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

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 (169) hide show
  1. package/CHANGELOG.md +114 -5
  2. package/dist/api/diagnostics.js +7 -2
  3. package/dist/api/diagnostics.js.map +1 -1
  4. package/dist/entry/commands/compact-action.js +29 -25
  5. package/dist/entry/commands/compact-action.js.map +1 -1
  6. package/dist/entry/commands/config-command.js +1 -1
  7. package/dist/entry/commands/config-command.js.map +1 -1
  8. package/dist/metrics/metrics-interfaces.d.ts +5 -1
  9. package/dist/metrics/metrics-interfaces.js.map +1 -1
  10. package/dist/metrics/open-telemetry/MetricAttributeFilteringExporter.d.ts +36 -0
  11. package/dist/metrics/open-telemetry/MetricAttributeFilteringExporter.js +70 -0
  12. package/dist/metrics/open-telemetry/MetricAttributeFilteringExporter.js.map +1 -0
  13. package/dist/metrics/open-telemetry/OpenTelemetryMetricsFactory.js +6 -1
  14. package/dist/metrics/open-telemetry/OpenTelemetryMetricsFactory.js.map +1 -1
  15. package/dist/metrics/open-telemetry/util.js +7 -3
  16. package/dist/metrics/open-telemetry/util.js.map +1 -1
  17. package/dist/migrations/PowerSyncMigrationManager.js +2 -1
  18. package/dist/migrations/PowerSyncMigrationManager.js.map +1 -1
  19. package/dist/replication/AbstractReplicator.d.ts +5 -0
  20. package/dist/replication/AbstractReplicator.js +31 -13
  21. package/dist/replication/AbstractReplicator.js.map +1 -1
  22. package/dist/replication/ReplicationModule.d.ts +0 -7
  23. package/dist/replication/ReplicationModule.js +0 -1
  24. package/dist/replication/ReplicationModule.js.map +1 -1
  25. package/dist/routes/configure-fastify.d.ts +12 -3
  26. package/dist/routes/endpoints/admin.d.ts +24 -6
  27. package/dist/routes/endpoints/admin.js +17 -11
  28. package/dist/routes/endpoints/admin.js.map +1 -1
  29. package/dist/routes/endpoints/socket-route.js +7 -5
  30. package/dist/routes/endpoints/socket-route.js.map +1 -1
  31. package/dist/routes/endpoints/sync-rules.js +18 -10
  32. package/dist/routes/endpoints/sync-rules.js.map +1 -1
  33. package/dist/storage/BucketStorageBatch.d.ts +2 -1
  34. package/dist/storage/BucketStorageBatch.js.map +1 -1
  35. package/dist/storage/BucketStorageFactory.d.ts +49 -6
  36. package/dist/storage/BucketStorageFactory.js +25 -8
  37. package/dist/storage/BucketStorageFactory.js.map +1 -1
  38. package/dist/storage/PersistedReplicationStream.d.ts +2 -1
  39. package/dist/storage/PersistedReplicationStream.js.map +1 -1
  40. package/dist/storage/PersistedSyncConfigContent.d.ts +6 -4
  41. package/dist/storage/PersistedSyncConfigContent.js +34 -14
  42. package/dist/storage/PersistedSyncConfigContent.js.map +1 -1
  43. package/dist/storage/ReplicationEventPayload.d.ts +6 -1
  44. package/dist/storage/SourceEntity.d.ts +7 -2
  45. package/dist/storage/SourceTable.d.ts +37 -6
  46. package/dist/storage/SourceTable.js +42 -10
  47. package/dist/storage/SourceTable.js.map +1 -1
  48. package/dist/storage/SourceTableReconciler.d.ts +83 -0
  49. package/dist/storage/SourceTableReconciler.js +95 -0
  50. package/dist/storage/SourceTableReconciler.js.map +1 -0
  51. package/dist/storage/StorageEngine.d.ts +4 -0
  52. package/dist/storage/StorageEngine.js +7 -1
  53. package/dist/storage/StorageEngine.js.map +1 -1
  54. package/dist/storage/StorageProvider.d.ts +8 -0
  55. package/dist/storage/StorageVersionConfig.d.ts +4 -0
  56. package/dist/storage/StorageVersionConfig.js +10 -1
  57. package/dist/storage/StorageVersionConfig.js.map +1 -1
  58. package/dist/storage/SyncConfigParser.d.ts +44 -0
  59. package/dist/storage/SyncConfigParser.js +70 -0
  60. package/dist/storage/SyncConfigParser.js.map +1 -0
  61. package/dist/storage/SyncRulesBucketStorage.d.ts +48 -8
  62. package/dist/storage/SyncRulesBucketStorage.js.map +1 -1
  63. package/dist/storage/WriteCheckpointAPI.d.ts +25 -3
  64. package/dist/storage/WriteCheckpointAPI.js.map +1 -1
  65. package/dist/storage/implementation/BucketDefinitionMapping.d.ts +23 -7
  66. package/dist/storage/implementation/BucketDefinitionMapping.js +88 -14
  67. package/dist/storage/implementation/BucketDefinitionMapping.js.map +1 -1
  68. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js +9 -5
  69. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js.map +1 -1
  70. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js +9 -1
  71. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js.map +1 -1
  72. package/dist/storage/storage-index.d.ts +2 -0
  73. package/dist/storage/storage-index.js +2 -0
  74. package/dist/storage/storage-index.js.map +1 -1
  75. package/dist/storage/storage-metrics.js +120 -4
  76. package/dist/storage/storage-metrics.js.map +1 -1
  77. package/dist/sync/BucketChecksumState.d.ts +2 -2
  78. package/dist/sync/BucketChecksumState.js +5 -4
  79. package/dist/sync/BucketChecksumState.js.map +1 -1
  80. package/dist/sync/sync.js +37 -9
  81. package/dist/sync/sync.js.map +1 -1
  82. package/dist/sync/util.d.ts +1 -1
  83. package/dist/sync/util.js +13 -1
  84. package/dist/sync/util.js.map +1 -1
  85. package/dist/system/ServiceContext.d.ts +20 -0
  86. package/dist/system/ServiceContext.js +29 -1
  87. package/dist/system/ServiceContext.js.map +1 -1
  88. package/dist/util/config/compound-config-collector.js +5 -0
  89. package/dist/util/config/compound-config-collector.js.map +1 -1
  90. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js +1 -0
  91. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js.map +1 -1
  92. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js +1 -0
  93. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js.map +1 -1
  94. package/dist/util/config/sync-rules/sync-rules-provider.d.ts +2 -0
  95. package/dist/util/config/sync-rules/sync-rules-provider.js +3 -0
  96. package/dist/util/config/sync-rules/sync-rules-provider.js.map +1 -1
  97. package/dist/util/config/types.d.ts +1 -0
  98. package/dist/util/param-logging.d.ts +5 -2
  99. package/dist/util/param-logging.js +17 -9
  100. package/dist/util/param-logging.js.map +1 -1
  101. package/dist/util/protocol-types.d.ts +11 -11
  102. package/dist/util/protocol-types.js +6 -5
  103. package/dist/util/protocol-types.js.map +1 -1
  104. package/dist/util/utils.d.ts +2 -1
  105. package/dist/util/utils.js +16 -1
  106. package/dist/util/utils.js.map +1 -1
  107. package/package.json +6 -5
  108. package/src/api/diagnostics.ts +8 -2
  109. package/src/entry/commands/compact-action.ts +33 -25
  110. package/src/entry/commands/config-command.ts +1 -1
  111. package/src/metrics/metrics-interfaces.ts +6 -1
  112. package/src/metrics/open-telemetry/MetricAttributeFilteringExporter.ts +85 -0
  113. package/src/metrics/open-telemetry/OpenTelemetryMetricsFactory.ts +7 -2
  114. package/src/metrics/open-telemetry/util.ts +7 -3
  115. package/src/migrations/PowerSyncMigrationManager.ts +2 -1
  116. package/src/replication/AbstractReplicator.ts +42 -13
  117. package/src/replication/ReplicationModule.ts +0 -10
  118. package/src/routes/endpoints/admin.ts +17 -17
  119. package/src/routes/endpoints/socket-route.ts +9 -6
  120. package/src/routes/endpoints/sync-rules.ts +21 -12
  121. package/src/storage/BucketStorageBatch.ts +2 -1
  122. package/src/storage/BucketStorageFactory.ts +77 -14
  123. package/src/storage/PersistedReplicationStream.ts +2 -1
  124. package/src/storage/PersistedSyncConfigContent.ts +42 -19
  125. package/src/storage/ReplicationEventPayload.ts +6 -1
  126. package/src/storage/SourceEntity.ts +6 -2
  127. package/src/storage/SourceTable.ts +68 -11
  128. package/src/storage/SourceTableReconciler.ts +188 -0
  129. package/src/storage/StorageEngine.ts +10 -1
  130. package/src/storage/StorageProvider.ts +8 -0
  131. package/src/storage/StorageVersionConfig.ts +11 -1
  132. package/src/storage/SyncConfigParser.ts +121 -0
  133. package/src/storage/SyncRulesBucketStorage.ts +56 -8
  134. package/src/storage/WriteCheckpointAPI.ts +32 -3
  135. package/src/storage/implementation/BucketDefinitionMapping.ts +120 -17
  136. package/src/storage/implementation/IncrementalReprocessingCompatibility.ts +14 -5
  137. package/src/storage/implementation/IncrementalReprocessingSyncConfigLog.ts +22 -5
  138. package/src/storage/storage-index.ts +2 -0
  139. package/src/storage/storage-metrics.ts +154 -8
  140. package/src/sync/BucketChecksumState.ts +8 -5
  141. package/src/sync/sync.ts +40 -11
  142. package/src/sync/util.ts +25 -9
  143. package/src/system/ServiceContext.ts +47 -1
  144. package/src/util/config/compound-config-collector.ts +6 -0
  145. package/src/util/config/sync-rules/impl/base64-sync-rules-collector.ts +1 -0
  146. package/src/util/config/sync-rules/impl/filesystem-sync-rules-collector.ts +1 -0
  147. package/src/util/config/sync-rules/sync-rules-provider.ts +5 -0
  148. package/src/util/config/types.ts +1 -0
  149. package/src/util/param-logging.ts +21 -14
  150. package/src/util/protocol-types.ts +8 -7
  151. package/src/util/utils.ts +15 -1
  152. package/test/src/AbstractReplicator.test.ts +62 -0
  153. package/test/src/MetricAttributeFilteringExporter.test.ts +96 -0
  154. package/test/src/PersistedSyncConfigContent.test.ts +154 -0
  155. package/test/src/SyncConfigParser.test.ts +330 -0
  156. package/test/src/broadcast_iterable.test.ts +26 -8
  157. package/test/src/config.test.ts +40 -0
  158. package/test/src/diagnostics.test.ts +48 -0
  159. package/test/src/routes/admin.test.ts +30 -2
  160. package/test/src/routes/mocks.ts +2 -0
  161. package/test/src/routes/stream.test.ts +123 -2
  162. package/test/src/source-table-reconciler.test.ts +244 -0
  163. package/test/src/storage/SourceTable.test.ts +4 -1
  164. package/test/src/storage-metrics.test.ts +148 -0
  165. package/test/src/sync/BucketChecksumState.test.ts +195 -6
  166. package/test/src/sync/util.test.ts +34 -0
  167. package/test/src/util/param-logging.test.ts +59 -0
  168. package/test/src/util/utils.test.ts +23 -0
  169. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,148 @@
