@powersync/service-core 0.0.0-dev-20260602073133 → 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,27 +1,92 @@
1
- import { BasicRouterRequest, Context, JwtPayload } from '@/index.js';
1
+ import { BasicRouterRequest, Context, JwtPayload, ParsedSyncConfigSet, storage } from '@/index.js';
2
2
  import { logger } from '@powersync/lib-services-framework';
3
- import { describe, expect, it } from 'vitest';
4
- import { validate } from '../../../src/routes/endpoints/admin.js';
3
+ import { SqlSyncRules } from '@powersync/service-sync-rules';
4
+ import { describe, expect, it, vi } from 'vitest';
5
+ import { diagnostics, reprocess, validate } from '../../../src/routes/endpoints/admin.js';
5
6
  import { mockServiceContext } from './mocks.js';
6
7
 
7
8
  describe('admin routes', () => {
9
+ const request: BasicRouterRequest = {
10
+ headers: {},
11
+ hostname: '',
12
+ protocol: 'http'
13
+ };
14
+
15
+ function makeContext(activeBucketStorage?: any): Context {
16
+ const service_context = mockServiceContext(null);
17
+ if (activeBucketStorage != null) {
18
+ (service_context.storageEngine as any).activeBucketStorage = activeBucketStorage;
19
+ }
20
+
21
+ return {
22
+ logger: logger,
23
+ service_context,
24
+ token_payload: new JwtPayload({
25
+ sub: '',
26
+ exp: 0,
27
+ iat: 0
28
+ })
29
+ };
30
+ }
31
+
32
+ function makeSyncConfigContent(options: {
33
+ id?: number;
34
+ syncConfigId?: string;
35
+ active?: boolean;
36
+ content?: string;
37
+ }): storage.PersistedSyncConfigContent {
38
+ const id = options.id ?? 1;
39
+ const syncConfigId = options.syncConfigId ?? String(id);
40
+ const active = options.active ?? true;
41
+ const state = active ? storage.SyncRuleState.ACTIVE : storage.SyncRuleState.PROCESSING;
42
+ const lastKeepaliveTs = new Date('2026-01-01T00:00:00.000Z');
43
+ const lastCheckpointTs = new Date('2026-01-01T00:00:00.000Z');
44
+ const syncConfigStatus = {
45
+ id: syncConfigId,
46
+ replicationStreamId: id,
47
+ state,
48
+ last_checkpoint_lsn: null,
49
+ last_fatal_error: null,
50
+ last_fatal_error_ts: null,
51
+ last_keepalive_ts: lastKeepaliveTs,
52
+ last_checkpoint_ts: lastCheckpointTs
53
+ };
54
+ const content = {
55
+ replicationStreamId: id,
56
+ syncConfigId,
57
+ replicationStreamName: `slot_${id}`,
58
+ sync_rules_content:
59
+ options.content ??
60
+ `
61
+ bucket_definitions:
62
+ global:
63
+ data:
64
+ - SELECT id FROM test
65
+ `,
66
+ compiled_plan: null,
67
+ storageVersion: storage.LEGACY_STORAGE_VERSION,
68
+ syncConfigState: syncConfigStatus.state,
69
+ parsed(options?: any) {
70
+ const syncRules = SqlSyncRules.fromYaml(content.sync_rules_content, {
71
+ ...options,
72
+ defaultSchema: 'public'
73
+ });
74
+ return {
75
+ syncConfigs: [syncRules]
76
+ } as ParsedSyncConfigSet;
77
+ },
78
+ asUpdateOptions: vi.fn(),
79
+ getStorageConfig: vi.fn(),
80
+ async getSyncConfigStatus() {
81
+ return syncConfigStatus;
82
+ }
83
+ };
84
+ return content as unknown as storage.PersistedSyncConfigContent;
85
+ }
86
+
8
87
  describe('validate', () => {
9
88
  it('reports errors with source location', async () => {
10
- const context: Context = {
11
- logger: logger,
12
- service_context: mockServiceContext(null),
13
- token_payload: new JwtPayload({
14
- sub: '',
15
- exp: 0,
16
- iat: 0
17
- })
18
- };
19
-
20
- const request: BasicRouterRequest = {
21
- headers: {},
22
- hostname: '',
23
- protocol: 'http'
24
- };
89
+ const context = makeContext();
25
90
 
26
91
  const response = await validate.handler({
27
92
  context,
@@ -45,4 +110,103 @@ bucket_definitions:
45
110
  ]);
46
111
  });
47
112
  });
113
+
114
+ describe('diagnostics', () => {
115
+ it('returns deploying config status', async () => {
116
+ const active = makeSyncConfigContent({ id: 1, syncConfigId: 'active-config' });
117
+ const deploying = makeSyncConfigContent({ id: 2, syncConfigId: 'deploying-config', active: false });
118
+ const getInstance = vi.fn(() => ({
119
+ async getStatus() {
120
+ return {
121
+ snapshotDone: false,
122
+ resumeLsn: null
123
+ };
124
+ }
125
+ }));
126
+ const activeBucketStorage = {
127
+ getActiveSyncConfig: vi.fn(async () => ({
128
+ content: active,
129
+ replicationStream: {},
130
+ storage: getInstance()
131
+ })),
132
+ getDeployingSyncConfig: vi.fn(async () => ({
133
+ content: deploying,
134
+ replicationStream: {},
135
+ storage: getInstance()
136
+ }))
137
+ };
138
+
139
+ const response = await diagnostics.handler({
140
+ context: makeContext(activeBucketStorage),
141
+ params: {},
142
+ request
143
+ });
144
+
145
+ expect(response.deploying_sync_rules?.connections[0].slot_name).toBe('slot_2');
146
+ expect(response.active_sync_rules?.connections[0].slot_name).toBe('slot_1');
147
+ });
148
+ });
149
+
150
+ describe('reprocess', () => {
151
+ it('reprocesses the active sync config', async () => {
152
+ const active = makeSyncConfigContent({ id: 7, syncConfigId: 'active-config' });
153
+ const updateSyncRules = vi.fn(async () => ({
154
+ replicationStreamId: 8,
155
+ replicationStreamName: 'new_slot',
156
+ state: storage.SyncRuleState.PROCESSING,
157
+ storageVersion: storage.LEGACY_STORAGE_VERSION,
158
+ replicationJobId: '8',
159
+ current_lock: null
160
+ }));
161
+ const activeBucketStorage = {
162
+ getDeployingSyncConfig: vi.fn(async () => null),
163
+ getActiveSyncConfig: vi.fn(async () => ({
164
+ content: active,
165
+ replicationStream: {},
166
+ storage: {}
167
+ })),
168
+ getSyncConfigContent: vi.fn(),
169
+ updateSyncRules
170
+ };
171
+
172
+ const response = await reprocess.handler({
173
+ context: makeContext(activeBucketStorage),
174
+ params: {},
175
+ request
176
+ });
177
+
178
+ expect(activeBucketStorage.getActiveSyncConfig).toHaveBeenCalledTimes(1);
179
+ expect(activeBucketStorage.getSyncConfigContent).not.toHaveBeenCalled();
180
+ expect(updateSyncRules).toHaveBeenCalledTimes(1);
181
+ expect(response.connections[0].slot_name).toBe('new_slot');
182
+ });
183
+
184
+ it('rejects reprocess while a sync config is deploying', async () => {
185
+ const activeBucketStorage = {
186
+ getDeployingSyncConfig: vi.fn(async () => ({
187
+ content: makeSyncConfigContent({ id: 2, active: false }),
188
+ replicationStream: {},
189
+ storage: {}
190
+ })),
191
+ getActiveSyncConfig: vi.fn(),
192
+ updateSyncRules: vi.fn()
193
+ };
194
+
195
+ await expect(
196
+ reprocess.handler({
197
+ context: makeContext(activeBucketStorage),
198
+ params: {},
199
+ request
200
+ })
201
+ ).rejects.toMatchObject({
202
+ errorData: {
203
+ status: 409,
204
+ code: 'PSYNC_S4106',
205
+ description: 'Busy processing sync config - cannot reprocess'
206
+ }
207
+ });
208
+ expect(activeBucketStorage.getActiveSyncConfig).not.toHaveBeenCalled();
209
+ expect(activeBucketStorage.updateSyncRules).not.toHaveBeenCalled();
210
+ });
211
+ });
48
212
  });
