@powersync/service-core-tests 0.0.0-dev-20260225160713 → 0.0.0-dev-20260511080634

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 (55) hide show
  1. package/CHANGELOG.md +95 -3
  2. package/dist/test-utils/MetricsHelper.js +1 -1
  3. package/dist/test-utils/MetricsHelper.js.map +1 -1
  4. package/dist/test-utils/StorageDataHelpers.d.ts +8 -0
  5. package/dist/test-utils/StorageDataHelpers.js +33 -0
  6. package/dist/test-utils/StorageDataHelpers.js.map +1 -0
  7. package/dist/test-utils/general-utils.d.ts +22 -3
  8. package/dist/test-utils/general-utils.js +56 -3
  9. package/dist/test-utils/general-utils.js.map +1 -1
  10. package/dist/test-utils/stream_utils.js +2 -2
  11. package/dist/test-utils/stream_utils.js.map +1 -1
  12. package/dist/test-utils/test-utils-index.d.ts +1 -0
  13. package/dist/test-utils/test-utils-index.js +1 -0
  14. package/dist/test-utils/test-utils-index.js.map +1 -1
  15. package/dist/tests/register-compacting-tests.d.ts +1 -1
  16. package/dist/tests/register-compacting-tests.js +514 -587
  17. package/dist/tests/register-compacting-tests.js.map +1 -1
  18. package/dist/tests/register-data-storage-checkpoint-tests.d.ts +1 -1
  19. package/dist/tests/register-data-storage-checkpoint-tests.js +200 -301
  20. package/dist/tests/register-data-storage-checkpoint-tests.js.map +1 -1
  21. package/dist/tests/register-data-storage-data-tests.d.ts +2 -2
  22. package/dist/tests/register-data-storage-data-tests.js +1220 -1041
  23. package/dist/tests/register-data-storage-data-tests.js.map +1 -1
  24. package/dist/tests/register-data-storage-parameter-tests.d.ts +1 -1
  25. package/dist/tests/register-data-storage-parameter-tests.js +681 -632
  26. package/dist/tests/register-data-storage-parameter-tests.js.map +1 -1
  27. package/dist/tests/register-migration-tests.js +63 -139
  28. package/dist/tests/register-migration-tests.js.map +1 -1
  29. package/dist/tests/register-parameter-compacting-tests.d.ts +1 -1
  30. package/dist/tests/register-parameter-compacting-tests.js +121 -201
  31. package/dist/tests/register-parameter-compacting-tests.js.map +1 -1
  32. package/dist/tests/register-sync-tests.d.ts +2 -1
  33. package/dist/tests/register-sync-tests.js +974 -1136
  34. package/dist/tests/register-sync-tests.js.map +1 -1
  35. package/dist/tests/tests-index.d.ts +4 -4
  36. package/dist/tests/tests-index.js +4 -4
  37. package/dist/tests/tests-index.js.map +1 -1
  38. package/dist/tests/util.d.ts +5 -4
  39. package/dist/tests/util.js +27 -12
  40. package/dist/tests/util.js.map +1 -1
  41. package/package.json +6 -6
  42. package/src/test-utils/MetricsHelper.ts +1 -1
  43. package/src/test-utils/StorageDataHelpers.ts +44 -0
  44. package/src/test-utils/general-utils.ts +81 -4
  45. package/src/test-utils/stream_utils.ts +2 -2
  46. package/src/test-utils/test-utils-index.ts +1 -0
  47. package/src/tests/register-compacting-tests.ts +376 -322
  48. package/src/tests/register-data-storage-checkpoint-tests.ts +85 -53
  49. package/src/tests/register-data-storage-data-tests.ts +1076 -563
  50. package/src/tests/register-data-storage-parameter-tests.ts +631 -327
  51. package/src/tests/register-parameter-compacting-tests.ts +92 -96
  52. package/src/tests/register-sync-tests.ts +463 -379
  53. package/src/tests/tests-index.ts +4 -4
  54. package/src/tests/util.ts +46 -17
  55. package/tsconfig.tsbuildinfo +1 -1
@@ -1,55 +1,3 @@
1
- var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
2
- if (value !== null && value !== void 0) {
3
- if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
- var dispose, inner;
5
- if (async) {
6
- if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
- dispose = value[Symbol.asyncDispose];
8
- }
9
- if (dispose === void 0) {
10
- if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
- dispose = value[Symbol.dispose];
12
- if (async) inner = dispose;
13
- }
14
- if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
- if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
16
- env.stack.push({ value: value, dispose: dispose, async: async });
17
- }
18
- else if (async) {
19
- env.stack.push({ async: true });
20
- }
21
- return value;
22
- };
23
- var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
24
- return function (env) {
25
- function fail(e) {
26
- env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
27
- env.hasError = true;
28
- }
29
- var r, s = 0;
30
- function next() {
31
- while (r = env.stack.pop()) {
32
- try {
33
- if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
34
- if (r.dispose) {
35
- var result = r.dispose.call(r.value);
36
- if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
37
- }
38
- else s |= 1;
39
- }
40
- catch (e) {
41
- fail(e);
42
- }
43
- }
44
- if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
45
- if (env.hasError) throw env.error;
46
- }
47
- return next();
48
- };
49
- })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
50
- var e = new Error(message);
51
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
- });
53
1
  import { createCoreAPIMetrics, JwtPayload, storage, sync, updateSyncRulesFromYaml } from '@powersync/service-core';
54
2
  import { JSONBig } from '@powersync/service-jsonbig';
55
3
  import path from 'path';
@@ -57,11 +5,9 @@ import * as timers from 'timers/promises';
57
5
  import { fileURLToPath } from 'url';
58
6
  import { expect, test } from 'vitest';
59
7
  import * as test_utils from '../test-utils/test-utils-index.js';
60
- import { METRICS_HELPER } from '../test-utils/test-utils-index.js';
61
- import { bucketRequest } from './util.js';
8
+ import { bucketRequest, METRICS_HELPER } from '../test-utils/test-utils-index.js';
62
9
  const __filename = fileURLToPath(import.meta.url);
63
10
  const __dirname = path.dirname(__filename);
64
- const TEST_TABLE = test_utils.makeTestTable('test', ['id']);
65
11
  const BASIC_SYNC_RULES = `
66
12
  bucket_definitions:
67
13
  mybucket:
@@ -77,7 +23,11 @@ export const SYNC_SNAPSHOT_PATH = path.resolve(__dirname, '../__snapshots/sync.t
77
23
  * });
78
24
  * ```
79
25
  */
80
- export function registerSyncTests(factory, options = {}) {
26
+ export function registerSyncTests(configOrFactory, options = {}) {
27
+ const config = typeof configOrFactory == 'function'
28
+ ? { factory: configOrFactory, tableIdStrings: options.tableIdStrings ?? true }
29
+ : configOrFactory;
30
+ const factory = config.factory;
81
31
  createCoreAPIMetrics(METRICS_HELPER.metricsEngine);
82
32
  const tracker = new sync.RequestTracker(METRICS_HELPER.metricsEngine);
83
33
  const syncContext = new sync.SyncContext({
@@ -92,66 +42,53 @@ export function registerSyncTests(factory, options = {}) {
92
42
  }));
93
43
  };
94
44
  test('sync global data', async () => {
95
- const env_1 = { stack: [], error: void 0, hasError: false };
96
- try {
97
- const f = __addDisposableResource(env_1, await factory(), true);
98
- const syncRules = await updateSyncRules(f, {
99
- content: BASIC_SYNC_RULES
100
- });
101
- const bucketStorage = f.getInstance(syncRules);
102
- const result = await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
103
- await batch.save({
104
- sourceTable: TEST_TABLE,
105
- tag: storage.SaveOperationTag.INSERT,
106
- after: {
107
- id: 't1',
108
- description: 'Test 1'
109
- },
110
- afterReplicaId: 't1'
111
- });
112
- await batch.save({
113
- sourceTable: TEST_TABLE,
114
- tag: storage.SaveOperationTag.INSERT,
115
- after: {
116
- id: 't2',
117
- description: 'Test 2'
118
- },
119
- afterReplicaId: 't2'
120
- });
121
- await batch.commit('0/1');
122
- });
123
- const stream = sync.streamResponse({
124
- syncContext,
125
- bucketStorage: bucketStorage,
126
- syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
127
- params: {
128
- buckets: [],
129
- include_checksum: true,
130
- raw_data: true
131
- },
132
- tracker,
133
- token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 10 }),
134
- isEncodingAsBson: false
135
- });
136
- const lines = await consumeCheckpointLines(stream);
137
- expect(lines).toMatchSnapshot();
138
- }
139
- catch (e_1) {
140
- env_1.error = e_1;
141
- env_1.hasError = true;
142
- }
143
- finally {
144
- const result_1 = __disposeResources(env_1);
145
- if (result_1)
146
- await result_1;
147
- }
45
+ await using f = await factory();
46
+ const syncRules = await updateSyncRules(f, {
47
+ content: BASIC_SYNC_RULES
48
+ });
49
+ const bucketStorage = f.getInstance(syncRules);
50
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
51
+ const sourceTable = await test_utils.resolveTestTable(writer, 'test', ['id'], config);
52
+ await writer.markAllSnapshotDone('0/1');
53
+ await writer.save({
54
+ sourceTable,
55
+ tag: storage.SaveOperationTag.INSERT,
56
+ after: {
57
+ id: 't1',
58
+ description: 'Test 1'
59
+ },
60
+ afterReplicaId: 't1'
61
+ });
62
+ await writer.save({
63
+ sourceTable,
64
+ tag: storage.SaveOperationTag.INSERT,
65
+ after: {
66
+ id: 't2',
67
+ description: 'Test 2'
68
+ },
69
+ afterReplicaId: 't2'
70
+ });
71
+ await writer.commit('0/1');
72
+ const stream = sync.streamResponse({
73
+ syncContext,
74
+ bucketStorage: bucketStorage,
75
+ syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
76
+ params: {
77
+ buckets: [],
78
+ include_checksum: true,
79
+ raw_data: true
80
+ },
81
+ tracker,
82
+ token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 10 }),
83
+ isEncodingAsBson: false
84
+ });
85
+ const lines = await consumeCheckpointLines(stream);
86
+ expect(lines).toMatchSnapshot();
148
87
  });
