@aglyn/tenant-feature-instance 1.20.1 → 1.20.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/lib/hooks/firebase/firebase-services.js +4 -0
- package/src/lib/hooks/firebase/firebase-services.js.map +1 -1
- package/src/lib/hooks/firebase/firestore-multitab-wedge.d.ts +19 -1
- package/src/lib/hooks/firebase/firestore-multitab-wedge.js +24 -11
- package/src/lib/hooks/firebase/firestore-multitab-wedge.js.map +1 -1
- package/src/lib/hooks/firebase/firestore-page-wedge-check.d.ts +94 -0
- package/src/lib/hooks/firebase/firestore-page-wedge-check.js +136 -0
- package/src/lib/hooks/firebase/firestore-page-wedge-check.js.map +1 -0
- package/src/lib/hooks/firebase/firestore-primary-yield.d.ts +37 -14
- package/src/lib/hooks/firebase/firestore-primary-yield.js +82 -23
- package/src/lib/hooks/firebase/firestore-primary-yield.js.map +1 -1
- package/src/lib/hooks/firebase/firestore-stall-recovery.d.ts +6 -0
- package/src/lib/hooks/firebase/firestore-stall-recovery.js +7 -0
- package/src/lib/hooks/firebase/firestore-stall-recovery.js.map +1 -1
- package/src/lib/hooks/merchant-payments-state.d.ts +59 -0
- package/src/lib/hooks/merchant-payments-state.js +90 -0
- package/src/lib/hooks/merchant-payments-state.js.map +1 -0
- package/src/lib/hooks/use-merchant-payments.d.ts +2 -42
- package/src/lib/hooks/use-merchant-payments.js +2 -49
- package/src/lib/hooks/use-merchant-payments.js.map +1 -1
|
@@ -46,9 +46,13 @@ import { openExisting, PRIMARY_LEASE_MAX_AGE_MS, readSharedClientIds } from "./f
|
|
|
46
46
|
* the lease and the holder's row, read-only. When the lease is live, held
|
|
47
47
|
* by another tab, and that tab's own row says it is in the background, it
|
|
48
48
|
* posts `yield` on a `BroadcastChannel` named for this cache. It looks
|
|
49
|
-
*
|
|
50
|
-
* {@link
|
|
51
|
-
* every {@link RECHECK_MS} while it stays
|
|
49
|
+
* as soon as its client has started and five more times in its first 10 s
|
|
50
|
+
* ({@link BOOT_CHECK_DELAYS_MS}), once it has been visible for
|
|
51
|
+
* {@link VISIBLE_DWELL_MS}, and every {@link RECHECK_MS} while it stays
|
|
52
|
+
* visible. When its own row still says hidden (the SDK writes a new tab's
|
|
53
|
+
* first row that way), it cycles its own network first, which rewrites
|
|
54
|
+
* the row from the visibility the SDK has read by then, instead of waiting
|
|
55
|
+
* for the SDK's 4 s tick.
|
|
52
56
|
* - **The holder** knows its own client id (the one `firestore_clients_*` key
|
|
53
57
|
* that appeared while its client started, as in AGL-3660). On a `yield`
|
|
54
58
|
* naming it, while it is hidden and online, it rereads in one transaction:
|
|
@@ -76,27 +80,43 @@ import { openExisting, PRIMARY_LEASE_MAX_AGE_MS, readSharedClientIds } from "./f
|
|
|
76
80
|
* started together) never acts as holder. The asker's row must be younger
|
|
77
81
|
* than {@link ASKER_FRESH_MS}, or the SDK would not hand to it and the
|
|
78
82
|
* holder's cycle would only flicker its network.
|
|
79
|
-
* - **Rate-limited both ways**:
|
|
80
|
-
*
|
|
81
|
-
*
|
|
83
|
+
* - **Rate-limited both ways**: up to {@link ASK_BURST} asks
|
|
84
|
+
* {@link ASK_RETRY_MS} apart (an ask a background holder never answered,
|
|
85
|
+
* or answered while the asker's row was not yet fresh, is asked again),
|
|
86
|
+
* then one per {@link ASK_INTERVAL_MS}; one yield per
|
|
87
|
+
* {@link YIELD_INTERVAL_MS}. Switching between two console tabs moves the
|
|
88
|
+
* role at most that often.
|
|
82
89
|
* - **Every failure is the old behaviour.** No `BroadcastChannel`, no
|
|
83
90
|
* database, a store another tab has locked, any throw: nothing is posted
|
|
84
91
|
* or cycled, and the SDK's election runs as it always has.
|
|
85
92
|
*/ /** How long a tab must stay visible before it asks for the role. */ export const VISIBLE_DWELL_MS = 3000;
|
|
86
93
|
/** How often a visible tab looks again while it stays visible. */ export const RECHECK_MS = 15000;
|
|
87
94
|
/**
|
|
88
|
-
* The looks after
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
*
|
|
95
|
+
* The looks after this tab's client has started. The first is immediate: a
|
|
96
|
+
* background holder costs a cold load 10-16 s (measured in production on
|
|
97
|
+
* 2026-11-10), and the first looks at 2, 5 and 9 s it replaced asked only
|
|
98
|
+
* on the third. The SDK writes a new tab's first row as hidden (see
|
|
99
|
+
* `firestore-tab-handoff.ts`), so a look that finds its own row not ready
|
|
100
|
+
* rewrites it with a network cycle ({@link REFRESH_INTERVAL_MS}) and asks
|
|
101
|
+
* once the rewrite has landed: in the same look, or in the next one a
|
|
102
|
+
* second later. The later looks cover a read that found the store
|
|
103
|
+
* locked and an ask the holder did not act on. Each is a no-op once the role
|
|
104
|
+
* has moved here.
|
|
94
105
|
*/ export const BOOT_CHECK_DELAYS_MS = [
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
106
|
+
0,
|
|
107
|
+
1000,
|
|
108
|
+
2500,
|
|
109
|
+
4500,
|
|
110
|
+
7000,
|
|
111
|
+
10000
|
|
98
112
|
];
|
|
99
|
-
/**
|
|
113
|
+
/** An unanswered ask may be repeated this soon, up to {@link ASK_BURST}. */ export const ASK_RETRY_MS = 3000;
|
|
114
|
+
/** Asks allowed {@link ASK_RETRY_MS} apart before the long interval. */ export const ASK_BURST = 3;
|
|
115
|
+
/** After a burst, at most one ask per this long from one tab. */ export const ASK_INTERVAL_MS = 15000;
|
|
116
|
+
/**
|
|
117
|
+
* At most one rewrite of this tab's own row per this long: the SDK's own
|
|
118
|
+
* renewal tick, after which it would have rewritten the row anyway.
|
|
119
|
+
*/ export const REFRESH_INTERVAL_MS = 4000;
|
|
100
120
|
/** At most one yield per this long from one tab. */ export const YIELD_INTERVAL_MS = 30000;
|
|
101
121
|
/**
|
|
102
122
|
* The asker's row must be at least this fresh. The SDK only hands the lease
|
|
@@ -282,6 +302,8 @@ const MUTATIONS_STORE = 'mutations';
|
|
|
282
302
|
* Neither method ever rejects.
|
|
283
303
|
*/ export function createPrimaryYield(deps) {
|
|
284
304
|
let lastAskAt = Number.NEGATIVE_INFINITY;
|
|
305
|
+
let asksInBurst = 0;
|
|
306
|
+
let lastRefreshAt = Number.NEGATIVE_INFINITY;
|
|
285
307
|
let lastYieldAt = Number.NEGATIVE_INFINITY;
|
|
286
308
|
let busy = false;
|
|
287
309
|
// Looks can overlap (a boot look, the dwell look and the recheck): only
|
|
@@ -298,7 +320,7 @@ const MUTATIONS_STORE = 'mutations';
|
|
|
298
320
|
result: 'skipped',
|
|
299
321
|
reason: 'self-not-ready'
|
|
300
322
|
});
|
|
301
|
-
if (looking ||
|
|
323
|
+
if (looking || !mayAsk()) return emit({
|
|
302
324
|
side: 'asker',
|
|
303
325
|
result: 'skipped',
|
|
304
326
|
reason: 'throttled'
|
|
@@ -316,15 +338,18 @@ const MUTATIONS_STORE = 'mutations';
|
|
|
316
338
|
});
|
|
317
339
|
}
|
|
318
340
|
}
|
|
319
|
-
/**
|
|
341
|
+
/** A short burst of asks, then the long interval. */ function mayAsk() {
|
|
342
|
+
const since = deps.now() - lastAskAt;
|
|
343
|
+
if (since >= ASK_INTERVAL_MS) return true;
|
|
344
|
+
return since >= ASK_RETRY_MS && asksInBurst < ASK_BURST;
|
|
345
|
+
}
|
|
346
|
+
/** One read, and the decision it supports. */ async function decide() {
|
|
320
347
|
const read = await deps.read([
|
|
321
348
|
deps.selfId
|
|
322
349
|
]);
|
|
323
|
-
if (read.state !== 'read') return
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
reason: read.state
|
|
327
|
-
});
|
|
350
|
+
if (read.state !== 'read') return {
|
|
351
|
+
skipped: read.state
|
|
352
|
+
};
|
|
328
353
|
const decision = decideAsk({
|
|
329
354
|
owner: read.owner,
|
|
330
355
|
holder: read.owner ? read.rows[read.owner.ownerId] : undefined,
|
|
@@ -332,6 +357,39 @@ const MUTATIONS_STORE = 'mutations';
|
|
|
332
357
|
selfId: deps.selfId,
|
|
333
358
|
now: deps.now()
|
|
334
359
|
});
|
|
360
|
+
return {
|
|
361
|
+
read,
|
|
362
|
+
decision
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
/** One read and, when it says so, one ask. */ async function look() {
|
|
366
|
+
let looked = await decide();
|
|
367
|
+
if ('skipped' in looked) return emit({
|
|
368
|
+
side: 'asker',
|
|
369
|
+
result: 'skipped',
|
|
370
|
+
reason: looked.skipped
|
|
371
|
+
});
|
|
372
|
+
// Visible and online, but the row the holder will read says otherwise:
|
|
373
|
+
// the SDK wrote it before it read the visibility. A network cycle runs
|
|
374
|
+
// its election, which rewrites the row; a secondary's cycle touches no
|
|
375
|
+
// stream. The SDK queues that election behind the cycle, so this second
|
|
376
|
+
// read usually sees it and sometimes does not; the next boot look, a
|
|
377
|
+
// second later, does.
|
|
378
|
+
if ('reason' in looked.decision && looked.decision.reason === 'self-not-ready' && deps.isVisible() && deps.isOnline() && deps.now() - lastRefreshAt >= REFRESH_INTERVAL_MS) {
|
|
379
|
+
lastRefreshAt = deps.now();
|
|
380
|
+
await deps.cycleNetwork();
|
|
381
|
+
emit({
|
|
382
|
+
side: 'asker',
|
|
383
|
+
result: 'refreshed'
|
|
384
|
+
});
|
|
385
|
+
looked = await decide();
|
|
386
|
+
if ('skipped' in looked) return emit({
|
|
387
|
+
side: 'asker',
|
|
388
|
+
result: 'skipped',
|
|
389
|
+
reason: looked.skipped
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
const { decision } = looked;
|
|
335
393
|
if ('reason' in decision) return emit({
|
|
336
394
|
side: 'asker',
|
|
337
395
|
result: 'skipped',
|
|
@@ -343,6 +401,7 @@ const MUTATIONS_STORE = 'mutations';
|
|
|
343
401
|
result: 'skipped',
|
|
344
402
|
reason: 'self-not-ready'
|
|
345
403
|
});
|
|
404
|
+
asksInBurst = deps.now() - lastAskAt >= ASK_INTERVAL_MS ? 1 : asksInBurst + 1;
|
|
346
405
|
lastAskAt = deps.now();
|
|
347
406
|
deps.post({
|
|
348
407
|
type: 'yield',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-primary-yield.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n disableNetwork,\n enableNetwork,\n type Firestore,\n} from 'firebase/firestore'\nimport {\n type ClientRow,\n type LeaseRow,\n openExisting,\n PRIMARY_LEASE_MAX_AGE_MS,\n readSharedClientIds,\n} from './firestore-tab-handoff'\n\n/**\n * A BACKGROUND TAB HANDS THE SHARED CACHE TO THE TAB THE USER IS LOOKING AT\n * (AGL-4204).\n *\n * ## What it fixes\n *\n * With `persistentMultipleTabManager` one tab, the lease holder, does every\n * tab's network and most of their IndexedDB work, and every SDK transaction\n * locks every store. The SDK never moves a LIVE lease\n * (`IndexedDbPersistence.canActAsPrimary`, `@firebase/firestore` 4.18.0):\n * a holder whose lease is under 5 s old and whose network is on keeps it\n * whatever its visibility, and a visible tab wins only on a lapse. A console\n * tab left in the background therefore serves the tab the user is in for as\n * long as it keeps renewing, from a renderer the browser runs at background\n * priority. Measured in production on 2026-11-06: reads in other tabs waited\n * 16.9 s, 18.9 s and 4.5 s behind a background holder within three minutes,\n * and a lease went 23.7 s stale. The cache's size never moved in those\n * stalls, so they were not LRU collection.\n *\n * `firestore-tab-handoff.ts` (AGL-3660) claims a LAPSED lease for a new\n * visible tab at boot. It cannot take a live one: two primaries over one\n * cache write tombstones (AGL-3788). This module covers the live case by\n * having the HOLDER let go, through the SDK's own election.\n *\n * ## How\n *\n * - **The asker** (a visible, online tab on the durable multi-tab cache) reads\n * the lease and the holder's row, read-only. When the lease is live, held\n * by another tab, and that tab's own row says it is in the background, it\n * posts `yield` on a `BroadcastChannel` named for this cache. It looks\n * three times in its first 9 s, once it has been visible for\n * {@link VISIBLE_DWELL_MS}, and\n * every {@link RECHECK_MS} while it stays visible.\n * - **The holder** knows its own client id (the one `firestore_clients_*` key\n * that appeared while its client started, as in AGL-3660). On a `yield`\n * naming it, while it is hidden and online, it rereads in one transaction:\n * still the holder; the asker's row fresh, foreground and online; no write\n * pending. Then `disableNetwork` → `enableNetwork`. With its network off,\n * the SDK's election finds the asker a better candidate\n * (`otherClientHasBetterNetworkState`) and releases the lease, after the\n * disable has stopped its Watch and write streams, because the election\n * is queued behind the disable. Re-enabled, it finds the lease vacant and\n * a foreground candidate, so it stays secondary. It replies `yielded`.\n * - **The asker** then cycles its own network. That cycle is invisible in a\n * secondary (`syncEngineApplyOnlineStateChange` ignores its own remote\n * store there), and the election it runs takes the vacant lease at once\n * instead of on its next 4 s tick.\n *\n * ## Why it is safe\n *\n * - **Never two primaries.** The lease is only ever released by its holder\n * and only ever taken vacant, both by the SDK's own code. Nothing here\n * writes a lease.\n * - **Never with a write in flight.** A new primary resends every\n * unacknowledged batch, so the holder declines while `mutations` has a row,\n * the same rule AGL-3660 follows.\n * - **Never on a guess.** A tab that cannot tell which client it is (two tabs\n * started together) never acts as holder. The asker's row must be younger\n * than {@link ASKER_FRESH_MS}, or the SDK would not hand to it and the\n * holder's cycle would only flicker its network.\n * - **Rate-limited both ways**: one ask per {@link ASK_INTERVAL_MS}, one\n * yield per {@link YIELD_INTERVAL_MS}. Switching between two console tabs\n * moves the role at most that often.\n * - **Every failure is the old behaviour.** No `BroadcastChannel`, no\n * database, a store another tab has locked, any throw: nothing is posted\n * or cycled, and the SDK's election runs as it always has.\n */\n\n/** How long a tab must stay visible before it asks for the role. */\nexport const VISIBLE_DWELL_MS = 3_000\n\n/** How often a visible tab looks again while it stays visible. */\nexport const RECHECK_MS = 15_000\n\n/**\n * The looks after boot. The first comes once AGL-3660's claim has had its\n * turn. The SDK writes a new tab's first row as hidden, and corrects it at\n * its first 4 s tick (see `firestore-tab-handoff.ts`), so the first look\n * often finds this tab \"not ready\". The later ones land after that tick. Each\n * is a no-op once an ask has gone out (`ASK_INTERVAL_MS`) or the role has\n * moved here.\n */\nexport const BOOT_CHECK_DELAYS_MS = [2_000, 5_000, 9_000] as const\n\n/** At most one ask per this long from one tab. */\nexport const ASK_INTERVAL_MS = 15_000\n\n/** At most one yield per this long from one tab. */\nexport const YIELD_INTERVAL_MS = 30_000\n\n/**\n * The asker's row must be at least this fresh. The SDK only hands the lease\n * to a client renewed within `MAX_PRIMARY_ELIGIBLE_AGE_MS` (5 s); a visible\n * tab renews every 4 s.\n */\nexport const ASKER_FRESH_MS = 4_500\n\n/** How long a read may wait to start before it counts as locked. */\nexport const READ_TIMEOUT_MS = 1_500\n\nexport type YieldMessage =\n | { type: 'yield'; holderId: string; askerId: string }\n | { type: 'yielded'; holderId: string; askerId: string }\n\n/** Why a visible tab did not ask. */\nexport type AskSkip =\n | 'vacant'\n | 'self-holds'\n | 'holder-unknown'\n | 'holder-visible'\n | 'lease-lapsed'\n | 'self-unknown'\n | 'self-not-ready'\n\nexport type AskDecision =\n { ask: true; holderId: string } | { ask: false; reason: AskSkip }\n\n/**\n * Whether the tab `selfId` should ask the holder to yield. Pure.\n *\n * A lapsed lease is left alone: the SDK's next election in a visible tab\n * takes it, and AGL-3660 claims it at boot.\n */\nexport function decideAsk(input: {\n owner: LeaseRow | undefined\n holder: ClientRow | undefined\n self: ClientRow | undefined\n selfId: string\n now: number\n}): AskDecision {\n const { owner, holder, self, selfId, now } = input\n if (!owner) return { ask: false, reason: 'vacant' }\n if (owner.ownerId === selfId) return { ask: false, reason: 'self-holds' }\n if (now - owner.leaseTimestampMs >= PRIMARY_LEASE_MAX_AGE_MS)\n return { ask: false, reason: 'lease-lapsed' }\n if (!holder) return { ask: false, reason: 'holder-unknown' }\n if (holder.inForeground) return { ask: false, reason: 'holder-visible' }\n if (!self) return { ask: false, reason: 'self-unknown' }\n // The SDK hands only to a client that has recorded itself foreground and\n // online; the first record a new tab writes says hidden (AGL-3660).\n if (!self.inForeground || !self.networkEnabled)\n return { ask: false, reason: 'self-not-ready' }\n return { ask: true, holderId: owner.ownerId }\n}\n\n/** Why the holder did not yield. */\nexport type YieldSkip =\n | 'not-holder'\n | 'asker-unknown'\n | 'asker-stale'\n | 'asker-hidden'\n | 'asker-offline'\n | 'pending-writes'\n\nexport type YieldDecision =\n { yield: true } | { yield: false; reason: YieldSkip }\n\n/** Whether the holder `selfId` should let go for `asker`. Pure. */\nexport function decideYield(input: {\n owner: LeaseRow | undefined\n asker: ClientRow | undefined\n selfId: string\n pendingWrites: number\n now: number\n}): YieldDecision {\n const { owner, asker, selfId, pendingWrites, now } = input\n if (owner?.ownerId !== selfId) return { yield: false, reason: 'not-holder' }\n if (pendingWrites > 0) return { yield: false, reason: 'pending-writes' }\n if (!asker) return { yield: false, reason: 'asker-unknown' }\n if (!asker.inForeground) return { yield: false, reason: 'asker-hidden' }\n if (!asker.networkEnabled) return { yield: false, reason: 'asker-offline' }\n if (now - asker.updateTimeMs > ASKER_FRESH_MS)\n return { yield: false, reason: 'asker-stale' }\n return { yield: true }\n}\n\n/** One read-only look at the lease, two client rows and the write queue. */\nexport type LeaseRead =\n | {\n state: 'read'\n owner: LeaseRow | undefined\n rows: Record<string, ClientRow | undefined>\n pendingWrites: number\n }\n | { state: 'locked' }\n | { state: 'unavailable' }\n\nconst OWNER_STORE = 'owner'\nconst OWNER_KEY = 'owner'\nconst CLIENT_METADATA_STORE = 'clientMetadata'\nconst MUTATIONS_STORE = 'mutations'\n\n/**\n * Reads the lease, the rows for `clientIds` (plus the holder's), and the\n * pending-write count in one `readonly` transaction. Gives up when the\n * transaction cannot start within `timeoutMs`: a store another tab holds is\n * the AGL-3428 wedge, which `firestore-multitab-wedge.ts` handles.\n */\nexport async function readLease(\n factory: IDBFactory | undefined,\n databaseName: string,\n clientIds: string[],\n { timeoutMs = READ_TIMEOUT_MS }: { timeoutMs?: number } = {},\n): Promise<LeaseRead> {\n if (!factory) return { state: 'unavailable' }\n const database = await openExisting(factory, databaseName).catch(\n () => undefined,\n )\n if (!database) return { state: 'unavailable' }\n const stores = [OWNER_STORE, CLIENT_METADATA_STORE, MUTATIONS_STORE]\n if (!stores.every((store) => database.objectStoreNames.contains(store))) {\n database.close()\n return { state: 'unavailable' }\n }\n return new Promise<LeaseRead>((resolve) => {\n let transaction: IDBTransaction\n try {\n transaction = database.transaction(stores, 'readonly')\n } catch {\n database.close()\n resolve({ state: 'unavailable' })\n return\n }\n let settled = false\n let started = false\n let result: LeaseRead = { state: 'unavailable' }\n const finish = (value: LeaseRead) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n database.close()\n resolve(value)\n }\n const timer = setTimeout(() => {\n if (started) return\n try {\n transaction.abort()\n } catch {\n // Already finished.\n }\n finish({ state: 'locked' })\n }, timeoutMs)\n transaction.oncomplete = () => finish(result)\n transaction.onabort = () =>\n finish(started ? { state: 'unavailable' } : { state: 'locked' })\n transaction.onerror = () => finish({ state: 'unavailable' })\n\n const clients = transaction.objectStore(CLIENT_METADATA_STORE)\n const ownerRequest = transaction.objectStore(OWNER_STORE).get(OWNER_KEY)\n ownerRequest.onsuccess = () => {\n started = true\n const owner = ownerRequest.result as LeaseRow | undefined\n const ids = [...new Set([...clientIds, owner?.ownerId].filter(Boolean))]\n const requests = ids.map((id) => [id, clients.get(id!)] as const)\n const countRequest = transaction.objectStore(MUTATIONS_STORE).count()\n countRequest.onsuccess = () => {\n // Requests in one transaction complete in order: every get landed.\n const rows: Record<string, ClientRow | undefined> = {}\n for (const [id, request] of requests)\n rows[id!] = request.result as ClientRow | undefined\n result = {\n state: 'read',\n owner,\n rows,\n pendingWrites: countRequest.result,\n }\n }\n }\n })\n}\n\n/** What one look or one message did, for the debug log and the specs. */\nexport type YieldEvent =\n | { side: 'asker'; result: 'asked'; holderId: string }\n | {\n side: 'asker'\n result: 'skipped'\n reason: AskSkip | 'locked' | 'unavailable' | 'throttled'\n }\n | { side: 'asker'; result: 'took-over'; fromId: string }\n | { side: 'holder'; result: 'yielded'; askerId: string }\n | {\n side: 'holder'\n result: 'skipped'\n reason:\n | YieldSkip\n | 'visible'\n | 'offline'\n | 'locked'\n | 'unavailable'\n | 'throttled'\n }\n | { side: 'holder' | 'asker'; result: 'error' }\n\nexport interface PrimaryYieldDeps {\n selfId: string\n isVisible: () => boolean\n isOnline: () => boolean\n now: () => number\n read: (clientIds: string[]) => Promise<LeaseRead>\n post: (message: YieldMessage) => void\n /** `disableNetwork` then `enableNetwork`: two elections, at once. */\n cycleNetwork: () => Promise<void>\n onEvent?: (event: YieldEvent) => void\n}\n\n/**\n * Both halves of the handoff for one tab, with the browser parts injected.\n * Neither method ever rejects.\n */\nexport function createPrimaryYield(deps: PrimaryYieldDeps) {\n let lastAskAt = Number.NEGATIVE_INFINITY\n let lastYieldAt = Number.NEGATIVE_INFINITY\n let busy = false\n // Looks can overlap (a boot look, the dwell look and the recheck): only\n // one reads at a time, so the throttle sees the ask the first one made.\n let looking = false\n const emit = (event: YieldEvent) => {\n deps.onEvent?.(event)\n return event\n }\n\n /** A visible tab's look: ask the holder to yield when it should. */\n async function check(): Promise<YieldEvent> {\n try {\n if (!deps.isVisible() || !deps.isOnline())\n return emit({\n side: 'asker',\n result: 'skipped',\n reason: 'self-not-ready',\n })\n if (looking || deps.now() - lastAskAt < ASK_INTERVAL_MS)\n return emit({ side: 'asker', result: 'skipped', reason: 'throttled' })\n looking = true\n try {\n return await look()\n } finally {\n looking = false\n }\n } catch {\n return emit({ side: 'asker', result: 'error' })\n }\n }\n\n /** One read and, when it says so, one ask. */\n async function look(): Promise<YieldEvent> {\n const read = await deps.read([deps.selfId])\n if (read.state !== 'read')\n return emit({ side: 'asker', result: 'skipped', reason: read.state })\n const decision = decideAsk({\n owner: read.owner,\n holder: read.owner ? read.rows[read.owner.ownerId] : undefined,\n self: read.rows[deps.selfId],\n selfId: deps.selfId,\n now: deps.now(),\n })\n if ('reason' in decision)\n return emit({ side: 'asker', result: 'skipped', reason: decision.reason })\n // Hidden or offline since the read: the SDK would not hand to us.\n if (!deps.isVisible() || !deps.isOnline())\n return emit({\n side: 'asker',\n result: 'skipped',\n reason: 'self-not-ready',\n })\n lastAskAt = deps.now()\n deps.post({\n type: 'yield',\n holderId: decision.holderId,\n askerId: deps.selfId,\n })\n return emit({ side: 'asker', result: 'asked', holderId: decision.holderId })\n }\n\n /** Both sides' message handler. */\n async function receive(message: unknown): Promise<YieldEvent | undefined> {\n if (!message || typeof message !== 'object') return undefined\n const { type, holderId, askerId } = message as Partial<YieldMessage>\n if (typeof holderId !== 'string' || typeof askerId !== 'string')\n return undefined\n try {\n if (type === 'yielded' && askerId === deps.selfId) {\n // The holder let go: run our election now, not on the next tick.\n if (!deps.isVisible() || !deps.isOnline()) return undefined\n await deps.cycleNetwork()\n return emit({ side: 'asker', result: 'took-over', fromId: holderId })\n }\n if (type !== 'yield' || holderId !== deps.selfId) return undefined\n if (deps.isVisible())\n return emit({ side: 'holder', result: 'skipped', reason: 'visible' })\n if (!deps.isOnline())\n return emit({ side: 'holder', result: 'skipped', reason: 'offline' })\n if (busy || deps.now() - lastYieldAt < YIELD_INTERVAL_MS)\n return emit({ side: 'holder', result: 'skipped', reason: 'throttled' })\n busy = true\n try {\n const read = await deps.read([askerId])\n if (read.state !== 'read')\n return emit({ side: 'holder', result: 'skipped', reason: read.state })\n const decision = decideYield({\n owner: read.owner,\n asker: read.rows[askerId],\n selfId: deps.selfId,\n pendingWrites: read.pendingWrites,\n now: deps.now(),\n })\n if ('reason' in decision)\n return emit({\n side: 'holder',\n result: 'skipped',\n reason: decision.reason,\n })\n // Shown again while we read: keep the role, the user is here now.\n if (deps.isVisible())\n return emit({ side: 'holder', result: 'skipped', reason: 'visible' })\n lastYieldAt = deps.now()\n await deps.cycleNetwork()\n deps.post({ type: 'yielded', holderId: deps.selfId, askerId })\n return emit({ side: 'holder', result: 'yielded', askerId })\n } finally {\n busy = false\n }\n } catch {\n return emit({\n side: type === 'yielded' ? 'asker' : 'holder',\n result: 'error',\n })\n }\n }\n\n return { check, receive }\n}\n\n/** What started, for the specs. */\nexport type PrimaryYieldStart =\n | { started: true; selfId: string }\n | { started: false; reason: 'no-channel' | 'unidentified' | 'error' }\n\nexport interface PrimaryYieldBrowser {\n /** Synchronous: the first call is the snapshot before this client starts. */\n readClientIds: () => ReadonlySet<string>\n startClient: () => Promise<void>\n openChannel: () =>\n | {\n post: (message: YieldMessage) => void\n listen: (handler: (message: unknown) => void) => void\n }\n | undefined\n onVisible: (handler: () => void) => void\n setTimer: (handler: () => void, ms: number) => void\n setRepeating: (handler: () => void, ms: number) => void\n factory: Omit<PrimaryYieldDeps, 'selfId' | 'post'>\n}\n\n/**\n * Identifies this tab's client, then wires the asker's looks and the\n * holder's handler. Never rejects.\n */\nexport async function runPrimaryYield(\n browser: PrimaryYieldBrowser,\n): Promise<PrimaryYieldStart> {\n try {\n // Before this tab's Firestore starts, or this tab would be in it.\n const before = browser.readClientIds()\n const channel = browser.openChannel()\n if (!channel) return { started: false, reason: 'no-channel' }\n await browser.startClient()\n const added = [...browser.readClientIds()].filter((id) => !before.has(id))\n // Exactly one new client is this tab; anything else cannot be told apart.\n if (added.length !== 1) return { started: false, reason: 'unidentified' }\n const selfId = added[0]\n const handoff = createPrimaryYield({\n ...browser.factory,\n selfId,\n post: channel.post,\n })\n channel.listen((message) => void handoff.receive(message))\n for (const delay of BOOT_CHECK_DELAYS_MS)\n browser.setTimer(() => {\n if (browser.factory.isVisible()) void handoff.check()\n }, delay)\n browser.onVisible(() =>\n browser.setTimer(() => {\n if (browser.factory.isVisible()) void handoff.check()\n }, VISIBLE_DWELL_MS),\n )\n browser.setRepeating(() => {\n if (browser.factory.isVisible()) void handoff.check()\n }, RECHECK_MS)\n return { started: true, selfId }\n } catch {\n return { started: false, reason: 'error' }\n }\n}\n\n/**\n * Starts the handoff for a Firestore that `initializeFirestore` has just\n * configured with the durable multi-tab cache under `prefix`. Call it in the\n * same task as `initializeFirestore`, before any read: its first step is the\n * synchronous snapshot of the clients that are not this tab.\n */\nexport function startFirestorePrimaryYield(\n firestore: Firestore,\n prefix: string,\n): Promise<PrimaryYieldStart> {\n if (typeof window === 'undefined')\n return Promise.resolve({ started: false, reason: 'no-channel' })\n let storage: Storage | undefined\n let factory: IDBFactory | undefined\n try {\n storage = window.localStorage\n factory = window.indexedDB\n } catch {\n // Site data blocked: the snapshot reads nothing and nothing starts.\n }\n const databaseName = `${prefix}main`\n const isVisible = () => document.visibilityState === 'visible'\n return runPrimaryYield({\n readClientIds: () => readSharedClientIds(storage, prefix),\n startClient: () => enableNetwork(firestore),\n openChannel: () => {\n if (typeof BroadcastChannel !== 'function') return undefined\n const channel = new BroadcastChannel(`aglyn:firestore-primary:${prefix}`)\n return {\n post: (message) => channel.postMessage(message),\n listen: (handler) => {\n channel.onmessage = (event) => handler(event.data)\n },\n }\n },\n onVisible: (handler) =>\n document.addEventListener('visibilitychange', () => {\n if (isVisible()) handler()\n }),\n setTimer: (handler, ms) => void setTimeout(handler, ms),\n setRepeating: (handler, ms) => void setInterval(handler, ms),\n factory: {\n isVisible,\n isOnline: () => navigator.onLine !== false,\n now: Date.now,\n read: (clientIds) => readLease(factory, databaseName, clientIds),\n cycleNetwork: async () => {\n await disableNetwork(firestore)\n await enableNetwork(firestore)\n },\n onEvent: (event) => {\n if (event.result === 'yielded' || event.result === 'took-over')\n console.debug(\n '[firestore] Moved the shared cache to the visible tab (AGL-4204).',\n event,\n )\n },\n },\n })\n}\n"],"names":["disableNetwork","enableNetwork","openExisting","PRIMARY_LEASE_MAX_AGE_MS","readSharedClientIds","VISIBLE_DWELL_MS","RECHECK_MS","BOOT_CHECK_DELAYS_MS","ASK_INTERVAL_MS","YIELD_INTERVAL_MS","ASKER_FRESH_MS","READ_TIMEOUT_MS","decideAsk","input","owner","holder","self","selfId","now","ask","reason","ownerId","leaseTimestampMs","inForeground","networkEnabled","holderId","decideYield","asker","pendingWrites","yield","updateTimeMs","OWNER_STORE","OWNER_KEY","CLIENT_METADATA_STORE","MUTATIONS_STORE","readLease","factory","databaseName","clientIds","timeoutMs","state","database","catch","undefined","stores","every","store","objectStoreNames","contains","close","Promise","resolve","transaction","settled","started","result","finish","value","clearTimeout","timer","setTimeout","abort","oncomplete","onabort","onerror","clients","objectStore","ownerRequest","get","onsuccess","ids","Set","filter","Boolean","requests","map","id","countRequest","count","rows","request","createPrimaryYield","deps","lastAskAt","Number","NEGATIVE_INFINITY","lastYieldAt","busy","looking","emit","event","onEvent","check","isVisible","isOnline","side","look","read","decision","post","type","askerId","receive","message","cycleNetwork","fromId","runPrimaryYield","browser","before","readClientIds","channel","openChannel","startClient","added","has","length","handoff","listen","delay","setTimer","onVisible","setRepeating","startFirestorePrimaryYield","firestore","prefix","window","storage","localStorage","indexedDB","document","visibilityState","BroadcastChannel","postMessage","handler","onmessage","data","addEventListener","ms","setInterval","navigator","onLine","Date","console","debug"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,cAAc,EACdC,aAAa,QAER,qBAAoB;AAC3B,SAGEC,YAAY,EACZC,wBAAwB,EACxBC,mBAAmB,QACd,6BAAyB;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkEC,GAED,kEAAkE,GAClE,OAAO,MAAMC,mBAAmB,KAAK;AAErC,gEAAgE,GAChE,OAAO,MAAMC,aAAa,MAAM;AAEhC;;;;;;;CAOC,GACD,OAAO,MAAMC,uBAAuB;IAAC;IAAO;IAAO;CAAM,CAAS;AAElE,gDAAgD,GAChD,OAAO,MAAMC,kBAAkB,MAAM;AAErC,kDAAkD,GAClD,OAAO,MAAMC,oBAAoB,MAAM;AAEvC;;;;CAIC,GACD,OAAO,MAAMC,iBAAiB,KAAK;AAEnC,kEAAkE,GAClE,OA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O,IAAI,CAAC;IACpC,MAAM/B,YAAY,IAAMoC,SAASC,eAAe,KAAK;IACrD,OAAOxB,gBAAgB;QACrBG,eAAe,IAAMzG,oBAAoB0H,SAASF;QAClDZ,aAAa,IAAM/G,cAAc0H;QACjCZ,aAAa;YACX,IAAI,OAAOoB,qBAAqB,YAAY,OAAOxF;YACnD,MAAMmE,UAAU,IAAIqB,iBAAiB,CAAC,wBAAwB,EAAEP,QAAQ;YACxE,OAAO;gBACLzB,MAAM,CAACI,UAAYO,QAAQsB,WAAW,CAAC7B;gBACvCc,QAAQ,CAACgB;oBACPvB,QAAQwB,SAAS,GAAG,CAAC5C,QAAU2C,QAAQ3C,MAAM6C,IAAI;gBACnD;YACF;QACF;QACAf,WAAW,CAACa,UACVJ,SAASO,gBAAgB,CAAC,oBAAoB;gBAC5C,IAAI3C,aAAawC;YACnB;QACFd,UAAU,CAACc,SAASI,KAAO,KAAK7E,WAAWyE,SAASI;QACpDhB,cAAc,CAACY,SAASI,KAAO,KAAKC,YAAYL,SAASI;QACzDrG,SAAS;YACPyD;YACAC,UAAU,IAAM6C,UAAUC,MAAM,KAAK;YACrC1H,KAAK2H,KAAK3H,GAAG;YACb+E,MAAM,CAAC3D,YAAcH,UAAUC,SAASC,cAAcC;YACtDkE,cAAc;gBACZ,MAAMxG,eAAe2H;gBACrB,MAAM1H,cAAc0H;YACtB;YACAhC,SAAS,CAACD;gBACR,IAAIA,MAAMnC,MAAM,KAAK,aAAamC,MAAMnC,MAAM,KAAK,aACjDuF,QAAQC,KAAK,CACX,qEACArD;YAEN;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-primary-yield.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n disableNetwork,\n enableNetwork,\n type Firestore,\n} from 'firebase/firestore'\nimport {\n type ClientRow,\n type LeaseRow,\n openExisting,\n PRIMARY_LEASE_MAX_AGE_MS,\n readSharedClientIds,\n} from './firestore-tab-handoff'\n\n/**\n * A BACKGROUND TAB HANDS THE SHARED CACHE TO THE TAB THE USER IS LOOKING AT\n * (AGL-4204).\n *\n * ## What it fixes\n *\n * With `persistentMultipleTabManager` one tab, the lease holder, does every\n * tab's network and most of their IndexedDB work, and every SDK transaction\n * locks every store. The SDK never moves a LIVE lease\n * (`IndexedDbPersistence.canActAsPrimary`, `@firebase/firestore` 4.18.0):\n * a holder whose lease is under 5 s old and whose network is on keeps it\n * whatever its visibility, and a visible tab wins only on a lapse. A console\n * tab left in the background therefore serves the tab the user is in for as\n * long as it keeps renewing, from a renderer the browser runs at background\n * priority. Measured in production on 2026-11-06: reads in other tabs waited\n * 16.9 s, 18.9 s and 4.5 s behind a background holder within three minutes,\n * and a lease went 23.7 s stale. The cache's size never moved in those\n * stalls, so they were not LRU collection.\n *\n * `firestore-tab-handoff.ts` (AGL-3660) claims a LAPSED lease for a new\n * visible tab at boot. It cannot take a live one: two primaries over one\n * cache write tombstones (AGL-3788). This module covers the live case by\n * having the HOLDER let go, through the SDK's own election.\n *\n * ## How\n *\n * - **The asker** (a visible, online tab on the durable multi-tab cache) reads\n * the lease and the holder's row, read-only. When the lease is live, held\n * by another tab, and that tab's own row says it is in the background, it\n * posts `yield` on a `BroadcastChannel` named for this cache. It looks\n * as soon as its client has started and five more times in its first 10 s\n * ({@link BOOT_CHECK_DELAYS_MS}), once it has been visible for\n * {@link VISIBLE_DWELL_MS}, and every {@link RECHECK_MS} while it stays\n * visible. When its own row still says hidden (the SDK writes a new tab's\n * first row that way), it cycles its own network first, which rewrites\n * the row from the visibility the SDK has read by then, instead of waiting\n * for the SDK's 4 s tick.\n * - **The holder** knows its own client id (the one `firestore_clients_*` key\n * that appeared while its client started, as in AGL-3660). On a `yield`\n * naming it, while it is hidden and online, it rereads in one transaction:\n * still the holder; the asker's row fresh, foreground and online; no write\n * pending. Then `disableNetwork` → `enableNetwork`. With its network off,\n * the SDK's election finds the asker a better candidate\n * (`otherClientHasBetterNetworkState`) and releases the lease, after the\n * disable has stopped its Watch and write streams, because the election\n * is queued behind the disable. Re-enabled, it finds the lease vacant and\n * a foreground candidate, so it stays secondary. It replies `yielded`.\n * - **The asker** then cycles its own network. That cycle is invisible in a\n * secondary (`syncEngineApplyOnlineStateChange` ignores its own remote\n * store there), and the election it runs takes the vacant lease at once\n * instead of on its next 4 s tick.\n *\n * ## Why it is safe\n *\n * - **Never two primaries.** The lease is only ever released by its holder\n * and only ever taken vacant, both by the SDK's own code. Nothing here\n * writes a lease.\n * - **Never with a write in flight.** A new primary resends every\n * unacknowledged batch, so the holder declines while `mutations` has a row,\n * the same rule AGL-3660 follows.\n * - **Never on a guess.** A tab that cannot tell which client it is (two tabs\n * started together) never acts as holder. The asker's row must be younger\n * than {@link ASKER_FRESH_MS}, or the SDK would not hand to it and the\n * holder's cycle would only flicker its network.\n * - **Rate-limited both ways**: up to {@link ASK_BURST} asks\n * {@link ASK_RETRY_MS} apart (an ask a background holder never answered,\n * or answered while the asker's row was not yet fresh, is asked again),\n * then one per {@link ASK_INTERVAL_MS}; one yield per\n * {@link YIELD_INTERVAL_MS}. Switching between two console tabs moves the\n * role at most that often.\n * - **Every failure is the old behaviour.** No `BroadcastChannel`, no\n * database, a store another tab has locked, any throw: nothing is posted\n * or cycled, and the SDK's election runs as it always has.\n */\n\n/** How long a tab must stay visible before it asks for the role. */\nexport const VISIBLE_DWELL_MS = 3_000\n\n/** How often a visible tab looks again while it stays visible. */\nexport const RECHECK_MS = 15_000\n\n/**\n * The looks after this tab's client has started. The first is immediate: a\n * background holder costs a cold load 10-16 s (measured in production on\n * 2026-11-10), and the first looks at 2, 5 and 9 s it replaced asked only\n * on the third. The SDK writes a new tab's first row as hidden (see\n * `firestore-tab-handoff.ts`), so a look that finds its own row not ready\n * rewrites it with a network cycle ({@link REFRESH_INTERVAL_MS}) and asks\n * once the rewrite has landed: in the same look, or in the next one a\n * second later. The later looks cover a read that found the store\n * locked and an ask the holder did not act on. Each is a no-op once the role\n * has moved here.\n */\nexport const BOOT_CHECK_DELAYS_MS = [\n 0, 1_000, 2_500, 4_500, 7_000, 10_000,\n] as const\n\n/** An unanswered ask may be repeated this soon, up to {@link ASK_BURST}. */\nexport const ASK_RETRY_MS = 3_000\n\n/** Asks allowed {@link ASK_RETRY_MS} apart before the long interval. */\nexport const ASK_BURST = 3\n\n/** After a burst, at most one ask per this long from one tab. */\nexport const ASK_INTERVAL_MS = 15_000\n\n/**\n * At most one rewrite of this tab's own row per this long: the SDK's own\n * renewal tick, after which it would have rewritten the row anyway.\n */\nexport const REFRESH_INTERVAL_MS = 4_000\n\n/** At most one yield per this long from one tab. */\nexport const YIELD_INTERVAL_MS = 30_000\n\n/**\n * The asker's row must be at least this fresh. The SDK only hands the lease\n * to a client renewed within `MAX_PRIMARY_ELIGIBLE_AGE_MS` (5 s); a visible\n * tab renews every 4 s.\n */\nexport const ASKER_FRESH_MS = 4_500\n\n/** How long a read may wait to start before it counts as locked. */\nexport const READ_TIMEOUT_MS = 1_500\n\nexport type YieldMessage =\n | { type: 'yield'; holderId: string; askerId: string }\n | { type: 'yielded'; holderId: string; askerId: string }\n\n/** Why a visible tab did not ask. */\nexport type AskSkip =\n | 'vacant'\n | 'self-holds'\n | 'holder-unknown'\n | 'holder-visible'\n | 'lease-lapsed'\n | 'self-unknown'\n | 'self-not-ready'\n\nexport type AskDecision =\n { ask: true; holderId: string } | { ask: false; reason: AskSkip }\n\n/**\n * Whether the tab `selfId` should ask the holder to yield. Pure.\n *\n * A lapsed lease is left alone: the SDK's next election in a visible tab\n * takes it, and AGL-3660 claims it at boot.\n */\nexport function decideAsk(input: {\n owner: LeaseRow | undefined\n holder: ClientRow | undefined\n self: ClientRow | undefined\n selfId: string\n now: number\n}): AskDecision {\n const { owner, holder, self, selfId, now } = input\n if (!owner) return { ask: false, reason: 'vacant' }\n if (owner.ownerId === selfId) return { ask: false, reason: 'self-holds' }\n if (now - owner.leaseTimestampMs >= PRIMARY_LEASE_MAX_AGE_MS)\n return { ask: false, reason: 'lease-lapsed' }\n if (!holder) return { ask: false, reason: 'holder-unknown' }\n if (holder.inForeground) return { ask: false, reason: 'holder-visible' }\n if (!self) return { ask: false, reason: 'self-unknown' }\n // The SDK hands only to a client that has recorded itself foreground and\n // online; the first record a new tab writes says hidden (AGL-3660).\n if (!self.inForeground || !self.networkEnabled)\n return { ask: false, reason: 'self-not-ready' }\n return { ask: true, holderId: owner.ownerId }\n}\n\n/** Why the holder did not yield. */\nexport type YieldSkip =\n | 'not-holder'\n | 'asker-unknown'\n | 'asker-stale'\n | 'asker-hidden'\n | 'asker-offline'\n | 'pending-writes'\n\nexport type YieldDecision =\n { yield: true } | { yield: false; reason: YieldSkip }\n\n/** Whether the holder `selfId` should let go for `asker`. Pure. */\nexport function decideYield(input: {\n owner: LeaseRow | undefined\n asker: ClientRow | undefined\n selfId: string\n pendingWrites: number\n now: number\n}): YieldDecision {\n const { owner, asker, selfId, pendingWrites, now } = input\n if (owner?.ownerId !== selfId) return { yield: false, reason: 'not-holder' }\n if (pendingWrites > 0) return { yield: false, reason: 'pending-writes' }\n if (!asker) return { yield: false, reason: 'asker-unknown' }\n if (!asker.inForeground) return { yield: false, reason: 'asker-hidden' }\n if (!asker.networkEnabled) return { yield: false, reason: 'asker-offline' }\n if (now - asker.updateTimeMs > ASKER_FRESH_MS)\n return { yield: false, reason: 'asker-stale' }\n return { yield: true }\n}\n\n/** One read-only look at the lease, two client rows and the write queue. */\nexport type LeaseRead =\n | {\n state: 'read'\n owner: LeaseRow | undefined\n rows: Record<string, ClientRow | undefined>\n pendingWrites: number\n }\n | { state: 'locked' }\n | { state: 'unavailable' }\n\nconst OWNER_STORE = 'owner'\nconst OWNER_KEY = 'owner'\nconst CLIENT_METADATA_STORE = 'clientMetadata'\nconst MUTATIONS_STORE = 'mutations'\n\n/**\n * Reads the lease, the rows for `clientIds` (plus the holder's), and the\n * pending-write count in one `readonly` transaction. Gives up when the\n * transaction cannot start within `timeoutMs`: a store another tab holds is\n * the AGL-3428 wedge, which `firestore-multitab-wedge.ts` handles.\n */\nexport async function readLease(\n factory: IDBFactory | undefined,\n databaseName: string,\n clientIds: string[],\n { timeoutMs = READ_TIMEOUT_MS }: { timeoutMs?: number } = {},\n): Promise<LeaseRead> {\n if (!factory) return { state: 'unavailable' }\n const database = await openExisting(factory, databaseName).catch(\n () => undefined,\n )\n if (!database) return { state: 'unavailable' }\n const stores = [OWNER_STORE, CLIENT_METADATA_STORE, MUTATIONS_STORE]\n if (!stores.every((store) => database.objectStoreNames.contains(store))) {\n database.close()\n return { state: 'unavailable' }\n }\n return new Promise<LeaseRead>((resolve) => {\n let transaction: IDBTransaction\n try {\n transaction = database.transaction(stores, 'readonly')\n } catch {\n database.close()\n resolve({ state: 'unavailable' })\n return\n }\n let settled = false\n let started = false\n let result: LeaseRead = { state: 'unavailable' }\n const finish = (value: LeaseRead) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n database.close()\n resolve(value)\n }\n const timer = setTimeout(() => {\n if (started) return\n try {\n transaction.abort()\n } catch {\n // Already finished.\n }\n finish({ state: 'locked' })\n }, timeoutMs)\n transaction.oncomplete = () => finish(result)\n transaction.onabort = () =>\n finish(started ? { state: 'unavailable' } : { state: 'locked' })\n transaction.onerror = () => finish({ state: 'unavailable' })\n\n const clients = transaction.objectStore(CLIENT_METADATA_STORE)\n const ownerRequest = transaction.objectStore(OWNER_STORE).get(OWNER_KEY)\n ownerRequest.onsuccess = () => {\n started = true\n const owner = ownerRequest.result as LeaseRow | undefined\n const ids = [...new Set([...clientIds, owner?.ownerId].filter(Boolean))]\n const requests = ids.map((id) => [id, clients.get(id!)] as const)\n const countRequest = transaction.objectStore(MUTATIONS_STORE).count()\n countRequest.onsuccess = () => {\n // Requests in one transaction complete in order: every get landed.\n const rows: Record<string, ClientRow | undefined> = {}\n for (const [id, request] of requests)\n rows[id!] = request.result as ClientRow | undefined\n result = {\n state: 'read',\n owner,\n rows,\n pendingWrites: countRequest.result,\n }\n }\n }\n })\n}\n\n/** What one look or one message did, for the debug log and the specs. */\nexport type YieldEvent =\n | { side: 'asker'; result: 'asked'; holderId: string }\n | {\n side: 'asker'\n result: 'skipped'\n reason: AskSkip | 'locked' | 'unavailable' | 'throttled'\n }\n | { side: 'asker'; result: 'took-over'; fromId: string }\n | { side: 'asker'; result: 'refreshed' }\n | { side: 'holder'; result: 'yielded'; askerId: string }\n | {\n side: 'holder'\n result: 'skipped'\n reason:\n | YieldSkip\n | 'visible'\n | 'offline'\n | 'locked'\n | 'unavailable'\n | 'throttled'\n }\n | { side: 'holder' | 'asker'; result: 'error' }\n\nexport interface PrimaryYieldDeps {\n selfId: string\n isVisible: () => boolean\n isOnline: () => boolean\n now: () => number\n read: (clientIds: string[]) => Promise<LeaseRead>\n post: (message: YieldMessage) => void\n /** `disableNetwork` then `enableNetwork`: two elections, at once. */\n cycleNetwork: () => Promise<void>\n onEvent?: (event: YieldEvent) => void\n}\n\n/**\n * Both halves of the handoff for one tab, with the browser parts injected.\n * Neither method ever rejects.\n */\nexport function createPrimaryYield(deps: PrimaryYieldDeps) {\n let lastAskAt = Number.NEGATIVE_INFINITY\n let asksInBurst = 0\n let lastRefreshAt = Number.NEGATIVE_INFINITY\n let lastYieldAt = Number.NEGATIVE_INFINITY\n let busy = false\n // Looks can overlap (a boot look, the dwell look and the recheck): only\n // one reads at a time, so the throttle sees the ask the first one made.\n let looking = false\n const emit = (event: YieldEvent) => {\n deps.onEvent?.(event)\n return event\n }\n\n /** A visible tab's look: ask the holder to yield when it should. */\n async function check(): Promise<YieldEvent> {\n try {\n if (!deps.isVisible() || !deps.isOnline())\n return emit({\n side: 'asker',\n result: 'skipped',\n reason: 'self-not-ready',\n })\n if (looking || !mayAsk())\n return emit({ side: 'asker', result: 'skipped', reason: 'throttled' })\n looking = true\n try {\n return await look()\n } finally {\n looking = false\n }\n } catch {\n return emit({ side: 'asker', result: 'error' })\n }\n }\n\n /** A short burst of asks, then the long interval. */\n function mayAsk(): boolean {\n const since = deps.now() - lastAskAt\n if (since >= ASK_INTERVAL_MS) return true\n return since >= ASK_RETRY_MS && asksInBurst < ASK_BURST\n }\n\n /** One read, and the decision it supports. */\n async function decide(): Promise<\n | { read: Extract<LeaseRead, { state: 'read' }>; decision: AskDecision }\n | { skipped: 'locked' | 'unavailable' }\n > {\n const read = await deps.read([deps.selfId])\n if (read.state !== 'read') return { skipped: read.state }\n const decision = decideAsk({\n owner: read.owner,\n holder: read.owner ? read.rows[read.owner.ownerId] : undefined,\n self: read.rows[deps.selfId],\n selfId: deps.selfId,\n now: deps.now(),\n })\n return { read, decision }\n }\n\n /** One read and, when it says so, one ask. */\n async function look(): Promise<YieldEvent> {\n let looked = await decide()\n if ('skipped' in looked)\n return emit({ side: 'asker', result: 'skipped', reason: looked.skipped })\n // Visible and online, but the row the holder will read says otherwise:\n // the SDK wrote it before it read the visibility. A network cycle runs\n // its election, which rewrites the row; a secondary's cycle touches no\n // stream. The SDK queues that election behind the cycle, so this second\n // read usually sees it and sometimes does not; the next boot look, a\n // second later, does.\n if (\n 'reason' in looked.decision &&\n looked.decision.reason === 'self-not-ready' &&\n deps.isVisible() &&\n deps.isOnline() &&\n deps.now() - lastRefreshAt >= REFRESH_INTERVAL_MS\n ) {\n lastRefreshAt = deps.now()\n await deps.cycleNetwork()\n emit({ side: 'asker', result: 'refreshed' })\n looked = await decide()\n if ('skipped' in looked)\n return emit({\n side: 'asker',\n result: 'skipped',\n reason: looked.skipped,\n })\n }\n const { decision } = looked\n if ('reason' in decision)\n return emit({ side: 'asker', result: 'skipped', reason: decision.reason })\n // Hidden or offline since the read: the SDK would not hand to us.\n if (!deps.isVisible() || !deps.isOnline())\n return emit({\n side: 'asker',\n result: 'skipped',\n reason: 'self-not-ready',\n })\n asksInBurst =\n deps.now() - lastAskAt >= ASK_INTERVAL_MS ? 1 : asksInBurst + 1\n lastAskAt = deps.now()\n deps.post({\n type: 'yield',\n holderId: decision.holderId,\n askerId: deps.selfId,\n })\n return emit({ side: 'asker', result: 'asked', holderId: decision.holderId })\n }\n\n /** Both sides' message handler. */\n async function receive(message: unknown): Promise<YieldEvent | undefined> {\n if (!message || typeof message !== 'object') return undefined\n const { type, holderId, askerId } = message as Partial<YieldMessage>\n if (typeof holderId !== 'string' || typeof askerId !== 'string')\n return undefined\n try {\n if (type === 'yielded' && askerId === deps.selfId) {\n // The holder let go: run our election now, not on the next tick.\n if (!deps.isVisible() || !deps.isOnline()) return undefined\n await deps.cycleNetwork()\n return emit({ side: 'asker', result: 'took-over', fromId: holderId })\n }\n if (type !== 'yield' || holderId !== deps.selfId) return undefined\n if (deps.isVisible())\n return emit({ side: 'holder', result: 'skipped', reason: 'visible' })\n if (!deps.isOnline())\n return emit({ side: 'holder', result: 'skipped', reason: 'offline' })\n if (busy || deps.now() - lastYieldAt < YIELD_INTERVAL_MS)\n return emit({ side: 'holder', result: 'skipped', reason: 'throttled' })\n busy = true\n try {\n const read = await deps.read([askerId])\n if (read.state !== 'read')\n return emit({ side: 'holder', result: 'skipped', reason: read.state })\n const decision = decideYield({\n owner: read.owner,\n asker: read.rows[askerId],\n selfId: deps.selfId,\n pendingWrites: read.pendingWrites,\n now: deps.now(),\n })\n if ('reason' in decision)\n return emit({\n side: 'holder',\n result: 'skipped',\n reason: decision.reason,\n })\n // Shown again while we read: keep the role, the user is here now.\n if (deps.isVisible())\n return emit({ side: 'holder', result: 'skipped', reason: 'visible' })\n lastYieldAt = deps.now()\n await deps.cycleNetwork()\n deps.post({ type: 'yielded', holderId: deps.selfId, askerId })\n return emit({ side: 'holder', result: 'yielded', askerId })\n } finally {\n busy = false\n }\n } catch {\n return emit({\n side: type === 'yielded' ? 'asker' : 'holder',\n result: 'error',\n })\n }\n }\n\n return { check, receive }\n}\n\n/** What started, for the specs. */\nexport type PrimaryYieldStart =\n | { started: true; selfId: string }\n | { started: false; reason: 'no-channel' | 'unidentified' | 'error' }\n\nexport interface PrimaryYieldBrowser {\n /** Synchronous: the first call is the snapshot before this client starts. */\n readClientIds: () => ReadonlySet<string>\n startClient: () => Promise<void>\n openChannel: () =>\n | {\n post: (message: YieldMessage) => void\n listen: (handler: (message: unknown) => void) => void\n }\n | undefined\n onVisible: (handler: () => void) => void\n setTimer: (handler: () => void, ms: number) => void\n setRepeating: (handler: () => void, ms: number) => void\n factory: Omit<PrimaryYieldDeps, 'selfId' | 'post'>\n}\n\n/**\n * Identifies this tab's client, then wires the asker's looks and the\n * holder's handler. Never rejects.\n */\nexport async function runPrimaryYield(\n browser: PrimaryYieldBrowser,\n): Promise<PrimaryYieldStart> {\n try {\n // Before this tab's Firestore starts, or this tab would be in it.\n const before = browser.readClientIds()\n const channel = browser.openChannel()\n if (!channel) return { started: false, reason: 'no-channel' }\n await browser.startClient()\n const added = [...browser.readClientIds()].filter((id) => !before.has(id))\n // Exactly one new client is this tab; anything else cannot be told apart.\n if (added.length !== 1) return { started: false, reason: 'unidentified' }\n const selfId = added[0]\n const handoff = createPrimaryYield({\n ...browser.factory,\n selfId,\n post: channel.post,\n })\n channel.listen((message) => void handoff.receive(message))\n for (const delay of BOOT_CHECK_DELAYS_MS)\n browser.setTimer(() => {\n if (browser.factory.isVisible()) void handoff.check()\n }, delay)\n browser.onVisible(() =>\n browser.setTimer(() => {\n if (browser.factory.isVisible()) void handoff.check()\n }, VISIBLE_DWELL_MS),\n )\n browser.setRepeating(() => {\n if (browser.factory.isVisible()) void handoff.check()\n }, RECHECK_MS)\n return { started: true, selfId }\n } catch {\n return { started: false, reason: 'error' }\n }\n}\n\n/**\n * Starts the handoff for a Firestore that `initializeFirestore` has just\n * configured with the durable multi-tab cache under `prefix`. Call it in the\n * same task as `initializeFirestore`, before any read: its first step is the\n * synchronous snapshot of the clients that are not this tab.\n */\nexport function startFirestorePrimaryYield(\n firestore: Firestore,\n prefix: string,\n): Promise<PrimaryYieldStart> {\n if (typeof window === 'undefined')\n return Promise.resolve({ started: false, reason: 'no-channel' })\n let storage: Storage | undefined\n let factory: IDBFactory | undefined\n try {\n storage = window.localStorage\n factory = window.indexedDB\n } catch {\n // Site data blocked: the snapshot reads nothing and nothing starts.\n }\n const databaseName = `${prefix}main`\n const isVisible = () => document.visibilityState === 'visible'\n return runPrimaryYield({\n readClientIds: () => readSharedClientIds(storage, prefix),\n startClient: () => enableNetwork(firestore),\n openChannel: () => {\n if (typeof BroadcastChannel !== 'function') return undefined\n const channel = new BroadcastChannel(`aglyn:firestore-primary:${prefix}`)\n return {\n post: (message) => channel.postMessage(message),\n listen: (handler) => {\n channel.onmessage = (event) => handler(event.data)\n },\n }\n },\n onVisible: (handler) =>\n document.addEventListener('visibilitychange', () => {\n if (isVisible()) handler()\n }),\n setTimer: (handler, ms) => void setTimeout(handler, ms),\n setRepeating: (handler, ms) => void setInterval(handler, ms),\n factory: {\n isVisible,\n isOnline: () => navigator.onLine !== false,\n now: Date.now,\n read: (clientIds) => readLease(factory, databaseName, clientIds),\n cycleNetwork: async () => {\n await disableNetwork(firestore)\n await enableNetwork(firestore)\n },\n onEvent: (event) => {\n if (event.result === 'yielded' || event.result === 'took-over')\n console.debug(\n '[firestore] Moved the shared cache to the visible tab (AGL-4204).',\n event,\n )\n },\n },\n })\n}\n"],"names":["disableNetwork","enableNetwork","openExisting","PRIMARY_LEASE_MAX_AGE_MS","readSharedClientIds","VISIBLE_DWELL_MS","RECHECK_MS","BOOT_CHECK_DELAYS_MS","ASK_RETRY_MS","ASK_BURST","ASK_INTERVAL_MS","REFRESH_INTERVAL_MS","YIELD_INTERVAL_MS","ASKER_FRESH_MS","READ_TIMEOUT_MS","decideAsk","input","owner","holder","self","selfId","now","ask","reason","ownerId","leaseTimestampMs","inForeground","networkEnabled","holderId","decideYield","asker","pendingWrites","yield","updateTimeMs","OWNER_STORE","OWNER_KEY","CLIENT_METADATA_STORE","MUTATIONS_STORE","readLease","factory","databaseName","clientIds","timeoutMs","state","database","catch","undefined","stores","every","store","objectStoreNames","contains","close","Promise","resolve","transaction","settled","started","result","finish","value","clearTimeout","timer","setTimeout","abort","oncomplete","onabort","onerror","clients","objectStore","ownerRequest","get","onsuccess","ids","Set","filter","Boolean","requests","map","id","countRequest","count","rows","request","createPrimaryYield","deps","lastAskAt","Number","NEGATIVE_INFINITY","asksInBurst","lastRefreshAt","lastYieldAt","busy","looking","emit","event","onEvent","check","isVisible","isOnline","side","mayAsk","look","since","decide","read","skipped","decision","looked","cycleNetwork","post","type","askerId","receive","message","fromId","runPrimaryYield","browser","before","readClientIds","channel","openChannel","startClient","added","has","length","handoff","listen","delay","setTimer","onVisible","setRepeating","startFirestorePrimaryYield","firestore","prefix","window","storage","localStorage","indexedDB","document","visibilityState","BroadcastChannel","postMessage","handler","onmessage","data","addEventListener","ms","setInterval","navigator","onLine","Date","console","debug"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,cAAc,EACdC,aAAa,QAER,qBAAoB;AAC3B,SAGEC,YAAY,EACZC,wBAAwB,EACxBC,mBAAmB,QACd,6BAAyB;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyEC,GAED,kEAAkE,GAClE,OAAO,MAAMC,mBAAmB,KAAK;AAErC,gEAAgE,GAChE,OAAO,MAAMC,aAAa,MAAM;AAEhC;;;;;;;;;;;CAWC,GACD,OAAO,MAAMC,uBAAuB;IAClC;IAAG;IAAO;IAAO;IAAO;IAAO;CAChC,CAAS;AAEV,0EAA0E,GAC1E,OAAO,MAAMC,eAAe,KAAK;AAEjC,sEAAsE,GACtE,OAAO,MAAMC,YAAY,EAAC;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MyC,SAASC,eAAe,KAAK;IACrD,OAAOxB,gBAAgB;QACrBG,eAAe,IAAMnH,oBAAoBoI,SAASF;QAClDZ,aAAa,IAAMzH,cAAcoI;QACjCZ,aAAa;YACX,IAAI,OAAOoB,qBAAqB,YAAY,OAAO/F;YACnD,MAAM0E,UAAU,IAAIqB,iBAAiB,CAAC,wBAAwB,EAAEP,QAAQ;YACxE,OAAO;gBACLxB,MAAM,CAACI,UAAYM,QAAQsB,WAAW,CAAC5B;gBACvCa,QAAQ,CAACgB;oBACPvB,QAAQwB,SAAS,GAAG,CAACjD,QAAUgD,QAAQhD,MAAMkD,IAAI;gBACnD;YACF;QACF;QACAf,WAAW,CAACa,UACVJ,SAASO,gBAAgB,CAAC,oBAAoB;gBAC5C,IAAIhD,aAAa6C;YACnB;QACFd,UAAU,CAACc,SAASI,KAAO,KAAKpF,WAAWgF,SAASI;QACpDhB,cAAc,CAACY,SAASI,KAAO,KAAKC,YAAYL,SAASI;QACzD5G,SAAS;YACP2D;YACAC,UAAU,IAAMkD,UAAUC,MAAM,KAAK;YACrCjI,KAAKkI,KAAKlI,GAAG;YACboF,MAAM,CAAChE,YAAcH,UAAUC,SAASC,cAAcC;YACtDoE,cAAc;gBACZ,MAAM7G,eAAeqI;gBACrB,MAAMpI,cAAcoI;YACtB;YACArC,SAAS,CAACD;gBACR,IAAIA,MAAMrC,MAAM,KAAK,aAAaqC,MAAMrC,MAAM,KAAK,aACjD8F,QAAQC,KAAK,CACX,qEACA1D;YAEN;QACF;IACF;AACF"}
|
|
@@ -244,6 +244,12 @@ export declare function noteFirestoreServerAnswer(firestore: Firestore | null |
|
|
|
244
244
|
* boot check's line between a tab still booting and one in use (AGL-4201).
|
|
245
245
|
*/
|
|
246
246
|
export declare function firestoreHasServerAnswered(firestore: Firestore | null | undefined): boolean;
|
|
247
|
+
/**
|
|
248
|
+
* When the server last confirmed anything for `firestore` in this tab, or
|
|
249
|
+
* `undefined` if it has not: the page check's line between a page still
|
|
250
|
+
* loading and one the server has reached (AGL-4204).
|
|
251
|
+
*/
|
|
252
|
+
export declare function firestoreLastServerAnswerAt(firestore: Firestore | null | undefined): number | undefined;
|
|
247
253
|
/**
|
|
248
254
|
* Recovers `firestore` if it has stalled. Safe to call from every reader
|
|
249
255
|
* that notices: the guards above collapse the calls into at most one network
|
|
@@ -276,6 +276,13 @@ const recoveries = new WeakMap();
|
|
|
276
276
|
*/ export function firestoreHasServerAnswered(firestore) {
|
|
277
277
|
return Boolean(firestore && typeof firestore === 'object' && serverAnswers.has(firestore));
|
|
278
278
|
}
|
|
279
|
+
/**
|
|
280
|
+
* When the server last confirmed anything for `firestore` in this tab, or
|
|
281
|
+
* `undefined` if it has not: the page check's line between a page still
|
|
282
|
+
* loading and one the server has reached (AGL-4204).
|
|
283
|
+
*/ export function firestoreLastServerAnswerAt(firestore) {
|
|
284
|
+
return firestore && typeof firestore === 'object' ? serverAnswers.get(firestore) : undefined;
|
|
285
|
+
}
|
|
279
286
|
/**
|
|
280
287
|
* Recovers `firestore` if it has stalled. Safe to call from every reader
|
|
281
288
|
* that notices: the guards above collapse the calls into at most one network
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-stall-recovery.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n disableNetwork,\n enableNetwork,\n type Firestore,\n} from 'firebase/firestore'\n\nimport {\n browserLeaseCheckFor,\n browserWedgeEscalationFor,\n type LeaseCheck,\n} from './firestore-multitab-wedge'\n\n/**\n * RECOVERING A FIRESTORE CLIENT THAT HAS STOPPED SYNCING (AGL-3373).\n *\n * ## The wedge\n *\n * The console runs the persistent cache with `persistentMultipleTabManager`\n * (`firestore-cache.ts`). Only the PRIMARY tab talks to the backend; every\n * other tab reads the shared IndexedDB cache and takes its online state from\n * a `localStorage` record the primary writes. A secondary that believes the\n * client is online answers a `getDocs` only once the primary has synced the\n * query, and raises no first snapshot for a listener whose cache is empty.\n *\n * When the primary dies without handing over — a crashed, discarded or\n * frozen tab — its \"Online\" record outlives it, and until some tab runs the\n * lease election and wins, nothing syncs. The election runs on a 4-second\n * timer inside each tab, which the browser throttles to about once a minute\n * in a hidden tab. On 2026-09-28 no live tab synced for about ten minutes:\n * the notifications page never left its loading state and a staff page sat\n * on its splash until a fresh tab (which wins the election on start) was\n * opened.\n *\n * ## The recovery, and why it is this one\n *\n * `disableNetwork` then `enableNetwork`, from the tab that noticed. Both are\n * public API, and in the multi-tab client each one calls\n * `setNetworkEnabled`, which schedules the lease election for IMMEDIATE\n * execution instead of the next (possibly throttled) timer tick. A visible\n * tab that finds the lease lapsed takes it, starts its own streams and\n * writes its own online state, which replaces the dead tab's. A tab that was\n * already primary with a silently dead stream gets fresh streams.\n *\n * Nothing is lost. Writes made meanwhile sit in the mutation queue (in\n * IndexedDB, under the persistent cache) and are sent when the network comes\n * back; the SDK's own contract for `disableNetwork` is that writes queue.\n *\n * The rejected alternatives:\n *\n * - **Clearing the persistence cache** (`terminate` + `clearIndexedDbPersistence`).\n * It deletes the mutation queue, so pending writes are lost, and\n * `waitForPendingWrites` cannot drain them first because draining is the\n * very thing that is stuck. It also refuses to run while any other tab\n * holds the database, which in a multi-tab wedge is always. And\n * `terminate` invalidates the one `Firestore` instance every hook in the\n * console holds.\n * - **Pruning the dead tab's online-state record at startup**, beside the\n * AGL-2845 prune. The SDK already ignores an online-state record at\n * startup unless its writer is an active, non-zombie client\n * (`WebStorageSharedClientState.handleOnlineStateEvent`), and a freshly\n * started tab wins the election anyway — which is why a fresh tab fixed\n * the incident. The tabs that stayed stuck were the ones ALREADY running,\n * which a startup prune never reaches.\n * - **`persistentSingleTabManager`.** It removes cross-tab dependency, but\n * every tab after the first falls back to a memory cache, so writes made\n * offline in those tabs are lost when they close. And a tab still on the\n * multi-tab build that meets a single-tab lease holder fails its queue\n * with `failed-precondition` until reloaded, so the rollout itself would\n * wedge the tabs left open across it.\n *\n * ## Guards\n *\n * - **Online only.** A browser that reports no network is correctly offline,\n * and the cache answering is the cache doing its job.\n * - **Visible only.** A hidden tab's timers are throttled and its reader is\n * not waiting; if it is stalled, it recovers the moment it is looked at.\n * - **Once per {@link STALL_RECOVERY_COOLDOWN_MS} per client.** Every list on\n * a page stalls together, and one cycle serves them all. A concurrent\n * request shares the cycle already running.\n * - **A client the server is answering is not stalled (AGL-4120).** See below.\n * - **Nor is one waiting on the shared cache, or served by a live lease\n * holder (AGL-4135).** See below.\n * - **The network is always re-enabled**, including when disabling fails.\n * - **Each step is bounded by {@link NETWORK_STEP_TIMEOUT_MS}.** Both calls are\n * queued on the client's AsyncQueue, and when another tab has locked the\n * shared IndexedDB they queue behind an operation that never finishes\n * (AGL-3428). Unbounded, the first such cycle never settled, and every\n * later recovery request shared it forever.\n *\n * ## The cycle is not free, so it needs a silent client (AGL-4120)\n *\n * A stall watch knows one thing: ITS listener has not been confirmed. That used\n * to be enough to cycle, so one slow listener among thirty-five took the whole\n * client off the network, and the cycle did real damage to one that was working.\n * `disableNetwork` makes a primary ineligible for its own lease\n * (`canActAsPrimary`), so it hands the lease over, to a hidden tab if one is\n * waiting: captured in production as `NET-OFF, LEASE-RELEASE, NET-ON`. And while\n * the network is off, every view in a primary goes Offline, so every listener the\n * server had already confirmed reads `fromCache` again until it is confirmed a\n * second time. A contact page read server-confirmed at 9 s and unconfirmed from\n * 14 s to past a minute, on a page nobody touched, refusing every save on it. A\n * slow page was turned into a broken one by the code meant to rescue it.\n *\n * So every server-confirmed snapshot stamps the client\n * ({@link noteFirestoreServerAnswer}), and a recovery within\n * {@link FIRESTORE_STALL_MS} of one answers `'answering'` and does nothing. A\n * client that is working through a page is left to finish. One that has really\n * gone silent stops stamping, and the next watch to fire gets its cycle.\n *\n * ## A client that is waiting is not silent either (AGL-4135)\n *\n * A client can go 8 s without an answer while nothing is wrong with it. Every\n * console tab shares one IndexedDB cache, and every SDK transaction locks every\n * store. A tab that is starved (busy, slow, throttled in the background) keeps\n * each transaction open until its event loop comes back between requests, for\n * seconds at a time. A healthy tab's client waits behind that lock and cannot\n * apply what the server sends, so it raises no confirmed snapshot. Measured in\n * production (v1.5.0, two tabs): the tab holding the lease was blocked for\n * about 12 s, and when its queue drained the cycle it had asked for ran, broadcast\n * `Offline` and put every confirmed view in both tabs back on the cache, the\n * record being saved included. The cycle cannot shorten another tab's\n * transaction, because both of its calls queue behind it.\n *\n * And a client in a tab that does not hold the lease is served by the tab that\n * does. Cycling it cannot reach the holder's stream. It only marks this tab\n * `networkEnabled: false` and reruns an election the live holder wins\n * (`networkEnabled: false` at 5.7 s in the AGL-4132 run).\n *\n * So before a cycle, the client reads the lease ({@link StallRecoveryDeps.checkLease}):\n *\n * - **the read waits** (`waiting`): a transaction holds the store. No cycle.\n * The wedge check below runs in its place, since a store that stays locked is\n * the AGL-3428 wedge whether or not a cycle ran first.\n * - **another tab holds a live lease** (`served`): no cycle. The holder is\n * slow, and nothing this tab does makes it faster.\n * - **anything else** (`silent`): this tab holds the lease and its stream has\n * gone quiet, or the lease has lapsed or is vacant and an election is due.\n * That is what the cycle is for, and it runs.\n *\n * The read takes up to a second (`LEASE_PROMPT_READ_MS`), so the client is\n * asked again afterwards whether the server has answered meanwhile.\n *\n * ## When the cycle is not enough (AGL-3428)\n *\n * A tab frozen partway through an IndexedDB transaction holds every store the\n * SDK uses, and the election the cycle forces cannot run. For a client on the\n * durable multi-tab cache the cycle is followed by the lease check in\n * `firestore-multitab-wedge.ts`, which moves the tab to a memory cache when\n * the lease shows the wedge. A client found `waiting` gets that check without\n * the cycle.\n */\n\n/**\n * How long a server read or a listener's first server-confirmed snapshot may\n * take before the client is treated as stalled. A healthy console answers\n * in well under two seconds; this leaves room for a slow network without\n * leaving a reader on a spinner for long.\n */\nexport const FIRESTORE_STALL_MS = 8_000\n\n/** The least time between two recoveries of the same client. */\nexport const STALL_RECOVERY_COOLDOWN_MS = 30_000\n\n/**\n * The longest the wait between two cycles grows to, on a client that cycling is\n * not bringing back. Doubling, so that a connection too slow to answer inside\n * one cooldown is not restarted before it can.\n */\nexport const STALL_RECOVERY_MAX_COOLDOWN_MS = 5 * 60_000\n\n/**\n * The longest `disableNetwork` or `enableNetwork` may take. Both finish in\n * milliseconds on a client whose queue is moving.\n */\nexport const NETWORK_STEP_TIMEOUT_MS = 5_000\n\n/** What a recovery request did. */\nexport type StallRecoveryOutcome =\n /** The browser reports no network: the cache is the right answer. */\n | 'offline'\n /** The tab is hidden: nobody is waiting on it. */\n | 'hidden'\n /** A recovery ran moments ago; this request rode on it. */\n | 'cooling'\n /** The server answered this client moments ago: it is busy, not stalled. */\n | 'answering'\n /** A transaction holds the shared cache, and this client is queued behind it (AGL-4135). */\n | 'waiting'\n /** Another tab holds a live lease and serves this client (AGL-4135). */\n | 'served'\n /** The network was cycled. */\n | 'recovered'\n /** The cycle threw or timed out; the network was still re-enabled if at all possible. */\n | 'failed'\n /** The multi-tab cache was wedged and this tab is moving to the memory cache. */\n | 'fell-back'\n\nexport interface StallRecoveryDeps {\n /** Take the client off the network. */\n disable: () => Promise<void>\n /** Put it back. */\n enable: () => Promise<void>\n /** `navigator.onLine`, or `true` where there is no navigator. */\n isOnline?: () => boolean\n /** Whether the document is visible, or `true` where there is none. */\n isVisible?: () => boolean\n now?: () => number\n /**\n * When the server last confirmed anything for this client, or `undefined`\n * if it has not. Without one, every stall is taken at its word.\n */\n lastServerAnswerAt?: () => number | undefined\n /** How recent an answer proves the client is alive. */\n answeringWindowMs?: number\n cooldownMs?: number\n /** The bound on each of `disable` and `enable`. */\n stepTimeoutMs?: number\n /**\n * Reads the shared cache's lease before a cycle (AGL-4135). Only a multi-tab\n * client has one; without it, every stall that passes the other guards is\n * cycled.\n */\n checkLease?: () => Promise<LeaseCheck>\n /**\n * The wedge check. Runs after every cycle, and in place of one for a client\n * found `waiting`. Resolves `true` when it has moved the tab off the shared\n * cache. Only a multi-tab client has one.\n */\n escalate?: () => Promise<boolean>\n}\n\nexport interface StallRecovery {\n recover: () => Promise<StallRecoveryOutcome>\n}\n\nconst browserOnline = () =>\n typeof navigator === 'undefined' || navigator.onLine !== false\n\nconst documentVisible = () =>\n typeof document === 'undefined' || document.visibilityState !== 'hidden'\n\n/** The recovery for one client, with its guards. Pure over `deps`. */\nexport function createStallRecovery(deps: StallRecoveryDeps): StallRecovery {\n const {\n disable,\n enable,\n isOnline = browserOnline,\n isVisible = documentVisible,\n now = Date.now,\n lastServerAnswerAt,\n answeringWindowMs = FIRESTORE_STALL_MS,\n cooldownMs = STALL_RECOVERY_COOLDOWN_MS,\n stepTimeoutMs = NETWORK_STEP_TIMEOUT_MS,\n checkLease,\n escalate,\n } = deps\n let lastStartedAt: number | undefined\n /** Cycles in a row that the server has not answered since. */\n let quietCycles = 0\n /** When a client found waiting last had the wedge check (AGL-4135). */\n let lastWaitCheckedAt: number | undefined\n let running: Promise<StallRecoveryOutcome> | undefined\n\n /** Whether `step` settled successfully within `stepTimeoutMs`. */\n const bounded = (step: () => Promise<void>): Promise<boolean> =>\n new Promise((resolve) => {\n const timer = setTimeout(() => resolve(false), stepTimeoutMs)\n const done = (ok: boolean) => {\n clearTimeout(timer)\n resolve(ok)\n }\n try {\n step().then(\n () => done(true),\n () => done(false),\n )\n } catch {\n done(false)\n }\n })\n\n /** Whether the escalation moved the tab off the shared cache. Best effort. */\n const escalated = async (): Promise<boolean> => {\n if (!escalate) return false\n try {\n return await escalate()\n } catch {\n return false\n }\n }\n\n const cycle = async (): Promise<StallRecoveryOutcome> => {\n let outcome: StallRecoveryOutcome = 'recovered'\n if (!(await bounded(disable))) outcome = 'failed'\n if (!(await bounded(enable))) outcome = 'failed'\n // The escalation is best effort; the cycle's own outcome stands.\n return (await escalated()) ? 'fell-back' : outcome\n }\n\n const answeredWithin = (at: number): boolean => {\n const answeredAt = lastServerAnswerAt?.()\n return answeredAt !== undefined && at - answeredAt < answeringWindowMs\n }\n\n /** Past the guards: reads the lease, then cycles only a client nothing explains. */\n const attempt = async (): Promise<StallRecoveryOutcome> => {\n let lease: LeaseCheck = { state: 'silent' }\n if (checkLease) {\n try {\n lease = await checkLease()\n } catch {\n // Unread, the stall is taken at its word, as it always was.\n }\n }\n if (lease.state === 'served') return 'served'\n if (lease.state === 'waiting') {\n // As often as a cycle would have run it, and no more: every check is\n // one more chance for a long wait to read as a wedge.\n const checkedAt = now()\n if (\n lastWaitCheckedAt !== undefined &&\n checkedAt - lastWaitCheckedAt < cooldownMs\n ) {\n return 'waiting'\n }\n lastWaitCheckedAt = checkedAt\n return (await escalated()) ? 'fell-back' : 'waiting'\n }\n // The read took time, and a client that was waiting may have answered.\n const at = now()\n if (answeredWithin(at)) return 'answering'\n if (lastStartedAt !== undefined) {\n const answeredAt = lastServerAnswerAt?.()\n const answeredSince =\n answeredAt !== undefined && answeredAt >= lastStartedAt\n quietCycles = answeredSince ? 0 : quietCycles + 1\n }\n lastStartedAt = at\n return cycle()\n }\n\n return {\n recover: () => {\n if (running) return running\n if (!isOnline()) return Promise.resolve('offline')\n if (!isVisible()) return Promise.resolve('hidden')\n const at = now()\n if (answeredWithin(at)) return Promise.resolve('answering')\n if (lastStartedAt !== undefined) {\n const cooldown = Math.min(\n cooldownMs * 2 ** quietCycles,\n STALL_RECOVERY_MAX_COOLDOWN_MS,\n )\n if (at - lastStartedAt < cooldown) return Promise.resolve('cooling')\n }\n running = attempt().finally(() => {\n running = undefined\n })\n return running\n },\n }\n}\n\nconst recoveries = new WeakMap<Firestore, StallRecovery>()\n\n/** When the server last confirmed a snapshot for each client. */\nconst serverAnswers = new WeakMap<Firestore, number>()\n\n/**\n * Records that the server just confirmed something for `firestore`: the\n * evidence a stall watch does not have that this client is alive. Every listener\n * that arms a watch calls this on a server-confirmed snapshot.\n */\nexport function noteFirestoreServerAnswer(\n firestore: Firestore | null | undefined,\n): void {\n if (firestore && typeof firestore === 'object') {\n serverAnswers.set(firestore, Date.now())\n }\n}\n\n/**\n * Whether the server has confirmed anything for `firestore` in this tab: the\n * boot check's line between a tab still booting and one in use (AGL-4201).\n */\nexport function firestoreHasServerAnswered(\n firestore: Firestore | null | undefined,\n): boolean {\n return Boolean(\n firestore && typeof firestore === 'object' && serverAnswers.has(firestore),\n )\n}\n\n/**\n * Recovers `firestore` if it has stalled. Safe to call from every reader\n * that notices: the guards above collapse the calls into at most one network\n * cycle per cooldown. Never rejects.\n */\nexport function recoverStalledFirestore(\n firestore: Firestore | null | undefined,\n): Promise<StallRecoveryOutcome> {\n if (!firestore || typeof firestore !== 'object') {\n return Promise.resolve('failed')\n }\n let recovery = recoveries.get(firestore)\n if (!recovery) {\n recovery = createStallRecovery({\n disable: () => disableNetwork(firestore),\n enable: () => enableNetwork(firestore),\n lastServerAnswerAt: () => serverAnswers.get(firestore),\n checkLease: browserLeaseCheckFor(firestore),\n escalate: browserWedgeEscalationFor(firestore),\n })\n recoveries.set(firestore, recovery)\n }\n return recovery.recover().catch(() => 'failed' as const)\n}\n\n/**\n * Arms a stall timer for one read or listen. Until `disarm` is called, `onStall`\n * runs (by default, {@link recoverStalledFirestore}) every `stallMs`. A tab that\n * is hidden when the timer fires waits until it is shown, since that is when a\n * reader is waiting again.\n *\n * It keeps firing because one call can do nothing: the request may land inside\n * a cooldown, or on a client that is still answering. A watch that spent itself\n * there left its listener unconfirmed for life (AGL-4120), which is how a tab's\n * first page worked and a later page's saves were refused. The calls cost nothing\n * until one of them finds a client that really needs a cycle.\n *\n * Returns `disarm`, which is idempotent.\n */\nexport function armFirestoreStallWatch(\n firestore: Firestore | null | undefined,\n options: { stallMs?: number; onStall?: () => void } = {},\n): () => void {\n const { stallMs = FIRESTORE_STALL_MS } = options\n const onStall =\n options.onStall ?? (() => void recoverStalledFirestore(firestore))\n let done = false\n let timer: ReturnType<typeof setTimeout> | undefined\n let onVisible: (() => void) | undefined\n const fire = () => {\n if (done) return\n if (!documentVisible() && typeof document !== 'undefined') {\n onVisible = () => {\n if (!documentVisible()) return\n document.removeEventListener('visibilitychange', onVisible!)\n onVisible = undefined\n fire()\n }\n document.addEventListener('visibilitychange', onVisible)\n return\n }\n onStall()\n timer = setTimeout(fire, stallMs)\n }\n timer = setTimeout(fire, stallMs)\n return () => {\n if (done) return\n done = true\n clearTimeout(timer)\n if (onVisible && typeof document !== 'undefined') {\n document.removeEventListener('visibilitychange', onVisible)\n }\n }\n}\n"],"names":["disableNetwork","enableNetwork","browserLeaseCheckFor","browserWedgeEscalationFor","FIRESTORE_STALL_MS","STALL_RECOVERY_COOLDOWN_MS","STALL_RECOVERY_MAX_COOLDOWN_MS","NETWORK_STEP_TIMEOUT_MS","browserOnline","navigator","onLine","documentVisible","document","visibilityState","createStallRecovery","deps","disable","enable","isOnline","isVisible","now","Date","lastServerAnswerAt","answeringWindowMs","cooldownMs","stepTimeoutMs","checkLease","escalate","lastStartedAt","quietCycles","lastWaitCheckedAt","running","bounded","step","Promise","resolve","timer","setTimeout","done","ok","clearTimeout","then","escalated","cycle","outcome","answeredWithin","at","answeredAt","undefined","attempt","lease","state","checkedAt","answeredSince","recover","cooldown","Math","min","finally","recoveries","WeakMap","serverAnswers","noteFirestoreServerAnswer","firestore","set","firestoreHasServerAnswered","Boolean","has","recoverStalledFirestore","recovery","get","catch","armFirestoreStallWatch","options","stallMs","onStall","onVisible","fire","removeEventListener","addEventListener"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,cAAc,EACdC,aAAa,QAER,qBAAoB;AAE3B,SACEC,oBAAoB,EACpBC,yBAAyB,QAEpB,gCAA4B;AAEnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAGqE;IACzC,MAAME,WACJF,mBAAAA,QAAQE,OAAO,YAAfF,mBAAoB,IAAM,KAAKL,wBAAwBL;IACzD,IAAIzB,OAAO;IACX,IAAIF;IACJ,IAAIwC;IACJ,MAAMC,OAAO;QACX,IAAIvC,MAAM;QACV,IAAI,CAAC3B,qBAAqB,OAAOC,aAAa,aAAa;YACzDgE,YAAY;gBACV,IAAI,CAACjE,mBAAmB;gBACxBC,SAASkE,mBAAmB,CAAC,oBAAoBF;gBACjDA,YAAY5B;gBACZ6B;YACF;YACAjE,SAASmE,gBAAgB,CAAC,oBAAoBH;YAC9C;QACF;QACAD;QACAvC,QAAQC,WAAWwC,MAAMH;IAC3B;IACAtC,QAAQC,WAAWwC,MAAMH;IACzB,OAAO;QACL,IAAIpC,MAAM;QACVA,OAAO;QACPE,aAAaJ;QACb,IAAIwC,aAAa,OAAOhE,aAAa,aAAa;YAChDA,SAASkE,mBAAmB,CAAC,oBAAoBF;QACnD;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-stall-recovery.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n disableNetwork,\n enableNetwork,\n type Firestore,\n} from 'firebase/firestore'\n\nimport {\n browserLeaseCheckFor,\n browserWedgeEscalationFor,\n type LeaseCheck,\n} from './firestore-multitab-wedge'\n\n/**\n * RECOVERING A FIRESTORE CLIENT THAT HAS STOPPED SYNCING (AGL-3373).\n *\n * ## The wedge\n *\n * The console runs the persistent cache with `persistentMultipleTabManager`\n * (`firestore-cache.ts`). Only the PRIMARY tab talks to the backend; every\n * other tab reads the shared IndexedDB cache and takes its online state from\n * a `localStorage` record the primary writes. A secondary that believes the\n * client is online answers a `getDocs` only once the primary has synced the\n * query, and raises no first snapshot for a listener whose cache is empty.\n *\n * When the primary dies without handing over — a crashed, discarded or\n * frozen tab — its \"Online\" record outlives it, and until some tab runs the\n * lease election and wins, nothing syncs. The election runs on a 4-second\n * timer inside each tab, which the browser throttles to about once a minute\n * in a hidden tab. On 2026-09-28 no live tab synced for about ten minutes:\n * the notifications page never left its loading state and a staff page sat\n * on its splash until a fresh tab (which wins the election on start) was\n * opened.\n *\n * ## The recovery, and why it is this one\n *\n * `disableNetwork` then `enableNetwork`, from the tab that noticed. Both are\n * public API, and in the multi-tab client each one calls\n * `setNetworkEnabled`, which schedules the lease election for IMMEDIATE\n * execution instead of the next (possibly throttled) timer tick. A visible\n * tab that finds the lease lapsed takes it, starts its own streams and\n * writes its own online state, which replaces the dead tab's. A tab that was\n * already primary with a silently dead stream gets fresh streams.\n *\n * Nothing is lost. Writes made meanwhile sit in the mutation queue (in\n * IndexedDB, under the persistent cache) and are sent when the network comes\n * back; the SDK's own contract for `disableNetwork` is that writes queue.\n *\n * The rejected alternatives:\n *\n * - **Clearing the persistence cache** (`terminate` + `clearIndexedDbPersistence`).\n * It deletes the mutation queue, so pending writes are lost, and\n * `waitForPendingWrites` cannot drain them first because draining is the\n * very thing that is stuck. It also refuses to run while any other tab\n * holds the database, which in a multi-tab wedge is always. And\n * `terminate` invalidates the one `Firestore` instance every hook in the\n * console holds.\n * - **Pruning the dead tab's online-state record at startup**, beside the\n * AGL-2845 prune. The SDK already ignores an online-state record at\n * startup unless its writer is an active, non-zombie client\n * (`WebStorageSharedClientState.handleOnlineStateEvent`), and a freshly\n * started tab wins the election anyway — which is why a fresh tab fixed\n * the incident. The tabs that stayed stuck were the ones ALREADY running,\n * which a startup prune never reaches.\n * - **`persistentSingleTabManager`.** It removes cross-tab dependency, but\n * every tab after the first falls back to a memory cache, so writes made\n * offline in those tabs are lost when they close. And a tab still on the\n * multi-tab build that meets a single-tab lease holder fails its queue\n * with `failed-precondition` until reloaded, so the rollout itself would\n * wedge the tabs left open across it.\n *\n * ## Guards\n *\n * - **Online only.** A browser that reports no network is correctly offline,\n * and the cache answering is the cache doing its job.\n * - **Visible only.** A hidden tab's timers are throttled and its reader is\n * not waiting; if it is stalled, it recovers the moment it is looked at.\n * - **Once per {@link STALL_RECOVERY_COOLDOWN_MS} per client.** Every list on\n * a page stalls together, and one cycle serves them all. A concurrent\n * request shares the cycle already running.\n * - **A client the server is answering is not stalled (AGL-4120).** See below.\n * - **Nor is one waiting on the shared cache, or served by a live lease\n * holder (AGL-4135).** See below.\n * - **The network is always re-enabled**, including when disabling fails.\n * - **Each step is bounded by {@link NETWORK_STEP_TIMEOUT_MS}.** Both calls are\n * queued on the client's AsyncQueue, and when another tab has locked the\n * shared IndexedDB they queue behind an operation that never finishes\n * (AGL-3428). Unbounded, the first such cycle never settled, and every\n * later recovery request shared it forever.\n *\n * ## The cycle is not free, so it needs a silent client (AGL-4120)\n *\n * A stall watch knows one thing: ITS listener has not been confirmed. That used\n * to be enough to cycle, so one slow listener among thirty-five took the whole\n * client off the network, and the cycle did real damage to one that was working.\n * `disableNetwork` makes a primary ineligible for its own lease\n * (`canActAsPrimary`), so it hands the lease over, to a hidden tab if one is\n * waiting: captured in production as `NET-OFF, LEASE-RELEASE, NET-ON`. And while\n * the network is off, every view in a primary goes Offline, so every listener the\n * server had already confirmed reads `fromCache` again until it is confirmed a\n * second time. A contact page read server-confirmed at 9 s and unconfirmed from\n * 14 s to past a minute, on a page nobody touched, refusing every save on it. A\n * slow page was turned into a broken one by the code meant to rescue it.\n *\n * So every server-confirmed snapshot stamps the client\n * ({@link noteFirestoreServerAnswer}), and a recovery within\n * {@link FIRESTORE_STALL_MS} of one answers `'answering'` and does nothing. A\n * client that is working through a page is left to finish. One that has really\n * gone silent stops stamping, and the next watch to fire gets its cycle.\n *\n * ## A client that is waiting is not silent either (AGL-4135)\n *\n * A client can go 8 s without an answer while nothing is wrong with it. Every\n * console tab shares one IndexedDB cache, and every SDK transaction locks every\n * store. A tab that is starved (busy, slow, throttled in the background) keeps\n * each transaction open until its event loop comes back between requests, for\n * seconds at a time. A healthy tab's client waits behind that lock and cannot\n * apply what the server sends, so it raises no confirmed snapshot. Measured in\n * production (v1.5.0, two tabs): the tab holding the lease was blocked for\n * about 12 s, and when its queue drained the cycle it had asked for ran, broadcast\n * `Offline` and put every confirmed view in both tabs back on the cache, the\n * record being saved included. The cycle cannot shorten another tab's\n * transaction, because both of its calls queue behind it.\n *\n * And a client in a tab that does not hold the lease is served by the tab that\n * does. Cycling it cannot reach the holder's stream. It only marks this tab\n * `networkEnabled: false` and reruns an election the live holder wins\n * (`networkEnabled: false` at 5.7 s in the AGL-4132 run).\n *\n * So before a cycle, the client reads the lease ({@link StallRecoveryDeps.checkLease}):\n *\n * - **the read waits** (`waiting`): a transaction holds the store. No cycle.\n * The wedge check below runs in its place, since a store that stays locked is\n * the AGL-3428 wedge whether or not a cycle ran first.\n * - **another tab holds a live lease** (`served`): no cycle. The holder is\n * slow, and nothing this tab does makes it faster.\n * - **anything else** (`silent`): this tab holds the lease and its stream has\n * gone quiet, or the lease has lapsed or is vacant and an election is due.\n * That is what the cycle is for, and it runs.\n *\n * The read takes up to a second (`LEASE_PROMPT_READ_MS`), so the client is\n * asked again afterwards whether the server has answered meanwhile.\n *\n * ## When the cycle is not enough (AGL-3428)\n *\n * A tab frozen partway through an IndexedDB transaction holds every store the\n * SDK uses, and the election the cycle forces cannot run. For a client on the\n * durable multi-tab cache the cycle is followed by the lease check in\n * `firestore-multitab-wedge.ts`, which moves the tab to a memory cache when\n * the lease shows the wedge. A client found `waiting` gets that check without\n * the cycle.\n */\n\n/**\n * How long a server read or a listener's first server-confirmed snapshot may\n * take before the client is treated as stalled. A healthy console answers\n * in well under two seconds; this leaves room for a slow network without\n * leaving a reader on a spinner for long.\n */\nexport const FIRESTORE_STALL_MS = 8_000\n\n/** The least time between two recoveries of the same client. */\nexport const STALL_RECOVERY_COOLDOWN_MS = 30_000\n\n/**\n * The longest the wait between two cycles grows to, on a client that cycling is\n * not bringing back. Doubling, so that a connection too slow to answer inside\n * one cooldown is not restarted before it can.\n */\nexport const STALL_RECOVERY_MAX_COOLDOWN_MS = 5 * 60_000\n\n/**\n * The longest `disableNetwork` or `enableNetwork` may take. Both finish in\n * milliseconds on a client whose queue is moving.\n */\nexport const NETWORK_STEP_TIMEOUT_MS = 5_000\n\n/** What a recovery request did. */\nexport type StallRecoveryOutcome =\n /** The browser reports no network: the cache is the right answer. */\n | 'offline'\n /** The tab is hidden: nobody is waiting on it. */\n | 'hidden'\n /** A recovery ran moments ago; this request rode on it. */\n | 'cooling'\n /** The server answered this client moments ago: it is busy, not stalled. */\n | 'answering'\n /** A transaction holds the shared cache, and this client is queued behind it (AGL-4135). */\n | 'waiting'\n /** Another tab holds a live lease and serves this client (AGL-4135). */\n | 'served'\n /** The network was cycled. */\n | 'recovered'\n /** The cycle threw or timed out; the network was still re-enabled if at all possible. */\n | 'failed'\n /** The multi-tab cache was wedged and this tab is moving to the memory cache. */\n | 'fell-back'\n\nexport interface StallRecoveryDeps {\n /** Take the client off the network. */\n disable: () => Promise<void>\n /** Put it back. */\n enable: () => Promise<void>\n /** `navigator.onLine`, or `true` where there is no navigator. */\n isOnline?: () => boolean\n /** Whether the document is visible, or `true` where there is none. */\n isVisible?: () => boolean\n now?: () => number\n /**\n * When the server last confirmed anything for this client, or `undefined`\n * if it has not. Without one, every stall is taken at its word.\n */\n lastServerAnswerAt?: () => number | undefined\n /** How recent an answer proves the client is alive. */\n answeringWindowMs?: number\n cooldownMs?: number\n /** The bound on each of `disable` and `enable`. */\n stepTimeoutMs?: number\n /**\n * Reads the shared cache's lease before a cycle (AGL-4135). Only a multi-tab\n * client has one; without it, every stall that passes the other guards is\n * cycled.\n */\n checkLease?: () => Promise<LeaseCheck>\n /**\n * The wedge check. Runs after every cycle, and in place of one for a client\n * found `waiting`. Resolves `true` when it has moved the tab off the shared\n * cache. Only a multi-tab client has one.\n */\n escalate?: () => Promise<boolean>\n}\n\nexport interface StallRecovery {\n recover: () => Promise<StallRecoveryOutcome>\n}\n\nconst browserOnline = () =>\n typeof navigator === 'undefined' || navigator.onLine !== false\n\nconst documentVisible = () =>\n typeof document === 'undefined' || document.visibilityState !== 'hidden'\n\n/** The recovery for one client, with its guards. Pure over `deps`. */\nexport function createStallRecovery(deps: StallRecoveryDeps): StallRecovery {\n const {\n disable,\n enable,\n isOnline = browserOnline,\n isVisible = documentVisible,\n now = Date.now,\n lastServerAnswerAt,\n answeringWindowMs = FIRESTORE_STALL_MS,\n cooldownMs = STALL_RECOVERY_COOLDOWN_MS,\n stepTimeoutMs = NETWORK_STEP_TIMEOUT_MS,\n checkLease,\n escalate,\n } = deps\n let lastStartedAt: number | undefined\n /** Cycles in a row that the server has not answered since. */\n let quietCycles = 0\n /** When a client found waiting last had the wedge check (AGL-4135). */\n let lastWaitCheckedAt: number | undefined\n let running: Promise<StallRecoveryOutcome> | undefined\n\n /** Whether `step` settled successfully within `stepTimeoutMs`. */\n const bounded = (step: () => Promise<void>): Promise<boolean> =>\n new Promise((resolve) => {\n const timer = setTimeout(() => resolve(false), stepTimeoutMs)\n const done = (ok: boolean) => {\n clearTimeout(timer)\n resolve(ok)\n }\n try {\n step().then(\n () => done(true),\n () => done(false),\n )\n } catch {\n done(false)\n }\n })\n\n /** Whether the escalation moved the tab off the shared cache. Best effort. */\n const escalated = async (): Promise<boolean> => {\n if (!escalate) return false\n try {\n return await escalate()\n } catch {\n return false\n }\n }\n\n const cycle = async (): Promise<StallRecoveryOutcome> => {\n let outcome: StallRecoveryOutcome = 'recovered'\n if (!(await bounded(disable))) outcome = 'failed'\n if (!(await bounded(enable))) outcome = 'failed'\n // The escalation is best effort; the cycle's own outcome stands.\n return (await escalated()) ? 'fell-back' : outcome\n }\n\n const answeredWithin = (at: number): boolean => {\n const answeredAt = lastServerAnswerAt?.()\n return answeredAt !== undefined && at - answeredAt < answeringWindowMs\n }\n\n /** Past the guards: reads the lease, then cycles only a client nothing explains. */\n const attempt = async (): Promise<StallRecoveryOutcome> => {\n let lease: LeaseCheck = { state: 'silent' }\n if (checkLease) {\n try {\n lease = await checkLease()\n } catch {\n // Unread, the stall is taken at its word, as it always was.\n }\n }\n if (lease.state === 'served') return 'served'\n if (lease.state === 'waiting') {\n // As often as a cycle would have run it, and no more: every check is\n // one more chance for a long wait to read as a wedge.\n const checkedAt = now()\n if (\n lastWaitCheckedAt !== undefined &&\n checkedAt - lastWaitCheckedAt < cooldownMs\n ) {\n return 'waiting'\n }\n lastWaitCheckedAt = checkedAt\n return (await escalated()) ? 'fell-back' : 'waiting'\n }\n // The read took time, and a client that was waiting may have answered.\n const at = now()\n if (answeredWithin(at)) return 'answering'\n if (lastStartedAt !== undefined) {\n const answeredAt = lastServerAnswerAt?.()\n const answeredSince =\n answeredAt !== undefined && answeredAt >= lastStartedAt\n quietCycles = answeredSince ? 0 : quietCycles + 1\n }\n lastStartedAt = at\n return cycle()\n }\n\n return {\n recover: () => {\n if (running) return running\n if (!isOnline()) return Promise.resolve('offline')\n if (!isVisible()) return Promise.resolve('hidden')\n const at = now()\n if (answeredWithin(at)) return Promise.resolve('answering')\n if (lastStartedAt !== undefined) {\n const cooldown = Math.min(\n cooldownMs * 2 ** quietCycles,\n STALL_RECOVERY_MAX_COOLDOWN_MS,\n )\n if (at - lastStartedAt < cooldown) return Promise.resolve('cooling')\n }\n running = attempt().finally(() => {\n running = undefined\n })\n return running\n },\n }\n}\n\nconst recoveries = new WeakMap<Firestore, StallRecovery>()\n\n/** When the server last confirmed a snapshot for each client. */\nconst serverAnswers = new WeakMap<Firestore, number>()\n\n/**\n * Records that the server just confirmed something for `firestore`: the\n * evidence a stall watch does not have that this client is alive. Every listener\n * that arms a watch calls this on a server-confirmed snapshot.\n */\nexport function noteFirestoreServerAnswer(\n firestore: Firestore | null | undefined,\n): void {\n if (firestore && typeof firestore === 'object') {\n serverAnswers.set(firestore, Date.now())\n }\n}\n\n/**\n * Whether the server has confirmed anything for `firestore` in this tab: the\n * boot check's line between a tab still booting and one in use (AGL-4201).\n */\nexport function firestoreHasServerAnswered(\n firestore: Firestore | null | undefined,\n): boolean {\n return Boolean(\n firestore && typeof firestore === 'object' && serverAnswers.has(firestore),\n )\n}\n\n/**\n * When the server last confirmed anything for `firestore` in this tab, or\n * `undefined` if it has not: the page check's line between a page still\n * loading and one the server has reached (AGL-4204).\n */\nexport function firestoreLastServerAnswerAt(\n firestore: Firestore | null | undefined,\n): number | undefined {\n return firestore && typeof firestore === 'object'\n ? serverAnswers.get(firestore)\n : undefined\n}\n\n/**\n * Recovers `firestore` if it has stalled. Safe to call from every reader\n * that notices: the guards above collapse the calls into at most one network\n * cycle per cooldown. Never rejects.\n */\nexport function recoverStalledFirestore(\n firestore: Firestore | null | undefined,\n): Promise<StallRecoveryOutcome> {\n if (!firestore || typeof firestore !== 'object') {\n return Promise.resolve('failed')\n }\n let recovery = recoveries.get(firestore)\n if (!recovery) {\n recovery = createStallRecovery({\n disable: () => disableNetwork(firestore),\n enable: () => enableNetwork(firestore),\n lastServerAnswerAt: () => serverAnswers.get(firestore),\n checkLease: browserLeaseCheckFor(firestore),\n escalate: browserWedgeEscalationFor(firestore),\n })\n recoveries.set(firestore, recovery)\n }\n return recovery.recover().catch(() => 'failed' as const)\n}\n\n/**\n * Arms a stall timer for one read or listen. Until `disarm` is called, `onStall`\n * runs (by default, {@link recoverStalledFirestore}) every `stallMs`. A tab that\n * is hidden when the timer fires waits until it is shown, since that is when a\n * reader is waiting again.\n *\n * It keeps firing because one call can do nothing: the request may land inside\n * a cooldown, or on a client that is still answering. A watch that spent itself\n * there left its listener unconfirmed for life (AGL-4120), which is how a tab's\n * first page worked and a later page's saves were refused. The calls cost nothing\n * until one of them finds a client that really needs a cycle.\n *\n * Returns `disarm`, which is idempotent.\n */\nexport function armFirestoreStallWatch(\n firestore: Firestore | null | undefined,\n options: { stallMs?: number; onStall?: () => void } = {},\n): () => void {\n const { stallMs = FIRESTORE_STALL_MS } = options\n const onStall =\n options.onStall ?? (() => void recoverStalledFirestore(firestore))\n let done = false\n let timer: ReturnType<typeof setTimeout> | undefined\n let onVisible: (() => void) | undefined\n const fire = () => {\n if (done) return\n if (!documentVisible() && typeof document !== 'undefined') {\n onVisible = () => {\n if (!documentVisible()) return\n document.removeEventListener('visibilitychange', onVisible!)\n onVisible = undefined\n fire()\n }\n document.addEventListener('visibilitychange', onVisible)\n return\n }\n onStall()\n timer = setTimeout(fire, stallMs)\n }\n timer = setTimeout(fire, stallMs)\n return () => {\n if (done) return\n done = true\n clearTimeout(timer)\n if (onVisible && typeof document !== 'undefined') {\n document.removeEventListener('visibilitychange', onVisible)\n }\n }\n}\n"],"names":["disableNetwork","enableNetwork","browserLeaseCheckFor","browserWedgeEscalationFor","FIRESTORE_STALL_MS","STALL_RECOVERY_COOLDOWN_MS","STALL_RECOVERY_MAX_COOLDOWN_MS","NETWORK_STEP_TIMEOUT_MS","browserOnline","navigator","onLine","documentVisible","document","visibilityState","createStallRecovery","deps","disable","enable","isOnline","isVisible","now","Date","lastServerAnswerAt","answeringWindowMs","cooldownMs","stepTimeoutMs","checkLease","escalate","lastStartedAt","quietCycles","lastWaitCheckedAt","running","bounded","step","Promise","resolve","timer","setTimeout","done","ok","clearTimeout","then","escalated","cycle","outcome","answeredWithin","at","answeredAt","undefined","attempt","lease","state","checkedAt","answeredSince","recover","cooldown","Math","min","finally","recoveries","WeakMap","serverAnswers","noteFirestoreServerAnswer","firestore","set","firestoreHasServerAnswered","Boolean","has","firestoreLastServerAnswerAt","get","recoverStalledFirestore","recovery","catch","armFirestoreStallWatch","options","stallMs","onStall","onVisible","fire","removeEventListener","addEventListener"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,cAAc,EACdC,aAAa,QAER,qBAAoB;AAE3B,SACEC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D;QACtC;QACAJ,WAAWK,GAAG,CAACD,WAAWQ;IAC5B;IACA,OAAOA,SAASjB,OAAO,GAAGkB,KAAK,CAAC,IAAM;AACxC;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,uBACdV,SAAuC,EACvCW,UAAsD,CAAC,CAAC;QAItDA;IAFF,MAAM,EAAEC,UAAUvE,kBAAkB,EAAE,GAAGsE;IACzC,MAAME,WACJF,mBAAAA,QAAQE,OAAO,YAAfF,mBAAoB,IAAM,KAAKJ,wBAAwBP;IACzD,IAAIzB,OAAO;IACX,IAAIF;IACJ,IAAIyC;IACJ,MAAMC,OAAO;QACX,IAAIxC,MAAM;QACV,IAAI,CAAC3B,qBAAqB,OAAOC,aAAa,aAAa;YACzDiE,YAAY;gBACV,IAAI,CAAClE,mBAAmB;gBACxBC,SAASmE,mBAAmB,CAAC,oBAAoBF;gBACjDA,YAAY7B;gBACZ8B;YACF;YACAlE,SAASoE,gBAAgB,CAAC,oBAAoBH;YAC9C;QACF;QACAD;QACAxC,QAAQC,WAAWyC,MAAMH;IAC3B;IACAvC,QAAQC,WAAWyC,MAAMH;IACzB,OAAO;QACL,IAAIrC,MAAM;QACVA,OAAO;QACPE,aAAaJ;QACb,IAAIyC,aAAa,OAAOjE,aAAa,aAAa;YAChDA,SAASmE,mBAAmB,CAAC,oBAAoBF;QACnD;IACF;AACF"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* Whether a site's workspace can take card payments, as the console can tell
|
|
19
|
+
* from the workspace owner's profile.
|
|
20
|
+
*
|
|
21
|
+
* - `pending` — the org or the owner's profile has not answered yet. Never
|
|
22
|
+
* gate on this: a notice that flashes before the read lands tells a
|
|
23
|
+
* connected merchant to connect.
|
|
24
|
+
* - `error` — the profile could not be read. Also never gated on.
|
|
25
|
+
* - `not-connected` — no Stripe account on file.
|
|
26
|
+
* - `charges-disabled` — Stripe has not enabled charges yet (onboarding
|
|
27
|
+
* unfinished, or Stripe needs more details).
|
|
28
|
+
* - `mode-mismatch` — the account is in the other Stripe mode from this
|
|
29
|
+
* deployment (a test account on a live deployment, or the reverse).
|
|
30
|
+
* Setting up payments replaces it with an account in this mode.
|
|
31
|
+
* - `mode-unverified` — a live deployment with an account whose mode was
|
|
32
|
+
* never recorded; reconnecting records it.
|
|
33
|
+
* - `ready` — charges go through.
|
|
34
|
+
*/
|
|
35
|
+
export type MerchantPaymentsState = 'pending' | 'error' | 'not-connected' | 'charges-disabled' | 'mode-mismatch' | 'mode-unverified' | 'ready';
|
|
36
|
+
export type MerchantPaymentsPlatformMode = 'live' | 'test' | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* This deployment's Stripe mode, from its publishable key: `pk_live_…` is
|
|
39
|
+
* live, `pk_test_…` is test. The server reads the same answer off its secret
|
|
40
|
+
* key, and the two keys of one deployment are always a pair.
|
|
41
|
+
*/
|
|
42
|
+
export declare function merchantPaymentsPlatformMode(publishableKey?: string | undefined): MerchantPaymentsPlatformMode;
|
|
43
|
+
/**
|
|
44
|
+
* The verdict for one owner profile. It is the client's copy of the server's
|
|
45
|
+
* `merchantAccountReadiness` and has to answer exactly as that does: a console
|
|
46
|
+
* that calls an account ready while checkout refuses it, or the reverse, puts
|
|
47
|
+
* a notice beside a control that works, or none beside one that fails.
|
|
48
|
+
*
|
|
49
|
+
* Only a literal `true` enables charges and only a literal boolean records a
|
|
50
|
+
* mode, because a field written as `'true'` or `1` was written by something
|
|
51
|
+
* other than the onboarding route.
|
|
52
|
+
*/
|
|
53
|
+
export declare function merchantPaymentsStateFromProfile(profile: Record<string, unknown> | null | undefined, platformMode: MerchantPaymentsPlatformMode): Exclude<MerchantPaymentsState, 'pending' | 'error'>;
|
|
54
|
+
/**
|
|
55
|
+
* One sentence on what stands between the workspace and card payments, for a
|
|
56
|
+
* notice or a disabled control's reason. `null` when nothing does, or while
|
|
57
|
+
* the answer is unknown.
|
|
58
|
+
*/
|
|
59
|
+
export declare function merchantPaymentsBlockedReason(state: MerchantPaymentsState, platformMode?: MerchantPaymentsPlatformMode): string | null;
|