@@ -0,0 +1,54 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { CheckpointRequestPayload, checkpointRequest } from '../../../src/routes/endpoints/checkpointing.js';
3
+
4
+ describe('checkpoint request route', () => {
5
+ const payload = (checkpointRequestId: string | number | bigint) => ({
6
+ client_id: 'client-a',
7
+ checkpoint_request_id: checkpointRequestId
8
+ });
9
+
10
+ it.each([
11
+ ['safe JSON number', 1, 1n],
12
+ ['max int64 string', '9223372036854775807', 9_223_372_036_854_775_807n],
13
+ ['bigint value', 42n, 42n]
14
+ ])('decodes a positive int64 checkpoint request id from a %s', (_description, checkpointRequestId, expected) => {
15
+ expect(CheckpointRequestPayload.decode(payload(checkpointRequestId)).checkpoint_request_id).toEqual(expected);
16
+ });
17
+
18
+ it.each([1, '9223372036854775807'])(
19
+ 'accepts API payloads with positive int64 checkpoint request id %s',
20
+ (checkpointRequestId) => {
21
+ expect(checkpointRequest.validator!.validate(payload(checkpointRequestId)).valid).toBe(true);
22
+ }
23
+ );
24
+
25
+ it.each([
26
+ 0,
27
+ -1,
28
+ '0',
29
+ '-1',
30
+ '9223372036854775808',
31
+ '999999999999999999999999999999999999999999999',
32
+ Number.MAX_SAFE_INTEGER + 1
33
+ ])('rejects invalid API checkpoint request id %s', (checkpointRequestId) => {
34
+ expect(checkpointRequest.validator!.validate(payload(checkpointRequestId)).valid).toBe(false);
35
+ });
36
+
37
+ it('returns the stored checkpoint request id from the checkpoint request route', async () => {
38
+ const writeCheckpointBatcher = {
39
+ enqueue: vi.fn(async () => ({ replicationHead: 'head-1', writeCheckpoint: '43' }))
40
+ };
41
+
42
+ await expect(
43
+ checkpointRequest.handler({
44
+ context: {
45
+ token_payload: { userIdString: 'user-a' },
46
+ service_context: { writeCheckpointBatcher }
47
+ },
48
+ params: payload(42)
49
+ } as any)
50
+ ).resolves.toEqual({ checkpoint_request_id: '43' });
51
+
52
+ expect(writeCheckpointBatcher.enqueue).toHaveBeenCalledWith('user-a/client-a', 42n);
53
+ });
54
+ });
@@ -18,8 +18,12 @@ export function mockServiceContext(storage: Partial<SyncRulesBucketStorage> | nu
18
18
 
19
19
  const storageEngine: StorageEngine = {
20
20
  activeBucketStorage: {
21
- async getActiveStorage() {
22
- return storage;
21
+ async getActiveSyncConfig() {
22
+ return storage == null
23
+ ? null
24
+ : {
25
+ storage
26
+ };
23
27
  }
24
28
  } as Partial<BucketStorageFactory>
25
29
  } as any;
@@ -0,0 +1,89 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import * as storage from '../../../src/storage/storage-index.js';
3
+
4
+ /**
5
+ * Build a SourceTable with the current `ref`-based options shape.
6
+ * Data/parameter sources are not relevant to the storeCurrentData behaviour, so they default to empty.
7
+ */
8
+ function makeTable(options: Partial<storage.SourceTableOptions> = {}): storage.SourceTable {
9
+ return new storage.SourceTable({
10
+ id: 'test-id',
11
+ ref: { connectionTag: 'test', schema: 'public', name: 'test_table' },
12
+ objectId: 123,
13
+ replicaIdColumns: [{ name: 'id' }],
14
+ snapshotComplete: true,
15
+ bucketDataSources: [],
16
+ parameterLookupSources: [],
17
+ ...options
18
+ });
19
+ }
20
+
21
+ describe('SourceTable', () => {
22
+ describe('storeCurrentData property', () => {
23
+ test('defaults to true', () => {
24
+ const table = makeTable();
25
+ expect(table.storeCurrentData).toBe(true);
26
+ });
27
+
28
+ test('can be set to false', () => {
29
+ const table = makeTable();
30
+ table.storeCurrentData = false;
31
+ expect(table.storeCurrentData).toBe(false);
32
+ });
33
+
34
+ test('is preserved when cloning', () => {
35
+ const table = makeTable();
36
+ table.storeCurrentData = false;
37
+ const cloned = table.clone();
38
+
39
+ expect(cloned.storeCurrentData).toBe(false);
40
+ expect(cloned).not.toBe(table);
41
+ });
42
+
43
+ test('clone preserves all properties including storeCurrentData', () => {
44
+ const table = makeTable({
45
+ replicaIdColumns: [{ name: 'id', type: 'int4' }],
46
+ snapshotComplete: false
47
+ });
48
+
49
+ table.syncData = false;
50
+ table.syncParameters = false;
51
+ table.syncEvent = false;
52
+ table.storeCurrentData = false;
53
+ table.snapshotStatus = {
54
+ totalEstimatedCount: 100,
55
+ replicatedCount: 50,
56
+ lastKey: Buffer.from('test')
57
+ };
58
+
59
+ const cloned = table.clone();
60
+
61
+ expect(cloned.syncData).toBe(false);
62
+ expect(cloned.syncParameters).toBe(false);
63
+ expect(cloned.syncEvent).toBe(false);
64
+ expect(cloned.storeCurrentData).toBe(false);
65
+ expect(cloned.snapshotStatus).toEqual(table.snapshotStatus);
66
+ });
67
+ });
68
+
69
+ describe('integration with other properties', () => {
70
+ test('storeCurrentData does not affect syncAny', () => {
71
+ const table = makeTable();
72
+
73
+ table.storeCurrentData = false;
74
+ table.syncData = true;
75
+ table.syncParameters = false;
76
+ table.syncEvent = false;
77
+
78
+ expect(table.syncAny).toBe(true); // Should still be true
79
+ });
80
+
81
+ test('storeCurrentData is independent of snapshot status', () => {
82
+ const table = makeTable({ snapshotComplete: false });
83
+
84
+ table.storeCurrentData = false;
85
+ expect(table.snapshotComplete).toBe(false);
86
+ expect(table.storeCurrentData).toBe(false);
87
+ });
88
+ });
89
+ });
@@ -137,6 +137,7 @@ bucket_definitions:
137
137
  priority: 3
138
138
  }
139
139
  ]);
