Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

app-updates.ts

551 lines18.1 KB

1import * as Updates from "expo-updates";
2​
3import {
4 type AtomCommandResult,
5 isAtomCommandInterrupted,
6 reportAtomCommandResult,
7 settlePromise,
8 squashAtomCommandFailure,
9} from "@t3tools/client-runtime/state/runtime";
10​
11export type AppUpdateCheckState =
12 | "idle"
13 | "checking"
14 | "downloading"
15 | "ready"
16 | "restarting"
17 | "current";
18​
19export interface AppUpdateClient {
20 readonly isEnabled: boolean;
21 readonly checkForUpdateAsync: () => Promise<{
22 readonly isAvailable: boolean;
23 readonly isRollBackToEmbedded: boolean;
24 }>;
25 readonly fetchUpdateAsync: () => Promise<{
26 readonly isNew: boolean;
27 readonly isRollBackToEmbedded: boolean;
28 }>;
29 readonly reloadAsync: () => Promise<void>;
31​
32export interface AppUpdateEnvironment {
33 readonly confirmInstallNow: () => Promise<boolean>;
34 readonly flushPendingWrites: () => Promise<void>;
35 /**
36 * Whether a deferred restart may fire right now: the app must still be
37 * backgrounded (flush latency or an iOS suspend can push the continuation
38 * into the next foreground session) and not merely paused behind an
39 * app-initiated handoff like the Android image picker.
40 */
41 readonly isSafeToRestartInBackground: () => Promise<boolean>;
42 /**
43 * With `includeCurrent`, an app that is already backgrounded fires
44 * immediately (so a backgrounding that raced module load is not missed);
45 * without it, only a future transition fires, so an attempt that already
46 * failed in the current background session cannot retry in a tight loop.
47 */
48 readonly onNextBackground: (apply: () => void, includeCurrent: boolean) => void;
49 readonly onForegroundStay: (apply: () => void) => void;
51​
52export interface AppUpdateDeferral {
53 pendingInstall: boolean;
54 installInProgress: boolean;
56​
57export function createAppUpdateDeferral(): AppUpdateDeferral {
58 return { pendingInstall: false, installInProgress: false };
60​
61const appUpdateDeferral = createAppUpdateDeferral();
62​
63interface AppUpdateCheckOptions {
64 readonly applyMode?: "background" | "immediate";
65 readonly client?: AppUpdateClient;
66 readonly deferral?: AppUpdateDeferral;
67 readonly environment?: AppUpdateEnvironment;
68 readonly onFailure?: (message: string) => void;
69 readonly onStateChange?: (state: AppUpdateCheckState) => void;
71​
72interface AppUpdateCheckProgress {
73 failure: string | undefined;
74 state: AppUpdateCheckState | undefined;
76​
77interface AppUpdateCheckInFlight {
78 readonly failureListeners: Set<NonNullable<AppUpdateCheckOptions["onFailure"]>>;
79 readonly progress: AppUpdateCheckProgress;
80 readonly promise: Promise<void>;
81 readonly stateListeners: Set<NonNullable<AppUpdateCheckOptions["onStateChange"]>>;
83​
84interface Deferred {
85 readonly promise: Promise<void>;
86 readonly reject: (cause: unknown) => void;
87 readonly resolve: () => void;
89​
90const HIDDEN_UPDATE_TAP_COUNT = 5;
91const UPDATE_CHECK_UNAVAILABLE_ERROR_CODES = new Set([
92 "ERR_NOT_AVAILABLE_IN_DEV_CLIENT",
93 "ERR_UPDATES_DISABLED",
94]);
95let appUpdateCheckInFlight: AppUpdateCheckInFlight | undefined;
96​
97/** Expo's development launcher reports updates as enabled even though its OTA APIs reject. */
98export function isAppUpdateCheckAvailable(client: Pick<AppUpdateClient, "isEnabled"> = Updates) {
99 return client.isEnabled && !(typeof __DEV__ !== "undefined" && __DEV__);
101​
102export function registerHiddenUpdateTap(count: number): {
103 readonly nextCount: number;
104 readonly shouldCheck: boolean;
105} {
106 const nextCount = count + 1;
107 if (nextCount >= HIDDEN_UPDATE_TAP_COUNT) {
108 return {
109 nextCount: 0,
110 shouldCheck: true,
111 };
112 }
113 return {
114 nextCount,
115 shouldCheck: false,
116 };
118​
119export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Promise<void> {
120 const client = options.client ?? Updates;
121 if (!isAppUpdateCheckAvailable(client)) return;
122​
123 if (appUpdateCheckInFlight) {
124 await observeAppUpdateCheck(appUpdateCheckInFlight, options);
125 if (options.applyMode === "immediate") {
126 const deferral = options.deferral ?? appUpdateDeferral;
127 if (deferral.pendingInstall) {
128 const environment = options.environment ?? defaultAppUpdateEnvironment;
129 await installPendingAppUpdate(client, environment, deferral, options);
130 }
131 }
132 return;
133 }
134​
135 const progress: AppUpdateCheckProgress = {
136 failure: undefined,
137 state: undefined,
138 };
139 const failureListeners = new Set<NonNullable<AppUpdateCheckOptions["onFailure"]>>();
140 const stateListeners = new Set<NonNullable<AppUpdateCheckOptions["onStateChange"]>>();
141 if (options.onFailure) failureListeners.add(options.onFailure);
142 if (options.onStateChange) stateListeners.add(options.onStateChange);
143​
144 const deferred = createDeferred();
145 const inFlight: AppUpdateCheckInFlight = {
146 failureListeners,
147 progress,
148 promise: deferred.promise,
149 stateListeners,
150 };
151 // Publish the operation before any state listener can synchronously re-enter.
152 appUpdateCheckInFlight = inFlight;
153​
154 const execution = performAppUpdateCheck(client, {
155 applyMode: options.applyMode,
156 deferral: options.deferral,
157 environment: options.environment,
158 onFailure: (message) => {
159 progress.failure = message;
160 notifyListeners(failureListeners, message);
161 },
162 onStateChange: (state) => {
163 progress.state = state;
164 notifyListeners(stateListeners, state);
165 },
166 });
167 void execution.then(deferred.resolve, deferred.reject);
168​
169 try {
170 await deferred.promise;
171 } finally {
172 if (appUpdateCheckInFlight === inFlight) {
173 appUpdateCheckInFlight = undefined;
174 }
175 }
177​
178function createDeferred(): Deferred {
179 let reject!: Deferred["reject"];
180 let resolve!: Deferred["resolve"];
181 const promise = new Promise<void>((resolvePromise, rejectPromise) => {
182 resolve = () => resolvePromise();
183 reject = rejectPromise;
184 });
185 return { promise, reject, resolve };
187​
188function notifyListeners<A>(listeners: ReadonlySet<(value: A) => void>, value: A): void {
189 // A listener can synchronously subscribe another caller. Snapshot so that
190 // caller receives only observeAppUpdateCheck's explicit current-value replay.
191 const snapshot = Array.from(listeners);
192 for (const listener of snapshot) listener(value);
194​
195async function observeAppUpdateCheck(
196 inFlight: AppUpdateCheckInFlight,
197 options: AppUpdateCheckOptions,
198): Promise<void> {
199 const onFailure = options.onFailure;
200 const onStateChange = options.onStateChange;
201​
202 if (onFailure) {
203 inFlight.failureListeners.add(onFailure);
204 if (inFlight.progress.failure) onFailure(inFlight.progress.failure);
205 }
206 if (onStateChange) {
207 inFlight.stateListeners.add(onStateChange);
208 if (inFlight.progress.state) onStateChange(inFlight.progress.state);
209 }
210​
211 try {
212 await inFlight.promise;
213 } finally {
214 if (onFailure) inFlight.failureListeners.delete(onFailure);
215 if (onStateChange) inFlight.stateListeners.delete(onStateChange);
216 }
218​
219async function performAppUpdateCheck(
220 client: AppUpdateClient,
221 options: AppUpdateCheckOptions,
222): Promise<void> {
223 const setState = options.onStateChange ?? (() => {});
224 const environment = options.environment ?? defaultAppUpdateEnvironment;
225 const deferral = options.deferral ?? appUpdateDeferral;
226​
227 if (options.applyMode === "immediate" && deferral.pendingInstall) {
228 await installPendingAppUpdate(client, environment, deferral, options);
229 return;
230 }
231​
232 setState("checking");
233 const check = await settlePromise(() => client.checkForUpdateAsync());
234 if (check._tag === "Failure") {
235 reportUpdateFailure(check, "Could not check for updates.", options.onFailure);
236 setState("idle");
237 return;
238 }
239 // A rollback directive (`eas update:rollback`) arrives as isAvailable: false
240 // with isRollBackToEmbedded: true. The running OTA still has to be dropped.
241 if (!check.value.isAvailable && !check.value.isRollBackToEmbedded) {
242 setState("current");
243 return;
244 }
245​
246 setState("downloading");
247 const fetched = await settlePromise(() => client.fetchUpdateAsync());
248 if (fetched._tag === "Failure") {
249 reportUpdateFailure(fetched, "Could not download the update.", options.onFailure);
250 setState("idle");
251 return;
252 }
253 // isNew is always false for a rollback, so it cannot be the sole gate.
254 if (!fetched.value.isNew && !fetched.value.isRollBackToEmbedded) {
255 setState("current");
256 return;
257 }
258​
259 if (options.applyMode === "immediate" || fetched.value.isRollBackToEmbedded) {
260 const outcome = await installAppUpdate(
261 client,
262 environment,
263 deferral,
264 options,
265 options.applyMode === "immediate",
266 );
267 if (outcome === "flush-failed") {
268 setState("ready");
269 armDeferredAppUpdateInstall(client, environment, deferral);
270 }
271 return;
272 }
273​
274 setState("ready");
275 armDeferredAppUpdateInstall(client, environment, deferral);
277​
278type AppUpdateInstallOutcome = "installed" | "flush-failed" | "restart-failed";
279​
280/**
281 * Restarting mid-session while native surfaces are mounted is the crashiest
282 * moment expo-updates has, so the restart flushes persistence first and, by
283 * default, waits for a backgrounding — where nothing is rendering and the
284 * teardown is invisible.
285 */
286async function installAppUpdate(
287 client: AppUpdateClient,
288 environment: AppUpdateEnvironment,
289 deferral: AppUpdateDeferral,
290 options: AppUpdateCheckOptions,
291 userRequested: boolean,
292): Promise<AppUpdateInstallOutcome> {
293 if (deferral.installInProgress) return "installed";
294 deferral.installInProgress = true;
295 const setState = options.onStateChange ?? (() => {});
296 setState("restarting");
297 const flushed = await settlePromise(() => environment.flushPendingWrites());
298 if (flushed._tag === "Failure") {
299 reportUpdateFailure(flushed, "Could not save pending state.", undefined);
300 if (!userRequested) {
301 deferral.installInProgress = false;
302 return "flush-failed";
303 }
304 }
305 const reloaded = await settlePromise(() => client.reloadAsync());
306 if (reloaded._tag === "Failure") {
307 reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.", options.onFailure);
308 setState("idle");
309 deferral.installInProgress = false;
310 return "restart-failed";
311 }
312 return "installed";
314​
315async function installPendingAppUpdate(
316 client: AppUpdateClient,
317 environment: AppUpdateEnvironment,
318 deferral: AppUpdateDeferral,
319 options: AppUpdateCheckOptions,
320): Promise<void> {
321 const outcome = await installAppUpdate(client, environment, deferral, options, true);
322 if (outcome === "restart-failed") {
323 deferral.pendingInstall = false;
324 }
326​
327function armDeferredAppUpdateInstall(
328 client: AppUpdateClient,
329 environment: AppUpdateEnvironment,
330 deferral: AppUpdateDeferral,
331): void {
332 if (deferral.pendingInstall) return;
333 deferral.pendingInstall = true;
334 scheduleDeferredAppUpdateInstall(client, environment, deferral, true);
335 environment.onForegroundStay(() => {
336 void promptDeferredAppUpdateInstall(client, environment, deferral);
337 });
339​
340async function promptDeferredAppUpdateInstall(
341 client: AppUpdateClient,
342 environment: AppUpdateEnvironment,
343 deferral: AppUpdateDeferral,
344): Promise<void> {
345 if (!deferral.pendingInstall || deferral.installInProgress) return;
346 const installNow = await settlePromise(() => environment.confirmInstallNow());
347 if (installNow._tag !== "Success" || !installNow.value) return;
348 // A backgrounding while the alert was up may have started the deferred
349 // restart already; the stale accept must not start a second one.
350 if (!deferral.pendingInstall || deferral.installInProgress) return;
351 await installPendingAppUpdate(client, environment, deferral, {});
353​
354function scheduleDeferredAppUpdateInstall(
355 client: AppUpdateClient,
356 environment: AppUpdateEnvironment,
357 deferral: AppUpdateDeferral,
358 includeCurrent: boolean,
359): void {
360 environment.onNextBackground(() => {
361 void applyDeferredAppUpdateInstall(client, environment, deferral);
362 }, includeCurrent);
364​
365async function applyDeferredAppUpdateInstall(
366 client: AppUpdateClient,
367 environment: AppUpdateEnvironment,
368 deferral: AppUpdateDeferral,
369): Promise<void> {
370 if (!deferral.pendingInstall || deferral.installInProgress) return;
371 deferral.installInProgress = true;
372 const flushed = await settlePromise(() => environment.flushPendingWrites());
373 const safe = await settlePromise(() => environment.isSafeToRestartInBackground());
374 if (flushed._tag === "Failure" || safe._tag !== "Success" || !safe.value) {
375 if (flushed._tag === "Failure") {
376 reportUpdateFailure(flushed, "Could not save pending state.", undefined);
377 }
378 deferral.installInProgress = false;
379 // This attempt already ran in the current background session; retrying
380 // before a fresh transition would just loop over the same failure.
381 scheduleDeferredAppUpdateInstall(client, environment, deferral, false);
382 return;
383 }
384 const reloaded = await settlePromise(() => client.reloadAsync());
385 if (reloaded._tag === "Failure") {
386 reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.", undefined);
387 deferral.installInProgress = false;
388 deferral.pendingInstall = false;
389 }
391​
392async function defaultConfirmInstallNow(): Promise<boolean> {
393 const Dialog = await import("../../components/ui/Dialog");
394 return new Promise<boolean>((resolve) => {
395 Dialog.alert(
396 "Update ready",
397 "A new version has been downloaded and installs automatically the next time you leave the app. Install it now instead?",
398 [
399 { onPress: () => resolve(false), style: "cancel", text: "Later" },
400 { onPress: () => resolve(true), text: "Install Now" },
401 ],
402 { cancelable: true, onDismiss: () => resolve(false) },
403 );
404 });
406​
407async function defaultFlushPendingWrites(): Promise<void> {
408 const results = await Promise.allSettled([
409 import("../../state/use-composer-drafts").then((drafts) => drafts.flushComposerDrafts()),
410 import("../../state/thread-outbox").then((outbox) => outbox.flushThreadOutbox()),
411 ]);
412 const failed = results.find(
413 (result): result is PromiseRejectedResult => result.status === "rejected",
414 );
415 if (failed) throw failed.reason;
417​
418async function defaultIsSafeToRestartInBackground(): Promise<boolean> {
419 const { isForegroundHandoffActive } = await import("../../lib/foreground-handoff");
420 if (isForegroundHandoffActive()) return false;
421 const { AppState } = await import("react-native");
422 return AppState.currentState === "background";
424​
425function defaultOnNextBackground(apply: () => void, includeCurrent: boolean): void {
426 void import("react-native").then(({ AppState }) => {
427 const subscription = AppState.addEventListener("change", (state) => {
428 if (state !== "background") return;
429 subscription.remove();
430 apply();
431 });
432 if (includeCurrent && AppState.currentState === "background") {
433 subscription.remove();
434 apply();
435 }
436 });
438​
439export const DEFERRED_INSTALL_PROMPT_AFTER_MS = 30 * 60 * 1000;
440​
441/**
442 * iOS "inactive" blips (app switcher, a pulled-down notification shade) leave
443 * the timer running.
444 */
445function defaultOnForegroundStay(apply: () => void): void {
446 void import("react-native").then(({ AppState }) => {
447 let timer: ReturnType<typeof setTimeout> | undefined;
448 const arm = () => {
449 timer ??= setTimeout(() => {
450 subscription.remove();
451 apply();
452 }, DEFERRED_INSTALL_PROMPT_AFTER_MS);
453 };
454 const disarm = () => {
455 if (timer === undefined) return;
456 clearTimeout(timer);
457 timer = undefined;
458 };
459 const subscription = AppState.addEventListener("change", (state) => {
460 if (state === "active") arm();
461 else if (state === "background") disarm();
462 });
463 if (AppState.currentState === "active") arm();
464 });
466​
467const defaultAppUpdateEnvironment: AppUpdateEnvironment = {
468 confirmInstallNow: defaultConfirmInstallNow,
469 flushPendingWrites: defaultFlushPendingWrites,
470 isSafeToRestartInBackground: defaultIsSafeToRestartInBackground,
471 onNextBackground: defaultOnNextBackground,
472 onForegroundStay: defaultOnForegroundStay,
473};
474​
475function reportUpdateFailure(
476 result: AtomCommandResult<unknown, unknown>,
477 fallback: string,
478 onFailure: AppUpdateCheckOptions["onFailure"],
479): void {
480 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
481 const error = squashAtomCommandFailure(result);
482 if (isAppUpdateUnavailableError(error)) return;
483​
484 reportAtomCommandResult(result, { label: "app update check" });
485 onFailure?.(error instanceof Error ? error.message : fallback);
487​
488function isAppUpdateUnavailableError(error: unknown): boolean {
489 if (typeof error !== "object" || error === null || !("code" in error)) return false;
490 const code = error.code;
491 return typeof code === "string" && UPDATE_CHECK_UNAVAILABLE_ERROR_CODES.has(code);
493​
494export function createAppUpdateLaunchCheck(
495 client: AppUpdateClient = Updates,
496): () => Promise<void> | undefined {
497 let started = false;
498​
499 return () => {
500 if (started || !isAppUpdateCheckAvailable(client)) return undefined;
501 started = true;
502 return runAppUpdateCheck({ client });
503 };
505​
506export const checkForAppUpdateOnLaunch = createAppUpdateLaunchCheck();
507​
508export const FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS = 15 * 60 * 1000;
509​
510export function shouldRecheckAppUpdateOnForeground(
511 backgroundedAtMs: number | null,
512 activeAtMs: number,
513 pendingInstall: boolean,
514): boolean {
515 if (pendingInstall) return false;
516 return (
517 backgroundedAtMs !== null &&
518 activeAtMs - backgroundedAtMs >= FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS
519 );
521​
522export function createAppUpdateForegroundRecheck(
523 client: AppUpdateClient = Updates,
524 deferral: AppUpdateDeferral = appUpdateDeferral,
525): () => void {
526 let started = false;
527​
528 return () => {
529 if (started || !isAppUpdateCheckAvailable(client)) return;
530 started = true;
531 void import("react-native").then(({ AppState }) => {
532 let backgroundedAtMs: number | null = null;
533 AppState.addEventListener("change", (state) => {
534 if (state === "background") {
535 backgroundedAtMs = Date.now();
536 return;
537 }
538 if (state !== "active") return;
539 const shouldCheck = shouldRecheckAppUpdateOnForeground(
540 backgroundedAtMs,
541 Date.now(),
542 deferral.pendingInstall,
543 );
544 backgroundedAtMs = null;
545 if (shouldCheck) void runAppUpdateCheck({ client, deferral });
546 });
547 });
548 };
550​
551export const startAppUpdateForegroundRecheck = createAppUpdateForegroundRecheck();