@powersync/service-core 0.0.0-dev-20260909133214 → 0.0.0-dev-20261005112123
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 +61 -5
- package/dist/api/diagnostics.js +5 -2
- package/dist/api/diagnostics.js.map +1 -1
- package/dist/auth/JwtPayload.d.ts +2 -2
- package/dist/auth/JwtPayload.js +2 -2
- package/dist/auth/JwtPayload.js.map +1 -1
- package/dist/entry/commands/compact-action.js +1 -1
- 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/migrations/PowerSyncMigrationManager.js +2 -1
- package/dist/migrations/PowerSyncMigrationManager.js.map +1 -1
- package/dist/replication/AbstractReplicator.js +8 -4
- 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 +3 -3
- package/dist/routes/endpoints/admin.d.ts +6 -6
- package/dist/routes/endpoints/admin.js +15 -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 +16 -10
- package/dist/routes/endpoints/sync-rules.js.map +1 -1
- package/dist/storage/BucketStorageFactory.d.ts +21 -2
- package/dist/storage/BucketStorageFactory.js +17 -4
- 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 +4 -4
- package/dist/storage/PersistedSyncConfigContent.js +12 -5
- package/dist/storage/PersistedSyncConfigContent.js.map +1 -1
- 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 +0 -4
- package/dist/storage/StorageVersionConfig.js +0 -4
- package/dist/storage/StorageVersionConfig.js.map +1 -1
- package/dist/storage/SyncConfigParser.d.ts +44 -0
- package/dist/storage/SyncConfigParser.js +73 -0
- package/dist/storage/SyncConfigParser.js.map +1 -0
- package/dist/storage/SyncRulesBucketStorage.d.ts +3 -1
- package/dist/storage/SyncRulesBucketStorage.js.map +1 -1
- package/dist/storage/implementation/IncrementalReprocessingCompatibility.js +9 -5
- package/dist/storage/implementation/IncrementalReprocessingCompatibility.js.map +1 -1
- package/dist/storage/storage-index.d.ts +1 -0
- package/dist/storage/storage-index.js +1 -0
- package/dist/storage/storage-index.js.map +1 -1
- package/dist/sync/BucketChecksumState.d.ts +1 -1
- package/dist/sync/BucketChecksumState.js +5 -4
- package/dist/sync/BucketChecksumState.js.map +1 -1
- package/dist/sync/util.d.ts +1 -1
- package/dist/sync/util.js +3 -0
- 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/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 +7 -7
- package/dist/util/protocol-types.js +3 -3
- package/package.json +5 -5
- package/src/api/diagnostics.ts +6 -2
- package/src/auth/JwtPayload.ts +2 -2
- package/src/entry/commands/compact-action.ts +1 -1
- package/src/entry/commands/config-command.ts +1 -1
- package/src/migrations/PowerSyncMigrationManager.ts +2 -1
- package/src/replication/AbstractReplicator.ts +8 -4
- package/src/replication/ReplicationModule.ts +0 -10
- package/src/routes/endpoints/admin.ts +15 -17
- package/src/routes/endpoints/socket-route.ts +9 -6
- package/src/routes/endpoints/sync-rules.ts +19 -12
- package/src/storage/BucketStorageFactory.ts +33 -6
- package/src/storage/PersistedReplicationStream.ts +2 -1
- package/src/storage/PersistedSyncConfigContent.ts +16 -8
- package/src/storage/StorageEngine.ts +10 -1
- package/src/storage/StorageProvider.ts +8 -0
- package/src/storage/StorageVersionConfig.ts +0 -5
- package/src/storage/SyncConfigParser.ts +124 -0
- package/src/storage/SyncRulesBucketStorage.ts +3 -1
- package/src/storage/implementation/IncrementalReprocessingCompatibility.ts +17 -5
- package/src/storage/storage-index.ts +1 -0
- package/src/sync/BucketChecksumState.ts +5 -4
- package/src/sync/util.ts +4 -1
- package/src/system/ServiceContext.ts +47 -1
- package/src/util/param-logging.ts +21 -14
- package/src/util/protocol-types.ts +5 -5
- package/test/src/AbstractReplicator.test.ts +70 -0
- package/test/src/PersistedSyncConfigContent.test.ts +3 -1
- package/test/src/SyncConfigParser.test.ts +309 -0
- package/test/src/broadcast_iterable.test.ts +26 -8
- package/test/src/diagnostics.test.ts +24 -0
- package/test/src/routes/admin.test.ts +22 -0
- package/test/src/routes/mocks.ts +2 -0
- package/test/src/sync/BucketChecksumState.test.ts +195 -6
- package/test/src/sync/util.test.ts +19 -0
- package/test/src/util/param-logging.test.ts +59 -0
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -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
|
}
|
|
@@ -49,11 +49,6 @@ export const STORAGE_VERSION_4 = 4;
|
|
|
49
49
|
*/
|
|
50
50
|
export const LEGACY_STORAGE_VERSION = STORAGE_VERSION_1;
|
|
51
51
|
|
|
52
|
-
/**
|
|
53
|
-
* Default storage version for newly persisted replication streams.
|
|
54
|
-
*/
|
|
55
|
-
export const CURRENT_STORAGE_VERSION = STORAGE_VERSION_2;
|
|
56
|
-
|
|
57
52
|
/**
|
|
58
53
|
* All versions that can be loaded.
|
|
59
54
|
*
|
|
@@ -0,0 +1,124 @@
|
|
|
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
|
+
const errors: YamlError[] = [];
|
|
84
|
+
const reportDiagnostic = (diagnostic: SyncConfigDiagnostic) => {
|
|
85
|
+
const location = diagnostic.location;
|
|
86
|
+
const error = new YamlError(
|
|
87
|
+
new Error(diagnostic.message),
|
|
88
|
+
location && {
|
|
89
|
+
start: location.start_offset,
|
|
90
|
+
end: location.end_offset
|
|
91
|
+
}
|
|
92
|
+
);
|
|
93
|
+
error.type = diagnostic.level;
|
|
94
|
+
errors.push(error);
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Ensure that all modules which created a persisted SyncConfig
|
|
99
|
+
* are currently loaded.
|
|
100
|
+
* This prevents a case for a SyncConfig with missing external modules to be loaded.
|
|
101
|
+
*/
|
|
102
|
+
const requiredIds = new Set(
|
|
103
|
+
config instanceof PrecompiledSyncConfig ? Object.keys(config.plan.moduleData ?? {}) : []
|
|
104
|
+
);
|
|
105
|
+
const registeredIds = new Set(this.#parsers.map((parser) => parser.id));
|
|
106
|
+
const missingIds = [...requiredIds].filter((id) => !registeredIds.has(id));
|
|
107
|
+
if (missingIds.length != 0) {
|
|
108
|
+
reportDiagnostic({
|
|
109
|
+
level: 'fatal',
|
|
110
|
+
message: `Missing required sync config parsers: ${missingIds.join(', ')}`
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
for (const parser of this.#parsers) {
|
|
115
|
+
if (!requiredIds.has(parser.id)) continue;
|
|
116
|
+
/**
|
|
117
|
+
* This allows additional validation of module specific semantics
|
|
118
|
+
*/
|
|
119
|
+
parser.validatePersisted?.({ config, context: { ...context, reportDiagnostic } });
|
|
120
|
+
}
|
|
121
|
+
if (errors.some((error) => error.type == 'fatal')) throw new SyncRulesErrors(errors);
|
|
122
|
+
return errors;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
@@ -11,11 +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';
|
|
17
16
|
import { SourceTableCandidateReconciler } from './SourceTableReconciler.js';
|
|
18
17
|
import { StorageVersionConfig } from './StorageVersionConfig.js';
|
|
18
|
+
import { ParseSyncConfigOptions } from './SyncConfigParser.js';
|
|
19
19
|
import { SyncStorageWriteCheckpointAPI } from './WriteCheckpointAPI.js';
|
|
20
20
|
|
|
21
21
|
/**
|
|
@@ -402,6 +402,8 @@ export interface CompactOptions {
|
|
|
402
402
|
}
|
|
403
403
|
|
|
404
404
|
export interface CompactInitialReplicationOptions {
|
|
405
|
+
/** Internal/testing use: bypass the new-chunk threshold in MongoDB V3/V4 storage. */
|
|
406
|
+
forceChunkCompaction?: boolean;
|
|
405
407
|
/**
|
|
406
408
|
* Compact data up to this op id.
|
|
407
409
|
*
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CompatibilityContext } from '@powersync/service-sync-rules';
|
|
1
|
+
import { CompatibilityContext, sourceTableConfigsEqual } from '@powersync/service-sync-rules';
|
|
2
2
|
import { Logger } from 'winston';
|
|
3
3
|
import { SerializedSyncPlan, UpdateSyncRulesOptions } from '../BucketStorageFactory.js';
|
|
4
4
|
|
|
@@ -11,8 +11,8 @@ export function isCompatible(
|
|
|
11
11
|
logger: Logger
|
|
12
12
|
): boolean {
|
|
13
13
|
if (updateConfig.plan == null) {
|
|
14
|
-
// Only support
|
|
15
|
-
logger.info(`Not using current
|
|
14
|
+
// Only support Sync Streams with serialized plans
|
|
15
|
+
logger.info(`Not using current Sync Streams - incremental reprocessing not supported`);
|
|
16
16
|
return false;
|
|
17
17
|
}
|
|
18
18
|
|
|
@@ -23,8 +23,8 @@ export function isCompatible(
|
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
if (existingPlans.some((plan) => plan == null)) {
|
|
26
|
-
// Only support
|
|
27
|
-
logger.info(`Existing replication stream not using current
|
|
26
|
+
// Only support Sync Streams with serialized plans
|
|
27
|
+
logger.info(`Existing replication stream not using current Sync Streams - incremental reprocessing not supported`);
|
|
28
28
|
return false;
|
|
29
29
|
}
|
|
30
30
|
|
|
@@ -37,5 +37,17 @@ export function isCompatible(
|
|
|
37
37
|
return false;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
if (
|
|
41
|
+
existingPlans.some(
|
|
42
|
+
(existing) =>
|
|
43
|
+
!sourceTableConfigsEqual(
|
|
44
|
+
existing!.plan.sourceTableConfig ?? {},
|
|
45
|
+
updateConfig.plan!.plan.sourceTableConfig ?? {}
|
|
46
|
+
)
|
|
47
|
+
)
|
|
48
|
+
) {
|
|
49
|
+
logger.info('Source table configuration changed - incremental reprocessing not supported');
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
40
52
|
return true;
|
|
41
53
|
}
|
|
@@ -25,3 +25,4 @@ export * from './implementation/BucketDefinitionMapping.js';
|
|
|
25
25
|
export * from './implementation/IncrementalReprocessingCompatibility.js';
|
|
26
26
|
export * from './implementation/IncrementalReprocessingSyncConfigLog.js';
|
|
27
27
|
export * from './implementation/ReplicationStreamStorageIds.js';
|
|
28
|
+
export * from './SyncConfigParser.js';
|
|
@@ -89,7 +89,7 @@ export class BucketChecksumState {
|
|
|
89
89
|
* subscribed to, we keep an index of the stream names to their index in that array.
|
|
90
90
|
*
|
|
91
91
|
* This is used to compress the representation of buckets in `checkpoint` and `checkpoint_diff` lines: For buckets
|
|
92
|
-
* that are part of
|
|
92
|
+
* that are part of legacy Sync Rules or default streams, we need to include the name of the defining bucket definition or stream
|
|
93
93
|
* yielding that bucket (so that clients can track progress for default streams).
|
|
94
94
|
* But instead of sending the name for each bucket, we use the fact that it's part of the streams array and only send
|
|
95
95
|
* their index, reducing the size of those messages.
|
|
@@ -747,7 +747,8 @@ export class BucketParameterState {
|
|
|
747
747
|
}
|
|
748
748
|
}
|
|
749
749
|
}
|
|
750
|
-
|
|
750
|
+
// A stream can reach the same bucket through both static and dynamic parameters.
|
|
751
|
+
const allBuckets = mergeBuckets([...staticBuckets, ...dynamicBuckets]);
|
|
751
752
|
|
|
752
753
|
if (invalidateDataBuckets) {
|
|
753
754
|
return {
|
|
@@ -816,7 +817,7 @@ function logCheckpoint(
|
|
|
816
817
|
}
|
|
817
818
|
|
|
818
819
|
/**
|
|
819
|
-
* Format a breakdown of dynamic buckets by
|
|
820
|
+
* Format a breakdown of dynamic buckets by Sync Stream or legacy bucket definition.
|
|
820
821
|
*
|
|
821
822
|
* Sorts definitions by count (descending), includes the top 100, and returns both the
|
|
822
823
|
* formatted message string and the counts record suitable for structured log data.
|
|
@@ -834,7 +835,7 @@ function formatBucketDefinitionBreakdown(
|
|
|
834
835
|
const allSorted = Array.from(bucketsByDefinition.entries()).sort((a, b) => b[1] - a[1]);
|
|
835
836
|
const sortedDefinitions = allSorted.slice(0, maxLoggedDefinitions);
|
|
836
837
|
|
|
837
|
-
const sourceLabel = bucketSourceType == BucketSourceType.SYNC_STREAM ? '
|
|
838
|
+
const sourceLabel = bucketSourceType == BucketSourceType.SYNC_STREAM ? 'Sync Stream' : 'bucket definition';
|
|
838
839
|
let message = `\nBuckets by ${sourceLabel}:`;
|
|
839
840
|
const countsByDefinition: Record<string, number> = {};
|
|
840
841
|
for (const [definition, count] of sortedDefinitions) {
|
package/src/sync/util.ts
CHANGED
|
@@ -144,8 +144,11 @@ export async function* transformToBytesTracked(
|
|
|
144
144
|
|
|
145
145
|
export function acquireSemaphoreAbortable(
|
|
146
146
|
semaphone: SemaphoreInterface,
|
|
147
|
-
abort
|
|
147
|
+
abort?: AbortSignal
|
|
148
148
|
): Promise<[number, SemaphoreInterface.Releaser] | 'aborted'> {
|
|
149
|
+
if (abort == null) {
|
|
150
|
+
return semaphone.acquire();
|
|
151
|
+
}
|
|
149
152
|
return new Promise((resolve, reject) => {
|
|
150
153
|
// An already-aborted signal never fires its listener, and we would wait for the semaphore
|
|
151
154
|
// indefinitely.
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { container, LifeCycledSystem, MigrationManager, ServiceIdentifier } from '@powersync/lib-services-framework';
|
|
2
|
+
import type { AdditionalSyncConfigParser } from '@powersync/service-sync-rules';
|
|
2
3
|
|
|
3
4
|
import { EventsEngine } from '../events/EventsEngine.js';
|
|
4
5
|
import { framework } from '../index.js';
|
|
@@ -10,6 +11,16 @@ import * as storage from '../storage/storage-index.js';
|
|
|
10
11
|
import { SyncContext } from '../sync/SyncContext.js';
|
|
11
12
|
import * as utils from '../util/util-index.js';
|
|
12
13
|
|
|
14
|
+
/**
|
|
15
|
+
* Registration-capable sync-config parser exposed to modules through the service context.
|
|
16
|
+
*/
|
|
17
|
+
export interface ServiceContextSyncConfigParser extends storage.SyncConfigParser {
|
|
18
|
+
/**
|
|
19
|
+
* Registers a deterministic parser extension during module initialization, before storage starts.
|
|
20
|
+
*/
|
|
21
|
+
registerParser(extension: AdditionalSyncConfigParser): void;
|
|
22
|
+
}
|
|
23
|
+
|
|
13
24
|
export interface ServiceContext {
|
|
14
25
|
configuration: utils.ResolvedPowerSyncConfig;
|
|
15
26
|
lifeCycleEngine: LifeCycledSystem;
|
|
@@ -22,6 +33,11 @@ export interface ServiceContext {
|
|
|
22
33
|
writeCheckpointBatcher: utils.WriteCheckpointBatcher;
|
|
23
34
|
serviceMode: ServiceContextMode;
|
|
24
35
|
eventsEngine: EventsEngine;
|
|
36
|
+
/**
|
|
37
|
+
* Service-wide parser shared by routes, replication, and storage. Source modules register parser extensions on this
|
|
38
|
+
* instance during module initialization.
|
|
39
|
+
*/
|
|
40
|
+
readonly syncConfigParser: ServiceContextSyncConfigParser;
|
|
25
41
|
}
|
|
26
42
|
|
|
27
43
|
export enum ServiceContextMode {
|
|
@@ -53,16 +69,20 @@ export class ServiceContextContainer implements ServiceContext {
|
|
|
53
69
|
routerEngine: routes.RouterEngine;
|
|
54
70
|
writeCheckpointBatcher: utils.WriteCheckpointBatcher;
|
|
55
71
|
serviceMode: ServiceContextMode;
|
|
72
|
+
readonly #syncConfigParser: ServiceContextSyncConfigParser;
|
|
56
73
|
|
|
57
74
|
constructor(options: ServiceContextOptions) {
|
|
58
75
|
this.serviceMode = options.serviceMode;
|
|
59
76
|
const { configuration } = options;
|
|
60
77
|
this.configuration = configuration;
|
|
61
78
|
|
|
79
|
+
this.#syncConfigParser = new ServiceContextSyncConfigParserImpl(() => this.storageEngine.started);
|
|
80
|
+
|
|
62
81
|
this.lifeCycleEngine = new LifeCycledSystem();
|
|
63
82
|
|
|
64
83
|
this.storageEngine = new storage.StorageEngine({
|
|
65
|
-
configuration
|
|
84
|
+
configuration,
|
|
85
|
+
syncConfigParser: this.#syncConfigParser
|
|
66
86
|
});
|
|
67
87
|
this.storageEngine.registerListener({
|
|
68
88
|
storageFatalError: (error) => {
|
|
@@ -114,6 +134,13 @@ export class ServiceContextContainer implements ServiceContext {
|
|
|
114
134
|
return container.getOptional(replication.ReplicationEngine);
|
|
115
135
|
}
|
|
116
136
|
|
|
137
|
+
/**
|
|
138
|
+
* Returns the service-wide parser shared by routes, replication, and storage.
|
|
139
|
+
*/
|
|
140
|
+
get syncConfigParser(): ServiceContextSyncConfigParser {
|
|
141
|
+
return this.#syncConfigParser;
|
|
142
|
+
}
|
|
143
|
+
|
|
117
144
|
get metricsEngine(): metrics.MetricsEngine {
|
|
118
145
|
return container.getImplementation(metrics.MetricsEngine);
|
|
119
146
|
}
|
|
@@ -137,3 +164,22 @@ export class ServiceContextContainer implements ServiceContext {
|
|
|
137
164
|
return container.getImplementation(identifier);
|
|
138
165
|
}
|
|
139
166
|
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Registration-capable parser exposed by the service context during module initialization.
|
|
170
|
+
*/
|
|
171
|
+
class ServiceContextSyncConfigParserImpl extends storage.SqlSyncConfigParser implements ServiceContextSyncConfigParser {
|
|
172
|
+
constructor(private readonly isStorageStarted: () => boolean) {
|
|
173
|
+
super();
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Registers an extension while preserving one parser definition for the service lifetime.
|
|
178
|
+
*/
|
|
179
|
+
override registerParser(extension: AdditionalSyncConfigParser): void {
|
|
180
|
+
if (this.isStorageStarted()) {
|
|
181
|
+
throw new Error('A sync config parser extension cannot be registered after the storage engine has started.');
|
|
182
|
+
}
|
|
183
|
+
super.registerParser(extension);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
@@ -18,8 +18,9 @@ export const DEFAULT_PARAM_LOGGING_FORMAT_OPTIONS: ParamLoggingFormatOptions = {
|
|
|
18
18
|
* Formats potentially arbitrary parameters for logging.
|
|
19
19
|
* This limits the number of keys and strings to a maximum length.
|
|
20
20
|
* A warning key-value is added if the number of keys exceeds the maximum.
|
|
21
|
-
*
|
|
21
|
+
* Keys and string values exceeding the maximum length are truncated.
|
|
22
22
|
* Non-String values are stringified, the maximum length is then applied.
|
|
23
|
+
* Values that cannot be serialized are replaced with a placeholder.
|
|
23
24
|
* @param params - The parameters to format.
|
|
24
25
|
* @param options - The options to use.
|
|
25
26
|
* @default DEFAULT_PARAM_LOGGING_FORMAT_OPTIONS
|
|
@@ -41,20 +42,26 @@ export function limitParamsForLogging(
|
|
|
41
42
|
return value;
|
|
42
43
|
}
|
|
43
44
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
45
|
+
function formatValue(value: unknown): string {
|
|
46
|
+
if (typeof value == 'string') {
|
|
47
|
+
return trimString(value);
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
return trimString(JSON.stringify(value) ?? '[undefined]');
|
|
51
|
+
} catch {
|
|
52
|
+
return trimString('[unserializable]');
|
|
53
|
+
}
|
|
54
|
+
}
|
|
49
55
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
56
|
+
return Object.fromEntries(
|
|
57
|
+
Object.entries(params)
|
|
58
|
+
.slice(0, maxKeyCount + 1)
|
|
59
|
+
.map(([key, value], index) => {
|
|
60
|
+
if (index == maxKeyCount) {
|
|
61
|
+
return ['⚠️', 'Additional parameters omitted'];
|
|
62
|
+
}
|
|
53
63
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
}
|
|
57
|
-
return [key, trimString(JSON.stringify(value))];
|
|
58
|
-
})
|
|
64
|
+
return [trimString(key), formatValue(value)];
|
|
65
|
+
})
|
|
59
66
|
);
|
|
60
67
|
}
|
|
@@ -19,7 +19,7 @@ export type BucketRequest = t.Decoded<typeof BucketRequest>;
|
|
|
19
19
|
*/
|
|
20
20
|
export const RequestedStreamSubscription = t.object({
|
|
21
21
|
/**
|
|
22
|
-
* The defined name of the stream as it appears in
|
|
22
|
+
* The defined name of the stream as it appears in Sync Stream definitions.
|
|
23
23
|
*/
|
|
24
24
|
stream: t.string,
|
|
25
25
|
/**
|
|
@@ -29,7 +29,7 @@ export const RequestedStreamSubscription = t.object({
|
|
|
29
29
|
/**
|
|
30
30
|
* Set when the client wishes to re-assign a different priority to this stream.
|
|
31
31
|
*
|
|
32
|
-
* Streams and
|
|
32
|
+
* Sync Streams and legacy bucket definitions can also assign a default priority, but clients are allowed to override those. This can be
|
|
33
33
|
* useful when the priority for partial syncs depends on e.g. the current page opened in a client.
|
|
34
34
|
*/
|
|
35
35
|
override_priority: orNull(t.number)
|
|
@@ -49,7 +49,7 @@ export const StreamSubscriptionRequest = t.object({
|
|
|
49
49
|
include_defaults: t.boolean.optional(),
|
|
50
50
|
|
|
51
51
|
/**
|
|
52
|
-
* An array of
|
|
52
|
+
* An array of Sync Streams the client has opened explicitly.
|
|
53
53
|
*/
|
|
54
54
|
subscriptions: t.array(RequestedStreamSubscription)
|
|
55
55
|
});
|
|
@@ -253,8 +253,8 @@ export interface BucketChecksum {
|
|
|
253
253
|
/**
|
|
254
254
|
* The reason a particular bucket is included in a checkpoint.
|
|
255
255
|
*
|
|
256
|
-
* This information allows clients to associate individual buckets with
|
|
257
|
-
* association is useful because it enables clients to track progress for individual
|
|
256
|
+
* This information allows clients to associate individual buckets with Sync Streams they're subscribed to. Having that
|
|
257
|
+
* association is useful because it enables clients to track progress for individual Sync Streams.
|
|
258
258
|
*/
|
|
259
259
|
export type BucketSubscriptionReason = BucketDerivedFromDefaultStream | BucketDerivedFromExplicitSubscription;
|
|
260
260
|
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { AbstractReplicationJob } from '@/replication/AbstractReplicationJob.js';
|
|
2
2
|
import { AbstractReplicator, AbstractReplicatorOptions, CreateJobOptions } from '@/replication/AbstractReplicator.js';
|
|
3
3
|
import { PersistedReplicationStream } from '@/storage/PersistedReplicationStream.js';
|
|
4
|
+
import { SqlSyncConfigParser } from '@/storage/SyncConfigParser.js';
|
|
4
5
|
import { SyncRulesBucketStorage } from '@/storage/SyncRulesBucketStorage.js';
|
|
6
|
+
import { PrecompiledSyncConfig } from '@powersync/service-sync-rules';
|
|
5
7
|
import { describe, expect, it, vi } from 'vitest';
|
|
6
8
|
|
|
7
9
|
class TestReplicator extends AbstractReplicator {
|
|
@@ -45,6 +47,13 @@ class TestReplicator extends AbstractReplicator {
|
|
|
45
47
|
return (this as any).heartbeatIntervalNanos;
|
|
46
48
|
}
|
|
47
49
|
|
|
50
|
+
async runStartupForTest(): Promise<void> {
|
|
51
|
+
const controller = new AbortController();
|
|
52
|
+
controller.abort();
|
|
53
|
+
(this as any).abortController = controller;
|
|
54
|
+
await (this as any).runLoop();
|
|
55
|
+
}
|
|
56
|
+
|
|
48
57
|
shouldHandleStreamForTest(
|
|
49
58
|
replicationStream: PersistedReplicationStream,
|
|
50
59
|
loadedSyncRules: string | undefined,
|
|
@@ -54,6 +63,67 @@ class TestReplicator extends AbstractReplicator {
|
|
|
54
63
|
}
|
|
55
64
|
}
|
|
56
65
|
|
|
66
|
+
describe('AbstractReplicator startup sync config', () => {
|
|
67
|
+
it.each([true, false])('retains registered module options with exit_on_error=%s', async (exitOnError) => {
|
|
68
|
+
const syncConfigParser = new SqlSyncConfigParser([
|
|
69
|
+
{
|
|
70
|
+
id: 'example.tables',
|
|
71
|
+
extendJsonSchema({ schema }) {
|
|
72
|
+
(schema.properties as any).config.properties.source_table_options.additionalProperties.properties.sample = {
|
|
73
|
+
type: 'number'
|
|
74
|
+
};
|
|
75
|
+
},
|
|
76
|
+
parse({ config, context }) {
|
|
77
|
+
const sourceTables = (config as { config: { source_table_options: { orders: { sample: number } } } }).config
|
|
78
|
+
.source_table_options;
|
|
79
|
+
context.parsedConfig.sourceTableConfig = sourceTables;
|
|
80
|
+
(context.parsedConfig as PrecompiledSyncConfig).plan.moduleData = { 'example.tables': null };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
]);
|
|
84
|
+
const yaml = /* yaml */ `
|
|
85
|
+
{
|
|
86
|
+
config: { edition: 3, source_table_options: { orders: { sample: 10 } } },
|
|
87
|
+
streams: { orders: { query: SELECT * FROM orders } }
|
|
88
|
+
}
|
|
89
|
+
`;
|
|
90
|
+
const configureSyncRules = vi.fn(async () => ({ updated: false }));
|
|
91
|
+
const replicator = new TestReplicator(async () => {}, {
|
|
92
|
+
id: 'test',
|
|
93
|
+
storageEngine: {
|
|
94
|
+
activeBucketStorage: { syncConfigParser, configureSyncRules }
|
|
95
|
+
} as unknown as AbstractReplicatorOptions['storageEngine'],
|
|
96
|
+
syncRuleProvider: { get: async () => yaml, exitOnError, versionLabel: 'v2' },
|
|
97
|
+
metricsEngine: {} as AbstractReplicatorOptions['metricsEngine'],
|
|
98
|
+
rateLimiter: {} as AbstractReplicatorOptions['rateLimiter']
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
await replicator.runStartupForTest();
|
|
102
|
+
|
|
103
|
+
expect(configureSyncRules).toHaveBeenCalledExactlyOnceWith(
|
|
104
|
+
expect.objectContaining({
|
|
105
|
+
lock: true,
|
|
106
|
+
version_label: 'v2',
|
|
107
|
+
config: expect.objectContaining({
|
|
108
|
+
parsed: expect.objectContaining({
|
|
109
|
+
errors: [],
|
|
110
|
+
config: expect.objectContaining({
|
|
111
|
+
sourceTableConfig: { orders: { sample: 10 } }
|
|
112
|
+
})
|
|
113
|
+
}),
|
|
114
|
+
plan: expect.objectContaining({
|
|
115
|
+
plan: expect.objectContaining({
|
|
116
|
+
version: 3,
|
|
117
|
+
sourceTableConfig: { orders: { sample: 10 } },
|
|
118
|
+
moduleData: { 'example.tables': null }
|
|
119
|
+
})
|
|
120
|
+
})
|
|
121
|
+
})
|
|
122
|
+
})
|
|
123
|
+
);
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
|
|
57
127
|
describe('AbstractReplicator heartbeat interval', () => {
|
|
58
128
|
const options: AbstractReplicatorOptions = {
|
|
59
129
|
id: 'test',
|
|
@@ -11,6 +11,7 @@ import { describe, expect, test } from 'vitest';
|
|
|
11
11
|
import {
|
|
12
12
|
parsePersistedSyncConfigContent,
|
|
13
13
|
SerializedSyncPlan,
|
|
14
|
+
SqlSyncConfigParser,
|
|
14
15
|
updateSyncRulesFromConfig
|
|
15
16
|
} from '../../src/storage/storage-index.js';
|
|
16
17
|
|
|
@@ -147,6 +148,7 @@ function restore(compiledPlan: SerializedSyncPlan) {
|
|
|
147
148
|
content: yamlWithEvents,
|
|
148
149
|
compiledPlan,
|
|
149
150
|
storageVersion: 1,
|
|
150
|
-
parseOptions: { defaultSchema: 'test_schema' }
|
|
151
|
+
parseOptions: { defaultSchema: 'test_schema' },
|
|
152
|
+
syncConfigParser: new SqlSyncConfigParser()
|
|
151
153
|
});
|
|
152
154
|
}
|