Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/wait-longer-for-first-ngrok-open.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@expo/build-tools': patch
---

Wait up to 90 seconds for the first ngrok tunnel open of a device run session, so a slow ngrok open no longer fails the session.
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ import {
} from '../deviceSessionHost';
import { readIosApplicationIdentifierAsync } from '../iosAppArtifact';
import { readLocalEgressHandoffAsync } from '../localEgress';
import { FIRST_OPEN_TIMEOUT_MS } from '../ngrokTunnel';
import { DeviceRunSessionTimeoutError } from '../deviceRunSessionTimeout';
import {
ensureFfmpegInstalledOnceAsync,
fetchWebPreviewTurnArgsAsync,
Expand Down Expand Up @@ -2683,7 +2685,7 @@ it.each(['opened', 'late'])(
}
);

it.each(['startup failure', 'cancellation', 'opening timeout'])(
it.each(['startup failure', 'cancellation'])(
'bounds cleanup after %s while preview opening stays pending, then closes its late listener',
async failure => {
jest.useFakeTimers({ doNotFake: ['setImmediate'] });
Expand Down Expand Up @@ -2738,22 +2740,14 @@ it.each(['startup failure', 'cancellation', 'opening timeout'])(
await new Promise(resolve => setImmediate(resolve));
}
expect(startDeviceRunSessionPreview).toHaveBeenCalledTimes(1);
if (failure === 'cancellation') {
controller.abort(startupError);
} else {
await jest.advanceTimersByTimeAsync(1000);
}
controller.abort(startupError);
}
await jest.advanceTimersByTimeAsync(4_999);
expect(stopServer).not.toHaveBeenCalled();
await jest.advanceTimersByTimeAsync(1);
const error = await outcome;
expect(error).toBeInstanceOf(AggregateError);
if (failure === 'opening timeout') {
expect(error.errors[0].message).toContain('Preview tunnel opening timed out');
} else {
expect(error.errors).toContain(startupError);
}
expect(error.errors).toContain(startupError);
expect(stopServer).toHaveBeenCalledTimes(1);
expect(finishScreenshots).toHaveBeenCalledWith(true);
expect(closeTunnel).not.toHaveBeenCalled();
Expand All @@ -2769,6 +2763,62 @@ it.each(['startup failure', 'cancellation', 'opening timeout'])(
}
);

it('waits for the first preview tunnel open past the host time-out, then fails on the tunnel time-out', async () => {
jest.useFakeTimers({ doNotFake: ['setImmediate'] });
const tunnel = deferred<Awaited<ReturnType<typeof ngrok.forward>>>();
const finishScreenshots = jest.fn().mockResolvedValue(undefined);
const screenshots = jest
.spyOn(screenshotCollector, 'startDeviceRunSessionScreenshotsAsync')
.mockResolvedValueOnce({ directory: '/mock/screenshots', finishAsync: finishScreenshots });
jest.mocked(ngrok.forward).mockReturnValueOnce(tunnel.promise);
const outcome = startDeviceSessionHostAsync(
ctx,
{
runtimePlatform: BuildRuntimePlatform.DARWIN,
preview: { baseDomain, authtoken },
env,
logger,
timeoutMs: 1000,
},
{
port: 3200,
turnArgs: Promise.resolve([]),
requiresPreviewRetirement: true,
startAsync: async () => ({
pid: undefined,
getOutput: () => '',
getExitError: () => undefined,
stopAsync: stopServer,
}),
stopAsync: stopServer,
}
).catch(error => error);
try {
for (let i = 0; i < 50 && !jest.mocked(startDeviceRunSessionPreview).mock.calls.length; i++) {
await new Promise(resolve => setImmediate(resolve));
}
expect(startDeviceRunSessionPreview).toHaveBeenCalledTimes(1);
await jest.advanceTimersByTimeAsync(FIRST_OPEN_TIMEOUT_MS - 1);
expect(stopServer).not.toHaveBeenCalled();
await jest.advanceTimersByTimeAsync(1);
const error = await outcome;
expect(error).toBeInstanceOf(DeviceRunSessionTimeoutError);
expect(error.message).toBe(`Ngrok tunnel open timed out after ${FIRST_OPEN_TIMEOUT_MS}ms.`);
expect(stopServer).toHaveBeenCalledTimes(1);
expect(finishScreenshots).toHaveBeenCalledWith(true);
tunnel.resolve({ url: () => 'https://late.example.test', close: closeTunnel } as never);
for (let i = 0; i < 50 && !closeTunnel.mock.calls.length; i++) {
await new Promise(resolve => setImmediate(resolve));
}
expect(closeTunnel).toHaveBeenCalledTimes(1);
} finally {
tunnel.resolve({ url: () => 'https://late.example.test', close: closeTunnel } as never);
await jest.advanceTimersByTimeAsync(10_000);
await outcome;
screenshots.mockRestore();
}
});

it.each([
{ action: 'app.install', tunnelTiming: 'opened' },
{ action: 'app.launch', tunnelTiming: 'late' },
Expand Down
52 changes: 38 additions & 14 deletions packages/build-tools/src/steps/utils/__tests__/ngrokTunnel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { type AddressInfo, createConnection, createServer as createTcpServer } f

import { Datadog } from '../../../datadog';
import { turtleFetch } from '../../../utils/turtleFetch';
import { startNgrokTunnelAsync } from '../ngrokTunnel';
import { FIRST_OPEN_TIMEOUT_MS, startNgrokTunnelAsync } from '../ngrokTunnel';

jest.mock('@ngrok/ngrok');
jest.mock('node:timers', () => ({
Expand Down Expand Up @@ -575,8 +575,10 @@ it('bounds initial tunnel creation, does not retry a timed-out open, and retires
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)))
.mockResolvedValue(replacement as never);
const opening = startNgrokTunnelAsync(options);
const rejected = expect(opening).rejects.toThrow('Ngrok tunnel open timed out after 19000ms');
await jest.advanceTimersByTimeAsync(19_000);
const rejected = expect(opening).rejects.toThrow(
`Ngrok tunnel open timed out after ${FIRST_OPEN_TIMEOUT_MS}ms`
);
await jest.advanceTimersByTimeAsync(FIRST_OPEN_TIMEOUT_MS);
await rejected;
// ngrok runs opens one at a time, so a retry would only wait behind the stuck open.
expect(ngrok.forward).toHaveBeenCalledTimes(1);
Expand All @@ -588,8 +590,8 @@ it('bounds initial tunnel creation, does not retry a timed-out open, and retires
await jest.advanceTimersByTimeAsync(0);
expect(initial.close).toHaveBeenCalledTimes(1);
expect(logger.info).toHaveBeenCalledWith(
expect.objectContaining({ outcome: 'opened', elapsedMs: 19_000 }),
'ngrok tunnel open for web-preview-fixed.example.test opened after 19000 ms, after it timed out or was cancelled.'
expect.objectContaining({ outcome: 'opened', elapsedMs: FIRST_OPEN_TIMEOUT_MS }),
`ngrok tunnel open for web-preview-fixed.example.test opened after ${FIRST_OPEN_TIMEOUT_MS} ms, after it timed out or was cancelled.`
);
});

Expand All @@ -614,6 +616,26 @@ it('keeps a first open that settles after the reopen time-out', async () => {
expect(initial.close).toHaveBeenCalledTimes(1);
});

it('keeps a first open that settles after 75 seconds', async () => {
let resolveOpening!: (value: ngrok.Listener) => void;
jest
.mocked(ngrok.forward)
.mockReset()
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)))
.mockResolvedValue(replacement as never);
const opening = startNgrokTunnelAsync(options);
await jest.advanceTimersByTimeAsync(75_000);
resolveOpening(initial as never);
const tunnel = await opening;
try {
expect(tunnel.url).toBe(url);
expect(ngrok.forward).toHaveBeenCalledTimes(1);
expect(initial.close).not.toHaveBeenCalled();
} finally {
await tunnel.stopAsync();
}
});