149
88
  test('sync buckets in order', async () => {
150
- const env_2 = { stack: [], error: void 0, hasError: false };
151
- try {
152
- const f = __addDisposableResource(env_2, await factory(), true);
153
- const syncRules = await updateSyncRules(f, {
154
- content: `
89
+ await using f = await factory();
90
+ const syncRules = await updateSyncRules(f, {
91
+ content: `
155
92
  bucket_definitions:
156
93
  b0:
157
94
  priority: 2
@@ -162,61 +99,116 @@ bucket_definitions:
162
99
  data:
163
100
  - SELECT * FROM test WHERE LENGTH(id) > 2;
164
101
  `
165
- });
166
- const bucketStorage = f.getInstance(syncRules);
167
- const result = await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
168
- await batch.save({
169
- sourceTable: TEST_TABLE,
170
- tag: storage.SaveOperationTag.INSERT,
171
- after: {
172
- id: 't1',
173
- description: 'Test 1'
174
- },
175
- afterReplicaId: 't1'
176
- });
177
- await batch.save({
178
- sourceTable: TEST_TABLE,
179
- tag: storage.SaveOperationTag.INSERT,
180
- after: {
181
- id: 'earlier',
182
- description: 'Test 2'
183
- },
184
- afterReplicaId: 'earlier'
185
- });
186
- await batch.commit('0/1');
187
- });
188
- const stream = sync.streamResponse({
189
- syncContext,
190
- bucketStorage,
191
- syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
192
- params: {
193
- buckets: [],
194
- include_checksum: true,
195
- raw_data: true
196
- },
197
- tracker,
198
- token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 10 }),
199
- isEncodingAsBson: false
200
- });
201
- const lines = await consumeCheckpointLines(stream);
202
- expect(lines).toMatchSnapshot();
203
- }
204
- catch (e_2) {
205
- env_2.error = e_2;
206
- env_2.hasError = true;
207
- }
208
- finally {
209
- const result_2 = __disposeResources(env_2);
210
- if (result_2)
211
- await result_2;
212
- }
102
+ });
103
+ const bucketStorage = f.getInstance(syncRules);
104
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
105
+ const testTable = await test_utils.resolveTestTable(writer, 'test', ['id'], config);
106
+ await writer.markAllSnapshotDone('0/1');
107
+ await writer.save({
108
+ sourceTable: testTable,
109
+ tag: storage.SaveOperationTag.INSERT,
110
+ after: {
111
+ id: 't1',
112
+ description: 'Test 1'
113
+ },
114
+ afterReplicaId: 't1'
115
+ });
116
+ await writer.save({
117
+ sourceTable: testTable,
118
+ tag: storage.SaveOperationTag.INSERT,
119
+ after: {
120
+ id: 'earlier',
121
+ description: 'Test 2'
122
+ },
123
+ afterReplicaId: 'earlier'
124
+ });
125
+ await writer.commit('0/1');
126
+ const stream = sync.streamResponse({
127
+ syncContext,
128
+ bucketStorage,
129
+ syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
130
+ params: {
131
+ buckets: [],
132
+ include_checksum: true,
133
+ raw_data: true
134
+ },
135
+ tracker,
136
+ token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 10 }),
137
+ isEncodingAsBson: false
138
+ });
139
+ const lines = await consumeCheckpointLines(stream);
140
+ expect(lines).toMatchSnapshot();
141
+ });
142
+ test('can override priority when subscribing to stream', async () => {
143
+ await using f = await factory();
144
+ const syncRules = await updateSyncRules(f, {
145
+ content: `
146
+ config:
147
+ edition: 3
148
+
149
+ streams:
150
+ todos:
151
+ query: SELECT * FROM test WHERE id IN subscription.parameter('test_ids')
152
+ `
153
+ });
154
+ const bucketStorage = f.getInstance(syncRules);
155
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
156
+ const testTable = await test_utils.resolveTestTable(writer, 'test', ['id'], config);
157
+ await writer.markAllSnapshotDone('0/1');
158
+ await writer.save({
159
+ sourceTable: testTable,
160
+ tag: storage.SaveOperationTag.INSERT,
161
+ after: {
162
+ id: 'a',
163
+ description: 'Test 1'
164
+ },
165
+ afterReplicaId: 't1'
166
+ });
167
+ await writer.save({
168
+ sourceTable: testTable,
169
+ tag: storage.SaveOperationTag.INSERT,
170
+ after: {
171
+ id: 'b',
172
+ description: 'Test 2'
173
+ },
174
+ afterReplicaId: 'earlier'
175
+ });
176
+ await writer.commit('0/1');
177
+ const stream = sync.streamResponse({
178
+ syncContext,
179
+ bucketStorage,
180
+ syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
181
+ params: {
182
+ buckets: [],
183
+ include_checksum: true,
184
+ raw_data: true,
185
+ streams: {
186
+ include_defaults: true,
187
+ subscriptions: [
188
+ {
189
+ stream: 'todos',
190
+ parameters: { test_ids: ['a'] },
191
+ override_priority: 0
192
+ },
193
+ {
194
+ stream: 'todos',
195
+ parameters: { test_ids: ['a', 'b'] },
196
+ override_priority: null
197
+ }
198
+ ]
199
+ }
200
+ },
201
+ tracker,
202
+ token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 10 }),
203
+ isEncodingAsBson: false
204
+ });
205
+ const lines = await consumeCheckpointLines(stream);
206
+ expect(lines).toMatchSnapshot();
213
207
  });
214
208
  test('sync interrupts low-priority buckets on new checkpoints', async () => {
215
- const env_3 = { stack: [], error: void 0, hasError: false };
216
- try {
217
- const f = __addDisposableResource(env_3, await factory(), true);
218
- const syncRules = await updateSyncRules(f, {
219
- content: `
209
+ await using f = await factory();
210
+ const syncRules = await updateSyncRules(f, {
211
+ content: `
220
212
  bucket_definitions:
221
213
  b0:
222
214
  priority: 2
@@ -227,106 +219,93 @@ bucket_definitions:
227
219
  data:
228
220
  - SELECT * FROM test WHERE LENGTH(id) > 5;
229
221
  `
230
- });
231
- const bucketStorage = f.getInstance(syncRules);
232
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
233
- // Initial data: Add one priority row and 10k low-priority rows.
234
- await batch.save({
235
- sourceTable: TEST_TABLE,
236
- tag: storage.SaveOperationTag.INSERT,
237
- after: {
238
- id: 'highprio',
239
- description: 'High priority row'
240
- },
241
- afterReplicaId: 'highprio'
242
- });
243
- for (let i = 0; i < 10_000; i++) {
244
- await batch.save({
245
- sourceTable: TEST_TABLE,
246
- tag: storage.SaveOperationTag.INSERT,
247
- after: {
248
- id: `${i}`,
249
- description: 'low prio'
250
- },
251
- afterReplicaId: `${i}`
252
- });
253
- }
254
- await batch.commit('0/1');
255
- });
256
- const stream = sync.streamResponse({
257
- syncContext,
258
- bucketStorage,
259
- syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
260
- params: {
261
- buckets: [],
262
- include_checksum: true,
263
- raw_data: true
222
+ });
223
+ const bucketStorage = f.getInstance(syncRules);
224
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
225
+ const testTable = await test_utils.resolveTestTable(writer, 'test', ['id'], config);
226
+ await writer.markAllSnapshotDone('0/1');
227
+ // Initial data: Add one priority row and 10k low-priority rows.
228
+ await writer.save({
229
+ sourceTable: testTable,
230
+ tag: storage.SaveOperationTag.INSERT,
231
+ after: {
232
+ id: 'highprio',
233
+ description: 'High priority row'
234
+ },
235
+ afterReplicaId: 'highprio'
236
+ });
237
+ for (let i = 0; i < 10_000; i++) {
238
+ await writer.save({
239
+ sourceTable: testTable,
240
+ tag: storage.SaveOperationTag.INSERT,
241
+ after: {
242
+ id: `${i}`,
243
+ description: 'low prio'
264
244
  },
265
- tracker,
266
- token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 10 }),
267
- isEncodingAsBson: false
245
+ afterReplicaId: `${i}`
268
246
  });
269
- let sentCheckpoints = 0;
270
- let sentRows = 0;
271
- for await (let next of stream) {
272
- if (typeof next == 'string') {
273
- next = JSON.parse(next);
274
- }
275
- if (typeof next === 'object' && next !== null) {
276
- if ('partial_checkpoint_complete' in next) {
277
- if (sentCheckpoints == 1) {
278
- // Save new data to interrupt the low-priority sync.
279
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
280
- // Add another high-priority row. This should interrupt the long-running low-priority sync.
281
- await batch.save({
282
- sourceTable: TEST_TABLE,
283
- tag: storage.SaveOperationTag.INSERT,
284
- after: {
285
- id: 'highprio2',
286
- description: 'Another high-priority row'
287
- },
288
- afterReplicaId: 'highprio2'
289
- });
290
- await batch.commit('0/2');
291
- });
292
- }
293
- else {
294
- // Low-priority sync from the first checkpoint was interrupted. This should not happen before
295
- // 1000 low-priority items were synchronized.
296
- expect(sentCheckpoints).toBe(2);
297
- expect(sentRows).toBeGreaterThan(1000);
298
- }
299
- }
300
- if ('checkpoint' in next || 'checkpoint_diff' in next) {
301
- sentCheckpoints += 1;
302
- }
303
- if ('data' in next) {
304
- sentRows += next.data.data.length;
247
+ }
248
+ await writer.commit('0/1');
249
+ const stream = sync.streamResponse({
250
+ syncContext,
251
+ bucketStorage,
252
+ syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
253
+ params: {
254
+ buckets: [],
255
+ include_checksum: true,
256
+ raw_data: true
257
+ },
258
+ tracker,
259
+ token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 10 }),
260
+ isEncodingAsBson: false
261
+ });
262
+ let sentCheckpoints = 0;
263
+ let sentRows = 0;
264
+ for await (let next of stream) {
265
+ if (typeof next == 'string') {
266
+ next = JSON.parse(next);
267
+ }
268
+ if (typeof next === 'object' && next !== null) {
269
+ if ('partial_checkpoint_complete' in next) {
270
+ if (sentCheckpoints == 1) {
271
+ // Save new data to interrupt the low-priority sync.
272
+ // Add another high-priority row. This should interrupt the long-running low-priority sync.
273
+ await writer.save({
274
+ sourceTable: testTable,
275
+ tag: storage.SaveOperationTag.INSERT,
276
+ after: {
277
+ id: 'highprio2',
278
+ description: 'Another high-priority row'
279
+ },
280
+ afterReplicaId: 'highprio2'
281
+ });
282
+ await writer.commit('0/2');
305
283
  }
306
- if ('checkpoint_complete' in next) {
307
- break;
284
+ else {
285
+ // Low-priority sync from the first checkpoint was interrupted. This should not happen before
286
+ // 1000 low-priority items were synchronized.
287
+ expect(sentCheckpoints).toBe(2);
288
+ expect(sentRows).toBeGreaterThan(1000);
308
289
  }
309
290
  }
291
+ if ('checkpoint' in next || 'checkpoint_diff' in next) {
292
+ sentCheckpoints += 1;
293
+ }
294
+ if ('data' in next) {
295
+ sentRows += next.data.data.length;
296
+ }
297
+ if ('checkpoint_complete' in next) {
298
+ break;
299
+ }
310
300
  }
311
- expect(sentCheckpoints).toBe(2);
312
- expect(sentRows).toBe(10002);
313
- }
314
- catch (e_3) {
315
- env_3.error = e_3;
316
- env_3.hasError = true;
317
- }
318
- finally {
319
- const result_3 = __disposeResources(env_3);
320
- if (result_3)
321
- await result_3;
322
301
  }
302
+ expect(sentCheckpoints).toBe(2);
303
+ expect(sentRows).toBe(10002);
323
304
  });
