-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathquery.ts
More file actions
1961 lines (1760 loc) · 62.9 KB
/
query.ts
File metadata and controls
1961 lines (1760 loc) · 62.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { QueryObserver, hashKey } from '@tanstack/query-core'
import { deepEquals } from '@tanstack/db'
import {
GetKeyRequiredError,
QueryClientRequiredError,
QueryFnRequiredError,
QueryKeyRequiredError,
} from './errors'
import { createWriteUtils } from './manual-sync'
import { serializeLoadSubsetOptions } from './serialization'
import type {
BaseCollectionConfig,
ChangeMessage,
CollectionConfig,
DeleteMutationFnParams,
InsertMutationFnParams,
LoadSubsetOptions,
SyncConfig,
SyncMetadataApi,
UpdateMutationFnParams,
UtilsRecord,
} from '@tanstack/db'
import type {
FetchStatus,
QueryClient,
QueryFunctionContext,
QueryKey,
QueryObserverOptions,
QueryObserverResult,
} from '@tanstack/query-core'
import type { StandardSchemaV1 } from '@standard-schema/spec'
// Re-export for external use
export type { SyncOperation } from './manual-sync'
// Schema output type inference helper (matches electric.ts pattern)
type InferSchemaOutput<T> = T extends StandardSchemaV1
? StandardSchemaV1.InferOutput<T> extends object
? StandardSchemaV1.InferOutput<T>
: Record<string, unknown>
: Record<string, unknown>
// Schema input type inference helper (matches electric.ts pattern)
type InferSchemaInput<T> = T extends StandardSchemaV1
? StandardSchemaV1.InferInput<T> extends object
? StandardSchemaV1.InferInput<T>
: Record<string, unknown>
: Record<string, unknown>
type TQueryKeyBuilder<TQueryKey> = (opts: LoadSubsetOptions) => TQueryKey
/**
* Configuration options for creating a Query Collection
* @template T - The explicit type of items stored in the collection
* @template TQueryFn - The queryFn type
* @template TError - The type of errors that can occur during queries
* @template TQueryKey - The type of the query key
* @template TKey - The type of the item keys
* @template TSchema - The schema type for validation
*/
export interface QueryCollectionConfig<
T extends object = object,
TQueryFn extends (context: QueryFunctionContext<any>) => any = (
context: QueryFunctionContext<any>,
) => any,
TError = unknown,
TQueryKey extends QueryKey = QueryKey,
TKey extends string | number = string | number,
TSchema extends StandardSchemaV1 = never,
TQueryData = Awaited<ReturnType<TQueryFn>>,
> extends BaseCollectionConfig<T, TKey, TSchema> {
/** The query key used by TanStack Query to identify this query */
queryKey: TQueryKey | TQueryKeyBuilder<TQueryKey>
/** Function that fetches data from the server. Must return the complete collection state */
queryFn: TQueryFn extends (
context: QueryFunctionContext<TQueryKey>,
) => Promise<Array<any>> | Array<any>
? (context: QueryFunctionContext<TQueryKey>) => Promise<Array<T>> | Array<T>
: TQueryFn
/* Function that extracts array items from wrapped API responses (e.g metadata, pagination) */
select?: (data: TQueryData) => Array<T>
/** The TanStack Query client instance */
queryClient: QueryClient
// Query-specific options
/** Whether the query should automatically run (default: true) */
enabled?: QueryObserverOptions<
TQueryData,
TError,
Array<T>,
TQueryData,
TQueryKey
>[`enabled`]
refetchInterval?: QueryObserverOptions<
TQueryData,
TError,
Array<T>,
TQueryData,
TQueryKey
>[`refetchInterval`]
retry?: QueryObserverOptions<
TQueryData,
TError,
Array<T>,
TQueryData,
TQueryKey
>[`retry`]
retryDelay?: QueryObserverOptions<
TQueryData,
TError,
Array<T>,
TQueryData,
TQueryKey
>[`retryDelay`]
staleTime?: QueryObserverOptions<
TQueryData,
TError,
Array<T>,
TQueryData,
TQueryKey
>[`staleTime`]
persistedGcTime?: number
/**
* Metadata to pass to the query.
* Available in queryFn via context.meta
*
* @example
* // Using meta for error context
* queryFn: async (context) => {
* try {
* return await api.getTodos(userId)
* } catch (error) {
* // Use meta for better error messages
* throw new Error(
* context.meta?.errorMessage || 'Failed to load todos'
* )
* }
* },
* meta: {
* errorMessage: `Failed to load todos for user ${userId}`
* }
*/
meta?: Record<string, unknown>
}
/**
* Type for the refetch utility function
* Returns the QueryObserverResult from TanStack Query
*/
export type RefetchFn = (opts?: {
throwOnError?: boolean
}) => Promise<Array<QueryObserverResult<any, any> | void>>
/**
* Utility methods available on Query Collections for direct writes and manual operations.
* Direct writes bypass the normal query/mutation flow and write directly to the synced data store.
* @template TItem - The type of items stored in the collection
* @template TKey - The type of the item keys
* @template TInsertInput - The type accepted for insert operations
* @template TError - The type of errors that can occur during queries
*/
export interface QueryCollectionUtils<
TItem extends object = Record<string, unknown>,
TKey extends string | number = string | number,
TInsertInput extends object = TItem,
TError = unknown,
> extends UtilsRecord {
/** Manually trigger a refetch of the query */
refetch: RefetchFn
/** Insert one or more items directly into the synced data store without triggering a query refetch or optimistic update */
writeInsert: (data: TInsertInput | Array<TInsertInput>) => void
/** Update one or more items directly in the synced data store without triggering a query refetch or optimistic update */
writeUpdate: (updates: Partial<TItem> | Array<Partial<TItem>>) => void
/** Delete one or more items directly from the synced data store without triggering a query refetch or optimistic update */
writeDelete: (keys: TKey | Array<TKey>) => void
/** Insert or update one or more items directly in the synced data store without triggering a query refetch or optimistic update */
writeUpsert: (data: Partial<TItem> | Array<Partial<TItem>>) => void
/** Execute multiple write operations as a single atomic batch to the synced data store */
writeBatch: (callback: () => void) => void
// Query Observer State (getters)
/** Get the last error encountered by the query (if any); reset on success */
lastError: TError | undefined
/** Check if the collection is in an error state */
isError: boolean
/**
* Get the number of consecutive sync failures.
* Incremented only when query fails completely (not per retry attempt); reset on success.
*/
errorCount: number
/** Check if query is currently fetching (initial or background) */
isFetching: boolean
/** Check if query is refetching in background (not initial fetch) */
isRefetching: boolean
/** Check if query is loading for the first time (no data yet) */
isLoading: boolean
/** Get timestamp of last successful data update (in milliseconds) */
dataUpdatedAt: number
/** Get current fetch status */
fetchStatus: `fetching` | `paused` | `idle`
/**
* Clear the error state and trigger a refetch of the query
* @returns Promise that resolves when the refetch completes successfully
* @throws Error if the refetch fails
*/
clearError: () => Promise<void>
}
/**
* Internal state object for tracking query observer and errors
*/
interface QueryCollectionState {
lastError: any
errorCount: number
lastErrorUpdatedAt: number
observers: Map<
string,
QueryObserver<Array<any>, any, Array<any>, Array<any>, any>
>
}
type PersistedQueryRetentionEntry =
| {
queryHash: string
mode: `ttl`
expiresAt: number
}
| {
queryHash: string
mode: `until-revalidated`
}
const QUERY_COLLECTION_GC_PREFIX = `queryCollection:gc:`
type PersistedScannedRowForQuery<TItem extends object> = {
key: string | number
value: TItem
metadata?: unknown
}
type QuerySyncMetadataWithPersistedScan<TItem extends object> = SyncMetadataApi<
string | number
> & {
row: SyncMetadataApi<string | number>[`row`] & {
scanPersisted?: (options?: {
metadataOnly?: boolean
}) => Promise<Array<PersistedScannedRowForQuery<TItem>>>
}
}
/**
* Implementation class for QueryCollectionUtils with explicit dependency injection
* for better testability and architectural clarity
*/
class QueryCollectionUtilsImpl {
private state: QueryCollectionState
private refetchFn: RefetchFn
// Write methods
public refetch: RefetchFn
public writeInsert: any
public writeUpdate: any
public writeDelete: any
public writeUpsert: any
public writeBatch: any
constructor(
state: QueryCollectionState,
refetch: RefetchFn,
writeUtils: ReturnType<typeof createWriteUtils>,
) {
this.state = state
this.refetchFn = refetch
// Initialize methods to use passed dependencies
this.refetch = refetch
this.writeInsert = writeUtils.writeInsert
this.writeUpdate = writeUtils.writeUpdate
this.writeDelete = writeUtils.writeDelete
this.writeUpsert = writeUtils.writeUpsert
this.writeBatch = writeUtils.writeBatch
}
public async clearError() {
this.state.lastError = undefined
this.state.errorCount = 0
this.state.lastErrorUpdatedAt = 0
await this.refetchFn({ throwOnError: true })
}
// Getters for error state
public get lastError() {
return this.state.lastError
}
public get isError() {
return !!this.state.lastError
}
public get errorCount() {
return this.state.errorCount
}
// Getters for QueryObserver state
public get isFetching() {
// check if any observer is fetching
return Array.from(this.state.observers.values()).some(
(observer) => observer.getCurrentResult().isFetching,
)
}
public get isRefetching() {
// check if any observer is refetching
return Array.from(this.state.observers.values()).some(
(observer) => observer.getCurrentResult().isRefetching,
)
}
public get isLoading() {
// check if any observer is loading
return Array.from(this.state.observers.values()).some(
(observer) => observer.getCurrentResult().isLoading,
)
}
public get dataUpdatedAt() {
// compute the max dataUpdatedAt of all observers
return Math.max(
0,
...Array.from(this.state.observers.values()).map(
(observer) => observer.getCurrentResult().dataUpdatedAt,
),
)
}
public get fetchStatus(): Array<FetchStatus> {
return Array.from(this.state.observers.values()).map(
(observer) => observer.getCurrentResult().fetchStatus,
)
}
}
/**
* Creates query collection options for use with a standard Collection.
* This integrates TanStack Query with TanStack DB for automatic synchronization.
*
* Supports automatic type inference following the priority order:
* 1. Schema inference (highest priority)
* 2. QueryFn return type inference (second priority)
*
* @template T - Type of the schema if a schema is provided otherwise it is the type of the values returned by the queryFn
* @template TError - The type of errors that can occur during queries
* @template TQueryKey - The type of the query key
* @template TKey - The type of the item keys
* @param config - Configuration options for the Query collection
* @returns Collection options with utilities for direct writes and manual operations
*
* @example
* // Type inferred from queryFn return type (NEW!)
* const todosCollection = createCollection(
* queryCollectionOptions({
* queryKey: ['todos'],
* queryFn: async () => {
* const response = await fetch('/api/todos')
* return response.json() as Todo[] // Type automatically inferred!
* },
* queryClient,
* getKey: (item) => item.id, // item is typed as Todo
* })
* )
*
* @example
* // Explicit type
* const todosCollection = createCollection<Todo>(
* queryCollectionOptions({
* queryKey: ['todos'],
* queryFn: async () => fetch('/api/todos').then(r => r.json()),
* queryClient,
* getKey: (item) => item.id,
* })
* )
*
* @example
* // Schema inference
* const todosCollection = createCollection(
* queryCollectionOptions({
* queryKey: ['todos'],
* queryFn: async () => fetch('/api/todos').then(r => r.json()),
* queryClient,
* schema: todoSchema, // Type inferred from schema
* getKey: (item) => item.id,
* })
* )
*
* @example
* // With persistence handlers
* const todosCollection = createCollection(
* queryCollectionOptions({
* queryKey: ['todos'],
* queryFn: fetchTodos,
* queryClient,
* getKey: (item) => item.id,
* onInsert: async ({ transaction }) => {
* await api.createTodos(transaction.mutations.map(m => m.modified))
* },
* onUpdate: async ({ transaction }) => {
* await api.updateTodos(transaction.mutations)
* },
* onDelete: async ({ transaction }) => {
* await api.deleteTodos(transaction.mutations.map(m => m.key))
* }
* })
* )
*
* @example
* // The select option extracts the items array from a response with metadata
* const todosCollection = createCollection(
* queryCollectionOptions({
* queryKey: ['todos'],
* queryFn: async () => fetch('/api/todos').then(r => r.json()),
* select: (data) => data.items, // Extract the array of items
* queryClient,
* schema: todoSchema,
* getKey: (item) => item.id,
* })
* )
*/
// Overload for when schema is provided and select present
export function queryCollectionOptions<
T extends StandardSchemaV1,
TQueryFn extends (context: QueryFunctionContext<any>) => any,
TError = unknown,
TQueryKey extends QueryKey = QueryKey,
TKey extends string | number = string | number,
TQueryData = Awaited<ReturnType<TQueryFn>>,
>(
config: QueryCollectionConfig<
InferSchemaOutput<T>,
TQueryFn,
TError,
TQueryKey,
TKey,
T
> & {
schema: T
select: (data: TQueryData) => Array<InferSchemaInput<T>>
},
): CollectionConfig<
InferSchemaOutput<T>,
TKey,
T,
QueryCollectionUtils<InferSchemaOutput<T>, TKey, InferSchemaInput<T>, TError>
> & {
schema: T
utils: QueryCollectionUtils<
InferSchemaOutput<T>,
TKey,
InferSchemaInput<T>,
TError
>
}
// Overload for when no schema is provided and select present
export function queryCollectionOptions<
T extends object,
TQueryFn extends (context: QueryFunctionContext<any>) => any = (
context: QueryFunctionContext<any>,
) => any,
TError = unknown,
TQueryKey extends QueryKey = QueryKey,
TKey extends string | number = string | number,
TQueryData = Awaited<ReturnType<TQueryFn>>,
>(
config: QueryCollectionConfig<
T,
TQueryFn,
TError,
TQueryKey,
TKey,
never,
TQueryData
> & {
schema?: never // prohibit schema
select: (data: TQueryData) => Array<T>
},
): CollectionConfig<
T,
TKey,
never,
QueryCollectionUtils<T, TKey, T, TError>
> & {
schema?: never // no schema in the result
utils: QueryCollectionUtils<T, TKey, T, TError>
}
// Overload for when schema is provided
export function queryCollectionOptions<
T extends StandardSchemaV1,
TError = unknown,
TQueryKey extends QueryKey = QueryKey,
TKey extends string | number = string | number,
>(
config: QueryCollectionConfig<
InferSchemaOutput<T>,
(
context: QueryFunctionContext<any>,
) => Array<InferSchemaOutput<T>> | Promise<Array<InferSchemaOutput<T>>>,
TError,
TQueryKey,
TKey,
T
> & {
schema: T
},
): CollectionConfig<
InferSchemaOutput<T>,
TKey,
T,
QueryCollectionUtils<InferSchemaOutput<T>, TKey, InferSchemaInput<T>, TError>
> & {
schema: T
utils: QueryCollectionUtils<
InferSchemaOutput<T>,
TKey,
InferSchemaInput<T>,
TError
>
}
// Overload for when no schema is provided
export function queryCollectionOptions<
T extends object,
TError = unknown,
TQueryKey extends QueryKey = QueryKey,
TKey extends string | number = string | number,
>(
config: QueryCollectionConfig<
T,
(context: QueryFunctionContext<any>) => Array<T> | Promise<Array<T>>,
TError,
TQueryKey,
TKey
> & {
schema?: never // prohibit schema
},
): CollectionConfig<
T,
TKey,
never,
QueryCollectionUtils<T, TKey, T, TError>
> & {
schema?: never // no schema in the result
utils: QueryCollectionUtils<T, TKey, T, TError>
}
export function queryCollectionOptions(
config: QueryCollectionConfig<
Record<string, unknown>,
(context: QueryFunctionContext<any>) => any
>,
): CollectionConfig<
Record<string, unknown>,
string | number,
never,
QueryCollectionUtils
> & {
utils: QueryCollectionUtils
} {
const {
queryKey,
queryFn,
select,
queryClient,
enabled,
refetchInterval,
retry,
retryDelay,
staleTime,
persistedGcTime,
getKey,
onInsert,
onUpdate,
onDelete,
meta,
...baseCollectionConfig
} = config
// Default to eager sync mode if not provided
const syncMode = baseCollectionConfig.syncMode ?? `eager`
// Compute the base query key once for cache lookups.
// All derived keys (from on-demand predicates or function-based queryKey) must
// share this prefix so that queryCache.findAll({ queryKey: baseKey }) can find them.
const baseKey: QueryKey =
typeof queryKey === `function`
? (queryKey({}) as unknown as QueryKey)
: (queryKey as unknown as QueryKey)
/**
* Validates that a derived query key extends the base key prefix.
* TanStack Query uses prefix matching in findAll(), so all keys for this collection
* must start with baseKey for stale cache updates to work correctly.
*/
const validateQueryKeyPrefix = (key: QueryKey): void => {
if (typeof queryKey !== `function`) return
const isValidPrefix =
key.length >= baseKey.length &&
baseKey.every((segment, i) => deepEquals(segment, key[i]))
if (!isValidPrefix) {
console.warn(
`[QueryCollection] queryKey function must return keys that extend the base key prefix. ` +
`Base: ${JSON.stringify(baseKey)}, Got: ${JSON.stringify(key)}. ` +
`This can cause stale cache issues.`,
)
}
}
// Validate required parameters
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!queryKey) {
throw new QueryKeyRequiredError()
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!queryFn) {
throw new QueryFnRequiredError()
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!queryClient) {
throw new QueryClientRequiredError()
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!getKey) {
throw new GetKeyRequiredError()
}
/** State object to hold error tracking and observer reference */
const state: QueryCollectionState = {
lastError: undefined as any,
errorCount: 0,
lastErrorUpdatedAt: 0,
observers: new Map<
string,
QueryObserver<Array<any>, any, Array<any>, Array<any>, any>
>(),
}
// hashedQueryKey → queryKey
const hashToQueryKey = new Map<string, QueryKey>()
// queryKey → Set<RowKey>
const queryToRows = new Map<string, Set<string | number>>()
// RowKey → Set<queryKey>
const rowToQueries = new Map<string | number, Set<string>>()
// queryKey → QueryObserver's unsubscribe function
const unsubscribes = new Map<string, () => void>()
// queryKey → reference count (how many loadSubset calls are active)
// Reference counting for QueryObserver lifecycle management
// =========================================================
// Tracks how many live query subscriptions are using each QueryObserver.
// Multiple live queries with identical predicates share the same QueryObserver for efficiency.
//
// Lifecycle:
// - Increment: when createQueryFromOpts creates or reuses an observer
// - Decrement: when subscription.unsubscribe() passes predicates to collection._sync.unloadSubset()
// - Reset: when cleanupQuery() is triggered by TanStack Query's cache GC
//
// When refcount reaches 0, unloadSubset():
// 1. Computes the same queryKey from the predicates
// 2. Uses existing machinery (queryToRows map) to find rows that query loaded
// 3. Decrements refcount and GCs rows where count reaches 0
const queryRefCounts = new Map<string, number>()
// Helper function to add a row to the internal state
const addRow = (rowKey: string | number, hashedQueryKey: string) => {
const rowToQueriesSet = rowToQueries.get(rowKey) || new Set()
rowToQueriesSet.add(hashedQueryKey)
rowToQueries.set(rowKey, rowToQueriesSet)
const queryToRowsSet = queryToRows.get(hashedQueryKey) || new Set()
queryToRowsSet.add(rowKey)
queryToRows.set(hashedQueryKey, queryToRowsSet)
}
// Helper function to remove a row from the internal state
const removeRow = (rowKey: string | number, hashedQuerKey: string) => {
const rowToQueriesSet = rowToQueries.get(rowKey) || new Set()
rowToQueriesSet.delete(hashedQuerKey)
rowToQueries.set(rowKey, rowToQueriesSet)
const queryToRowsSet = queryToRows.get(hashedQuerKey) || new Set()
queryToRowsSet.delete(rowKey)
queryToRows.set(hashedQuerKey, queryToRowsSet)
return rowToQueriesSet.size === 0
}
const internalSync: SyncConfig<any>[`sync`] = (params) => {
const { begin, write, commit, markReady, collection, metadata } = params
const persistedMetadata = metadata as
| QuerySyncMetadataWithPersistedScan<any>
| undefined
// Track whether sync has been started
let syncStarted = false
let startupRetentionSettled = false
const retainedQueriesPendingRevalidation = new Set<string>()
const effectivePersistedGcTimes = new Map<string, number>()
const persistedRetentionTimers = new Map<
string,
ReturnType<typeof setTimeout>
>()
let persistedRetentionMaintenance = Promise.resolve()
const getRowMetadata = (rowKey: string | number) => {
return (metadata?.row.get(rowKey) ??
collection._state.syncedMetadata.get(rowKey)) as
| Record<string, unknown>
| undefined
}
const getPersistedOwners = (rowKey: string | number) => {
const rowMetadata = getRowMetadata(rowKey)
const queryMetadata = rowMetadata?.queryCollection
if (!queryMetadata || typeof queryMetadata !== `object`) {
return new Set<string>()
}
const owners = (queryMetadata as Record<string, unknown>).owners
if (!owners || typeof owners !== `object`) {
return new Set<string>()
}
return new Set(Object.keys(owners as Record<string, true>))
}
const setPersistedOwners = (
rowKey: string | number,
owners: Set<string>,
) => {
if (!metadata) {
return
}
const currentMetadata = { ...(getRowMetadata(rowKey) ?? {}) }
if (owners.size === 0) {
delete currentMetadata.queryCollection
if (Object.keys(currentMetadata).length === 0) {
metadata.row.delete(rowKey)
} else {
metadata.row.set(rowKey, currentMetadata)
}
return
}
metadata.row.set(rowKey, {
...currentMetadata,
queryCollection: {
owners: Object.fromEntries(
Array.from(owners.values()).map((owner) => [owner, true]),
),
},
})
}
const parsePersistedQueryRetentionEntry = (
value: unknown,
expectedHash: string,
): PersistedQueryRetentionEntry | undefined => {
if (!value || typeof value !== `object`) {
return undefined
}
const record = value as Record<string, unknown>
if (record.queryHash !== expectedHash) {
return undefined
}
if (record.mode === `until-revalidated`) {
return {
queryHash: expectedHash,
mode: `until-revalidated`,
}
}
if (
record.mode === `ttl` &&
typeof record.expiresAt === `number` &&
Number.isFinite(record.expiresAt)
) {
return {
queryHash: expectedHash,
mode: `ttl`,
expiresAt: record.expiresAt,
}
}
return undefined
}
const runPersistedRetentionMaintenance = (task: () => Promise<void>) => {
persistedRetentionMaintenance = persistedRetentionMaintenance.then(
task,
task,
)
return persistedRetentionMaintenance
}
const cancelPersistedRetentionExpiry = (hashedQueryKey: string) => {
const timer = persistedRetentionTimers.get(hashedQueryKey)
if (timer) {
clearTimeout(timer)
persistedRetentionTimers.delete(hashedQueryKey)
}
}
const getHydratedOwnedRowsForQueryBaseline = (hashedQueryKey: string) => {
const knownRows = queryToRows.get(hashedQueryKey)
if (knownRows) {
return new Set(knownRows)
}
const ownedRows = new Set<string | number>()
for (const [rowKey] of collection._state.syncedData.entries()) {
const persistedOwners = getPersistedOwners(rowKey)
if (persistedOwners.size === 0) {
continue
}
// MERGE persisted owners into any existing in-memory owners. Never
// overwrite — other queries may have claimed ownership in-memory via
// `addRow` without a corresponding `setPersistedOwners` yet (e.g.
// when the collection runs without a SyncMetadataApi). Overwriting
// would desync `rowToQueries` from `queryToRows` and cause
// `cleanupQueryInternal` to later delete rows still needed by active
// queries.
const existingOwners = rowToQueries.get(rowKey)
if (existingOwners) {
persistedOwners.forEach((owner) => existingOwners.add(owner))
} else {
rowToQueries.set(rowKey, new Set(persistedOwners))
}
persistedOwners.forEach((owner) => {
const queryToRowsSet = queryToRows.get(owner) || new Set()
queryToRowsSet.add(rowKey)
queryToRows.set(owner, queryToRowsSet)
})
if (persistedOwners.has(hashedQueryKey)) {
ownedRows.add(rowKey)
}
}
return ownedRows
}
const loadPersistedBaselineForQuery = async (
hashedQueryKey: string,
): Promise<
Map<
string | number,
{
value: any
owners: Set<string>
}
>
> => {
const knownRows = queryToRows.get(hashedQueryKey)
if (
knownRows &&
Array.from(knownRows).every((rowKey) => collection.has(rowKey))
) {
const baseline = new Map<
string | number,
{ value: any; owners: Set<string> }
>()
knownRows.forEach((rowKey) => {
const value = collection.get(rowKey)
const owners = rowToQueries.get(rowKey)
if (value && owners) {
baseline.set(rowKey, {
value,
owners: new Set(owners),
})
}
})
return baseline
}
const scanPersisted = persistedMetadata?.row.scanPersisted
if (!scanPersisted) {
const baseline = new Map<
string | number,
{ value: any; owners: Set<string> }
>()
getHydratedOwnedRowsForQueryBaseline(hashedQueryKey).forEach(
(rowKey) => {
const value = collection.get(rowKey)
const owners = rowToQueries.get(rowKey)
if (value && owners) {
baseline.set(rowKey, {
value,
owners: new Set(owners),
})
}
},
)
return baseline
}
const baseline = new Map<
string | number,
{ value: any; owners: Set<string> }
>()
const scannedRows = await scanPersisted()
scannedRows.forEach((row) => {
const rowMetadata = row.metadata as Record<string, unknown> | undefined
const queryMetadata = rowMetadata?.queryCollection
if (!queryMetadata || typeof queryMetadata !== `object`) {
return
}
const owners = (queryMetadata as Record<string, unknown>).owners
if (!owners || typeof owners !== `object`) {
return
}
const ownerSet = new Set(Object.keys(owners as Record<string, true>))
if (ownerSet.size === 0) {
return
}
// MERGE into existing in-memory owners (see note in
// getHydratedOwnedRowsForQueryBaseline). Overwriting here would strip
// in-memory-only ownership registered by active queries.
const existingOwners = rowToQueries.get(row.key)
if (existingOwners) {
ownerSet.forEach((owner) => existingOwners.add(owner))
} else {
rowToQueries.set(row.key, new Set(ownerSet))
}
ownerSet.forEach((owner) => {
const queryToRowsSet = queryToRows.get(owner) || new Set()
queryToRowsSet.add(row.key)
queryToRows.set(owner, queryToRowsSet)
})
if (ownerSet.has(hashedQueryKey)) {
baseline.set(row.key, {
value: row.value,
owners: ownerSet,
})
}
})
return baseline
}
const cleanupPersistedPlaceholder = async (hashedQueryKey: string) => {
if (!metadata) {
return
}
const baseline = await loadPersistedBaselineForQuery(hashedQueryKey)
const rowsToDelete: Array<any> = []
begin()
baseline.forEach(({ value: oldItem, owners }, rowKey) => {
owners.delete(hashedQueryKey)
setPersistedOwners(rowKey, owners)
const needToRemove = removeRow(rowKey, hashedQueryKey)
if (needToRemove) {
rowsToDelete.push(oldItem)
}
})
rowsToDelete.forEach((row) => {
write({ type: `delete`, value: row })
})
metadata.collection.delete(
`${QUERY_COLLECTION_GC_PREFIX}${hashedQueryKey}`,
)
commit()
}
const schedulePersistedRetentionExpiry = (
entry: PersistedQueryRetentionEntry,
) => {
if (entry.mode !== `ttl`) {
return