140
+ expect(line.bucketDataRequestHint).toEqual('bulk');
140
141
  // This is the bucket data to be fetched
141
142
  expect(bucketStarts(line.getFilteredBucketPositions())).toEqual(new Map([['1#global[]', 0n]]));
142
143
 
@@ -170,6 +171,45 @@ bucket_definitions:
170
171
  }
171
172
  });
172
173
  expect(bucketStarts(line2.getFilteredBucketPositions())).toEqual(new Map([['1#global[]', 1n]]));
174
+ expect(line2.bucketDataRequestHint).toEqual('incremental');
175
+ });
176
+
177
+ test('unfinished bulk bucket does not make checkpoint diff bulk', async () => {
178
+ const storage = new MockBucketChecksumStateStorage();
179
+ storage.updateTestChecksum({ bucket: '1#global[]', checksum: 1, count: 1 });
180
+
181
+ const state = new BucketChecksumState({
182
+ syncContext,
183
+ syncRequest,
184
+ tokenPayload,
185
+ syncRules: SYNC_RULES_GLOBAL,
186
+ bucketStorage: storage
187
+ });
188
+
189
+ const line = (await state.buildNextCheckpointLine({
190
+ base: storage.makeCheckpoint(1n),
191
+ writeCheckpoint: null,
192
+ update: CHECKPOINT_INVALIDATE_ALL
193
+ }))!;
194
+ line.advance();
195
+ line.updateBucketPosition({ bucket: '1#global[]', nextAfter: 1n, hasMore: true });
196
+
197
+ storage.updateTestChecksum({ bucket: '1#global[]', checksum: 2, count: 2 });
198
+
199
+ const line2 = (await state.buildNextCheckpointLine({
200
+ base: storage.makeCheckpoint(2n),
201
+ writeCheckpoint: null,
202
+ update: {
203
+ updatedDataBuckets: new Set(['1#global[]']),
204
+ invalidateDataBuckets: false,
205
+ updatedParameterLookups: new Set(),
206
+ invalidateParameterBuckets: false
207
+ }
208
+ }))!;
209
+ line2.advance();
210
+
211
+ expect(line2.bucketDataRequestHint).toEqual('incremental');
212
+ expect(bucketStarts(line2.getFilteredBucketPositions())).toEqual(new Map([['1#global[]', 1n]]));
173
213
  });
