Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
82 changes: 70 additions & 12 deletions packages/kit/src/components/AppUpdate/updateRetry.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { globalNetInfo } from '@onekeyhq/components/src/hooks/useNetInfo';
import { OneKeyLocalError } from '@onekeyhq/shared/src/errors';
import { defaultLogger } from '@onekeyhq/shared/src/logger/logger';
import timerUtils from '@onekeyhq/shared/src/utils/timerUtils';
Expand All @@ -7,30 +8,87 @@ import {
isUnrecoverableDownloadError,
} from './updateErrorTaxonomy';

const DOWNLOAD_RETRY_MAX_ATTEMPTS = 3;
const DOWNLOAD_RETRY_MAX_ATTEMPTS = 5;
const DOWNLOAD_RETRY_BASE_DELAY_MS = 1500;
const DOWNLOAD_RETRY_MAX_DELAY_MS = 60_000;
// Cap on how long we'll camp on the NetInfo listener before falling back to
// the regular backoff. 5 minutes is long enough to cover Wi-Fi → cellular
// handover, captive-portal re-auth, and most train-tunnel blackouts without
// leaving the retry loop wedged forever on a user who just put the phone down.
const DOWNLOAD_RETRY_OFFLINE_WAIT_MS = 5 * 60 * 1000;
// Brief grace after the network is reported back so we don't fire the next
// request while the OS is still negotiating DNS / probing the captive portal.
const DOWNLOAD_RETRY_ONLINE_GRACE_MS = 1500;

// Visible for testing; main callers go through runDownloadWithRetry.
export function computeDownloadRetryDelayMs(attempt: number): number {
return (
const exp =
DOWNLOAD_RETRY_BASE_DELAY_MS * 2 ** attempt +
Math.floor(Math.random() * 500)
);
Math.floor(Math.random() * 500);
return Math.min(exp, DOWNLOAD_RETRY_MAX_DELAY_MS);
}

/**
* Wait until either `timeoutMs` elapses OR globalNetInfo reports the device
* is online (isInternetReachable !== false), whichever comes first. The
* `null` (unknown) state is treated as "not offline" — we never block on a
* NetInfo that hasn't booted yet, since blocking on `null` would wedge the
* retry loop on environments where the reachability probe never runs.
*/
async function waitForOnlineOrTimeout(timeoutMs: number): Promise<void> {
if (globalNetInfo.currentState().isInternetReachable !== false) return;
await new Promise<void>((resolve) => {
let timeoutId: ReturnType<typeof setTimeout> | null = null;
let unsubscribe: (() => void) | null = null;
let resolved = false;
const finish = () => {
if (resolved) return;
resolved = true;
if (timeoutId !== null) clearTimeout(timeoutId);
unsubscribe?.();
resolve();
};
timeoutId = setTimeout(finish, timeoutMs);
unsubscribe = globalNetInfo.addEventListener((state) => {
if (state.isInternetReachable !== false) finish();
});
});
}

/**
* Retries `operation` on transient bundle-update failures (network drops,
* partial truncation, transient server 5xx) up to DOWNLOAD_RETRY_MAX_ATTEMPTS
* times with exponential backoff + jitter. The native modules persist their
* Sleep before the next attempt. When the device is currently reported
* offline, prefer "wait until online" over a fixed exponential delay —
* a 1.5s backoff in a 30s tunnel just burns retries against DNS for nothing.
* When the device is online, fall back to the original
* exp + jitter schedule capped at DOWNLOAD_RETRY_MAX_DELAY_MS.
*/
async function waitBeforeRetry(attempt: number): Promise<void> {
const baseDelay = computeDownloadRetryDelayMs(attempt);
if (globalNetInfo.currentState().isInternetReachable === false) {
await waitForOnlineOrTimeout(DOWNLOAD_RETRY_OFFLINE_WAIT_MS);
// After the listener fires (or the offline cap expires), give the OS a
// moment to stabilize the new path before we hammer the CDN again.
await timerUtils.wait(Math.min(baseDelay, DOWNLOAD_RETRY_ONLINE_GRACE_MS));
return;
}
await timerUtils.wait(baseDelay);
}