1
+ import { MetricsEngine } from '@/metrics/MetricsEngine.js';
2
+ import {
3
+ MetricMetadata,
4
+ MetricsFactory,
5
+ ObservableGauge,
6
+ ObservableGaugeObservation
7
+ } from '@/metrics/metrics-interfaces.js';
8
+ import { BucketStorageFactory, StorageMetrics, StorageSyncConfigMetrics } from '@/storage/BucketStorageFactory.js';
9
+ import { createCoreStorageMetrics, initializeCoreStorageMetrics } from '@/storage/storage-metrics.js';
10
+ import { StorageMetric } from '@powersync/service-types';
11
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
12
+
13
+ type ValueProvider = () => Promise<number | ObservableGaugeObservation[] | undefined>;
14
+
15
+ function testEngine() {
16
+ const providers = new Map<string, ValueProvider>();
17
+ const factory: MetricsFactory = {
18
+ createCounter: () => ({ add: () => {} }),
19
+ createUpDownCounter: () => ({ add: () => {} }),
20
+ createObservableGauge: (metadata: MetricMetadata): ObservableGauge => ({
21
+ setValueProvider: (valueProvider) => providers.set(metadata.name, valueProvider)
22
+ })
23
+ };
24
+ const engine = new MetricsEngine({ factory, disable_telemetry_sharing: true });
25
+ createCoreStorageMetrics(engine);
26
+ return { engine, providers };
27
+ }
28
+
29
+ function syncConfigMetrics(id: string, state: string, bytes: number, versionLabel?: string): StorageSyncConfigMetrics {
30
+ return {
31
+ sync_config_id: id,
32
+ sync_config_state: state,
33
+ version_label: versionLabel,
34
+ attributed_bucket_data_bytes: bytes,
35
+ attributed_parameter_indexes_bytes: bytes,
36
+ attributed_source_records_bytes: bytes,
37
+ attributed_object_storage_bytes: bytes
38
+ };
39
+ }
40
+
41
+ function storageMetrics(sync_config_metrics: StorageSyncConfigMetrics[]): StorageMetrics {
42
+ return {
43
+ operations_size_bytes: 0,
44
+ parameters_size_bytes: 0,
45
+ replication_size_bytes: 0,
46
+ object_storage_size_bytes: 0,
47
+ sync_config_metrics
48
+ };
49
+ }
50
+
51
+ describe('storage metrics', () => {
52
+ beforeEach(() => {
53
+ vi.useFakeTimers();
54
+ vi.setSystemTime(0);
55
+ });
56
+
57
+ afterEach(() => {
58
+ vi.useRealTimers();
59
+ });
60
+
61
+ it('reports retired sync configs as zero, then stops reporting them', async () => {
62
+ let current = storageMetrics([syncConfigMetrics('config-a', 'ACTIVE', 100)]);
63
+ const storage = {
64
+ getStorageMetrics: async () => current
65
+ } as unknown as BucketStorageFactory;
66
+
67
+ const { engine, providers } = testEngine();
68
+ initializeCoreStorageMetrics(engine, storage);
69
+ const provider = providers.get(StorageMetric.ATTRIBUTED_BUCKET_DATA_BYTES)!;
70
+
71
+ expect(await provider()).toEqual([
72
+ { value: 100, attributes: { sync_config_id: 'config-a', sync_config_state: 'ACTIVE' } }
73
+ ]);
74
+
75
+ // The sync config is pruned. Its series must go to zero rather than keep its last value,
76
+ // since the SDK carries the last reported value forward under cumulative temporality.
77
+ current = storageMetrics([syncConfigMetrics('config-b', 'ACTIVE', 50)]);
78
+ vi.setSystemTime(61_000);
79
+
80
+ expect(await provider()).toEqual([
81
+ { value: 50, attributes: { sync_config_id: 'config-b', sync_config_state: 'ACTIVE' } },
82
+ { value: 0, attributes: { sync_config_id: 'config-a', sync_config_state: 'ACTIVE' } }
83
+ ]);
84
+
85
+ // Once every reader has had a chance to observe the zero, stop reporting it entirely.
86
+ vi.setSystemTime(61_000 + 16 * 60_000);
87
+
88
+ expect(await provider()).toEqual([
89
+ { value: 50, attributes: { sync_config_id: 'config-b', sync_config_state: 'ACTIVE' } }
90
+ ]);
91
+ });
92
+
93
+ it('treats a state transition as a retired attribute set', async () => {
94
+ let current = storageMetrics([syncConfigMetrics('config-a', 'PROCESSING', 100, 'v1')]);
95
+ const storage = {
96
+ getStorageMetrics: async () => current
97
+ } as unknown as BucketStorageFactory;
98
+
99
+ const { engine, providers } = testEngine();
100
+ initializeCoreStorageMetrics(engine, storage);
101
+ const provider = providers.get(StorageMetric.ATTRIBUTED_SOURCE_RECORDS_BYTES)!;
102
+
103
+ await provider();
104
+
105
+ current = storageMetrics([syncConfigMetrics('config-a', 'ACTIVE', 120, 'v1')]);
106
+ vi.setSystemTime(61_000);
107
+
108
+ expect(await provider()).toEqual([
109
+ {
110
+ value: 120,
111
+ attributes: { sync_config_id: 'config-a', sync_config_state: 'ACTIVE', version_label: 'v1' }
112
+ },
113
+ {
114
+ value: 0,
115
+ attributes: { sync_config_id: 'config-a', sync_config_state: 'PROCESSING', version_label: 'v1' }
116
+ }
117
+ ]);
118
+ });
119
+
120
+ it('does not report anything as retired when reading the metrics fails', async () => {
121
+ let fail = false;
122
+ const storage = {
123
+ getStorageMetrics: async () => {
124
+ if (fail) {
125
+ throw new Error('storage unavailable');
126
+ }
127
+ return storageMetrics([syncConfigMetrics('config-a', 'ACTIVE', 100)]);
128
+ }
129
+ } as unknown as BucketStorageFactory;
130
+
131
+ const { engine, providers } = testEngine();
132
+ initializeCoreStorageMetrics(engine, storage);
133
+ const provider = providers.get(StorageMetric.ATTRIBUTED_OBJECT_STORAGE_BYTES)!;
134
+
135
+ await provider();
136
+
137
+ fail = true;
138
+ vi.setSystemTime(61_000);
139
+ expect(await provider()).toBeUndefined();
140
+
141
+ // The failure must not be interpreted as the sync config having been pruned.
142
+ fail = false;
143
+ vi.setSystemTime(122_000);
144
+ expect(await provider()).toEqual([
145
+ { value: 100, attributes: { sync_config_id: 'config-a', sync_config_state: 'ACTIVE' } }
146
+ ]);
147
+ });
148
+ });
@@ -719,6 +719,195 @@ config:
719
719
  storage.updateTestChecksum({ bucket: '1#stream|0["b"]', checksum: 1, count: 1 });
