@aglyn/tenant-feature-instance 1.22.1 → 1.22.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/helpers/guarded-seed-write.d.ts +6 -0
- package/src/lib/hooks/helpers/guarded-seed-write.js +11 -2
- package/src/lib/hooks/helpers/guarded-seed-write.js.map +1 -1
- package/src/lib/hooks/helpers/listen-confirmation.d.ts +68 -3
- package/src/lib/hooks/helpers/listen-confirmation.js +101 -7
- package/src/lib/hooks/helpers/listen-confirmation.js.map +1 -1
- package/src/lib/hooks/helpers/use-doc.js +10 -3
- package/src/lib/hooks/helpers/use-doc.js.map +1 -1
- package/src/lib/hooks/use-confirmed-doc.js +14 -3
- package/src/lib/hooks/use-confirmed-doc.js.map +1 -1
- package/src/lib/hooks/use-firestore-collection.js +10 -3
- package/src/lib/hooks/use-firestore-collection.js.map +1 -1
- package/src/lib/hooks/use-firestore-doc.js +10 -3
- package/src/lib/hooks/use-firestore-doc.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/tenant-feature-instance",
|
|
3
|
-
"version": "1.22.
|
|
3
|
+
"version": "1.22.3",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,12 +25,12 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.22.
|
|
29
|
-
"@aglyn/shared-data-enums": "1.22.
|
|
30
|
-
"@aglyn/shared-ui-jsx": "1.22.
|
|
31
|
-
"@aglyn/shared-util-email": "1.22.
|
|
32
|
-
"@aglyn/shared-util-http": "1.22.
|
|
33
|
-
"@aglyn/shared-util-timestamp": "1.22.
|
|
28
|
+
"@aglyn/aglyn": "1.22.3",
|
|
29
|
+
"@aglyn/shared-data-enums": "1.22.3",
|
|
30
|
+
"@aglyn/shared-ui-jsx": "1.22.3",
|
|
31
|
+
"@aglyn/shared-util-email": "1.22.3",
|
|
32
|
+
"@aglyn/shared-util-http": "1.22.3",
|
|
33
|
+
"@aglyn/shared-util-timestamp": "1.22.3",
|
|
34
34
|
"@swc/helpers": "0.5.24",
|
|
35
35
|
"lodash-es": "^4.18.1",
|
|
36
36
|
"mobx": "^7.1.6"
|
|
@@ -140,6 +140,12 @@ export declare function checkSeedFreshness(options: GuardedSeedWriteOptions): Gu
|
|
|
140
140
|
* is normally a moment. The other reasons are facts about the read or the
|
|
141
141
|
* session that waiting does not change, and they refuse at once. A save that
|
|
142
142
|
* names its seed's listener (`listen`) waits on that read alone (AGL-4135).
|
|
143
|
+
*
|
|
144
|
+
* A listener the server confirmed keeps that confirmation for a while after
|
|
145
|
+
* it falls back to the cache, so its hook reports `fromCache: false` and the
|
|
146
|
+
* save writes at once (AGL-4047, see `listen-confirmation.ts`). A save that
|
|
147
|
+
* names the listener also checks the keep's deadline by the wall clock, so a
|
|
148
|
+
* device that slept past it waits for the server like any unconfirmed seed.
|
|
143
149
|
*/
|
|
144
150
|
export declare function writeGuardedBySeed(options: GuardedSeedWriteOptions, write: () => Promise<void>): Promise<GuardedSeedWriteResult>;
|
|
145
151
|
export default writeGuardedBySeed;
|
|
@@ -72,7 +72,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
72
72
|
* check simply reports "not stale", which is what the tenant runtime and the
|
|
73
73
|
* unit tests want; the other two signals are unaffected, and they are the
|
|
74
74
|
* ones the doc above says must carry the guard anyway.
|
|
75
|
-
*/ import { whenListenConfirmed, whenListensConfirmed } from "./listen-confirmation.js";
|
|
75
|
+
*/ import { lapseOverdueConfirmation, whenListenConfirmed, whenListensConfirmed } from "./listen-confirmation.js";
|
|
76
76
|
/**
|
|
77
77
|
* The console's `session-health` verdict, injected because it is app state.
|
|
78
78
|
* Null until the app registers one — see {@link setStaleSessionCheck}.
|
|
@@ -169,8 +169,17 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
169
169
|
* is normally a moment. The other reasons are facts about the read or the
|
|
170
170
|
* session that waiting does not change, and they refuse at once. A save that
|
|
171
171
|
* names its seed's listener (`listen`) waits on that read alone (AGL-4135).
|
|
172
|
+
*
|
|
173
|
+
* A listener the server confirmed keeps that confirmation for a while after
|
|
174
|
+
* it falls back to the cache, so its hook reports `fromCache: false` and the
|
|
175
|
+
* save writes at once (AGL-4047, see `listen-confirmation.ts`). A save that
|
|
176
|
+
* names the listener also checks the keep's deadline by the wall clock, so a
|
|
177
|
+
* device that slept past it waits for the server like any unconfirmed seed.
|
|
172
178
|
*/ export async function writeGuardedBySeed(options, write) {
|
|
173
|
-
const
|
|
179
|
+
const lapsed = !options.fromCache && !options.unreadable && options.listen != null && lapseOverdueConfirmation(options.listen);
|
|
180
|
+
const verdict = checkSeedFreshness(lapsed ? _extends({}, options, {
|
|
181
|
+
fromCache: true
|
|
182
|
+
}) : options);
|
|
174
183
|
if (verdict.ok) {
|
|
175
184
|
await write();
|
|
176
185
|
return verdict;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/helpers/guarded-seed-write.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\n/**\n * Refuse a whole-object write whose form was seeded from a read we cannot\n * trust (AGL-1356, AGL-1358, AGL-1066).\n *\n * ## The shape this exists for\n *\n * A form seeded from a Firestore LISTENER, saved with a payload that carries\n * every field rather than the one that changed. `merge: true` protects\n * nothing there — the untouched fields are all present in the payload — so\n * saving one edit rewrites the rest to whatever the seed held. If the seed\n * came from IndexedDB during a stale session, \"whatever the seed held\" can\n * be arbitrarily old, and the user's real values are destroyed by a save\n * they asked for and had every reason to expect to be safe.\n *\n * ## Why it WRAPS the write instead of preceding it\n *\n * The guards this replaces sat in front of their writes as early returns,\n * which is a shape you can have and still write — add a branch, reorder a\n * line, and the guard is decoration. Here the write is only reachable\n * THROUGH the verdict, so a call site cannot keep the guard and lose the\n * protection. It also makes the refusal testable as a refusal: assert the\n * inner function never ran.\n *\n * ## The three signals, in the order they are worth trusting\n *\n * 1. `fromCache` — the server never confirmed what is on screen (AGL-1066).\n * This is the one that catches the dangerous case, because a cache-served\n * read looks completely healthy: populated form, plausible values. It is\n * per-listener ground truth from the SDK, so it needs no threshold and no\n * window, and it clears itself the instant a server snapshot lands. It\n * leads because it is also the more ACCURATE explanation whenever it is\n * true — see the ordering note on `checkSeedFreshness`. It is also the one\n * signal that a little patience answers, so `writeGuardedBySeed` waits for\n * the confirmation before it refuses on this alone (AGL-4120).\n * 2. `unreadable` — the read FAILED and there is nothing cached behind it\n * (AGL-1143). Saving would write blanks over a populated document.\n * 3. `staleSession` — the console's own heuristic. Kept because it means\n * something the other two do not (the SESSION is dead, not merely\n * unconfirmed), but it must never be the ONLY guard: it needs two\n * distinct labelled collections denied inside 60s, which is unreachable\n * on a listener-only page. That was exactly how AGL-1356 stayed open.\n *\n * ## Why this lives in the library rather than the console (AGL-1358)\n *\n * Most of the ~forty sites wearing this shape are plugin cards in\n * `libs/plugins/**`, which cannot import from `apps/console`. The guard\n * itself is pure, and `fromCache` — the signal that actually fires —\n * originates here, on the listener hooks. What it cannot own is\n * `session-health`, which is console state.\n *\n * So the third signal is INJECTED, through the same seam\n * `firestore-denial-reporter` already uses for the reverse direction: the\n * console registers a check at startup and the guard pulls it. That keeps a\n * single guard for every call site with no new dependency edge and nothing\n * inverted — the library still knows nothing about the app. An unregistered\n * check simply reports \"not stale\", which is what the tenant runtime and the\n * unit tests want; the other two signals are unaffected, and they are the\n * ones the doc above says must carry the guard anyway.\n */\n\nimport {\n whenListenConfirmed,\n whenListensConfirmed,\n type ListenHandle,\n} from './listen-confirmation'\n\nexport type { ListenHandle } from './listen-confirmation'\n\nexport type StaleSeedReason =\n | 'unreadable'\n | 'unconfirmed'\n | 'stale-session'\n /** The server's confirmation changed the values the form was built from. */\n | 'refreshed'\n\n/**\n * The console's `session-health` verdict, injected because it is app state.\n * Null until the app registers one — see {@link setStaleSessionCheck}.\n */\nlet staleSessionCheck: (() => boolean) | null = null\n\n/**\n * Register the app's stale-session verdict. Called once, by the app that owns\n * `session-health`. Pass `null` to unregister (tests).\n *\n * Registered at module scope alongside `setFirestoreSessionReporters` rather\n * than in an effect, for the same reason: a save can be clicked before any\n * effect has run, and a guard that consults a check which does not exist yet\n * silently loses its third signal.\n */\nexport function setStaleSessionCheck(check: (() => boolean) | null): void {\n staleSessionCheck = check\n}\n\n/** The registered verdict, or `false` when nothing is registered. */\nfunction isSessionStale(): boolean {\n return staleSessionCheck ? staleSessionCheck() : false\n}\n\nexport interface GuardedSeedWriteOptions {\n /**\n * What is being saved, in the user's words — \"profile\", \"settings\".\n * Used to build the refusal message, so it reads naturally in a sentence\n * like \"Your profile could not be loaded\".\n */\n subject: string\n /** The seeding read FAILED (`status === 'error'`). */\n unreadable?: boolean\n /** The seeding snapshot came from cache (`metadata.fromCache`). */\n fromCache?: boolean\n /**\n * The listener the seed came from: `listen` on the hook that gave\n * `fromCache` (AGL-4135). With it, an unconfirmed seed waits on that read\n * alone. Without it, the save waits on every listener unconfirmed at the\n * click, so an unrelated one that is slow, refused or torn down can hold it\n * back or refuse it.\n */\n listen?: ListenHandle | null\n /**\n * Also consult `session-health`. On by default; the only reason to turn it\n * off is a surface that deliberately writes during a known-degraded\n * session.\n */\n checkSession?: boolean\n}\n\nexport interface GuardedSeedWriteResult {\n /** True when the write RAN. */\n ok: boolean\n /** Why it did not run. */\n reason?: StaleSeedReason\n /**\n * What to tell the user. Always populated when `ok` is false — a refused\n * save that says nothing is its own bug: the user retypes the form and\n * tries again, and the second attempt is refused just as silently.\n */\n message?: string\n}\n\n/**\n * Why we refused, in words that say what to DO about it.\n *\n * ## The subject is INTERPOLATED, so nothing here may agree with it (AGL-1446)\n *\n * Call sites pass \"profile\", \"SEO settings\", \"theme overrides\", \"categories\".\n * The copy used to read \"Your SEO settings **has** not been confirmed\", \"so\n * **it** cannot be saved\", \"so **this** SEO settings may be out of date\" —\n * fine for the singular subjects it was written against and wrong for half the\n * ~126 call sites. Every sentence below is number-neutral instead, and\n * `guarded-seed-write.spec.ts` pins all three verbatim against a plural\n * subject so it stays that way.\n *\n * ## What `unconfirmed` may claim (AGL-4120)\n *\n * It used to tell people a tab could be \"permanently cache-only\" and to open a\n * new one, \"because reloading cannot restore a connection this tab never\n * opened\". That theory was wrong twice over. AGL-2486 showed the Listen channel\n * open and answering all along, and AGL-4120 measured what was left: nothing\n * had disconnected, the console's own stall recovery had taken a healthy client\n * off the network. A fresh tab only looked like a cure because it had not been\n * knocked off yet.\n *\n * By the time this reads, the save has waited {@link SEED_CONFIRM_WAIT_MS} for\n * the confirmation. So it says the three things that are true, which are the\n * three a person acting on it needs: the save did not happen, what they typed\n * is still there, and trying again in a moment is the remedy.\n */\nfunction refusalMessage(subject: string, reason: StaleSeedReason): string {\n switch (reason) {\n case 'unreadable':\n return (\n `Your ${subject} could not be loaded, so there is nothing safe to ` +\n 'save — saving now would overwrite the stored copy with blanks. ' +\n 'Reload and try again.'\n )\n case 'unconfirmed':\n return (\n `We could not confirm your ${subject} with the server yet, so nothing ` +\n 'was saved. What you entered is still here. Check your connection and ' +\n 'save again in a moment.'\n )\n case 'refreshed':\n return (\n `Your ${subject} just updated from the server, so nothing was saved ` +\n 'yet. Check the latest values, then save again.'\n )\n case 'stale-session':\n return (\n `Your session went stale, so your ${subject} may be out of date — ` +\n 'saving now could overwrite newer values. Sign in again and reload.'\n )\n }\n}\n\n/** The verdict on its own, for a caller that needs it before the click. */\nexport function checkSeedFreshness(\n options: GuardedSeedWriteOptions,\n): GuardedSeedWriteResult {\n const { subject, unreadable, fromCache, checkSession = true } = options\n /**\n * `fromCache` OUTRANKS `unreadable` (AGL-1066).\n *\n * It did not, and the ordering was harmless only while a refused listen\n * could never reach `status: 'error'`. Now that it can, the common case is\n * BOTH flags true at once — the cache is serving the document and the\n * server has stopped answering for it — and taking `unreadable` there\n * tells the user their settings \"could not be loaded\" and that saving\n * \"would overwrite it with blanks\", while a populated, plausible form sits\n * in front of them. The refusal is right; that explanation is not, and a\n * refusal whose reason is visibly false is one the user works around.\n *\n * What is left to `unreadable` is the read that failed with nothing to\n * show for it, which is the AGL-1143 case it was written for and where the\n * blanks are real. The heuristic still comes last.\n */\n const reason: StaleSeedReason | undefined = fromCache\n ? 'unconfirmed'\n : unreadable\n ? 'unreadable'\n : checkSession && isSessionStale()\n ? 'stale-session'\n : undefined\n if (!reason) return { ok: true }\n return { ok: false, reason, message: refusalMessage(subject, reason) }\n}\n\n/**\n * Run `write` only if the seed can be trusted.\n *\n * Never throws on refusal — the caller reports `message` and leaves the\n * user's typed values on screen, because the whole point is that we are not\n * confident enough to touch the stored document, not that the input was bad.\n *\n * A seed that is only UNCONFIRMED is waited for before it is refused\n * (AGL-4120): the save stays in its busy state while the server answers, which\n * is normally a moment. The other reasons are facts about the read or the\n * session that waiting does not change, and they refuse at once. A save that\n * names its seed's listener (`listen`) waits on that read alone (AGL-4135).\n */\nexport async function writeGuardedBySeed(\n options: GuardedSeedWriteOptions,\n write: () => Promise<void>,\n): Promise<GuardedSeedWriteResult> {\n const verdict = checkSeedFreshness(options)\n if (verdict.ok) {\n await write()\n return verdict\n }\n if (verdict.reason !== 'unconfirmed') return verdict\n const settlement = options.listen\n ? await whenListenConfirmed(options.listen)\n : await whenListensConfirmed()\n if (settlement === 'refreshed') {\n return {\n ok: false,\n reason: 'refreshed',\n message: refusalMessage(options.subject, 'refreshed'),\n }\n }\n if (settlement !== 'confirmed') return verdict\n // The wait took time, and the session may not have survived it.\n const confirmed = checkSeedFreshness({ ...options, fromCache: false })\n if (!confirmed.ok) return confirmed\n await write()\n return confirmed\n}\n\nexport default writeGuardedBySeed\n"],"names":["whenListenConfirmed","whenListensConfirmed","staleSessionCheck","setStaleSessionCheck","check","isSessionStale","refusalMessage","subject","reason","checkSeedFreshness","options","unreadable","fromCache","checkSession","undefined","ok","message","writeGuardedBySeed","write","verdict","settlement","listen","confirmed"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0DC,GAED,SACEA,mBAAmB,EACnBC,oBAAoB,QAEf,2BAAuB;AAW9B;;;CAGC,GACD,IAAIC,oBAA4C;AAEhD;;;;;;;;CAQC,GACD,OAAO,SAASC,qBAAqBC,KAA6B;IAChEF,oBAAoBE;AACtB;AAEA,mEAAmE,GACnE,SAASC;IACP,OAAOH,oBAAoBA,sBAAsB;AACnD;AA0CA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,SAASI,eAAeC,OAAe,EAAEC,MAAuB;IAC9D,OAAQA;QACN,KAAK;YACH,OACE,CAAC,KAAK,EAAED,QAAQ,kDAAkD,CAAC,GACnE,oEACA;QAEJ,KAAK;YACH,OACE,CAAC,0BAA0B,EAAEA,QAAQ,iCAAiC,CAAC,GACvE,0EACA;QAEJ,KAAK;YACH,OACE,CAAC,KAAK,EAAEA,QAAQ,oDAAoD,CAAC,GACrE;QAEJ,KAAK;YACH,OACE,CAAC,iCAAiC,EAAEA,QAAQ,sBAAsB,CAAC,GACnE;IAEN;AACF;AAEA,yEAAyE,GACzE,OAAO,SAASE,mBACdC,OAAgC;IAEhC,MAAM,EAAEH,OAAO,EAAEI,UAAU,EAAEC,SAAS,EAAEC,eAAe,IAAI,EAAE,GAAGH;IAChE;;;;;;;;;;;;;;;GAeC,GACD,MAAMF,SAAsCI,YACxC,gBACAD,aACE,eACAE,gBAAgBR,mBACd,kBACAS;IACR,IAAI,CAACN,QAAQ,OAAO;QAAEO,IAAI;IAAK;IAC/B,OAAO;QAAEA,IAAI;QAAOP;QAAQQ,SAASV,eAAeC,SAASC;IAAQ;AACvE;AAEA;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeS,mBACpBP,OAAgC,EAChCQ,KAA0B;IAE1B,MAAMC,UAAUV,mBAAmBC;IACnC,IAAIS,QAAQJ,EAAE,EAAE;QACd,MAAMG;QACN,OAAOC;IACT;IACA,IAAIA,QAAQX,MAAM,KAAK,eAAe,OAAOW;IAC7C,MAAMC,aAAaV,QAAQW,MAAM,GAC7B,MAAMrB,oBAAoBU,QAAQW,MAAM,IACxC,MAAMpB;IACV,IAAImB,eAAe,aAAa;QAC9B,OAAO;YACLL,IAAI;YACJP,QAAQ;YACRQ,SAASV,eAAeI,QAAQH,OAAO,EAAE;QAC3C;IACF;IACA,IAAIa,eAAe,aAAa,OAAOD;IACvC,gEAAgE;IAChE,MAAMG,YAAYb,mBAAmB,aAAKC;QAASE,WAAW;;IAC9D,IAAI,CAACU,UAAUP,EAAE,EAAE,OAAOO;IAC1B,MAAMJ;IACN,OAAOI;AACT;AAEA,eAAeL,mBAAkB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/helpers/guarded-seed-write.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\n/**\n * Refuse a whole-object write whose form was seeded from a read we cannot\n * trust (AGL-1356, AGL-1358, AGL-1066).\n *\n * ## The shape this exists for\n *\n * A form seeded from a Firestore LISTENER, saved with a payload that carries\n * every field rather than the one that changed. `merge: true` protects\n * nothing there — the untouched fields are all present in the payload — so\n * saving one edit rewrites the rest to whatever the seed held. If the seed\n * came from IndexedDB during a stale session, \"whatever the seed held\" can\n * be arbitrarily old, and the user's real values are destroyed by a save\n * they asked for and had every reason to expect to be safe.\n *\n * ## Why it WRAPS the write instead of preceding it\n *\n * The guards this replaces sat in front of their writes as early returns,\n * which is a shape you can have and still write — add a branch, reorder a\n * line, and the guard is decoration. Here the write is only reachable\n * THROUGH the verdict, so a call site cannot keep the guard and lose the\n * protection. It also makes the refusal testable as a refusal: assert the\n * inner function never ran.\n *\n * ## The three signals, in the order they are worth trusting\n *\n * 1. `fromCache` — the server never confirmed what is on screen (AGL-1066).\n * This is the one that catches the dangerous case, because a cache-served\n * read looks completely healthy: populated form, plausible values. It is\n * per-listener ground truth from the SDK, so it needs no threshold and no\n * window, and it clears itself the instant a server snapshot lands. It\n * leads because it is also the more ACCURATE explanation whenever it is\n * true — see the ordering note on `checkSeedFreshness`. It is also the one\n * signal that a little patience answers, so `writeGuardedBySeed` waits for\n * the confirmation before it refuses on this alone (AGL-4120).\n * 2. `unreadable` — the read FAILED and there is nothing cached behind it\n * (AGL-1143). Saving would write blanks over a populated document.\n * 3. `staleSession` — the console's own heuristic. Kept because it means\n * something the other two do not (the SESSION is dead, not merely\n * unconfirmed), but it must never be the ONLY guard: it needs two\n * distinct labelled collections denied inside 60s, which is unreachable\n * on a listener-only page. That was exactly how AGL-1356 stayed open.\n *\n * ## Why this lives in the library rather than the console (AGL-1358)\n *\n * Most of the ~forty sites wearing this shape are plugin cards in\n * `libs/plugins/**`, which cannot import from `apps/console`. The guard\n * itself is pure, and `fromCache` — the signal that actually fires —\n * originates here, on the listener hooks. What it cannot own is\n * `session-health`, which is console state.\n *\n * So the third signal is INJECTED, through the same seam\n * `firestore-denial-reporter` already uses for the reverse direction: the\n * console registers a check at startup and the guard pulls it. That keeps a\n * single guard for every call site with no new dependency edge and nothing\n * inverted — the library still knows nothing about the app. An unregistered\n * check simply reports \"not stale\", which is what the tenant runtime and the\n * unit tests want; the other two signals are unaffected, and they are the\n * ones the doc above says must carry the guard anyway.\n */\n\nimport {\n lapseOverdueConfirmation,\n whenListenConfirmed,\n whenListensConfirmed,\n type ListenHandle,\n} from './listen-confirmation'\n\nexport type { ListenHandle } from './listen-confirmation'\n\nexport type StaleSeedReason =\n | 'unreadable'\n | 'unconfirmed'\n | 'stale-session'\n /** The server's confirmation changed the values the form was built from. */\n | 'refreshed'\n\n/**\n * The console's `session-health` verdict, injected because it is app state.\n * Null until the app registers one — see {@link setStaleSessionCheck}.\n */\nlet staleSessionCheck: (() => boolean) | null = null\n\n/**\n * Register the app's stale-session verdict. Called once, by the app that owns\n * `session-health`. Pass `null` to unregister (tests).\n *\n * Registered at module scope alongside `setFirestoreSessionReporters` rather\n * than in an effect, for the same reason: a save can be clicked before any\n * effect has run, and a guard that consults a check which does not exist yet\n * silently loses its third signal.\n */\nexport function setStaleSessionCheck(check: (() => boolean) | null): void {\n staleSessionCheck = check\n}\n\n/** The registered verdict, or `false` when nothing is registered. */\nfunction isSessionStale(): boolean {\n return staleSessionCheck ? staleSessionCheck() : false\n}\n\nexport interface GuardedSeedWriteOptions {\n /**\n * What is being saved, in the user's words — \"profile\", \"settings\".\n * Used to build the refusal message, so it reads naturally in a sentence\n * like \"Your profile could not be loaded\".\n */\n subject: string\n /** The seeding read FAILED (`status === 'error'`). */\n unreadable?: boolean\n /** The seeding snapshot came from cache (`metadata.fromCache`). */\n fromCache?: boolean\n /**\n * The listener the seed came from: `listen` on the hook that gave\n * `fromCache` (AGL-4135). With it, an unconfirmed seed waits on that read\n * alone. Without it, the save waits on every listener unconfirmed at the\n * click, so an unrelated one that is slow, refused or torn down can hold it\n * back or refuse it.\n */\n listen?: ListenHandle | null\n /**\n * Also consult `session-health`. On by default; the only reason to turn it\n * off is a surface that deliberately writes during a known-degraded\n * session.\n */\n checkSession?: boolean\n}\n\nexport interface GuardedSeedWriteResult {\n /** True when the write RAN. */\n ok: boolean\n /** Why it did not run. */\n reason?: StaleSeedReason\n /**\n * What to tell the user. Always populated when `ok` is false — a refused\n * save that says nothing is its own bug: the user retypes the form and\n * tries again, and the second attempt is refused just as silently.\n */\n message?: string\n}\n\n/**\n * Why we refused, in words that say what to DO about it.\n *\n * ## The subject is INTERPOLATED, so nothing here may agree with it (AGL-1446)\n *\n * Call sites pass \"profile\", \"SEO settings\", \"theme overrides\", \"categories\".\n * The copy used to read \"Your SEO settings **has** not been confirmed\", \"so\n * **it** cannot be saved\", \"so **this** SEO settings may be out of date\" —\n * fine for the singular subjects it was written against and wrong for half the\n * ~126 call sites. Every sentence below is number-neutral instead, and\n * `guarded-seed-write.spec.ts` pins all three verbatim against a plural\n * subject so it stays that way.\n *\n * ## What `unconfirmed` may claim (AGL-4120)\n *\n * It used to tell people a tab could be \"permanently cache-only\" and to open a\n * new one, \"because reloading cannot restore a connection this tab never\n * opened\". That theory was wrong twice over. AGL-2486 showed the Listen channel\n * open and answering all along, and AGL-4120 measured what was left: nothing\n * had disconnected, the console's own stall recovery had taken a healthy client\n * off the network. A fresh tab only looked like a cure because it had not been\n * knocked off yet.\n *\n * By the time this reads, the save has waited {@link SEED_CONFIRM_WAIT_MS} for\n * the confirmation. So it says the three things that are true, which are the\n * three a person acting on it needs: the save did not happen, what they typed\n * is still there, and trying again in a moment is the remedy.\n */\nfunction refusalMessage(subject: string, reason: StaleSeedReason): string {\n switch (reason) {\n case 'unreadable':\n return (\n `Your ${subject} could not be loaded, so there is nothing safe to ` +\n 'save — saving now would overwrite the stored copy with blanks. ' +\n 'Reload and try again.'\n )\n case 'unconfirmed':\n return (\n `We could not confirm your ${subject} with the server yet, so nothing ` +\n 'was saved. What you entered is still here. Check your connection and ' +\n 'save again in a moment.'\n )\n case 'refreshed':\n return (\n `Your ${subject} just updated from the server, so nothing was saved ` +\n 'yet. Check the latest values, then save again.'\n )\n case 'stale-session':\n return (\n `Your session went stale, so your ${subject} may be out of date — ` +\n 'saving now could overwrite newer values. Sign in again and reload.'\n )\n }\n}\n\n/** The verdict on its own, for a caller that needs it before the click. */\nexport function checkSeedFreshness(\n options: GuardedSeedWriteOptions,\n): GuardedSeedWriteResult {\n const { subject, unreadable, fromCache, checkSession = true } = options\n /**\n * `fromCache` OUTRANKS `unreadable` (AGL-1066).\n *\n * It did not, and the ordering was harmless only while a refused listen\n * could never reach `status: 'error'`. Now that it can, the common case is\n * BOTH flags true at once — the cache is serving the document and the\n * server has stopped answering for it — and taking `unreadable` there\n * tells the user their settings \"could not be loaded\" and that saving\n * \"would overwrite it with blanks\", while a populated, plausible form sits\n * in front of them. The refusal is right; that explanation is not, and a\n * refusal whose reason is visibly false is one the user works around.\n *\n * What is left to `unreadable` is the read that failed with nothing to\n * show for it, which is the AGL-1143 case it was written for and where the\n * blanks are real. The heuristic still comes last.\n */\n const reason: StaleSeedReason | undefined = fromCache\n ? 'unconfirmed'\n : unreadable\n ? 'unreadable'\n : checkSession && isSessionStale()\n ? 'stale-session'\n : undefined\n if (!reason) return { ok: true }\n return { ok: false, reason, message: refusalMessage(subject, reason) }\n}\n\n/**\n * Run `write` only if the seed can be trusted.\n *\n * Never throws on refusal — the caller reports `message` and leaves the\n * user's typed values on screen, because the whole point is that we are not\n * confident enough to touch the stored document, not that the input was bad.\n *\n * A seed that is only UNCONFIRMED is waited for before it is refused\n * (AGL-4120): the save stays in its busy state while the server answers, which\n * is normally a moment. The other reasons are facts about the read or the\n * session that waiting does not change, and they refuse at once. A save that\n * names its seed's listener (`listen`) waits on that read alone (AGL-4135).\n *\n * A listener the server confirmed keeps that confirmation for a while after\n * it falls back to the cache, so its hook reports `fromCache: false` and the\n * save writes at once (AGL-4047, see `listen-confirmation.ts`). A save that\n * names the listener also checks the keep's deadline by the wall clock, so a\n * device that slept past it waits for the server like any unconfirmed seed.\n */\nexport async function writeGuardedBySeed(\n options: GuardedSeedWriteOptions,\n write: () => Promise<void>,\n): Promise<GuardedSeedWriteResult> {\n const lapsed =\n !options.fromCache &&\n !options.unreadable &&\n options.listen != null &&\n lapseOverdueConfirmation(options.listen)\n const verdict = checkSeedFreshness(\n lapsed ? { ...options, fromCache: true } : options,\n )\n if (verdict.ok) {\n await write()\n return verdict\n }\n if (verdict.reason !== 'unconfirmed') return verdict\n const settlement = options.listen\n ? await whenListenConfirmed(options.listen)\n : await whenListensConfirmed()\n if (settlement === 'refreshed') {\n return {\n ok: false,\n reason: 'refreshed',\n message: refusalMessage(options.subject, 'refreshed'),\n }\n }\n if (settlement !== 'confirmed') return verdict\n // The wait took time, and the session may not have survived it.\n const confirmed = checkSeedFreshness({ ...options, fromCache: false })\n if (!confirmed.ok) return confirmed\n await write()\n return confirmed\n}\n\nexport default writeGuardedBySeed\n"],"names":["lapseOverdueConfirmation","whenListenConfirmed","whenListensConfirmed","staleSessionCheck","setStaleSessionCheck","check","isSessionStale","refusalMessage","subject","reason","checkSeedFreshness","options","unreadable","fromCache","checkSession","undefined","ok","message","writeGuardedBySeed","write","lapsed","listen","verdict","settlement","confirmed"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0DC,GAED,SACEA,wBAAwB,EACxBC,mBAAmB,EACnBC,oBAAoB,QAEf,2BAAuB;AAW9B;;;CAGC,GACD,IAAIC,oBAA4C;AAEhD;;;;;;;;CAQC,GACD,OAAO,SAASC,qBAAqBC,KAA6B;IAChEF,oBAAoBE;AACtB;AAEA,mEAAmE,GACnE,SAASC;IACP,OAAOH,oBAAoBA,sBAAsB;AACnD;AA0CA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,SAASI,eAAeC,OAAe,EAAEC,MAAuB;IAC9D,OAAQA;QACN,KAAK;YACH,OACE,CAAC,KAAK,EAAED,QAAQ,kDAA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E,MAAME,YAAYd,mBAAmB,aAAKC;QAASE,WAAW;;IAC9D,IAAI,CAACW,UAAUR,EAAE,EAAE,OAAOQ;IAC1B,MAAML;IACN,OAAOK;AACT;AAEA,eAAeN,mBAAkB"}
|
|
@@ -57,6 +57,36 @@
|
|
|
57
57
|
* so writing it now would overwrite the new ones: the exact loss the guard
|
|
58
58
|
* exists to stop. That settles as `refreshed` and the save is refused for one
|
|
59
59
|
* click, so they see the new values first.
|
|
60
|
+
*
|
|
61
|
+
* ## A confirmation is kept through a short fall back to the cache (AGL-4047)
|
|
62
|
+
*
|
|
63
|
+
* A listener the server has confirmed reads `fromCache` again whenever the
|
|
64
|
+
* client's online state goes `Offline`, which the SDK applies to every view at
|
|
65
|
+
* once (`syncEngineApplyOnlineStateChange`). In the console that is routine,
|
|
66
|
+
* and has nothing to do with the values: a background tab handing the shared
|
|
67
|
+
* cache to the visible one cycles its network (`firestore-primary-yield.ts`),
|
|
68
|
+
* as does a stall recovery in either tab, and every secondary tab takes the
|
|
69
|
+
* holder's `Offline` from the shared client state. The view comes back only
|
|
70
|
+
* when the server marks its target current again, which behind a starved lease
|
|
71
|
+
* holder took longer than the guard's wait. So a card confirmed minutes
|
|
72
|
+
* earlier, whose stored copy never changed, held its next Save for 12 s and
|
|
73
|
+
* then refused it (production, v1.22.2: 2 of 4 presses on Business profile,
|
|
74
|
+
* 30–60 s after an earlier save, with a second console tab open).
|
|
75
|
+
*
|
|
76
|
+
* Such a fall is not the danger the guard exists for. The guard stops a form
|
|
77
|
+
* seeded from a copy the server never vouched for, which can be any age. A
|
|
78
|
+
* cached snapshot that FOLLOWS a confirmation on the same listener can hold
|
|
79
|
+
* nothing older than that confirmation, because the cache only ever moves
|
|
80
|
+
* forward (server values, or writes made on this device); and up to the fall
|
|
81
|
+
* the listener was hearing every change as it happened. So a confirmed
|
|
82
|
+
* listener stays confirmed for {@link SEED_CONFIRMATION_KEPT_MS} after it
|
|
83
|
+
* falls back: the hook keeps reporting `fromCache: false`, and a save writes
|
|
84
|
+
* at once. If the server has not confirmed it again by then, the confirmation
|
|
85
|
+
* LAPSES and the listener is unconfirmed like any other: the hook reports
|
|
86
|
+
* `fromCache: true`, a save waits for the server, and it is refused only if
|
|
87
|
+
* nothing comes within the guard's own wait. The deadline is read from the
|
|
88
|
+
* wall clock as well as a timer, so a device that slept through it never
|
|
89
|
+
* saves over a copy it has not heard about since.
|
|
60
90
|
*/
|
|
61
91
|
/**
|
|
62
92
|
* How long a save waits for a confirmation before saying so. Past the 8 s stall
|
|
@@ -76,6 +106,21 @@ export declare function setSeedConfirmWaitMs(ms?: number): void;
|
|
|
76
106
|
* guard would have waited for it.
|
|
77
107
|
*/
|
|
78
108
|
export declare function seedConfirmWaitMs(): number;
|
|
109
|
+
/**
|
|
110
|
+
* How long a listener the server confirmed stays confirmed after it falls back
|
|
111
|
+
* to the cache (AGL-4047). Longer than a handoff of the shared cache between
|
|
112
|
+
* two tabs takes to re-confirm (reads waited up to 18.9 s behind a background
|
|
113
|
+
* holder, and a lease went 23.7 s stale, measured in production in AGL-4204),
|
|
114
|
+
* and short enough that a client the server has really stopped answering is
|
|
115
|
+
* soon treated as one.
|
|
116
|
+
*/
|
|
117
|
+
export declare const SEED_CONFIRMATION_KEPT_MS = 60000;
|
|
118
|
+
/**
|
|
119
|
+
* How long a confirmation is kept. For a spec that pins what happens once it
|
|
120
|
+
* lapses: pass `0` to lapse at the fall, and restore the default (no argument)
|
|
121
|
+
* when done.
|
|
122
|
+
*/
|
|
123
|
+
export declare function setSeedConfirmationKeptMs(ms?: number): void;
|
|
79
124
|
/** The part of a document snapshot {@link sameDocument} reads. */
|
|
80
125
|
interface DocumentValues {
|
|
81
126
|
exists: () => boolean;
|
|
@@ -117,8 +162,12 @@ export interface ListenConfirmation {
|
|
|
117
162
|
* A snapshot arrived. `changed` says a confirmation brought different values
|
|
118
163
|
* from the ones this listener had shown; a first answer showed nothing, so
|
|
119
164
|
* it cannot have changed anything.
|
|
165
|
+
*
|
|
166
|
+
* Returns the `fromCache` the hook reports: the snapshot's own, except that
|
|
167
|
+
* a cached snapshot following a confirmation reads `false` while the
|
|
168
|
+
* confirmation is kept (AGL-4047).
|
|
120
169
|
*/
|
|
121
|
-
report: (fromCache: boolean, changed?: boolean) =>
|
|
170
|
+
report: (fromCache: boolean, changed?: boolean) => boolean;
|
|
122
171
|
/**
|
|
123
172
|
* The listener was refused. A wait on every listener ends unconfirmed; a wait
|
|
124
173
|
* on this one goes on, for the retry.
|
|
@@ -130,12 +179,26 @@ export interface ListenConfirmation {
|
|
|
130
179
|
*/
|
|
131
180
|
close: () => void;
|
|
132
181
|
}
|
|
182
|
+
export interface TrackListenOptions {
|
|
183
|
+
/**
|
|
184
|
+
* A confirmation kept through a fall back to the cache has lapsed: the hook
|
|
185
|
+
* reports `fromCache: true` from now on, until the server answers.
|
|
186
|
+
*/
|
|
187
|
+
onLapse?: () => void;
|
|
188
|
+
}
|
|
133
189
|
/**
|
|
134
190
|
* One listener's line in the record. Unconfirmed from the start, for the same
|
|
135
191
|
* reason every hook's `fromCache` state starts true. With `handle`, the handle
|
|
136
192
|
* points at this listener from now on.
|
|
137
193
|
*/
|
|
138
|
-
export declare function trackListenConfirmation(handle?: ListenHandle): ListenConfirmation;
|
|
194
|
+
export declare function trackListenConfirmation(handle?: ListenHandle, options?: TrackListenOptions): ListenConfirmation;
|
|
195
|
+
/**
|
|
196
|
+
* Whether the listener `handle` points at is on a kept confirmation whose
|
|
197
|
+
* deadline the wall clock has passed (AGL-4047): a device that slept, or a tab
|
|
198
|
+
* whose timers were held back, has not run the lapse yet. It lapses now, so
|
|
199
|
+
* the caller treats the seed as unconfirmed and waits for the server.
|
|
200
|
+
*/
|
|
201
|
+
export declare function lapseOverdueConfirmation(handle: ListenHandle): boolean;
|
|
139
202
|
/**
|
|
140
203
|
* Resolves when every listener unconfirmed right now has settled, or after
|
|
141
204
|
* `timeoutMs`. Never rejects.
|
|
@@ -146,7 +209,9 @@ export declare function whenListensConfirmed(timeoutMs?: number): Promise<Listen
|
|
|
146
209
|
* `timeoutMs` (AGL-4135). Never rejects.
|
|
147
210
|
*
|
|
148
211
|
* - **Already confirmed**: at once, `refreshed` if that confirmation changed
|
|
149
|
-
* the values on screen. The caller read `fromCache` before it landed.
|
|
212
|
+
* the values on screen. The caller read `fromCache` before it landed. A
|
|
213
|
+
* confirmation kept through a fall back to the cache counts, until its
|
|
214
|
+
* deadline (AGL-4047); past it, the listener is unconfirmed and waited on.
|
|
150
215
|
* - **Unconfirmed, refused or torn down**: waits. A refused listener retries
|
|
151
216
|
* and reports again; a torn-down one is replaced, and the handle points at
|
|
152
217
|
* the replacement. Neither is ever taken for a confirmation.
|
|
@@ -56,6 +56,36 @@
|
|
|
56
56
|
* so writing it now would overwrite the new ones: the exact loss the guard
|
|
57
57
|
* exists to stop. That settles as `refreshed` and the save is refused for one
|
|
58
58
|
* click, so they see the new values first.
|
|
59
|
+
*
|
|
60
|
+
* ## A confirmation is kept through a short fall back to the cache (AGL-4047)
|
|
61
|
+
*
|
|
62
|
+
* A listener the server has confirmed reads `fromCache` again whenever the
|
|
63
|
+
* client's online state goes `Offline`, which the SDK applies to every view at
|
|
64
|
+
* once (`syncEngineApplyOnlineStateChange`). In the console that is routine,
|
|
65
|
+
* and has nothing to do with the values: a background tab handing the shared
|
|
66
|
+
* cache to the visible one cycles its network (`firestore-primary-yield.ts`),
|
|
67
|
+
* as does a stall recovery in either tab, and every secondary tab takes the
|
|
68
|
+
* holder's `Offline` from the shared client state. The view comes back only
|
|
69
|
+
* when the server marks its target current again, which behind a starved lease
|
|
70
|
+
* holder took longer than the guard's wait. So a card confirmed minutes
|
|
71
|
+
* earlier, whose stored copy never changed, held its next Save for 12 s and
|
|
72
|
+
* then refused it (production, v1.22.2: 2 of 4 presses on Business profile,
|
|
73
|
+
* 30–60 s after an earlier save, with a second console tab open).
|
|
74
|
+
*
|
|
75
|
+
* Such a fall is not the danger the guard exists for. The guard stops a form
|
|
76
|
+
* seeded from a copy the server never vouched for, which can be any age. A
|
|
77
|
+
* cached snapshot that FOLLOWS a confirmation on the same listener can hold
|
|
78
|
+
* nothing older than that confirmation, because the cache only ever moves
|
|
79
|
+
* forward (server values, or writes made on this device); and up to the fall
|
|
80
|
+
* the listener was hearing every change as it happened. So a confirmed
|
|
81
|
+
* listener stays confirmed for {@link SEED_CONFIRMATION_KEPT_MS} after it
|
|
82
|
+
* falls back: the hook keeps reporting `fromCache: false`, and a save writes
|
|
83
|
+
* at once. If the server has not confirmed it again by then, the confirmation
|
|
84
|
+
* LAPSES and the listener is unconfirmed like any other: the hook reports
|
|
85
|
+
* `fromCache: true`, a save waits for the server, and it is refused only if
|
|
86
|
+
* nothing comes within the guard's own wait. The deadline is read from the
|
|
87
|
+
* wall clock as well as a timer, so a device that slept through it never
|
|
88
|
+
* saves over a copy it has not heard about since.
|
|
59
89
|
*/ /**
|
|
60
90
|
* How long a save waits for a confirmation before saying so. Past the 8 s stall
|
|
61
91
|
* window, so a client that really is silent has been recovered by the time the
|
|
@@ -76,6 +106,22 @@ let confirmWaitMs = SEED_CONFIRM_WAIT_MS;
|
|
|
76
106
|
*/ export function seedConfirmWaitMs() {
|
|
77
107
|
return confirmWaitMs;
|
|
78
108
|
}
|
|
109
|
+
/**
|
|
110
|
+
* How long a listener the server confirmed stays confirmed after it falls back
|
|
111
|
+
* to the cache (AGL-4047). Longer than a handoff of the shared cache between
|
|
112
|
+
* two tabs takes to re-confirm (reads waited up to 18.9 s behind a background
|
|
113
|
+
* holder, and a lease went 23.7 s stale, measured in production in AGL-4204),
|
|
114
|
+
* and short enough that a client the server has really stopped answering is
|
|
115
|
+
* soon treated as one.
|
|
116
|
+
*/ export const SEED_CONFIRMATION_KEPT_MS = 60000;
|
|
117
|
+
let confirmationKeptMs = SEED_CONFIRMATION_KEPT_MS;
|
|
118
|
+
/**
|
|
119
|
+
* How long a confirmation is kept. For a spec that pins what happens once it
|
|
120
|
+
* lapses: pass `0` to lapse at the fall, and restore the default (no argument)
|
|
121
|
+
* when done.
|
|
122
|
+
*/ export function setSeedConfirmationKeptMs(ms = SEED_CONFIRMATION_KEPT_MS) {
|
|
123
|
+
confirmationKeptMs = ms;
|
|
124
|
+
}
|
|
79
125
|
/**
|
|
80
126
|
* Whether two snapshots of one document hold the same values. Read only on the
|
|
81
127
|
* step from a cached snapshot to a confirmed one, never on every update, because
|
|
@@ -117,15 +163,35 @@ function settleSeedWaiters(token) {
|
|
|
117
163
|
* One listener's line in the record. Unconfirmed from the start, for the same
|
|
118
164
|
* reason every hook's `fromCache` state starts true. With `handle`, the handle
|
|
119
165
|
* points at this listener from now on.
|
|
120
|
-
*/ export function trackListenConfirmation(handle) {
|
|
166
|
+
*/ export function trackListenConfirmation(handle, options = {}) {
|
|
167
|
+
let keepTimer = null;
|
|
168
|
+
const endKeep = ()=>{
|
|
169
|
+
if (keepTimer) clearTimeout(keepTimer);
|
|
170
|
+
keepTimer = null;
|
|
171
|
+
token.keptUntil = null;
|
|
172
|
+
};
|
|
173
|
+
const unconfirm = ()=>{
|
|
174
|
+
token.state = 'unconfirmed';
|
|
175
|
+
token.changed = false;
|
|
176
|
+
unconfirmed.add(token);
|
|
177
|
+
};
|
|
121
178
|
const token = {
|
|
122
179
|
state: 'unconfirmed',
|
|
123
|
-
changed: false
|
|
180
|
+
changed: false,
|
|
181
|
+
keptUntil: null,
|
|
182
|
+
lapse: ()=>{
|
|
183
|
+
if (token.keptUntil === null) return;
|
|
184
|
+
endKeep();
|
|
185
|
+
if (token.state !== 'confirmed') return;
|
|
186
|
+
unconfirm();
|
|
187
|
+
options.onLapse == null ? void 0 : options.onLapse.call(options);
|
|
188
|
+
}
|
|
124
189
|
};
|
|
125
190
|
unconfirmed.add(token);
|
|
126
191
|
const bound = handle;
|
|
127
192
|
if (bound) bound.token = token;
|
|
128
193
|
const release = ()=>{
|
|
194
|
+
endKeep();
|
|
129
195
|
token.state = 'released';
|
|
130
196
|
token.changed = false;
|
|
131
197
|
unconfirmed.delete(token);
|
|
@@ -136,11 +202,22 @@ function settleSeedWaiters(token) {
|
|
|
136
202
|
return {
|
|
137
203
|
report: (fromCache, changed = false)=>{
|
|
138
204
|
if (fromCache) {
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
205
|
+
// Confirmed, and now the cache's: the client's online state moved,
|
|
206
|
+
// not the values. Kept, from the first such snapshot (AGL-4047).
|
|
207
|
+
if (token.state === 'confirmed' && confirmationKeptMs > 0) {
|
|
208
|
+
if (token.keptUntil === null) {
|
|
209
|
+
token.keptUntil = Date.now() + confirmationKeptMs;
|
|
210
|
+
keepTimer = setTimeout(token.lapse, confirmationKeptMs);
|
|
211
|
+
}
|
|
212
|
+
if (Date.now() < token.keptUntil) return false;
|
|
213
|
+
token.lapse();
|
|
214
|
+
return true;
|
|
215
|
+
}
|
|
216
|
+
endKeep();
|
|
217
|
+
unconfirm();
|
|
218
|
+
return true;
|
|
143
219
|
}
|
|
220
|
+
endKeep();
|
|
144
221
|
token.state = 'confirmed';
|
|
145
222
|
token.changed = changed;
|
|
146
223
|
unconfirmed.delete(token);
|
|
@@ -148,6 +225,7 @@ function settleSeedWaiters(token) {
|
|
|
148
225
|
changed
|
|
149
226
|
});
|
|
150
227
|
settleSeedWaiters(token);
|
|
228
|
+
return false;
|
|
151
229
|
},
|
|
152
230
|
release,
|
|
153
231
|
close: ()=>{
|
|
@@ -156,6 +234,19 @@ function settleSeedWaiters(token) {
|
|
|
156
234
|
}
|
|
157
235
|
};
|
|
158
236
|
}
|
|
237
|
+
/**
|
|
238
|
+
* Whether the listener `handle` points at is on a kept confirmation whose
|
|
239
|
+
* deadline the wall clock has passed (AGL-4047): a device that slept, or a tab
|
|
240
|
+
* whose timers were held back, has not run the lapse yet. It lapses now, so
|
|
241
|
+
* the caller treats the seed as unconfirmed and waits for the server.
|
|
242
|
+
*/ export function lapseOverdueConfirmation(handle) {
|
|
243
|
+
const token = handle.token;
|
|
244
|
+
if (!token || token.keptUntil === null || Date.now() < token.keptUntil) {
|
|
245
|
+
return false;
|
|
246
|
+
}
|
|
247
|
+
token.lapse();
|
|
248
|
+
return token.state === 'unconfirmed';
|
|
249
|
+
}
|
|
159
250
|
/**
|
|
160
251
|
* Resolves when every listener unconfirmed right now has settled, or after
|
|
161
252
|
* `timeoutMs`. Never rejects.
|
|
@@ -181,7 +272,9 @@ function settleSeedWaiters(token) {
|
|
|
181
272
|
* `timeoutMs` (AGL-4135). Never rejects.
|
|
182
273
|
*
|
|
183
274
|
* - **Already confirmed**: at once, `refreshed` if that confirmation changed
|
|
184
|
-
* the values on screen. The caller read `fromCache` before it landed.
|
|
275
|
+
* the values on screen. The caller read `fromCache` before it landed. A
|
|
276
|
+
* confirmation kept through a fall back to the cache counts, until its
|
|
277
|
+
* deadline (AGL-4047); past it, the listener is unconfirmed and waited on.
|
|
185
278
|
* - **Unconfirmed, refused or torn down**: waits. A refused listener retries
|
|
186
279
|
* and reports again; a torn-down one is replaced, and the handle points at
|
|
187
280
|
* the replacement. Neither is ever taken for a confirmation.
|
|
@@ -191,6 +284,7 @@ function settleSeedWaiters(token) {
|
|
|
191
284
|
const state = handle;
|
|
192
285
|
const token = state.token;
|
|
193
286
|
if (!token) return Promise.resolve('untracked');
|
|
287
|
+
lapseOverdueConfirmation(handle);
|
|
194
288
|
if (token.state === 'confirmed') {
|
|
195
289
|
return Promise.resolve(token.changed ? 'refreshed' : 'confirmed');
|
|
196
290
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/helpers/listen-confirmation.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\n/**\n * THE LISTENERS THE SERVER HAS NOT CONFIRMED YET, FOR A SAVE THAT NEEDS ONE\n * (AGL-4120).\n *\n * `writeGuardedBySeed` was handed one boolean, read when the button was\n * clicked, and refused the moment it was true. So a save made a second before\n * the server answered was thrown back at the person who made it, with an\n * instruction to reload — though nothing was wrong and waiting would have\n * done. Under load that window ran to a minute (measured in production, beta.297).\n *\n * A guard cannot watch a value it was passed by copy, and fifty-eight call\n * sites pass one. So the four hooks that produce `fromCache` report here, and\n * the guard asks this module instead of its caller: every listener that was\n * unconfirmed at the click has now heard from the server.\n *\n * ## Which listeners\n *\n * The seed's own, when the save names it (AGL-4135). Each hook that produces\n * `fromCache` also returns a {@link ListenHandle}, which always points at that\n * hook's current listener, and a call site that passes it to the guard waits\n * on that read alone ({@link whenListenConfirmed}).\n *\n * Otherwise all of them, because the guard cannot name its own. That errs one\n * way only: a listener nobody is saving can make a save wait, or refuse it, by\n * being slow, refused or torn down during the wait. It can never let a save\n * through on an unconfirmed seed, because the seed's own listener is in the set\n * being waited on. Measured in production with another tab starving the shared\n * cache (AGL-4135), every listener on a page is slow at once, so waiting on all\n * of them is waiting on the slowest one.\n *\n * Waiting on one listener keeps the same promise. A refusal or a teardown\n * never counts as a confirmation: the wait goes on, for the retry that reports\n * again or for the listener that replaces it, and ends unconfirmed at the\n * deadline if neither comes.\n *\n * ## A confirmation can change what is on screen\n *\n * The seed being protected may be out of date, which is the whole point of the\n * guard. When a listener's confirmation brought values that differ from the\n * ones it had shown, the form the person edited was built from the old ones,\n * so writing it now would overwrite the new ones: the exact loss the guard\n * exists to stop. That settles as `refreshed` and the save is refused for one\n * click, so they see the new values first.\n */\n\n/**\n * How long a save waits for a confirmation before saying so. Past the 8 s stall\n * window, so a client that really is silent has been recovered by the time the\n * wait ends, and short enough to read as a slow save rather than a dead button.\n */\nexport const SEED_CONFIRM_WAIT_MS = 12_000\n\nlet confirmWaitMs = SEED_CONFIRM_WAIT_MS\n\n/**\n * How long a save waits. For a spec that pins what happens when the confirmation\n * never comes, which is the refusal and not the wait: pass `0`, and restore the\n * default (no argument) when done, the way `setStaleSessionCheck` is unregistered.\n */\nexport function setSeedConfirmWaitMs(ms: number = SEED_CONFIRM_WAIT_MS): void {\n confirmWaitMs = ms\n}\n\n/**\n * How long a save waits, as set now: for a Save pressed while it is held\n * (`useHeldSave`, AGL-4047), which keeps the press for exactly as long as the\n * guard would have waited for it.\n */\nexport function seedConfirmWaitMs(): number {\n return confirmWaitMs\n}\n\n/** The part of a document snapshot {@link sameDocument} reads. */\ninterface DocumentValues {\n exists: () => boolean\n data: () => unknown\n}\n\n/**\n * Whether two snapshots of one document hold the same values. Read only on the\n * step from a cached snapshot to a confirmed one, never on every update, because\n * the SDK hands a doc listener no list of what changed.\n */\nexport function sameDocument(a: DocumentValues, b: DocumentValues): boolean {\n if (a.exists() !== b.exists()) return false\n return JSON.stringify(a.data()) === JSON.stringify(b.data())\n}\n\n/** How the wait ended. */\nexport type ListenSettlement =\n /** Every listener that was unconfirmed at the start has heard from the server. */\n | 'confirmed'\n /** They did, and at least one brought different values from the ones it showed. */\n | 'refreshed'\n /** The wait ran out, or a listener was refused or went away before answering. */\n | 'unconfirmed'\n /**\n * No listener here was unconfirmed, so whatever said the seed is unconfirmed\n * is not one this module can vouch for. The caller's answer stands.\n */\n | 'untracked'\n\n/** One listener's line in the record. */\ninterface Token {\n /** Where its last word left it. A refusal or a teardown is never `confirmed`. */\n state: 'unconfirmed' | 'confirmed' | 'released'\n /** Its latest confirmation brought values that differ from the ones it showed. */\n changed: boolean\n}\n\ninterface Waiter {\n pending: Set<Token>\n refreshed: boolean\n lost: boolean\n finish: (settlement: ListenSettlement) => void\n}\n\n/** A save waiting on one listener (AGL-4135). */\ninterface SeedWaiter {\n handle: HandleState\n finish: (settlement: ListenSettlement) => void\n}\n\ndeclare const listenHandleBrand: unique symbol\n\n/**\n * One hook's listener, for a save that waits on it alone (AGL-4135). Stable\n * for the life of the hook, and always points at the hook's CURRENT listener,\n * so a listener replaced during the wait (new deps, a reopen) is the one\n * waited on. Opaque: a call site only hands it to `writeGuardedBySeed`.\n */\nexport interface ListenHandle {\n readonly [listenHandleBrand]: true\n}\n\ninterface HandleState {\n token: Token | null\n}\n\n/** A handle for one hook instance. Create it once (`useState(createListenHandle)`). */\nexport function createListenHandle(): ListenHandle {\n const state: HandleState = { token: null }\n return state as unknown as ListenHandle\n}\n\nconst unconfirmed = new Set<Token>()\nconst waiters = new Set<Waiter>()\nconst seedWaiters = new Set<SeedWaiter>()\n\nfunction settleWaiters(token: Token, how: { changed?: boolean; lost?: boolean }) {\n for (const waiter of [...waiters]) {\n if (!waiter.pending.delete(token)) continue\n if (how.changed) waiter.refreshed = true\n if (how.lost) waiter.lost = true\n if (waiter.pending.size > 0) continue\n if (waiter.lost) waiter.finish('unconfirmed')\n else waiter.finish(waiter.refreshed ? 'refreshed' : 'confirmed')\n }\n}\n\nfunction settleSeedWaiters(token: Token) {\n for (const waiter of [...seedWaiters]) {\n if (waiter.handle.token !== token) continue\n waiter.finish(token.changed ? 'refreshed' : 'confirmed')\n }\n}\n\nexport interface ListenConfirmation {\n /**\n * A snapshot arrived. `changed` says a confirmation brought different values\n * from the ones this listener had shown; a first answer showed nothing, so\n * it cannot have changed anything.\n */\n report: (fromCache: boolean, changed?: boolean) => void\n /**\n * The listener was refused. A wait on every listener ends unconfirmed; a wait\n * on this one goes on, for the retry.\n */\n release: () => void\n /**\n * The listener was torn down. As `release`, and its handle no longer points\n * at it, so a wait on this one goes on for the listener that replaces it.\n */\n close: () => void\n}\n\n/**\n * One listener's line in the record. Unconfirmed from the start, for the same\n * reason every hook's `fromCache` state starts true. With `handle`, the handle\n * points at this listener from now on.\n */\nexport function trackListenConfirmation(\n handle?: ListenHandle,\n): ListenConfirmation {\n const token: Token = { state: 'unconfirmed', changed: false }\n unconfirmed.add(token)\n const bound = handle as unknown as HandleState | undefined\n if (bound) bound.token = token\n const release = () => {\n token.state = 'released'\n token.changed = false\n unconfirmed.delete(token)\n settleWaiters(token, { lost: true })\n }\n return {\n report: (fromCache, changed = false) => {\n if (fromCache) {\n token.state = 'unconfirmed'\n token.changed = false\n unconfirmed.add(token)\n return\n }\n token.state = 'confirmed'\n token.changed = changed\n unconfirmed.delete(token)\n settleWaiters(token, { changed })\n settleSeedWaiters(token)\n },\n release,\n close: () => {\n release()\n if (bound?.token === token) bound.token = null\n },\n }\n}\n\n/**\n * Resolves when every listener unconfirmed right now has settled, or after\n * `timeoutMs`. Never rejects.\n */\nexport function whenListensConfirmed(\n timeoutMs: number = confirmWaitMs,\n): Promise<ListenSettlement> {\n if (unconfirmed.size === 0) return Promise.resolve('untracked')\n return new Promise((resolve) => {\n const waiter: Waiter = {\n pending: new Set(unconfirmed),\n refreshed: false,\n lost: false,\n finish: (settlement) => {\n clearTimeout(timer)\n waiters.delete(waiter)\n resolve(settlement)\n },\n }\n const timer = setTimeout(() => waiter.finish('unconfirmed'), timeoutMs)\n waiters.add(waiter)\n })\n}\n\n/**\n * Resolves when the listener `handle` points at is confirmed, or after\n * `timeoutMs` (AGL-4135). Never rejects.\n *\n * - **Already confirmed**: at once, `refreshed` if that confirmation changed\n * the values on screen. The caller read `fromCache` before it landed.\n * - **Unconfirmed, refused or torn down**: waits. A refused listener retries\n * and reports again; a torn-down one is replaced, and the handle points at\n * the replacement. Neither is ever taken for a confirmation.\n * - **No listener behind the handle** (its hook has not listened, or has\n * stopped): `untracked`, so the caller's answer stands.\n */\nexport function whenListenConfirmed(\n handle: ListenHandle,\n timeoutMs: number = confirmWaitMs,\n): Promise<ListenSettlement> {\n const state = handle as unknown as HandleState\n const token = state.token\n if (!token) return Promise.resolve('untracked')\n if (token.state === 'confirmed') {\n return Promise.resolve(token.changed ? 'refreshed' : 'confirmed')\n }\n return new Promise((resolve) => {\n const waiter: SeedWaiter = {\n handle: state,\n finish: (settlement) => {\n clearTimeout(timer)\n seedWaiters.delete(waiter)\n resolve(settlement)\n },\n }\n const timer = setTimeout(() => waiter.finish('unconfirmed'), timeoutMs)\n seedWaiters.add(waiter)\n })\n}\n"],"names":["SEED_CONFIRM_WAIT_MS","confirmWaitMs","setSeedConfirmWaitMs","ms","seedConfirmWaitMs","sameDocument","a","b","exists","JSON","stringify","data","createListenHandle","state","token","unconfirmed","Set","waiters","seedWaiters","settleWaiters","how","waiter","pending","delete","changed","refreshed","lost","size","finish","settleSeedWaiters","handle","trackListenConfirmation","add","bound","release","report","fromCache","close","whenListensConfirmed","timeoutMs","Promise","resolve","settlement","clearTimeout","timer","setTimeout","whenListenConfirmed"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC,GAED;;;;CAIC,GACD,OAAO,MAAMA,uBAAuB,MAAM;AAE1C,IAAIC,gBAAgBD;AAEpB;;;;CAIC,GACD,OAAO,SAASE,qBAAqBC,KAAaH,oBAAoB;IACpEC,gBAAgBE;AAClB;AAEA;;;;CAIC,GACD,OAAO,SAASC;IACd,OAAOH;AACT;AAQA;;;;CAIC,GACD,OAAO,SAASI,aAAaC,CAAiB,EAAEC,CAAiB;IAC/D,IAAID,EAAEE,MAAM,OAAOD,EAAEC,MAAM,IAAI,OAAO;IACtC,OAAOC,KAAKC,SAAS,CAACJ,EAAEK,IAAI,QAAQF,KAAKC,SAAS,CAACH,EAAEI,IAAI;AAC3D;AAqDA,qFAAqF,GACrF,OAAO,SAASC;IACd,MAAMC,QAAqB;QAAEC,OAAO;IAAK;IACzC,OAAOD;AACT;AAEA,MAAME,cAAc,IAAIC;AACxB,MAAMC,UAAU,IAAID;AACpB,MAAME,cAAc,IAAIF;AAExB,SAASG,cAAcL,KAAY,EAAEM,GAA0C;IAC7E,KAAK,MAAMC,UAAU;WAAIJ;KAAQ,CAAE;QACjC,IAAI,CAACI,OAAOC,OAAO,CAACC,MAAM,CAACT,QAAQ;QACnC,IAAIM,IAAII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,SAASwB,qBACdC,YAAoBtC,aAAa;IAEjC,IAAIc,YAAYY,IAAI,KAAK,GAAG,OAAOa,QAAQC,OAAO,CAAC;IACnD,OAAO,IAAID,QAAQ,CAACC;QAClB,MAAMpB,SAAiB;YACrBC,SAAS,IAAIN,IAAID;YACjBU,WAAW;YACXC,MAAM;YACNE,QAAQ,CAACc;gBACPC,aAAaC;gBACb3B,QAAQM,MAAM,CAACF;gBACfoB,QAAQC;YACV;QACF;QACA,MAAME,QAAQC,WAAW,IAAMxB,OAAOO,MAAM,CAAC,gBAAgBW;QAC7DtB,QAAQe,GAAG,CAACX;IACd;AACF;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,SAASyB,oBACdhB,MAAoB,EACpBS,YAAoBtC,aAAa;IAEjC,MAAMY,QAAQiB;IACd,MAAMhB,QAAQD,MAAMC,KAAK;IACzB,IAAI,CAACA,OAAO,OAAO0B,QAAQC,OAAO,CAAC;IACnC,IAAI3B,MAAMD,KAAK,KAAK,aAAa;QAC/B,OAAO2B,QAAQC,OAAO,CAAC3B,MAAMU,OAAO,GAAG,cAAc;IACvD;IACA,OAAO,IAAIgB,QAAQ,CAACC;QAClB,MAAMpB,SAAqB;YACzBS,QAAQjB;YACRe,QAAQ,CAACc;gBACPC,aAAaC;gBACb1B,YAAYK,MAAM,CAACF;gBACnBoB,QAAQC;YACV;QACF;QACA,MAAME,QAAQC,WAAW,IAAMxB,OAAOO,MAAM,CAAC,gBAAgBW;QAC7DrB,YAAYc,GAAG,CAACX;IAClB;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/helpers/listen-confirmation.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\n/**\n * THE LISTENERS THE SERVER HAS NOT CONFIRMED YET, FOR A SAVE THAT NEEDS ONE\n * (AGL-4120).\n *\n * `writeGuardedBySeed` was handed one boolean, read when the button was\n * clicked, and refused the moment it was true. So a save made a second before\n * the server answered was thrown back at the person who made it, with an\n * instruction to reload — though nothing was wrong and waiting would have\n * done. Under load that window ran to a minute (measured in production, beta.297).\n *\n * A guard cannot watch a value it was passed by copy, and fifty-eight call\n * sites pass one. So the four hooks that produce `fromCache` report here, and\n * the guard asks this module instead of its caller: every listener that was\n * unconfirmed at the click has now heard from the server.\n *\n * ## Which listeners\n *\n * The seed's own, when the save names it (AGL-4135). Each hook that produces\n * `fromCache` also returns a {@link ListenHandle}, which always points at that\n * hook's current listener, and a call site that passes it to the guard waits\n * on that read alone ({@link whenListenConfirmed}).\n *\n * Otherwise all of them, because the guard cannot name its own. That errs one\n * way only: a listener nobody is saving can make a save wait, or refuse it, by\n * being slow, refused or torn down during the wait. It can never let a save\n * through on an unconfirmed seed, because the seed's own listener is in the set\n * being waited on. Measured in production with another tab starving the shared\n * cache (AGL-4135), every listener on a page is slow at once, so waiting on all\n * of them is waiting on the slowest one.\n *\n * Waiting on one listener keeps the same promise. A refusal or a teardown\n * never counts as a confirmation: the wait goes on, for the retry that reports\n * again or for the listener that replaces it, and ends unconfirmed at the\n * deadline if neither comes.\n *\n * ## A confirmation can change what is on screen\n *\n * The seed being protected may be out of date, which is the whole point of the\n * guard. When a listener's confirmation brought values that differ from the\n * ones it had shown, the form the person edited was built from the old ones,\n * so writing it now would overwrite the new ones: the exact loss the guard\n * exists to stop. That settles as `refreshed` and the save is refused for one\n * click, so they see the new values first.\n *\n * ## A confirmation is kept through a short fall back to the cache (AGL-4047)\n *\n * A listener the server has confirmed reads `fromCache` again whenever the\n * client's online state goes `Offline`, which the SDK applies to every view at\n * once (`syncEngineApplyOnlineStateChange`). In the console that is routine,\n * and has nothing to do with the values: a background tab handing the shared\n * cache to the visible one cycles its network (`firestore-primary-yield.ts`),\n * as does a stall recovery in either tab, and every secondary tab takes the\n * holder's `Offline` from the shared client state. The view comes back only\n * when the server marks its target current again, which behind a starved lease\n * holder took longer than the guard's wait. So a card confirmed minutes\n * earlier, whose stored copy never changed, held its next Save for 12 s and\n * then refused it (production, v1.22.2: 2 of 4 presses on Business profile,\n * 30–60 s after an earlier save, with a second console tab open).\n *\n * Such a fall is not the danger the guard exists for. The guard stops a form\n * seeded from a copy the server never vouched for, which can be any age. A\n * cached snapshot that FOLLOWS a confirmation on the same listener can hold\n * nothing older than that confirmation, because the cache only ever moves\n * forward (server values, or writes made on this device); and up to the fall\n * the listener was hearing every change as it happened. So a confirmed\n * listener stays confirmed for {@link SEED_CONFIRMATION_KEPT_MS} after it\n * falls back: the hook keeps reporting `fromCache: false`, and a save writes\n * at once. If the server has not confirmed it again by then, the confirmation\n * LAPSES and the listener is unconfirmed like any other: the hook reports\n * `fromCache: true`, a save waits for the server, and it is refused only if\n * nothing comes within the guard's own wait. The deadline is read from the\n * wall clock as well as a timer, so a device that slept through it never\n * saves over a copy it has not heard about since.\n */\n\n/**\n * How long a save waits for a confirmation before saying so. Past the 8 s stall\n * window, so a client that really is silent has been recovered by the time the\n * wait ends, and short enough to read as a slow save rather than a dead button.\n */\nexport const SEED_CONFIRM_WAIT_MS = 12_000\n\nlet confirmWaitMs = SEED_CONFIRM_WAIT_MS\n\n/**\n * How long a save waits. For a spec that pins what happens when the confirmation\n * never comes, which is the refusal and not the wait: pass `0`, and restore the\n * default (no argument) when done, the way `setStaleSessionCheck` is unregistered.\n */\nexport function setSeedConfirmWaitMs(ms: number = SEED_CONFIRM_WAIT_MS): void {\n confirmWaitMs = ms\n}\n\n/**\n * How long a save waits, as set now: for a Save pressed while it is held\n * (`useHeldSave`, AGL-4047), which keeps the press for exactly as long as the\n * guard would have waited for it.\n */\nexport function seedConfirmWaitMs(): number {\n return confirmWaitMs\n}\n\n/**\n * How long a listener the server confirmed stays confirmed after it falls back\n * to the cache (AGL-4047). Longer than a handoff of the shared cache between\n * two tabs takes to re-confirm (reads waited up to 18.9 s behind a background\n * holder, and a lease went 23.7 s stale, measured in production in AGL-4204),\n * and short enough that a client the server has really stopped answering is\n * soon treated as one.\n */\nexport const SEED_CONFIRMATION_KEPT_MS = 60_000\n\nlet confirmationKeptMs = SEED_CONFIRMATION_KEPT_MS\n\n/**\n * How long a confirmation is kept. For a spec that pins what happens once it\n * lapses: pass `0` to lapse at the fall, and restore the default (no argument)\n * when done.\n */\nexport function setSeedConfirmationKeptMs(\n ms: number = SEED_CONFIRMATION_KEPT_MS,\n): void {\n confirmationKeptMs = ms\n}\n\n/** The part of a document snapshot {@link sameDocument} reads. */\ninterface DocumentValues {\n exists: () => boolean\n data: () => unknown\n}\n\n/**\n * Whether two snapshots of one document hold the same values. Read only on the\n * step from a cached snapshot to a confirmed one, never on every update, because\n * the SDK hands a doc listener no list of what changed.\n */\nexport function sameDocument(a: DocumentValues, b: DocumentValues): boolean {\n if (a.exists() !== b.exists()) return false\n return JSON.stringify(a.data()) === JSON.stringify(b.data())\n}\n\n/** How the wait ended. */\nexport type ListenSettlement =\n /** Every listener that was unconfirmed at the start has heard from the server. */\n | 'confirmed'\n /** They did, and at least one brought different values from the ones it showed. */\n | 'refreshed'\n /** The wait ran out, or a listener was refused or went away before answering. */\n | 'unconfirmed'\n /**\n * No listener here was unconfirmed, so whatever said the seed is unconfirmed\n * is not one this module can vouch for. The caller's answer stands.\n */\n | 'untracked'\n\n/** One listener's line in the record. */\ninterface Token {\n /**\n * Where its last word left it. A refusal or a teardown is never `confirmed`.\n * A confirmed listener that fell back to the cache stays `confirmed` until\n * its confirmation lapses (`keptUntil`).\n */\n state: 'unconfirmed' | 'confirmed' | 'released'\n /** Its latest confirmation brought values that differ from the ones it showed. */\n changed: boolean\n /**\n * Epoch ms at which a confirmation kept through a fall back to the cache\n * lapses; null while the listener is not on a kept confirmation.\n */\n keptUntil: number | null\n /** End a kept confirmation now: the listener is unconfirmed from here. */\n lapse: () => void\n}\n\ninterface Waiter {\n pending: Set<Token>\n refreshed: boolean\n lost: boolean\n finish: (settlement: ListenSettlement) => void\n}\n\n/** A save waiting on one listener (AGL-4135). */\ninterface SeedWaiter {\n handle: HandleState\n finish: (settlement: ListenSettlement) => void\n}\n\ndeclare const listenHandleBrand: unique symbol\n\n/**\n * One hook's listener, for a save that waits on it alone (AGL-4135). Stable\n * for the life of the hook, and always points at the hook's CURRENT listener,\n * so a listener replaced during the wait (new deps, a reopen) is the one\n * waited on. Opaque: a call site only hands it to `writeGuardedBySeed`.\n */\nexport interface ListenHandle {\n readonly [listenHandleBrand]: true\n}\n\ninterface HandleState {\n token: Token | null\n}\n\n/** A handle for one hook instance. Create it once (`useState(createListenHandle)`). */\nexport function createListenHandle(): ListenHandle {\n const state: HandleState = { token: null }\n return state as unknown as ListenHandle\n}\n\nconst unconfirmed = new Set<Token>()\nconst waiters = new Set<Waiter>()\nconst seedWaiters = new Set<SeedWaiter>()\n\nfunction settleWaiters(token: Token, how: { changed?: boolean; lost?: boolean }) {\n for (const waiter of [...waiters]) {\n if (!waiter.pending.delete(token)) continue\n if (how.changed) waiter.refreshed = true\n if (how.lost) waiter.lost = true\n if (waiter.pending.size > 0) continue\n if (waiter.lost) waiter.finish('unconfirmed')\n else waiter.finish(waiter.refreshed ? 'refreshed' : 'confirmed')\n }\n}\n\nfunction settleSeedWaiters(token: Token) {\n for (const waiter of [...seedWaiters]) {\n if (waiter.handle.token !== token) continue\n waiter.finish(token.changed ? 'refreshed' : 'confirmed')\n }\n}\n\nexport interface ListenConfirmation {\n /**\n * A snapshot arrived. `changed` says a confirmation brought different values\n * from the ones this listener had shown; a first answer showed nothing, so\n * it cannot have changed anything.\n *\n * Returns the `fromCache` the hook reports: the snapshot's own, except that\n * a cached snapshot following a confirmation reads `false` while the\n * confirmation is kept (AGL-4047).\n */\n report: (fromCache: boolean, changed?: boolean) => boolean\n /**\n * The listener was refused. A wait on every listener ends unconfirmed; a wait\n * on this one goes on, for the retry.\n */\n release: () => void\n /**\n * The listener was torn down. As `release`, and its handle no longer points\n * at it, so a wait on this one goes on for the listener that replaces it.\n */\n close: () => void\n}\n\nexport interface TrackListenOptions {\n /**\n * A confirmation kept through a fall back to the cache has lapsed: the hook\n * reports `fromCache: true` from now on, until the server answers.\n */\n onLapse?: () => void\n}\n\n/**\n * One listener's line in the record. Unconfirmed from the start, for the same\n * reason every hook's `fromCache` state starts true. With `handle`, the handle\n * points at this listener from now on.\n */\nexport function trackListenConfirmation(\n handle?: ListenHandle,\n options: TrackListenOptions = {},\n): ListenConfirmation {\n let keepTimer: ReturnType<typeof setTimeout> | null = null\n const endKeep = () => {\n if (keepTimer) clearTimeout(keepTimer)\n keepTimer = null\n token.keptUntil = null\n }\n const unconfirm = () => {\n token.state = 'unconfirmed'\n token.changed = false\n unconfirmed.add(token)\n }\n const token: Token = {\n state: 'unconfirmed',\n changed: false,\n keptUntil: null,\n lapse: () => {\n if (token.keptUntil === null) return\n endKeep()\n if (token.state !== 'confirmed') return\n unconfirm()\n options.onLapse?.()\n },\n }\n unconfirmed.add(token)\n const bound = handle as unknown as HandleState | undefined\n if (bound) bound.token = token\n const release = () => {\n endKeep()\n token.state = 'released'\n token.changed = false\n unconfirmed.delete(token)\n settleWaiters(token, { lost: true })\n }\n return {\n report: (fromCache, changed = false) => {\n if (fromCache) {\n // Confirmed, and now the cache's: the client's online state moved,\n // not the values. Kept, from the first such snapshot (AGL-4047).\n if (token.state === 'confirmed' && confirmationKeptMs > 0) {\n if (token.keptUntil === null) {\n token.keptUntil = Date.now() + confirmationKeptMs\n keepTimer = setTimeout(token.lapse, confirmationKeptMs)\n }\n if (Date.now() < token.keptUntil) return false\n token.lapse()\n return true\n }\n endKeep()\n unconfirm()\n return true\n }\n endKeep()\n token.state = 'confirmed'\n token.changed = changed\n unconfirmed.delete(token)\n settleWaiters(token, { changed })\n settleSeedWaiters(token)\n return false\n },\n release,\n close: () => {\n release()\n if (bound?.token === token) bound.token = null\n },\n }\n}\n\n/**\n * Whether the listener `handle` points at is on a kept confirmation whose\n * deadline the wall clock has passed (AGL-4047): a device that slept, or a tab\n * whose timers were held back, has not run the lapse yet. It lapses now, so\n * the caller treats the seed as unconfirmed and waits for the server.\n */\nexport function lapseOverdueConfirmation(handle: ListenHandle): boolean {\n const token = (handle as unknown as HandleState).token\n if (!token || token.keptUntil === null || Date.now() < token.keptUntil) {\n return false\n }\n token.lapse()\n return token.state === 'unconfirmed'\n}\n\n/**\n * Resolves when every listener unconfirmed right now has settled, or after\n * `timeoutMs`. Never rejects.\n */\nexport function whenListensConfirmed(\n timeoutMs: number = confirmWaitMs,\n): Promise<ListenSettlement> {\n if (unconfirmed.size === 0) return Promise.resolve('untracked')\n return new Promise((resolve) => {\n const waiter: Waiter = {\n pending: new Set(unconfirmed),\n refreshed: false,\n lost: false,\n finish: (settlement) => {\n clearTimeout(timer)\n waiters.delete(waiter)\n resolve(settlement)\n },\n }\n const timer = setTimeout(() => waiter.finish('unconfirmed'), timeoutMs)\n waiters.add(waiter)\n })\n}\n\n/**\n * Resolves when the listener `handle` points at is confirmed, or after\n * `timeoutMs` (AGL-4135). Never rejects.\n *\n * - **Already confirmed**: at once, `refreshed` if that confirmation changed\n * the values on screen. The caller read `fromCache` before it landed. A\n * confirmation kept through a fall back to the cache counts, until its\n * deadline (AGL-4047); past it, the listener is unconfirmed and waited on.\n * - **Unconfirmed, refused or torn down**: waits. A refused listener retries\n * and reports again; a torn-down one is replaced, and the handle points at\n * the replacement. Neither is ever taken for a confirmation.\n * - **No listener behind the handle** (its hook has not listened, or has\n * stopped): `untracked`, so the caller's answer stands.\n */\nexport function whenListenConfirmed(\n handle: ListenHandle,\n timeoutMs: number = confirmWaitMs,\n): Promise<ListenSettlement> {\n const state = handle as unknown as HandleState\n const token = state.token\n if (!token) return Promise.resolve('untracked')\n lapseOverdueConfirmation(handle)\n if (token.state === 'confirmed') {\n return Promise.resolve(token.changed ? 'refreshed' : 'confirmed')\n }\n return new Promise((resolve) => {\n const waiter: SeedWaiter = {\n handle: state,\n finish: (settlement) => {\n clearTimeout(timer)\n seedWaiters.delete(waiter)\n resolve(settlement)\n },\n }\n const timer = setTimeout(() => waiter.finish('unconfirmed'), timeoutMs)\n seedWaiters.add(waiter)\n })\n}\n"],"names":["SEED_CONFIRM_WAIT_MS","confirmWaitMs","setSeedConfirmWaitMs","ms","seedConfirmWaitMs","SEED_CONFIRMATION_KEPT_MS","confirmationKeptMs","setSeedConfirmationKeptMs","sameDocument","a","b","exists","JSON","stringify","data","createListenHandle","state","token","unconfirmed","Set","waiters","seedWaiters","settleWaiters","how","waiter","pending","delete","changed","refreshed","lost","size","finish","settleSeedWaiters","handle","trackListenConfirmation","options","keepTimer","endKeep","clearTimeout","keptUntil","unconfirm","add","lapse","onLapse","bound","release","report","fromCache","Date","now","setTimeout","close","lapseOverdueConfirmation","whenListensConfirmed","timeoutMs","Promise","resolve","settlement","timer","whenListenConfirmed"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyEC,GAED;;;;CAIC,GACD,OAAO,MAAMA,uBAAuB,MAAM;AAE1C,IAAIC,gBAAgBD;AAEpB;;;;CAIC,GACD,OAAO,SAASE,qBAAqBC,KAAaH,oBAAoB;IACpEC,gBAAgBE;AAClB;AAEA;;;;CAIC,GACD,OAAO,SAASC;IACd,OAAOH;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,MAAMI,4BAA4B,MAAM;AAE/C,IAAIC,qBAAqBD;AAEzB;;;;CAIC,GACD,OAAO,SAASE,0BACdJ,KAAaE,yBAAyB;IAEtCC,qBAAqBH;AACvB;AAQA;;;;CAIC,GACD,OAAO,SAASK,aAAaC,CAAiB,EAAEC,CAAiB;IAC/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,7 +80,13 @@ const MAX_RETRIES = 5;
|
|
|
80
80
|
* that precedes every reopened refusal (AGL-1066). See the longer note
|
|
81
81
|
* on the same variable in `use-firestore-collection`.
|
|
82
82
|
*/ let terminal = false;
|
|
83
|
-
/** What a save waits on while this listener is unconfirmed (AGL-4120). */ const confirmation = trackListenConfirmation(listen
|
|
83
|
+
/** What a save waits on while this listener is unconfirmed (AGL-4120). */ const confirmation = trackListenConfirmation(listen, {
|
|
84
|
+
// A confirmation kept through a fall back to the cache ran out
|
|
85
|
+
// before the server answered again (AGL-4047).
|
|
86
|
+
onLapse: ()=>{
|
|
87
|
+
if (!cancelled) setFromCache(true);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
84
90
|
/** The cached snapshot on screen, while one is (AGL-4120). */ let shownFromCache = null;
|
|
85
91
|
const subscribe = ()=>{
|
|
86
92
|
unsubscribe = onSnapshot(ref, // Without this the cache→server confirmation is never delivered and
|
|
@@ -121,8 +127,9 @@ const MAX_RETRIES = 5;
|
|
|
121
127
|
// (AGL-1262). Callers that record a "last saved" state need to
|
|
122
128
|
// know the difference.
|
|
123
129
|
setHasPendingWrites(snapshot.metadata.hasPendingWrites);
|
|
124
|
-
|
|
125
|
-
|
|
130
|
+
// The snapshot's own, unless it is a short fall back to the cache
|
|
131
|
+
// after a confirmation, which keeps it (AGL-4047).
|
|
132
|
+
setFromCache(confirmation.report(snapshot.metadata.fromCache, !snapshot.metadata.fromCache && shownFromCache !== null && !sameDocument(shownFromCache, snapshot)));
|
|
126
133
|
shownFromCache = snapshot.metadata.fromCache ? snapshot : null;
|
|
127
134
|
const value = snapshot.exists() ? _extends({}, snapshot.data(), idField ? {
|
|
128
135
|
[idField]: snapshot.id
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/helpers/use-doc.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2022 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 onSnapshot,\n type DocumentData,\n type DocumentReference,\n type DocumentSnapshot,\n} from 'firebase/firestore'\nimport { useEffect, useRef, useState } from 'react'\nimport type { ObservableStatus, FirestoreDocOptions } from '../firebase/firebase-services'\nimport {\n DENIAL_STREAK_TO_REPORT,\n noteFirestoreServerRead,\n scheduleRefusedReopen,\n subscribeFirestoreSessionHeal,\n} from '../firestore-denial-reporter'\nimport {\n createListenHandle,\n sameDocument,\n trackListenConfirmation,\n} from './listen-confirmation'\nimport { CONFIRMABLE_LISTEN_OPTIONS } from './listen-options'\nimport useModifyDocCallback, {\n type UseModifyDocCallback,\n} from './use-modify-doc-callback'\n\nconst RETRY_DELAY_MS = 400\nconst MAX_RETRIES = 5\n// The refused cadence is shared policy — see `scheduleRefusedReopen` in\n// `firestore-denial-reporter.ts` (AGL-1066, AGL-1440, AGL-2944, AGL-2945).\n\n/**\n * Raw `onSnapshot` listener with its own retry/backoff instead of\n * reactfire's `useFirestoreDocData` — that hook caches the query's RxJS\n * Observable, and once it errors the Observable is *terminated forever*:\n * remounting the component never reopens the Firestore subscription, so a\n * single transient `permission-denied` (e.g. right after sign-in, before\n * Firestore's own credential provider has attached the user's ID token)\n * permanently breaks every caller of `useHost`/`useLayout`/`useScreen`/\n * `useScreenVersion`/`useLayoutVersion` for the rest of the session\n * (AGL-216/217/223). A fresh `onSnapshot` call each retry opens a genuinely\n * new listener, so it recovers once the token has propagated.\n */\nexport function useDocData<T>(\n ref: DocumentReference<T>,\n options?: FirestoreDocOptions<T>,\n): ObservableStatus<T> {\n const idField = options?.idField\n const initialData = options?.initialData\n const [status, setStatus] = useState<'loading' | 'error' | 'success'>(\n initialData !== undefined ? 'success' : 'loading',\n )\n const [data, setData] = useState<T>(initialData as T)\n const [error, setError] = useState<Error | undefined>(undefined)\n const [hasEmitted, setHasEmitted] = useState(initialData !== undefined)\n const [hasPendingWrites, setHasPendingWrites] = useState(false)\n // Un-confirmed until a snapshot says otherwise (AGL-1066).\n const [fromCache, setFromCache] = useState(true)\n const [serverDenied, setServerDenied] = useState(false)\n const [listen] = useState(createListenHandle)\n const resolveFirstValueRef = useRef<(() => void) | undefined>(undefined)\n const firstValuePromiseRef = useRef<Promise<void> | undefined>(undefined)\n if (!firstValuePromiseRef.current) {\n firstValuePromiseRef.current = new Promise((resolve) => {\n resolveFirstValueRef.current = resolve\n })\n }\n\n useEffect(() => {\n setStatus('loading')\n setError(undefined)\n\n let cancelled = false\n let unsubscribe: (() => void) | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n /** Cancels a pending reopen on the refused cadence (AGL-2944). */\n let cancelRefusedReopen: (() => void) | null = null\n let attempt = 0\n /**\n * Refusals since the last SERVER snapshot (AGL-1066).\n *\n * Still distinct from `attempt` after the flip: `attempt` is a BUDGET\n * that the heal broadcast may refund, whereas this is EVIDENCE about the\n * server that only a server snapshot may clear. Counted here to publish\n * `serverDenied` and to decide the slow cadence — the `session-health`\n * reporting the other two listener hooks do is a separate decision, and\n * this hook's callers (the besigner document family) are exactly the ones\n * a false verdict would hurt most.\n */\n let deniedStreak = 0\n /** Epoch ms of the current streak's first refusal (AGL-1440). */\n let deniedStreakStartedAt = 0\n /**\n * The retry budget is spent and the server's last word was a refusal —\n * what keeps `status: 'error'` from being undone by the cached emission\n * that precedes every reopened refusal (AGL-1066). See the longer note\n * on the same variable in `use-firestore-collection`.\n */\n let terminal = false\n /** What a save waits on while this listener is unconfirmed (AGL-4120). */\n const confirmation = trackListenConfirmation(listen)\n /** The cached snapshot on screen, while one is (AGL-4120). */\n let shownFromCache: DocumentSnapshot<DocumentData> | null = null\n\n const subscribe = () => {\n unsubscribe = onSnapshot(\n ref,\n // Without this the cache→server confirmation is never delivered and\n // `fromCache` latches true for the life of the listener, refusing\n // every guarded save on the page (AGL-2486). See `listen-options.ts`.\n CONFIRMABLE_LISTEN_OPTIONS,\n (snapshot) => {\n if (cancelled) return\n // Only the SERVER answering refunds the retry budget, and only a\n // server snapshot ends a refusal (AGL-1066).\n if (!snapshot.metadata.fromCache) {\n attempt = 0\n terminal = false\n deniedStreak = 0\n setServerDenied(false)\n // Evidence only, deliberately not the reporting call: this hook\n // stays out of `session-health` (see `deniedStreak` above), but\n // its server answers are still proof the session can read, which\n // is what `refusedRetryDelayMs` splits the cadence on (AGL-1440).\n noteFirestoreServerRead()\n } else if (deniedStreak === 0) {\n // Cached, but nothing has been refused since the server last\n // answered — not the AGL-1066 fault, so the budget is refunded\n // exactly as it always was. This is what keeps offline inert:\n // `unavailable` never enters `deniedStreak`.\n attempt = 0\n }\n if (!terminal) {\n setStatus('success')\n setError(undefined)\n }\n // Always true after ANY emission, cached included: this is what\n // tells a consumer \"I have data, the server refused\" apart from \"I\n // never had data\" — the distinction the besigner editors and the\n // host setup Theme tab blank on (AGL-1066).\n setHasEmitted(true)\n // Kept, not dropped: a snapshot that still carries this client's\n // own queued write is not evidence of what the store holds\n // (AGL-1262). Callers that record a \"last saved\" state need to\n // know the difference.\n setHasPendingWrites(snapshot.metadata.hasPendingWrites)\n setFromCache(snapshot.metadata.fromCache)\n confirmation.report(\n snapshot.metadata.fromCache,\n !snapshot.metadata.fromCache &&\n shownFromCache !== null &&\n !sameDocument(shownFromCache, snapshot),\n )\n shownFromCache = snapshot.metadata.fromCache ? snapshot : null\n const value = snapshot.exists()\n ? ({\n ...(snapshot.data() as object),\n ...(idField ? { [idField]: snapshot.id } : {}),\n } as T)\n : (undefined as T)\n setData(value)\n resolveFirstValueRef.current?.()\n },\n (err) => {\n if (cancelled) return\n confirmation.release()\n unsubscribe?.()\n // Only a refusal — a lost network produces no error callback at\n // all, and anything that does surface one carries `unavailable`,\n // which must never read as a dead session.\n if ((err as { code?: string })?.code === 'permission-denied') {\n deniedStreak += 1\n if (deniedStreak === 1) deniedStreakStartedAt = Date.now()\n if (deniedStreak >= DENIAL_STREAK_TO_REPORT) setServerDenied(true)\n }\n if (attempt < MAX_RETRIES) {\n attempt += 1\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n } else {\n timer = setTimeout(subscribe, RETRY_DELAY_MS)\n }\n } else {\n terminal = true\n setStatus('error')\n setError(err)\n resolveFirstValueRef.current?.()\n // A refusal streak keeps a slow road back for a recovery nobody\n // announced — see the same branch in `use-firestore-collection`.\n // The cadence splits on session-vs-ref evidence (AGL-1440), grows\n // with the streak's age (AGL-2945) and waits while the tab is\n // hidden (AGL-2944).\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n }\n }\n },\n )\n }\n subscribe()\n\n /**\n * Reopen when the session heals — see the long note on the same\n * subscription in `use-firestore-collection` (AGL-1066).\n *\n * This hook is where it counts most: its deps are `[ref.firestore,\n * ref.path]`, neither of which moves when a `stale` re-auth signs the\n * same uid back in, and it is what every besigner editor reads through.\n * Nothing else was ever going to bring those pages back without a reload.\n */\n const unsubscribeHeal = subscribeFirestoreSessionHeal(() => {\n if (cancelled || deniedStreak === 0) return\n if (timer) {\n clearTimeout(timer)\n timer = null\n }\n cancelRefusedReopen?.()\n cancelRefusedReopen = null\n unsubscribe?.()\n attempt = 0\n subscribe()\n })\n\n return () => {\n cancelled = true\n confirmation.close()\n unsubscribeHeal()\n if (timer) clearTimeout(timer)\n cancelRefusedReopen?.()\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [ref.firestore, ref.path])\n\n return {\n status,\n hasEmitted,\n isComplete: false,\n data,\n error,\n firstValuePromise: firstValuePromiseRef.current,\n hasPendingWrites,\n fromCache,\n serverDenied,\n listen,\n }\n}\nexport type UseDocData<T> = typeof useDocData<T>\n\nexport function useDoc<T>(\n ref: DocumentReference<T>,\n options?: FirestoreDocOptions<T>,\n): {doc: ReturnType<UseDocData<T>>, setDoc: ReturnType<UseModifyDocCallback<T>>} {\n return {doc: useDocData(ref, options), setDoc: useModifyDocCallback(ref)}\n}\n\n\nexport default useDoc\n"],"names":["onSnapshot","useEffect","useRef","useState","DENIAL_STREAK_TO_REPORT","noteFirestoreServerRead","scheduleRefusedReopen","subscribeFirestoreSessionHeal","createListenHandle","sameDocument","trackListenConfirmation","CONFIRMABLE_LISTEN_OPTIONS","useModifyDocCallback","RETRY_DELAY_MS","MAX_RETRIES","useDocData","ref","options","idField","initialData","status","setStatus","undefined","data","setData","error","setError","hasEmitted","setHasEmitted","hasPendingWrites","setHasPendingWrites","fromCache","setFromCache","serverDenied","setServerDenied","listen","resolveFirstValueRef","firstValuePromiseRef","current","Promise","resolve","cancelled","unsubscribe","timer","cancelRefusedReopen","attempt","deniedStreak","deniedStreakStartedAt","terminal","confirmation","shownFromCache","subscribe","snapshot","metadata","report","value","exists","id","err","release","code","Date","now","setTimeout","unsubscribeHeal","clearTimeout","close","firestore","path","isComplete","firstValuePromise","useDoc","doc","setDoc"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,QAIL,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAEnD,SACEC,uBAAuB,EACvBC,uBAAuB,EACvBC,qBAAqB,EACrBC,6BAA6B,QACxB,kCAA8B;AACrC,SACEC,kBAAkB,EAClBC,YAAY,EACZC,uBAAuB,QAClB,2BAAuB;AAC9B,SAASC,0BAA0B,QAAQ,sBAAkB;AAC7D,OAAOC,0BAEA,+BAA2B;AAElC,MAAMC,iBAAiB;AACvB,MAAMC,cAAc;AACpB,wEAAwE;AACxE,2EAA2E;AAE3E;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,WACdC,GAAyB,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eAAeuD,OAAM"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/helpers/use-doc.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2022 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 onSnapshot,\n type DocumentData,\n type DocumentReference,\n type DocumentSnapshot,\n} from 'firebase/firestore'\nimport { useEffect, useRef, useState } from 'react'\nimport type { ObservableStatus, FirestoreDocOptions } from '../firebase/firebase-services'\nimport {\n DENIAL_STREAK_TO_REPORT,\n noteFirestoreServerRead,\n scheduleRefusedReopen,\n subscribeFirestoreSessionHeal,\n} from '../firestore-denial-reporter'\nimport {\n createListenHandle,\n sameDocument,\n trackListenConfirmation,\n} from './listen-confirmation'\nimport { CONFIRMABLE_LISTEN_OPTIONS } from './listen-options'\nimport useModifyDocCallback, {\n type UseModifyDocCallback,\n} from './use-modify-doc-callback'\n\nconst RETRY_DELAY_MS = 400\nconst MAX_RETRIES = 5\n// The refused cadence is shared policy — see `scheduleRefusedReopen` in\n// `firestore-denial-reporter.ts` (AGL-1066, AGL-1440, AGL-2944, AGL-2945).\n\n/**\n * Raw `onSnapshot` listener with its own retry/backoff instead of\n * reactfire's `useFirestoreDocData` — that hook caches the query's RxJS\n * Observable, and once it errors the Observable is *terminated forever*:\n * remounting the component never reopens the Firestore subscription, so a\n * single transient `permission-denied` (e.g. right after sign-in, before\n * Firestore's own credential provider has attached the user's ID token)\n * permanently breaks every caller of `useHost`/`useLayout`/`useScreen`/\n * `useScreenVersion`/`useLayoutVersion` for the rest of the session\n * (AGL-216/217/223). A fresh `onSnapshot` call each retry opens a genuinely\n * new listener, so it recovers once the token has propagated.\n */\nexport function useDocData<T>(\n ref: DocumentReference<T>,\n options?: FirestoreDocOptions<T>,\n): ObservableStatus<T> {\n const idField = options?.idField\n const initialData = options?.initialData\n const [status, setStatus] = useState<'loading' | 'error' | 'success'>(\n initialData !== undefined ? 'success' : 'loading',\n )\n const [data, setData] = useState<T>(initialData as T)\n const [error, setError] = useState<Error | undefined>(undefined)\n const [hasEmitted, setHasEmitted] = useState(initialData !== undefined)\n const [hasPendingWrites, setHasPendingWrites] = useState(false)\n // Un-confirmed until a snapshot says otherwise (AGL-1066).\n const [fromCache, setFromCache] = useState(true)\n const [serverDenied, setServerDenied] = useState(false)\n const [listen] = useState(createListenHandle)\n const resolveFirstValueRef = useRef<(() => void) | undefined>(undefined)\n const firstValuePromiseRef = useRef<Promise<void> | undefined>(undefined)\n if (!firstValuePromiseRef.current) {\n firstValuePromiseRef.current = new Promise((resolve) => {\n resolveFirstValueRef.current = resolve\n })\n }\n\n useEffect(() => {\n setStatus('loading')\n setError(undefined)\n\n let cancelled = false\n let unsubscribe: (() => void) | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n /** Cancels a pending reopen on the refused cadence (AGL-2944). */\n let cancelRefusedReopen: (() => void) | null = null\n let attempt = 0\n /**\n * Refusals since the last SERVER snapshot (AGL-1066).\n *\n * Still distinct from `attempt` after the flip: `attempt` is a BUDGET\n * that the heal broadcast may refund, whereas this is EVIDENCE about the\n * server that only a server snapshot may clear. Counted here to publish\n * `serverDenied` and to decide the slow cadence — the `session-health`\n * reporting the other two listener hooks do is a separate decision, and\n * this hook's callers (the besigner document family) are exactly the ones\n * a false verdict would hurt most.\n */\n let deniedStreak = 0\n /** Epoch ms of the current streak's first refusal (AGL-1440). */\n let deniedStreakStartedAt = 0\n /**\n * The retry budget is spent and the server's last word was a refusal —\n * what keeps `status: 'error'` from being undone by the cached emission\n * that precedes every reopened refusal (AGL-1066). See the longer note\n * on the same variable in `use-firestore-collection`.\n */\n let terminal = false\n /** What a save waits on while this listener is unconfirmed (AGL-4120). */\n const confirmation = trackListenConfirmation(listen, {\n // A confirmation kept through a fall back to the cache ran out\n // before the server answered again (AGL-4047).\n onLapse: () => {\n if (!cancelled) setFromCache(true)\n },\n })\n /** The cached snapshot on screen, while one is (AGL-4120). */\n let shownFromCache: DocumentSnapshot<DocumentData> | null = null\n\n const subscribe = () => {\n unsubscribe = onSnapshot(\n ref,\n // Without this the cache→server confirmation is never delivered and\n // `fromCache` latches true for the life of the listener, refusing\n // every guarded save on the page (AGL-2486). See `listen-options.ts`.\n CONFIRMABLE_LISTEN_OPTIONS,\n (snapshot) => {\n if (cancelled) return\n // Only the SERVER answering refunds the retry budget, and only a\n // server snapshot ends a refusal (AGL-1066).\n if (!snapshot.metadata.fromCache) {\n attempt = 0\n terminal = false\n deniedStreak = 0\n setServerDenied(false)\n // Evidence only, deliberately not the reporting call: this hook\n // stays out of `session-health` (see `deniedStreak` above), but\n // its server answers are still proof the session can read, which\n // is what `refusedRetryDelayMs` splits the cadence on (AGL-1440).\n noteFirestoreServerRead()\n } else if (deniedStreak === 0) {\n // Cached, but nothing has been refused since the server last\n // answered — not the AGL-1066 fault, so the budget is refunded\n // exactly as it always was. This is what keeps offline inert:\n // `unavailable` never enters `deniedStreak`.\n attempt = 0\n }\n if (!terminal) {\n setStatus('success')\n setError(undefined)\n }\n // Always true after ANY emission, cached included: this is what\n // tells a consumer \"I have data, the server refused\" apart from \"I\n // never had data\" — the distinction the besigner editors and the\n // host setup Theme tab blank on (AGL-1066).\n setHasEmitted(true)\n // Kept, not dropped: a snapshot that still carries this client's\n // own queued write is not evidence of what the store holds\n // (AGL-1262). Callers that record a \"last saved\" state need to\n // know the difference.\n setHasPendingWrites(snapshot.metadata.hasPendingWrites)\n // The snapshot's own, unless it is a short fall back to the cache\n // after a confirmation, which keeps it (AGL-4047).\n setFromCache(\n confirmation.report(\n snapshot.metadata.fromCache,\n !snapshot.metadata.fromCache &&\n shownFromCache !== null &&\n !sameDocument(shownFromCache, snapshot),\n ),\n )\n shownFromCache = snapshot.metadata.fromCache ? snapshot : null\n const value = snapshot.exists()\n ? ({\n ...(snapshot.data() as object),\n ...(idField ? { [idField]: snapshot.id } : {}),\n } as T)\n : (undefined as T)\n setData(value)\n resolveFirstValueRef.current?.()\n },\n (err) => {\n if (cancelled) return\n confirmation.release()\n unsubscribe?.()\n // Only a refusal — a lost network produces no error callback at\n // all, and anything that does surface one carries `unavailable`,\n // which must never read as a dead session.\n if ((err as { code?: string })?.code === 'permission-denied') {\n deniedStreak += 1\n if (deniedStreak === 1) deniedStreakStartedAt = Date.now()\n if (deniedStreak >= DENIAL_STREAK_TO_REPORT) setServerDenied(true)\n }\n if (attempt < MAX_RETRIES) {\n attempt += 1\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n } else {\n timer = setTimeout(subscribe, RETRY_DELAY_MS)\n }\n } else {\n terminal = true\n setStatus('error')\n setError(err)\n resolveFirstValueRef.current?.()\n // A refusal streak keeps a slow road back for a recovery nobody\n // announced — see the same branch in `use-firestore-collection`.\n // The cadence splits on session-vs-ref evidence (AGL-1440), grows\n // with the streak's age (AGL-2945) and waits while the tab is\n // hidden (AGL-2944).\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n }\n }\n },\n )\n }\n subscribe()\n\n /**\n * Reopen when the session heals — see the long note on the same\n * subscription in `use-firestore-collection` (AGL-1066).\n *\n * This hook is where it counts most: its deps are `[ref.firestore,\n * ref.path]`, neither of which moves when a `stale` re-auth signs the\n * same uid back in, and it is what every besigner editor reads through.\n * Nothing else was ever going to bring those pages back without a reload.\n */\n const unsubscribeHeal = subscribeFirestoreSessionHeal(() => {\n if (cancelled || deniedStreak === 0) return\n if (timer) {\n clearTimeout(timer)\n timer = null\n }\n cancelRefusedReopen?.()\n cancelRefusedReopen = null\n unsubscribe?.()\n attempt = 0\n subscribe()\n })\n\n return () => {\n cancelled = true\n confirmation.close()\n unsubscribeHeal()\n if (timer) clearTimeout(timer)\n cancelRefusedReopen?.()\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [ref.firestore, ref.path])\n\n return {\n status,\n hasEmitted,\n isComplete: false,\n data,\n error,\n firstValuePromise: firstValuePromiseRef.current,\n hasPendingWrites,\n fromCache,\n serverDenied,\n listen,\n }\n}\nexport type UseDocData<T> = typeof useDocData<T>\n\nexport function useDoc<T>(\n ref: DocumentReference<T>,\n options?: FirestoreDocOptions<T>,\n): {doc: ReturnType<UseDocData<T>>, setDoc: ReturnType<UseModifyDocCallback<T>>} {\n return {doc: useDocData(ref, options), setDoc: useModifyDocCallback(ref)}\n}\n\n\nexport default useDoc\n"],"names":["onSnapshot","useEffect","useRef","useState","DENIAL_STREAK_TO_REPORT","noteFirestoreServerRead","scheduleRefusedReopen","subscribeFirestoreSessionHeal","createListenHandle","sameDocument","trackListenConfirmation","CONFIRMABLE_LISTEN_OPTIONS","useModifyDocCallback","RETRY_DELAY_MS","MAX_RETRIES","useDocData","ref","options","idField","initialData","status","setStatus","undefined","data","setData","error","setError","hasEmitted","setHasEmitted","hasPendingWrites","setHasPendingWrites","fromCache","setFromCache","serverDenied","setServerDenied","listen","resolveFirstValueRef","firstValuePromiseRef","current","Promise","resolve","cancelled","unsubscribe","timer","cancelRefusedReopen","attempt","deniedStreak","deniedStreakStartedAt","terminal","confirmation","onLapse","shownFromCache","subscribe","snapshot","metadata","report","value","exists","id","err","release","code","Date","now","setTimeout","unsubscribeHeal","clearTimeout","close","firestore","path","isComplete","firstValuePromise","useDoc","doc","setDoc"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,QAIL,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAEnD,SACEC,uBAAuB,EACvB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A,IAAItB,OAAOuB,aAAavB;YACxBC,uCAAAA;YACAF,+BAAAA;QACF;IACA,uDAAuD;IACzD,GAAG;QAAC1B,IAAIoD,SAAS;QAAEpD,IAAIqD,IAAI;KAAC;IAE5B,OAAO;QACLjD;QACAO;QACA2C,YAAY;QACZ/C;QACAE;QACA8C,mBAAmBlC,qBAAqBC,OAAO;QAC/CT;QACAE;QACAE;QACAE;IACF;AACF;AAGA,OAAO,SAASqC,OACdxD,GAAyB,EACzBC,OAAgC;IAEhC,OAAO;QAACwD,KAAK1D,WAAWC,KAAKC;QAAUyD,QAAQ9D,qBAAqBI;IAAI;AAC1E;AAGA,eAAewD,OAAM"}
|
|
@@ -119,11 +119,22 @@ const MAX_RETRY_DELAY_MS = 15000;
|
|
|
119
119
|
let confirmTimer = null;
|
|
120
120
|
let confirmRequested = false;
|
|
121
121
|
const ref = doc(firestore, pathKey);
|
|
122
|
-
/** What a save waits on while this read is unconfirmed (AGL-4120). */ const confirmation = trackListenConfirmation(
|
|
122
|
+
/** What a save waits on while this read is unconfirmed (AGL-4120). */ const confirmation = trackListenConfirmation(undefined, {
|
|
123
|
+
// A confirmation kept through a fall back to the cache ran out
|
|
124
|
+
// before the server answered again (AGL-4047).
|
|
125
|
+
onLapse: ()=>{
|
|
126
|
+
if (cancelled) return;
|
|
127
|
+
setState((current)=>current.fromCache ? current : _extends({}, current, {
|
|
128
|
+
fromCache: true
|
|
129
|
+
}));
|
|
130
|
+
}
|
|
131
|
+
});
|
|
123
132
|
/** The cached values on screen, while they are (AGL-4120). */ let shownFromCache;
|
|
124
133
|
const deliver = (exists, id, payload, fromCache)=>{
|
|
125
134
|
const values = JSON.stringify(exists ? payload != null ? payload : null : undefined);
|
|
126
|
-
|
|
135
|
+
// The snapshot's own, unless it is a short fall back to the cache
|
|
136
|
+
// after a confirmation, which keeps it (AGL-4047).
|
|
137
|
+
const shown = confirmation.report(fromCache, !fromCache && shownFromCache !== undefined && shownFromCache !== values);
|
|
127
138
|
shownFromCache = fromCache ? values != null ? values : 'missing' : undefined;
|
|
128
139
|
setState({
|
|
129
140
|
data: exists ? _extends({
|
|
@@ -131,7 +142,7 @@ const MAX_RETRY_DELAY_MS = 15000;
|
|
|
131
142
|
}, payload) : undefined,
|
|
132
143
|
ready: true,
|
|
133
144
|
error: false,
|
|
134
|
-
fromCache
|
|
145
|
+
fromCache: shown
|
|
135
146
|
});
|
|
136
147
|
};
|
|
137
148
|
const subscribe = ()=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-confirmed-doc.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'use client'\n\nimport {\n doc,\n getDocFromServer,\n onSnapshot,\n type DocumentData,\n type DocumentReference,\n type DocumentSnapshot,\n type Firestore,\n} from 'firebase/firestore'\nimport { useEffect, useState } from 'react'\nimport { trackListenConfirmation } from './helpers/listen-confirmation'\n\nconst RETRY_DELAY_MS = 400\nconst MAX_RETRIES = 8\nconst MAX_RETRY_DELAY_MS = 15_000\n\nexport interface ConfirmedDocState<T> {\n /** The doc's data (with `$id`), or undefined while loading / when absent. */\n data: T | undefined\n /**\n * True once an answer worth acting on has arrived: any snapshot that has\n * data, or a MISS the server itself has confirmed. Consumers must not\n * 404, fall back to a default, or otherwise treat \"no doc\" as real until\n * this is true.\n */\n ready: boolean\n /** True only when retries were exhausted — offer a retry, never a 404. */\n error: boolean\n /**\n * `data` is being served from the local cache and the server has not\n * confirmed it (AGL-1066). Never a reason to withhold the value — only a\n * reason not to let it decide something irreversible.\n */\n fromCache: boolean\n}\n\nexport interface UseConfirmedDocOptions {\n /**\n * Also confirm a cache-served hit that EXISTS, not just a miss (AGL-1066).\n *\n * The base contract trusts any snapshot that exists, whatever its source.\n * That is right for ordinary content — the value was legitimately the\n * user's a moment ago, and blanking it costs more than it buys. It is NOT\n * right for the entitlement doc: `orgs/{orgId}` is the only plan source\n * (AGL-238), and a cached copy from before a plan change renders the org\n * at the wrong tier for as long as the session stays stale. AGL-887 closed\n * the tombstone direction of exactly this fault (a Business workspace\n * rendering as Free); this closes the stale-EXISTS direction.\n *\n * Opt-in because it can cost one extra server read, and only when the\n * listener has actually failed to reach the server — see the deferral in\n * the implementation. Enable it for entitlement-shaped documents only.\n */\n confirmCachedHit?: boolean\n}\n\n/**\n * How long a cached hit is allowed to stand before it is confirmed.\n *\n * Not zero, and this is the whole reason the option is affordable: on a\n * healthy load the first snapshot is routinely from cache and the server\n * snapshot follows within milliseconds. Confirming immediately would bill an\n * extra read on every mount for every user; waiting means the confirm fires\n * only when the server genuinely did not answer.\n */\nconst CONFIRM_CACHED_HIT_DELAY_MS = 1_500\n\n/**\n * Confirms in flight, keyed by document path (AGL-1440).\n *\n * `useCurrentOrg` is a plain hook, not a context, and the console chrome mounts\n * it seven-plus times per page — user menu, org switcher, branding, and three\n * separate paths through `ConsolePluginsGate`. The `onSnapshot`s are nearly\n * free, because the SDK serves identical listens off ONE target; the confirms\n * are not. Each instance scheduled its own `getDocFromServer`, so a console\n * page load billed seven server reads of `orgs/{orgId}` to answer one question.\n *\n * Sharing the PROMISE, rather than suppressing the duplicates, is what keeps\n * this behaviour-preserving: every instance still resolves from a real server\n * snapshot and still calls `deliver(..., fromCache: false)`, so none of them is\n * left displaying a value flagged unconfirmed. Suppressing instead would leave\n * the six quiet instances on `fromCache: true` forever, which is a state\n * consumers are told means \"do not let this decide anything irreversible\".\n *\n * The entry is dropped as soon as it settles, so this is a burst collapser and\n * nothing more: a mount two seconds later asks the server again, exactly as it\n * does today. NOTHING about the entitlement is cached — this shares one READ\n * of the org document; every consumer evaluates the plan off it as before.\n */\nconst confirmsInFlight = new Map<\n string,\n Promise<DocumentSnapshot<DocumentData>>\n>()\n\n/** The server's copy of `ref`, shared with any confirm already in flight. */\nfunction sharedConfirm(\n pathKey: string,\n ref: DocumentReference,\n): Promise<DocumentSnapshot<DocumentData>> {\n const existing = confirmsInFlight.get(pathKey)\n if (existing) return existing\n const pending = getDocFromServer(ref).finally(() => {\n confirmsInFlight.delete(pathKey)\n })\n confirmsInFlight.set(pathKey, pending)\n return pending\n}\n\n/** Test seam — the in-flight map is module scope by design. */\nexport function resetConfirmedDocSharing(): void {\n confirmsInFlight.clear()\n}\n\n/**\n * A doc listen that never presents an unconfirmed miss (AGL-928).\n *\n * This is the shared form of the contract four consumers learned the hard\n * way (AGL-813/827/875/886/887): the console's multi-tab IndexedDB\n * persistence can serve a stale `noDocument` tombstone for a LIVE doc, and\n * a resumed listen never re-sends the correction — so `exists() === false`\n * from cache looks confirmed while being wrong. Symptoms ranged from valid\n * hosts 404ing to a Business workspace rendering as Free.\n *\n * Contract implemented here:\n * - Subscribe with a raw `onSnapshot` + exponential-backoff resubscribe:\n * right after sign-in (and on cold loads behind App Check) the first\n * listen can sit in transient `permission-denied` before the ID token\n * attaches (AGL-216); reactfire's cached Observable would replay that\n * error forever.\n * - A snapshot that EXISTS is trusted immediately, whatever its source.\n * - A snapshot that is MISSING and came from cache is confirmed via\n * `getDocFromServer` before it is believed; a failed confirm leaves\n * `ready` false rather than lying.\n * - Exhausted retries set `error` (and `ready`) so consumers can offer\n * \"try again\" — never a false 404 or a fallback default.\n *\n * For QUERY listens the same contract lives in `useOrgHosts` (empty →\n * `getDocsFromServer` confirm); extract it the same way if a third query\n * consumer appears.\n *\n * @param segments Doc path segments (`['orgs', orgId]`), or null to idle\n * (state resets while null, matching \"clear on scope change\").\n */\nexport function useConfirmedDoc<T extends Record<string, unknown>>(\n firestore: Firestore,\n segments: readonly [string, ...string[]] | null,\n options: UseConfirmedDocOptions = {},\n): ConfirmedDocState<T> {\n const [state, setState] = useState<ConfirmedDocState<T>>({\n data: undefined,\n ready: false,\n error: false,\n fromCache: true,\n })\n // Effect key: a new path must tear down and restart the listen.\n const pathKey = segments ? segments.join('/') : null\n const confirmCachedHit = options.confirmCachedHit\n\n useEffect(() => {\n setState({ data: undefined, ready: false, error: false, fromCache: true })\n if (!pathKey) return\n\n let cancelled = false\n let unsubscribe: (() => void) | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n let attempt = 0\n // One confirm per mount, and never once the server has answered.\n let confirmTimer: ReturnType<typeof setTimeout> | null = null\n let confirmRequested = false\n const ref = doc(firestore, pathKey)\n /** What a save waits on while this read is unconfirmed (AGL-4120). */\n const confirmation = trackListenConfirmation()\n /** The cached values on screen, while they are (AGL-4120). */\n let shownFromCache: string | undefined\n\n const deliver = (\n exists: boolean,\n id: string,\n payload: Record<string, unknown> | undefined,\n fromCache: boolean,\n ) => {\n const values = JSON.stringify(exists ? (payload ?? null) : undefined)\n confirmation.report(\n fromCache,\n !fromCache && shownFromCache !== undefined && shownFromCache !== values,\n )\n shownFromCache = fromCache ? (values ?? 'missing') : undefined\n setState({\n data: exists ? ({ $id: id, ...payload } as unknown as T) : undefined,\n ready: true,\n error: false,\n fromCache,\n })\n }\n\n const subscribe = () => {\n unsubscribe = onSnapshot(\n ref,\n (snapshot) => {\n if (cancelled) return\n attempt = 0\n const fromCache = snapshot.metadata.fromCache\n if (!fromCache && confirmTimer) {\n // The server answered on its own; nothing left to confirm.\n clearTimeout(confirmTimer)\n confirmTimer = null\n }\n if (!snapshot.exists() && fromCache) {\n // Unconfirmed miss: ask the server before believing it. On\n // failure stay un-ready — the listener remains subscribed and\n // the next (server) snapshot resolves it.\n void sharedConfirm(pathKey, ref)\n .then((server) => {\n if (cancelled) return\n deliver(server.exists(), server.id, server.data(), false)\n })\n .catch(() => undefined)\n return\n }\n deliver(snapshot.exists(), snapshot.id, snapshot.data(), fromCache)\n\n /**\n * Unconfirmed HIT (AGL-1066), for entitlement-shaped docs only.\n *\n * The value is already delivered above and stays on screen\n * whatever happens here — this never blanks the page and never\n * holds `ready` false, because a transient blip must not become a\n * wrong tier OR a 404. It only replaces a cached answer with the\n * server's when the server can be reached.\n */\n if (\n confirmCachedHit &&\n fromCache &&\n snapshot.exists() &&\n !confirmRequested &&\n !confirmTimer\n ) {\n confirmTimer = setTimeout(() => {\n confirmTimer = null\n confirmRequested = true\n void sharedConfirm(pathKey, ref)\n .then((server) => {\n if (cancelled) return\n deliver(server.exists(), server.id, server.data(), false)\n })\n // Could not reach the server: keep showing the cached value,\n // still flagged `fromCache`. Refusing to answer would be the\n // stale-`ready` false-404 this hook exists to prevent.\n .catch(() => undefined)\n }, CONFIRM_CACHED_HIT_DELAY_MS)\n }\n },\n () => {\n if (cancelled) return\n unsubscribe?.()\n if (attempt < MAX_RETRIES) {\n const delay = Math.min(\n RETRY_DELAY_MS * 2 ** attempt,\n MAX_RETRY_DELAY_MS,\n )\n attempt += 1\n timer = setTimeout(subscribe, delay)\n } else {\n setState({\n data: undefined,\n ready: true,\n error: true,\n fromCache: true,\n })\n }\n },\n )\n }\n subscribe()\n\n return () => {\n cancelled = true\n confirmation.release()\n if (timer) clearTimeout(timer)\n if (confirmTimer) clearTimeout(confirmTimer)\n unsubscribe?.()\n }\n }, [firestore, pathKey, confirmCachedHit])\n\n return state\n}\n\nexport default useConfirmedDoc\n"],"names":["doc","getDocFromServer","onSnapshot","useEffect","useState","trackListenConfirmation","RETRY_DELAY_MS","MAX_RETRIES","MAX_RETRY_DELAY_MS","CONFIRM_CACHED_HIT_DELAY_MS","confirmsInFlight","Map","sharedConfirm","pathKey","ref","existing","get","pending","finally","delete","set","resetConfirmedDocSharing","clear","useConfirmedDoc","firestore","segments","options","state","setState","data","undefined","ready","error","fromCache","join","confirmCachedHit","cancelled","unsubscribe","timer","attempt","confirmTimer","confirmRequested","confirmation","shownFromCache","deliver","exists","id","payload","values","JSON","stringify","report","$id","subscribe","snapshot","metadata","clearTimeout","then","server","catch","setTimeout","delay","Math","min","release"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,GAAG,EACHC,gBAAgB,EAChBC,UAAU,QAKL,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAC3C,SAASC,uBAAuB,QAAQ,mCAA+B;AAEvE,MAAMC,iBAAiB;AACvB,MAAMC,cAAc;AACpB,MAAMC,qBAAqB;AA0C3B;;;;;;;;CAQC,GACD,MAAMC,8BAA8B;AAEpC;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,MAAMC,mBAAmB,IAAIC;AAK7B,2EAA2E,GAC3E,SAASC,cACPC,OAAe,EACfC,GAAsB;IAEtB,MAAMC,WAAWL,iBAAiBM,GAAG,CAACH;IACtC,IAAIE,UAAU,OAAOA;IACrB,MAAME,UAAUhB,iBAAiBa,KAAKI,OAAO,CAAC;QAC5CR,iBAAiBS,MAAM,CAACN;IAC1B;IACAH,iBAAiBU,GAAG,CAACP,SAASI;IAC9B,OAAOA;AACT;AAEA,6DAA6D,GAC7D,OAAO,SAASI;IACdX,iBAAiBY,KAAK;AACxB;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GACD,OAAO,SAASC,gBACdC,SAAoB,EACpBC,QAA+C,EAC/CC,UAAkC,CAAC,CAAC;IAEpC,MAAM,CAACC,OAAOC,SAAS,GAAGxB,SAA+B;QACvDyB,MAAMC;QACNC,OAAO;QACPC,OAAO;QACPC,WAAW;IACb;IACA,gEAAgE;IAChE,MAAMpB,UAAUY,WAAWA,SAASS,IAAI,CAAC,OAAO;IAChD,MAAMC,mBAAmBT,QAAQS,gBAAgB;IAEjDhC,UAAU;QACRyB,SAAS;YAAEC,MAAMC;YAAWC,OAAO;YAAOC,OAAO;YAAOC,WAAW;QAAK;QACxE,IAAI,CAACpB,SAAS;QAEd,IAAIuB,YAAY;QAChB,IAAIC,cAAmC;QAC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AA,eAAeoB,WAAW;wBACxBpB,eAAe;wBACfC,mBAAmB;wBACnB,KAAK7B,cAAcC,SAASC,KACzB2C,IAAI,CAAC,CAACC;4BACL,IAAItB,WAAW;4BACfQ,QAAQc,OAAOb,MAAM,IAAIa,OAAOZ,EAAE,EAAEY,OAAO7B,IAAI,IAAI;wBACrD,EACA,6DAA6D;wBAC7D,6DAA6D;wBAC7D,uDAAuD;yBACtD8B,KAAK,CAAC,IAAM7B;oBACjB,GAAGrB;gBACL;YACF,GACA;gBACE,IAAI2B,WAAW;gBACfC,+BAAAA;gBACA,IAAIE,UAAUhC,aAAa;oBACzB,MAAMsD,QAAQC,KAAKC,GAAG,CACpBzD,iBAAiB,KAAKiC,SACtB/B;oBAEF+B,WAAW;oBACXD,QAAQsB,WAAWP,WAAWQ;gBAChC,OAAO;oBACLjC,SAAS;wBACPC,MAAMC;wBACNC,OAAO;wBACPC,OAAO;wBACPC,WAAW;oBACb;gBACF;YACF;QAEJ;QACAoB;QAEA,OAAO;YACLjB,YAAY;YACZM,aAAasB,OAAO;YACpB,IAAI1B,OAAOkB,aAAalB;YACxB,IAAIE,cAAcgB,aAAahB;YAC/BH,+BAAAA;QACF;IACF,GAAG;QAACb;QAAWX;QAASsB;KAAiB;IAEzC,OAAOR;AACT;AAEA,eAAeJ,gBAAe"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-confirmed-doc.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'use client'\n\nimport {\n doc,\n getDocFromServer,\n onSnapshot,\n type DocumentData,\n type DocumentReference,\n type DocumentSnapshot,\n type Firestore,\n} from 'firebase/firestore'\nimport { useEffect, useState } from 'react'\nimport { trackListenConfirmation } from './helpers/listen-confirmation'\n\nconst RETRY_DELAY_MS = 400\nconst MAX_RETRIES = 8\nconst MAX_RETRY_DELAY_MS = 15_000\n\nexport interface ConfirmedDocState<T> {\n /** The doc's data (with `$id`), or undefined while loading / when absent. */\n data: T | undefined\n /**\n * True once an answer worth acting on has arrived: any snapshot that has\n * data, or a MISS the server itself has confirmed. Consumers must not\n * 404, fall back to a default, or otherwise treat \"no doc\" as real until\n * this is true.\n */\n ready: boolean\n /** True only when retries were exhausted — offer a retry, never a 404. */\n error: boolean\n /**\n * `data` is being served from the local cache and the server has not\n * confirmed it (AGL-1066). Never a reason to withhold the value — only a\n * reason not to let it decide something irreversible.\n */\n fromCache: boolean\n}\n\nexport interface UseConfirmedDocOptions {\n /**\n * Also confirm a cache-served hit that EXISTS, not just a miss (AGL-1066).\n *\n * The base contract trusts any snapshot that exists, whatever its source.\n * That is right for ordinary content — the value was legitimately the\n * user's a moment ago, and blanking it costs more than it buys. It is NOT\n * right for the entitlement doc: `orgs/{orgId}` is the only plan source\n * (AGL-238), and a cached copy from before a plan change renders the org\n * at the wrong tier for as long as the session stays stale. AGL-887 closed\n * the tombstone direction of exactly this fault (a Business workspace\n * rendering as Free); this closes the stale-EXISTS direction.\n *\n * Opt-in because it can cost one extra server read, and only when the\n * listener has actually failed to reach the server — see the deferral in\n * the implementation. Enable it for entitlement-shaped documents only.\n */\n confirmCachedHit?: boolean\n}\n\n/**\n * How long a cached hit is allowed to stand before it is confirmed.\n *\n * Not zero, and this is the whole reason the option is affordable: on a\n * healthy load the first snapshot is routinely from cache and the server\n * snapshot follows within milliseconds. Confirming immediately would bill an\n * extra read on every mount for every user; waiting means the confirm fires\n * only when the server genuinely did not answer.\n */\nconst CONFIRM_CACHED_HIT_DELAY_MS = 1_500\n\n/**\n * Confirms in flight, keyed by document path (AGL-1440).\n *\n * `useCurrentOrg` is a plain hook, not a context, and the console chrome mounts\n * it seven-plus times per page — user menu, org switcher, branding, and three\n * separate paths through `ConsolePluginsGate`. The `onSnapshot`s are nearly\n * free, because the SDK serves identical listens off ONE target; the confirms\n * are not. Each instance scheduled its own `getDocFromServer`, so a console\n * page load billed seven server reads of `orgs/{orgId}` to answer one question.\n *\n * Sharing the PROMISE, rather than suppressing the duplicates, is what keeps\n * this behaviour-preserving: every instance still resolves from a real server\n * snapshot and still calls `deliver(..., fromCache: false)`, so none of them is\n * left displaying a value flagged unconfirmed. Suppressing instead would leave\n * the six quiet instances on `fromCache: true` forever, which is a state\n * consumers are told means \"do not let this decide anything irreversible\".\n *\n * The entry is dropped as soon as it settles, so this is a burst collapser and\n * nothing more: a mount two seconds later asks the server again, exactly as it\n * does today. NOTHING about the entitlement is cached — this shares one READ\n * of the org document; every consumer evaluates the plan off it as before.\n */\nconst confirmsInFlight = new Map<\n string,\n Promise<DocumentSnapshot<DocumentData>>\n>()\n\n/** The server's copy of `ref`, shared with any confirm already in flight. */\nfunction sharedConfirm(\n pathKey: string,\n ref: DocumentReference,\n): Promise<DocumentSnapshot<DocumentData>> {\n const existing = confirmsInFlight.get(pathKey)\n if (existing) return existing\n const pending = getDocFromServer(ref).finally(() => {\n confirmsInFlight.delete(pathKey)\n })\n confirmsInFlight.set(pathKey, pending)\n return pending\n}\n\n/** Test seam — the in-flight map is module scope by design. */\nexport function resetConfirmedDocSharing(): void {\n confirmsInFlight.clear()\n}\n\n/**\n * A doc listen that never presents an unconfirmed miss (AGL-928).\n *\n * This is the shared form of the contract four consumers learned the hard\n * way (AGL-813/827/875/886/887): the console's multi-tab IndexedDB\n * persistence can serve a stale `noDocument` tombstone for a LIVE doc, and\n * a resumed listen never re-sends the correction — so `exists() === false`\n * from cache looks confirmed while being wrong. Symptoms ranged from valid\n * hosts 404ing to a Business workspace rendering as Free.\n *\n * Contract implemented here:\n * - Subscribe with a raw `onSnapshot` + exponential-backoff resubscribe:\n * right after sign-in (and on cold loads behind App Check) the first\n * listen can sit in transient `permission-denied` before the ID token\n * attaches (AGL-216); reactfire's cached Observable would replay that\n * error forever.\n * - A snapshot that EXISTS is trusted immediately, whatever its source.\n * - A snapshot that is MISSING and came from cache is confirmed via\n * `getDocFromServer` before it is believed; a failed confirm leaves\n * `ready` false rather than lying.\n * - Exhausted retries set `error` (and `ready`) so consumers can offer\n * \"try again\" — never a false 404 or a fallback default.\n *\n * For QUERY listens the same contract lives in `useOrgHosts` (empty →\n * `getDocsFromServer` confirm); extract it the same way if a third query\n * consumer appears.\n *\n * @param segments Doc path segments (`['orgs', orgId]`), or null to idle\n * (state resets while null, matching \"clear on scope change\").\n */\nexport function useConfirmedDoc<T extends Record<string, unknown>>(\n firestore: Firestore,\n segments: readonly [string, ...string[]] | null,\n options: UseConfirmedDocOptions = {},\n): ConfirmedDocState<T> {\n const [state, setState] = useState<ConfirmedDocState<T>>({\n data: undefined,\n ready: false,\n error: false,\n fromCache: true,\n })\n // Effect key: a new path must tear down and restart the listen.\n const pathKey = segments ? segments.join('/') : null\n const confirmCachedHit = options.confirmCachedHit\n\n useEffect(() => {\n setState({ data: undefined, ready: false, error: false, fromCache: true })\n if (!pathKey) return\n\n let cancelled = false\n let unsubscribe: (() => void) | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n let attempt = 0\n // One confirm per mount, and never once the server has answered.\n let confirmTimer: ReturnType<typeof setTimeout> | null = null\n let confirmRequested = false\n const ref = doc(firestore, pathKey)\n /** What a save waits on while this read is unconfirmed (AGL-4120). */\n const confirmation = trackListenConfirmation(undefined, {\n // A confirmation kept through a fall back to the cache ran out\n // before the server answered again (AGL-4047).\n onLapse: () => {\n if (cancelled) return\n setState((current) =>\n current.fromCache ? current : { ...current, fromCache: true },\n )\n },\n })\n /** The cached values on screen, while they are (AGL-4120). */\n let shownFromCache: string | undefined\n\n const deliver = (\n exists: boolean,\n id: string,\n payload: Record<string, unknown> | undefined,\n fromCache: boolean,\n ) => {\n const values = JSON.stringify(exists ? (payload ?? null) : undefined)\n // The snapshot's own, unless it is a short fall back to the cache\n // after a confirmation, which keeps it (AGL-4047).\n const shown = confirmation.report(\n fromCache,\n !fromCache && shownFromCache !== undefined && shownFromCache !== values,\n )\n shownFromCache = fromCache ? (values ?? 'missing') : undefined\n setState({\n data: exists ? ({ $id: id, ...payload } as unknown as T) : undefined,\n ready: true,\n error: false,\n fromCache: shown,\n })\n }\n\n const subscribe = () => {\n unsubscribe = onSnapshot(\n ref,\n (snapshot) => {\n if (cancelled) return\n attempt = 0\n const fromCache = snapshot.metadata.fromCache\n if (!fromCache && confirmTimer) {\n // The server answered on its own; nothing left to confirm.\n clearTimeout(confirmTimer)\n confirmTimer = null\n }\n if (!snapshot.exists() && fromCache) {\n // Unconfirmed miss: ask the server before believing it. On\n // failure stay un-ready — the listener remains subscribed and\n // the next (server) snapshot resolves it.\n void sharedConfirm(pathKey, ref)\n .then((server) => {\n if (cancelled) return\n deliver(server.exists(), server.id, server.data(), false)\n })\n .catch(() => undefined)\n return\n }\n deliver(snapshot.exists(), snapshot.id, snapshot.data(), fromCache)\n\n /**\n * Unconfirmed HIT (AGL-1066), for entitlement-shaped docs only.\n *\n * The value is already delivered above and stays on screen\n * whatever happens here — this never blanks the page and never\n * holds `ready` false, because a transient blip must not become a\n * wrong tier OR a 404. It only replaces a cached answer with the\n * server's when the server can be reached.\n */\n if (\n confirmCachedHit &&\n fromCache &&\n snapshot.exists() &&\n !confirmRequested &&\n !confirmTimer\n ) {\n confirmTimer = setTimeout(() => {\n confirmTimer = null\n confirmRequested = true\n void sharedConfirm(pathKey, ref)\n .then((server) => {\n if (cancelled) return\n deliver(server.exists(), server.id, server.data(), false)\n })\n // Could not reach the server: keep showing the cached value,\n // still flagged `fromCache`. Refusing to answer would be the\n // stale-`ready` false-404 this hook exists to prevent.\n .catch(() => undefined)\n }, CONFIRM_CACHED_HIT_DELAY_MS)\n }\n },\n () => {\n if (cancelled) return\n unsubscribe?.()\n if (attempt < MAX_RETRIES) {\n const delay = Math.min(\n RETRY_DELAY_MS * 2 ** attempt,\n MAX_RETRY_DELAY_MS,\n )\n attempt += 1\n timer = setTimeout(subscribe, delay)\n } else {\n setState({\n data: undefined,\n ready: true,\n error: true,\n fromCache: true,\n })\n }\n },\n )\n }\n subscribe()\n\n return () => {\n cancelled = true\n confirmation.release()\n if (timer) clearTimeout(timer)\n if (confirmTimer) clearTimeout(confirmTimer)\n unsubscribe?.()\n }\n }, [firestore, pathKey, confirmCachedHit])\n\n return state\n}\n\nexport default useConfirmedDoc\n"],"names":["doc","getDocFromServer","onSnapshot","useEffect","useState","trackListenConfirmation","RETRY_DELAY_MS","MAX_RETRIES","MAX_RETRY_DELAY_MS","CONFIRM_CACHED_HIT_DELAY_MS","confirmsInFlight","Map","sharedConfirm","pathKey","ref","existing","get","pending","finally","delete","set","resetConfirmedDocSharing","clear","useConfirmedDoc","firestore","segments","options","state","setState","data","undefined","ready","error","fromCache","join","confirmCachedHit","cancelled","unsubscribe","timer","attempt","confirmTimer","confirmRequested","confirmation","onLapse","current","shownFromCache","deliver","exists","id","payload","values","JSON","stringify","shown","report","$id","subscribe","snapshot","metadata","clearTimeout","then","server","catch","setTimeout","delay","Math","min","release"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,GAAG,EACHC,gBAAgB,EAChBC,UAAU,QAKL,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAC3C,SAASC,uBAAuB,QAAQ,mCAA+B;AAEvE,MAAMC,iBAAiB;AACvB,MAAMC,cAAc;AACpB,MAAMC,qBAAqB;AA0C3B;;;;;;;;CAQC,GACD,MAAMC,8BAA8B;AAEpC;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,MAAMC,mBAAmB,IAAIC;AAK7B,2EAA2E,GAC3E,SAASC,cACPC,OAAe,EACfC,GAAsB;IAEtB,MAAMC,WAAWL,iBAAiBM,GAAG,CAACH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AGrB;gBACL;YACF,GACA;gBACE,IAAI2B,WAAW;gBACfC,+BAAAA;gBACA,IAAIE,UAAUhC,aAAa;oBACzB,MAAMyD,QAAQC,KAAKC,GAAG,CACpB5D,iBAAiB,KAAKiC,SACtB/B;oBAEF+B,WAAW;oBACXD,QAAQyB,WAAWP,WAAWQ;gBAChC,OAAO;oBACLpC,SAAS;wBACPC,MAAMC;wBACNC,OAAO;wBACPC,OAAO;wBACPC,WAAW;oBACb;gBACF;YACF;QAEJ;QACAuB;QAEA,OAAO;YACLpB,YAAY;YACZM,aAAayB,OAAO;YACpB,IAAI7B,OAAOqB,aAAarB;YACxB,IAAIE,cAAcmB,aAAanB;YAC/BH,+BAAAA;QACF;IACF,GAAG;QAACb;QAAWX;QAASsB;KAAiB;IAEzC,OAAOR;AACT;AAEA,eAAeJ,gBAAe"}
|
|
@@ -102,7 +102,13 @@ const MAX_RETRIES = 5;
|
|
|
102
102
|
* first server-confirmed snapshot, by an error (a refusal is not a
|
|
103
103
|
* stall) and by cleanup.
|
|
104
104
|
*/ const disarmStall = armFirestoreStallWatch(q.firestore);
|
|
105
|
-
/** What a save waits on while this listener is unconfirmed (AGL-4120). */ const confirmation = trackListenConfirmation(listen
|
|
105
|
+
/** What a save waits on while this listener is unconfirmed (AGL-4120). */ const confirmation = trackListenConfirmation(listen, {
|
|
106
|
+
// A confirmation kept through a fall back to the cache ran out
|
|
107
|
+
// before the server answered again (AGL-4047).
|
|
108
|
+
onLapse: ()=>{
|
|
109
|
+
if (!cancelled) setFromCache(true);
|
|
110
|
+
}
|
|
111
|
+
});
|
|
106
112
|
/** Whether the rows on screen came from the cache (AGL-4120). */ let shownFromCache = false;
|
|
107
113
|
// Disappearance tracking (AGL-1196); inert unless opted in.
|
|
108
114
|
const seen = new Set();
|
|
@@ -115,8 +121,9 @@ const MAX_RETRIES = 5;
|
|
|
115
121
|
setStatus('success');
|
|
116
122
|
setError(undefined);
|
|
117
123
|
}
|
|
118
|
-
|
|
119
|
-
confirmation
|
|
124
|
+
// The snapshot's own, unless it is a short fall back to the cache
|
|
125
|
+
// after a confirmation, which keeps it (AGL-4047).
|
|
126
|
+
setFromCache(confirmation.report(cached, !cached && shownFromCache && changed));
|
|
120
127
|
shownFromCache = cached;
|
|
121
128
|
setData(docs.map((docSnap)=>{
|
|
122
129
|
const value = _extends({}, docSnap.data());
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-firestore-collection.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'use client'\n\nimport {\n getDocsFromServer,\n onSnapshot,\n type DocumentData,\n type FirestoreError,\n type Query,\n type QueryDocumentSnapshot,\n} from 'firebase/firestore'\nimport { useEffect, useRef, useState, type DependencyList } from 'react'\nimport { CONFIRMABLE_LISTEN_OPTIONS } from './helpers/listen-options'\nimport {\n DENIAL_STREAK_TO_REPORT,\n denialLabelForQuery,\n reportFirestoreDenial,\n reportFirestoreServerRead,\n scheduleRefusedReopen,\n subscribeFirestoreSessionHeal,\n} from './firestore-denial-reporter'\nimport {\n armFirestoreStallWatch,\n noteFirestoreServerAnswer,\n} from './firebase/firestore-stall-recovery'\nimport {\n createListenHandle,\n trackListenConfirmation,\n type ListenHandle,\n} from './helpers/listen-confirmation'\n\nconst RETRY_DELAY_MS = 400\nconst MAX_RETRIES = 5\n\n/*\n * The cadence once a refusal streak has outlived the retry budget lives in\n * `firestore-denial-reporter.ts` (`scheduleRefusedReopen`), shared by all\n * three listener hooks. It starts at 2s while the fault could be the whole\n * session and at 60s once another listener's server answer proves the\n * session reads and this refusal is about the ref (AGL-1440), then grows\n * with the streak's age to a five-minute ceiling (AGL-2945). A hidden tab\n * sets no timer (AGL-2944). The tab becoming visible, the window regaining\n * focus and a heal broadcast (`subscribeFirestoreSessionHeal`) all reopen\n * at once.\n */\n\nexport type FirestoreCollectionStatus = 'loading' | 'success' | 'error'\n\nexport interface UseFirestoreCollectionOptions {\n idField?: string\n /**\n * Confirm against the server when a document disappears from a NON-EMPTY\n * result, instead of trusting the live snapshot (AGL-1196).\n *\n * OPT-IN, and only worth setting for a query whose `where` reads a MUTABLE\n * field. Such a document can stop matching mid-session — a scope edit, an\n * un/republish — leave the query target, and get cached as a `noDocument`\n * tombstone at its own path, which is then served to every other reader of\n * that path including single-document reads (AGL-827/929).\n *\n * A query with no predicate, or one keyed on `documentId()`, cannot produce\n * this and must not pay for the extra read. Where the predicate can be\n * dropped entirely, drop it — that removes the mechanism rather than\n * repairing it after the fact (AGL-1190).\n */\n confirmDisappearances?: boolean\n}\n\nexport interface UseFirestoreCollectionResult<T> {\n data: T[]\n status: FirestoreCollectionStatus\n error: FirestoreError | undefined\n /**\n * `data` came from the local cache and the server has not confirmed it\n * (AGL-1066). See `ObservableStatus.fromCache` for why this matters and\n * why it is the signal to reach for rather than `staleSession`.\n */\n fromCache: boolean\n /**\n * The server has REFUSED this listen for longer than the retry budget, and\n * no server snapshot has arrived since (AGL-1066).\n *\n * Kept after the flip rather than folded into `status`, because it says\n * something `status` does not: WHY the listen is failing. `status:\n * 'error'` covers every terminal error; this one counts `permission-denied`\n * alone, so it cannot fire offline, and a single server snapshot clears it.\n * A consumer asking \"is what I am rendering cache-only because the session\n * is refused\" wants this; one asking \"did the read fail at all\" wants\n * `status`.\n */\n serverDenied: boolean\n /**\n * This hook's listener, for a guarded save seeded from `data` to wait on\n * alone (`writeGuardedBySeed`'s `listen`, AGL-4135). Stable for the life of\n * the hook.\n */\n listen: ListenHandle\n}\n\n/**\n * Collection-query counterpart to reactfire's `useFirestoreCollectionData`,\n * but backed by a raw `onSnapshot` listener with its own retry/backoff\n * instead of reactfire's cached Observable. That cache terminates forever on\n * its first error — a transient `permission-denied` right after sign-in\n * (before Firestore's own credential provider has attached the user's ID\n * token) permanently breaks the query for the rest of the session, even\n * across remounts. A fresh `onSnapshot` call each retry reopens a genuinely\n * new listener, so it recovers once the token has propagated (AGL-216/217).\n *\n * `buildQuery` is re-invoked from `deps` the same way a `useEffect`/`useMemo`\n * callback would be — pass the same primitive values (ids, uid, firestore)\n * you'd put in a `useMemo` dependency array, not the `Query` object itself.\n */\nexport function useFirestoreCollection<T = DocumentData>(\n buildQuery: () => Query<DocumentData> | null | undefined,\n deps: DependencyList,\n options: UseFirestoreCollectionOptions = {},\n): UseFirestoreCollectionResult<T> {\n const [data, setData] = useState<T[]>([])\n const [status, setStatus] = useState<FirestoreCollectionStatus>('loading')\n const [error, setError] = useState<FirestoreError | undefined>(undefined)\n // Un-confirmed until a snapshot says otherwise: a hook that has not heard\n // from the server yet must not read as server-confirmed.\n const [fromCache, setFromCache] = useState(true)\n const [serverDenied, setServerDenied] = useState(false)\n const [listen] = useState(createListenHandle)\n const buildQueryRef = useRef(buildQuery)\n buildQueryRef.current = buildQuery\n const idField = options.idField\n const confirmDisappearances = options.confirmDisappearances\n\n useEffect(() => {\n setStatus('loading')\n setError(undefined)\n // Clear on EVERY dep change, not only when the query goes null: when\n // the scope moves between two live queries (org A → org B, host A →\n // host B) the old rows would otherwise stay rendered until the new\n // snapshot arrives — the org-switch \"remnants\" bug (AGL-591). Same\n // hold-nothing-rather-than-show-the-wrong-org rule as useOrgHosts.\n setData([])\n setFromCache(true)\n setServerDenied(false)\n\n const q = buildQueryRef.current()\n if (!q) {\n return\n }\n\n let cancelled = false\n let unsubscribe: (() => void) | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n /** Cancels a pending reopen on the refused cadence (AGL-2944). */\n let cancelRefusedReopen: (() => void) | null = null\n let attempt = 0\n /**\n * Refusals since the last SERVER snapshot (AGL-1066).\n *\n * Deliberately not `attempt`: that one is reset by any snapshot,\n * including a cached one, so under `persistentLocalCache` it never\n * reaches its budget and can never report anything.\n */\n let deniedStreak = 0\n /** Epoch ms of the current streak's first refusal (AGL-1440). */\n let deniedStreakStartedAt = 0\n let denialReported = false\n /**\n * The retry budget is spent and the last thing the server did was refuse\n * (AGL-1066).\n *\n * This is what makes `status: 'error'` STICK. Every reopened listen emits\n * from the cache before it learns it is still refused, and an\n * unconditional `setStatus('success')` in the success handler would hand\n * the page back to `success` on that emission — so the surface would\n * oscillate error → success → error at the retry cadence, which is worse\n * to look at than either state. Only a snapshot the SERVER answered\n * clears this, for the same reason it is the only thing that clears\n * `deniedStreak`: a cached emission is not evidence about the server.\n */\n let terminal = false\n const denialLabel = denialLabelForQuery(q)\n /**\n * A listen the server has not confirmed within `FIRESTORE_STALL_MS`,\n * while the browser is online and the tab is visible, is the multi-tab\n * wedge (AGL-3373): no tab is syncing, so an empty cache raises no first\n * snapshot at all and a warm one never confirms. The client is asked to\n * recover — a network cycle that forces the lease election — and this\n * listener then hears from the server like any other. Disarmed by the\n * first server-confirmed snapshot, by an error (a refusal is not a\n * stall) and by cleanup.\n */\n const disarmStall = armFirestoreStallWatch(q.firestore)\n /** What a save waits on while this listener is unconfirmed (AGL-4120). */\n const confirmation = trackListenConfirmation(listen)\n /** Whether the rows on screen came from the cache (AGL-4120). */\n let shownFromCache = false\n // Disappearance tracking (AGL-1196); inert unless opted in.\n const seen = new Set<string>()\n const confirmedGone = new Set<string>()\n\n const emit = (\n docs: QueryDocumentSnapshot<DocumentData>[],\n cached: boolean,\n changed: boolean,\n ) => {\n // A server-answered emission is the one thing that ends the refusal,\n // including the `getDocsFromServer` confirmation path below.\n if (!cached) terminal = false\n if (!terminal) {\n setStatus('success')\n setError(undefined)\n }\n setFromCache(cached)\n confirmation.report(cached, !cached && shownFromCache && changed)\n shownFromCache = cached\n setData(\n docs.map((docSnap) => {\n const value = { ...docSnap.data() } as Record<string, unknown>\n if (idField) value[idField] = docSnap.id\n return value as T\n }),\n )\n }\n\n const subscribe = () => {\n unsubscribe = onSnapshot(\n q,\n // Without this the cache→server confirmation is never delivered and\n // `fromCache` latches true for the life of the listener, refusing\n // every guarded save on the page (AGL-2486). See `listen-options.ts`.\n CONFIRMABLE_LISTEN_OPTIONS,\n (snapshot) => {\n if (cancelled) return\n /**\n * Only a SERVER-answered snapshot refunds the retry budget — the\n * AGL-1066 flip, and the reason it took four commits to become\n * safe.\n *\n * Under `persistentLocalCache` a reopened listen emits from the\n * cache BEFORE it learns the server refused it. Refunding on that\n * emission handed the budget back every cycle, so `attempt` never\n * reached `MAX_RETRIES`, `status` could never become `'error'`, and\n * a dead session looked exactly like a healthy one on every\n * listener-backed page for as long as it stayed dead.\n *\n * Landing this alone would have been a regression, and the three\n * things that made it one are now in place:\n *\n * - the budget is 5 x 400ms, and the error branch used to stop\n * retrying for good, while the heal is an AGL-664 in-place\n * re-auth that takes as long as a human takes to type a\n * password. A resolved re-auth now broadcasts and this listener\n * reopens on it (`subscribeFirestoreSessionHeal` below), and a\n * refusal streak keeps a slow road back for a recovery nobody\n * announced (see the error branch);\n * - `status: 'error'` had to become STICKY, or the cached emission\n * that precedes each refusal would flip it straight back — see\n * `terminal` above;\n * - the surfaces that BLANK on `error` had to learn the\n * difference between \"never had data\" and \"have data, the server\n * refused\". They read `hasEmitted` now, so the besigner canvas\n * and the host setup Theme tab keep rendering across a refusal\n * instead of collapsing to \"Not found\".\n *\n * The withholding is keyed on a REFUSAL having happened, not on the\n * emission being cached, and that is load-bearing: offline stays\n * exactly as inert as it was. A lost network yields `unavailable`\n * (when it yields an error callback at all), which never enters\n * `deniedStreak`, so a cached emission still refunds the budget and\n * an offline listener still never goes terminal. The cache exists\n * for offline; this must not change what happens there.\n */\n // Only the SERVER answering is evidence the session can read.\n if (!snapshot.metadata.fromCache) {\n disarmStall()\n noteFirestoreServerAnswer(q.firestore)\n attempt = 0\n deniedStreak = 0\n denialReported = false\n setServerDenied(false)\n // Proof the session can read — stronger than any accumulated\n // denial, and what stops a scoped collaborator's by-design\n // denials from ever adding up to a re-auth prompt.\n reportFirestoreServerRead()\n } else if (deniedStreak === 0) {\n // Cached, but nothing has been refused since the server last\n // answered — so this is not the AGL-1066 fault and the budget is\n // refunded exactly as it always was.\n attempt = 0\n }\n\n // Only the values count: a metadata-only tick is not a change.\n const changed = snapshot.docChanges?.().length > 0\n\n if (confirmDisappearances) {\n const present = new Set(snapshot.docs.map((d) => d.id))\n const vanished = [...seen].filter(\n (id) => !present.has(id) && !confirmedGone.has(id),\n )\n if (vanished.length) {\n // A fresh (non-resumed) read ignores the resume token, returns\n // the true set and rewrites the cache, dropping any tombstone.\n getDocsFromServer(q)\n .then((fresh) => {\n if (cancelled) return\n const freshIds = new Set(fresh.docs.map((d) => d.id))\n // Only an absence the SERVER agrees with is real. One that\n // came back was a tombstone and must stay eligible to heal\n // if it vanishes again.\n vanished.forEach((id) => {\n if (!freshIds.has(id)) confirmedGone.add(id)\n })\n freshIds.forEach((id) => seen.add(id))\n // `getDocsFromServer` is server-confirmed by definition.\n emit(fresh.docs, false, true)\n })\n .catch(() => {\n // Couldn't confirm: show the live result rather than an\n // error. A possibly-short list beats an empty one.\n if (!cancelled) {\n emit(snapshot.docs, snapshot.metadata.fromCache, changed)\n }\n })\n return\n }\n snapshot.docs.forEach((d) => seen.add(d.id))\n }\n\n emit(snapshot.docs, snapshot.metadata.fromCache, changed)\n },\n (err) => {\n if (cancelled) return\n disarmStall()\n confirmation.release()\n unsubscribe?.()\n // Say so once per outage, and only for a refusal — a lost network\n // produces no error callback at all, so this cannot fire offline.\n if (err?.code === 'permission-denied') {\n deniedStreak += 1\n // When the streak began — the reference point that lets\n // `refusedRetryDelayMs` ask whether the session has read from\n // the server SINCE this listen started being refused (AGL-1440).\n if (deniedStreak === 1) deniedStreakStartedAt = Date.now()\n if (deniedStreak >= DENIAL_STREAK_TO_REPORT) {\n setServerDenied(true)\n if (!denialReported) {\n denialReported = true\n reportFirestoreDenial(denialLabel)\n }\n }\n }\n if (attempt < MAX_RETRIES) {\n attempt += 1\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n } else {\n timer = setTimeout(subscribe, RETRY_DELAY_MS)\n }\n } else {\n terminal = true\n setStatus('error')\n setError(err)\n /**\n * A refusal streak keeps a slow road back (AGL-1066).\n *\n * Before the flip this listener reopened forever, which is also\n * what HEALED it — a token that attached late, an App Check\n * hiccup, one of the AGL-1143 transient token-layer denials.\n * None of those broadcast a heal, because none of them involved\n * a re-auth the console asked for, so stopping here would leave\n * every listen in the console terminal until the user reloaded.\n * The status is corrected; the recovery is not taken away.\n *\n * Any OTHER terminal error still stops exactly as before — this\n * is deliberately keyed on the refusal streak, not on `attempt`.\n * How slow the road is depends on whether the refusal looks like\n * the session or the ref (AGL-1440) and on how long it has\n * lasted (AGL-2945), and a hidden tab waits to be looked at\n * (AGL-2944) — see `scheduleRefusedReopen`.\n */\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n }\n }\n },\n )\n }\n subscribe()\n\n /**\n * The session came back — reopen NOW rather than on the next tick of a\n * cadence tuned for a session that has not (AGL-1066).\n *\n * Gated on this listener actually being refused. A healthy listener has\n * an open subscription and nothing to recover, so it must ignore the\n * broadcast entirely: without this gate a heal would tear down and\n * reopen every listen in the console at once, which is a listener storm\n * dressed up as a fix.\n *\n * What is refunded is `attempt` — the retry BUDGET, which was spent on a\n * fault that is now over. `deniedStreak` is deliberately left alone: it\n * is evidence about the server, and only the server answering may clear\n * it. So `serverDenied` stays true across the heal and goes false on the\n * snapshot that actually proves the read works, and a heal that turns\n * out to be wishful thinking falls straight back to the slow cadence\n * instead of resuming a 400ms storm.\n *\n * `denialReported` IS reset: the outage ended here. If reads are still\n * refused afterwards that is a new one, and it has to be able to raise\n * the AGL-1063 banner again.\n */\n const unsubscribeHeal = subscribeFirestoreSessionHeal(() => {\n if (cancelled || deniedStreak === 0) return\n if (timer) {\n clearTimeout(timer)\n timer = null\n }\n cancelRefusedReopen?.()\n cancelRefusedReopen = null\n unsubscribe?.()\n attempt = 0\n denialReported = false\n subscribe()\n })\n\n return () => {\n cancelled = true\n disarmStall()\n confirmation.close()\n unsubscribeHeal()\n if (timer) clearTimeout(timer)\n cancelRefusedReopen?.()\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps)\n\n return { data, status, error, fromCache, serverDenied, listen }\n}\n\nexport default useFirestoreCollection\n"],"names":["getDocsFromServer","onSnapshot","useEffect","useRef","useState","CONFIRMABLE_LISTEN_OPTIONS","DENIAL_STREAK_TO_REPORT","denialLabelForQuery","reportFirestoreDenial","reportFirestoreServerRead","scheduleRefusedReopen","subscribeFirestoreSessionHeal","armFirestoreStallWatch","noteFirestoreServerAnswer","createListenHandle","trackListenConfirmation","RETRY_DELAY_MS","MAX_RETRIES","useFirestoreCollection","buildQuery","deps","options","data","setData","status","setStatus","error","setError","undefined","fromCache","setFromCache","serverDenied","setServerDenied","listen","buildQueryRef","current","idField","confirmDisappearances","q","cancelled","unsubscribe","timer","cancelRefusedReopen","attempt","deniedStreak","deniedStreakStartedAt","denialReported","terminal","denialLabel","disarmStall","firestore","confirmation","shownFromCache","seen","Set","confirmedGone","emit","docs","cached","changed","report","map","docSnap","value","id","subscribe","snapshot","metadata","docChanges","length","present","d","vanished","filter","has","then","fresh","freshIds","forEach","add","catch","err","release","code","Date","now","setTimeout","unsubscribeHeal","clearTimeout","close"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,iBAAiB,EACjBC,UAAU,QAKL,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAA6B,QAAO;AACxE,SAASC,0BAA0B,QAAQ,8BAA0B;AACrE,SACEC,uBAAuB,EACvBC,mBAAmB,EAC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|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-firestore-collection.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'use client'\n\nimport {\n getDocsFromServer,\n onSnapshot,\n type DocumentData,\n type FirestoreError,\n type Query,\n type QueryDocumentSnapshot,\n} from 'firebase/firestore'\nimport { useEffect, useRef, useState, type DependencyList } from 'react'\nimport { CONFIRMABLE_LISTEN_OPTIONS } from './helpers/listen-options'\nimport {\n DENIAL_STREAK_TO_REPORT,\n denialLabelForQuery,\n reportFirestoreDenial,\n reportFirestoreServerRead,\n scheduleRefusedReopen,\n subscribeFirestoreSessionHeal,\n} from './firestore-denial-reporter'\nimport {\n armFirestoreStallWatch,\n noteFirestoreServerAnswer,\n} from './firebase/firestore-stall-recovery'\nimport {\n createListenHandle,\n trackListenConfirmation,\n type ListenHandle,\n} from './helpers/listen-confirmation'\n\nconst RETRY_DELAY_MS = 400\nconst MAX_RETRIES = 5\n\n/*\n * The cadence once a refusal streak has outlived the retry budget lives in\n * `firestore-denial-reporter.ts` (`scheduleRefusedReopen`), shared by all\n * three listener hooks. It starts at 2s while the fault could be the whole\n * session and at 60s once another listener's server answer proves the\n * session reads and this refusal is about the ref (AGL-1440), then grows\n * with the streak's age to a five-minute ceiling (AGL-2945). A hidden tab\n * sets no timer (AGL-2944). The tab becoming visible, the window regaining\n * focus and a heal broadcast (`subscribeFirestoreSessionHeal`) all reopen\n * at once.\n */\n\nexport type FirestoreCollectionStatus = 'loading' | 'success' | 'error'\n\nexport interface UseFirestoreCollectionOptions {\n idField?: string\n /**\n * Confirm against the server when a document disappears from a NON-EMPTY\n * result, instead of trusting the live snapshot (AGL-1196).\n *\n * OPT-IN, and only worth setting for a query whose `where` reads a MUTABLE\n * field. Such a document can stop matching mid-session — a scope edit, an\n * un/republish — leave the query target, and get cached as a `noDocument`\n * tombstone at its own path, which is then served to every other reader of\n * that path including single-document reads (AGL-827/929).\n *\n * A query with no predicate, or one keyed on `documentId()`, cannot produce\n * this and must not pay for the extra read. Where the predicate can be\n * dropped entirely, drop it — that removes the mechanism rather than\n * repairing it after the fact (AGL-1190).\n */\n confirmDisappearances?: boolean\n}\n\nexport interface UseFirestoreCollectionResult<T> {\n data: T[]\n status: FirestoreCollectionStatus\n error: FirestoreError | undefined\n /**\n * `data` came from the local cache and the server has not confirmed it\n * (AGL-1066). See `ObservableStatus.fromCache` for why this matters and\n * why it is the signal to reach for rather than `staleSession`.\n */\n fromCache: boolean\n /**\n * The server has REFUSED this listen for longer than the retry budget, and\n * no server snapshot has arrived since (AGL-1066).\n *\n * Kept after the flip rather than folded into `status`, because it says\n * something `status` does not: WHY the listen is failing. `status:\n * 'error'` covers every terminal error; this one counts `permission-denied`\n * alone, so it cannot fire offline, and a single server snapshot clears it.\n * A consumer asking \"is what I am rendering cache-only because the session\n * is refused\" wants this; one asking \"did the read fail at all\" wants\n * `status`.\n */\n serverDenied: boolean\n /**\n * This hook's listener, for a guarded save seeded from `data` to wait on\n * alone (`writeGuardedBySeed`'s `listen`, AGL-4135). Stable for the life of\n * the hook.\n */\n listen: ListenHandle\n}\n\n/**\n * Collection-query counterpart to reactfire's `useFirestoreCollectionData`,\n * but backed by a raw `onSnapshot` listener with its own retry/backoff\n * instead of reactfire's cached Observable. That cache terminates forever on\n * its first error — a transient `permission-denied` right after sign-in\n * (before Firestore's own credential provider has attached the user's ID\n * token) permanently breaks the query for the rest of the session, even\n * across remounts. A fresh `onSnapshot` call each retry reopens a genuinely\n * new listener, so it recovers once the token has propagated (AGL-216/217).\n *\n * `buildQuery` is re-invoked from `deps` the same way a `useEffect`/`useMemo`\n * callback would be — pass the same primitive values (ids, uid, firestore)\n * you'd put in a `useMemo` dependency array, not the `Query` object itself.\n */\nexport function useFirestoreCollection<T = DocumentData>(\n buildQuery: () => Query<DocumentData> | null | undefined,\n deps: DependencyList,\n options: UseFirestoreCollectionOptions = {},\n): UseFirestoreCollectionResult<T> {\n const [data, setData] = useState<T[]>([])\n const [status, setStatus] = useState<FirestoreCollectionStatus>('loading')\n const [error, setError] = useState<FirestoreError | undefined>(undefined)\n // Un-confirmed until a snapshot says otherwise: a hook that has not heard\n // from the server yet must not read as server-confirmed.\n const [fromCache, setFromCache] = useState(true)\n const [serverDenied, setServerDenied] = useState(false)\n const [listen] = useState(createListenHandle)\n const buildQueryRef = useRef(buildQuery)\n buildQueryRef.current = buildQuery\n const idField = options.idField\n const confirmDisappearances = options.confirmDisappearances\n\n useEffect(() => {\n setStatus('loading')\n setError(undefined)\n // Clear on EVERY dep change, not only when the query goes null: when\n // the scope moves between two live queries (org A → org B, host A →\n // host B) the old rows would otherwise stay rendered until the new\n // snapshot arrives — the org-switch \"remnants\" bug (AGL-591). Same\n // hold-nothing-rather-than-show-the-wrong-org rule as useOrgHosts.\n setData([])\n setFromCache(true)\n setServerDenied(false)\n\n const q = buildQueryRef.current()\n if (!q) {\n return\n }\n\n let cancelled = false\n let unsubscribe: (() => void) | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n /** Cancels a pending reopen on the refused cadence (AGL-2944). */\n let cancelRefusedReopen: (() => void) | null = null\n let attempt = 0\n /**\n * Refusals since the last SERVER snapshot (AGL-1066).\n *\n * Deliberately not `attempt`: that one is reset by any snapshot,\n * including a cached one, so under `persistentLocalCache` it never\n * reaches its budget and can never report anything.\n */\n let deniedStreak = 0\n /** Epoch ms of the current streak's first refusal (AGL-1440). */\n let deniedStreakStartedAt = 0\n let denialReported = false\n /**\n * The retry budget is spent and the last thing the server did was refuse\n * (AGL-1066).\n *\n * This is what makes `status: 'error'` STICK. Every reopened listen emits\n * from the cache before it learns it is still refused, and an\n * unconditional `setStatus('success')` in the success handler would hand\n * the page back to `success` on that emission — so the surface would\n * oscillate error → success → error at the retry cadence, which is worse\n * to look at than either state. Only a snapshot the SERVER answered\n * clears this, for the same reason it is the only thing that clears\n * `deniedStreak`: a cached emission is not evidence about the server.\n */\n let terminal = false\n const denialLabel = denialLabelForQuery(q)\n /**\n * A listen the server has not confirmed within `FIRESTORE_STALL_MS`,\n * while the browser is online and the tab is visible, is the multi-tab\n * wedge (AGL-3373): no tab is syncing, so an empty cache raises no first\n * snapshot at all and a warm one never confirms. The client is asked to\n * recover — a network cycle that forces the lease election — and this\n * listener then hears from the server like any other. Disarmed by the\n * first server-confirmed snapshot, by an error (a refusal is not a\n * stall) and by cleanup.\n */\n const disarmStall = armFirestoreStallWatch(q.firestore)\n /** What a save waits on while this listener is unconfirmed (AGL-4120). */\n const confirmation = trackListenConfirmation(listen, {\n // A confirmation kept through a fall back to the cache ran out\n // before the server answered again (AGL-4047).\n onLapse: () => {\n if (!cancelled) setFromCache(true)\n },\n })\n /** Whether the rows on screen came from the cache (AGL-4120). */\n let shownFromCache = false\n // Disappearance tracking (AGL-1196); inert unless opted in.\n const seen = new Set<string>()\n const confirmedGone = new Set<string>()\n\n const emit = (\n docs: QueryDocumentSnapshot<DocumentData>[],\n cached: boolean,\n changed: boolean,\n ) => {\n // A server-answered emission is the one thing that ends the refusal,\n // including the `getDocsFromServer` confirmation path below.\n if (!cached) terminal = false\n if (!terminal) {\n setStatus('success')\n setError(undefined)\n }\n // The snapshot's own, unless it is a short fall back to the cache\n // after a confirmation, which keeps it (AGL-4047).\n setFromCache(\n confirmation.report(cached, !cached && shownFromCache && changed),\n )\n shownFromCache = cached\n setData(\n docs.map((docSnap) => {\n const value = { ...docSnap.data() } as Record<string, unknown>\n if (idField) value[idField] = docSnap.id\n return value as T\n }),\n )\n }\n\n const subscribe = () => {\n unsubscribe = onSnapshot(\n q,\n // Without this the cache→server confirmation is never delivered and\n // `fromCache` latches true for the life of the listener, refusing\n // every guarded save on the page (AGL-2486). See `listen-options.ts`.\n CONFIRMABLE_LISTEN_OPTIONS,\n (snapshot) => {\n if (cancelled) return\n /**\n * Only a SERVER-answered snapshot refunds the retry budget — the\n * AGL-1066 flip, and the reason it took four commits to become\n * safe.\n *\n * Under `persistentLocalCache` a reopened listen emits from the\n * cache BEFORE it learns the server refused it. Refunding on that\n * emission handed the budget back every cycle, so `attempt` never\n * reached `MAX_RETRIES`, `status` could never become `'error'`, and\n * a dead session looked exactly like a healthy one on every\n * listener-backed page for as long as it stayed dead.\n *\n * Landing this alone would have been a regression, and the three\n * things that made it one are now in place:\n *\n * - the budget is 5 x 400ms, and the error branch used to stop\n * retrying for good, while the heal is an AGL-664 in-place\n * re-auth that takes as long as a human takes to type a\n * password. A resolved re-auth now broadcasts and this listener\n * reopens on it (`subscribeFirestoreSessionHeal` below), and a\n * refusal streak keeps a slow road back for a recovery nobody\n * announced (see the error branch);\n * - `status: 'error'` had to become STICKY, or the cached emission\n * that precedes each refusal would flip it straight back — see\n * `terminal` above;\n * - the surfaces that BLANK on `error` had to learn the\n * difference between \"never had data\" and \"have data, the server\n * refused\". They read `hasEmitted` now, so the besigner canvas\n * and the host setup Theme tab keep rendering across a refusal\n * instead of collapsing to \"Not found\".\n *\n * The withholding is keyed on a REFUSAL having happened, not on the\n * emission being cached, and that is load-bearing: offline stays\n * exactly as inert as it was. A lost network yields `unavailable`\n * (when it yields an error callback at all), which never enters\n * `deniedStreak`, so a cached emission still refunds the budget and\n * an offline listener still never goes terminal. The cache exists\n * for offline; this must not change what happens there.\n */\n // Only the SERVER answering is evidence the session can read.\n if (!snapshot.metadata.fromCache) {\n disarmStall()\n noteFirestoreServerAnswer(q.firestore)\n attempt = 0\n deniedStreak = 0\n denialReported = false\n setServerDenied(false)\n // Proof the session can read — stronger than any accumulated\n // denial, and what stops a scoped collaborator's by-design\n // denials from ever adding up to a re-auth prompt.\n reportFirestoreServerRead()\n } else if (deniedStreak === 0) {\n // Cached, but nothing has been refused since the server last\n // answered — so this is not the AGL-1066 fault and the budget is\n // refunded exactly as it always was.\n attempt = 0\n }\n\n // Only the values count: a metadata-only tick is not a change.\n const changed = snapshot.docChanges?.().length > 0\n\n if (confirmDisappearances) {\n const present = new Set(snapshot.docs.map((d) => d.id))\n const vanished = [...seen].filter(\n (id) => !present.has(id) && !confirmedGone.has(id),\n )\n if (vanished.length) {\n // A fresh (non-resumed) read ignores the resume token, returns\n // the true set and rewrites the cache, dropping any tombstone.\n getDocsFromServer(q)\n .then((fresh) => {\n if (cancelled) return\n const freshIds = new Set(fresh.docs.map((d) => d.id))\n // Only an absence the SERVER agrees with is real. One that\n // came back was a tombstone and must stay eligible to heal\n // if it vanishes again.\n vanished.forEach((id) => {\n if (!freshIds.has(id)) confirmedGone.add(id)\n })\n freshIds.forEach((id) => seen.add(id))\n // `getDocsFromServer` is server-confirmed by definition.\n emit(fresh.docs, false, true)\n })\n .catch(() => {\n // Couldn't confirm: show the live result rather than an\n // error. A possibly-short list beats an empty one.\n if (!cancelled) {\n emit(snapshot.docs, snapshot.metadata.fromCache, changed)\n }\n })\n return\n }\n snapshot.docs.forEach((d) => seen.add(d.id))\n }\n\n emit(snapshot.docs, snapshot.metadata.fromCache, changed)\n },\n (err) => {\n if (cancelled) return\n disarmStall()\n confirmation.release()\n unsubscribe?.()\n // Say so once per outage, and only for a refusal — a lost network\n // produces no error callback at all, so this cannot fire offline.\n if (err?.code === 'permission-denied') {\n deniedStreak += 1\n // When the streak began — the reference point that lets\n // `refusedRetryDelayMs` ask whether the session has read from\n // the server SINCE this listen started being refused (AGL-1440).\n if (deniedStreak === 1) deniedStreakStartedAt = Date.now()\n if (deniedStreak >= DENIAL_STREAK_TO_REPORT) {\n setServerDenied(true)\n if (!denialReported) {\n denialReported = true\n reportFirestoreDenial(denialLabel)\n }\n }\n }\n if (attempt < MAX_RETRIES) {\n attempt += 1\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n } else {\n timer = setTimeout(subscribe, RETRY_DELAY_MS)\n }\n } else {\n terminal = true\n setStatus('error')\n setError(err)\n /**\n * A refusal streak keeps a slow road back (AGL-1066).\n *\n * Before the flip this listener reopened forever, which is also\n * what HEALED it — a token that attached late, an App Check\n * hiccup, one of the AGL-1143 transient token-layer denials.\n * None of those broadcast a heal, because none of them involved\n * a re-auth the console asked for, so stopping here would leave\n * every listen in the console terminal until the user reloaded.\n * The status is corrected; the recovery is not taken away.\n *\n * Any OTHER terminal error still stops exactly as before — this\n * is deliberately keyed on the refusal streak, not on `attempt`.\n * How slow the road is depends on whether the refusal looks like\n * the session or the ref (AGL-1440) and on how long it has\n * lasted (AGL-2945), and a hidden tab waits to be looked at\n * (AGL-2944) — see `scheduleRefusedReopen`.\n */\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n }\n }\n },\n )\n }\n subscribe()\n\n /**\n * The session came back — reopen NOW rather than on the next tick of a\n * cadence tuned for a session that has not (AGL-1066).\n *\n * Gated on this listener actually being refused. A healthy listener has\n * an open subscription and nothing to recover, so it must ignore the\n * broadcast entirely: without this gate a heal would tear down and\n * reopen every listen in the console at once, which is a listener storm\n * dressed up as a fix.\n *\n * What is refunded is `attempt` — the retry BUDGET, which was spent on a\n * fault that is now over. `deniedStreak` is deliberately left alone: it\n * is evidence about the server, and only the server answering may clear\n * it. So `serverDenied` stays true across the heal and goes false on the\n * snapshot that actually proves the read works, and a heal that turns\n * out to be wishful thinking falls straight back to the slow cadence\n * instead of resuming a 400ms storm.\n *\n * `denialReported` IS reset: the outage ended here. If reads are still\n * refused afterwards that is a new one, and it has to be able to raise\n * the AGL-1063 banner again.\n */\n const unsubscribeHeal = subscribeFirestoreSessionHeal(() => {\n if (cancelled || deniedStreak === 0) return\n if (timer) {\n clearTimeout(timer)\n timer = null\n }\n cancelRefusedReopen?.()\n cancelRefusedReopen = null\n unsubscribe?.()\n attempt = 0\n denialReported = false\n subscribe()\n })\n\n return () => {\n cancelled = true\n disarmStall()\n confirmation.close()\n unsubscribeHeal()\n if (timer) clearTimeout(timer)\n cancelRefusedReopen?.()\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps)\n\n return { data, status, error, fromCache, serverDenied, listen }\n}\n\nexport default useFirestoreCollection\n"],"names":["getDocsFromServer","onSnapshot","useEffect","useRef","useState","CONFIRMABLE_LISTEN_OPTIONS","DENIAL_STREAK_TO_REPORT","denialLabelForQuery","reportFirestoreDenial","reportFirestoreServerRead","scheduleRefusedReopen","subscribeFirestoreSessionHeal","armFirestoreStallWatch","noteFirestoreServerAnswer","createListenHandle","trackListenConfirmation","RETRY_DELAY_MS","MAX_RETRIES","useFirestoreCollection","buildQuery","deps","options","data","setData","status","setStatus","error","setError","undefined","fromCache","setFromCache","serverDenied","setServerDenied","listen","buildQueryRef","current","idField","confirmDisappearances","q","cancelled","unsubscribe","timer","cancelRefusedReopen","attempt","deniedStreak","deniedStreakStartedAt","denialReported","terminal","denialLabel","disarmStall","firestore","confirmation","onLapse","shownFromCache","seen","Set","confirmedGone","emit","docs","cached","changed","report","map","docSnap","value","id","subscribe","snapshot","metadata","docChanges","length","present","d","vanished","filter","has","then","fresh","freshIds","forEach","add","catch","err","release","code","Date","now","setTimeout","unsubscribeHeal","clearTimeout","close"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,iBAAiB,EACjBC,UAAU,QAKL,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAA6B,QAAO;AACxE,SAASC,0BAA0B,QAAQ,8BAA0B;AACrE,SACEC,uBAAuB,EACvBC,mBAAmB,EACnBC,qBAAqB,EACrBC,yBAAyB,EACzBC,qBAAqB,EACrBC,6BAA6B,QACxB,iCAA6B;AACpC,SACEC,sBA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;AAEA,eAAef,uBAAsB"}
|
|
@@ -97,7 +97,13 @@ const MAX_RETRIES = 5;
|
|
|
97
97
|
* first server-confirmed snapshot, by an error (a refusal is not a
|
|
98
98
|
* stall) and by cleanup.
|
|
99
99
|
*/ const disarmStall = armFirestoreStallWatch(ref.firestore);
|
|
100
|
-
/** What a save waits on while this listener is unconfirmed (AGL-4120). */ const confirmation = trackListenConfirmation(listen
|
|
100
|
+
/** What a save waits on while this listener is unconfirmed (AGL-4120). */ const confirmation = trackListenConfirmation(listen, {
|
|
101
|
+
// A confirmation kept through a fall back to the cache ran out
|
|
102
|
+
// before the server answered again (AGL-4047).
|
|
103
|
+
onLapse: ()=>{
|
|
104
|
+
if (!cancelled) setFromCache(true);
|
|
105
|
+
}
|
|
106
|
+
});
|
|
101
107
|
/** The cached snapshot on screen, while one is (AGL-4120). */ let shownFromCache = null;
|
|
102
108
|
const subscribe = ()=>{
|
|
103
109
|
unsubscribe = onSnapshot(ref, // Without this the cache→server confirmation is never delivered and
|
|
@@ -110,8 +116,9 @@ const MAX_RETRIES = 5;
|
|
|
110
116
|
setError(undefined);
|
|
111
117
|
}
|
|
112
118
|
setHasPendingWrites(snapshot.metadata.hasPendingWrites);
|
|
113
|
-
|
|
114
|
-
|
|
119
|
+
// The snapshot's own, unless it is a short fall back to the cache
|
|
120
|
+
// after a confirmation, which keeps it (AGL-4047).
|
|
121
|
+
setFromCache(confirmation.report(snapshot.metadata.fromCache, !snapshot.metadata.fromCache && shownFromCache !== null && !sameDocument(shownFromCache, snapshot)));
|
|
115
122
|
shownFromCache = snapshot.metadata.fromCache ? snapshot : null;
|
|
116
123
|
// Only the SERVER answering is evidence the session can read — and
|
|
117
124
|
// the only thing that refunds the retry budget (AGL-1066). See the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-firestore-doc.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'use client'\n\nimport {\n onSnapshot,\n type DocumentData,\n type DocumentReference,\n type DocumentSnapshot,\n type FirestoreError,\n} from 'firebase/firestore'\nimport { useEffect, useRef, useState, type DependencyList } from 'react'\nimport { CONFIRMABLE_LISTEN_OPTIONS } from './helpers/listen-options'\nimport {\n DENIAL_STREAK_TO_REPORT,\n denialLabelForQuery,\n reportFirestoreDenial,\n reportFirestoreServerRead,\n scheduleRefusedReopen,\n subscribeFirestoreSessionHeal,\n} from './firestore-denial-reporter'\nimport {\n armFirestoreStallWatch,\n noteFirestoreServerAnswer,\n} from './firebase/firestore-stall-recovery'\nimport {\n createListenHandle,\n sameDocument,\n trackListenConfirmation,\n type ListenHandle,\n} from './helpers/listen-confirmation'\n\nconst RETRY_DELAY_MS = 400\nconst MAX_RETRIES = 5\n// The refused cadence is shared policy — see `scheduleRefusedReopen` in\n// `firestore-denial-reporter.ts` (AGL-1066, AGL-1440, AGL-2944, AGL-2945).\n\nexport type FirestoreDocStatus = 'loading' | 'success' | 'error'\n\nexport interface UseFirestoreDocOptions {\n idField?: string\n}\n\nexport interface UseFirestoreDocResult<T> {\n data: T | undefined\n status: FirestoreDocStatus\n error: FirestoreError | undefined\n /**\n * `data` still carries writes this client made that the server has NOT\n * acknowledged. Carried rather than dropped for the same reason as\n * `ObservableStatus.hasPendingWrites` — see that comment (AGL-1262).\n */\n hasPendingWrites: boolean\n /**\n * `data` came from the local cache and the server has not confirmed it\n * (AGL-1066). See `ObservableStatus.fromCache` for why this matters and\n * why it is the signal to reach for rather than `staleSession`.\n */\n fromCache: boolean\n /**\n * The server has REFUSED this listen for longer than the retry budget and\n * no server snapshot has arrived since (AGL-1066) — the reason behind an\n * `error`, not a duplicate of it. See\n * `UseFirestoreCollectionResult.serverDenied`.\n */\n serverDenied: boolean\n /**\n * This hook's listener, for a guarded save seeded from `data` to wait on\n * alone (`writeGuardedBySeed`'s `listen`, AGL-4135). Stable for the life of\n * the hook.\n */\n listen: ListenHandle\n}\n\n/** Where a document read stands: still loading, failed, answered with nothing, or answered. */\nexport type FirestoreDocPhase = 'loading' | 'error' | 'missing' | 'ready'\n\n/**\n * Where a {@link useFirestoreDoc} read stands (AGL-4089), for a page that\n * must not state a document's empty values as facts while it loads. A\n * document is only `missing` once the SERVER says so: the cache answers\n * \"missing\" first for a document it has never held, and while another tab\n * holds the shared cache that answer can stand for half a minute.\n */\nexport function firestoreDocPhase(\n read: Pick<UseFirestoreDocResult<unknown>, 'data' | 'status' | 'fromCache'>,\n): FirestoreDocPhase {\n if (read.data) return 'ready'\n if (read.status === 'error') return 'error'\n return read.status === 'loading' || read.fromCache ? 'loading' : 'missing'\n}\n\n/**\n * Single-document counterpart to `useFirestoreCollection` — see that hook's\n * doc comment for why this exists instead of reactfire's\n * `useFirestoreDocData` (AGL-216/217).\n *\n * `buildRef` is re-invoked from `deps` the same way a `useEffect`/`useMemo`\n * callback would be — pass the same primitive values (ids, uid, firestore)\n * you'd put in a `useMemo` dependency array, not the `DocumentReference`\n * object itself.\n */\nexport function useFirestoreDoc<T = DocumentData>(\n buildRef: () => DocumentReference<DocumentData> | null | undefined,\n deps: DependencyList,\n options: UseFirestoreDocOptions = {},\n): UseFirestoreDocResult<T> {\n const [data, setData] = useState<T | undefined>(undefined)\n const [status, setStatus] = useState<FirestoreDocStatus>('loading')\n const [error, setError] = useState<FirestoreError | undefined>(undefined)\n const [hasPendingWrites, setHasPendingWrites] = useState(false)\n // Un-confirmed until a snapshot says otherwise: a hook that has not heard\n // from the server yet must not read as server-confirmed.\n const [fromCache, setFromCache] = useState(true)\n const [serverDenied, setServerDenied] = useState(false)\n const [listen] = useState(createListenHandle)\n const buildRefRef = useRef(buildRef)\n buildRefRef.current = buildRef\n const idField = options.idField\n\n useEffect(() => {\n setStatus('loading')\n setError(undefined)\n // Clear on every dep change (AGL-591): a scope move between two live\n // refs must not keep showing the previous doc until the new snapshot\n // arrives. Mirrors use-firestore-collection.\n setData(undefined)\n setHasPendingWrites(false)\n setFromCache(true)\n setServerDenied(false)\n\n const ref = buildRefRef.current()\n if (!ref) {\n return\n }\n\n let cancelled = false\n let unsubscribe: (() => void) | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n /** Cancels a pending reopen on the refused cadence (AGL-2944). */\n let cancelRefusedReopen: (() => void) | null = null\n let attempt = 0\n // Refusals since the last SERVER snapshot (AGL-1066) — see the note on\n // `DENIAL_STREAK_TO_REPORT` for why this is not `attempt`.\n let deniedStreak = 0\n /** Epoch ms of the current streak's first refusal (AGL-1440). */\n let deniedStreakStartedAt = 0\n let denialReported = false\n /**\n * The retry budget is spent and the server's last word was a refusal —\n * what keeps `status: 'error'` from being undone by the cached emission\n * that precedes every reopened refusal (AGL-1066). See the longer note\n * on the same variable in `use-firestore-collection`.\n */\n let terminal = false\n const denialLabel = denialLabelForQuery(ref)\n /**\n * A listen the server has not confirmed within `FIRESTORE_STALL_MS`,\n * while the browser is online and the tab is visible, is the multi-tab\n * wedge (AGL-3373): no tab is syncing, so an empty cache raises no first\n * snapshot at all and a warm one never confirms. The client is asked to\n * recover — a network cycle that forces the lease election — and this\n * listener then hears from the server like any other. Disarmed by the\n * first server-confirmed snapshot, by an error (a refusal is not a\n * stall) and by cleanup.\n */\n const disarmStall = armFirestoreStallWatch(ref.firestore)\n /** What a save waits on while this listener is unconfirmed (AGL-4120). */\n const confirmation = trackListenConfirmation(listen)\n /** The cached snapshot on screen, while one is (AGL-4120). */\n let shownFromCache: DocumentSnapshot<DocumentData> | null = null\n\n const subscribe = () => {\n unsubscribe = onSnapshot(\n ref,\n // Without this the cache→server confirmation is never delivered and\n // `fromCache` latches true for the life of the listener, refusing\n // every guarded save on the page (AGL-2486). See `listen-options.ts`.\n CONFIRMABLE_LISTEN_OPTIONS,\n (snapshot) => {\n if (cancelled) return\n if (!terminal) {\n setStatus('success')\n setError(undefined)\n }\n setHasPendingWrites(snapshot.metadata.hasPendingWrites)\n setFromCache(snapshot.metadata.fromCache)\n confirmation.report(\n snapshot.metadata.fromCache,\n !snapshot.metadata.fromCache &&\n shownFromCache !== null &&\n !sameDocument(shownFromCache, snapshot),\n )\n shownFromCache = snapshot.metadata.fromCache ? snapshot : null\n // Only the SERVER answering is evidence the session can read — and\n // the only thing that refunds the retry budget (AGL-1066). See the\n // long note on the same gate in `use-firestore-collection`.\n if (!snapshot.metadata.fromCache) {\n disarmStall()\n noteFirestoreServerAnswer(ref.firestore)\n attempt = 0\n terminal = false\n setStatus('success')\n setError(undefined)\n deniedStreak = 0\n denialReported = false\n setServerDenied(false)\n // Proof the session can read — stronger than any accumulated\n // denial, and what stops a scoped collaborator's by-design\n // denials from ever adding up to a re-auth prompt.\n reportFirestoreServerRead()\n } else if (deniedStreak === 0) {\n // Cached, but nothing has been refused since the server last\n // answered — not the AGL-1066 fault, so the budget is refunded\n // exactly as it always was. This is what keeps offline inert:\n // `unavailable` never enters `deniedStreak`.\n attempt = 0\n }\n if (!snapshot.exists()) {\n setData(undefined)\n return\n }\n const value = { ...snapshot.data() } as Record<string, unknown>\n if (idField) value[idField] = snapshot.id\n setData(value as T)\n },\n (err) => {\n if (cancelled) return\n disarmStall()\n confirmation.release()\n unsubscribe?.()\n // Say so once per outage, and only for a refusal — a lost network\n // produces no error callback at all, so this cannot fire offline.\n if (err?.code === 'permission-denied') {\n deniedStreak += 1\n if (deniedStreak === 1) deniedStreakStartedAt = Date.now()\n if (deniedStreak >= DENIAL_STREAK_TO_REPORT) {\n setServerDenied(true)\n if (!denialReported) {\n denialReported = true\n reportFirestoreDenial(denialLabel)\n }\n }\n }\n if (attempt < MAX_RETRIES) {\n attempt += 1\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n } else {\n timer = setTimeout(subscribe, RETRY_DELAY_MS)\n }\n } else {\n terminal = true\n setStatus('error')\n setError(err)\n // A refusal streak keeps a slow road back for a recovery nobody\n // announced — see the same branch in `use-firestore-collection`.\n // The cadence splits on session-vs-ref evidence (AGL-1440), grows\n // with the streak's age (AGL-2945) and waits while the tab is\n // hidden (AGL-2944).\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n }\n }\n },\n )\n }\n subscribe()\n\n // Reopen when the session heals — see the long note on the same\n // subscription in `use-firestore-collection` (AGL-1066). Gated on this\n // listen actually being refused, so a healthy one ignores the broadcast.\n const unsubscribeHeal = subscribeFirestoreSessionHeal(() => {\n if (cancelled || deniedStreak === 0) return\n if (timer) {\n clearTimeout(timer)\n timer = null\n }\n cancelRefusedReopen?.()\n cancelRefusedReopen = null\n unsubscribe?.()\n attempt = 0\n denialReported = false\n subscribe()\n })\n\n return () => {\n cancelled = true\n disarmStall()\n confirmation.close()\n unsubscribeHeal()\n if (timer) clearTimeout(timer)\n cancelRefusedReopen?.()\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps)\n\n return { data, status, error, hasPendingWrites, fromCache, serverDenied, listen }\n}\n\nexport default useFirestoreDoc\n"],"names":["onSnapshot","useEffect","useRef","useState","CONFIRMABLE_LISTEN_OPTIONS","DENIAL_STREAK_TO_REPORT","denialLabelForQuery","reportFirestoreDenial","reportFirestoreServerRead","scheduleRefusedReopen","subscribeFirestoreSessionHeal","armFirestoreStallWatch","noteFirestoreServerAnswer","createListenHandle","sameDocument","trackListenConfirmation","RETRY_DELAY_MS","MAX_RETRIES","firestoreDocPhase","read","data","status","fromCache","useFirestoreDoc","buildRef","deps","options","setData","undefined","setStatus","error","setError","hasPendingWrites","setHasPendingWrites","setFromCache","serverDenied","setServerDenied","listen","buildRefRef","current","idField","ref","cancelled","unsubscribe","timer","cancelRefusedReopen","attempt","deniedStreak","deniedStreakStartedAt","denialReported","terminal","denialLabel","disarmStall","firestore","confirmation","shownFromCache","subscribe","snapshot","metadata","report","exists","value","id","err","release","code","Date","now","setTimeout","unsubscribeHeal","clearTimeout","close"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,UAAU,QAKL,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAA6B,QAAO;AACxE,SAASC,0BAA0B,QAAQ,8BAA0B;AACrE,SACEC,uBAAuB,EACvBC,mBAAmB,EACnBC,qBAAqB,EACrBC,yBAAyB,EACzBC,qBAAqB,EACrBC,6BAA6B,QACxB,iCAA6B;AACpC,SACEC,sBAAsB,EACtBC,yBAAyB,QACpB,yCAAqC;AAC5C,SACEC,kBAAkB,EAClBC,YAAY,EACZC,uBAAuB,QAElB,mCAA+B;AAEtC,MAAMC,iBAAiB;AACvB,MAAMC,cAAc;AA4CpB;;;;;;CAMC,GACD,OAAO,SAASC,kBACdC,IAA2E;IAE3E,IAAIA,KAAKC,IAAI,EAAE,OAAO;IACtB,IAAID,KAAKE,MAAM,KAAK,SAAS,OAAO;IACpC,OAAOF,KAAKE,MAAM,KAAK,aAAaF,KAAKG,SAAS,GAAG,YAAY;AACnE;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASC,gBACdC,QAAkE,EAClEC,IAAoB,EACpBC,UAAkC,CAAC,CAAC;IAEpC,MAAM,CAACN,MAAMO,QAAQ,GAAGxB,SAAwByB;IAChD,MAAM,CAACP,QAAQQ,UAAU,GAAG1B,SAA6B;IACzD,MAAM,CAAC2B,OAAOC,SAAS,GAAG5B,SAAqCyB;IAC/D,MAAM,CAACI,kBAAkBC,oBAAoB,GAAG9B,SAAS;IACzD,0EAA0E;IAC1E,yDAAyD;IACzD,MAAM,CAACmB,WAAWY,aAAa,GAAG/B,SAAS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,WAAWxC;oBAChC;gBACF,OAAO;oBACLkC,WAAW;oBACXrB,UAAU;oBACVE,SAASgC;oBACT,gEAAgE;oBAChE,iEAAiE;oBACjE,kEAAkE;oBAClE,8DAA8D;oBAC9D,qBAAqB;oBACrB,IAAIhB,eAAe9B,aAAa;wBAC9B4B,sBAAsBpC,sBACpB+C,WACAR;oBAEJ;gBACF;YACF;QAEJ;QACAQ;QAEA,gEAAgE;QAChE,uEAAuE;QACvE,yEAAyE;QACzE,MAAMa,kBAAkB3D,8BAA8B;YACpD,IAAIgC,aAAaK,iBAAiB,GAAG;YACrC,IAAIH,OAAO;gBACT0B,aAAa1B;gBACbA,QAAQ;YACV;YACAC,uCAAAA;YACAA,sBAAsB;YACtBF,+BAAAA;YACAG,UAAU;YACVG,iBAAiB;YACjBO;QACF;QAEA,OAAO;YACLd,YAAY;YACZU;YACAE,aAAaiB,KAAK;YAClBF;YACA,IAAIzB,OAAO0B,aAAa1B;YACxBC,uCAAAA;YACAF,+BAAAA;QACF;IACA,uDAAuD;IACzD,GAAGlB;IAEH,OAAO;QAAEL;QAAMC;QAAQS;QAAOE;QAAkBV;QAAWa;QAAcE;IAAO;AAClF;AAEA,eAAed,gBAAe"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-firestore-doc.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'use client'\n\nimport {\n onSnapshot,\n type DocumentData,\n type DocumentReference,\n type DocumentSnapshot,\n type FirestoreError,\n} from 'firebase/firestore'\nimport { useEffect, useRef, useState, type DependencyList } from 'react'\nimport { CONFIRMABLE_LISTEN_OPTIONS } from './helpers/listen-options'\nimport {\n DENIAL_STREAK_TO_REPORT,\n denialLabelForQuery,\n reportFirestoreDenial,\n reportFirestoreServerRead,\n scheduleRefusedReopen,\n subscribeFirestoreSessionHeal,\n} from './firestore-denial-reporter'\nimport {\n armFirestoreStallWatch,\n noteFirestoreServerAnswer,\n} from './firebase/firestore-stall-recovery'\nimport {\n createListenHandle,\n sameDocument,\n trackListenConfirmation,\n type ListenHandle,\n} from './helpers/listen-confirmation'\n\nconst RETRY_DELAY_MS = 400\nconst MAX_RETRIES = 5\n// The refused cadence is shared policy — see `scheduleRefusedReopen` in\n// `firestore-denial-reporter.ts` (AGL-1066, AGL-1440, AGL-2944, AGL-2945).\n\nexport type FirestoreDocStatus = 'loading' | 'success' | 'error'\n\nexport interface UseFirestoreDocOptions {\n idField?: string\n}\n\nexport interface UseFirestoreDocResult<T> {\n data: T | undefined\n status: FirestoreDocStatus\n error: FirestoreError | undefined\n /**\n * `data` still carries writes this client made that the server has NOT\n * acknowledged. Carried rather than dropped for the same reason as\n * `ObservableStatus.hasPendingWrites` — see that comment (AGL-1262).\n */\n hasPendingWrites: boolean\n /**\n * `data` came from the local cache and the server has not confirmed it\n * (AGL-1066). See `ObservableStatus.fromCache` for why this matters and\n * why it is the signal to reach for rather than `staleSession`.\n */\n fromCache: boolean\n /**\n * The server has REFUSED this listen for longer than the retry budget and\n * no server snapshot has arrived since (AGL-1066) — the reason behind an\n * `error`, not a duplicate of it. See\n * `UseFirestoreCollectionResult.serverDenied`.\n */\n serverDenied: boolean\n /**\n * This hook's listener, for a guarded save seeded from `data` to wait on\n * alone (`writeGuardedBySeed`'s `listen`, AGL-4135). Stable for the life of\n * the hook.\n */\n listen: ListenHandle\n}\n\n/** Where a document read stands: still loading, failed, answered with nothing, or answered. */\nexport type FirestoreDocPhase = 'loading' | 'error' | 'missing' | 'ready'\n\n/**\n * Where a {@link useFirestoreDoc} read stands (AGL-4089), for a page that\n * must not state a document's empty values as facts while it loads. A\n * document is only `missing` once the SERVER says so: the cache answers\n * \"missing\" first for a document it has never held, and while another tab\n * holds the shared cache that answer can stand for half a minute.\n */\nexport function firestoreDocPhase(\n read: Pick<UseFirestoreDocResult<unknown>, 'data' | 'status' | 'fromCache'>,\n): FirestoreDocPhase {\n if (read.data) return 'ready'\n if (read.status === 'error') return 'error'\n return read.status === 'loading' || read.fromCache ? 'loading' : 'missing'\n}\n\n/**\n * Single-document counterpart to `useFirestoreCollection` — see that hook's\n * doc comment for why this exists instead of reactfire's\n * `useFirestoreDocData` (AGL-216/217).\n *\n * `buildRef` is re-invoked from `deps` the same way a `useEffect`/`useMemo`\n * callback would be — pass the same primitive values (ids, uid, firestore)\n * you'd put in a `useMemo` dependency array, not the `DocumentReference`\n * object itself.\n */\nexport function useFirestoreDoc<T = DocumentData>(\n buildRef: () => DocumentReference<DocumentData> | null | undefined,\n deps: DependencyList,\n options: UseFirestoreDocOptions = {},\n): UseFirestoreDocResult<T> {\n const [data, setData] = useState<T | undefined>(undefined)\n const [status, setStatus] = useState<FirestoreDocStatus>('loading')\n const [error, setError] = useState<FirestoreError | undefined>(undefined)\n const [hasPendingWrites, setHasPendingWrites] = useState(false)\n // Un-confirmed until a snapshot says otherwise: a hook that has not heard\n // from the server yet must not read as server-confirmed.\n const [fromCache, setFromCache] = useState(true)\n const [serverDenied, setServerDenied] = useState(false)\n const [listen] = useState(createListenHandle)\n const buildRefRef = useRef(buildRef)\n buildRefRef.current = buildRef\n const idField = options.idField\n\n useEffect(() => {\n setStatus('loading')\n setError(undefined)\n // Clear on every dep change (AGL-591): a scope move between two live\n // refs must not keep showing the previous doc until the new snapshot\n // arrives. Mirrors use-firestore-collection.\n setData(undefined)\n setHasPendingWrites(false)\n setFromCache(true)\n setServerDenied(false)\n\n const ref = buildRefRef.current()\n if (!ref) {\n return\n }\n\n let cancelled = false\n let unsubscribe: (() => void) | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n /** Cancels a pending reopen on the refused cadence (AGL-2944). */\n let cancelRefusedReopen: (() => void) | null = null\n let attempt = 0\n // Refusals since the last SERVER snapshot (AGL-1066) — see the note on\n // `DENIAL_STREAK_TO_REPORT` for why this is not `attempt`.\n let deniedStreak = 0\n /** Epoch ms of the current streak's first refusal (AGL-1440). */\n let deniedStreakStartedAt = 0\n let denialReported = false\n /**\n * The retry budget is spent and the server's last word was a refusal —\n * what keeps `status: 'error'` from being undone by the cached emission\n * that precedes every reopened refusal (AGL-1066). See the longer note\n * on the same variable in `use-firestore-collection`.\n */\n let terminal = false\n const denialLabel = denialLabelForQuery(ref)\n /**\n * A listen the server has not confirmed within `FIRESTORE_STALL_MS`,\n * while the browser is online and the tab is visible, is the multi-tab\n * wedge (AGL-3373): no tab is syncing, so an empty cache raises no first\n * snapshot at all and a warm one never confirms. The client is asked to\n * recover — a network cycle that forces the lease election — and this\n * listener then hears from the server like any other. Disarmed by the\n * first server-confirmed snapshot, by an error (a refusal is not a\n * stall) and by cleanup.\n */\n const disarmStall = armFirestoreStallWatch(ref.firestore)\n /** What a save waits on while this listener is unconfirmed (AGL-4120). */\n const confirmation = trackListenConfirmation(listen, {\n // A confirmation kept through a fall back to the cache ran out\n // before the server answered again (AGL-4047).\n onLapse: () => {\n if (!cancelled) setFromCache(true)\n },\n })\n /** The cached snapshot on screen, while one is (AGL-4120). */\n let shownFromCache: DocumentSnapshot<DocumentData> | null = null\n\n const subscribe = () => {\n unsubscribe = onSnapshot(\n ref,\n // Without this the cache→server confirmation is never delivered and\n // `fromCache` latches true for the life of the listener, refusing\n // every guarded save on the page (AGL-2486). See `listen-options.ts`.\n CONFIRMABLE_LISTEN_OPTIONS,\n (snapshot) => {\n if (cancelled) return\n if (!terminal) {\n setStatus('success')\n setError(undefined)\n }\n setHasPendingWrites(snapshot.metadata.hasPendingWrites)\n // The snapshot's own, unless it is a short fall back to the cache\n // after a confirmation, which keeps it (AGL-4047).\n setFromCache(\n confirmation.report(\n snapshot.metadata.fromCache,\n !snapshot.metadata.fromCache &&\n shownFromCache !== null &&\n !sameDocument(shownFromCache, snapshot),\n ),\n )\n shownFromCache = snapshot.metadata.fromCache ? snapshot : null\n // Only the SERVER answering is evidence the session can read — and\n // the only thing that refunds the retry budget (AGL-1066). See the\n // long note on the same gate in `use-firestore-collection`.\n if (!snapshot.metadata.fromCache) {\n disarmStall()\n noteFirestoreServerAnswer(ref.firestore)\n attempt = 0\n terminal = false\n setStatus('success')\n setError(undefined)\n deniedStreak = 0\n denialReported = false\n setServerDenied(false)\n // Proof the session can read — stronger than any accumulated\n // denial, and what stops a scoped collaborator's by-design\n // denials from ever adding up to a re-auth prompt.\n reportFirestoreServerRead()\n } else if (deniedStreak === 0) {\n // Cached, but nothing has been refused since the server last\n // answered — not the AGL-1066 fault, so the budget is refunded\n // exactly as it always was. This is what keeps offline inert:\n // `unavailable` never enters `deniedStreak`.\n attempt = 0\n }\n if (!snapshot.exists()) {\n setData(undefined)\n return\n }\n const value = { ...snapshot.data() } as Record<string, unknown>\n if (idField) value[idField] = snapshot.id\n setData(value as T)\n },\n (err) => {\n if (cancelled) return\n disarmStall()\n confirmation.release()\n unsubscribe?.()\n // Say so once per outage, and only for a refusal — a lost network\n // produces no error callback at all, so this cannot fire offline.\n if (err?.code === 'permission-denied') {\n deniedStreak += 1\n if (deniedStreak === 1) deniedStreakStartedAt = Date.now()\n if (deniedStreak >= DENIAL_STREAK_TO_REPORT) {\n setServerDenied(true)\n if (!denialReported) {\n denialReported = true\n reportFirestoreDenial(denialLabel)\n }\n }\n }\n if (attempt < MAX_RETRIES) {\n attempt += 1\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n } else {\n timer = setTimeout(subscribe, RETRY_DELAY_MS)\n }\n } else {\n terminal = true\n setStatus('error')\n setError(err)\n // A refusal streak keeps a slow road back for a recovery nobody\n // announced — see the same branch in `use-firestore-collection`.\n // The cadence splits on session-vs-ref evidence (AGL-1440), grows\n // with the streak's age (AGL-2945) and waits while the tab is\n // hidden (AGL-2944).\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n }\n }\n },\n )\n }\n subscribe()\n\n // Reopen when the session heals — see the long note on the same\n // subscription in `use-firestore-collection` (AGL-1066). Gated on this\n // listen actually being refused, so a healthy one ignores the broadcast.\n const unsubscribeHeal = subscribeFirestoreSessionHeal(() => {\n if (cancelled || deniedStreak === 0) return\n if (timer) {\n clearTimeout(timer)\n timer = null\n }\n cancelRefusedReopen?.()\n cancelRefusedReopen = null\n unsubscribe?.()\n attempt = 0\n denialReported = false\n subscribe()\n })\n\n return () => {\n cancelled = true\n disarmStall()\n confirmation.close()\n unsubscribeHeal()\n if (timer) clearTimeout(timer)\n cancelRefusedReopen?.()\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps)\n\n return { data, status, error, hasPendingWrites, fromCache, serverDenied, listen }\n}\n\nexport default useFirestoreDoc\n"],"names":["onSnapshot","useEffect","useRef","useState","CONFIRMABLE_LISTEN_OPTIONS","DENIAL_STREAK_TO_REPORT","denialLabelForQuery","reportFirestoreDenial","reportFirestoreServerRead","scheduleRefusedReopen","subscribeFirestoreSessionHeal","armFirestoreStallWatch","noteFirestoreServerAnswer","createListenHandle","sameDocument","trackListenConfirmation","RETRY_DELAY_MS","MAX_RETRIES","firestoreDocPhase","read","data","status","fromCache","useFirestoreDoc","buildRef","deps","options","setData","undefined","setStatus","error","setError","hasPendingWrites","setHasPendingWrites","setFromCache","serverDenied","setServerDenied","listen","buildRefRef","current","idField","ref","cancelled","unsubscribe","timer","cancelRefusedReopen","attempt","deniedStreak","deniedStreakStartedAt","denialReported","terminal","denialLabel","disarmStall","firestore","confirmation","onLapse","shownFromCache","subscribe","snapshot","metadata","report","exists","value","id","err","release","code","Date","now","setTimeout","unsubscribeHeal","clearTimeout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