it('fails without a retry when the first open fails for another reason after 15 seconds', async () => {
let rejectOpening!: (error: Error) => void;
jest
Expand All @@ -640,7 +662,7 @@ it('does not retry a timed-out open that ngrok rejects later', async () => {
.mockResolvedValue(replacement as never);
const opening = startNgrokTunnelAsync(options);
const rejected = expect(opening).rejects.toThrow('Ngrok tunnel open timed out');
await jest.advanceTimersByTimeAsync(19_000);
await jest.advanceTimersByTimeAsync(FIRST_OPEN_TIMEOUT_MS);
await rejected;
rejectOpening(new Error(ERR_802));
await jest.advanceTimersByTimeAsync(10_000);
Expand Down Expand Up @@ -842,7 +864,7 @@ it('retries a rejected close of a late listener after initial tunnel creation ti
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)));
const opening = startNgrokTunnelAsync(options);
const rejected = expect(opening).rejects.toThrow('Ngrok tunnel open timed out');
await jest.advanceTimersByTimeAsync(19_000);
await jest.advanceTimersByTimeAsync(FIRST_OPEN_TIMEOUT_MS);
await rejected;
initial.close.mockRejectedValueOnce(new Error('temporary unlisten failure'));
resolveOpening(initial as never);
Expand Down Expand Up @@ -1069,7 +1091,7 @@ it.each(['resolve', 'reject'])(
const rejected = expect(opening).rejects.toThrow('open timed out');
await new Promise<void>(resolve => setImmediate(resolve));
// The first open times out, and startup does not retry it while it is still pending.
await jest.advanceTimersByTimeAsync(19_000);
await jest.advanceTimersByTimeAsync(FIRST_OPEN_TIMEOUT_MS);
await rejected;
expect(ngrok.forward).toHaveBeenCalledTimes(1);
const targetPort = (jest.mocked(ngrok.forward).mock.calls[0][0] as ngrok.Config).addr as number;
Expand Down Expand Up @@ -1233,16 +1255,18 @@ describe('metrics', () => {
.mockReset()
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)));
const opening = startNgrokTunnelAsync(options);
const rejected = expect(opening).rejects.toThrow('Ngrok tunnel open timed out after 19000ms');
await jest.advanceTimersByTimeAsync(19_000);
const rejected = expect(opening).rejects.toThrow(
`Ngrok tunnel open timed out after ${FIRST_OPEN_TIMEOUT_MS}ms`
);
await jest.advanceTimersByTimeAsync(FIRST_OPEN_TIMEOUT_MS);
await rejected;
await jest.advanceTimersByTimeAsync(6_000);
resolveOpening(initial as never);
await jest.advanceTimersByTimeAsync(0);
expect(metrics()).toEqual([
[
'eas.device_run_session.ngrok_tunnel.open',
19_000,
FIRST_OPEN_TIMEOUT_MS,
{ tunnel: 'web-preview', kind: 'initial_1', result: 'timed_out', error_code: 'none' },
],
[
Expand All @@ -1252,7 +1276,7 @@ describe('metrics', () => {
],
[
'eas.device_run_session.ngrok_tunnel.late_open',
25_000,
FIRST_OPEN_TIMEOUT_MS + 6_000,
{ tunnel: 'web-preview', kind: 'initial_1', result: 'opened', error_code: 'none' },
],
]);
Expand Down Expand Up @@ -1321,14 +1345,14 @@ describe('metrics', () => {
.mockReturnValueOnce(new Promise((_, reject) => (rejectOpening = reject)));
const opening = startNgrokTunnelAsync(options);
const rejected = expect(opening).rejects.toThrow('Ngrok tunnel open timed out');
await jest.advanceTimersByTimeAsync(19_000);
await jest.advanceTimersByTimeAsync(FIRST_OPEN_TIMEOUT_MS);
await rejected;
await jest.advanceTimersByTimeAsync(2_000);
rejectOpening(new Error(ERR_802));
await jest.advanceTimersByTimeAsync(0);
expect(metrics().at(-1)).toEqual([
'eas.device_run_session.ngrok_tunnel.late_open',
21_000,
FIRST_OPEN_TIMEOUT_MS + 2_000,
{ tunnel: 'web-preview', kind: 'initial_1', result: 'failed', error_code: 'ERR_NGROK_802' },
]);
});
Expand Down
8 changes: 7 additions & 1 deletion packages/build-tools/src/steps/utils/deviceSessionHost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
import { LOCAL_EGRESS_PROXY_HOST, readLocalEgressHandoffAsync } from './localEgress';
import { withDeviceRunSessionTimeoutAsync } from './deviceRunSessionTimeout';
import { EMULATOR_CAPTURE_REQUESTED_ENV } from './emulatorCapture';
import { INITIAL_OPEN_MAX_DURATION_MS } from './ngrokTunnel';
import {
IosSimulatorRecordingUtils,
SERVE_SIM_STOP_GRACE_PERIOD_MS,
Expand Down Expand Up @@ -708,7 +709,12 @@ async function startDeviceSessionHostInternalAsync(
}
const earlyPreview = asyncResult(
withDeviceRunSessionTimeoutAsync(
{ name: 'Preview tunnel opening', timeoutMs, signal: startup.signal },
{
name: 'Preview tunnel opening',
// The tunnel bounds its own first open, which can take longer than the other startup steps.
timeoutMs: Math.max(timeoutMs, INITIAL_OPEN_MAX_DURATION_MS),
signal: startup.signal,
},
async () => await openPreviewAsync()
).catch(error => {
if (!finishTask) {
Expand Down
14 changes: 11 additions & 3 deletions packages/build-tools/src/steps/utils/ngrokTunnel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,19 @@ const FAILURE_THRESHOLD = 3;
const STOP_TIMEOUT_MS = 4_000;
const OPEN_TIMEOUT_MS = 15_000;
// @ngrok/ngrok runs one open at a time, so nothing can open again until a timed-out open
// settles. The first open waits longer instead, and keeps a listener that arrives late. Retries
// use OPEN_TIMEOUT_MS, so all attempts fit in the 60-second preview opening bound.
const FIRST_OPEN_TIMEOUT_MS = 19_000;
// settles. The first open waits longer instead, and keeps a listener that arrives late.
// An open usually takes less than 1 second. When ngrok is slow, most slow opens finish after
// about 75 seconds, so the first open waits for them instead of failing the session.
export const FIRST_OPEN_TIMEOUT_MS = 90_000;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Queued opens share the startup budget

Cold agent-device startup waits for both tunnels, but openAsync starts timing before ngrok acquires its shared lock. The single-tunnel test misses time spent behind a slow first open.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

const INITIAL_OPEN_ATTEMPTS = 3;
const INITIAL_OPEN_RETRY_DELAY_MS = 1_000;
/** The longest time the first open of a tunnel can take, with all of its retries. */
export const INITIAL_OPEN_MAX_DURATION_MS =
FIRST_OPEN_TIMEOUT_MS +
Array.from(
{ length: INITIAL_OPEN_ATTEMPTS - 1 },
(_, index) => INITIAL_OPEN_RETRY_DELAY_MS * (index + 1) + OPEN_TIMEOUT_MS
).reduce((sum, value) => sum + value, 0);
/** ngrok error codes for failed control-plane requests that can succeed on a retry. */
const RETRYABLE_NGROK_ERROR_CODES = new Set(['ERR_NGROK_802']);
/**
Expand Down
Loading