mirror of
https://github.com/expo/eas-cli.git
synced 2026-11-25 00:15:45 -10:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ad6311fb39 | ||
|
|
a42de8ad81 |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'eas-cli': patch
|
||||
---
|
||||
|
||||
Keep simulator credentials when the stop response does not confirm that the allocated session stopped.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Expose simulator allocation and cleanup records on stderr when EAS_SIMULATOR_LIFECYCLE is set to a request UUID.
|
||||
@@ -0,0 +1,68 @@
|
||||
// Replace the API in the CLI subprocess so the command runs against local responses.
|
||||
const nock = require('nock');
|
||||
nock.disableNetConnect();
|
||||
|
||||
const app = { id: 'app-123', slug: 'testapp', ownerAccount: { name: 'testuser' } };
|
||||
const session = { id: 'session-123', app, status: 'IN_PROGRESS', turtleJobRun: { id: 'job-123' } };
|
||||
const actor = {
|
||||
__typename: 'User',
|
||||
id: 'user',
|
||||
username: 'testuser',
|
||||
isExpoAdmin: true,
|
||||
accounts: [],
|
||||
};
|
||||
const scenario = process.env.FIXTURE_SCENARIO;
|
||||
|
||||
nock('http://127.0.0.1:3000')
|
||||
.persist()
|
||||
.post('/graphql')
|
||||
.reply(200, (_uri, body) => {
|
||||
switch (body.operationName) {
|
||||
case 'CurrentUser':
|
||||
if (scenario === 'auth-error') {
|
||||
return { errors: [{ message: 'fixture auth error' }] };
|
||||
}
|
||||
return { data: { meActor: actor } };
|
||||
case 'AppByIdQuery':
|
||||
return { data: { app: { byId: app } } };
|
||||
case 'StatuspageServiceByServiceNamesQuery':
|
||||
return { data: { statuspageService: { byServiceNames: [] } } };
|
||||
case 'CreateDeviceRunSessionMutation':
|
||||
if (scenario === 'create-error') {
|
||||
return { errors: [{ message: 'fixture create error' }] };
|
||||
}
|
||||
return {
|
||||
data: {
|
||||
deviceRunSession: {
|
||||
createDeviceRunSession:
|
||||
scenario === 'missing-job' ? { ...session, turtleJobRun: null } : session,
|
||||
},
|
||||
},
|
||||
};
|
||||
case 'DeviceRunSessionByIdQuery': {
|
||||
// Same pipe as lifecycle events so the parent can check ordering across the process boundary.
|
||||
process.stderr.write('fixture: polling readiness\n');
|
||||
if (scenario !== 'ready') {
|
||||
return { errors: [{ message: 'fixture readiness error' }] };
|
||||
}
|
||||
const remoteConfig = {
|
||||
__typename: 'AgentDeviceRunSessionRemoteConfig',
|
||||
agentDeviceRemoteSessionUrl: 'https://agent.example.com',
|
||||
agentDeviceRemoteSessionToken: 'fixture-token',
|
||||
};
|
||||
return { data: { deviceRunSessions: { byId: { ...session, remoteConfig } } } };
|
||||
}
|
||||
case 'EnsureDeviceRunSessionStoppedMutation': {
|
||||
if (scenario === 'stop-error') {
|
||||
return { errors: [{ message: 'fixture stop error' }] };
|
||||
}
|
||||
const stop = {
|
||||
id: session.id,
|
||||
status: scenario === 'still-running' ? 'IN_PROGRESS' : 'STOPPED',
|
||||
};
|
||||
return { data: { deviceRunSession: { ensureDeviceRunSessionStopped: stop } } };
|
||||
}
|
||||
default:
|
||||
return { errors: [{ message: 'Unexpected fixture query: ' + body.operationName }] };
|
||||
}
|
||||
});
|
||||
@@ -42,6 +42,7 @@ import { maybeWarnAboutEasOutagesAsync } from '../../../utils/statuspageService'
|
||||
import Simulator from '../index';
|
||||
|
||||
jest.mock('fs-extra');
|
||||
jest.mock('proper-lockfile', () => ({ lock: async () => async () => {} }));
|
||||
jest.mock('../../../simulator/startSetup');
|
||||
jest.mock('../../../analytics/AnalyticsManager', () => ({
|
||||
...jest.requireActual('../../../analytics/AnalyticsManager'),
|
||||
@@ -3495,6 +3496,31 @@ describe(Simulator, () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ id: 'session-123', status: DeviceRunSessionStatus.InProgress },
|
||||
{ id: 'another-session', status: DeviceRunSessionStatus.Stopped },
|
||||
])(
|
||||
'keeps local credentials when the stop response does not confirm this session: %j',
|
||||
async response => {
|
||||
mockByIdAsync
|
||||
.mockResolvedValueOnce(makeDeviceRunSession())
|
||||
.mockImplementationOnce(async () => {
|
||||
process.emit('SIGINT');
|
||||
return makeDeviceRunSession();
|
||||
});
|
||||
mockEnsureDeviceRunSessionStoppedAsync.mockResolvedValueOnce(response);
|
||||
|
||||
const { command } = createCommand(['--platform', 'ios']);
|
||||
await command.runAsync();
|
||||
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(mockResetSimulatorEnvAsync).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it('stops the session when interrupted while it is running', async () => {
|
||||
mockByIdAsync.mockResolvedValueOnce(makeDeviceRunSession()).mockImplementationOnce(async () => {
|
||||
process.emit('SIGINT');
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
// CI typechecks the workspace before Jest, emitting the packaged command. Local runs
|
||||
// use the dev entrypoint so a stale build cannot hide changes to the TypeScript source.
|
||||
const cli = path.resolve(__dirname, '../../../..');
|
||||
const bin = path.join(cli, 'bin', process.env.GITHUB_ACTIONS === 'true' ? 'run' : 'dev');
|
||||
const api = path.join(__dirname, 'fixtures/lifecycle-api.cjs');
|
||||
const start = { event: 'start' };
|
||||
const allocated = { event: 'allocated', id: 'session-123' };
|
||||
const requestId = '86c52eaa-ef2c-42b0-b638-d93c68c6af5a';
|
||||
const prefix = `EAS_SIMULATOR_LIFECYCLE ${requestId} `;
|
||||
|
||||
function runStart(scenario: string, { enabled = true, json = true } = {}) {
|
||||
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'eas-start-'));
|
||||
try {
|
||||
fs.writeFileSync(path.join(cwd, 'package.json'), '{}');
|
||||
fs.writeFileSync(
|
||||
path.join(cwd, 'app.json'),
|
||||
JSON.stringify({
|
||||
expo: {
|
||||
name: 'testapp',
|
||||
slug: 'testapp',
|
||||
sdkVersion: '55.0.0',
|
||||
extra: { eas: { projectId: 'app-123' } },
|
||||
},
|
||||
})
|
||||
);
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
'-r',
|
||||
api,
|
||||
bin,
|
||||
'simulator',
|
||||
'--platform',
|
||||
'ios',
|
||||
'--type',
|
||||
'agent-device',
|
||||
'--non-interactive',
|
||||
...(json ? ['--json'] : []),
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
encoding: 'utf8',
|
||||
timeout: 30_000,
|
||||
env: {
|
||||
PATH: process.env.PATH,
|
||||
HOME: cwd,
|
||||
USERPROFILE: cwd,
|
||||
SystemRoot: process.env.SystemRoot,
|
||||
EXPO_LOCAL: '1',
|
||||
EXPO_TOKEN: 'fixture',
|
||||
EAS_NO_VCS: '1',
|
||||
EAS_PROJECT_ROOT: cwd,
|
||||
DISABLE_EAS_ANALYTICS: '1',
|
||||
EAS_SIMULATOR_LIFECYCLE: enabled ? requestId : '',
|
||||
FIXTURE_SCENARIO: scenario,
|
||||
},
|
||||
}
|
||||
);
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
const events = result.stderr
|
||||
.split('\n')
|
||||
.filter(line => line.startsWith(prefix))
|
||||
.map(line => JSON.parse(line.slice(prefix.length)));
|
||||
const dotenv = path.join(cwd, '.env.eas-simulator');
|
||||
return {
|
||||
...result,
|
||||
events,
|
||||
dotenv: fs.existsSync(dotenv) ? fs.readFileSync(dotenv, 'utf8') : '',
|
||||
};
|
||||
} finally {
|
||||
fs.rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
it.each([
|
||||
['auth-error', 'fixture auth error'],
|
||||
['create-error', 'fixture create error'],
|
||||
])('reports no allocation on %s', (scenario, message) => {
|
||||
const result = runStart(scenario);
|
||||
expect(result.stderr).toContain(message);
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stdout).toBe('');
|
||||
expect(result.events).toEqual([start]);
|
||||
});
|
||||
|
||||
it('reports the allocation even when the create response is missing the job', () => {
|
||||
const result = runStart('missing-job');
|
||||
expect(result.stderr).toContain('Expected simulator session to start');
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stdout).toBe('');
|
||||
expect(result.events).toEqual([start, allocated]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['poll-error', 'stopped'],
|
||||
['stop-error', 'unknown'],
|
||||
['still-running', 'unknown'],
|
||||
])('reports the allocation before polling and the cleanup outcome on %s', (scenario, outcome) => {
|
||||
const json = scenario === 'still-running';
|
||||
const result = runStart(scenario, { json });
|
||||
expect(result.stderr).toContain('fixture readiness error');
|
||||
expect(result.status).toBe(1);
|
||||
if (json) {
|
||||
expect(result.stdout).toBe('');
|
||||
} else {
|
||||
expect(result.dotenv.includes('session-123')).toBe(outcome === 'unknown');
|
||||
}
|
||||
expect(result.events).toEqual([
|
||||
start,
|
||||
allocated,
|
||||
{ event: 'cleanup', id: 'session-123', outcome },
|
||||
]);
|
||||
expect(result.stderr.indexOf(prefix + JSON.stringify(allocated))).toBeLessThan(
|
||||
result.stderr.indexOf('fixture: polling readiness')
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves the final JSON result with and without lifecycle output', () => {
|
||||
const enabled = runStart('ready');
|
||||
const disabled = runStart('ready', { enabled: false });
|
||||
expect(enabled.status).toBe(0);
|
||||
expect(disabled.status).toBe(0);
|
||||
expect(enabled.events).toEqual([start, allocated]);
|
||||
expect(disabled.events).toEqual([]);
|
||||
expect(JSON.parse(enabled.stdout)).toMatchObject({
|
||||
id: 'session-123',
|
||||
type: 'agent-device',
|
||||
remoteConfig: { agentDeviceRemoteSessionUrl: 'https://agent.example.com' },
|
||||
});
|
||||
expect(enabled.stdout).toBe(disabled.stdout);
|
||||
});
|
||||
@@ -135,6 +135,20 @@ describe(SimulatorStop, () => {
|
||||
}
|
||||
});
|
||||
|
||||
it.each([{ status: DeviceRunSessionStatus.InProgress }, { id: 'another-session' }])(
|
||||
'preserves credentials when the stop is unconfirmed: %j',
|
||||
async response => {
|
||||
mockEnsureDeviceRunSessionStoppedAsync.mockResolvedValueOnce(
|
||||
makeStoppedDeviceRunSession(response)
|
||||
);
|
||||
const { command } = createCommand(['--id', 'session-123', '--json']);
|
||||
|
||||
await expect(command.runAsync()).rejects.toThrow('could not confirm');
|
||||
expect(mockResetSimulatorEnvAsync).not.toHaveBeenCalled();
|
||||
expect(mockPrintJsonOnlyOutput).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it('throws a helpful error when no simulator session ID is available', async () => {
|
||||
const previousDeviceRunSessionId = process.env[EAS_SIMULATOR_SESSION_ID];
|
||||
delete process.env[EAS_SIMULATOR_SESSION_ID];
|
||||
|
||||
@@ -45,6 +45,7 @@ import { resolveStartConfigAsync } from '../../simulator/startConfig';
|
||||
import { applyStartConfigAsync } from '../../simulator/startSetup';
|
||||
import { parseEgressAllowList, runLocalEgressAsync } from '../../simulator/egress';
|
||||
import { parseCorsOriginList, parseFrameAncestorList } from '../../simulator/frameAncestors';
|
||||
import { reportSimulatorLifecycle } from '../../simulator/lifecycle';
|
||||
import { parseNetworkCaptureFields } from '../../simulator/networkCapture';
|
||||
import {
|
||||
EAS_SIMULATOR_SESSION_ID,
|
||||
@@ -77,6 +78,7 @@ import {
|
||||
getLocalEgressConfig,
|
||||
getPreviewApiAccess,
|
||||
getRemoteSessionEnvironmentVariables,
|
||||
isSimulatorStopConfirmed,
|
||||
sanitizeRemoteConfigForJson,
|
||||
} from '../../simulator/utils';
|
||||
import { enableJsonOutput, printJsonOnlyOutput } from '../../utils/json';
|
||||
@@ -104,6 +106,15 @@ export default class Simulator extends EasCommand {
|
||||
|
||||
Preview links require sign-in by default.
|
||||
|
||||
For machine-readable progress, set EAS_SIMULATOR_LIFECYCLE to a fresh UUID for each invocation. Read lines from stderr beginning with "EAS_SIMULATOR_LIFECYCLE <uuid> " and parse the remaining JSON.
|
||||
|
||||
{"event":"start"} The command supports lifecycle records.
|
||||
{"event":"allocated","id":"..."} EAS allocated the session. Readiness checks follow.
|
||||
{"event":"cleanup","id":"...","outcome":"stopped"} EAS confirmed the session stopped.
|
||||
{"event":"cleanup","id":"...","outcome":"unknown"} The CLI attempted cleanup but could not confirm the stop.
|
||||
|
||||
If the command fails after allocation without a cleanup record, check the session by ID. With --json, stdout carries the final result.
|
||||
|
||||
Use --import to load saved start options and actions. CLI flags override saved options, including lists:
|
||||
|
||||
{
|
||||
@@ -268,6 +279,11 @@ With local egress, actions wait for the connection and require interactive mode.
|
||||
...this.ContextOptions.Analytics,
|
||||
};
|
||||
|
||||
override run(): Promise<void> {
|
||||
reportSimulatorLifecycle({ event: 'start' });
|
||||
return super.run();
|
||||
}
|
||||
|
||||
async runAsync(): Promise<void> {
|
||||
// Import preflight can fail before parsing; keep diagnostics off JSON stdout.
|
||||
if (this.argv.includes('--json')) {
|
||||
@@ -419,6 +435,7 @@ With local egress, actions wait for the connection and require interactive mode.
|
||||
let deviceRunSessionId: string;
|
||||
let deviceRunSessionUrl: string;
|
||||
let deviceRunSessionPreviewUrl: string;
|
||||
let simulatorEnvWritten = false;
|
||||
let sessionInterrupt: SessionInterrupt | undefined;
|
||||
try {
|
||||
const agentIdentity = await agentIdentityInputAsync();
|
||||
@@ -477,6 +494,9 @@ With local egress, actions wait for the connection and require interactive mode.
|
||||
...agentIdentity,
|
||||
maxRunTimeMinutes: flags['max-duration-minutes'],
|
||||
maxIdleTimeMinutes: flags['max-idle-time-minutes'],
|
||||
}).then(created => {
|
||||
reportSimulatorLifecycle({ event: 'allocated', id: created.id });
|
||||
return created;
|
||||
}),
|
||||
createdSession =>
|
||||
stopDeviceRunSessionCreatedAfterCancelAsync(graphqlClient, createdSession.id)
|
||||
@@ -494,7 +514,7 @@ With local egress, actions wait for the connection and require interactive mode.
|
||||
deviceRunSessionId
|
||||
);
|
||||
sessionInterrupt = registerSessionInterrupt(deviceRunSessionId);
|
||||
const simulatorEnvWritten =
|
||||
simulatorEnvWritten =
|
||||
!jsonFlag &&
|
||||
!imported.config?.actions?.length &&
|
||||
flags['out-config-type'] === OUT_CONFIG_TYPE_VALUES.Dotenv
|
||||
@@ -518,6 +538,18 @@ With local egress, actions wait for the connection and require interactive mode.
|
||||
throw err;
|
||||
}
|
||||
|
||||
const stopAfterReadinessFailureAsync = async (): Promise<void> => {
|
||||
const stopped = await ensureDeviceRunSessionStoppedSafelyAsync(
|
||||
graphqlClient,
|
||||
deviceRunSessionId
|
||||
);
|
||||
if (stopped && simulatorEnvWritten) {
|
||||
await resetSimulatorEnvAsync(projectDir, deviceRunSessionId).catch(error => {
|
||||
Log.warn(`Failed to clean up ${SIMULATOR_DOTENV_FILE_NAME}: ${String(error)}`);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const pollSpinner = ora(`⏳ Waiting for ${flags.type} session to be ready`).start();
|
||||
let startupDeadline: number | undefined = Date.now() + STARTUP_TIMEOUT_MS;
|
||||
let remoteConfig: DeviceRunSessionRemoteConfig | undefined;
|
||||
@@ -574,7 +606,7 @@ With local egress, actions wait for the connection and require interactive mode.
|
||||
}
|
||||
} catch (err) {
|
||||
pollSpinner.fail(`Failed while polling for ${flags.type} session to be ready`);
|
||||
await ensureDeviceRunSessionStoppedSafelyAsync(graphqlClient, deviceRunSessionId);
|
||||
await stopAfterReadinessFailureAsync();
|
||||
sessionInterrupt.dispose();
|
||||
throw err;
|
||||
}
|
||||
@@ -592,7 +624,7 @@ With local egress, actions wait for the connection and require interactive mode.
|
||||
|
||||
if (!remoteConfig) {
|
||||
pollSpinner.fail(`Timed out waiting for ${flags.type} session to start`);
|
||||
await ensureDeviceRunSessionStoppedSafelyAsync(graphqlClient, deviceRunSessionId);
|
||||
await stopAfterReadinessFailureAsync();
|
||||
sessionInterrupt.dispose();
|
||||
throw new Error(
|
||||
`Timed out after ${Math.round(STARTUP_TIMEOUT_MS / 1000)}s waiting for ${flags.type} session to start (excluding time in the queue). ${link(deviceRunSessionUrl)}`
|
||||
@@ -1119,12 +1151,19 @@ async function ensureDeviceRunSessionStoppedSafelyAsync(
|
||||
deviceRunSessionId: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
await DeviceRunSessionMutation.ensureDeviceRunSessionStoppedAsync(
|
||||
const stopped = await DeviceRunSessionMutation.ensureDeviceRunSessionStoppedAsync(
|
||||
graphqlClient,
|
||||
deviceRunSessionId
|
||||
);
|
||||
return true;
|
||||
const confirmed = isSimulatorStopConfirmed(stopped, deviceRunSessionId);
|
||||
reportSimulatorLifecycle({
|
||||
event: 'cleanup',
|
||||
id: deviceRunSessionId,
|
||||
outcome: confirmed ? 'stopped' : 'unknown',
|
||||
});
|
||||
return confirmed;
|
||||
} catch (err) {
|
||||
reportSimulatorLifecycle({ event: 'cleanup', id: deviceRunSessionId, outcome: 'unknown' });
|
||||
// Cleanup is best-effort; surface the failure but don't mask the original error.
|
||||
Log.warn(
|
||||
`Failed to stop simulator session ${deviceRunSessionId}: ${
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
loadSimulatorEnvAsync,
|
||||
resetSimulatorEnvAsync,
|
||||
} from '../../simulator/env';
|
||||
import { isSimulatorStopConfirmed } from '../../simulator/utils';
|
||||
import { enableJsonOutput, printJsonOnlyOutput } from '../../utils/json';
|
||||
import {
|
||||
getSimulatorCommandAliases,
|
||||
@@ -67,6 +68,9 @@ export default class SimulatorStop extends EasCommand {
|
||||
graphqlClient,
|
||||
flagId
|
||||
);
|
||||
if (!isSimulatorStopConfirmed(session, flagId)) {
|
||||
throw new Error(`EAS could not confirm that simulator session ${flagId} stopped.`);
|
||||
}
|
||||
stopSpinner.succeed(`🎉 Simulator session ${session.id} is ${session.status.toLowerCase()}`);
|
||||
} catch (err) {
|
||||
stopSpinner.fail(`Failed to stop simulator session ${flagId}`);
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from '../utils';
|
||||
|
||||
jest.mock('fs-extra');
|
||||
jest.mock('proper-lockfile', () => ({ lock: async () => async () => {} }));
|
||||
|
||||
const configs: DeviceRunSessionRemoteConfig[] = [
|
||||
{
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import * as fs from 'fs-extra';
|
||||
import { parse as parseDotenv } from 'dotenv';
|
||||
import * as realFs from 'node:fs/promises';
|
||||
import { fork } from 'node:child_process';
|
||||
import { once } from 'node:events';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
@@ -23,10 +25,16 @@ import { readLocalEgressConfigFromEnv } from '../egress';
|
||||
jest.mock('fs-extra');
|
||||
|
||||
describe(resetSimulatorEnvAsync, () => {
|
||||
const projectDir = '/test/project';
|
||||
const simulatorDotenvPath = getSimulatorEnvFilePath(projectDir);
|
||||
let projectDir: string;
|
||||
let simulatorDotenvPath: string;
|
||||
|
||||
beforeEach(() => {
|
||||
afterEach(async () => {
|
||||
await realFs.rm(projectDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
projectDir = await realFs.mkdtemp(path.join(os.tmpdir(), 'eas-simulator-env-'));
|
||||
simulatorDotenvPath = getSimulatorEnvFilePath(projectDir);
|
||||
jest.clearAllMocks();
|
||||
jest
|
||||
.mocked(fs.readFile)
|
||||
@@ -47,9 +55,33 @@ describe(resetSimulatorEnvAsync, () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves the new session when another process writes during a reset', async () => {
|
||||
await realFs.writeFile(simulatorDotenvPath, `${EAS_SIMULATOR_SESSION_ID}=session-123\n`);
|
||||
jest.mocked(fs.writeFile).mockImplementation(jest.requireActual('fs-extra').writeFile);
|
||||
jest.mocked(fs.truncate).mockImplementation(jest.requireActual('fs-extra').truncate);
|
||||
|
||||
let writerExit: Promise<unknown[]> | undefined;
|
||||
jest.mocked(fs.readFile).mockImplementationOnce(async () => {
|
||||
const old = await realFs.readFile(simulatorDotenvPath, 'utf8');
|
||||
const writer = fork(path.join(__dirname, 'fixtures/write-simulator-env.cjs'), [projectDir], {
|
||||
execArgv: [],
|
||||
});
|
||||
writerExit = once(writer, 'exit');
|
||||
// If either side omits the lock, the writer exits first and the old reset erases its file.
|
||||
const [state] = await Promise.race([once(writer, 'message'), writerExit]);
|
||||
expect(state).toBe('contended');
|
||||
return old;
|
||||
});
|
||||
|
||||
await resetSimulatorEnvAsync(projectDir, 'session-123');
|
||||
expect(await writerExit).toEqual([0, null]);
|
||||
expect(parseDotenv(await realFs.readFile(simulatorDotenvPath, 'utf8'))).toEqual({
|
||||
[EAS_SIMULATOR_SESSION_ID]: 'new-session',
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores a missing simulator dotenv file', async () => {
|
||||
const err = Object.assign(new Error('missing file'), { code: 'ENOENT' });
|
||||
jest.mocked(fs.readFile).mockRejectedValue(err as never);
|
||||
jest.mocked(fs.access).mockImplementationOnce(jest.requireActual('fs-extra').access);
|
||||
|
||||
await expect(resetSimulatorEnvAsync(projectDir, 'session-123')).resolves.toBeUndefined();
|
||||
|
||||
@@ -194,10 +226,16 @@ describe(loadSimulatorEnvAsync, () => {
|
||||
});
|
||||
|
||||
describe(writeSimulatorEnvAsync, () => {
|
||||
const projectDir = '/test/project';
|
||||
const simulatorDotenvPath = getSimulatorEnvFilePath(projectDir);
|
||||
let projectDir: string;
|
||||
let simulatorDotenvPath: string;
|
||||
|
||||
beforeEach(() => {
|
||||
afterEach(async () => {
|
||||
await realFs.rm(projectDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
projectDir = await realFs.mkdtemp(path.join(os.tmpdir(), 'eas-simulator-env-'));
|
||||
simulatorDotenvPath = getSimulatorEnvFilePath(projectDir);
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(fs.writeFile).mockResolvedValue(undefined as never);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
const path = require('node:path');
|
||||
const lockfile = require('proper-lockfile');
|
||||
const cli = path.resolve(__dirname, '../../../..');
|
||||
require('ts-node').register({ project: path.join(cli, 'tsconfig.json'), transpileOnly: true });
|
||||
const { writeSimulatorEnvAsync, EAS_SIMULATOR_SESSION_ID } = require('../../env.ts');
|
||||
|
||||
// Tell the parent exactly when the writer contends, without racing a sleep against startup.
|
||||
const lock = lockfile.lock;
|
||||
lockfile.lock = async (file, options) => {
|
||||
try {
|
||||
return await lock(file, { ...options, retries: 0 });
|
||||
} catch (err) {
|
||||
if (err.code !== 'ELOCKED') throw err;
|
||||
process.send('contended');
|
||||
return lock(file, options);
|
||||
}
|
||||
};
|
||||
writeSimulatorEnvAsync(process.argv[2], { [EAS_SIMULATOR_SESSION_ID]: 'new-session' }).catch(
|
||||
err => {
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
);
|
||||
@@ -2,6 +2,7 @@ import { loadEnvFiles, loadProjectEnv } from '@expo/env';
|
||||
import { parse as parseDotenv } from 'dotenv';
|
||||
import * as fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
import lockfile from 'proper-lockfile';
|
||||
|
||||
import Log from '../log';
|
||||
|
||||
@@ -75,7 +76,9 @@ export async function writeSimulatorEnvAsync(
|
||||
.join('\n') +
|
||||
'\n';
|
||||
|
||||
await fs.writeFile(simulatorDotenvFilePath, simulatorDotenvContent);
|
||||
await withSimulatorEnvLockAsync(simulatorDotenvFilePath, async () => {
|
||||
await fs.writeFile(simulatorDotenvFilePath, simulatorDotenvContent);
|
||||
});
|
||||
}
|
||||
|
||||
export async function resetSimulatorEnvAsync(
|
||||
@@ -85,20 +88,24 @@ export async function resetSimulatorEnvAsync(
|
||||
const simulatorDotenvFilePath = getSimulatorEnvFilePath(projectDir);
|
||||
|
||||
try {
|
||||
const currentEnv = parseDotenv(await fs.readFile(simulatorDotenvFilePath, 'utf8'));
|
||||
if (currentEnv[EAS_SIMULATOR_SESSION_ID] !== expectedDeviceRunSessionId) {
|
||||
// The file was overwritten by a newer simulator session, so it is no longer
|
||||
// ours to reset. This is expected when sessions overlap; log at debug level
|
||||
// for troubleshooting without surfacing noise during normal use.
|
||||
Log.debug(
|
||||
`Skipping ${SIMULATOR_DOTENV_FILE_NAME} reset: it belongs to simulator session ${
|
||||
currentEnv[EAS_SIMULATOR_SESSION_ID] ?? '(unknown)'
|
||||
}, not ${expectedDeviceRunSessionId}.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
await fs.writeFile(simulatorDotenvFilePath, SIMULATOR_DOTENV_FILE_HEADER, { flag: 'r+' });
|
||||
await fs.truncate(simulatorDotenvFilePath, Buffer.byteLength(SIMULATOR_DOTENV_FILE_HEADER));
|
||||
// A missing file needs no reset, including in a read-only project directory.
|
||||
await fs.access(simulatorDotenvFilePath);
|
||||
await withSimulatorEnvLockAsync(simulatorDotenvFilePath, async () => {
|
||||
const currentEnv = parseDotenv(await fs.readFile(simulatorDotenvFilePath, 'utf8'));
|
||||
if (currentEnv[EAS_SIMULATOR_SESSION_ID] !== expectedDeviceRunSessionId) {
|
||||
// The file was overwritten by a newer simulator session, so it is no longer
|
||||
// ours to reset. This is expected when sessions overlap; log at debug level
|
||||
// for troubleshooting without surfacing noise during normal use.
|
||||
Log.debug(
|
||||
`Skipping ${SIMULATOR_DOTENV_FILE_NAME} reset: it belongs to simulator session ${
|
||||
currentEnv[EAS_SIMULATOR_SESSION_ID] ?? '(unknown)'
|
||||
}, not ${expectedDeviceRunSessionId}.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
await fs.writeFile(simulatorDotenvFilePath, SIMULATOR_DOTENV_FILE_HEADER, { flag: 'r+' });
|
||||
await fs.truncate(simulatorDotenvFilePath, Buffer.byteLength(SIMULATOR_DOTENV_FILE_HEADER));
|
||||
});
|
||||
} catch (err) {
|
||||
if (typeof err === 'object' && err !== null && 'code' in err && err.code === 'ENOENT') {
|
||||
return;
|
||||
@@ -107,3 +114,20 @@ export async function resetSimulatorEnvAsync(
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// The dotenv may not exist yet. Lock the same sibling path for creation and for the
|
||||
// entire ownership check and reset, so another eas process cannot write between them.
|
||||
async function withSimulatorEnvLockAsync(
|
||||
file: string,
|
||||
updateAsync: () => Promise<void>
|
||||
): Promise<void> {
|
||||
const release = await lockfile.lock(file, {
|
||||
realpath: false,
|
||||
retries: { retries: 60, minTimeout: 50, maxTimeout: 200 },
|
||||
});
|
||||
try {
|
||||
await updateAsync();
|
||||
} finally {
|
||||
await release();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { validate as isUuid } from 'uuid';
|
||||
|
||||
type SimulatorLifecycleEvent =
|
||||
| { event: 'start' }
|
||||
| { event: 'allocated'; id: string }
|
||||
| { event: 'cleanup'; id: string; outcome: 'stopped' | 'unknown' };
|
||||
|
||||
// Only the invoking process opts in. Project dotenv files load during the command.
|
||||
const requestId = process.env.EAS_SIMULATOR_LIFECYCLE;
|
||||
|
||||
export function reportSimulatorLifecycle(event: SimulatorLifecycleEvent): void {
|
||||
if (requestId && isUuid(requestId)) {
|
||||
// A spinner may have left an unterminated frame on stderr.
|
||||
process.stderr.write(`\nEAS_SIMULATOR_LIFECYCLE ${requestId} ${JSON.stringify(event)}\n`);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
AppPlatform,
|
||||
DeviceRunSessionByIdQuery,
|
||||
DeviceRunSessionResourceClass,
|
||||
DeviceRunSessionStatus,
|
||||
DeviceRunSessionType,
|
||||
} from '../graphql/generated';
|
||||
import { link } from '../log';
|
||||
@@ -21,6 +22,13 @@ import {
|
||||
type DeviceRunSessionByIdResult = DeviceRunSessionByIdQuery['deviceRunSessions']['byId'];
|
||||
export type DeviceRunSessionRemoteConfig = NonNullable<DeviceRunSessionByIdResult['remoteConfig']>;
|
||||
|
||||
export function isSimulatorStopConfirmed(
|
||||
session: Pick<DeviceRunSessionByIdResult, 'id' | 'status'>,
|
||||
requestedId: string
|
||||
): boolean {
|
||||
return session.id === requestedId && session.status === DeviceRunSessionStatus.Stopped;
|
||||
}
|
||||
|
||||
/**
|
||||
* Message shown when EAS Simulator is not enabled for the account. Shared by every
|
||||
* command that can hit the gate so users always get the same upgrade pointer. The gate
|
||||
|
||||
Reference in new issue
Block a user