@powersync/service-core 0.0.0-dev-20260601140105 → 0.0.0-dev-20260803144812

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.
Files changed (183) hide show
  1. package/CHANGELOG.md +83 -4
  2. package/dist/api/RouteAPI.d.ts +42 -14
  3. package/dist/api/diagnostics.d.ts +12 -1
  4. package/dist/api/diagnostics.js +34 -22
  5. package/dist/api/diagnostics.js.map +1 -1
  6. package/dist/entry/commands/compact-action.js +5 -1
  7. package/dist/entry/commands/compact-action.js.map +1 -1
  8. package/dist/modules/AbstractModule.d.ts +6 -2
  9. package/dist/modules/AbstractModule.js.map +1 -1
  10. package/dist/replication/AbstractReplicator.d.ts +26 -7
  11. package/dist/replication/AbstractReplicator.js +148 -68
  12. package/dist/replication/AbstractReplicator.js.map +1 -1
  13. package/dist/replication/ReplicationModule.d.ts +3 -3
  14. package/dist/replication/ReplicationModule.js.map +1 -1
  15. package/dist/routes/RouterEngine.d.ts +1 -0
  16. package/dist/routes/RouterEngine.js +6 -1
  17. package/dist/routes/RouterEngine.js.map +1 -1
  18. package/dist/routes/configure-fastify.d.ts +95 -56
  19. package/dist/routes/configure-fastify.js +15 -2
  20. package/dist/routes/configure-fastify.js.map +1 -1
  21. package/dist/routes/endpoints/admin.d.ts +24 -24
  22. package/dist/routes/endpoints/admin.js +46 -35
  23. package/dist/routes/endpoints/admin.js.map +1 -1
  24. package/dist/routes/endpoints/checkpointing.d.ts +62 -0
  25. package/dist/routes/endpoints/checkpointing.js +65 -7
  26. package/dist/routes/endpoints/checkpointing.js.map +1 -1
  27. package/dist/routes/endpoints/socket-route.js +3 -2
  28. package/dist/routes/endpoints/socket-route.js.map +1 -1
  29. package/dist/routes/endpoints/sync-rules.js +22 -13
  30. package/dist/routes/endpoints/sync-rules.js.map +1 -1
  31. package/dist/routes/endpoints/sync-stream.js +1 -1
  32. package/dist/routes/endpoints/sync-stream.js.map +1 -1
  33. package/dist/runner/teardown.js +8 -8
  34. package/dist/runner/teardown.js.map +1 -1
  35. package/dist/storage/BucketStorageBatch.d.ts +63 -17
  36. package/dist/storage/BucketStorageBatch.js.map +1 -1
  37. package/dist/storage/BucketStorageFactory.d.ts +22 -27
  38. package/dist/storage/BucketStorageFactory.js +4 -18
  39. package/dist/storage/BucketStorageFactory.js.map +1 -1
  40. package/dist/storage/CheckpointChecksumInvalidatedError.d.ts +12 -0
  41. package/dist/storage/CheckpointChecksumInvalidatedError.js +17 -0
  42. package/dist/storage/CheckpointChecksumInvalidatedError.js.map +1 -0
  43. package/dist/storage/ChecksumCache.d.ts +11 -6
  44. package/dist/storage/ChecksumCache.js +5 -4
  45. package/dist/storage/ChecksumCache.js.map +1 -1
  46. package/dist/storage/ParsedSyncConfigSet.d.ts +23 -0
  47. package/dist/storage/ParsedSyncConfigSet.js +2 -0
  48. package/dist/storage/ParsedSyncConfigSet.js.map +1 -0
  49. package/dist/storage/PersistedReplicationStream.d.ts +32 -0
  50. package/dist/storage/PersistedReplicationStream.js +26 -0
  51. package/dist/storage/PersistedReplicationStream.js.map +1 -0
  52. package/dist/storage/PersistedSyncConfigContent.d.ts +63 -0
  53. package/dist/storage/PersistedSyncConfigContent.js +125 -0
  54. package/dist/storage/PersistedSyncConfigContent.js.map +1 -0
  55. package/dist/storage/PersistedSyncConfigStatus.d.ts +13 -0
  56. package/dist/storage/PersistedSyncConfigStatus.js +2 -0
  57. package/dist/storage/PersistedSyncConfigStatus.js.map +1 -0
  58. package/dist/storage/SourceEntity.d.ts +6 -0
  59. package/dist/storage/SourceTable.d.ts +21 -3
  60. package/dist/storage/SourceTable.js +26 -3
  61. package/dist/storage/SourceTable.js.map +1 -1
  62. package/dist/storage/SyncRulesBucketStorage.d.ts +119 -21
  63. package/dist/storage/SyncRulesBucketStorage.js +3 -0
  64. package/dist/storage/SyncRulesBucketStorage.js.map +1 -1
  65. package/dist/storage/WriteCheckpointAPI.d.ts +60 -3
  66. package/dist/storage/WriteCheckpointAPI.js +33 -0
  67. package/dist/storage/WriteCheckpointAPI.js.map +1 -1
  68. package/dist/storage/implementation/BucketDefinitionMapping.d.ts +117 -0
  69. package/dist/storage/implementation/BucketDefinitionMapping.js +277 -0
  70. package/dist/storage/implementation/BucketDefinitionMapping.js.map +1 -0
  71. package/dist/storage/implementation/IncrementalReprocessingCompatibility.d.ts +6 -0
  72. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js +31 -0
  73. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js.map +1 -0
  74. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.d.ts +17 -0
  75. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js +62 -0
  76. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js.map +1 -0
  77. package/dist/storage/implementation/ReplicationStreamStorageIds.d.ts +15 -0
  78. package/dist/storage/implementation/ReplicationStreamStorageIds.js +20 -0
  79. package/dist/storage/implementation/ReplicationStreamStorageIds.js.map +1 -0
  80. package/dist/storage/storage-index.d.ts +9 -1
  81. package/dist/storage/storage-index.js +9 -1
  82. package/dist/storage/storage-index.js.map +1 -1
  83. package/dist/sync/BucketChecksumState.d.ts +12 -2
  84. package/dist/sync/BucketChecksumState.js +69 -21
  85. package/dist/sync/BucketChecksumState.js.map +1 -1
  86. package/dist/sync/RequestTracker.d.ts +7 -0
  87. package/dist/sync/RequestTracker.js +12 -0
  88. package/dist/sync/RequestTracker.js.map +1 -1
  89. package/dist/sync/sync.js +154 -41
  90. package/dist/sync/sync.js.map +1 -1
  91. package/dist/sync/util.d.ts +5 -0
  92. package/dist/sync/util.js +9 -0
  93. package/dist/sync/util.js.map +1 -1
  94. package/dist/system/ServiceContext.d.ts +2 -0
  95. package/dist/system/ServiceContext.js +2 -0
  96. package/dist/system/ServiceContext.js.map +1 -1
  97. package/dist/tracing/PerformanceTracer.d.ts +23 -1
  98. package/dist/tracing/PerformanceTracer.js +11 -0
  99. package/dist/tracing/PerformanceTracer.js.map +1 -1
  100. package/dist/util/checkpointing.d.ts +4 -8
  101. package/dist/util/checkpointing.js +1 -16
  102. package/dist/util/checkpointing.js.map +1 -1
  103. package/dist/util/config/compound-config-collector.js +18 -2
  104. package/dist/util/config/compound-config-collector.js.map +1 -1
  105. package/dist/util/config/defaults.d.ts +2 -0
  106. package/dist/util/config/defaults.js +2 -0
  107. package/dist/util/config/defaults.js.map +1 -1
  108. package/dist/util/config/types.d.ts +3 -1
  109. package/dist/util/lsn.d.ts +4 -0
  110. package/dist/util/lsn.js +10 -0
  111. package/dist/util/lsn.js.map +1 -1
  112. package/dist/util/util-index.d.ts +1 -0
  113. package/dist/util/util-index.js +1 -0
  114. package/dist/util/util-index.js.map +1 -1
  115. package/dist/util/utils.d.ts +1 -1
  116. package/dist/util/utils.js +1 -1
  117. package/dist/util/write-checkpoint-batcher.d.ts +19 -0
  118. package/dist/util/write-checkpoint-batcher.js +100 -0
  119. package/dist/util/write-checkpoint-batcher.js.map +1 -0
  120. package/package.json +6 -7
  121. package/src/api/RouteAPI.ts +43 -14
  122. package/src/api/diagnostics.ts +43 -26
  123. package/src/entry/commands/compact-action.ts +7 -1
  124. package/src/modules/AbstractModule.ts +6 -2
  125. package/src/replication/AbstractReplicator.ts +181 -72
  126. package/src/replication/ReplicationModule.ts +2 -3
  127. package/src/routes/RouterEngine.ts +7 -1
  128. package/src/routes/configure-fastify.ts +25 -2
  129. package/src/routes/endpoints/admin.ts +72 -50
  130. package/src/routes/endpoints/checkpointing.ts +79 -8
  131. package/src/routes/endpoints/socket-route.ts +3 -2
  132. package/src/routes/endpoints/sync-rules.ts +23 -13
  133. package/src/routes/endpoints/sync-stream.ts +1 -1
  134. package/src/runner/teardown.ts +8 -8
  135. package/src/storage/BucketStorageBatch.ts +64 -18
  136. package/src/storage/BucketStorageFactory.ts +30 -39
  137. package/src/storage/CheckpointChecksumInvalidatedError.ts +17 -0
  138. package/src/storage/ChecksumCache.ts +27 -14
  139. package/src/storage/ParsedSyncConfigSet.ts +25 -0
  140. package/src/storage/PersistedReplicationStream.ts +55 -0
  141. package/src/storage/PersistedSyncConfigContent.ts +192 -0
  142. package/src/storage/PersistedSyncConfigStatus.ts +14 -0
  143. package/src/storage/SourceEntity.ts +6 -0
  144. package/src/storage/SourceTable.ts +34 -3
  145. package/src/storage/SyncRulesBucketStorage.ts +138 -22
  146. package/src/storage/WriteCheckpointAPI.ts +108 -3
  147. package/src/storage/implementation/BucketDefinitionMapping.ts +436 -0
  148. package/src/storage/implementation/IncrementalReprocessingCompatibility.ts +41 -0
  149. package/src/storage/implementation/IncrementalReprocessingSyncConfigLog.ts +109 -0
  150. package/src/storage/implementation/ReplicationStreamStorageIds.ts +21 -0
  151. package/src/storage/storage-index.ts +10 -1
  152. package/src/sync/BucketChecksumState.ts +103 -21
  153. package/src/sync/RequestTracker.ts +20 -0
  154. package/src/sync/sync.ts +183 -48
  155. package/src/sync/util.ts +12 -0
  156. package/src/system/ServiceContext.ts +7 -0
  157. package/src/tracing/PerformanceTracer.ts +41 -1
  158. package/src/util/checkpointing.ts +4 -22
  159. package/src/util/config/compound-config-collector.ts +25 -1
  160. package/src/util/config/defaults.ts +2 -0
  161. package/src/util/config/types.ts +3 -1
  162. package/src/util/lsn.ts +9 -0
  163. package/src/util/util-index.ts +1 -0
  164. package/src/util/utils.ts +1 -1
  165. package/src/util/write-checkpoint-batcher.ts +142 -0
  166. package/test/src/AbstractReplicator.test.ts +115 -0
  167. package/test/src/checksum_cache.test.ts +22 -0
  168. package/test/src/config.test.ts +102 -0
  169. package/test/src/diagnostics.test.ts +62 -34
  170. package/test/src/module-loader.test.ts +33 -1
  171. package/test/src/routes/admin.test.ts +182 -18
  172. package/test/src/routes/checkpointing.test.ts +54 -0
  173. package/test/src/routes/mocks.ts +6 -2
  174. package/test/src/storage/SourceTable.test.ts +89 -0
  175. package/test/src/sync/BucketChecksumState.test.ts +98 -12
  176. package/test/src/sync/util.test.ts +13 -1
  177. package/test/src/util/checkpointing.test.ts +249 -0
  178. package/tsconfig.json +1 -4
  179. package/tsconfig.tsbuildinfo +1 -1
  180. package/dist/storage/PersistedSyncRulesContent.d.ts +0 -59
  181. package/dist/storage/PersistedSyncRulesContent.js +0 -100
  182. package/dist/storage/PersistedSyncRulesContent.js.map +0 -1
  183. package/src/storage/PersistedSyncRulesContent.ts +0 -174
