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

app-updates.ts

546 lines17.9 KB

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