324
305
  test('sync interruptions with unrelated data', async () => {
325
- const env_4 = { stack: [], error: void 0, hasError: false };
326
- try {
327
- const f = __addDisposableResource(env_4, await factory(), true);
328
- const syncRules = await updateSyncRules(f, {
329
- content: `
306
+ await using f = await factory();
307
+ const syncRules = await updateSyncRules(f, {
308
+ content: `
330
309
  bucket_definitions:
331
310
  b0:
332
311
  priority: 2
@@ -338,131 +317,116 @@ bucket_definitions:
338
317
  data:
339
318
  - SELECT * FROM test WHERE LENGTH(id) > 5 AND description = bucket.user_id;
340
319
  `
341
- });
342
- const bucketStorage = f.getInstance(syncRules);
343
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
344
- // Initial data: Add one priority row and 10k low-priority rows.
345
- await batch.save({
346
- sourceTable: TEST_TABLE,
347
- tag: storage.SaveOperationTag.INSERT,
348
- after: {
349
- id: 'highprio',
350
- description: 'user_one'
351
- },
352
- afterReplicaId: 'highprio'
353
- });
354
- for (let i = 0; i < 10_000; i++) {
355
- await batch.save({
356
- sourceTable: TEST_TABLE,
357
- tag: storage.SaveOperationTag.INSERT,
358
- after: {
359
- id: `${i}`,
360
- description: 'low prio'
361
- },
362
- afterReplicaId: `${i}`
363
- });
364
- }
365
- await batch.commit('0/1');
366
- });
367
- const stream = sync.streamResponse({
368
- syncContext,
369
- bucketStorage,
370
- syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
371
- params: {
372
- buckets: [],
373
- include_checksum: true,
374
- raw_data: true
320
+ });
321
+ const bucketStorage = f.getInstance(syncRules);
322
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
323
+ const testTable = await test_utils.resolveTestTable(writer, 'test', ['id'], config);
324
+ await writer.markAllSnapshotDone('0/1');
325
+ // Initial data: Add one priority row and 10k low-priority rows.
326
+ await writer.save({
327
+ sourceTable: testTable,
328
+ tag: storage.SaveOperationTag.INSERT,
329
+ after: {
330
+ id: 'highprio',
331
+ description: 'user_one'
332
+ },
333
+ afterReplicaId: 'highprio'
334
+ });
335
+ for (let i = 0; i < 10_000; i++) {
336
+ await writer.save({
337
+ sourceTable: testTable,
338
+ tag: storage.SaveOperationTag.INSERT,
339
+ after: {
340
+ id: `${i}`,
341
+ description: 'low prio'
375
342
  },
376
- tracker,
377
- token: new JwtPayload({ sub: 'user_one', exp: Date.now() / 1000 + 100000 }),
378
- isEncodingAsBson: false
343
+ afterReplicaId: `${i}`
379
344
  });
380
- let sentCheckpoints = 0;
381
- let completedCheckpoints = 0;
382
- let sentRows = 0;
383
- // Expected flow:
384
- // 1. Stream starts, we receive a checkpoint followed by the one high-prio row and a partial completion.
385
- // 2. We insert a new row that is not part of a bucket relevant to this stream.
386
- // 3. This means that no interruption happens and we receive all the low-priority data, followed by a checkpoint.
387
- // 4. After the checkpoint, add a new row that _is_ relevant for this sync, which should trigger a new iteration.
388
- for await (let next of stream) {
389
- if (typeof next == 'string') {
390
- next = JSON.parse(next);
391
- }
392
- if (typeof next === 'object' && next !== null) {
393
- if ('partial_checkpoint_complete' in next) {
394
- if (sentCheckpoints == 1) {
395
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
396
- // Add a high-priority row that doesn't affect this sync stream.
397
- await batch.save({
398
- sourceTable: TEST_TABLE,
399
- tag: storage.SaveOperationTag.INSERT,
400
- after: {
401
- id: 'highprio2',
402
- description: 'user_two'
403
- },
404
- afterReplicaId: 'highprio2'
405
- });
406
- await batch.commit('0/2');
407
- });
408
- }
409
- else {
410
- expect(sentCheckpoints).toBe(2);
411
- expect(sentRows).toBe(10002);
412
- }
345
+ }
346
+ await writer.commit('0/1');
347
+ const stream = sync.streamResponse({
348
+ syncContext,
349
+ bucketStorage,
350
+ syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
351
+ params: {
352
+ buckets: [],
353
+ include_checksum: true,
354
+ raw_data: true
355
+ },
356
+ tracker,
357
+ token: new JwtPayload({ sub: 'user_one', exp: Date.now() / 1000 + 100000 }),
358
+ isEncodingAsBson: false
359
+ });
360
+ let sentCheckpoints = 0;
361
+ let completedCheckpoints = 0;
362
+ let sentRows = 0;
363
+ // Expected flow:
364
+ // 1. Stream starts, we receive a checkpoint followed by the one high-prio row and a partial completion.
365
+ // 2. We insert a new row that is not part of a bucket relevant to this stream.
366
+ // 3. This means that no interruption happens and we receive all the low-priority data, followed by a checkpoint.
367
+ // 4. After the checkpoint, add a new row that _is_ relevant for this sync, which should trigger a new iteration.
368
+ for await (let next of stream) {
369
+ if (typeof next == 'string') {
370
+ next = JSON.parse(next);
371
+ }
372
+ if (typeof next === 'object' && next !== null) {
373
+ if ('partial_checkpoint_complete' in next) {
374
+ if (sentCheckpoints == 1) {
375
+ // Add a high-priority row that doesn't affect this sync stream.
376
+ await writer.save({
377
+ sourceTable: testTable,
378
+ tag: storage.SaveOperationTag.INSERT,
379
+ after: {
380
+ id: 'highprio2',
381
+ description: 'user_two'
382
+ },
383
+ afterReplicaId: 'highprio2'
384
+ });
385
+ await writer.commit('0/2');
413
386
  }
414
- if ('checkpoint' in next || 'checkpoint_diff' in next) {
415
- sentCheckpoints += 1;
387
+ else {
388
+ expect(sentCheckpoints).toBe(2);
389
+ expect(sentRows).toBe(10002);
416
390
  }
417
- if ('data' in next) {
418
- sentRows += next.data.data.length;
391
+ }
392
+ if ('checkpoint' in next || 'checkpoint_diff' in next) {
393
+ sentCheckpoints += 1;
394
+ }
395
+ if ('data' in next) {
396
+ sentRows += next.data.data.length;
397
+ }
398
+ if ('checkpoint_complete' in next) {
399
+ completedCheckpoints++;
400
+ if (completedCheckpoints == 2) {
401
+ break;
419
402
  }
420
- if ('checkpoint_complete' in next) {
421
- completedCheckpoints++;
422
- if (completedCheckpoints == 2) {
423
- break;
424
- }
425
- if (completedCheckpoints == 1) {
426
- expect(sentRows).toBe(10001);
427
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
428
- // Add a high-priority row that affects this sync stream.
429
- await batch.save({
430
- sourceTable: TEST_TABLE,
431
- tag: storage.SaveOperationTag.INSERT,
432
- after: {
433
- id: 'highprio3',
434
- description: 'user_one'
435
- },
436
- afterReplicaId: 'highprio3'
437
- });
438
- await batch.commit('0/3');
439
- });
440
- }
403
+ if (completedCheckpoints == 1) {
404
+ expect(sentRows).toBe(10001);
405
+ // Add a high-priority row that affects this sync stream.
406
+ await writer.save({
407
+ sourceTable: testTable,
408
+ tag: storage.SaveOperationTag.INSERT,
409
+ after: {
410
+ id: 'highprio3',
411
+ description: 'user_one'
412
+ },
413
+ afterReplicaId: 'highprio3'
414
+ });
415
+ await writer.commit('0/3');
441
416
  }
442
417
  }
443
418
  }
444
- expect(sentCheckpoints).toBe(2);
445
- expect(sentRows).toBe(10002);
446
- }
447
- catch (e_4) {
448
- env_4.error = e_4;
449
- env_4.hasError = true;
450
- }
451
- finally {
452
- const result_4 = __disposeResources(env_4);
453
- if (result_4)
454
- await result_4;
455
419
  }
420
+ expect(sentCheckpoints).toBe(2);
421
+ expect(sentRows).toBe(10002);
456
422
  });
457
423
  test('sync interrupts low-priority buckets on new checkpoints (2)', async () => {
458
- const env_5 = { stack: [], error: void 0, hasError: false };
459
- try {
460
- const f = __addDisposableResource(env_5, await factory(), true);
461
- // bucket0a -> send all data
462
- // then interrupt checkpoint with new data for all buckets
463
- // -> data for all buckets should be sent in the new checkpoint
464
- const syncRules = await updateSyncRules(f, {
465
- content: `
424
+ await using f = await factory();
425
+ // bucket0a -> send all data
426
+ // then interrupt checkpoint with new data for all buckets
427
+ // -> data for all buckets should be sent in the new checkpoint
428
+ const syncRules = await updateSyncRules(f, {
429
+ content: `
466
430
  bucket_definitions:
467
431
  b0a:
468
432
  priority: 2
@@ -477,215 +441,192 @@ bucket_definitions:
477
441
  data:
478
442
  - SELECT * FROM test WHERE LENGTH(id) > 5;
479
443
  `
480
- });
481
- const bucketStorage = f.getInstance(syncRules);
482
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
483
- // Initial data: Add one priority row and 10k low-priority rows.
484
- await batch.save({
485
- sourceTable: TEST_TABLE,
486
- tag: storage.SaveOperationTag.INSERT,
487
- after: {
488
- id: 'highprio',
489
- description: 'High priority row'
490
- },
491
- afterReplicaId: 'highprio'
492
- });
493
- for (let i = 0; i < 2_000; i++) {
494
- await batch.save({
495
- sourceTable: TEST_TABLE,
496
- tag: storage.SaveOperationTag.INSERT,
497
- after: {
498
- id: `${i}`,
499
- description: 'low prio'
500
- },
501
- afterReplicaId: `${i}`
502
- });
503
- }
504
- await batch.commit('0/1');
505
- });
506
- const stream = sync.streamResponse({
507
- syncContext,
508
- bucketStorage,
509
- syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
510
- params: {
511
- buckets: [],
512
- include_checksum: true,
513
- raw_data: true
444
+ });
445
+ const bucketStorage = f.getInstance(syncRules);
446
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
447
+ const testTable = await test_utils.resolveTestTable(writer, 'test', ['id'], config);
448
+ await writer.markAllSnapshotDone('0/1');
449
+ // Initial data: Add one priority row and 10k low-priority rows.
450
+ await writer.save({
451
+ sourceTable: testTable,
452
+ tag: storage.SaveOperationTag.INSERT,
453
+ after: {
454
+ id: 'highprio',
455
+ description: 'High priority row'
456
+ },
457
+ afterReplicaId: 'highprio'
458
+ });
459
+ for (let i = 0; i < 2_000; i++) {
460
+ await writer.save({
461
+ sourceTable: testTable,
462
+ tag: storage.SaveOperationTag.INSERT,
463
+ after: {
464
+ id: `${i}`,
465
+ description: 'low prio'
514
466
  },
515
- tracker,
516
- token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 10 }),
517
- isEncodingAsBson: false
467
+ afterReplicaId: `${i}`
518
468
  });
519
- let sentRows = 0;
520
- let lines = [];
521
- for await (let next of stream) {
522
- if (typeof next == 'string') {
523
- next = JSON.parse(next);
469
+ }
470
+ await writer.commit('0/1');
471
+ const stream = sync.streamResponse({
472
+ syncContext,
473
+ bucketStorage,
474
+ syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
475
+ params: {
476
+ buckets: [],
477
+ include_checksum: true,
478
+ raw_data: true
479
+ },
480
+ tracker,
481
+ token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 10 }),
482
+ isEncodingAsBson: false
483
+ });
484
+ let sentRows = 0;
485
+ let lines = [];
486
+ for await (let next of stream) {
487
+ if (typeof next == 'string') {
488
+ next = JSON.parse(next);
489
+ }
490
+ if (typeof next === 'object' && next !== null) {
491
+ if ('partial_checkpoint_complete' in next) {
492
+ lines.push(next);
524
493
  }
525
- if (typeof next === 'object' && next !== null) {
526
- if ('partial_checkpoint_complete' in next) {
527
- lines.push(next);
528
- }
529
- if ('checkpoint' in next || 'checkpoint_diff' in next) {
530
- lines.push(next);
494
+ if ('checkpoint' in next || 'checkpoint_diff' in next) {
495
+ lines.push(next);
496
+ }
497
+ if ('data' in next) {
498
+ lines.push({ data: { ...next.data, data: undefined } });
499
+ sentRows += next.data.data.length;
500
+ if (sentRows == 1001) {
501
+ // Save new data to interrupt the low-priority sync.
502
+ // Add another high-priority row. This should interrupt the long-running low-priority sync.
503
+ await writer.save({
504
+ sourceTable: testTable,
505
+ tag: storage.SaveOperationTag.INSERT,
506
+ after: {
507
+ id: 'highprio2',
508
+ description: 'Another high-priority row'
509
+ },
510
+ afterReplicaId: 'highprio2'
511
+ });
512
+ // Also add a low-priority row
513
+ await writer.save({
514
+ sourceTable: testTable,
515
+ tag: storage.SaveOperationTag.INSERT,
516
+ after: {
517
+ id: '2001',
518
+ description: 'Another low-priority row'
519
+ },
520
+ afterReplicaId: '2001'
521
+ });
522
+ await writer.commit('0/2');
531
523
  }
532
- if ('data' in next) {
533
- lines.push({ data: { ...next.data, data: undefined } });
534
- sentRows += next.data.data.length;
535
- if (sentRows == 1001) {
536
- // Save new data to interrupt the low-priority sync.
537
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
538
- // Add another high-priority row. This should interrupt the long-running low-priority sync.
539
- await batch.save({
540
- sourceTable: TEST_TABLE,
541
- tag: storage.SaveOperationTag.INSERT,
542
- after: {
543
- id: 'highprio2',
544
- description: 'Another high-priority row'
545
- },
546
- afterReplicaId: 'highprio2'
547
- });
548
- // Also add a low-priority row
549
- await batch.save({
550
- sourceTable: TEST_TABLE,
551
- tag: storage.SaveOperationTag.INSERT,
552
- after: {
553
- id: '2001',
554
- description: 'Another low-priority row'
555
- },
556
- afterReplicaId: '2001'
557
- });
558
- await batch.commit('0/2');
559
- });
560
- }
561
- if (sentRows >= 1000 && sentRows <= 2001) {
562
- // pause for a bit to give the stream time to process interruptions.
563
- // This covers the data batch above and the next one.
564
- await timers.setTimeout(50);
565
- }
566
- }
567
- if ('checkpoint_complete' in next) {
568
- lines.push(next);
569
- break;
524
+ if (sentRows >= 1000 && sentRows <= 2001) {
525
+ // pause for a bit to give the stream time to process interruptions.
526
+ // This covers the data batch above and the next one.
527
+ await timers.setTimeout(50);
570
528
  }
571
529
  }
530
+ if ('checkpoint_complete' in next) {
531
+ lines.push(next);
532
+ break;
533
+ }
572
534
  }
573
- // Expected lines (full details in snapshot):
574
- //
575
- // checkpoint (4001)
576
- // data (b1[] 0 -> 1)
577
- // partial_checkpoint_complete (4001, priority 1)
578
- // data (b0a[], 0 -> 2000)
579
- // ## adds new data, interrupting the checkpoint
580
- // data (b0a[], 2000 -> 4000) # expected - stream is already busy with this by the time it receives the interruption
581
- // checkpoint_diff (4004)
582
- // data (b1[], 1 -> 4002)
583
- // partial_checkpoint_complete (4004, priority 1)
584
- // data (b0a[], 4000 -> 4003)
585
- // data (b0b[], 0 -> 1999)
586
- // data (b0b[], 1999 -> 3999)
587
- // data (b0b[], 3999 -> 4004)
588
- // checkpoint_complete (4004)
589
- expect(lines).toMatchSnapshot();
590
- expect(sentRows).toBe(4004);
591
- }
592
- catch (e_5) {
593
- env_5.error = e_5;
594
- env_5.hasError = true;
595
- }
596
- finally {
597
- const result_5 = __disposeResources(env_5);
598
- if (result_5)
599
- await result_5;
600
535
  }
536
+ // Expected lines (full details in snapshot):
537
+ //
538
+ // checkpoint (4001)
539
+ // data (b1[] 0 -> 1)
540
+ // partial_checkpoint_complete (4001, priority 1)
541
+ // data (b0a[], 0 -> 2000)
542
+ // ## adds new data, interrupting the checkpoint
543
+ // data (b0a[], 2000 -> 4000) # expected - stream is already busy with this by the time it receives the interruption
544
+ // checkpoint_diff (4004)
545
+ // data (b1[], 1 -> 4002)
546
+ // partial_checkpoint_complete (4004, priority 1)
547
+ // data (b0a[], 4000 -> 4003)
548
+ // data (b0b[], 0 -> 1999)
549
+ // data (b0b[], 1999 -> 3999)
550
+ // data (b0b[], 3999 -> 4004)
551
+ // checkpoint_complete (4004)
552
+ expect(lines).toMatchSnapshot();
553
+ expect(sentRows).toBe(4004);
601
554
  });
602
555
  test('sends checkpoint complete line for empty checkpoint', async () => {
603
- const env_6 = { stack: [], error: void 0, hasError: false };
604
- try {
605
- const f = __addDisposableResource(env_6, await factory(), true);
606
- const syncRules = await updateSyncRules(f, {
607
- content: BASIC_SYNC_RULES
608
- });
609
- const bucketStorage = f.getInstance(syncRules);
610
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
611
- await batch.save({
612
- sourceTable: TEST_TABLE,
613
- tag: storage.SaveOperationTag.INSERT,
614
- after: {
615
- id: 't1',
616
- description: 'sync'
617
- },
618
- afterReplicaId: 't1'
619
- });
620
- await batch.commit('0/1');
621
- });
622
- const stream = sync.streamResponse({
623
- syncContext,
624
- bucketStorage,
625
- syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
626
- params: {
627
- buckets: [],
628
- include_checksum: true,
629
- raw_data: true
630
- },
631
- tracker,
632
- token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 100000 }),
633
- isEncodingAsBson: false
634
- });
635
- const lines = [];
636
- let receivedCompletions = 0;
637
- for await (let next of stream) {
638
- if (typeof next == 'string') {
639
- next = JSON.parse(next);
640
- }
641
- lines.push(next);
642
- if (typeof next === 'object' && next !== null) {
643
- if ('checkpoint_complete' in next) {
644
- receivedCompletions++;
645
- if (receivedCompletions == 1) {
646
- // Trigger an empty bucket update.
647
- await bucketStorage.createManagedWriteCheckpoint({ user_id: '', heads: { '1': '1/0' } });
648
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
649
- await batch.commit('1/0');
650
- });
651
- }
652
- else {
653
- break;
654
- }
556
+ await using f = await factory();
557
+ const syncRules = await updateSyncRules(f, {
558
+ content: BASIC_SYNC_RULES
559
+ });
560
+ const bucketStorage = f.getInstance(syncRules);
561
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
562
+ const testTable = await test_utils.resolveTestTable(writer, 'test', ['id'], config);
563
+ await writer.markAllSnapshotDone('0/1');
564
+ await writer.save({
565
+ sourceTable: testTable,
566
+ tag: storage.SaveOperationTag.INSERT,
567
+ after: {
568
+ id: 't1',
569
+ description: 'sync'
570
+ },
571
+ afterReplicaId: 't1'
572
+ });
573
+ await writer.commit('0/1');
574
+ const stream = sync.streamResponse({
575
+ syncContext,
576
+ bucketStorage,
577
+ syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
578
+ params: {
579
+ buckets: [],
580
+ include_checksum: true,
581
+ raw_data: true
582
+ },
583
+ tracker,
584
+ token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 100000 }),
585
+ isEncodingAsBson: false
586
+ });
587
+ const lines = [];
588
+ let receivedCompletions = 0;
589
+ for await (let next of stream) {
590
+ if (typeof next == 'string') {
591
+ next = JSON.parse(next);
592
+ }
593
+ lines.push(next);
594
+ if (typeof next === 'object' && next !== null) {
595
+ if ('checkpoint_complete' in next) {
596
+ receivedCompletions++;
597
+ if (receivedCompletions == 1) {
598
+ // Trigger an empty bucket update.
599
+ await bucketStorage.createManagedWriteCheckpoint({ user_id: '', heads: { '1': '1/0' } });
600
+ await writer.commit('1/0');
601
+ }
602
+ else {
603
+ break;
655
604
  }
656
605
  }
657
606
  }
658
- expect(lines).toMatchSnapshot();
659
- }
660
- catch (e_6) {
661
- env_6.error = e_6;
662
- env_6.hasError = true;
663
- }
664
- finally {
665
- const result_6 = __disposeResources(env_6);
666
- if (result_6)
667
- await result_6;
668
607
  }
