@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.
- package/CHANGELOG.md +114 -5
- package/dist/api/diagnostics.js +7 -2
- package/dist/api/diagnostics.js.map +1 -1
- package/dist/entry/commands/compact-action.js +29 -25
- package/dist/entry/commands/compact-action.js.map +1 -1
- package/dist/entry/commands/config-command.js +1 -1
- package/dist/entry/commands/config-command.js.map +1 -1
- package/dist/metrics/metrics-interfaces.d.ts +5 -1
- package/dist/metrics/metrics-interfaces.js.map +1 -1
- package/dist/metrics/open-telemetry/MetricAttributeFilteringExporter.d.ts +36 -0
- package/dist/metrics/open-telemetry/MetricAttributeFilteringExporter.js +70 -0
- package/dist/metrics/open-telemetry/MetricAttributeFilteringExporter.js.map +1 -0
- package/dist/metrics/open-telemetry/OpenTelemetryMetricsFactory.js +6 -1
- package/dist/metrics/open-telemetry/OpenTelemetryMetricsFactory.js.map +1 -1
- package/dist/metrics/open-telemetry/util.js +7 -3
- package/dist/metrics/open-telemetry/util.js.map +1 -1
- package/dist/migrations/PowerSyncMigrationManager.js +2 -1
- package/dist/migrations/PowerSyncMigrationManager.js.map +1 -1
- package/dist/replication/AbstractReplicator.d.ts +5 -0
- package/dist/replication/AbstractReplicator.js +31 -13
- package/dist/replication/AbstractReplicator.js.map +1 -1
- package/dist/replication/ReplicationModule.d.ts +0 -7
- package/dist/replication/ReplicationModule.js +0 -1
- package/dist/replication/ReplicationModule.js.map +1 -1
- package/dist/routes/configure-fastify.d.ts +12 -3
- package/dist/routes/endpoints/admin.d.ts +24 -6
- package/dist/routes/endpoints/admin.js +17 -11
- package/dist/routes/endpoints/admin.js.map +1 -1
- package/dist/routes/endpoints/socket-route.js +7 -5
- package/dist/routes/endpoints/socket-route.js.map +1 -1
- package/dist/routes/endpoints/sync-rules.js +18 -10
- package/dist/routes/endpoints/sync-rules.js.map +1 -1
- package/dist/storage/BucketStorageBatch.d.ts +2 -1
- package/dist/storage/BucketStorageBatch.js.map +1 -1
- package/dist/storage/BucketStorageFactory.d.ts +49 -6
- package/dist/storage/BucketStorageFactory.js +25 -8
- package/dist/storage/BucketStorageFactory.js.map +1 -1
- package/dist/storage/PersistedReplicationStream.d.ts +2 -1
- package/dist/storage/PersistedReplicationStream.js.map +1 -1
- package/dist/storage/PersistedSyncConfigContent.d.ts +6 -4
- package/dist/storage/PersistedSyncConfigContent.js +34 -14
- package/dist/storage/PersistedSyncConfigContent.js.map +1 -1
- package/dist/storage/ReplicationEventPayload.d.ts +6 -1
- package/dist/storage/SourceEntity.d.ts +7 -2
- package/dist/storage/SourceTable.d.ts +37 -6
- package/dist/storage/SourceTable.js +42 -10
- package/dist/storage/SourceTable.js.map +1 -1
- package/dist/storage/SourceTableReconciler.d.ts +83 -0
- package/dist/storage/SourceTableReconciler.js +95 -0
- package/dist/storage/SourceTableReconciler.js.map +1 -0
- package/dist/storage/StorageEngine.d.ts +4 -0
- package/dist/storage/StorageEngine.js +7 -1
- package/dist/storage/StorageEngine.js.map +1 -1
- package/dist/storage/StorageProvider.d.ts +8 -0
- package/dist/storage/StorageVersionConfig.d.ts +4 -0
- package/dist/storage/StorageVersionConfig.js +10 -1
- package/dist/storage/StorageVersionConfig.js.map +1 -1
- package/dist/storage/SyncConfigParser.d.ts +44 -0
- package/dist/storage/SyncConfigParser.js +70 -0
- package/dist/storage/SyncConfigParser.js.map +1 -0
- package/dist/storage/SyncRulesBucketStorage.d.ts +48 -8
- package/dist/storage/SyncRulesBucketStorage.js.map +1 -1
- package/dist/storage/WriteCheckpointAPI.d.ts +25 -3
- package/dist/storage/WriteCheckpointAPI.js.map +1 -1
- package/dist/storage/implementation/BucketDefinitionMapping.d.ts +23 -7
- package/dist/storage/implementation/BucketDefinitionMapping.js +88 -14
- package/dist/storage/implementation/BucketDefinitionMapping.js.map +1 -1
- package/dist/storage/implementation/IncrementalReprocessingCompatibility.js +9 -5
- package/dist/storage/implementation/IncrementalReprocessingCompatibility.js.map +1 -1
- package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js +9 -1
- package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js.map +1 -1
- package/dist/storage/storage-index.d.ts +2 -0
- package/dist/storage/storage-index.js +2 -0
- package/dist/storage/storage-index.js.map +1 -1
- package/dist/storage/storage-metrics.js +120 -4
- package/dist/storage/storage-metrics.js.map +1 -1
- package/dist/sync/BucketChecksumState.d.ts +2 -2
- package/dist/sync/BucketChecksumState.js +5 -4
- package/dist/sync/BucketChecksumState.js.map +1 -1
- package/dist/sync/sync.js +37 -9
- package/dist/sync/sync.js.map +1 -1
- package/dist/sync/util.d.ts +1 -1
- package/dist/sync/util.js +13 -1
- package/dist/sync/util.js.map +1 -1
- package/dist/system/ServiceContext.d.ts +20 -0
- package/dist/system/ServiceContext.js +29 -1
- package/dist/system/ServiceContext.js.map +1 -1
- package/dist/util/config/compound-config-collector.js +5 -0
- package/dist/util/config/compound-config-collector.js.map +1 -1
- package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js +1 -0
- package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js.map +1 -1
- package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js +1 -0
- package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js.map +1 -1
- package/dist/util/config/sync-rules/sync-rules-provider.d.ts +2 -0
- package/dist/util/config/sync-rules/sync-rules-provider.js +3 -0
- package/dist/util/config/sync-rules/sync-rules-provider.js.map +1 -1
- package/dist/util/config/types.d.ts +1 -0
- package/dist/util/param-logging.d.ts +5 -2
- package/dist/util/param-logging.js +17 -9
- package/dist/util/param-logging.js.map +1 -1
- package/dist/util/protocol-types.d.ts +11 -11
- package/dist/util/protocol-types.js +6 -5
- package/dist/util/protocol-types.js.map +1 -1
- package/dist/util/utils.d.ts +2 -1
- package/dist/util/utils.js +16 -1
- package/dist/util/utils.js.map +1 -1
- package/package.json +6 -5
- package/src/api/diagnostics.ts +8 -2
- package/src/entry/commands/compact-action.ts +33 -25
- package/src/entry/commands/config-command.ts +1 -1
- package/src/metrics/metrics-interfaces.ts +6 -1
- package/src/metrics/open-telemetry/MetricAttributeFilteringExporter.ts +85 -0
- package/src/metrics/open-telemetry/OpenTelemetryMetricsFactory.ts +7 -2
- package/src/metrics/open-telemetry/util.ts +7 -3
- package/src/migrations/PowerSyncMigrationManager.ts +2 -1
- package/src/replication/AbstractReplicator.ts +42 -13
- package/src/replication/ReplicationModule.ts +0 -10
- package/src/routes/endpoints/admin.ts +17 -17
- package/src/routes/endpoints/socket-route.ts +9 -6
- package/src/routes/endpoints/sync-rules.ts +21 -12
- package/src/storage/BucketStorageBatch.ts +2 -1
- package/src/storage/BucketStorageFactory.ts +77 -14
- package/src/storage/PersistedReplicationStream.ts +2 -1
- package/src/storage/PersistedSyncConfigContent.ts +42 -19
- package/src/storage/ReplicationEventPayload.ts +6 -1
- package/src/storage/SourceEntity.ts +6 -2
- package/src/storage/SourceTable.ts +68 -11
- package/src/storage/SourceTableReconciler.ts +188 -0
- package/src/storage/StorageEngine.ts +10 -1
- package/src/storage/StorageProvider.ts +8 -0
- package/src/storage/StorageVersionConfig.ts +11 -1
- package/src/storage/SyncConfigParser.ts +121 -0
- package/src/storage/SyncRulesBucketStorage.ts +56 -8
- package/src/storage/WriteCheckpointAPI.ts +32 -3
- package/src/storage/implementation/BucketDefinitionMapping.ts +120 -17
- package/src/storage/implementation/IncrementalReprocessingCompatibility.ts +14 -5
- package/src/storage/implementation/IncrementalReprocessingSyncConfigLog.ts +22 -5
- package/src/storage/storage-index.ts +2 -0
- package/src/storage/storage-metrics.ts +154 -8
- package/src/sync/BucketChecksumState.ts +8 -5
- package/src/sync/sync.ts +40 -11
- package/src/sync/util.ts +25 -9
- package/src/system/ServiceContext.ts +47 -1
- package/src/util/config/compound-config-collector.ts +6 -0
- package/src/util/config/sync-rules/impl/base64-sync-rules-collector.ts +1 -0
- package/src/util/config/sync-rules/impl/filesystem-sync-rules-collector.ts +1 -0
- package/src/util/config/sync-rules/sync-rules-provider.ts +5 -0
- package/src/util/config/types.ts +1 -0
- package/src/util/param-logging.ts +21 -14
- package/src/util/protocol-types.ts +8 -7
- package/src/util/utils.ts +15 -1
- package/test/src/AbstractReplicator.test.ts +62 -0
- package/test/src/MetricAttributeFilteringExporter.test.ts +96 -0
- package/test/src/PersistedSyncConfigContent.test.ts +154 -0
- package/test/src/SyncConfigParser.test.ts +330 -0
- package/test/src/broadcast_iterable.test.ts +26 -8
- package/test/src/config.test.ts +40 -0
- package/test/src/diagnostics.test.ts +48 -0
- package/test/src/routes/admin.test.ts +30 -2
- package/test/src/routes/mocks.ts +2 -0
- package/test/src/routes/stream.test.ts +123 -2
- package/test/src/source-table-reconciler.test.ts +244 -0
- package/test/src/storage/SourceTable.test.ts +4 -1
- package/test/src/storage-metrics.test.ts +148 -0
- package/test/src/sync/BucketChecksumState.test.ts +195 -6
- package/test/src/sync/util.test.ts +34 -0
- package/test/src/util/param-logging.test.ts +59 -0
- package/test/src/util/utils.test.ts +23 -0
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { ServiceAssertionError } from '@powersync/lib-services-framework';
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
+
import { JsonValue, SourceEntityDescriptor } from './SourceEntity.js';
|
|
4
|
+
import { SourceTable, SourceTableCandidate, SourceTableId, sourceTableIdEquals } from './SourceTable.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A source connector's classification of overlapping persisted tables.
|
|
8
|
+
*/
|
|
9
|
+
export interface SourceTableCandidateResolution {
|
|
10
|
+
/**
|
|
11
|
+
* Records storage can reuse. Copies may include updated source metadata.
|
|
12
|
+
*/
|
|
13
|
+
compatibleTables: ReadonlyArray<SourceTableCandidate>;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Records that cannot be reused. Every candidate must appear in exactly one result list.
|
|
17
|
+
*/
|
|
18
|
+
incompatibleTables: ReadonlyArray<SourceTableCandidate>;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Values for records storage creates during this resolution.
|
|
22
|
+
*/
|
|
23
|
+
newTableValues: SourceTableCreateValues;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface SourceTableCreateValues {
|
|
27
|
+
/**
|
|
28
|
+
* Source metadata for new records. Null means no metadata.
|
|
29
|
+
*/
|
|
30
|
+
sourceMetadata: JsonValue;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Input to a source-owned reconciliation callback. The callback may run inside a storage
|
|
35
|
+
* transaction, so it must not mutate storage or perform slow external work.
|
|
36
|
+
*/
|
|
37
|
+
export interface SourceTableCandidateReconcilerInput {
|
|
38
|
+
/**
|
|
39
|
+
* Source entity being resolved.
|
|
40
|
+
*/
|
|
41
|
+
source: SourceEntityDescriptor;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Persisted tables overlapping by name or object id.
|
|
45
|
+
*/
|
|
46
|
+
candidates: ReadonlyArray<SourceTableCandidate>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export type SourceTableCandidateReconciler = (
|
|
50
|
+
input: SourceTableCandidateReconcilerInput
|
|
51
|
+
) => SourceTableCandidateResolution | Promise<SourceTableCandidateResolution>;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Compare replica-id columns in order.
|
|
55
|
+
*/
|
|
56
|
+
export function sameReplicaIdColumns(
|
|
57
|
+
left: SourceTableCandidate['replicaIdColumns'],
|
|
58
|
+
right: SourceEntityDescriptor
|
|
59
|
+
): boolean {
|
|
60
|
+
const target = right.replicaIdColumns;
|
|
61
|
+
return (
|
|
62
|
+
left.length == target.length &&
|
|
63
|
+
left.every(
|
|
64
|
+
(column, index) =>
|
|
65
|
+
column.name == target[index].name && column.type == target[index].type && column.typeId == target[index].typeId
|
|
66
|
+
)
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Compare the shared source-table identity fields.
|
|
72
|
+
*/
|
|
73
|
+
export function sourceIdentityCompatible(source: SourceEntityDescriptor, candidate: SourceTableCandidate): boolean {
|
|
74
|
+
return (
|
|
75
|
+
candidate.schema == source.schema &&
|
|
76
|
+
candidate.name == source.name &&
|
|
77
|
+
(source.objectId == null || candidate.objectId == source.objectId) &&
|
|
78
|
+
sameReplicaIdColumns(candidate.replicaIdColumns, source)
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Default identity-based reconciliation for connectors without source-specific metadata.
|
|
84
|
+
*/
|
|
85
|
+
export const defaultSourceTableReconciler: SourceTableCandidateReconciler = ({ source, candidates }) => {
|
|
86
|
+
const compatibleTables: SourceTableCandidate[] = [];
|
|
87
|
+
const incompatibleTables: SourceTableCandidate[] = [];
|
|
88
|
+
for (const candidate of candidates) {
|
|
89
|
+
if (sourceIdentityCompatible(source, candidate)) {
|
|
90
|
+
compatibleTables.push(candidate);
|
|
91
|
+
} else {
|
|
92
|
+
incompatibleTables.push(candidate);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return { compatibleTables, incompatibleTables, newTableValues: { sourceMetadata: null } };
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Check that every candidate was classified exactly once.
|
|
100
|
+
*/
|
|
101
|
+
export function validateSourceTableCandidateResolution(
|
|
102
|
+
candidates: ReadonlyArray<SourceTableCandidate>,
|
|
103
|
+
resolution: SourceTableCandidateResolution
|
|
104
|
+
): void {
|
|
105
|
+
const classifiedTables = [...resolution.compatibleTables, ...resolution.incompatibleTables];
|
|
106
|
+
|
|
107
|
+
for (const candidate of candidates) {
|
|
108
|
+
const classifications = classifiedTables.filter((table) => sourceTableIdEquals(table.id, candidate.id));
|
|
109
|
+
if (classifications.length !== 1) {
|
|
110
|
+
throw new ServiceAssertionError(
|
|
111
|
+
`Source table candidate ${candidate.id.toString()} must be classified exactly once, got ${classifications.length}`
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
for (const table of classifiedTables) {
|
|
117
|
+
if (!candidates.some((candidate) => sourceTableIdEquals(candidate.id, table.id))) {
|
|
118
|
+
throw new ServiceAssertionError(`Source table reconciliation returned unknown candidate ${table.id.toString()}`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* A source-metadata update to persist.
|
|
125
|
+
*/
|
|
126
|
+
export interface SourceTableMetadataUpdate {
|
|
127
|
+
id: SourceTableId;
|
|
128
|
+
sourceMetadata: JsonValue;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Rebuild a resolution from storage-owned tables, applying only reconciler-owned metadata to
|
|
133
|
+
* compatible tables. All other mutable table state comes from storage.
|
|
134
|
+
*
|
|
135
|
+
* Reconciler candidates are typed as read-only, but TypeScript types provide no runtime protection:
|
|
136
|
+
* callback code can cast a cloned candidate and mutate it. Rematerializing by id ensures those
|
|
137
|
+
* mutations are not trusted even when the compile-time boundary is bypassed.
|
|
138
|
+
*/
|
|
139
|
+
export function materializeSourceTableResolution(
|
|
140
|
+
tables: ReadonlyArray<SourceTable>,
|
|
141
|
+
resolution: SourceTableCandidateResolution
|
|
142
|
+
): MaterializedSourceTableResolution {
|
|
143
|
+
const findTable = (candidate: SourceTableCandidate): SourceTable => {
|
|
144
|
+
const table = tables.find((table) => sourceTableIdEquals(table.id, candidate.id));
|
|
145
|
+
if (table == null) {
|
|
146
|
+
throw new ServiceAssertionError(`Source table candidate ${candidate.id.toString()} was not persisted`);
|
|
147
|
+
}
|
|
148
|
+
return table;
|
|
149
|
+
};
|
|
150
|
+
return {
|
|
151
|
+
compatibleTables: resolution.compatibleTables.map((candidate) =>
|
|
152
|
+
findTable(candidate).withSourceMetadata(candidate.sourceMetadata)
|
|
153
|
+
),
|
|
154
|
+
incompatibleTables: resolution.incompatibleTables.map(findTable),
|
|
155
|
+
newTableValues: resolution.newTableValues
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export interface MaterializedSourceTableResolution {
|
|
160
|
+
compatibleTables: SourceTable[];
|
|
161
|
+
incompatibleTables: SourceTable[];
|
|
162
|
+
newTableValues: SourceTableCreateValues;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Return source-metadata changes from compatible candidates, comparing metadata by value against
|
|
167
|
+
* the original storage-owned tables. The reconciler may mutate its isolated candidate clones, so
|
|
168
|
+
* those clones cannot be used as the persisted baseline.
|
|
169
|
+
*/
|
|
170
|
+
export function diffSourceTableUpdates(
|
|
171
|
+
persistedTables: ReadonlyArray<SourceTable>,
|
|
172
|
+
resolution: SourceTableCandidateResolution
|
|
173
|
+
): SourceTableMetadataUpdate[] {
|
|
174
|
+
const updates: SourceTableMetadataUpdate[] = [];
|
|
175
|
+
for (const resolvedTable of resolution.compatibleTables) {
|
|
176
|
+
const persistedTable = persistedTables.find((table) => sourceTableIdEquals(table.id, resolvedTable.id));
|
|
177
|
+
if (persistedTable == null) {
|
|
178
|
+
throw new ServiceAssertionError(
|
|
179
|
+
`Source table reconciliation returned unknown candidate ${resolvedTable.id.toString()}`
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
if (isDeepStrictEqual(persistedTable.sourceMetadata, resolvedTable.sourceMetadata)) {
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
updates.push({ id: resolvedTable.id, sourceMetadata: resolvedTable.sourceMetadata });
|
|
186
|
+
}
|
|
187
|
+
return updates;
|
|
188
|
+
}
|
|
@@ -2,9 +2,11 @@ import { BaseObserver, logger, ServiceError } from '@powersync/lib-services-fram
|
|
|
2
2
|
import { ResolvedPowerSyncConfig } from '../util/util-index.js';
|
|
3
3
|
import { BucketStorageFactory } from './BucketStorageFactory.js';
|
|
4
4
|
import { ActiveStorage, StorageProvider } from './StorageProvider.js';
|
|
5
|
+
import { SyncConfigParser } from './SyncConfigParser.js';
|
|
5
6
|
|
|
6
7
|
export type StorageEngineOptions = {
|
|
7
8
|
configuration: ResolvedPowerSyncConfig;
|
|
9
|
+
syncConfigParser: SyncConfigParser;
|
|
8
10
|
};
|
|
9
11
|
|
|
10
12
|
export interface StorageEngineListener {
|
|
@@ -15,6 +17,7 @@ export interface StorageEngineListener {
|
|
|
15
17
|
export class StorageEngine extends BaseObserver<StorageEngineListener> {
|
|
16
18
|
// TODO: This will need to revisited when we actually support multiple storage providers.
|
|
17
19
|
private storageProviders: Map<string, StorageProvider> = new Map();
|
|
20
|
+
private startupStarted = false;
|
|
18
21
|
private currentActiveStorage: ActiveStorage | null = null;
|
|
19
22
|
|
|
20
23
|
constructor(private options: StorageEngineOptions) {
|
|
@@ -33,6 +36,10 @@ export class StorageEngine extends BaseObserver<StorageEngineListener> {
|
|
|
33
36
|
return this.currentActiveStorage;
|
|
34
37
|
}
|
|
35
38
|
|
|
39
|
+
get started(): boolean {
|
|
40
|
+
return this.startupStarted;
|
|
41
|
+
}
|
|
42
|
+
|
|
36
43
|
/**
|
|
37
44
|
* Register a provider which generates a {@link BucketStorageFactory}
|
|
38
45
|
* given the matching config specified in the loaded {@link ResolvedPowerSyncConfig}
|
|
@@ -42,10 +49,12 @@ export class StorageEngine extends BaseObserver<StorageEngineListener> {
|
|
|
42
49
|
}
|
|
43
50
|
|
|
44
51
|
public async start(): Promise<void> {
|
|
52
|
+
this.startupStarted = true;
|
|
45
53
|
logger.info('Starting Storage Engine...');
|
|
46
54
|
const { configuration } = this.options;
|
|
47
55
|
this.currentActiveStorage = await this.storageProviders.get(configuration.storage.type)!.getStorage({
|
|
48
|
-
resolvedConfig: configuration
|
|
56
|
+
resolvedConfig: configuration,
|
|
57
|
+
syncConfigParser: this.options.syncConfigParser
|
|
49
58
|
});
|
|
50
59
|
this.iterateListeners((cb) => cb.storageActivated?.(this.activeBucketStorage));
|
|
51
60
|
this.currentActiveStorage.onFatalError?.((error) => {
|
|
@@ -2,6 +2,7 @@ import { ServiceError } from '@powersync/lib-services-framework';
|
|
|
2
2
|
import * as util from '../util/util-index.js';
|
|
3
3
|
import { BucketStorageFactory } from './BucketStorageFactory.js';
|
|
4
4
|
import { ReportStorage } from './ReportStorage.js';
|
|
5
|
+
import { SyncConfigParser } from './SyncConfigParser.js';
|
|
5
6
|
|
|
6
7
|
export interface ActiveStorage {
|
|
7
8
|
storage: BucketStorageFactory;
|
|
@@ -19,6 +20,10 @@ export interface ActiveStorage {
|
|
|
19
20
|
export interface GetStorageOptions {
|
|
20
21
|
// TODO: This should just be the storage config. Update once the slot name prefix coupling has been removed from the storage
|
|
21
22
|
resolvedConfig: util.ResolvedPowerSyncConfig;
|
|
23
|
+
/**
|
|
24
|
+
* Service-wide parser containing every extension registered during module initialization.
|
|
25
|
+
*/
|
|
26
|
+
syncConfigParser: SyncConfigParser;
|
|
22
27
|
}
|
|
23
28
|
|
|
24
29
|
/**
|
|
@@ -31,5 +36,8 @@ export interface StorageProvider {
|
|
|
31
36
|
*/
|
|
32
37
|
type: string;
|
|
33
38
|
|
|
39
|
+
/**
|
|
40
|
+
* Creates active storage during storage-engine startup using the fully assembled service parser.
|
|
41
|
+
*/
|
|
34
42
|
getStorage(options: GetStorageOptions): Promise<ActiveStorage>;
|
|
35
43
|
}
|
|
@@ -39,6 +39,11 @@ export const STORAGE_VERSION_2 = 2;
|
|
|
39
39
|
*/
|
|
40
40
|
export const STORAGE_VERSION_3 = 3;
|
|
41
41
|
|
|
42
|
+
/**
|
|
43
|
+
* Same as version 3, but marked as stable.
|
|
44
|
+
*/
|
|
45
|
+
export const STORAGE_VERSION_4 = 4;
|
|
46
|
+
|
|
42
47
|
/**
|
|
43
48
|
* Oldest supported storage version.
|
|
44
49
|
*/
|
|
@@ -54,7 +59,7 @@ export const CURRENT_STORAGE_VERSION = STORAGE_VERSION_2;
|
|
|
54
59
|
*
|
|
55
60
|
* This includes unstable versions.
|
|
56
61
|
*/
|
|
57
|
-
export const SUPPORTED_STORAGE_VERSIONS = [STORAGE_VERSION_1, STORAGE_VERSION_2, STORAGE_VERSION_3];
|
|
62
|
+
export const SUPPORTED_STORAGE_VERSIONS = [STORAGE_VERSION_1, STORAGE_VERSION_2, STORAGE_VERSION_3, STORAGE_VERSION_4];
|
|
58
63
|
|
|
59
64
|
/**
|
|
60
65
|
* Shared storage-version behavior across storage implementations.
|
|
@@ -74,5 +79,10 @@ export const STORAGE_VERSION_CONFIG: Record<number, StorageVersionConfig | undef
|
|
|
74
79
|
version: STORAGE_VERSION_3,
|
|
75
80
|
versionedBuckets: true,
|
|
76
81
|
softDeleteCurrentData: true
|
|
82
|
+
},
|
|
83
|
+
[STORAGE_VERSION_4]: {
|
|
84
|
+
version: STORAGE_VERSION_4,
|
|
85
|
+
versionedBuckets: true,
|
|
86
|
+
softDeleteCurrentData: true
|
|
77
87
|
}
|
|
78
88
|
};
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AdditionalSyncConfigParser,
|
|
3
|
+
compileSyncRulesSchemaValidator,
|
|
4
|
+
createSyncRulesSchema,
|
|
5
|
+
JsonObject,
|
|
6
|
+
PrecompiledSyncConfig,
|
|
7
|
+
SqlSyncRules,
|
|
8
|
+
SyncConfig,
|
|
9
|
+
SyncConfigDiagnostic,
|
|
10
|
+
SyncConfigWithErrors,
|
|
11
|
+
SyncRulesErrors,
|
|
12
|
+
SyncRulesOptions,
|
|
13
|
+
SyncRulesSchemaValidator,
|
|
14
|
+
validateAdditionalSyncConfigParsers,
|
|
15
|
+
YamlError
|
|
16
|
+
} from '@powersync/service-sync-rules';
|
|
17
|
+
|
|
18
|
+
export type ParseSyncConfigOptions = Omit<SyncRulesOptions, 'parsers' | 'schemaValidator'>;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Shared by service routes, deployment, replication and persisted storage; only initialization can register hooks.
|
|
22
|
+
*/
|
|
23
|
+
export interface SyncConfigParser {
|
|
24
|
+
/**
|
|
25
|
+
* A JSON schema which can be used to validate the format of a supplied sync config.
|
|
26
|
+
*/
|
|
27
|
+
readonly jsonSchema: JsonObject;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Parses string content.
|
|
31
|
+
*
|
|
32
|
+
* @returns The parsed {@link SyncConfigWithErrors}
|
|
33
|
+
*/
|
|
34
|
+
parseContent(content: string, options: ParseSyncConfigOptions): SyncConfigWithErrors;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Validates a persisted/parsed sync config.
|
|
38
|
+
*
|
|
39
|
+
* @returns Any errors detected.
|
|
40
|
+
*/
|
|
41
|
+
validatePersisted(options: { config: SyncConfig; context: { defaultSchema: string } }): YamlError[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export class SqlSyncConfigParser implements SyncConfigParser {
|
|
45
|
+
readonly #parsers: AdditionalSyncConfigParser[];
|
|
46
|
+
#jsonSchema: JsonObject;
|
|
47
|
+
#schemaValidator: SyncRulesSchemaValidator;
|
|
48
|
+
|
|
49
|
+
constructor(parsers: readonly AdditionalSyncConfigParser[] = []) {
|
|
50
|
+
validateAdditionalSyncConfigParsers(parsers);
|
|
51
|
+
this.#parsers = [...parsers];
|
|
52
|
+
this.#jsonSchema = createSyncRulesSchema(parsers);
|
|
53
|
+
this.#schemaValidator = compileSyncRulesSchemaValidator(this.#jsonSchema);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
get jsonSchema(): JsonObject {
|
|
57
|
+
// Tooling can customize its copy without changing validation for the running service.
|
|
58
|
+
return structuredClone(this.#jsonSchema);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Validate the candidate composition before mutating the registry.
|
|
63
|
+
*/
|
|
64
|
+
registerParser(parser: AdditionalSyncConfigParser): void {
|
|
65
|
+
const parsers = [...this.#parsers, parser];
|
|
66
|
+
validateAdditionalSyncConfigParsers(parsers);
|
|
67
|
+
const schema = createSyncRulesSchema(parsers);
|
|
68
|
+
const validator = compileSyncRulesSchemaValidator(schema);
|
|
69
|
+
this.#parsers.push(parser);
|
|
70
|
+
this.#jsonSchema = schema;
|
|
71
|
+
this.#schemaValidator = validator;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
parseContent(content: string, options: ParseSyncConfigOptions): SyncConfigWithErrors {
|
|
75
|
+
return SqlSyncRules.fromYaml(content, {
|
|
76
|
+
...options,
|
|
77
|
+
parsers: this.#parsers,
|
|
78
|
+
schemaValidator: this.#schemaValidator
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
validatePersisted({ config, context }: { config: SyncConfig; context: { defaultSchema: string } }): YamlError[] {
|
|
83
|
+
/**
|
|
84
|
+
* Ensure that all modules which created a persisted SyncConfig
|
|
85
|
+
* are currently loaded.
|
|
86
|
+
* This prevents a case for a SyncConfig with missing external modules to be loaded.
|
|
87
|
+
*/
|
|
88
|
+
const requiredIds = new Set(
|
|
89
|
+
config instanceof PrecompiledSyncConfig ? Object.keys(config.plan.moduleData ?? {}) : []
|
|
90
|
+
);
|
|
91
|
+
const registeredIds = new Set(this.#parsers.map((parser) => parser.id));
|
|
92
|
+
const missingIds = [...requiredIds].filter((id) => !registeredIds.has(id));
|
|
93
|
+
if (missingIds.length != 0) {
|
|
94
|
+
throw new Error(`Missing required sync config parsers: ${missingIds.join(', ')}`);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const errors: YamlError[] = [];
|
|
98
|
+
const reportDiagnostic = (diagnostic: SyncConfigDiagnostic) => {
|
|
99
|
+
const location = diagnostic.location;
|
|
100
|
+
const error = new YamlError(
|
|
101
|
+
new Error(diagnostic.message),
|
|
102
|
+
location && {
|
|
103
|
+
start: location.start_offset,
|
|
104
|
+
end: location.end_offset
|
|
105
|
+
}
|
|
106
|
+
);
|
|
107
|
+
error.type = diagnostic.level;
|
|
108
|
+
errors.push(error);
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
for (const parser of this.#parsers) {
|
|
112
|
+
if (!requiredIds.has(parser.id)) continue;
|
|
113
|
+
/**
|
|
114
|
+
* This allows additional validation of module specific semantics
|
|
115
|
+
*/
|
|
116
|
+
parser.validatePersisted?.({ config, context: { ...context, reportDiagnostic } });
|
|
117
|
+
}
|
|
118
|
+
if (errors.some((error) => error.type == 'fatal')) throw new SyncRulesErrors(errors);
|
|
119
|
+
return errors;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -11,10 +11,11 @@ import * as util from '../util/util-index.js';
|
|
|
11
11
|
import { BucketStorageBatch, FlushedResult, SaveUpdate } from './BucketStorageBatch.js';
|
|
12
12
|
import { BucketStorageFactory } from './BucketStorageFactory.js';
|
|
13
13
|
import { ParsedSyncConfigSet } from './ParsedSyncConfigSet.js';
|
|
14
|
-
import { ParseSyncConfigOptions } from './PersistedSyncConfigContent.js';
|
|
15
14
|
import { SourceEntityDescriptor } from './SourceEntity.js';
|
|
16
15
|
import { SourceTable } from './SourceTable.js';
|
|
16
|
+
import { SourceTableCandidateReconciler } from './SourceTableReconciler.js';
|
|
17
17
|
import { StorageVersionConfig } from './StorageVersionConfig.js';
|
|
18
|
+
import { ParseSyncConfigOptions } from './SyncConfigParser.js';
|
|
18
19
|
import { SyncStorageWriteCheckpointAPI } from './WriteCheckpointAPI.js';
|
|
19
20
|
|
|
20
21
|
/**
|
|
@@ -96,12 +97,20 @@ export interface SyncRulesBucketStorage
|
|
|
96
97
|
*/
|
|
97
98
|
reportError(e: any): Promise<void>;
|
|
98
99
|
|
|
100
|
+
/**
|
|
101
|
+
* Whether parameter compaction can run when {@link CompactOptions.incrementalOnly} is set.
|
|
102
|
+
*
|
|
103
|
+
* Storage implementations that do not support incremental parameter compaction must return
|
|
104
|
+
* false; the compact command will skip parameter compaction in that mode.
|
|
105
|
+
*/
|
|
106
|
+
supportsIncrementalParameterCompaction(): boolean;
|
|
107
|
+
|
|
99
108
|
compact(options?: CompactOptions): Promise<void>;
|
|
100
109
|
|
|
101
110
|
/**
|
|
102
|
-
*
|
|
111
|
+
* Compact storage after initial replication, before the first checkpoint exists.
|
|
103
112
|
*/
|
|
104
|
-
|
|
113
|
+
compactInitialReplication(options: CompactInitialReplicationOptions): Promise<CompactInitialReplicationResults>;
|
|
105
114
|
|
|
106
115
|
// ## Read operations
|
|
107
116
|
|
|
@@ -212,6 +221,11 @@ export interface ResolveTablesOptions {
|
|
|
212
221
|
* Source table or collection metadata discovered during snapshot or streaming.
|
|
213
222
|
*/
|
|
214
223
|
source: SourceEntityDescriptor;
|
|
224
|
+
/**
|
|
225
|
+
* Classifies overlapping persisted tables. Defaults to identity-based reconciliation.
|
|
226
|
+
* This may run inside a storage transaction and must not mutate storage.
|
|
227
|
+
*/
|
|
228
|
+
reconcileSourceTables?: SourceTableCandidateReconciler;
|
|
215
229
|
/**
|
|
216
230
|
* For tests only - custom id generator for stable ids.
|
|
217
231
|
*/
|
|
@@ -271,6 +285,14 @@ export interface CreateWriterOptions extends ParseSyncConfigOptions {
|
|
|
271
285
|
tracer?: PerformanceTracer<'storage' | 'evaluate'>;
|
|
272
286
|
|
|
273
287
|
logger?: Logger;
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Aborts long-running storage work started by this writer, such as uploads to object storage.
|
|
291
|
+
*
|
|
292
|
+
* This does not replace flushing or committing at the appropriate source boundary: it only
|
|
293
|
+
* cancels work that is still in flight when replication stops.
|
|
294
|
+
*/
|
|
295
|
+
signal?: AbortSignal;
|
|
274
296
|
}
|
|
275
297
|
|
|
276
298
|
export interface StorageHooks {
|
|
@@ -315,6 +337,15 @@ export interface CompactOptions {
|
|
|
315
337
|
|
|
316
338
|
compactParameterData?: boolean;
|
|
317
339
|
|
|
340
|
+
/**
|
|
341
|
+
* Only perform compaction that can be done incrementally.
|
|
342
|
+
*
|
|
343
|
+
* This includes full bucket compaction on MongoDB V3 storage.
|
|
344
|
+
*
|
|
345
|
+
* On MongoDB v1 and Postgres storage, this makes compacting a no-op.
|
|
346
|
+
*/
|
|
347
|
+
incrementalOnly?: boolean;
|
|
348
|
+
|
|
318
349
|
/**
|
|
319
350
|
* Delete client-requested write checkpoints created before this time.
|
|
320
351
|
*
|
|
@@ -348,6 +379,18 @@ export interface CompactOptions {
|
|
|
348
379
|
*/
|
|
349
380
|
minChangeRatio?: number;
|
|
350
381
|
|
|
382
|
+
/** Minimum delay before a V3 bucket is checked for chunk compaction. Default: five minutes. */
|
|
383
|
+
minCompactChunkIntervalMs?: number;
|
|
384
|
+
|
|
385
|
+
/** Minimum elapsed write pressure before the v3 sliding-scale full compact. Default: two hours. */
|
|
386
|
+
minCompactFullIntervalMs?: number;
|
|
387
|
+
|
|
388
|
+
/** Maximum age of writes not covered by a v3 full compact. */
|
|
389
|
+
maxCompactFullIntervalMs?: number;
|
|
390
|
+
|
|
391
|
+
/** How long a v3 worker owns a claimed bucket before another worker may recover it. */
|
|
392
|
+
compactLeaseDurationMs?: number;
|
|
393
|
+
|
|
351
394
|
/**
|
|
352
395
|
* Internal/testing use: Cache size for compacting parameters.
|
|
353
396
|
*/
|
|
@@ -358,12 +401,14 @@ export interface CompactOptions {
|
|
|
358
401
|
logger?: Logger;
|
|
359
402
|
}
|
|
360
403
|
|
|
361
|
-
export interface
|
|
404
|
+
export interface CompactInitialReplicationOptions {
|
|
405
|
+
/** Internal/testing use: bypass the new-chunk threshold in MongoDB V3/V4 storage. */
|
|
406
|
+
forceChunkCompaction?: boolean;
|
|
362
407
|
/**
|
|
363
|
-
*
|
|
408
|
+
* Compact data up to this op id.
|
|
364
409
|
*
|
|
365
410
|
* Defaults to the highest persisted op id for the replication stream, which covers
|
|
366
|
-
* the common case of
|
|
411
|
+
* the common case of compacting right after initial replication, before
|
|
367
412
|
* the first checkpoint exists.
|
|
368
413
|
*/
|
|
369
414
|
maxOpId?: util.InternalOpId;
|
|
@@ -371,9 +416,9 @@ export interface PopulateChecksumCacheOptions {
|
|
|
371
416
|
signal?: AbortSignal;
|
|
372
417
|
}
|
|
373
418
|
|
|
374
|
-
export interface
|
|
419
|
+
export interface CompactInitialReplicationResults {
|
|
375
420
|
/**
|
|
376
|
-
* Number of buckets
|
|
421
|
+
* Number of buckets processed.
|
|
377
422
|
*/
|
|
378
423
|
buckets: number;
|
|
379
424
|
}
|
|
@@ -413,6 +458,9 @@ export interface BucketDataBatchOptions {
|
|
|
413
458
|
/** Abort any in-progress work for this batch, including object-storage downloads. */
|
|
414
459
|
signal?: AbortSignal;
|
|
415
460
|
|
|
461
|
+
/** Traces data reads performed by the storage implementation. */
|
|
462
|
+
tracer?: PerformanceTracer<string>;
|
|
463
|
+
|
|
416
464
|
/** Limit number of documents returned. Defaults to 1000. */
|
|
417
465
|
limit?: number;
|
|
418
466
|
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { EventDefinitionId } from '@powersync/service-sync-rules';
|
|
2
|
+
|
|
1
3
|
export enum WriteCheckpointMode {
|
|
2
4
|
/**
|
|
3
5
|
* Raw mappings of `user_id` to `write_checkpoint`s should
|
|
@@ -31,7 +33,9 @@ export interface ClientRequestedCheckpointOptions {
|
|
|
31
33
|
checkpoint_request_id?: bigint;
|
|
32
34
|
}
|
|
33
35
|
|
|
34
|
-
export
|
|
36
|
+
export type SyncStorageCustomWriteCheckpointFilters = BaseWriteCheckpointIdentifier;
|
|
37
|
+
|
|
38
|
+
export interface CustomWriteCheckpointFilters extends SyncStorageCustomWriteCheckpointFilters {
|
|
35
39
|
/**
|
|
36
40
|
* Replication stream which was active when this checkpoint was created.
|
|
37
41
|
*/
|
|
@@ -44,6 +48,14 @@ export interface BatchedCustomWriteCheckpointOptions extends BaseWriteCheckpoint
|
|
|
44
48
|
* "write checkpoint" in storage APIs for backwards compatibility.
|
|
45
49
|
*/
|
|
46
50
|
checkpoint: bigint;
|
|
51
|
+
/**
|
|
52
|
+
* Compiled event definition which created the checkpoint.
|
|
53
|
+
*
|
|
54
|
+
* Incremental replication uses this to keep checkpoint records produced by
|
|
55
|
+
* active and processing sync configs separate. This is required by v3
|
|
56
|
+
* storage and unused by legacy storage versions.
|
|
57
|
+
*/
|
|
58
|
+
event_id?: EventDefinitionId;
|
|
47
59
|
/**
|
|
48
60
|
* Required when this custom checkpoint was created from a client checkpoint
|
|
49
61
|
* request and should be eligible for checkpoint request retention cleanup.
|
|
@@ -155,12 +167,29 @@ function shouldReplaceManagedWriteCheckpoint(
|
|
|
155
167
|
return candidateRequestId > existingRequestId;
|
|
156
168
|
}
|
|
157
169
|
|
|
158
|
-
export type SyncStorageLastWriteCheckpointFilters =
|
|
170
|
+
export type SyncStorageLastWriteCheckpointFilters =
|
|
171
|
+
| SyncStorageCustomWriteCheckpointFilters
|
|
172
|
+
| ManagedWriteCheckpointFilters;
|
|
159
173
|
export type LastWriteCheckpointFilters = CustomWriteCheckpointFilters | ManagedWriteCheckpointFilters;
|
|
160
174
|
|
|
175
|
+
/** Configures checkpoint ownership and generation for a storage instance. */
|
|
176
|
+
export type WriteCheckpointModeConfig =
|
|
177
|
+
| {
|
|
178
|
+
mode: WriteCheckpointMode.CUSTOM;
|
|
179
|
+
/**
|
|
180
|
+
* Name of the event whose custom checkpoints are served. Storage resolves this name through the active sync
|
|
181
|
+
* config's persisted mapping; integrations must not construct or persist event ids themselves. Required by
|
|
182
|
+
* storage implementations that scope custom checkpoints by event definition.
|
|
183
|
+
*/
|
|
184
|
+
eventName?: string;
|
|
185
|
+
}
|
|
186
|
+
| {
|
|
187
|
+
mode: WriteCheckpointMode.MANAGED;
|
|
188
|
+
};
|
|
189
|
+
|
|
161
190
|
export interface BaseWriteCheckpointAPI {
|
|
162
191
|
readonly writeCheckpointMode: WriteCheckpointMode;
|
|
163
|
-
setWriteCheckpointMode(
|
|
192
|
+
setWriteCheckpointMode(config: WriteCheckpointModeConfig): void;
|
|
164
193
|
createManagedWriteCheckpoints(
|
|
165
194
|
checkpoints: ManagedWriteCheckpointOptions[]
|
|
166
195
|
): Promise<CreateManagedWriteCheckpointsResult>;
|