@@ -1,6 +1,7 @@
1
1
  import { BaseObserver, logger } from '@powersync/lib-services-framework';
2
2
  import {
3
3
  PrecompiledSyncConfig,
4
+ SerializedSyncPlan as RawSerializedSyncPlan,
4
5
  SerializedCompatibilityContext,
5
6
  serializeSyncPlan,
6
7
  SqlSyncRules,
@@ -8,7 +9,8 @@ import {
8
9
  } from '@powersync/service-sync-rules';
9
10
  import { ReplicationError } from '@powersync/service-types';
10
11
  import { syncConfigYamlErrorToReplicationError } from '../util/errors.js';
11
- import { ParseSyncRulesOptions, PersistedSyncRules, PersistedSyncRulesContent } from './PersistedSyncRulesContent.js';
12
+ import { PersistedReplicationStream } from './PersistedReplicationStream.js';
13
+ import { PersistedSyncConfigContent } from './PersistedSyncConfigContent.js';
12
14
  import { ReplicationEventPayload } from './ReplicationEventPayload.js';
13
15
  import { ReplicationLock } from './ReplicationLock.js';
14
16
  import { ReportStorage } from './ReportStorage.js';
@@ -31,14 +33,14 @@ export abstract class BucketStorageFactory
31
33
  */
32
34
  async configureSyncRules(
33
35
  options: UpdateSyncRulesOptions
34
- ): Promise<{ updated: boolean; persisted_sync_rules?: PersistedSyncRulesContent; lock?: ReplicationLock }> {
35
- const next = await this.getNextSyncRulesContent();
36
- const active = await this.getActiveSyncRulesContent();
36
+ ): Promise<{ updated: boolean; persisted_sync_rules?: PersistedReplicationStream; lock?: ReplicationLock }> {
37
+ const deploying = await this.getDeployingSyncConfig();
38
+ const active = await this.getActiveSyncConfig();
37
39
 
38
- if (next?.sync_rules_content == options.config.yaml) {
40
+ if (deploying?.content.sync_rules_content == options.config.yaml) {
39
41
  logger.info('Sync config unchanged');
40
42
  return { updated: false };
41
- } else if (next == null && active?.sync_rules_content == options.config.yaml) {
43
+ } else if (deploying == null && active?.content.sync_rules_content == options.config.yaml) {
42
44
  logger.info('Sync config unchanged');
43
45
  return { updated: false };
44
46
  } else {
@@ -51,12 +53,15 @@ export abstract class BucketStorageFactory
51
53
  /**
52
54
  * Get a storage instance to query sync data for specific sync config.
53
55
  */
54
- abstract getInstance(syncRules: PersistedSyncRulesContent, options?: GetIntanceOptions): SyncRulesBucketStorage;
56
+ abstract getInstance(
57
+ replicationStream: PersistedReplicationStream,
58
+ options?: GetIntanceOptions
59
+ ): SyncRulesBucketStorage;
55
60
 
56
61
  /**
57
62
  * Deploy new sync config.
58
63
  */
59
- abstract updateSyncRules(options: UpdateSyncRulesOptions): Promise<PersistedSyncRulesContent>;
64
+ abstract updateSyncRules(options: UpdateSyncRulesOptions): Promise<PersistedReplicationStream>;
60
65
 
61
66
  /**
62
67
  * Indicate that a slot was removed, and we should re-sync by creating
@@ -68,48 +73,27 @@ export abstract class BucketStorageFactory
68
73
  *
69
74
  * Replication should be restarted after this.
70
75
  */
71
- abstract restartReplication(sync_rules_group_id: number): Promise<void>;
76
+ abstract restartReplication(replicationStreamId: number): Promise<void>;
72
77
 
73
78
  /**
74
- * Get the sync config used for querying.
79
+ * Get the sync config and storage used for querying.
75
80
  */
76
- async getActiveSyncRules(options: ParseSyncRulesOptions): Promise<PersistedSyncRules | null> {
77
- const content = await this.getActiveSyncRulesContent();
78
- return content?.parsed(options) ?? null;
79
- }
81
+ abstract getActiveSyncConfig(): Promise<ResolvedSyncConfig | null>;
80
82
 
81
83
  /**
82
- * Get the sync config used for querying.
84
+ * Get the sync config and storage that is still deploying.
83
85
  */
84
- abstract getActiveSyncRulesContent(): Promise<PersistedSyncRulesContent | null>;
86
+ abstract getDeployingSyncConfig(): Promise<ResolvedSyncConfig | null>;
85
87
 
86
88
  /**
87
- * Get the sync config that will be active next once done with initial replicatino.
89
+ * Get all replication streams currently replicating.
88
90
  */
89
- async getNextSyncRules(options: ParseSyncRulesOptions): Promise<PersistedSyncRules | null> {
90
- const content = await this.getNextSyncRulesContent();
91
- return content?.parsed(options) ?? null;
92
- }
91
+ abstract getReplicatingReplicationStreams(): Promise<PersistedReplicationStream[]>;
93
92
 
94
93
  /**
95
- * Get the sync config that will be active next once done with initial replicatino.
94
+ * Get all replication streams stopped but not terminated yet.
96
95
  */
97
- abstract getNextSyncRulesContent(): Promise<PersistedSyncRulesContent | null>;
98
-
99
- /**
100
- * Get all sync config currently replicating. Typically this is the "active" and "next" sync config.
101
- */
102
- abstract getReplicatingSyncRules(): Promise<PersistedSyncRulesContent[]>;
103
-
104
- /**
105
- * Get all sync config stopped but not terminated yet.
106
- */
107
- abstract getStoppedSyncRules(): Promise<PersistedSyncRulesContent[]>;
108
-
109
- /**
110
- * Get the active storage instance.
111
- */
112
- abstract getActiveStorage(): Promise<SyncRulesBucketStorage | null>;
96
+ abstract getStoppedReplicationStreams(): Promise<PersistedReplicationStream[]>;
113
97
 
114
98
  /**
115
99
  * Get storage size of active replication stream.
@@ -134,6 +118,12 @@ export interface BucketStorageFactoryListener {
134
118
  replicationEvent: (event: ReplicationEventPayload) => void;
135
119
  }
136
120
 
121
+ export interface ResolvedSyncConfig {
122
+ content: PersistedSyncConfigContent;
123
+ replicationStream: PersistedReplicationStream;
124
+ storage: SyncRulesBucketStorage;
125
+ }
126
+
137
127
  export interface StorageMetrics {
138
128
  /**
139
129
  * Size of operations (bucket_data)
@@ -181,7 +171,7 @@ export interface SerializedSyncPlan {
181
171
  /**
182
172
  * The serialized plan, from {@link serializeSyncPlan}.
183
173
  */
184
- plan: unknown;
174
+ plan: RawSerializedSyncPlan;
185
175
  compatibility: SerializedCompatibilityContext;
186
176
  /**
187
177
  * Event descriptors are not currently represented in the sync plan because they don't use the sync streams compiler
@@ -278,4 +268,5 @@ export interface TestStorageConfig {
278
268
  factory: TestStorageFactory;
279
269
  tableIdStrings: boolean;
280
270
  storageVersion?: number;
271
+ compressedBucketStorage?: boolean;
281
272
  }
@@ -0,0 +1,17 @@
1
+ import { InternalOpId } from '../util/util-index.js';
2
+
3
+ /**
4
+ * A checkpoint cannot be served because compaction rewrote a bucket-data
5
+ * document across its end boundary.
6
+ *
7
+ * The sync loop must skip this checkpoint before it sends its checkpoint line.
8
+ */
9
+ export class CheckpointChecksumInvalidatedError extends Error {
10
+ constructor(
11
+ public readonly checkpoint: InternalOpId,
12
+ public readonly bucket: string
13
+ ) {
14
+ super(`Checkpoint ${checkpoint} was invalidated by compaction in bucket ${bucket}`);
15
+ this.name = 'CheckpointChecksumInvalidatedError';
16
+ }
17
+ }
@@ -5,7 +5,7 @@ import { BucketChecksum } from '../util/protocol-types.js';
5
5
  import { addBucketChecksums, ChecksumMap, InternalOpId, PartialChecksum } from '../util/utils.js';
6
6
  import { BucketChecksumRequest } from './SyncRulesBucketStorage.js';
7
7
 
8
- interface ChecksumFetchContext {
8
+ interface ChecksumFetchContext<TContext> {
9
9
  fetch(bucket: string): Promise<BucketChecksum>;
10
10
  checkpoint: InternalOpId;
11
11
  }
@@ -20,26 +20,35 @@ export interface FetchPartialBucketChecksum {
20
20
  export type PartialOrFullChecksum = PartialChecksum | BucketChecksum;
21
21
  export type PartialChecksumMap = Map<string, PartialOrFullChecksum>;
22
22
 
23
- export type FetchChecksums = (batch: FetchPartialBucketChecksum[]) => Promise<PartialChecksumMap>;
23
+ export type FetchChecksums<TContext = undefined> = (
24
+ batch: FetchPartialBucketChecksum[],
25
+ context: TContext
26
+ ) => Promise<PartialChecksumMap>;
24
27
 
25
- export interface ChecksumCacheOptions {
28
+ export interface ChecksumCacheOptions<TContext = undefined> {
26
29
  /**
27
30
  * Upstream checksum implementation.
28
31
  *
29
32
  * This fetches a batch of either entire bucket checksums, or a partial range.
30
33
  */
31
- fetchChecksums: FetchChecksums;
34
+ fetchChecksums: FetchChecksums<TContext>;
32
35
 
33
36
  /**
34
37
  * Maximum number of cached checksums.
35
38
  */
36
39
  maxSize?: number;
40
+
41
+ /**
42
+ * How long to keep cached checksums before refreshing them.
43
+ */
44
+ ttlMs?: number;
37
45
  }
38
46
 
39
47
  // Approximately 5MB of memory, if we assume 50 bytes per entry
40
48
  const DEFAULT_MAX_SIZE = 100_000;
41
49
 
42
- const TTL_MS = 3_600_000;
50
+ // Default to 1h
51
+ export const DEFAULT_CHECKSUM_CACHE_TTL_MS = 1 * 3_600_000;
43
52
 
44
53
  /**
45
54
  * Implement a LRU cache for checksum requests. Each (bucket, checkpoint) request is cached separately,
@@ -50,22 +59,22 @@ const TTL_MS = 3_600_000;
50
59
  *
51
60
  * We use the LRUCache fetchMethod to deduplicate in-progress requests.
52
61
  */
53
- export class ChecksumCache {
62
+ export class ChecksumCache<TContext = undefined> {
54
63
  /**
55
64
  * The primary checksum cache, with key of `${checkpoint}/${bucket}`.
56
65
  */
57
- private cache: LRUCache<string, BucketChecksum, ChecksumFetchContext>;
66
+ private cache: LRUCache<string, BucketChecksum, ChecksumFetchContext<TContext>>;
58
67
  /**
59
68
  * For each bucket, an ordered set of cached checkpoints.
60
69
  */
61
70
  private bucketCheckpoints = new Map<string, OrderedSet<bigint>>();
62
71
 
63
- private fetchChecksums: FetchChecksums;
72
+ private fetchChecksums: FetchChecksums<TContext>;
64
73
 
65
- constructor(options: ChecksumCacheOptions) {
74
+ constructor(options: ChecksumCacheOptions<TContext>) {
66
75
  this.fetchChecksums = options.fetchChecksums;
67
76
 
68
- this.cache = new LRUCache<string, BucketChecksum, ChecksumFetchContext>({
77
+ this.cache = new LRUCache<string, BucketChecksum, ChecksumFetchContext<TContext>>({
69
78
  max: options.maxSize ?? DEFAULT_MAX_SIZE,
70
79
  fetchMethod: async (cacheKey, _staleValue, options) => {
71
80
  // Called when this checksum hasn't been cached yet.
@@ -105,7 +114,7 @@ export class ChecksumCache {
105
114
  // We use a TTL so that counts can eventually be refreshed
106
115
  // after a compact. This only has effect if the bucket has
107
116
  // not been checked in the meantime.
108
- ttl: TTL_MS,
117
+ ttl: options.ttlMs ?? DEFAULT_CHECKSUM_CACHE_TTL_MS,
109
118
  ttlResolution: 1_000,
110
119
  allowStale: false
111
120
  });
@@ -129,7 +138,11 @@ export class ChecksumCache {
129
138
  *
130
139
  * @returns a Map with exactly one entry for each bucket requested
131
140
  */
132
- async getChecksumMap(checkpoint: InternalOpId, buckets: BucketChecksumRequest[]): Promise<ChecksumMap> {
141
+ async getChecksumMap(
142
+ checkpoint: InternalOpId,
143
+ buckets: BucketChecksumRequest[],
144
+ fetchContext?: TContext
145
+ ): Promise<ChecksumMap> {
133
146
  // Buckets that don't have a cached checksum for this checkpoint yet
134
147
  let toFetch = new Set<string>();
135
148
 
@@ -147,7 +160,7 @@ export class ChecksumCache {
147
160
  // Accumulated results - both from cached checksums, and fetched checksums
148
161
  let finalResults = new Map<string, BucketChecksum>();
149
162
 
150
- const context: ChecksumFetchContext = {
163
+ const context: ChecksumFetchContext<TContext> = {
151
164
  async fetch(bucket) {
152
165
  await fetchPromise;
153
166
  if (!toFetch.has(bucket)) {
@@ -260,7 +273,7 @@ export class ChecksumCache {
260
273
  }
261
274
 
262
275
  // Fetch partial checksums from upstream
263
- const results = await this.fetchChecksums(bucketRequests);
276
+ const results = await this.fetchChecksums(bucketRequests, fetchContext as TContext);
264
277
 
265
278
  for (let bucket of toFetch) {
266
279
  const result = results.get(bucket);
@@ -0,0 +1,25 @@
1
+ import { HydratedSyncConfig, HydrationState, SyncConfigWithErrors } from '@powersync/service-sync-rules';
2
+
3
+ /**
4
+ * A parsed sync config set is the identity boundary for parsed sync config state.
5
+ *
6
+ * All values on a single instance - the parsed configs, hydration state and hydrated
7
+ * sync config - are derived from the same parse, and may be associated with each other
8
+ * by object identity. Values from two different instances must never be mixed, even if
9
+ * they were parsed from the same persisted content.
10
+ */
11
+ export interface ParsedSyncConfigSet {
12
+ readonly replicationStreamId: number;
13
+ readonly replicationStreamName: string;
14
+ readonly syncConfigs: SyncConfigWithErrors[];
15
+ /**
16
+ * For testing only.
17
+ */
18
+ readonly hydrationState: HydrationState;
19
+
20
+ /**
21
+ * The hydrated sync config for this parse. This is a stable property: repeated reads
22
+ * return the same instance.
23
+ */
24
+ readonly hydratedSyncConfig: HydratedSyncConfig;
25
+ }
@@ -0,0 +1,55 @@
1
+ import { logger as defaultLogger, ErrorCode, ServiceError } from '@powersync/lib-services-framework';
2
+ import { Logger } from 'winston';
3
+ import { SyncRuleState } from './BucketStorage.js';
4
+ import type { ParsedSyncConfigSet } from './ParsedSyncConfigSet.js';
5
+ import type { ParseSyncConfigOptions, PersistedSyncConfigContent } from './PersistedSyncConfigContent.js';
6
+ import { ReplicationLock } from './ReplicationLock.js';
7
+ import { STORAGE_VERSION_CONFIG, StorageVersionConfig } from './StorageVersionConfig.js';
8
+
9
+ export abstract class PersistedReplicationStream implements PersistedReplicationStreamData {
10
+ readonly replicationStreamId: number;
11
+ readonly replicationJobId: string;
12
+ readonly replicationStreamName: string;
13
+ readonly state: SyncRuleState;
14
+ readonly storageVersion: number;
15
+ readonly logger: Logger;
16
+
17
+ abstract readonly syncConfigContent: readonly PersistedSyncConfigContent[];
18
+ abstract readonly current_lock: ReplicationLock | null;
19
+
20
+ constructor(data: PersistedReplicationStreamData) {
21
+ this.replicationStreamId = data.replicationStreamId;
22
+ this.replicationJobId = data.replicationJobId ?? String(data.replicationStreamId);
23
+ this.replicationStreamName = data.replicationStreamName;
24
+ this.state = data.state;
25
+ this.storageVersion = data.storageVersion;
26
+ this.logger = defaultLogger.child({ prefix: `[${this.replicationStreamName}] ` });
27
+ }
28
+
29
+ getStorageConfig(): StorageVersionConfig {
30
+ const storageConfig = STORAGE_VERSION_CONFIG[this.storageVersion];
31
+ if (storageConfig == null) {
32
+ throw new ServiceError(
33
+ ErrorCode.PSYNC_S1005,
34
+ `Unsupported storage version ${this.storageVersion} for replication stream ${this.replicationStreamId}`
35
+ );
36
+ }
37
+ return storageConfig;
38
+ }
39
+
40
+ abstract lock(): Promise<ReplicationLock>;
41
+
42
+ abstract parsed(options: ParseSyncConfigOptions): ParsedSyncConfigSet;
43
+ }
44
+ export interface PersistedReplicationStreamData {
45
+ readonly replicationStreamId: number;
46
+ readonly replicationStreamName: string;
47
+ readonly state: SyncRuleState;
48
+ readonly storageVersion: number;
49
+ /**
50
+ * Uniquely identifies a job, as a combination of replication stream and processing sync configs.
51
+ *
52
+ * Used in-memory only.
53
+ */
54
+ readonly replicationJobId?: string;
55
+ }
@@ -0,0 +1,192 @@
1
+ import { logger as defaultLogger, ErrorCode, ServiceError } from '@powersync/lib-services-framework';
2
+ import {
3
+ CompatibilityContext,
4
+ CompatibilityOption,
5
+ DEFAULT_HYDRATION_STATE,
6
+ deserializeSyncPlan,
7
+ ErrorLocation,
8
+ HydratedSyncConfig,
9
+ HydrationState,
10
+ nodeSqlite,
11
+ PrecompiledSyncConfig,
12
+ SqlEventDescriptor,
13
+ SqlSyncRules,
14
+ SyncConfigWithErrors,
15
+ versionedHydrationState,
16
+ YamlError
17
+ } from '@powersync/service-sync-rules';
18
+ import * as sqlite from 'node:sqlite';
19
+ import { Logger } from 'winston';
20
+ import { SyncRuleState } from './BucketStorage.js';
21
+ import { SerializedSyncPlan, UpdateSyncRulesOptions } from './BucketStorageFactory.js';
22
+ import { ParsedSyncConfigSet } from './ParsedSyncConfigSet.js';
23
+ import { PersistedSyncConfigStatus } from './PersistedSyncConfigStatus.js';
24
+ import { STORAGE_VERSION_CONFIG, StorageVersionConfig } from './StorageVersionConfig.js';
25
+
26
+ export interface ParsePersistedSyncConfigContentOptions {
27
+ content: string;
28
+ compiledPlan: SerializedSyncPlan | null;
29
+ storageVersion: number;
30
+ parseOptions: ParseSyncConfigOptions;
31
+ }
32
+
33
+ export function parsePersistedSyncConfigContent(options: ParsePersistedSyncConfigContentOptions): SyncConfigWithErrors {
34
+ const { content, compiledPlan, storageVersion, parseOptions } = options;
35
+
36
+ if (compiledPlan == null) {
37
+ // Fallback: Only parse from YAML if no compiled plan is available.
38
+ return SqlSyncRules.fromYaml(content, parseOptions);
39
+ }
40
+
41
+ const plan = deserializeSyncPlan(compiledPlan.plan);
42
+ const compatibility = CompatibilityContext.deserialize(compiledPlan.compatibility);
43
+ const eventDefinitions: SqlEventDescriptor[] = [];
44
+ for (const [name, queries] of Object.entries(compiledPlan.eventDescriptors)) {
45
+ const descriptor = new SqlEventDescriptor(name, compatibility);
46
+ for (const query of queries) {
47
+ descriptor.addSourceQuery(query, parseOptions);
48
+ }
49
+
50
+ eventDefinitions.push(descriptor);
51
+ }
52
+
53
+ const precompiled = new PrecompiledSyncConfig(plan, compatibility, eventDefinitions, {
54
+ defaultSchema: parseOptions.defaultSchema,
55
+ sourceText: content
56
+ });
57
+
58
+ // Note: If the original content did not define a storage version, this will still set the storage version.
59
+ // This means asUpdateOptions will not change the storage version, even if the default changes.
60
+ precompiled.storageVersion = storageVersion;
61
+
62
+ const errors: YamlError[] = [];
63
+ if (compiledPlan.errors) {
64
+ for (const error of compiledPlan.errors) {
65
+ const location: ErrorLocation | undefined = error.location && {
66
+ start: error.location.start_offset,
67
+ end: error.location.end_offset
68
+ };
69
+ const asYamlError = new YamlError(new Error(error.message), location);
70
+ asYamlError.type = error.level;
71
+
72
+ errors.push(asYamlError);
73
+ }
74
+ }
75
+
76
+ return { config: precompiled, errors };
77
+ }
78
+
79
+ /**
80
+ * Immutable sync config content for one sync config inside a replication stream.
81
+ *
82
+ * This represents the persisted config content. Fetch per-config status with
83
+ * {@link getSyncConfigStatus}. Use {@link PersistedReplicationStream} for stream
84
+ * lifecycle concerns such as locking and termination.
85
+ */
86
+
87
+ export abstract class PersistedSyncConfigContent implements PersistedSyncConfigContentData {
88
+ readonly replicationStreamId: number;
89
+ readonly sync_rules_content: string;
90
+ readonly compiled_plan: SerializedSyncPlan | null;
91
+ readonly replicationStreamName: string;
92
+ readonly storageVersion: number;
93
+ readonly logger: Logger;
94
+ readonly syncConfigId: PersistedSyncConfigId | null;
95
+ readonly syncConfigState: SyncRuleState;
96
+
97
+ constructor(data: PersistedSyncConfigContentData) {
98
+ this.replicationStreamId = data.replicationStreamId;
99
+ this.sync_rules_content = data.sync_rules_content;
100
+ this.compiled_plan = data.compiled_plan;
101
+ this.replicationStreamName = data.replicationStreamName;
102
+ this.storageVersion = data.storageVersion;
103
+ this.syncConfigId = data.syncConfigId ?? null;
104
+ this.syncConfigState = data.syncConfigState;
105
+ this.logger = defaultLogger.child({ prefix: `[${this.replicationStreamName}] ` });
106
+ }
107
+
108
+ /**
109
+ * Load the storage config.
110
+ *
111
+ * This may throw if the persisted storage version is not supported.
112
+ */
113
+ getStorageConfig(): StorageVersionConfig {
114
+ const storageConfig = STORAGE_VERSION_CONFIG[this.storageVersion];
115
+ if (storageConfig == null) {
116
+ throw new ServiceError(
117
+ ErrorCode.PSYNC_S1005,
118
+ `Unsupported storage version ${this.storageVersion} for replication stream ${this.replicationStreamId}`
119
+ );
120
+ }
121
+ return storageConfig;
122
+ }
123
+
124
+ /**
125
+ * Parse only this config's content into a single {@link SyncConfigWithErrors}.
126
+ *
127
+ * This does not depend on any other configs in the same replication stream.
128
+ */
129
+ protected parseSingleConfig(options: ParseSyncConfigOptions): SyncConfigWithErrors {
130
+ return parsePersistedSyncConfigContent({
131
+ content: this.sync_rules_content,
132
+ compiledPlan: this.compiled_plan,
133
+ storageVersion: this.storageVersion,
134
+ parseOptions: options
135
+ });
136
+ }
137
+
138
+ parsed(options: ParseSyncConfigOptions): ParsedSyncConfigSet {
139
+ let hydrationState: HydrationState;
140
+ const config = this.parseSingleConfig(options);
141
+
142
+ const storageConfig = this.getStorageConfig();
143
+ if (
144
+ storageConfig.versionedBuckets ||
145
+ config.config.compatibility.isEnabled(CompatibilityOption.versionedBucketIds)
146
+ ) {
147
+ hydrationState = versionedHydrationState(this.replicationStreamId);
148
+ } else {
149
+ hydrationState = DEFAULT_HYDRATION_STATE;
150
+ }
151
+
152
+ let hydrated: HydratedSyncConfig | undefined;
153
+ return {
154
+ replicationStreamId: this.replicationStreamId,
155
+ replicationStreamName: this.replicationStreamName,
156
+ syncConfigs: [config],
157
+ hydrationState,
158
+ get hydratedSyncConfig(): HydratedSyncConfig {
159
+ hydrated ??= config.config.hydrate({ hydrationState, sqlite: nodeSqlite(sqlite) });
160
+ return hydrated;
161
+ }
162
+ };
163
+ }
164
+
165
+ asUpdateOptions(options?: Omit<UpdateSyncRulesOptions, 'config'>): UpdateSyncRulesOptions {
166
+ // defaultSchema is not relevant for the parsed version here
167
+ const parsed = this.parseSingleConfig({ defaultSchema: 'not_applicable' });
168
+ return {
169
+ config: { yaml: this.sync_rules_content, plan: this.compiled_plan, parsed },
170
+ ...options
171
+ };
172
+ }
173
+
174
+ /**
175
+ * Fetch the current persisted state for this exact sync config.
176
+ */
177
+ abstract getSyncConfigStatus(): Promise<PersistedSyncConfigStatus | null>;
178
+ }
179
+ export interface PersistedSyncConfigContentData {
180
+ readonly replicationStreamId: number;
181
+ readonly sync_rules_content: string;
182
+ readonly compiled_plan: SerializedSyncPlan | null;
183
+ readonly replicationStreamName: string;
184
+ readonly storageVersion: number;
185
+
186
+ readonly syncConfigId?: PersistedSyncConfigId | null;
187
+ readonly syncConfigState: SyncRuleState;
188
+ }
189
+ export type PersistedSyncConfigId = string;
190
+ export interface ParseSyncConfigOptions {
191
+ defaultSchema: string;
192
+ }
@@ -0,0 +1,14 @@
1
+ import { SyncRuleState } from './BucketStorage.js';
2
+ import { PersistedSyncConfigId } from './PersistedSyncConfigContent.js';
3
+
4
+ export interface PersistedSyncConfigStatus {
5
+ readonly id: PersistedSyncConfigId;
6
+ readonly replicationStreamId: number;
7
+ readonly state: SyncRuleState;
8
+ readonly snapshot_done?: boolean;
9
+ readonly last_checkpoint_lsn: string | null;
10
+ readonly last_fatal_error?: string | null;
11
+ readonly last_fatal_error_ts?: Date | null;
12
+ readonly last_keepalive_ts?: Date | null;
13
+ readonly last_checkpoint_ts?: Date | null;
14
+ }
@@ -25,4 +25,10 @@ export interface SourceEntityDescriptor extends SourceTableRef {
25
25
  * The columns that are used to uniquely identify a record in the source entity.
26
26
  */
27
27
  replicaIdColumns: ColumnDescriptor[];
28
+ /**
29
+ * Whether the source always sends complete row data with each operation (e.g. Postgres REPLICA
30
+ * IDENTITY FULL). When true, no current_data copy is needed. Undefined means the source does not
31
+ * report this, in which case we default to keeping a copy.
32
+ */
33
+ sendsCompleteRows?: boolean;
28
34
  }
@@ -1,6 +1,8 @@
1
1
  import {
2
2
  BucketDataSource,
3
+ BucketDefinitionId,
3
4
  DEFAULT_TAG,
5
+ ParameterIndexId,
4
6
  ParameterIndexLookupCreator,
5
7
  SourceTableRef
6
8
  } from '@powersync/service-sync-rules';
@@ -21,6 +23,8 @@ export interface SourceTableOptions {
21
23
  snapshotComplete: boolean;
22
24
  bucketDataSources: BucketDataSource[];
23
25
  parameterLookupSources: ParameterIndexLookupCreator[];
26
+ bucketDataSourceIds?: Set<BucketDefinitionId>;
27
+ parameterLookupSourceIds?: Set<ParameterIndexId>;
24
28
  }
25
29
 
26
30
  export interface TableSnapshotStatus {
@@ -57,14 +61,29 @@ export class SourceTable {
57
61
  public syncParameters = true;
58
62
 
59
63
  /**
60
- * True if the table is used in sync config for events.
64
+ * True if this table should fire events for row changes.
61
65
  *
62
- * This value is resolved externally, and cached here.
66
+ * This value is resolved externally, and cached here. When multiple SourceTables exist
67
+ * for the same SourceTableRef (v3 storage), resolveTables designates exactly one of them
68
+ * as the event carrier, so that a row change saved once per table fires each event once.
63
69
  *
64
70
  * Defaults to true for tests.
65
71
  */
66
72
  public syncEvent = true;
67
73
 
74
+ /**
75
+ * True if raw data should be stored in current_data collection.
76
+ *
77
+ * This is needed when the source sends partial row data (e.g. TOAST values).
78
+ * When REPLICA IDENTITY FULL is configured, complete rows are always sent,
79
+ * so we don't need to store raw data.
80
+ *
81
+ * This value is resolved externally based on table configuration.
82
+ *
83
+ * Defaults to true for tests (conservative approach).
84
+ */
85
+ public storeCurrentData = true;
86
+
68
87
  /**
69
88
  * Always undefined if snapshotComplete = true.
70
89
  *
@@ -109,6 +128,14 @@ export class SourceTable {
109
128
  return this.options.parameterLookupSources;
110
129
  }
111
130
 
131
+ get bucketDataSourceIds() {
132
+ return this.options.bucketDataSourceIds;
133
+ }
134
+
135
+ get parameterLookupSourceIds() {
136
+ return this.options.parameterLookupSourceIds;
137
+ }
138
+
112
139
  /**
113
140
  * Sanitized name of the entity in the format of "{schema}.{entity name}".
114
141
  * Suitable for safe use in Postgres queries.
@@ -132,11 +159,15 @@ export class SourceTable {
132
159
  replicaIdColumns: this.replicaIdColumns,
133
160
  snapshotComplete: this.snapshotComplete,
134
161
  bucketDataSources: this.bucketDataSources,
135
- parameterLookupSources: this.parameterLookupSources
162
+ parameterLookupSources: this.parameterLookupSources,
163
+ bucketDataSourceIds: this.bucketDataSourceIds == null ? undefined : new Set(this.bucketDataSourceIds),
164
+ parameterLookupSourceIds:
165
+ this.parameterLookupSourceIds == null ? undefined : new Set(this.parameterLookupSourceIds)
136
166
  });
137
167
  copy.syncData = this.syncData;
138
168
  copy.syncParameters = this.syncParameters;
139
169
  copy.syncEvent = this.syncEvent;
170
+ copy.storeCurrentData = this.storeCurrentData;
140
171
  copy.snapshotStatus = this.snapshotStatus;
141
172
  return copy;
142
173
  }