@ttt-productions/query-core 0.14.1 → 0.14.2
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/dist/domain-events/cache-invalidation.d.ts +21 -0
- package/dist/domain-events/cache-invalidation.d.ts.map +1 -1
- package/dist/domain-events/cache-invalidation.js +58 -19
- package/dist/domain-events/cache-invalidation.js.map +1 -1
- package/dist/react/firestore/absence-scheduler.d.ts +39 -0
- package/dist/react/firestore/absence-scheduler.d.ts.map +1 -0
- package/dist/react/firestore/absence-scheduler.js +182 -0
- package/dist/react/firestore/absence-scheduler.js.map +1 -0
- package/dist/react/firestore/batch-doc-loader.d.ts +45 -0
- package/dist/react/firestore/batch-doc-loader.d.ts.map +1 -0
- package/dist/react/firestore/batch-doc-loader.js +179 -0
- package/dist/react/firestore/batch-doc-loader.js.map +1 -0
- package/dist/react/firestore/doc-subscription-registry.d.ts +9 -0
- package/dist/react/firestore/doc-subscription-registry.d.ts.map +1 -1
- package/dist/react/firestore/doc-subscription-registry.js +0 -0
- package/dist/react/firestore/doc-subscription-registry.js.map +1 -1
- package/dist/react/firestore/useBatchFirestoreDocs.d.ts +63 -21
- package/dist/react/firestore/useBatchFirestoreDocs.d.ts.map +1 -1
- package/dist/react/firestore/useBatchFirestoreDocs.js +117 -109
- package/dist/react/firestore/useBatchFirestoreDocs.js.map +1 -1
- package/dist/react/index.d.ts +2 -1
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +1 -0
- package/dist/react/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -24,5 +24,26 @@ export declare function predicate(description: string, match: (query: Query) =>
|
|
|
24
24
|
refetchType?: RefetchType;
|
|
25
25
|
}): CacheInvalidation;
|
|
26
26
|
export declare function serializeInvalidation(inv: CacheInvalidation): string;
|
|
27
|
+
/**
|
|
28
|
+
* Dispatch a deduplicated list of cache invalidations.
|
|
29
|
+
*
|
|
30
|
+
* Synchronous by contract: the underlying `invalidateQueries` / `cancelQueries`
|
|
31
|
+
* promises are fire-and-forget, so a mutation success path never awaits its own
|
|
32
|
+
* cache refresh.
|
|
33
|
+
*
|
|
34
|
+
* Before each invalidation, any query it matches that is mid-PENDING-INITIAL-READ
|
|
35
|
+
* is cancelled (see `cancelPendingInitialReads`) so a read that started before
|
|
36
|
+
* the write committed can never land as the query's first — and freshly-marked —
|
|
37
|
+
* value.
|
|
38
|
+
*
|
|
39
|
+
* `refetchType` governs whether that cancellation happens:
|
|
40
|
+
* - `'active'` (the default) and `'all'` cancel-then-invalidate every matched
|
|
41
|
+
* pending initial read — including one TanStack's refetch pass will not
|
|
42
|
+
* restart, since a stale first value would otherwise land and mark the query
|
|
43
|
+
* fresh, while a cancelled one simply refetches for its next observer.
|
|
44
|
+
* - `'none'` invalidates WITHOUT cancelling: the caller has asked for no
|
|
45
|
+
* refetch at all, so cancelling would abandon the only in-flight read the
|
|
46
|
+
* consumer has and leave it with no data and no pending request.
|
|
47
|
+
*/
|
|
27
48
|
export declare function applyInvalidations(queryClient: QueryClient, invalidations: ReadonlyArray<CacheInvalidation>): void;
|
|
28
49
|
//# sourceMappingURL=cache-invalidation.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-invalidation.d.ts","sourceRoot":"","sources":["../../src/domain-events/cache-invalidation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,WAAW,
|
|
1
|
+
{"version":3,"file":"cache-invalidation.d.ts","sourceRoot":"","sources":["../../src/domain-events/cache-invalidation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,WAAW,EAAgB,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAExF,MAAM,MAAM,WAAW,GAAG,QAAQ,GAAG,KAAK,GAAG,MAAM,CAAC;AAEpD,MAAM,MAAM,iBAAiB,GACzB;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,QAAQ,EAAE,QAAQ,CAAC;IAAC,WAAW,CAAC,EAAE,WAAW,CAAA;CAAE,GAChE;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,EAAE,QAAQ,CAAC;IAAC,WAAW,CAAC,EAAE,WAAW,CAAA;CAAE,GACjE;IACE,IAAI,EAAE,WAAW,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,OAAO,CAAC;IACjC,WAAW,CAAC,EAAE,WAAW,CAAC;CAC3B,CAAC;AAEN,wBAAgB,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,WAAW,CAAA;CAAE,GAAG,iBAAiB,CAEjG;AAED,wBAAgB,MAAM,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,WAAW,CAAA;CAAE,GAAG,iBAAiB,CAElG;AAED,wBAAgB,SAAS,CACvB,WAAW,EAAE,MAAM,EACnB,KAAK,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,OAAO,EAChC,IAAI,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,WAAW,CAAA;CAAE,GACnC,iBAAiB,CAEnB;AAED,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,iBAAiB,GAAG,MAAM,CAGpE;AAiCD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,kBAAkB,CAChC,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,aAAa,CAAC,iBAAiB,CAAC,GAC9C,IAAI,CAgBN"}
|
|
@@ -12,6 +12,60 @@ export function serializeInvalidation(inv) {
|
|
|
12
12
|
return `predicate:${inv.description}`;
|
|
13
13
|
return `${inv.kind}:${JSON.stringify(inv.queryKey)}`;
|
|
14
14
|
}
|
|
15
|
+
/** The cache filter that selects exactly the queries one invalidation targets. */
|
|
16
|
+
function invalidationFilters(inv) {
|
|
17
|
+
if (inv.kind === "exact")
|
|
18
|
+
return { queryKey: inv.queryKey, exact: true };
|
|
19
|
+
if (inv.kind === "prefix")
|
|
20
|
+
return { queryKey: inv.queryKey, exact: false };
|
|
21
|
+
return { predicate: inv.match };
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Cancel every query matched by `filters` that is in a PENDING INITIAL READ —
|
|
25
|
+
* currently fetching with no data yet.
|
|
26
|
+
*
|
|
27
|
+
* TanStack's `Query.fetch` only cancels a running request on refetch when the
|
|
28
|
+
* query already holds data; an initial fetch in flight is REUSED instead, so
|
|
29
|
+
* the invalidation's refetch resolves with the value the server returned BEFORE
|
|
30
|
+
* the mutation committed and then marks the query fresh. Cancelling first makes
|
|
31
|
+
* the invalidation's refetch a genuinely new request: the retryer is rejected
|
|
32
|
+
* synchronously (its `onCancel` reverts state to idle in the same tick), so the
|
|
33
|
+
* `invalidateQueries` call that follows starts a fresh fetch, and the abandoned
|
|
34
|
+
* promise's late, stale resolution is discarded.
|
|
35
|
+
*
|
|
36
|
+
* Cancellation is always scoped to one concrete query key — never a bare
|
|
37
|
+
* `cancelQueries()`.
|
|
38
|
+
*/
|
|
39
|
+
function cancelPendingInitialReads(queryClient, filters) {
|
|
40
|
+
for (const query of queryClient.getQueryCache().findAll(filters)) {
|
|
41
|
+
if (query.state.fetchStatus !== "fetching")
|
|
42
|
+
continue;
|
|
43
|
+
if (query.state.data !== undefined)
|
|
44
|
+
continue;
|
|
45
|
+
void queryClient.cancelQueries({ queryKey: query.queryKey, exact: true });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Dispatch a deduplicated list of cache invalidations.
|
|
50
|
+
*
|
|
51
|
+
* Synchronous by contract: the underlying `invalidateQueries` / `cancelQueries`
|
|
52
|
+
* promises are fire-and-forget, so a mutation success path never awaits its own
|
|
53
|
+
* cache refresh.
|
|
54
|
+
*
|
|
55
|
+
* Before each invalidation, any query it matches that is mid-PENDING-INITIAL-READ
|
|
56
|
+
* is cancelled (see `cancelPendingInitialReads`) so a read that started before
|
|
57
|
+
* the write committed can never land as the query's first — and freshly-marked —
|
|
58
|
+
* value.
|
|
59
|
+
*
|
|
60
|
+
* `refetchType` governs whether that cancellation happens:
|
|
61
|
+
* - `'active'` (the default) and `'all'` cancel-then-invalidate every matched
|
|
62
|
+
* pending initial read — including one TanStack's refetch pass will not
|
|
63
|
+
* restart, since a stale first value would otherwise land and mark the query
|
|
64
|
+
* fresh, while a cancelled one simply refetches for its next observer.
|
|
65
|
+
* - `'none'` invalidates WITHOUT cancelling: the caller has asked for no
|
|
66
|
+
* refetch at all, so cancelling would abandon the only in-flight read the
|
|
67
|
+
* consumer has and leave it with no data and no pending request.
|
|
68
|
+
*/
|
|
15
69
|
export function applyInvalidations(queryClient, invalidations) {
|
|
16
70
|
const seen = new Set();
|
|
17
71
|
for (const inv of invalidations) {
|
|
@@ -20,26 +74,11 @@ export function applyInvalidations(queryClient, invalidations) {
|
|
|
20
74
|
continue;
|
|
21
75
|
seen.add(sig);
|
|
22
76
|
const refetchType = inv.refetchType ?? "active";
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
exact: true,
|
|
27
|
-
refetchType,
|
|
28
|
-
});
|
|
29
|
-
}
|
|
30
|
-
else if (inv.kind === "prefix") {
|
|
31
|
-
void queryClient.invalidateQueries({
|
|
32
|
-
queryKey: inv.queryKey,
|
|
33
|
-
exact: false,
|
|
34
|
-
refetchType,
|
|
35
|
-
});
|
|
36
|
-
}
|
|
37
|
-
else {
|
|
38
|
-
void queryClient.invalidateQueries({
|
|
39
|
-
predicate: inv.match,
|
|
40
|
-
refetchType,
|
|
41
|
-
});
|
|
77
|
+
const filters = invalidationFilters(inv);
|
|
78
|
+
if (refetchType !== "none") {
|
|
79
|
+
cancelPendingInitialReads(queryClient, filters);
|
|
42
80
|
}
|
|
81
|
+
void queryClient.invalidateQueries({ ...filters, refetchType });
|
|
43
82
|
}
|
|
44
83
|
}
|
|
45
84
|
//# sourceMappingURL=cache-invalidation.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-invalidation.js","sourceRoot":"","sources":["../../src/domain-events/cache-invalidation.ts"],"names":[],"mappings":"AAcA,MAAM,UAAU,KAAK,CAAC,QAAkB,EAAE,IAAoC;IAC5E,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC;AACrE,CAAC;AAED,MAAM,UAAU,MAAM,CAAC,QAAkB,EAAE,IAAoC;IAC7E,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC;AACtE,CAAC;AAED,MAAM,UAAU,SAAS,CACvB,WAAmB,EACnB,KAAgC,EAChC,IAAoC;IAEpC,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC;AACnF,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,GAAsB;IAC1D,IAAI,GAAG,CAAC,IAAI,KAAK,WAAW;QAAE,OAAO,aAAa,GAAG,CAAC,WAAW,EAAE,CAAC;IACpE,OAAO,GAAG,GAAG,CAAC,IAAI,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;AACvD,CAAC;AAED,
|
|
1
|
+
{"version":3,"file":"cache-invalidation.js","sourceRoot":"","sources":["../../src/domain-events/cache-invalidation.ts"],"names":[],"mappings":"AAcA,MAAM,UAAU,KAAK,CAAC,QAAkB,EAAE,IAAoC;IAC5E,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC;AACrE,CAAC;AAED,MAAM,UAAU,MAAM,CAAC,QAAkB,EAAE,IAAoC;IAC7E,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE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C,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC5E,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,kBAAkB,CAChC,WAAwB,EACxB,aAA+C;IAE/C,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,GAAG,IAAI,aAAa,EAAE,CAAC;QAChC,MAAM,GAAG,GAAG,qBAAqB,CAAC,GAAG,CAAC,CAAC;QACvC,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;YAAE,SAAS;QAC5B,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAEd,MAAM,WAAW,GAAgB,GAAG,CAAC,WAAW,IAAI,QAAQ,CAAC;QAC7D,MAAM,OAAO,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC;QAEzC,IAAI,WAAW,KAAK,MAAM,EAAE,CAAC;YAC3B,yBAAyB,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;QAClD,CAAC;QAED,KAAK,WAAW,CAAC,iBAAiB,CAAC,EAAE,GAAG,OAAO,EAAE,WAAW,EAAE,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import type { Query, QueryClient, QueryFilters, QueryKey } from \"@tanstack/react-query\";\n\nexport type RefetchType = \"active\" | \"all\" | \"none\";\n\nexport type CacheInvalidation =\n | { kind: \"exact\"; queryKey: QueryKey; refetchType?: RefetchType }\n | { kind: \"prefix\"; queryKey: QueryKey; refetchType?: RefetchType }\n | {\n kind: \"predicate\";\n description: string;\n match: (query: Query) => boolean;\n refetchType?: RefetchType;\n };\n\nexport function exact(queryKey: QueryKey, opts?: { refetchType?: RefetchType }): CacheInvalidation {\n return { kind: \"exact\", queryKey, refetchType: opts?.refetchType };\n}\n\nexport function prefix(queryKey: QueryKey, opts?: { refetchType?: RefetchType }): CacheInvalidation {\n return { kind: \"prefix\", queryKey, refetchType: opts?.refetchType };\n}\n\nexport function predicate(\n description: string,\n match: (query: Query) => boolean,\n opts?: { refetchType?: RefetchType },\n): CacheInvalidation {\n return { kind: \"predicate\", description, match, refetchType: opts?.refetchType };\n}\n\nexport function serializeInvalidation(inv: CacheInvalidation): string {\n if (inv.kind === \"predicate\") return `predicate:${inv.description}`;\n return `${inv.kind}:${JSON.stringify(inv.queryKey)}`;\n}\n\n/** The cache filter that selects exactly the queries one invalidation targets. */\nfunction invalidationFilters(inv: CacheInvalidation): QueryFilters {\n if (inv.kind === \"exact\") return { queryKey: inv.queryKey, exact: true };\n if (inv.kind === \"prefix\") return { queryKey: inv.queryKey, exact: false };\n return { predicate: inv.match };\n}\n\n/**\n * Cancel every query matched by `filters` that is in a PENDING INITIAL READ —\n * currently fetching with no data yet.\n *\n * TanStack's `Query.fetch` only cancels a running request on refetch when the\n * query already holds data; an initial fetch in flight is REUSED instead, so\n * the invalidation's refetch resolves with the value the server returned BEFORE\n * the mutation committed and then marks the query fresh. Cancelling first makes\n * the invalidation's refetch a genuinely new request: the retryer is rejected\n * synchronously (its `onCancel` reverts state to idle in the same tick), so the\n * `invalidateQueries` call that follows starts a fresh fetch, and the abandoned\n * promise's late, stale resolution is discarded.\n *\n * Cancellation is always scoped to one concrete query key — never a bare\n * `cancelQueries()`.\n */\nfunction cancelPendingInitialReads(queryClient: QueryClient, filters: QueryFilters): void {\n for (const query of queryClient.getQueryCache().findAll(filters)) {\n if (query.state.fetchStatus !== \"fetching\") continue;\n if (query.state.data !== undefined) continue;\n void queryClient.cancelQueries({ queryKey: query.queryKey, exact: true });\n }\n}\n\n/**\n * Dispatch a deduplicated list of cache invalidations.\n *\n * Synchronous by contract: the underlying `invalidateQueries` / `cancelQueries`\n * promises are fire-and-forget, so a mutation success path never awaits its own\n * cache refresh.\n *\n * Before each invalidation, any query it matches that is mid-PENDING-INITIAL-READ\n * is cancelled (see `cancelPendingInitialReads`) so a read that started before\n * the write committed can never land as the query's first — and freshly-marked —\n * value.\n *\n * `refetchType` governs whether that cancellation happens:\n * - `'active'` (the default) and `'all'` cancel-then-invalidate every matched\n * pending initial read — including one TanStack's refetch pass will not\n * restart, since a stale first value would otherwise land and mark the query\n * fresh, while a cancelled one simply refetches for its next observer.\n * - `'none'` invalidates WITHOUT cancelling: the caller has asked for no\n * refetch at all, so cancelling would abandon the only in-flight read the\n * consumer has and leave it with no data and no pending request.\n */\nexport function applyInvalidations(\n queryClient: QueryClient,\n invalidations: ReadonlyArray<CacheInvalidation>,\n): void {\n const seen = new Set<string>();\n for (const inv of invalidations) {\n const sig = serializeInvalidation(inv);\n if (seen.has(sig)) continue;\n seen.add(sig);\n\n const refetchType: RefetchType = inv.refetchType ?? \"active\";\n const filters = invalidationFilters(inv);\n\n if (refetchType !== \"none\") {\n cancelPendingInitialReads(queryClient, filters);\n }\n\n void queryClient.invalidateQueries({ ...filters, refetchType });\n }\n}\n"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { QueryClient, QueryKey } from '@tanstack/react-query';
|
|
2
|
+
/**
|
|
3
|
+
* Bounded re-read ladder for a document that resolved ABSENT.
|
|
4
|
+
*
|
|
5
|
+
* A one-shot lookup that lands `null` has no listener to tell it when the doc appears —
|
|
6
|
+
* the row would stay blank until something invalidates it. That is the real failure the
|
|
7
|
+
* realtime path was introduced to fix (a mirror doc that is missing or lagging at fetch
|
|
8
|
+
* time: just after a create-and-redirect, or in a second tab racing the server mirror).
|
|
9
|
+
* This scheduler restores the recovery without a listener: after an absent result it
|
|
10
|
+
* re-reads a few times on a widening ladder, then gives up.
|
|
11
|
+
*
|
|
12
|
+
* Delays (ms) between re-reads within one absence episode. After the last rung the episode
|
|
13
|
+
* is exhausted and never restarts on its own; only a later PRESENT→absent transition opens
|
|
14
|
+
* a new one.
|
|
15
|
+
*/
|
|
16
|
+
export declare const ABSENT_RETRY_DELAYS_MS: readonly [5000, 15000, 45000, 120000];
|
|
17
|
+
export interface TrackAbsentDocParams {
|
|
18
|
+
queryClient: QueryClient;
|
|
19
|
+
/** Exact key of the per-id lookup query. */
|
|
20
|
+
queryKey: QueryKey;
|
|
21
|
+
/**
|
|
22
|
+
* Ladder this registrant wants; an empty array means it wants no re-reads. Registrants
|
|
23
|
+
* on the same key combine by union — the longest ladder among them governs — so one
|
|
24
|
+
* consumer passing `[]` never disables polling another consumer asked for.
|
|
25
|
+
*/
|
|
26
|
+
delays?: readonly number[];
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Register interest in re-reading `queryKey` while it resolves absent. Returns an
|
|
30
|
+
* idempotent release function; releasing the last interested consumer pauses the ladder
|
|
31
|
+
* without spending the episode's remaining budget, and releasing the last registrant that
|
|
32
|
+
* wanted polling shrinks the effective ladder for the episode still in progress.
|
|
33
|
+
*/
|
|
34
|
+
export declare function trackAbsentDoc({ queryClient, queryKey, delays, }: TrackAbsentDocParams): () => void;
|
|
35
|
+
/** Test-only: number of absence episodes currently tracked for a QueryClient. */
|
|
36
|
+
export declare function __absenceEpisodeCount(queryClient: QueryClient): number;
|
|
37
|
+
/** Test-only: rungs already spent on a key's current episode, or `null` if there is none. */
|
|
38
|
+
export declare function __absenceAttempt(queryClient: QueryClient, queryKey: QueryKey): number | null;
|
|
39
|
+
//# sourceMappingURL=absence-scheduler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"absence-scheduler.d.ts","sourceRoot":"","sources":["../../../src/react/firestore/absence-scheduler.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAEnE;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,sBAAsB,uCAA4C,CAAC;AAgLhF,MAAM,WAAW,oBAAoB;IACnC,WAAW,EAAE,WAAW,CAAC;IACzB,4CAA4C;IAC5C,QAAQ,EAAE,QAAQ,CAAC;IACnB;;;;OAIG;IACH,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC5B;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,EAC7B,WAAW,EACX,QAAQ,EACR,MAA+B,GAChC,EAAE,oBAAoB,GAAG,MAAM,IAAI,CAmCnC;AAED,iFAAiF;AACjF,wBAAgB,qBAAqB,CAAC,WAAW,EAAE,WAAW,GAAG,MAAM,CAEtE;AAED,6FAA6F;AAC7F,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,WAAW,EAAE,QAAQ,EAAE,QAAQ,GAAG,MAAM,GAAG,IAAI,CAE5F"}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
/**
|
|
3
|
+
* Bounded re-read ladder for a document that resolved ABSENT.
|
|
4
|
+
*
|
|
5
|
+
* A one-shot lookup that lands `null` has no listener to tell it when the doc appears —
|
|
6
|
+
* the row would stay blank until something invalidates it. That is the real failure the
|
|
7
|
+
* realtime path was introduced to fix (a mirror doc that is missing or lagging at fetch
|
|
8
|
+
* time: just after a create-and-redirect, or in a second tab racing the server mirror).
|
|
9
|
+
* This scheduler restores the recovery without a listener: after an absent result it
|
|
10
|
+
* re-reads a few times on a widening ladder, then gives up.
|
|
11
|
+
*
|
|
12
|
+
* Delays (ms) between re-reads within one absence episode. After the last rung the episode
|
|
13
|
+
* is exhausted and never restarts on its own; only a later PRESENT→absent transition opens
|
|
14
|
+
* a new one.
|
|
15
|
+
*/
|
|
16
|
+
export const ABSENT_RETRY_DELAYS_MS = [5_000, 15_000, 45_000, 120_000];
|
|
17
|
+
const NO_DELAYS = [];
|
|
18
|
+
// Per-QueryClient, like the doc-subscription registry: a discarded client is GC'd with its
|
|
19
|
+
// bookkeeping, and each browser tab schedules independently.
|
|
20
|
+
const schedulers = new WeakMap();
|
|
21
|
+
/**
|
|
22
|
+
* Hash a key the way THIS client hashes it, so a consumer with a custom
|
|
23
|
+
* `queryKeyHashFn` still lines up with `QueryCache.get()`.
|
|
24
|
+
*/
|
|
25
|
+
function hashOf(queryClient, queryKey) {
|
|
26
|
+
return queryClient.defaultQueryOptions({ queryKey }).queryHash;
|
|
27
|
+
}
|
|
28
|
+
/** Union of the registrants' ladders: the longest one wins; none means no polling. */
|
|
29
|
+
function effectiveDelays(tracked) {
|
|
30
|
+
if (!tracked)
|
|
31
|
+
return NO_DELAYS;
|
|
32
|
+
let longest = NO_DELAYS;
|
|
33
|
+
for (const registration of tracked.registrations) {
|
|
34
|
+
if (registration.delays.length > longest.length)
|
|
35
|
+
longest = registration.delays;
|
|
36
|
+
}
|
|
37
|
+
return longest;
|
|
38
|
+
}
|
|
39
|
+
function clearTimer(episode) {
|
|
40
|
+
if (episode?.timer != null) {
|
|
41
|
+
clearTimeout(episode.timer);
|
|
42
|
+
episode.timer = null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function discardEpisode(state, hash) {
|
|
46
|
+
clearTimer(state.episodes.get(hash));
|
|
47
|
+
state.episodes.delete(hash);
|
|
48
|
+
}
|
|
49
|
+
function schedule(queryClient, state, hash) {
|
|
50
|
+
const tracked = state.tracked.get(hash);
|
|
51
|
+
const episode = state.episodes.get(hash);
|
|
52
|
+
if (!tracked || !episode || episode.timer !== null)
|
|
53
|
+
return;
|
|
54
|
+
const delays = effectiveDelays(tracked);
|
|
55
|
+
if (episode.attempt >= delays.length)
|
|
56
|
+
return;
|
|
57
|
+
episode.timer = setTimeout(() => {
|
|
58
|
+
episode.timer = null;
|
|
59
|
+
episode.attempt += 1;
|
|
60
|
+
const current = state.tracked.get(hash);
|
|
61
|
+
if (!current || !isAbsentAndActive(queryClient, hash))
|
|
62
|
+
return;
|
|
63
|
+
void queryClient.refetchQueries({ queryKey: current.queryKey, exact: true, type: 'active' });
|
|
64
|
+
// Lay the next rung; the ladder stops the moment the doc appears, the budget runs
|
|
65
|
+
// out, or the last enabled observer goes away.
|
|
66
|
+
evaluate(queryClient, state, hash);
|
|
67
|
+
}, delays[episode.attempt]);
|
|
68
|
+
}
|
|
69
|
+
function isAbsentAndActive(queryClient, hash) {
|
|
70
|
+
const query = queryClient.getQueryCache().get(hash);
|
|
71
|
+
if (!query)
|
|
72
|
+
return false;
|
|
73
|
+
return query.state.status === 'success' && query.state.data === null && query.isActive();
|
|
74
|
+
}
|
|
75
|
+
function evaluate(queryClient, state, hash) {
|
|
76
|
+
const query = queryClient.getQueryCache().get(hash);
|
|
77
|
+
if (!query) {
|
|
78
|
+
discardEpisode(state, hash);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const { status, data } = query.state;
|
|
82
|
+
if (status === 'success' && data !== null) {
|
|
83
|
+
// The doc is present — the episode is over.
|
|
84
|
+
discardEpisode(state, hash);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (status !== 'success') {
|
|
88
|
+
// Pending or errored: never polled, but the budget survives so an error mid-episode
|
|
89
|
+
// cannot hand the id a fresh ladder when it returns to absent.
|
|
90
|
+
clearTimer(state.episodes.get(hash));
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const tracked = state.tracked.get(hash);
|
|
94
|
+
if (!tracked) {
|
|
95
|
+
clearTimer(state.episodes.get(hash));
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
let episode = state.episodes.get(hash);
|
|
99
|
+
if (!episode) {
|
|
100
|
+
// No registrant wants polling — do not open an episode that could never spend a rung.
|
|
101
|
+
if (effectiveDelays(tracked).length === 0)
|
|
102
|
+
return;
|
|
103
|
+
episode = { attempt: 0, timer: null };
|
|
104
|
+
state.episodes.set(hash, episode);
|
|
105
|
+
}
|
|
106
|
+
if (!query.isActive()) {
|
|
107
|
+
clearTimer(episode);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
schedule(queryClient, state, hash);
|
|
111
|
+
}
|
|
112
|
+
function getState(queryClient) {
|
|
113
|
+
let state = schedulers.get(queryClient);
|
|
114
|
+
if (state)
|
|
115
|
+
return state;
|
|
116
|
+
state = { episodes: new Map(), tracked: new Map() };
|
|
117
|
+
schedulers.set(queryClient, state);
|
|
118
|
+
const scheduler = state;
|
|
119
|
+
// Exactly ONE cache listener per QueryClient, created with this state and never detached:
|
|
120
|
+
// it is WeakMap-scoped, so it is collected together with the client it belongs to.
|
|
121
|
+
queryClient.getQueryCache().subscribe((event) => {
|
|
122
|
+
const hash = event.query.queryHash;
|
|
123
|
+
if (!scheduler.tracked.has(hash) && !scheduler.episodes.has(hash))
|
|
124
|
+
return;
|
|
125
|
+
if (event.type === 'removed') {
|
|
126
|
+
discardEpisode(scheduler, hash);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
evaluate(queryClient, scheduler, hash);
|
|
130
|
+
});
|
|
131
|
+
return state;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Register interest in re-reading `queryKey` while it resolves absent. Returns an
|
|
135
|
+
* idempotent release function; releasing the last interested consumer pauses the ladder
|
|
136
|
+
* without spending the episode's remaining budget, and releasing the last registrant that
|
|
137
|
+
* wanted polling shrinks the effective ladder for the episode still in progress.
|
|
138
|
+
*/
|
|
139
|
+
export function trackAbsentDoc({ queryClient, queryKey, delays = ABSENT_RETRY_DELAYS_MS, }) {
|
|
140
|
+
const state = getState(queryClient);
|
|
141
|
+
const hash = hashOf(queryClient, queryKey);
|
|
142
|
+
const registration = { delays };
|
|
143
|
+
const existing = state.tracked.get(hash);
|
|
144
|
+
if (existing)
|
|
145
|
+
existing.registrations.push(registration);
|
|
146
|
+
else
|
|
147
|
+
state.tracked.set(hash, { queryKey, registrations: [registration] });
|
|
148
|
+
evaluate(queryClient, state, hash);
|
|
149
|
+
let released = false;
|
|
150
|
+
return () => {
|
|
151
|
+
if (released)
|
|
152
|
+
return;
|
|
153
|
+
released = true;
|
|
154
|
+
const current = state.tracked.get(hash);
|
|
155
|
+
if (!current)
|
|
156
|
+
return;
|
|
157
|
+
const before = effectiveDelays(current).length;
|
|
158
|
+
const index = current.registrations.indexOf(registration);
|
|
159
|
+
if (index >= 0)
|
|
160
|
+
current.registrations.splice(index, 1);
|
|
161
|
+
if (current.registrations.length === 0) {
|
|
162
|
+
state.tracked.delete(hash);
|
|
163
|
+
clearTimer(state.episodes.get(hash));
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (effectiveDelays(current).length !== before) {
|
|
167
|
+
// The effective ladder changed: re-derive under the new one rather than letting a
|
|
168
|
+
// timer from the departed registrant's ladder fire.
|
|
169
|
+
clearTimer(state.episodes.get(hash));
|
|
170
|
+
evaluate(queryClient, state, hash);
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
/** Test-only: number of absence episodes currently tracked for a QueryClient. */
|
|
175
|
+
export function __absenceEpisodeCount(queryClient) {
|
|
176
|
+
return schedulers.get(queryClient)?.episodes.size ?? 0;
|
|
177
|
+
}
|
|
178
|
+
/** Test-only: rungs already spent on a key's current episode, or `null` if there is none. */
|
|
179
|
+
export function __absenceAttempt(queryClient, queryKey) {
|
|
180
|
+
return schedulers.get(queryClient)?.episodes.get(hashOf(queryClient, queryKey))?.attempt ?? null;
|
|
181
|
+
}
|
|
182
|
+
//# sourceMappingURL=absence-scheduler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"absence-scheduler.js","sourceRoot":"","sources":["../../../src/react/firestore/absence-scheduler.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAIb;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAU,CAAC;AA+ChF,MAAM,SAAS,GAAsB,EAAE,CAAC;AAExC,2FAA2F;AAC3F,6DAA6D;AAC7D,MAAM,UAAU,GAAG,IAAI,OAAO,EAA+B,CAAC;AAE9D;;;GAGG;AACH,SAAS,MAAM,CAAC,WAAwB,EAAE,QAAkB;IAC1D,OAAO,WAAW,CAAC,mBAAmB,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,SAAS,CAAC;AACjE,CAAC;AAED,sFAAsF;AACtF,SAAS,eAAe,CA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ACzD,CAAC;AAED,6FAA6F;AAC7F,MAAM,UAAU,gBAAgB,CAAC,WAAwB,EAAE,QAAkB;IAC3E,OAAO,UAAU,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC,EAAE,OAAO,IAAI,IAAI,CAAC;AACnG,CAAC","sourcesContent":["'use client';\n\nimport type { QueryClient, QueryKey } from '@tanstack/react-query';\n\n/**\n * Bounded re-read ladder for a document that resolved ABSENT.\n *\n * A one-shot lookup that lands `null` has no listener to tell it when the doc appears —\n * the row would stay blank until something invalidates it. That is the real failure the\n * realtime path was introduced to fix (a mirror doc that is missing or lagging at fetch\n * time: just after a create-and-redirect, or in a second tab racing the server mirror).\n * This scheduler restores the recovery without a listener: after an absent result it\n * re-reads a few times on a widening ladder, then gives up.\n *\n * Delays (ms) between re-reads within one absence episode. After the last rung the episode\n * is exhausted and never restarts on its own; only a later PRESENT→absent transition opens\n * a new one.\n */\nexport const ABSENT_RETRY_DELAYS_MS = [5_000, 15_000, 45_000, 120_000] as const;\n\n/**\n * The rules the scheduler holds to:\n *\n * - It polls ONLY a query in `status: 'success'` whose data is `null`. An error state is\n * never polled (a denial is not an absence), and an error mid-episode pauses the ladder\n * with its remaining budget intact.\n * - One timer per query key and one budget per absence episode: the first successful\n * `undefined → null` opens the episode, and neither a repeated `null` nor an additional\n * consumer resets it. A `present → null` transition opens a NEW episode.\n * - Several consumers may register the same key with DIFFERENT ladders. The effective\n * ladder is the union: poll if any registrant wants polling, using the LONGEST ladder\n * among them, recomputed on every register and release. Mount order never decides.\n * - Eligibility is TanStack's `query.isActive()` — at least one observer that is not\n * disabled. Subscribe-mode and disabled observers therefore never keep an episode\n * polling, while disabling ONE consumer cannot stop polling another still needs.\n * - Losing the last enabled observer PAUSES the ladder and retains the episode's remaining\n * rungs; a later enabled observer resumes from there. A new observer on an EXHAUSTED\n * episode does not restart it.\n * - Cache removal (gc) discards the episode outright, so a later re-fetch that lands absent\n * starts fresh.\n *\n * Because the timer is per key rather than per observer, N consumers of one absent id cost\n * one re-read per rung, not N.\n */\n\ntype Episode = {\n /** Rungs consumed so far; `>= effectiveDelays().length` means exhausted. */\n attempt: number;\n timer: ReturnType<typeof setTimeout> | null;\n};\n\ntype Registration = {\n delays: readonly number[];\n};\n\ntype Tracked = {\n queryKey: QueryKey;\n registrations: Registration[];\n};\n\ntype SchedulerState = {\n episodes: Map<string, Episode>;\n tracked: Map<string, Tracked>;\n};\n\nconst NO_DELAYS: readonly number[] = [];\n\n// Per-QueryClient, like the doc-subscription registry: a discarded client is GC'd with its\n// bookkeeping, and each browser tab schedules independently.\nconst schedulers = new WeakMap<QueryClient, SchedulerState>();\n\n/**\n * Hash a key the way THIS client hashes it, so a consumer with a custom\n * `queryKeyHashFn` still lines up with `QueryCache.get()`.\n */\nfunction hashOf(queryClient: QueryClient, queryKey: QueryKey): string {\n return queryClient.defaultQueryOptions({ queryKey }).queryHash;\n}\n\n/** Union of the registrants' ladders: the longest one wins; none means no polling. */\nfunction effectiveDelays(tracked: Tracked | undefined): readonly number[] {\n if (!tracked) return NO_DELAYS;\n let longest: readonly number[] = NO_DELAYS;\n for (const registration of tracked.registrations) {\n if (registration.delays.length > longest.length) longest = registration.delays;\n }\n return longest;\n}\n\nfunction clearTimer(episode: Episode | undefined): void {\n if (episode?.timer != null) {\n clearTimeout(episode.timer);\n episode.timer = null;\n }\n}\n\nfunction discardEpisode(state: SchedulerState, hash: string): void {\n clearTimer(state.episodes.get(hash));\n state.episodes.delete(hash);\n}\n\nfunction schedule(queryClient: QueryClient, state: SchedulerState, hash: string): void {\n const tracked = state.tracked.get(hash);\n const episode = state.episodes.get(hash);\n if (!tracked || !episode || episode.timer !== null) return;\n\n const delays = effectiveDelays(tracked);\n if (episode.attempt >= delays.length) return;\n\n episode.timer = setTimeout(() => {\n episode.timer = null;\n episode.attempt += 1;\n const current = state.tracked.get(hash);\n if (!current || !isAbsentAndActive(queryClient, hash)) return;\n void queryClient.refetchQueries({ queryKey: current.queryKey, exact: true, type: 'active' });\n // Lay the next rung; the ladder stops the moment the doc appears, the budget runs\n // out, or the last enabled observer goes away.\n evaluate(queryClient, state, hash);\n }, delays[episode.attempt]);\n}\n\nfunction isAbsentAndActive(queryClient: QueryClient, hash: string): boolean {\n const query = queryClient.getQueryCache().get(hash);\n if (!query) return false;\n return query.state.status === 'success' && query.state.data === null && query.isActive();\n}\n\nfunction evaluate(queryClient: QueryClient, state: SchedulerState, hash: string): void {\n const query = queryClient.getQueryCache().get(hash);\n if (!query) {\n discardEpisode(state, hash);\n return;\n }\n\n const { status, data } = query.state;\n\n if (status === 'success' && data !== null) {\n // The doc is present — the episode is over.\n discardEpisode(state, hash);\n return;\n }\n\n if (status !== 'success') {\n // Pending or errored: never polled, but the budget survives so an error mid-episode\n // cannot hand the id a fresh ladder when it returns to absent.\n clearTimer(state.episodes.get(hash));\n return;\n }\n\n const tracked = state.tracked.get(hash);\n if (!tracked) {\n clearTimer(state.episodes.get(hash));\n return;\n }\n\n let episode = state.episodes.get(hash);\n if (!episode) {\n // No registrant wants polling — do not open an episode that could never spend a rung.\n if (effectiveDelays(tracked).length === 0) return;\n episode = { attempt: 0, timer: null };\n state.episodes.set(hash, episode);\n }\n\n if (!query.isActive()) {\n clearTimer(episode);\n return;\n }\n\n schedule(queryClient, state, hash);\n}\n\nfunction getState(queryClient: QueryClient): SchedulerState {\n let state = schedulers.get(queryClient);\n if (state) return state;\n\n state = { episodes: new Map(), tracked: new Map() };\n schedulers.set(queryClient, state);\n\n const scheduler = state;\n // Exactly ONE cache listener per QueryClient, created with this state and never detached:\n // it is WeakMap-scoped, so it is collected together with the client it belongs to.\n queryClient.getQueryCache().subscribe((event) => {\n const hash = event.query.queryHash;\n if (!scheduler.tracked.has(hash) && !scheduler.episodes.has(hash)) return;\n if (event.type === 'removed') {\n discardEpisode(scheduler, hash);\n return;\n }\n evaluate(queryClient, scheduler, hash);\n });\n\n return state;\n}\n\nexport interface TrackAbsentDocParams {\n queryClient: QueryClient;\n /** Exact key of the per-id lookup query. */\n queryKey: QueryKey;\n /**\n * Ladder this registrant wants; an empty array means it wants no re-reads. Registrants\n * on the same key combine by union — the longest ladder among them governs — so one\n * consumer passing `[]` never disables polling another consumer asked for.\n */\n delays?: readonly number[];\n}\n\n/**\n * Register interest in re-reading `queryKey` while it resolves absent. Returns an\n * idempotent release function; releasing the last interested consumer pauses the ladder\n * without spending the episode's remaining budget, and releasing the last registrant that\n * wanted polling shrinks the effective ladder for the episode still in progress.\n */\nexport function trackAbsentDoc({\n queryClient,\n queryKey,\n delays = ABSENT_RETRY_DELAYS_MS,\n}: TrackAbsentDocParams): () => void {\n const state = getState(queryClient);\n const hash = hashOf(queryClient, queryKey);\n const registration: Registration = { delays };\n\n const existing = state.tracked.get(hash);\n if (existing) existing.registrations.push(registration);\n else state.tracked.set(hash, { queryKey, registrations: [registration] });\n\n evaluate(queryClient, state, hash);\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const current = state.tracked.get(hash);\n if (!current) return;\n\n const before = effectiveDelays(current).length;\n const index = current.registrations.indexOf(registration);\n if (index >= 0) current.registrations.splice(index, 1);\n\n if (current.registrations.length === 0) {\n state.tracked.delete(hash);\n clearTimer(state.episodes.get(hash));\n return;\n }\n\n if (effectiveDelays(current).length !== before) {\n // The effective ladder changed: re-derive under the new one rather than letting a\n // timer from the departed registrant's ladder fire.\n clearTimer(state.episodes.get(hash));\n evaluate(queryClient, state, hash);\n }\n };\n}\n\n/** Test-only: number of absence episodes currently tracked for a QueryClient. */\nexport function __absenceEpisodeCount(queryClient: QueryClient): number {\n return schedulers.get(queryClient)?.episodes.size ?? 0;\n}\n\n/** Test-only: rungs already spent on a key's current episode, or `null` if there is none. */\nexport function __absenceAttempt(queryClient: QueryClient, queryKey: QueryKey): number | null {\n return schedulers.get(queryClient)?.episodes.get(hashOf(queryClient, queryKey))?.attempt ?? null;\n}\n"]}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { type Firestore } from 'firebase/firestore';
|
|
2
|
+
import type { QueryClient } from '@tanstack/react-query';
|
|
3
|
+
/**
|
|
4
|
+
* Coalescing document loader behind {@link useBatchFirestoreDocs}'s one-shot mode.
|
|
5
|
+
*
|
|
6
|
+
* Every id is its own observed React Query query, so without coalescing N ids would issue
|
|
7
|
+
* N Firestore round-trips. The loader collects the ids enqueued in a single microtask and
|
|
8
|
+
* dispatches them as `where(documentId(), 'in', chunk)` queries of at most 30 ids each
|
|
9
|
+
* (`'batch'` transport), or as concurrent per-document gets (`'get'` transport — required
|
|
10
|
+
* for collections whose rules gate reads on `resource.data`, where an unconstrained list
|
|
11
|
+
* query is denied wholesale but per-document gets are evaluated per doc).
|
|
12
|
+
*
|
|
13
|
+
* Two properties are load-bearing:
|
|
14
|
+
*
|
|
15
|
+
* - **The loader resolves promises only — it NEVER writes the query cache.** TanStack's
|
|
16
|
+
* per-query fetch identity is therefore the sole guard against a late batch response
|
|
17
|
+
* overwriting a newer per-id result.
|
|
18
|
+
* - **A dispatched batch is closed.** A later enqueue of the same id (a refetch after a
|
|
19
|
+
* cancellation, say) always joins a NEW batch, never the in-flight one — so a cancelled
|
|
20
|
+
* read can never be served by the request it was cancelled out of.
|
|
21
|
+
*
|
|
22
|
+
* Cancelling one per-id query detaches only that waiter; the shared request still completes
|
|
23
|
+
* for its batch-mates.
|
|
24
|
+
*
|
|
25
|
+
* Loaders are scoped per `(QueryClient, Firestore instance, collectionPath)`. The Firestore
|
|
26
|
+
* instance is part of the scope on purpose: two `db` instances sharing a collection path
|
|
27
|
+
* must never share a request.
|
|
28
|
+
*/
|
|
29
|
+
/** Firestore's hard cap on the number of values in an `in` filter. */
|
|
30
|
+
export declare const FIRESTORE_IN_LIMIT = 30;
|
|
31
|
+
/** Maximum `in`-query requests in flight at once, per loader scope. */
|
|
32
|
+
export declare const MAX_CONCURRENT_BATCH_REQUESTS = 4;
|
|
33
|
+
/** Maximum per-document gets in flight at once, per loader scope. */
|
|
34
|
+
export declare const MAX_CONCURRENT_DOC_GETS = 12;
|
|
35
|
+
export type LoadedDoc = Record<string, unknown> & {
|
|
36
|
+
id: string;
|
|
37
|
+
};
|
|
38
|
+
export type DocLoader = {
|
|
39
|
+
/** Resolve one id through the coalescing `in`-query batcher. */
|
|
40
|
+
loadBatched(id: string, signal?: AbortSignal): Promise<LoadedDoc | null>;
|
|
41
|
+
/** Resolve one id through its own `getDoc`, bounded by the get concurrency limit. */
|
|
42
|
+
loadOne(id: string, signal?: AbortSignal): Promise<LoadedDoc | null>;
|
|
43
|
+
};
|
|
44
|
+
export declare function getDocLoader(queryClient: QueryClient, db: Firestore, collectionPath: string): DocLoader;
|
|
45
|
+
//# sourceMappingURL=batch-doc-loader.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"batch-doc-loader.d.ts","sourceRoot":"","sources":["../../../src/react/firestore/batch-doc-loader.ts"],"names":[],"mappings":"AAEA,OAAO,EAQL,KAAK,SAAS,EACf,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEzD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,sEAAsE;AACtE,eAAO,MAAM,kBAAkB,KAAK,CAAC;AAErC,uEAAuE;AACvE,eAAO,MAAM,6BAA6B,IAAI,CAAC;AAE/C,qEAAqE;AACrE,eAAO,MAAM,uBAAuB,KAAK,CAAC;AAE1C,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC;AAOjE,MAAM,MAAM,SAAS,GAAG;IACtB,gEAAgE;IAChE,WAAW,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC;IACzE,qFAAqF;IACrF,OAAO,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC;CACtE,CAAC;AAoJF,wBAAgB,YAAY,CAC1B,WAAW,EAAE,WAAW,EACxB,EAAE,EAAE,SAAS,EACb,cAAc,EAAE,MAAM,GACrB,SAAS,CAiBX"}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { collection, doc, documentId, getDoc, getDocs, query, where, } from 'firebase/firestore';
|
|
3
|
+
/**
|
|
4
|
+
* Coalescing document loader behind {@link useBatchFirestoreDocs}'s one-shot mode.
|
|
5
|
+
*
|
|
6
|
+
* Every id is its own observed React Query query, so without coalescing N ids would issue
|
|
7
|
+
* N Firestore round-trips. The loader collects the ids enqueued in a single microtask and
|
|
8
|
+
* dispatches them as `where(documentId(), 'in', chunk)` queries of at most 30 ids each
|
|
9
|
+
* (`'batch'` transport), or as concurrent per-document gets (`'get'` transport — required
|
|
10
|
+
* for collections whose rules gate reads on `resource.data`, where an unconstrained list
|
|
11
|
+
* query is denied wholesale but per-document gets are evaluated per doc).
|
|
12
|
+
*
|
|
13
|
+
* Two properties are load-bearing:
|
|
14
|
+
*
|
|
15
|
+
* - **The loader resolves promises only — it NEVER writes the query cache.** TanStack's
|
|
16
|
+
* per-query fetch identity is therefore the sole guard against a late batch response
|
|
17
|
+
* overwriting a newer per-id result.
|
|
18
|
+
* - **A dispatched batch is closed.** A later enqueue of the same id (a refetch after a
|
|
19
|
+
* cancellation, say) always joins a NEW batch, never the in-flight one — so a cancelled
|
|
20
|
+
* read can never be served by the request it was cancelled out of.
|
|
21
|
+
*
|
|
22
|
+
* Cancelling one per-id query detaches only that waiter; the shared request still completes
|
|
23
|
+
* for its batch-mates.
|
|
24
|
+
*
|
|
25
|
+
* Loaders are scoped per `(QueryClient, Firestore instance, collectionPath)`. The Firestore
|
|
26
|
+
* instance is part of the scope on purpose: two `db` instances sharing a collection path
|
|
27
|
+
* must never share a request.
|
|
28
|
+
*/
|
|
29
|
+
/** Firestore's hard cap on the number of values in an `in` filter. */
|
|
30
|
+
export const FIRESTORE_IN_LIMIT = 30;
|
|
31
|
+
/** Maximum `in`-query requests in flight at once, per loader scope. */
|
|
32
|
+
export const MAX_CONCURRENT_BATCH_REQUESTS = 4;
|
|
33
|
+
/** Maximum per-document gets in flight at once, per loader scope. */
|
|
34
|
+
export const MAX_CONCURRENT_DOC_GETS = 12;
|
|
35
|
+
/** Runs at most `max` tasks concurrently; a slot is released when its task settles. */
|
|
36
|
+
function createConcurrencyLimiter(max) {
|
|
37
|
+
let active = 0;
|
|
38
|
+
const waiting = [];
|
|
39
|
+
const pump = () => {
|
|
40
|
+
while (active < max && waiting.length > 0) {
|
|
41
|
+
const start = waiting.shift();
|
|
42
|
+
active += 1;
|
|
43
|
+
start?.();
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const release = () => {
|
|
47
|
+
active -= 1;
|
|
48
|
+
pump();
|
|
49
|
+
};
|
|
50
|
+
return (task) => new Promise((resolve, reject) => {
|
|
51
|
+
waiting.push(() => {
|
|
52
|
+
task().then((value) => {
|
|
53
|
+
release();
|
|
54
|
+
resolve(value);
|
|
55
|
+
}, (error) => {
|
|
56
|
+
release();
|
|
57
|
+
reject(error);
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
pump();
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
function abortReason(signal) {
|
|
64
|
+
return signal.reason ?? new Error('Document read was cancelled');
|
|
65
|
+
}
|
|
66
|
+
function createDocLoader(db, collectionPath) {
|
|
67
|
+
const runBatchRequest = createConcurrencyLimiter(MAX_CONCURRENT_BATCH_REQUESTS);
|
|
68
|
+
const runDocGet = createConcurrencyLimiter(MAX_CONCURRENT_DOC_GETS);
|
|
69
|
+
// Ids enqueued in the CURRENT microtask. Nulled out at dispatch so the dispatched batch
|
|
70
|
+
// is closed and a later enqueue opens a fresh one.
|
|
71
|
+
let openBatch = null;
|
|
72
|
+
const runChunk = (chunk, batch) => runBatchRequest(async () => {
|
|
73
|
+
let found = null;
|
|
74
|
+
let failure;
|
|
75
|
+
try {
|
|
76
|
+
const snapshot = await getDocs(query(collection(db, collectionPath), where(documentId(), 'in', chunk)));
|
|
77
|
+
found = new Map();
|
|
78
|
+
snapshot.forEach((snap) => {
|
|
79
|
+
found.set(snap.id, { id: snap.id, ...snap.data() });
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
failure = error;
|
|
84
|
+
}
|
|
85
|
+
for (const id of chunk) {
|
|
86
|
+
const waiters = batch.get(id);
|
|
87
|
+
batch.delete(id);
|
|
88
|
+
if (!waiters)
|
|
89
|
+
continue;
|
|
90
|
+
for (const waiter of [...waiters]) {
|
|
91
|
+
if (found)
|
|
92
|
+
waiter.resolve(found.get(id) ?? null);
|
|
93
|
+
else
|
|
94
|
+
waiter.reject(failure);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
const dispatch = () => {
|
|
99
|
+
const batch = openBatch;
|
|
100
|
+
openBatch = null;
|
|
101
|
+
if (!batch || batch.size === 0)
|
|
102
|
+
return;
|
|
103
|
+
const ids = [...batch.keys()];
|
|
104
|
+
for (let i = 0; i < ids.length; i += FIRESTORE_IN_LIMIT) {
|
|
105
|
+
void runChunk(ids.slice(i, i + FIRESTORE_IN_LIMIT), batch);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
const loadBatched = (id, signal) => new Promise((resolve, reject) => {
|
|
109
|
+
if (signal?.aborted) {
|
|
110
|
+
reject(abortReason(signal));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (!openBatch) {
|
|
114
|
+
openBatch = new Map();
|
|
115
|
+
queueMicrotask(dispatch);
|
|
116
|
+
}
|
|
117
|
+
const batch = openBatch;
|
|
118
|
+
let slot = batch.get(id);
|
|
119
|
+
if (!slot) {
|
|
120
|
+
slot = [];
|
|
121
|
+
batch.set(id, slot);
|
|
122
|
+
}
|
|
123
|
+
const waiters = slot;
|
|
124
|
+
let settled = false;
|
|
125
|
+
let onAbort;
|
|
126
|
+
const settle = (run) => {
|
|
127
|
+
if (settled)
|
|
128
|
+
return;
|
|
129
|
+
settled = true;
|
|
130
|
+
const index = waiters.indexOf(waiter);
|
|
131
|
+
if (index >= 0)
|
|
132
|
+
waiters.splice(index, 1);
|
|
133
|
+
// An id nobody is waiting on any more must not ride into a billed `in` query.
|
|
134
|
+
if (waiters.length === 0 && batch.get(id) === waiters)
|
|
135
|
+
batch.delete(id);
|
|
136
|
+
if (onAbort)
|
|
137
|
+
signal?.removeEventListener('abort', onAbort);
|
|
138
|
+
run();
|
|
139
|
+
};
|
|
140
|
+
const waiter = {
|
|
141
|
+
resolve: (value) => settle(() => resolve(value)),
|
|
142
|
+
reject: (error) => settle(() => reject(error)),
|
|
143
|
+
};
|
|
144
|
+
waiters.push(waiter);
|
|
145
|
+
if (signal) {
|
|
146
|
+
onAbort = () => waiter.reject(abortReason(signal));
|
|
147
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
const loadOne = (id, signal) => runDocGet(async () => {
|
|
151
|
+
if (signal?.aborted)
|
|
152
|
+
throw abortReason(signal);
|
|
153
|
+
const snapshot = await getDoc(doc(db, collectionPath, id));
|
|
154
|
+
return snapshot.exists() ? { id: snapshot.id, ...snapshot.data() } : null;
|
|
155
|
+
});
|
|
156
|
+
return { loadBatched, loadOne };
|
|
157
|
+
}
|
|
158
|
+
// Per-QueryClient → per-Firestore-instance → per-collectionPath. WeakMaps so a discarded
|
|
159
|
+
// client or db instance takes its loaders with it.
|
|
160
|
+
const loaderScopes = new WeakMap();
|
|
161
|
+
export function getDocLoader(queryClient, db, collectionPath) {
|
|
162
|
+
let byDb = loaderScopes.get(queryClient);
|
|
163
|
+
if (!byDb) {
|
|
164
|
+
byDb = new WeakMap();
|
|
165
|
+
loaderScopes.set(queryClient, byDb);
|
|
166
|
+
}
|
|
167
|
+
let byPath = byDb.get(db);
|
|
168
|
+
if (!byPath) {
|
|
169
|
+
byPath = new Map();
|
|
170
|
+
byDb.set(db, byPath);
|
|
171
|
+
}
|
|
172
|
+
let loader = byPath.get(collectionPath);
|
|
173
|
+
if (!loader) {
|
|
174
|
+
loader = createDocLoader(db, collectionPath);
|
|
175
|
+
byPath.set(collectionPath, loader);
|
|
176
|
+
}
|
|
177
|
+
return loader;
|
|
178
|
+
}
|
|
179
|
+
//# sourceMappingURL=batch-doc-loader.js.map
|