608
+ expect(lines).toMatchSnapshot();
669
609
  });
670
610
  test('sync legacy non-raw data', async () => {
671
- const f = await factory();
611
+ await using f = await factory();
672
612
  const syncRules = await updateSyncRules(f, {
673
613
  content: BASIC_SYNC_RULES
674
614
  });
675
615
  const bucketStorage = await f.getInstance(syncRules);
676
- const result = await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
677
- await batch.save({
678
- sourceTable: TEST_TABLE,
679
- tag: storage.SaveOperationTag.INSERT,
680
- after: {
681
- id: 't1',
682
- description: 'Test\n"string"',
683
- large_num: 12345678901234567890n
684
- },
685
- afterReplicaId: 't1'
686
- });
687
- await batch.commit('0/1');
616
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
617
+ const testTable = await test_utils.resolveTestTable(writer, 'test', ['id'], config);
618
+ await writer.markAllSnapshotDone('0/1');
619
+ await writer.save({
620
+ sourceTable: testTable,
621
+ tag: storage.SaveOperationTag.INSERT,
622
+ after: {
623
+ id: 't1',
624
+ description: 'Test\n"string"',
625
+ large_num: 12345678901234567890n
626
+ },
627
+ afterReplicaId: 't1'
688
628
  });
629
+ await writer.commit('0/1');
689
630
  const stream = sync.streamResponse({
690
631
  syncContext,
691
632
  bucketStorage,
@@ -705,525 +646,510 @@ bucket_definitions:
705
646
  expect(lines[1].data.data[0].data.large_num).toEqual(12345678901234567890n);
706
647
  });
707
648
  test('expired token', async () => {
708
- const env_7 = { stack: [], error: void 0, hasError: false };
709
- try {
710
- const f = __addDisposableResource(env_7, await factory(), true);
711
- const syncRules = await updateSyncRules(f, {
712
- content: BASIC_SYNC_RULES
713
- });
714
- const bucketStorage = await f.getInstance(syncRules);
715
- const stream = sync.streamResponse({
716
- syncContext,
717
- bucketStorage,
718
- syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
719
- params: {
720
- buckets: [],
721
- include_checksum: true,
722
- raw_data: true
723
- },
724
- tracker,
725
- token: new JwtPayload({ sub: '', exp: 0 }),
726
- isEncodingAsBson: false
727
- });
728
- const lines = await consumeCheckpointLines(stream);
729
- expect(lines).toMatchSnapshot();
730
- }
731
- catch (e_7) {
732
- env_7.error = e_7;
733
- env_7.hasError = true;
734
- }
735
- finally {
736
- const result_7 = __disposeResources(env_7);
737
- if (result_7)
738
- await result_7;
739
- }
649
+ await using f = await factory();
650
+ const syncRules = await updateSyncRules(f, {
651
+ content: BASIC_SYNC_RULES
652
+ });
653
+ const bucketStorage = await f.getInstance(syncRules);
654
+ const stream = sync.streamResponse({
655
+ syncContext,
656
+ bucketStorage,
657
+ syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
658
+ params: {
659
+ buckets: [],
660
+ include_checksum: true,
661
+ raw_data: true
662
+ },
663
+ tracker,
664
+ token: new JwtPayload({ sub: '', exp: 0 }),
665
+ isEncodingAsBson: false
666
+ });
667
+ const lines = await consumeCheckpointLines(stream);
668
+ expect(lines).toMatchSnapshot();
740
669
  });
741
670
  test('sync updates to global data', async (context) => {
742
- const env_8 = { stack: [], error: void 0, hasError: false };
743
- try {
744
- const f = __addDisposableResource(env_8, await factory(), true);
745
- const syncRules = await updateSyncRules(f, {
746
- content: BASIC_SYNC_RULES
747
- });
748
- const bucketStorage = await f.getInstance(syncRules);
749
- // Activate
750
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
751
- await batch.keepalive('0/0');
752
- });
753
- const stream = sync.streamResponse({
754
- syncContext,
755
- bucketStorage,
756
- syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
757
- params: {
758
- buckets: [],
759
- include_checksum: true,
760
- raw_data: true
761
- },
762
- tracker,
763
- token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 10 }),
764
- isEncodingAsBson: false
765
- });
766
- const iter = stream[Symbol.asyncIterator]();
767
- context.onTestFinished(() => {
768
- iter.return?.();
769
- });
770
- expect(await getCheckpointLines(iter)).toMatchSnapshot();
771
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
772
- await batch.save({
773
- sourceTable: TEST_TABLE,
774
- tag: storage.SaveOperationTag.INSERT,
775
- after: {
776
- id: 't1',
777
- description: 'Test 1'
778
- },
779
- afterReplicaId: 't1'
780
- });
781
- await batch.commit('0/1');
782
- });
783
- expect(await getCheckpointLines(iter)).toMatchSnapshot();
784
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
785
- await batch.save({
786
- sourceTable: TEST_TABLE,
787
- tag: storage.SaveOperationTag.INSERT,
788
- after: {
789
- id: 't2',
790
- description: 'Test 2'
791
- },
792
- afterReplicaId: 't2'
793
- });
794
- await batch.commit('0/2');
795
- });
796
- expect(await getCheckpointLines(iter)).toMatchSnapshot();
797
- }
798
- catch (e_8) {
799
- env_8.error = e_8;
800
- env_8.hasError = true;
801
- }
802
- finally {
803
- const result_8 = __disposeResources(env_8);
804
- if (result_8)
805
- await result_8;
806
- }
671
+ await using f = await factory();
672
+ const syncRules = await updateSyncRules(f, {
673
+ content: BASIC_SYNC_RULES
674
+ });
675
+ const bucketStorage = await f.getInstance(syncRules);
676
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
677
+ const testTable = await test_utils.resolveTestTable(writer, 'test', ['id'], config);
678
+ // Activate
679
+ await writer.markAllSnapshotDone('0/0');
680
+ await writer.keepalive('0/0');
681
+ const stream = sync.streamResponse({
682
+ syncContext,
683
+ bucketStorage,
684
+ syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
685
+ params: {
686
+ buckets: [],
687
+ include_checksum: true,
688
+ raw_data: true
689
+ },
690
+ tracker,
691
+ token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 10 }),
692
+ isEncodingAsBson: false
693
+ });
694
+ const iter = stream[Symbol.asyncIterator]();
695
+ context.onTestFinished(() => {
696
+ iter.return?.();
697
+ });
698
+ expect(await getCheckpointLines(iter)).toMatchSnapshot();
699
+ await writer.save({
700
+ sourceTable: testTable,
701
+ tag: storage.SaveOperationTag.INSERT,
702
+ after: {
703
+ id: 't1',
704
+ description: 'Test 1'
705
+ },
706
+ afterReplicaId: 't1'
707
+ });
708
+ await writer.commit('0/1');
709
+ expect(await getCheckpointLines(iter)).toMatchSnapshot();
710
+ await writer.save({
711
+ sourceTable: testTable,
712
+ tag: storage.SaveOperationTag.INSERT,
713
+ after: {
714
+ id: 't2',
715
+ description: 'Test 2'
716
+ },
717
+ afterReplicaId: 't2'
718
+ });
719
+ await writer.commit('0/2');
720
+ expect(await getCheckpointLines(iter)).toMatchSnapshot();
807
721
  });