720
720
  });
721
721
 
722
+ // Auto-subscription includes profiles in both cases. The explicit subscription adds another
723
+ // inclusion reason and overrides priority 3 with priority 1; it does not enable the stream.
724
+ test.each([false, true])(
725
+ 'fetches overlapping static and dynamic buckets only once (custom subscription: %s)',
726
+ async (subscribe) => {
727
+ // Alice's profile is selected directly through auth.user_id() and also
728
+ // through her membership in her own group. Both branches resolve to the same bucket.
729
+ const state = checksumState(
730
+ /* yaml */ `
731
+ # Select the same profile through static and dynamic parameters.
732
+ config:
733
+ edition: 3
734
+ streams:
735
+ profiles:
736
+ auto_subscribe: true
737
+ query: |
738
+ SELECT id, name FROM profiles
739
+ WHERE id = auth.user_id()
740
+ OR id IN (SELECT member_id FROM memberships WHERE owner_id = auth.user_id())
741
+ `,
742
+ {
743
+ tokenPayload: new JwtPayload({ sub: 'alice' }),
744
+ syncRequest: {
745
+ streams: {
746
+ subscriptions: subscribe ? [{ stream: 'profiles', parameters: null, override_priority: 1 }] : []
747
+ }
748
+ }
749
+ }
750
+ );
751
+ const bucket = '1#profiles|0["alice"]';
752
+ storage.updateTestChecksum({ bucket, checksum: 1, count: 1 });
753
+
754
+ const line = (await state.buildNextCheckpointLine({
755
+ // Supply the membership lookup result without a database. '0' is the generated
756
+ // output column for member_id in the compiled parameter query.
757
+ base: storage.makeCheckpoint(1n, (lookups) => [{ lookup: lookups[0], rows: [{ '0': 'alice' }] }]),
758
+ writeCheckpoint: null,
759
+ update: CHECKPOINT_INVALIDATE_ALL
760
+ }))!;
761
+ line.advance();
762
+
763
+ // Check the request arrays directly: converting them to a Map would hide duplicates.
764
+ // Postgres fetches operations once per request, so duplicates here duplicate the data.
765
+ expect(line.bucketsToFetch.map((description) => description.bucket)).toEqual([bucket]);
766
+ expect(line.getFilteredBucketPositions().map((request) => request.bucket)).toEqual([bucket]);
767
+ // Merging must retain the default and any explicit subscription, using the lowest
768
+ // numeric priority (the highest sync priority) among them.
769
+ expect(line.checkpointLine).toMatchObject({
770
+ checkpoint: {
771
+ buckets: [
772
+ {
773
+ bucket,
774
+ checksum: 1,
775
+ count: 1,
776
+ priority: subscribe ? 1 : 3,
777
+ subscriptions: expect.arrayContaining(subscribe ? [{ default: 0 }, { sub: 0 }] : [{ default: 0 }])
778
+ }
779
+ ]
780
+ }
781
+ });
782
+
783
+ // Only bucket data changes at this checkpoint, so reuse the cached membership result.
784
+ // The first download is still pending; its next fetch must also contain only one request.
785
+ // Incremental requests are already deduplicated by a Set, so also check the description:
786
+ // it must retain the inclusion reasons from both the static and cached dynamic matches.
787
+ storage.updateTestChecksum({ bucket, checksum: 2, count: 2 });
788
+ const cachedLine = (await state.buildNextCheckpointLine({
789
+ base: storage.makeCheckpoint(2n),
790
+ writeCheckpoint: null,
791
+ update: {
792
+ invalidateDataBuckets: false,
793
+ invalidateParameterBuckets: false,
794
+ updatedDataBuckets: new Set([bucket]),
795
+ updatedParameterLookups: new Set()
796
+ }
797
+ }))!;
798
+ cachedLine.advance();
799
+ expect(cachedLine.getFilteredBucketPositions().map((request) => request.bucket)).toEqual([bucket]);
800
+ expect(cachedLine.bucketsToFetch).toMatchObject([
801
+ {
802
+ bucket,
803
+ priority: subscribe ? 1 : 3,
804
+ inclusion_reasons: expect.arrayContaining(subscribe ? ['default', { subscription: 0 }] : ['default'])
805
+ }
806
+ ]);
807
+ expect(cachedLine.checkpointLine).toMatchObject({
808
+ checkpoint_diff: {
809
+ updated_buckets: [
810
+ {
811
+ bucket,
812
+ checksum: 2,
813
+ count: 2,
814
+ priority: subscribe ? 1 : 3,
815
+ subscriptions: expect.arrayContaining(subscribe ? [{ default: 0 }, { sub: 0 }] : [{ default: 0 }])
816
+ }
817
+ ]
818
+ }
819
+ });
820
+
821
+ // Simulate Alice leaving the group by returning no membership rows. The direct auth
822
+ // match must keep her bucket. Change its checksum so a new checkpoint line is emitted.
823
+ storage.updateTestChecksum({ bucket, checksum: 3, count: 3 });
824
+ const staticLine = (await state.buildNextCheckpointLine({
825
+ base: storage.makeCheckpoint(3n, (lookups) => lookups.map((lookup) => ({ lookup, rows: [] }))),
826
+ writeCheckpoint: null,
827
+ update: CHECKPOINT_INVALIDATE_ALL
828
+ }))!;
829
+ staticLine.advance();
830
+ expect(staticLine.getFilteredBucketPositions().map((request) => request.bucket)).toEqual([bucket]);
831
+ }
832
+ );
833
+
834
+ test('preserves static subscription metadata when a dynamic match overlaps', async () => {
835
+ const state = checksumState(
836
+ /* yaml */ `
837
+ # The explicit subscription contributes priority through its static match.
838
+ config:
839
+ edition: 3
840
+ streams:
841
+ profiles:
842
+ auto_subscribe: true
843
+ query: |
844
+ SELECT id, name FROM profiles
845
+ WHERE id = auth.user_id()
846
+ OR id IN (
847
+ SELECT member_id FROM memberships
848
+ WHERE owner_id = ifnull(subscription.parameter('owner_id'), auth.user_id())
849
+ )
850
+ `,
851
+ {
852
+ tokenPayload: new JwtPayload({ sub: 'alice' }),
853
+ syncRequest: {
854
+ streams: {
855
+ subscriptions: [{ stream: 'profiles', parameters: { owner_id: 'bob' }, override_priority: 1 }]
856
+ }
857
+ }
858
+ }
859
+ );
860
+ const bucket = '1#profiles|0["alice"]';
861
+
862
+ // Both subscriptions select Alice statically, but only the default subscription finds
863
+ // her through memberships. Keeping only the dynamic description would lose sub: 0 and
864
+ // its priority override. Check both the initial and cached incremental checkpoints.
865
+ for (const checkpoint of [1n, 2n]) {
866
+ storage.updateTestChecksum({ bucket, checksum: Number(checkpoint), count: Number(checkpoint) });
867
+ const line = (await state.buildNextCheckpointLine({
868
+ base: storage.makeCheckpoint(
869
+ checkpoint,
870
+ checkpoint === 1n
871
+ ? (lookups) =>
872
+ lookups.map((lookup) => ({
873
+ lookup,
874
+ rows: lookup.values.includes('alice') ? [{ '0': 'alice' }] : []
875
+ }))
876
+ : undefined
877
+ ),
878
+ writeCheckpoint: null,
879
+ update:
880
+ checkpoint === 1n
881
+ ? CHECKPOINT_INVALIDATE_ALL
882
+ : {
883
+ invalidateDataBuckets: false,
884
+ invalidateParameterBuckets: false,
885
+ updatedDataBuckets: new Set([bucket]),
886
+ updatedParameterLookups: new Set()
887
+ }
888
+ }))!;
889
+ line.advance();
890
+ expect(line.bucketsToFetch).toMatchObject([
891
+ {
892
+ bucket,
893
+ priority: 1,
894
+ inclusion_reasons: expect.arrayContaining(['default', { subscription: 0 }])
895
+ }
896
+ ]);
897
+ const descriptions =
898
+ 'checkpoint' in line.checkpointLine
899
+ ? line.checkpointLine.checkpoint.buckets
900
+ : line.checkpointLine.checkpoint_diff.updated_buckets;
901
+ expect(descriptions).toMatchObject([
902
+ {
903
+ bucket,
904
+ priority: 1,
905
+ subscriptions: expect.arrayContaining([{ default: 0 }, { sub: 0 }])
906
+ }
907
+ ]);
908
+ }
909
+ });
910
+
722
911
  test('includes defaults', async () => {
723
912
  const state = checksumState(true);
724
913
  const line = await state.buildNextCheckpointLine({
@@ -1183,7 +1372,7 @@ streams:
1183
1372
  ).rejects.toThrow('Too many buckets: 60 (limit of 50');
1184
1373
 
1185
1374
  // Verify error log includes breakdown
1186
- expect(errorMessages[0]).toContain('(limit of 50)\nBuckets by sync stream:');
1375
+ expect(errorMessages[0]).toContain('(limit of 50)\nBuckets by Sync Stream:');
1187
1376
  expect(errorMessages[0]).toContain('projects: 30');
1188
1377
  expect(errorMessages[0]).toContain('tasks: 20');
1189
1378
  expect(errorMessages[0]).toContain('comments: 10');
@@ -1242,8 +1431,8 @@ bucket_definitions:
1242
1431
  expect(errorMessages[0]).toContain('projects: 60');
1243
1432
  });
1244
1433
 
1245
- test('limits bucket breakdown to top 100 sync streams', async () => {
1246
- // Create 105 sync streams with dynamic parameters.
1434
+ test('limits bucket breakdown to top 100 Sync Streams', async () => {
1435
+ // Create 105 Sync Streams with dynamic parameters.
1247
1436
  let yamlDefinitions = `
1248
1437
  config:
1249
1438
  edition: 3
@@ -1301,10 +1490,10 @@ streams:
1301
1490
 
1302
1491
  // Verify only the first 100 are shown.
1303
1492
  const errorMessage = errorMessages[0];
1304
- expect(errorMessage).toContain('Buckets by sync stream:');
1305
- expect(errorMessage).toContain('... and 5 more buckets from 5 sync streams');
1493
+ expect(errorMessage).toContain('Buckets by Sync Stream:');
1494
+ expect(errorMessage).toContain('... and 5 more buckets from 5 Sync Streams');
1306
1495
 
1307
- // Count how many sync streams are listed (should be exactly 100).
1496
+ // Count how many Sync Streams are listed (should be exactly 100).
1308
1497
  const defMatches = errorMessage.match(/def\d+:/g);
1309
1498
  expect(defMatches?.length).toBe(100);
1310
1499
  });
@@ -15,6 +15,25 @@ describe('isAbortError', () => {
15
15
  });
16
16
 
17
17
  describe('acquireSemaphoreAbortable', () => {
18
+ test('waits for an available slot without a signal', async () => {
19
+ const semaphore = new Semaphore(1);
20
+ const [, release] = await semaphore.acquire();
21
+ const resolved = vi.fn();
22
+ const waiting = acquireSemaphoreAbortable(semaphore).then((result) => {
23
+ resolved();
24
+ return result;
25
+ });
26
+ await Promise.resolve();
27
+ expect(resolved).not.toHaveBeenCalled();
28
+
29
+ release();
30
+ const acquired = await waiting;
31
+ expect(acquired).not.toBe('aborted');
32
+ expect(semaphore.getValue()).toBe(0);
33
+ (acquired as [number, SemaphoreInterface.Releaser])[1]();
34
+ expect(semaphore.getValue()).toBe(1);
35
+ });
36
+
18
37
  test('can acquire', async () => {
19
38
  const semaphore = new Semaphore(1);
20
39
  const controller = new AbortController();
@@ -43,4 +62,19 @@ describe('acquireSemaphoreAbortable', () => {
43
62
  // Releasing the semaphore should not invoke resolve again
44
63
  release();
45
64
  });
65
+
66
+ test('does not wait when the signal is already aborted', async () => {
67
+ const semaphore = new Semaphore(1);
68
+ const controller = new AbortController();
69
+
70
+ // Hold the only slot, so acquiring would block indefinitely.
71
+ const result = await acquireSemaphoreAbortable(semaphore, controller.signal);
72
+ expect(result).not.toBe('aborted');
73
+ const [, release] = result as [number, SemaphoreInterface.Releaser];
74
+
75
+ controller.abort();
76
+ expect(await acquireSemaphoreAbortable(semaphore, controller.signal)).toBe('aborted');
77
+
78
+ release();
79
+ });
46
80
  });
@@ -0,0 +1,59 @@
1
+ import { limitParamsForLogging } from '@/util/param-logging.js';
2
+ import { StreamingSyncRequest } from '@/util/protocol-types.js';
3
+ import { schema } from '@powersync/lib-services-framework';
4
+ import { deserialize } from 'bson';
5
+ import { describe, expect, test } from 'vitest';
6
+
7
+ describe('parameter logging', () => {
8
+ test('handles BSON Undefined accepted by the sync request validator', () => {
9
+ // Raw BSON is required: the serializer normally omits undefined values.
10
+ // This encodes { parameters: { x: undefined } } using BSON type 0x06.
11
+ const request = deserialize(Buffer.from('1900000003706172616d657465727300080000000678000000', 'hex'));
12
+ const validator = schema.createTsCodecValidator(StreamingSyncRequest, { allowAdditional: true });
13
+
14
+ expect(validator.validate(request).valid).toBe(true);
15
+ expect(Object.hasOwn(request.parameters, 'x')).toBe(true);
16
+ expect(request.parameters.x).toBeUndefined();
17
+ expect(limitParamsForLogging(request.parameters)).toEqual({ x: '[undefined]' });
18
+ });
19
+
20
+ test('handles values without a JSON representation and serialization errors', () => {
21
+ const circular: Record<string, unknown> = {};
22
+ circular.self = circular;
23
+
24
+ expect(limitParamsForLogging({ missing: undefined, fn: () => {}, symbol: Symbol(), bigint: 1n, circular })).toEqual(
25
+ {
26
+ missing: '[undefined]',
27
+ fn: '[undefined]',
28
+ symbol: '[undefined]',
29
+ bigint: '[unserializable]',
30
+ circular: '[unserializable]'
31
+ }
32
+ );
33
+ });
34
+
35
+ test('bounds keys and values, including JSON-encoded values', () => {
36
+ const params = { ['k'.repeat(100_000)]: 'v'.repeat(1000), nested: { text: 'v'.repeat(1000) }, null: null };
37
+ const result = limitParamsForLogging(params);
38
+
39
+ expect(result['k'.repeat(97) + '...']).toBe('v'.repeat(97) + '...');
40
+ expect(result.nested).toHaveLength(100);
41
+ expect(result.null).toBe('null');
42
+ expect(Object.keys(params)[0]).toHaveLength(100_000);
43
+ });
44
+
45
+ test('omits excess entries without serializing their values', () => {
46
+ const params = Object.fromEntries(Array.from({ length: 20 }, (_, i) => ['key' + i, 'value']));
47
+ const result = limitParamsForLogging({
48
+ ...params,
49
+ omitted: {
50
+ toJSON: () => {
51
+ throw new Error('must not serialize');
52
+ }
53
+ },
54
+ alsoOmitted: 'value'
55
+ });
56
+
57
+ expect(result).toEqual({ ...params, '⚠️': 'Additional parameters omitted' });
58
+ });
59
+ });
@@ -0,0 +1,23 @@
1
+ import { formatBytes } from '@/index.js';
2
+ import { describe, expect, test } from 'vitest';
3
+
4
+ describe('formatBytes', () => {
5
+ test('formats bytes', () => {
6
+ expect(formatBytes(500)).toBe('500B');
7
+ });
8
+
9
+ test('formats kilobytes', () => {
10
+ expect(formatBytes(1024)).toBe('1.0KB');
11
+ expect(formatBytes(1536)).toBe('1.5KB');
12
+ });
13
+
14
+ test('formats megabytes', () => {
15
+ expect(formatBytes(1024 * 1024)).toBe('1.0MB');
16
+ expect(formatBytes(1.5 * 1024 * 1024)).toBe('1.5MB');
17
+ });
18
+
19
+ test('formats gigabytes', () => {
20
+ expect(formatBytes(1024 * 1024 * 1024)).toBe('1.0GB');
21
+ expect(formatBytes(10.5 * 1024 * 1024 * 1024)).toBe('10.5GB');
22
+ });
23
+ });