174
214
 
175
215
  test('global bucket with initial state', async () => {
@@ -1143,7 +1183,7 @@ streams:
1143
1183
  ).rejects.toThrow('Too many buckets: 60 (limit of 50');
1144
1184
 
1145
1185
  // Verify error log includes breakdown
1146
- expect(errorMessages[0]).toContain('Buckets by definition:');
1186
+ expect(errorMessages[0]).toContain('(limit of 50)\nBuckets by sync stream:');
1147
1187
  expect(errorMessages[0]).toContain('projects: 30');
1148
1188
  expect(errorMessages[0]).toContain('tasks: 20');
1149
1189
  expect(errorMessages[0]).toContain('comments: 10');
@@ -1157,15 +1197,60 @@ streams:
1157
1197
  });
1158
1198
  });
1159
1199
 
1160
- test('limits bucket breakdown to top 10 definitions', async () => {
1161
- // Create sync streams with 15 different definitions with dynamic parameters
1200
+ test('labels the bucket breakdown as bucket definitions for legacy sync rules', async () => {
1201
+ const legacySyncRules = SqlSyncRules.fromYaml(
1202
+ `
1203
+ bucket_definitions:
1204
+ projects:
1205
+ parameters: SELECT id FROM projects WHERE user_id = request.user_id()
1206
+ data: []
1207
+ `,
1208
+ { defaultSchema: 'public' }
1209
+ ).config.hydrate({ hydrationState: versionedHydrationState(5), sqlite: nodeSqlite(sqlite) });
1210
+
1211
+ const storage = new MockBucketChecksumStateStorage();
1212
+ const errorMessages: string[] = [];
1213
+ const state = new BucketChecksumState({
1214
+ syncContext: new SyncContext({
1215
+ maxBuckets: 50,
1216
+ maxParameterQueryResults: 100,
1217
+ maxDataFetchConcurrency: 10
1218
+ }),
1219
+ tokenPayload: new JwtPayload({ sub: 'u1' }),
1220
+ syncRequest,
1221
+ syncRules: legacySyncRules,
1222
+ bucketStorage: storage,
1223
+ logger: {
1224
+ info: () => {},
1225
+ error: (message: string) => errorMessages.push(message),
1226
+ warn: () => {},
1227
+ debug: () => {}
1228
+ } as any
1229
+ });
1230
+
1231
+ await expect(
1232
+ state.buildNextCheckpointLine({
1233
+ base: storage.makeCheckpoint(1n, (lookups) => [
1234
+ { lookup: lookups[0], rows: Array.from({ length: 60 }, (_, id) => ({ id })) }
1235
+ ]),
1236
+ writeCheckpoint: null,
1237
+ update: CHECKPOINT_INVALIDATE_ALL
1238
+ })
1239
+ ).rejects.toThrow('Too many buckets: 60 (limit of 50)');
1240
+
1241
+ expect(errorMessages[0]).toContain('(limit of 50)\nBuckets by bucket definition:');
1242
+ expect(errorMessages[0]).toContain('projects: 60');
1243
+ });
1244
+
1245
+ test('limits bucket breakdown to top 100 sync streams', async () => {
1246
+ // Create 105 sync streams with dynamic parameters.
1162
1247
  let yamlDefinitions = `
1163
1248
  config:
1164
1249
  edition: 3
1165
1250
 
1166
1251
  streams:
1167
1252
  `;
1168
- for (let i = 1; i <= 15; i++) {
1253
+ for (let i = 1; i <= 105; i++) {
1169
1254
  yamlDefinitions += ` def${i}:\n`;
1170
1255
  yamlDefinitions += ` auto_subscribe: true\n`;
1171
1256
  yamlDefinitions += ` query: SELECT * FROM tbl WHERE b = auth.parameter('${i}')\n`;
@@ -1189,7 +1274,7 @@ streams:
1189
1274
  };
1190
1275
 
1191
1276
  const smallContext = new SyncContext({
1192
- maxBuckets: 10,
1277
+ maxBuckets: 100,
1193
1278
  maxParameterQueryResults: 10,
1194
1279
  maxDataFetchConcurrency: 10
1195
1280
  });
@@ -1198,7 +1283,7 @@ streams:
1198
1283
  syncContext: smallContext,
1199
1284
  tokenPayload: new JwtPayload({
1200
1285
  sub: 'u1',
1201
- ...Object.fromEntries(Array.from({ length: 30 }, (_, i) => [i.toString(), BigInt(i)]))
1286
+ ...Object.fromEntries(Array.from({ length: 106 }, (_, i) => [i.toString(), BigInt(i)]))
1202
1287
  }),
1203
1288
  syncRequest,
1204
1289
  syncRules: SYNC_RULES_MANY,
@@ -1212,15 +1297,16 @@ streams:
1212
1297
  writeCheckpoint: null,
1213
1298
  update: CHECKPOINT_INVALIDATE_ALL
1214
1299
  })
1215
- ).rejects.toThrow('Too many buckets: 15 (limit of 10)');
1300
+ ).rejects.toThrow('Too many buckets: 105 (limit of 100)');
1216
1301
 
1217
- // Verify only top 10 are shown
1302
+ // Verify only the first 100 are shown.
1218
1303
  const errorMessage = errorMessages[0];
1219
- expect(errorMessage).toContain('... and 5 more results from 5 definitions');
1304
+ expect(errorMessage).toContain('Buckets by sync stream:');
1305
+ expect(errorMessage).toContain('... and 5 more buckets from 5 sync streams');
1220
1306
 
1221
- // Count how many definitions are listed (should be exactly 10)
1307
+ // Count how many sync streams are listed (should be exactly 100).
1222
1308
  const defMatches = errorMessage.match(/def\d+:/g);
1223
- expect(defMatches?.length).toBe(10);
1309
+ expect(defMatches?.length).toBe(100);
1224
1310
  });