808
722
  test('sync updates to parameter query only', async (context) => {
809
- const env_9 = { stack: [], error: void 0, hasError: false };
810
- try {
811
- const f = __addDisposableResource(env_9, await factory(), true);
812
- const syncRules = await updateSyncRules(f, {
813
- content: `bucket_definitions:
723
+ await using f = await factory();
724
+ const syncRules = await updateSyncRules(f, {
725
+ content: `bucket_definitions:
814
726
  by_user:
815
727
  parameters: select users.id as user_id from users where users.id = request.user_id()
816
728
  data:
817
729
  - select * from lists where user_id = bucket.user_id
818
730
  `
819
- });
820
- const usersTable = test_utils.makeTestTable('users', ['id']);
821
- const listsTable = test_utils.makeTestTable('lists', ['id']);
822
- const bucketStorage = await f.getInstance(syncRules);
823
- // Activate
824
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
825
- await batch.keepalive('0/0');
826
- });
827
- const stream = sync.streamResponse({
828
- syncContext,
829
- bucketStorage,
830
- syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
831
- params: {
832
- buckets: [],
833
- include_checksum: true,
834
- raw_data: true
835
- },
836
- tracker,
837
- token: new JwtPayload({ sub: 'user1', exp: Date.now() / 1000 + 100 }),
838
- isEncodingAsBson: false
839
- });
840
- const iter = stream[Symbol.asyncIterator]();
841
- context.onTestFinished(() => {
842
- iter.return?.();
843
- });
844
- // Initial empty checkpoint
845
- const checkpoint1 = await getCheckpointLines(iter);
846
- expect(checkpoint1[0].checkpoint?.buckets?.map((b) => b.bucket)).toEqual([]);
847
- expect(checkpoint1).toMatchSnapshot();
848
- // Add user
849
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
850
- await batch.save({
851
- sourceTable: usersTable,
852
- tag: storage.SaveOperationTag.INSERT,
853
- after: {
854
- id: 'user1',
855
- name: 'User 1'
856
- },
857
- afterReplicaId: 'user1'
858
- });
859
- await batch.commit('0/1');
860
- });
861
- const checkpoint2 = await getCheckpointLines(iter);
862
- expect(checkpoint2[0].checkpoint_diff?.updated_buckets?.map((b) => b.bucket)).toEqual([bucketRequest(syncRules, 'by_user["user1"]')]);
863
- expect(checkpoint2).toMatchSnapshot();
864
- }
865
- catch (e_9) {
866
- env_9.error = e_9;
867
- env_9.hasError = true;
868
- }
869
- finally {
870
- const result_9 = __disposeResources(env_9);
871
- if (result_9)
872
- await result_9;
873
- }
731
+ });
732
+ const bucketStorage = await f.getInstance(syncRules);
733
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
734
+ const usersTable = await test_utils.resolveTestTable(writer, 'users', ['id'], config, 1);
735
+ // Activate
736
+ await writer.markAllSnapshotDone('0/0');
737
+ await writer.keepalive('0/0');
738
+ const stream = sync.streamResponse({
739
+ syncContext,
740
+ bucketStorage,
741
+ syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
742
+ params: {
743
+ buckets: [],
744
+ include_checksum: true,
745
+ raw_data: true
746
+ },
747
+ tracker,
748
+ token: new JwtPayload({ sub: 'user1', exp: Date.now() / 1000 + 100 }),
749
+ isEncodingAsBson: false
750
+ });
751
+ const iter = stream[Symbol.asyncIterator]();
752
+ context.onTestFinished(() => {
753
+ iter.return?.();
754
+ });
755
+ // Initial empty checkpoint
756
+ const checkpoint1 = await getCheckpointLines(iter);
757
+ expect(checkpoint1[0].checkpoint?.buckets?.map((b) => b.bucket)).toEqual([]);
758
+ expect(checkpoint1).toMatchSnapshot();
759
+ // Add user
760
+ await writer.save({
761
+ sourceTable: usersTable,
762
+ tag: storage.SaveOperationTag.INSERT,
763
+ after: {
764
+ id: 'user1',
765
+ name: 'User 1'
766
+ },
767
+ afterReplicaId: 'user1'
768
+ });
769
+ await writer.commit('0/1');
770
+ const checkpoint2 = await getCheckpointLines(iter);
771
+ const { bucket } = test_utils.bucketRequest(syncRules, 'by_user["user1"]');
772
+ expect(checkpoint2[0].checkpoint_diff?.updated_buckets?.map((b) => b.bucket)).toEqual([bucket]);
773
+ expect(checkpoint2).toMatchSnapshot();
874
774
  });
875
775
  test('sync updates to data query only', async (context) => {
876
- const env_10 = { stack: [], error: void 0, hasError: false };
877
- try {
878
- const f = __addDisposableResource(env_10, await factory(), true);
879
- const syncRules = await updateSyncRules(f, {
880
- content: `bucket_definitions:
776
+ await using f = await factory();
777
+ const syncRules = await updateSyncRules(f, {
778
+ content: `bucket_definitions:
881
779
  by_user:
882
780
  parameters: select users.id as user_id from users where users.id = request.user_id()
883
781
  data:
884
782
  - select * from lists where user_id = bucket.user_id
885
783
  `
886
- });
887
- const usersTable = test_utils.makeTestTable('users', ['id']);
888
- const listsTable = test_utils.makeTestTable('lists', ['id']);
889
- const bucketStorage = await f.getInstance(syncRules);
890
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
891
- await batch.save({
892
- sourceTable: usersTable,
893
- tag: storage.SaveOperationTag.INSERT,
894
- after: {
895
- id: 'user1',
896
- name: 'User 1'
897
- },
898
- afterReplicaId: 'user1'
899
- });
900
- await batch.commit('0/1');
901
- });
902
- const stream = sync.streamResponse({
903
- syncContext,
904
- bucketStorage,
905
- syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
906
- params: {
907
- buckets: [],
908
- include_checksum: true,
909
- raw_data: true
910
- },
911
- tracker,
912
- token: new JwtPayload({ sub: 'user1', exp: Date.now() / 1000 + 100 }),
913
- isEncodingAsBson: false
914
- });
915
- const iter = stream[Symbol.asyncIterator]();
916
- context.onTestFinished(() => {
917
- iter.return?.();
918
- });
919
- const checkpoint1 = await getCheckpointLines(iter);
920
- expect(checkpoint1[0].checkpoint?.buckets?.map((b) => b.bucket)).toEqual([
921
- bucketRequest(syncRules, 'by_user["user1"]')
922
- ]);
923
- expect(checkpoint1).toMatchSnapshot();
924
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
925
- await batch.save({
926
- sourceTable: listsTable,
927
- tag: storage.SaveOperationTag.INSERT,
928
- after: {
929
- id: 'list1',
930
- user_id: 'user1',
931
- name: 'User 1'
932
- },
933
- afterReplicaId: 'list1'
934
- });
935
- await batch.commit('0/1');
936
- });
937
- const checkpoint2 = await getCheckpointLines(iter);
938
- expect(checkpoint2[0].checkpoint_diff?.updated_buckets?.map((b) => b.bucket)).toEqual([bucketRequest(syncRules, 'by_user["user1"]')]);
939
- expect(checkpoint2).toMatchSnapshot();
940
- }
941
- catch (e_10) {
942
- env_10.error = e_10;
943
- env_10.hasError = true;
944
- }
945
- finally {
946
- const result_10 = __disposeResources(env_10);
947
- if (result_10)
948
- await result_10;
949
- }
784
+ });
785
+ const bucketStorage = await f.getInstance(syncRules);
786
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
787
+ const usersTable = await test_utils.resolveTestTable(writer, 'users', ['id'], config, 1);
788
+ const listsTable = await test_utils.resolveTestTable(writer, 'lists', ['id'], config, 2);
789
+ await writer.markAllSnapshotDone('0/1');
790
+ await writer.save({
791
+ sourceTable: usersTable,
792
+ tag: storage.SaveOperationTag.INSERT,
793
+ after: {
794
+ id: 'user1',
795
+ name: 'User 1'
796
+ },
797
+ afterReplicaId: 'user1'
798
+ });
799
+ await writer.commit('0/1');
800
+ const stream = sync.streamResponse({
801
+ syncContext,
802
+ bucketStorage,
803
+ syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
804
+ params: {
805
+ buckets: [],
806
+ include_checksum: true,
807
+ raw_data: true
808
+ },
809
+ tracker,
810
+ token: new JwtPayload({ sub: 'user1', exp: Date.now() / 1000 + 100 }),
811
+ isEncodingAsBson: false
812
+ });
813
+ const iter = stream[Symbol.asyncIterator]();
814
+ context.onTestFinished(() => {
815
+ iter.return?.();
816
+ });
817
+ const { bucket } = bucketRequest(syncRules, 'by_user["user1"]');
818
+ const checkpoint1 = await getCheckpointLines(iter);
819
+ expect(checkpoint1[0].checkpoint?.buckets?.map((b) => b.bucket)).toEqual([bucket]);
820
+ expect(checkpoint1).toMatchSnapshot();
821
+ await writer.save({
822
+ sourceTable: listsTable,
823
+ tag: storage.SaveOperationTag.INSERT,
824
+ after: {
825
+ id: 'list1',
826
+ user_id: 'user1',
827
+ name: 'User 1'
828
+ },
829
+ afterReplicaId: 'list1'
830
+ });
831
+ await writer.commit('0/1');
832
+ const checkpoint2 = await getCheckpointLines(iter);
833
+ expect(checkpoint2[0].checkpoint_diff?.updated_buckets?.map((b) => b.bucket)).toEqual([bucket]);
834
+ expect(checkpoint2).toMatchSnapshot();
950
835
  });
