Compare commits

...
Author SHA1 Message Date
szdziedzic 05a6628bc4 [build-tools] Link serve-sim to simulator session details 2026-08-20 15:59:13 +02:00
2 changed files with 168 additions and 2 deletions

No files matched your search

@@ -15,6 +15,8 @@ import { sleepAsync } from '../../../utils/retry';
import {
createServeSimArgs,
ensureFfmpegInstalledAsync,
expoWebsiteBaseUrlFromApiServerUrl,
fetchDeviceRunSessionDetailsUrlAsync,
fetchServeSimTurnArgsAsync,
metricsCorsOriginToServeSimArgs,
startNgrokTunnelAsync,
@@ -157,6 +159,86 @@ describe(createServeSimArgs, () => {
'https://expo.dev',
]);
});
it('passes the simulator session details URL to serve-sim when provided', () => {
const args = createServeSimArgs({
port: 4321,
sessionDetailsUrl:
'https://expo.dev/accounts/acme/projects/app/simulator-sessions/session-123',
});
expect(args.slice(-2)).toEqual([
'--session-details-url',
'https://expo.dev/accounts/acme/projects/app/simulator-sessions/session-123',
]);
});
});
describe(expoWebsiteBaseUrlFromApiServerUrl, () => {
it.each([
['https://api.expo.dev', 'https://expo.dev'],
['https://staging-api.expo.dev', 'https://staging.expo.dev'],
['http://127.0.0.1:3000', 'http://expo.test'],
])('maps %s to %s', (apiServerUrl, websiteBaseUrl) => {
expect(expoWebsiteBaseUrlFromApiServerUrl(apiServerUrl)).toBe(websiteBaseUrl);
});
});
describe(fetchDeviceRunSessionDetailsUrlAsync, () => {
it('builds the Expo session URL from the authenticated session lookup', async () => {
const query = jest.fn(() => ({
toPromise: async () => ({
data: {
deviceRunSessions: {
byId: {
id: 'session-123',
app: {
slug: 'my app',
ownerAccount: { name: 'acme team' },
},
},
},
},
}),
}));
const ctx = {
env: { __API_SERVER_URL: 'https://staging-api.expo.dev' },
graphqlClient: { query },
} as unknown as CustomBuildContext;
await expect(
fetchDeviceRunSessionDetailsUrlAsync(ctx, {
deviceRunSessionId: 'session-123',
logger: createLoggerMock(),
})
).resolves.toBe(
'https://staging.expo.dev/accounts/acme%20team/projects/my%20app/simulator-sessions/session-123'
);
expect(query).toHaveBeenCalledWith(expect.anything(), {
deviceRunSessionId: 'session-123',
});
});
it('keeps the preview available when the session URL cannot be resolved', async () => {
const logger = createLoggerMock();
const ctx = {
graphqlClient: {
query: jest.fn(() => ({
toPromise: async () => ({ error: new Error('lookup failed') }),
})),
},
} as unknown as CustomBuildContext;
await expect(
fetchDeviceRunSessionDetailsUrlAsync(ctx, {
deviceRunSessionId: 'session-123',
logger,
})
).resolves.toBeUndefined();
expect(logger.warn).toHaveBeenCalledWith(
expect.objectContaining({ err: expect.any(Error) }),
expect.stringContaining('serve-sim will start without a return link')
);
});
});
describe(metricsCorsOriginToServeSimArgs, () => {
@@ -51,6 +51,22 @@ const DEVICE_RUN_SESSION_STATUS_QUERY = graphql(`
}
`);
const DEVICE_RUN_SESSION_DETAILS_QUERY = graphql(`
query DeviceRunSessionDetails($deviceRunSessionId: ID!) {
deviceRunSessions {
byId(deviceRunSessionId: $deviceRunSessionId) {
id
app {
slug
ownerAccount {
name
}
}
}
}
}
`);
const ENSURE_DEVICE_RUN_SESSION_STOPPED_MUTATION = graphql(`
mutation EnsureDeviceRunSessionStopped($deviceRunSessionId: ID!) {
deviceRunSession {
@@ -596,14 +612,77 @@ export function metricsCorsOriginToServeSimArgs(env: BuildStepEnv): string[] {
return args;
}
export function expoWebsiteBaseUrlFromApiServerUrl(apiServerUrl: string): string {
const apiUrl = new URL(apiServerUrl);
if (apiUrl.hostname === '127.0.0.1' || apiUrl.hostname === 'localhost') {
return 'http://expo.test';
}
if (apiUrl.hostname.startsWith('staging-api.')) {
apiUrl.hostname = `staging.${apiUrl.hostname.slice('staging-api.'.length)}`;
apiUrl.port = '';
} else if (apiUrl.hostname.startsWith('api.')) {
apiUrl.hostname = apiUrl.hostname.slice('api.'.length);
apiUrl.port = '';
}
return apiUrl.origin;
}
export async function fetchDeviceRunSessionDetailsUrlAsync(
ctx: CustomBuildContext,
{
deviceRunSessionId,
logger,
}: {
deviceRunSessionId: string;
logger: bunyan;
}
): Promise<string | undefined> {
try {
const result = await ctx.graphqlClient
.query(DEVICE_RUN_SESSION_DETAILS_QUERY, { deviceRunSessionId })
.toPromise();
if (result.error) {
throw result.error;
}
const session = result.data?.deviceRunSessions?.byId;
if (!session) {
throw new Error(`Device run session ${deviceRunSessionId} response was missing.`);
}
const websiteBaseUrl = expoWebsiteBaseUrlFromApiServerUrl(
nullthrows(ctx.env.__API_SERVER_URL, '__API_SERVER_URL is not set')
);
return new URL(
`/accounts/${encodeURIComponent(session.app.ownerAccount.name)}/projects/${encodeURIComponent(
session.app.slug
)}/simulator-sessions/${encodeURIComponent(session.id)}`,
websiteBaseUrl
).toString();
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('Could not resolve device run session details URL', error, {
level: 'warning',
});
logger.warn(
{ err: error },
'Could not resolve the simulator session details URL; serve-sim will start without a return link.'
);
return undefined;
}
}
export function createServeSimArgs({
port,
turnArgs = [],
metricsCorsArgs = [],
sessionDetailsUrl,
}: {
port: number;
turnArgs?: string[];
metricsCorsArgs?: string[];
sessionDetailsUrl?: string;
}): string[] {
return [
'--yes',
@@ -626,6 +705,7 @@ export function createServeSimArgs({
SERVE_SIM_VIDEO_FPS,
...turnArgs,
...metricsCorsArgs,
...(sessionDetailsUrl ? ['--session-details-url', sessionDetailsUrl] : []),
];
}
@@ -709,11 +789,15 @@ export async function startServeSimWithTunnelAsync(
): Promise<ServeSimPreviewHandle> {
const port = await findAvailablePortAsync();
logger.info(`Launching ${SERVE_SIM_PACKAGE_SPEC} on ${SERVE_SIM_HOST}:${port}.`);
const turnArgs = await fetchServeSimTurnArgsAsync(ctx, { env, logger });
const deviceRunSessionId = getDeviceRunSessionIdOrThrow(env);
const [turnArgs, sessionDetailsUrl] = await Promise.all([
fetchServeSimTurnArgsAsync(ctx, { env, logger }),
fetchDeviceRunSessionDetailsUrlAsync(ctx, { deviceRunSessionId, logger }),
]);
const metricsCorsArgs = metricsCorsOriginToServeSimArgs(env);
const serveSim = spawnDetached({
command: 'npx',
args: createServeSimArgs({ port, turnArgs, metricsCorsArgs }),
args: createServeSimArgs({ port, turnArgs, metricsCorsArgs, sessionDetailsUrl }),
env,
});