1225
1311
  });
1226
1312
  });
@@ -1240,7 +1326,7 @@ class MockBucketChecksumStateStorage implements BucketChecksumStateStorage {
1240
1326
  this.filter?.({ invalidate: true });
1241
1327
  }
1242
1328
 
1243
- async getChecksums(_checkpoint: InternalOpId, buckets: { bucket: string }[]): Promise<ChecksumMap> {
1329
+ async getChecksums(_checkpoint: ReplicationCheckpoint, buckets: { bucket: string }[]): Promise<ChecksumMap> {
1244
1330
  return new Map<string, BucketChecksum>(
1245
1331
  buckets.map(({ bucket }) => {
1246
1332
  const checksum = this.state.get(bucket);
@@ -1,7 +1,19 @@
1
- import { acquireSemaphoreAbortable } from '@/index.js';
1
+ import { acquireSemaphoreAbortable, isAbortError } from '@/index.js';
2
2
  import { Semaphore, SemaphoreInterface } from 'async-mutex';
3
+ import { AbortError } from 'ix/aborterror.js';
3
4
  import { describe, expect, test, vi } from 'vitest';
4
5
 
6
+ describe('isAbortError', () => {
7
+ test('recognizes ix and native abort errors', () => {
8
+ const controller = new AbortController();
9
+ controller.abort();
10
+
11
+ expect(isAbortError(new AbortError())).toBe(true);
12
+ expect(isAbortError(controller.signal.reason)).toBe(true);
13
+ expect(isAbortError(new Error('not aborted'))).toBe(false);
14
+ });
15
+ });
16
+
5
17
  describe('acquireSemaphoreAbortable', () => {
6
18
  test('can acquire', async () => {
7
19
  const semaphore = new Semaphore(1);