951
836
  test('sync updates to parameter query + data', async (context) => {
952
- const env_11 = { stack: [], error: void 0, hasError: false };
953
- try {
954
- const f = __addDisposableResource(env_11, await factory(), true);
955
- const syncRules = await updateSyncRules(f, {
956
- content: `bucket_definitions:
837
+ await using f = await factory();
838
+ const syncRules = await updateSyncRules(f, {
839
+ content: `bucket_definitions:
957
840
  by_user:
958
841
  parameters: select users.id as user_id from users where users.id = request.user_id()
959
842
  data:
960
843
  - select * from lists where user_id = bucket.user_id
961
844
  `
962
- });
963
- const usersTable = test_utils.makeTestTable('users', ['id']);
964
- const listsTable = test_utils.makeTestTable('lists', ['id']);
965
- const bucketStorage = await f.getInstance(syncRules);
966
- // Activate
967
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
968
- await batch.keepalive('0/0');
969
- });
970
- const stream = sync.streamResponse({
971
- syncContext,
972
- bucketStorage,
973
- syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
974
- params: {
975
- buckets: [],
976
- include_checksum: true,
977
- raw_data: true
978
- },
979
- tracker,
980
- token: new JwtPayload({ sub: 'user1', exp: Date.now() / 1000 + 100 }),
981
- isEncodingAsBson: false
982
- });
983
- const iter = stream[Symbol.asyncIterator]();
984
- context.onTestFinished(() => {
985
- iter.return?.();
986
- });
987
- // Initial empty checkpoint
988
- expect(await getCheckpointLines(iter)).toMatchSnapshot();
989
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
990
- await batch.save({
991
- sourceTable: listsTable,
992
- tag: storage.SaveOperationTag.INSERT,
993
- after: {
994
- id: 'list1',
995
- user_id: 'user1',
996
- name: 'User 1'
997
- },
998
- afterReplicaId: 'list1'
999
- });
1000
- await batch.save({
1001
- sourceTable: usersTable,
1002
- tag: storage.SaveOperationTag.INSERT,
1003
- after: {
1004
- id: 'user1',
1005
- name: 'User 1'
1006
- },
1007
- afterReplicaId: 'user1'
1008
- });
1009
- await batch.commit('0/1');
1010
- });
1011
- const checkpoint2 = await getCheckpointLines(iter);
1012
- expect(checkpoint2[0].checkpoint_diff?.updated_buckets?.map((b) => b.bucket)).toEqual([bucketRequest(syncRules, 'by_user["user1"]')]);
1013
- expect(checkpoint2).toMatchSnapshot();
1014
- }
1015
- catch (e_11) {
1016
- env_11.error = e_11;
1017
- env_11.hasError = true;
1018
- }
1019
- finally {
1020
- const result_11 = __disposeResources(env_11);
1021
- if (result_11)
1022
- await result_11;
1023
- }
845
+ });
846
+ const bucketStorage = await f.getInstance(syncRules);
847
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
848
+ const usersTable = await test_utils.resolveTestTable(writer, 'users', ['id'], config, 1);
849
+ const listsTable = await test_utils.resolveTestTable(writer, 'lists', ['id'], config, 2);
850
+ // Activate
851
+ await writer.markAllSnapshotDone('0/0');
852
+ await writer.keepalive('0/0');
853
+ const stream = sync.streamResponse({
854
+ syncContext,
855
+ bucketStorage,
856
+ syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
857
+ params: {
858
+ buckets: [],
859
+ include_checksum: true,
860
+ raw_data: true
861
+ },
862
+ tracker,
863
+ token: new JwtPayload({ sub: 'user1', exp: Date.now() / 1000 + 100 }),
864
+ isEncodingAsBson: false
865
+ });
866
+ const iter = stream[Symbol.asyncIterator]();
867
+ context.onTestFinished(() => {
868
+ iter.return?.();
869
+ });
870
+ // Initial empty checkpoint
871
+ expect(await getCheckpointLines(iter)).toMatchSnapshot();
872
+ await writer.markAllSnapshotDone('0/1');
873
+ await writer.save({
874
+ sourceTable: listsTable,
875
+ tag: storage.SaveOperationTag.INSERT,
876
+ after: {
877
+ id: 'list1',
878
+ user_id: 'user1',
879
+ name: 'User 1'
880
+ },
881
+ afterReplicaId: 'list1'
882
+ });
883
+ await writer.save({
884
+ sourceTable: usersTable,
885
+ tag: storage.SaveOperationTag.INSERT,
886
+ after: {
887
+ id: 'user1',
888
+ name: 'User 1'
889
+ },
890
+ afterReplicaId: 'user1'
891
+ });
892
+ await writer.commit('0/1');
893
+ const { bucket } = test_utils.bucketRequest(syncRules, 'by_user["user1"]');
894
+ const checkpoint2 = await getCheckpointLines(iter);
895
+ expect(checkpoint2[0].checkpoint_diff?.updated_buckets?.map((b) => b.bucket)).toEqual([bucket]);
896
+ expect(checkpoint2).toMatchSnapshot();
1024
897
  });
1025
898
  test('expiring token', async (context) => {
1026
- const env_12 = { stack: [], error: void 0, hasError: false };
1027
- try {
1028
- const f = __addDisposableResource(env_12, await factory(), true);
1029
- const syncRules = await updateSyncRules(f, {
1030
- content: BASIC_SYNC_RULES
1031
- });
1032
- const bucketStorage = await f.getInstance(syncRules);
1033
- // Activate
1034
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
1035
- await batch.keepalive('0/0');
1036
- });
1037
- const exp = Date.now() / 1000 + 0.1;
1038
- const stream = sync.streamResponse({
1039
- syncContext,
1040
- bucketStorage,
1041
- syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
1042
- params: {
1043
- buckets: [],
1044
- include_checksum: true,
1045
- raw_data: true
1046
- },
1047
- tracker,
1048
- token: new JwtPayload({ sub: '', exp: exp }),
1049
- isEncodingAsBson: false
1050
- });
1051
- const iter = stream[Symbol.asyncIterator]();
1052
- context.onTestFinished(() => {
1053
- iter.return?.();
1054
- });
1055
- const checkpoint = await getCheckpointLines(iter);
1056
- expect(checkpoint).toMatchSnapshot();
1057
- const expLines = await getCheckpointLines(iter);
1058
- expect(expLines).toMatchSnapshot();
1059
- }
1060
- catch (e_12) {
1061
- env_12.error = e_12;
1062
- env_12.hasError = true;
1063
- }
1064
- finally {
1065
- const result_12 = __disposeResources(env_12);
1066
- if (result_12)
1067
- await result_12;
1068
- }
899
+ await using f = await factory();
900
+ const syncRules = await updateSyncRules(f, {
901
+ content: BASIC_SYNC_RULES
902
+ });
903
+ const bucketStorage = await f.getInstance(syncRules);
904
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
905
+ // Activate
906
+ await writer.markAllSnapshotDone('0/0');
907
+ await writer.keepalive('0/0');
908
+ const exp = Date.now() / 1000 + 0.1;
909
+ const stream = sync.streamResponse({
910
+ syncContext,
911
+ bucketStorage,
912
+ syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
913
+ params: {
914
+ buckets: [],
915
+ include_checksum: true,
916
+ raw_data: true
917
+ },
918
+ tracker,
919
+ token: new JwtPayload({ sub: '', exp: exp }),
920
+ isEncodingAsBson: false
921
+ });
922
+ const iter = stream[Symbol.asyncIterator]();
923
+ context.onTestFinished(() => {
924
+ iter.return?.();
925
+ });
926
+ const checkpoint = await getCheckpointLines(iter);
927
+ expect(checkpoint).toMatchSnapshot();
928
+ const expLines = await getCheckpointLines(iter);
929
+ expect(expLines).toMatchSnapshot();
1069
930
  });
1070
931
  test('compacting data - invalidate checkpoint', async (context) => {
1071
- const env_13 = { stack: [], error: void 0, hasError: false };
1072
- try {
1073
- // This tests a case of a compact operation invalidating a checkpoint in the
1074
- // middle of syncing data.
1075
- // This is expected to be rare in practice, but it is important to handle
1076
- // this case correctly to maintain consistency on the client.
1077
- const f = __addDisposableResource(env_13, await factory(), true);
1078
- const syncRules = await updateSyncRules(f, {
1079
- content: BASIC_SYNC_RULES
1080
- });
1081
- const bucketStorage = await f.getInstance(syncRules);
1082
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
1083
- await batch.save({
1084
- sourceTable: TEST_TABLE,
1085
- tag: storage.SaveOperationTag.INSERT,
1086
- after: {
1087
- id: 't1',
1088
- description: 'Test 1'
1089
- },
1090
- afterReplicaId: 't1'
1091
- });
1092
- await batch.save({
1093
- sourceTable: TEST_TABLE,
1094
- tag: storage.SaveOperationTag.INSERT,
1095
- after: {
1096
- id: 't2',
1097
- description: 'Test 2'
1098
- },
1099
- afterReplicaId: 't2'
1100
- });
1101
- await batch.commit('0/1');
1102
- });
1103
- const stream = sync.streamResponse({
1104
- syncContext,
1105
- bucketStorage,
1106
- syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
1107
- params: {
1108
- buckets: [],
1109
- include_checksum: true,
1110
- raw_data: true
1111
- },
1112
- tracker,
1113
- token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 10 }),
1114
- isEncodingAsBson: false
1115
- });
1116
- const iter = stream[Symbol.asyncIterator]();
1117
- context.onTestFinished(() => {
1118
- iter.return?.();
1119
- });
1120
- // Only consume the first "checkpoint" message, and pause before receiving data.
1121
- const lines = await consumeIterator(iter, { consume: false, isDone: (line) => line?.checkpoint != null });
1122
- expect(lines).toMatchSnapshot();
1123
- expect(lines[0]).toEqual({
1124
- checkpoint: expect.objectContaining({
1125
- last_op_id: '2'
1126
- })
1127
- });
1128
- // Now we save additional data AND compact before continuing.
1129
- // This invalidates the checkpoint we've received above.
1130
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
1131
- await batch.save({
1132
- sourceTable: TEST_TABLE,
1133
- tag: storage.SaveOperationTag.UPDATE,
1134
- after: {
1135
- id: 't1',
1136
- description: 'Test 1b'
1137
- },
1138
- afterReplicaId: 't1'
1139
- });
1140
- await batch.save({
1141
- sourceTable: TEST_TABLE,
1142
- tag: storage.SaveOperationTag.UPDATE,
1143
- after: {
1144
- id: 't2',
1145
- description: 'Test 2b'
1146
- },
1147
- afterReplicaId: 't2'
1148
- });
1149
- await batch.commit('0/2');
1150
- });
1151
- await bucketStorage.compact({
1152
- minBucketChanges: 1,
1153
- minChangeRatio: 0
1154
- });
1155
- const lines2 = await getCheckpointLines(iter, { consume: true });
1156
- // Snapshot test checks for changes in general.
1157
- // The tests after that documents the specific things we're looking for
1158
- // in this test.
1159
- expect(lines2).toMatchSnapshot();
1160
- expect(lines2[0]).toEqual({
1161
- data: expect.objectContaining({
1162
- has_more: false,
1163
- data: [
1164
- // The first two ops have been replaced by a single CLEAR op
1165
- expect.objectContaining({
1166
- op: 'CLEAR'
1167
- })
1168
- ]
1169
- })
1170
- });
1171
- // Note: No checkpoint_complete here, since the checkpoint has been
1172
- // invalidated by the CLEAR op.
1173
- expect(lines2[1]).toEqual({
1174
- checkpoint_diff: expect.objectContaining({
1175
- last_op_id: '4'
1176
- })
1177
- });
1178
- expect(lines2[2]).toEqual({
1179
- data: expect.objectContaining({
1180
- has_more: false,
1181
- data: [
1182
- expect.objectContaining({
1183
- op: 'PUT'
1184
- }),
1185
- expect.objectContaining({
1186
- op: 'PUT'
1187
- })
1188
- ]
1189
- })
1190
- });
1191
- // Now we get a checkpoint_complete
1192
- expect(lines2[3]).toEqual({
1193
- checkpoint_complete: expect.objectContaining({
1194
- last_op_id: '4'
1195
- })
1196
- });
1197
- }
1198
- catch (e_13) {
1199
- env_13.error = e_13;
1200
- env_13.hasError = true;
1201
- }
1202
- finally {
1203
- const result_13 = __disposeResources(env_13);
1204
- if (result_13)
1205
- await result_13;
1206
- }
932
+ // This tests a case of a compact operation invalidating a checkpoint in the
933
+ // middle of syncing data.
934
+ // This is expected to be rare in practice, but it is important to handle
935
+ // this case correctly to maintain consistency on the client.
936
+ await using f = await factory();
937
+ const syncRules = await updateSyncRules(f, {
938
+ content: BASIC_SYNC_RULES
939
+ });
940
+ const bucketStorage = await f.getInstance(syncRules);
941
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
942
+ const testTable = await test_utils.resolveTestTable(writer, 'test', ['id'], config);
943
+ await writer.markAllSnapshotDone('0/1');
944
+ await writer.save({
945
+ sourceTable: testTable,
946
+ tag: storage.SaveOperationTag.INSERT,
947
+ after: {
948
+ id: 't1',
949
+ description: 'Test 1'
950
+ },
951
+ afterReplicaId: 't1'
952
+ });
953
+ await writer.save({
954
+ sourceTable: testTable,
955
+ tag: storage.SaveOperationTag.INSERT,
956
+ after: {
957
+ id: 't2',
958
+ description: 'Test 2'
959
+ },
960
+ afterReplicaId: 't2'
961
+ });
962
+ await writer.commit('0/1');
963
+ const stream = sync.streamResponse({
964
+ syncContext,
965
+ bucketStorage,
966
+ syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
967
+ params: {
968
+ buckets: [],
969
+ include_checksum: true,
970
+ raw_data: true
971
+ },
972
+ tracker,
973
+ token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 10 }),
974
+ isEncodingAsBson: false
975
+ });
976
+ const iter = stream[Symbol.asyncIterator]();
977
+ context.onTestFinished(() => {
978
+ iter.return?.();
979
+ });
980
+ // Only consume the first "checkpoint" message, and pause before receiving data.
981
+ const lines = await consumeIterator(iter, { consume: false, isDone: (line) => line?.checkpoint != null });
982
+ expect(lines).toMatchSnapshot();
983
+ expect(lines[0]).toEqual({
984
+ checkpoint: expect.objectContaining({
985
+ last_op_id: '2'
986
+ })
987
+ });
988
+ // Now we save additional data AND compact before continuing.
989
+ // This invalidates the checkpoint we've received above.
990
+ await writer.markAllSnapshotDone('0/1');
991
+ await writer.save({
992
+ sourceTable: testTable,
993
+ tag: storage.SaveOperationTag.UPDATE,
994
+ after: {
995
+ id: 't1',
996
+ description: 'Test 1b'
997
+ },
998
+ afterReplicaId: 't1'
999
+ });
1000
+ await writer.save({
1001
+ sourceTable: testTable,
1002
+ tag: storage.SaveOperationTag.UPDATE,
1003
+ after: {
1004
+ id: 't2',
1005
+ description: 'Test 2b'
1006
+ },
1007
+ afterReplicaId: 't2'
1008
+ });
1009
+ await writer.commit('0/2');
1010
+ await bucketStorage.compact({
1011
+ minBucketChanges: 1,
1012
+ minChangeRatio: 0
1013
+ });
1014
+ const lines2 = await getCheckpointLines(iter, { consume: true });
1015
+ // Snapshot test checks for changes in general.
1016
+ // The tests after that documents the specific things we're looking for
1017
+ // in this test.
1018
+ expect(lines2).toMatchSnapshot();
1019
+ expect(lines2[0]).toEqual({
1020
+ data: expect.objectContaining({
1021
+ has_more: false,
1022
+ data: [
1023
+ // The first two ops have been replaced by a single CLEAR op
1024
+ expect.objectContaining({
1025
+ op: 'CLEAR'
1026
+ })
1027
+ ]
1028
+ })
1029
+ });
1030
+ // Note: No checkpoint_complete here, since the checkpoint has been
1031
+ // invalidated by the CLEAR op.
1032
+ expect(lines2[1]).toEqual({
1033
+ checkpoint_diff: expect.objectContaining({
1034
+ last_op_id: '4'
1035
+ })
1036
+ });
1037
+ expect(lines2[2]).toEqual({
1038
+ data: expect.objectContaining({
1039
+ has_more: false,
1040
+ data: [
1041
+ expect.objectContaining({
1042
+ op: 'PUT'
1043
+ }),
1044
+ expect.objectContaining({
1045
+ op: 'PUT'
1046
+ })
1047
+ ]
1048
+ })
1049
+ });
1050
+ // Now we get a checkpoint_complete
1051
+ expect(lines2[3]).toEqual({
1052
+ checkpoint_complete: expect.objectContaining({
1053
+ last_op_id: '4'
1054
+ })
1055
+ });
1207
1056
  });
1208
1057
  test('write checkpoint', async () => {
1209
- const env_14 = { stack: [], error: void 0, hasError: false };
1210
- try {
1211
- const f = __addDisposableResource(env_14, await factory(), true);
1058
+ await using f = await factory();
1059
+ const syncRules = await updateSyncRules(f, {
1060
+ content: BASIC_SYNC_RULES
1061
+ });
1062
+ const bucketStorage = f.getInstance(syncRules);
1063
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
1064
+ await writer.markAllSnapshotDone('0/1');
1065
+ // <= the managed write checkpoint LSN below
1066
+ await writer.commit('0/1');
1067
+ const checkpoint = await bucketStorage.createManagedWriteCheckpoint({
1068
+ user_id: 'test',
1069
+ heads: { '1': '1/0' }
1070
+ });
1071
+ const params = {
1072
+ syncContext,
1073
+ bucketStorage,
1074
+ syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
1075
+ params: {
1076
+ buckets: [],
1077
+ include_checksum: true,
1078
+ raw_data: true
1079
+ },
1080
+ tracker,
1081
+ token: new JwtPayload({ sub: 'test', exp: Date.now() / 1000 + 10 }),
1082
+ isEncodingAsBson: false
1083
+ };
1084
+ const stream1 = sync.streamResponse(params);
1085
+ const lines1 = await consumeCheckpointLines(stream1);
1086
+ // If write checkpoints are not correctly filtered, this may already
1087
+ // contain the write checkpoint.
1088
+ expect(lines1[0]).toMatchObject({
1089
+ checkpoint: expect.objectContaining({
1090
+ last_op_id: '0',
1091
+ write_checkpoint: undefined
1092
+ })
1093
+ });
1094
+ await writer.markAllSnapshotDone('0/1');
1095
+ // must be >= the managed write checkpoint LSN
1096
+ await writer.commit('1/0');
1097
+ // At this point the LSN has advanced, so the write checkpoint should be
1098
+ // included in the next checkpoint message.
1099
+ const stream2 = sync.streamResponse(params);
1100
+ const lines2 = await consumeCheckpointLines(stream2);
1101
+ expect(lines2[0]).toMatchObject({
1102
+ checkpoint: expect.objectContaining({
1103
+ last_op_id: '0',
1104
+ write_checkpoint: `${checkpoint}`
1105
+ })
1106
+ });
1107
+ });
1108
+ test('encodes sync rules id in buckets for streams', async () => {
1109
+ await using f = await factory();
1110
+ // This test relies making an actual update to sync rules to test the different bucket names.
1111
+ // The actual naming scheme may change, as long as the two buckets have different names.
1112
+ const rules = [
1113
+ `
1114
+ streams:
1115
+ test:
1116
+ auto_subscribe: true
1117
+ query: SELECT * FROM test;
1118
+
1119
+ config:
1120
+ edition: 2
1121
+ `,
1122
+ `
1123
+ streams:
1124
+ test2:
1125
+ auto_subscribe: true
1126
+ query: SELECT * FROM test WHERE 1;
1127
+
1128
+ config:
1129
+ edition: 2
1130
+ `
1131
+ ];
1132
+ for (let i = 0; i < 2; i++) {
1212
1133
  const syncRules = await updateSyncRules(f, {
1213
- content: BASIC_SYNC_RULES
1134
+ content: rules[i]
1214
1135
  });
1215
1136
  const bucketStorage = f.getInstance(syncRules);
1216
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
1217
- // <= the managed write checkpoint LSN below
1218
- await batch.commit('0/1');
1219
- });
1220
- const checkpoint = await bucketStorage.createManagedWriteCheckpoint({
1221
- user_id: 'test',
1222
- heads: { '1': '1/0' }
1137
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
1138
+ const testTable = await test_utils.resolveTestTable(writer, 'test', ['id'], config, i + 1);
1139
+ await writer.markAllSnapshotDone('0/1');
1140
+ await writer.save({
1141
+ sourceTable: testTable,
1142
+ tag: storage.SaveOperationTag.INSERT,
1143
+ after: {
1144
+ id: 't1',
1145
+ description: 'Test 1'
1146
+ },
1147
+ afterReplicaId: 't1'
1223
1148
  });
1224
- const params = {
1149
+ await writer.commit('0/1');
1150
+ const stream = sync.streamResponse({
1225
1151
  syncContext,
1226
- bucketStorage,
1152
+ bucketStorage: bucketStorage,
1227
1153
  syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
1228
1154
  params: {
1229
1155
  buckets: [],
@@ -1231,99 +1157,11 @@ bucket_definitions:
1231
1157
  raw_data: true
1232
1158
  },
1233
1159
  tracker,
1234
- token: new JwtPayload({ sub: 'test', exp: Date.now() / 1000 + 10 }),
1160
+ token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 10 }),
1235
1161
  isEncodingAsBson: false
1236
- };
1237
- const stream1 = sync.streamResponse(params);
1238
- const lines1 = await consumeCheckpointLines(stream1);
1239
- // If write checkpoints are not correctly filtered, this may already
1240
- // contain the write checkpoint.
1241
- expect(lines1[0]).toMatchObject({
1242
- checkpoint: expect.objectContaining({
1243
- last_op_id: '0',
1244
- write_checkpoint: undefined
1245
- })
1246
- });
1247
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
1248
- // must be >= the managed write checkpoint LSN
1249
- await batch.commit('1/0');
1250
1162
  });
1251
- // At this point the LSN has advanced, so the write checkpoint should be
1252
- // included in the next checkpoint message.
1253
- const stream2 = sync.streamResponse(params);
1254
- const lines2 = await consumeCheckpointLines(stream2);
1255
- expect(lines2[0]).toMatchObject({
1256
- checkpoint: expect.objectContaining({
1257
- last_op_id: '0',
1258
- write_checkpoint: `${checkpoint}`
1259
- })
1260
- });
1261
- }
1262
- catch (e_14) {
1263
- env_14.error = e_14;
1264
- env_14.hasError = true;
1265
- }
1266
- finally {
1267
- const result_14 = __disposeResources(env_14);
1268
- if (result_14)
1269
- await result_14;
1270
- }
1271
- });
1272
- test('encodes sync rules id in buckes for streams', async () => {
1273
- const env_15 = { stack: [], error: void 0, hasError: false };
1274
- try {
1275
- const f = __addDisposableResource(env_15, await factory(), true);
1276
- const rules = `
1277
- streams:
1278
- test:
1279
- auto_subscribe: true
1280
- query: SELECT * FROM test;
1281
-
1282
- config:
1283
- edition: 2
1284
- `;
1285
- for (let i = 0; i < 2; i++) {
1286
- const syncRules = await updateSyncRules(f, {
1287
- content: rules
1288
- });
1289
- const bucketStorage = f.getInstance(syncRules);
1290
- await bucketStorage.startBatch(test_utils.BATCH_OPTIONS, async (batch) => {
1291
- await batch.save({
1292
- sourceTable: TEST_TABLE,
1293
- tag: storage.SaveOperationTag.INSERT,
1294
- after: {
1295
- id: 't1',
1296
- description: 'Test 1'
1297
- },
1298
- afterReplicaId: 't1'
1299
- });
1300
- await batch.commit('0/1');
1301
- });
1302
- const stream = sync.streamResponse({
1303
- syncContext,
1304
- bucketStorage: bucketStorage,
1305
- syncRules: bucketStorage.getParsedSyncRules(test_utils.PARSE_OPTIONS),
1306
- params: {
1307
- buckets: [],
1308
- include_checksum: true,
1309
- raw_data: true
1310
- },
1311
- tracker,
1312
- token: new JwtPayload({ sub: '', exp: Date.now() / 1000 + 10 }),
1313
- isEncodingAsBson: false
1314
- });
1315
- const lines = await consumeCheckpointLines(stream);
1316
- expect(lines).toMatchSnapshot();
1317
- }
1318
- }
1319
- catch (e_15) {
1320
- env_15.error = e_15;
1321
- env_15.hasError = true;
1322
- }
1323
- finally {
1324
- const result_15 = __disposeResources(env_15);
1325
- if (result_15)
1326
- await result_15;
1163
+ const lines = await consumeCheckpointLines(stream);
1164
+ expect(lines).toMatchSnapshot();
1327
1165
  }
1328
1166
  });
1329
1167
  }