/**
* Retries `operation` on transient bundle / APK download failures (network
* drops, partial truncation, transient server 5xx) up to
* DOWNLOAD_RETRY_MAX_ATTEMPTS times. The native modules persist their
* resume artifact (iOS .resume / Android & Desktop .partial) on each failure,
* so each retry is a true range-resume rather than a from-byte-zero re-fetch.
*
* Wait strategy is reachability-aware: while NetInfo reports offline we camp
* on its listener (capped by DOWNLOAD_RETRY_OFFLINE_WAIT_MS) and only release
* once the link comes back; when online we use exponential backoff
* (`1500 * 2^attempt + jitter[0,500)`, capped at DOWNLOAD_RETRY_MAX_DELAY_MS).
*
* Bails immediately for unrecoverable codes (SHA mismatch, HTTP 403/404/410,
* config errors) so we don't waste backoff windows on deterministic dead
* states. Cap of 3 attempts (initial + 3 retries = 4 total round-trips).
* Backoff schedule is `1500 * 2^attempt + jitter[0,500)`, i.e. roughly
* 1.5s, 3s, 6s before the 4th attempt; total worst-case wall time
* before bubbling up is ~10.5s + ~1.5s of jitter.
* states.
*/
export async function runDownloadWithRetry<T>(
operation: () => Promise<T>,
Expand All @@ -54,7 +112,7 @@ export async function runDownloadWithRetry<T>(
extractUpdateErrorCode(e) ?? '<none>'
}`,
);
await timerUtils.wait(delayMs);
await waitBeforeRetry(attempt);
}
}
throw new OneKeyLocalError(
Expand Down
103 changes: 87 additions & 16 deletions packages/kit/src/components/AppUpdate/useAppUpdate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,12 +132,41 @@ jest.mock('@onekeyhq/components', () => {
const te = jest.fn();
(globalThis as any).__mockDialogShow = ds;
(globalThis as any).__mockToastError = te;
// The root jest.config.js moduleNameMapper rewrites `@onekeyhq/components`
// AND every deeper subpath under it (including
// `@onekeyhq/components/src/hooks/useNetInfo`) to the same
// __mocks__/componentsMock.ts. As a result jest.mock attaches to the
// resolved file, so both `import { Toast } from '@onekeyhq/components'`
// AND `import { globalNetInfo } from '@onekeyhq/components/src/hooks/useNetInfo'`
// pull from this single returned object — we must expose ALL named exports
// here, or one import path will silently overwrite the other.
const netInfoListeners: Array<
(s: { isInternetReachable: boolean | null }) => void
> = [];
const globalNetInfo = {
currentState: () => ({ isInternetReachable: null as boolean | null }),
addEventListener: (
l: (s: { isInternetReachable: boolean | null }) => void,
) => {
netInfoListeners.push(l);
return () => {
const idx = netInfoListeners.indexOf(l);
if (idx >= 0) netInfoListeners.splice(idx, 1);
};
},
__emit: (state: { isInternetReachable: boolean | null }) => {
[...netInfoListeners].forEach((l) => l(state));
},
__reset: () => netInfoListeners.splice(0, netInfoListeners.length),
};
(globalThis as any).__mockGlobalNetInfo = globalNetInfo;
return {
Dialog: { show: ds },
Toast: { error: te },
LottieView: () => null,
YStack: ({ children }: any) => children,
useInTabDialog: () => ({ show: ds }),
globalNetInfo,
};
});

Expand Down Expand Up @@ -477,24 +506,26 @@ describe('runDownloadWithRetry', () => {
}
});

test('throws the last error after exhausting all 3 retries', async () => {
const e1 = new Error('NSURLErrorDomain -1005');
const e2 = new Error('NSURLErrorDomain -1001');
const e3 = new Error('HTTP 502');
const e4 = new Error('IO_SocketTimeoutException');
const op = jest
.fn<Promise<string>, []>()
.mockRejectedValueOnce(e1)
.mockRejectedValueOnce(e2)
.mockRejectedValueOnce(e3)
.mockRejectedValueOnce(e4);
test('throws the last error after exhausting all 5 retries', async () => {
const errs = [
new Error('NSURLErrorDomain -1005'),
new Error('NSURLErrorDomain -1001'),
new Error('HTTP 502'),
new Error('IO_SocketTimeoutException'),
new Error('NSURLErrorDomain -1009'),
new Error('HTTP 503'),
];
const op = jest.fn<Promise<string>, []>();
errs.forEach((e) => op.mockRejectedValueOnce(e));
const promise = runDownloadWithRetry(op, 'test').catch((err) => err);
await flush();
await flush();
await flush();
// initial + 5 retries = 6 attempts; flush once per await chain.
for (let i = 0; i < errs.length + 1; i += 1) {
// eslint-disable-next-line no-await-in-loop
await flush();
}
const finalErr = await promise;
expect(finalErr).toBe(e4);
expect(op).toHaveBeenCalledTimes(4); // initial + 3 retries
expect(finalErr).toBe(errs[errs.length - 1]);
expect(op).toHaveBeenCalledTimes(errs.length); // initial + 5 retries
});

test('computeDownloadRetryDelayMs grows exponentially with jitter floor', () => {
Expand All @@ -510,6 +541,46 @@ describe('runDownloadWithRetry', () => {
expect(a2).toBeGreaterThanOrEqual(6000);
expect(a2).toBeLessThan(6500);
});

test('computeDownloadRetryDelayMs is capped at 60s for late attempts', () => {
// base * 2^6 = 96_000 > 60_000 cap; cap must clamp before jitter pushes
// us further. Same for attempt 10 (way past the cap).
expect(computeDownloadRetryDelayMs(6)).toBeLessThanOrEqual(60_000);
expect(computeDownloadRetryDelayMs(10)).toBeLessThanOrEqual(60_000);
});

test('camps on the NetInfo listener while offline and resumes once back online', async () => {
const netInfo = (globalThis as any).__mockGlobalNetInfo;
netInfo.__reset();
// Start offline: the first retry should NOT proceed off the regular
// backoff clock — it should wait for an online emission.
let online = false;
netInfo.currentState = () => ({
isInternetReachable: online ? null : false,
});
const op = jest
.fn<Promise<string>, []>()
.mockRejectedValueOnce(new Error('NSURLErrorDomain -1009'))
.mockResolvedValueOnce('ok');
const promise = runDownloadWithRetry(op, 'test').catch((e) => e);
// Let the rejection settle and waitBeforeRetry block on addEventListener.
for (let i = 0; i < 8; i += 1) {
// eslint-disable-next-line no-await-in-loop
await Promise.resolve();
}
expect(op).toHaveBeenCalledTimes(1);
// Simulate the device coming back online — the listener fires and the
// grace-period setTimeout schedules; advance both.
online = true;
netInfo.__emit({ isInternetReachable: true });
await flush();
await flush();
const result = await promise;
expect(result).toBe('ok');
expect(op).toHaveBeenCalledTimes(2);
// Restore default for sibling tests.
netInfo.currentState = () => ({ isInternetReachable: null });
});
});

// =========================================================================
Expand Down
Loading
Loading