@powersync/service-module-mongodb-storage 0.26.2 → 0.27.0

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 (68) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/storage/MongoBucketStorage.d.ts +3 -1
  3. package/dist/storage/MongoBucketStorage.js +2 -1
  4. package/dist/storage/MongoBucketStorage.js.map +1 -1
  5. package/dist/storage/implementation/MongoBucketBatch.d.ts +12 -1
  6. package/dist/storage/implementation/MongoBucketBatch.js +115 -50
  7. package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
  8. package/dist/storage/implementation/MongoStorageProvider.js +2 -1
  9. package/dist/storage/implementation/MongoStorageProvider.js.map +1 -1
  10. package/dist/storage/implementation/MongoSyncBucketStorage.d.ts +3 -0
  11. package/dist/storage/implementation/MongoSyncBucketStorage.js +2 -0
  12. package/dist/storage/implementation/MongoSyncBucketStorage.js.map +1 -1
  13. package/dist/storage/implementation/OperationBatch.d.ts +24 -2
  14. package/dist/storage/implementation/OperationBatch.js +21 -1
  15. package/dist/storage/implementation/OperationBatch.js.map +1 -1
  16. package/dist/storage/implementation/common/BatchOperationBuffer.js +15 -3
  17. package/dist/storage/implementation/common/BatchOperationBuffer.js.map +1 -1
  18. package/dist/storage/implementation/common/PersistedBatch.d.ts +3 -3
  19. package/dist/storage/implementation/common/SourceRecordStore.d.ts +3 -3
  20. package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.js +4 -1
  21. package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.js.map +1 -1
  22. package/dist/storage/implementation/v1/PersistedBatchV1.js +3 -0
  23. package/dist/storage/implementation/v1/PersistedBatchV1.js.map +1 -1
  24. package/dist/storage/implementation/v1/SourceRecordStoreV1.d.ts +3 -3
  25. package/dist/storage/implementation/v1/SourceRecordStoreV1.js +10 -4
  26. package/dist/storage/implementation/v1/SourceRecordStoreV1.js.map +1 -1
  27. package/dist/storage/implementation/v3/MongoBucketBatchV3.d.ts +10 -1
  28. package/dist/storage/implementation/v3/MongoBucketBatchV3.js +47 -4
  29. package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
  30. package/dist/storage/implementation/v3/MongoRustEvaluator.d.ts +19 -0
  31. package/dist/storage/implementation/v3/MongoRustEvaluator.js +51 -0
  32. package/dist/storage/implementation/v3/MongoRustEvaluator.js.map +1 -0
  33. package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.js +20 -3
  34. package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.js.map +1 -1
  35. package/dist/storage/implementation/v3/PersistedBatchV3.js +15 -3
  36. package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
  37. package/dist/storage/implementation/v3/SourceRecordStoreV3.d.ts +3 -3
  38. package/dist/storage/implementation/v3/SourceRecordStoreV3.js +15 -5
  39. package/dist/storage/implementation/v3/SourceRecordStoreV3.js.map +1 -1
  40. package/dist/storage/implementation/v3/source-table-utils.d.ts +3 -1
  41. package/dist/storage/implementation/v3/source-table-utils.js +23 -11
  42. package/dist/storage/implementation/v3/source-table-utils.js.map +1 -1
  43. package/dist/types/types.d.ts +13 -0
  44. package/dist/types/types.js +13 -1
  45. package/dist/types/types.js.map +1 -1
  46. package/dist/utils/test-utils.js +2 -1
  47. package/dist/utils/test-utils.js.map +1 -1
  48. package/package.json +5 -5
  49. package/src/storage/MongoBucketStorage.ts +6 -2
  50. package/src/storage/implementation/MongoBucketBatch.ts +165 -72
  51. package/src/storage/implementation/MongoStorageProvider.ts +2 -1
  52. package/src/storage/implementation/MongoSyncBucketStorage.ts +5 -1
  53. package/src/storage/implementation/OperationBatch.ts +33 -3
  54. package/src/storage/implementation/common/BatchOperationBuffer.ts +16 -3
  55. package/src/storage/implementation/common/PersistedBatch.ts +9 -3
  56. package/src/storage/implementation/common/SourceRecordStore.ts +10 -3
  57. package/src/storage/implementation/v1/MongoSyncBucketStorageV1.ts +5 -1
  58. package/src/storage/implementation/v1/PersistedBatchV1.ts +4 -0
  59. package/src/storage/implementation/v1/SourceRecordStoreV1.ts +14 -7
  60. package/src/storage/implementation/v3/MongoBucketBatchV3.ts +54 -5
  61. package/src/storage/implementation/v3/MongoRustEvaluator.ts +64 -0
  62. package/src/storage/implementation/v3/MongoSyncBucketStorageV3.ts +28 -3
  63. package/src/storage/implementation/v3/PersistedBatchV3.ts +22 -4
  64. package/src/storage/implementation/v3/SourceRecordStoreV3.ts +18 -8
  65. package/src/storage/implementation/v3/source-table-utils.ts +34 -8
  66. package/src/types/types.ts +17 -1
  67. package/src/utils/test-utils.ts +2 -1
  68. package/tsconfig.tsbuildinfo +1 -1
@@ -6,7 +6,7 @@ import {
6
6
  ServiceAssertionError,
7
7
  ServiceError
8
8
  } from '@powersync/lib-services-framework';
9
- import { InternalOpId, storage } from '@powersync/service-core';
9
+ import { InternalOpId, ProcessUndecodedDocument, storage } from '@powersync/service-core';
10
10
  import { EventDefinitionId, HydratedEventDescriptor } from '@powersync/service-sync-rules';
11
11
  import * as bson from 'bson';
12
12
  import { mongoTableId } from '../../../utils/util.js';
@@ -21,6 +21,7 @@ import { stopReplicationStreamPipeline } from '../SyncRuleStateUpdate.js';
21
21
  import { PreparedPublication } from '../common/PreparedPublication.js';
22
22
  import { LoadedSourceRecord } from '../common/SourceRecordStore.js';
23
23
  import { SyncRuleDocumentBase } from '../models.js';
24
+ import { MongoRustEvaluator } from './MongoRustEvaluator.js';
24
25
  import { PersistedBatchV3 } from './PersistedBatchV3.js';
25
26
  import { ReplicationPipelineV3 } from './ReplicationPipelineV3.js';
26
27
  import { SourceRecordStoreV3 } from './SourceRecordStoreV3.js';
@@ -62,6 +63,8 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
62
63
  private readonly knownEventIds: ReadonlySet<EventDefinitionId>;
63
64
  private readonly syncConfigIds: bson.ObjectId[];
64
65
  private needsActivationV3 = true;
66
+ /** Evaluator for rows passed as undecoded BSON, or null if Rust evaluation is disabled. */
67
+ private readonly rustEvaluator: MongoRustEvaluator | null;
65
68
  private lastWaitingLogThrottledV3 = 0;
66
69
 
67
70
  constructor(options: MongoBucketBatchOptions) {
@@ -78,6 +81,7 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
78
81
  this.syncConfigIds = syncConfigIds;
79
82
  this.knownEventIds = new Set(this.mapping.allEventDefinitionIds());
80
83
  this.store = new SourceRecordStoreV3(this.db, this.replicationStreamId, this.mapping);
84
+ this.rustEvaluator = options.rust == null ? null : new MongoRustEvaluator(options.rust, this.sync_rules);
81
85
  this.pipeline.registerWriter(this);
82
86
  }
83
87
 
@@ -106,6 +110,13 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
106
110
  override async save(record: storage.SaveOptions): Promise<storage.FlushedResult | null> {
107
111
  try {
108
112
  this.options.replicationLock.throwIfAborted();
113
+ if (this.rustEvaluator?.options.force) {
114
+ throw new ServiceError(
115
+ ErrorCode.PSYNC_S1006,
116
+ 'Received decoded row from source database that should be evaluated in Rust.'
117
+ );
118
+ }
119
+
109
120
  // No await or mutex is needed to append an input event. Flushes detach their
110
121
  // input before yielding, so preparation never reads this mutable buffer.
111
122
  // A full buffer still waits for preparation capacity, bounding read-ahead.
@@ -119,6 +130,30 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
119
130
  }
120
131
  }
121
132
 
133
+ prepareUndecodedSave(format: unknown): ProcessUndecodedDocument | undefined {
134
+ if (format !== 'bson' || this.rustEvaluator == null) return;
135
+
136
+ return (record: storage.SaveUndecodedOptions) => this.saveUndecoded(record);
137
+ }
138
+
139
+ /**
140
+ * Like {@link save}, but for rows passed as raw BSON documents.
141
+ *
142
+ * These rows are evaluated in Rust once the batch is captured for a flush (see {@link takeBufferedInput}).
143
+ */
144
+ private async saveUndecoded(record: storage.SaveUndecodedOptions): Promise<storage.FlushedResult | null> {
145
+ try {
146
+ this.options.replicationLock.throwIfAborted();
147
+ if (this.bufferRecord(record)) {
148
+ return await this.automaticFlush();
149
+ }
150
+ return null;
151
+ } catch (error) {
152
+ this.pipeline.fail(error);
153
+ throw error;
154
+ }
155
+ }
156
+
122
157
  override async commit(lsn: string, options?: storage.BucketBatchCommitOptions): Promise<storage.CheckpointResult> {
123
158
  this.options.replicationLock.throwIfAborted();
124
159
  if (this.markRecordUnavailable != null && (this.batch?.length ?? 0) > 0) {
@@ -174,6 +209,13 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
174
209
  private takeBufferedInput(): OperationBatch | null {
175
210
  const input = this.batch;
176
211
  this.batch = null;
212
+ if (input != null && this.rustEvaluator != null && input.length > 0) {
213
+ // The batch is complete, so start evaluating undecoded rows in the background. This overlaps with waiting for
214
+ // the writer lock, the predecessor's publication and the source record lookup. prepareRows() awaits the results.
215
+ input.rustEvaluation = this.rustEvaluator.evaluate(input.batch);
216
+ // Failures are surfaced by prepareRows(). Avoid unhandled rejections if the input is abandoned before that.
217
+ input.rustEvaluation.catch(() => {});
218
+ }
177
219
  return input;
178
220
  }
179
221
 
@@ -628,6 +670,11 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
628
670
  records.set(op.internalBeforeKey, loaded.get(op.internalBeforeKey) ?? null);
629
671
  }
630
672
  }
673
+ if (input.rustEvaluation != null) {
674
+ // Rust is evaluating rows on a background thread, we need results as we start iterating over blocks.
675
+ using _rust = this.tracer.span('storage', 'wait_for_rust');
676
+ await input.rustEvaluation;
677
+ }
631
678
  let group: PersistedBatchV3 | null = this.createPersistedBatch(writtenSize);
632
679
  for (const op of block) {
633
680
  if (resumeBatch != null) {
@@ -915,7 +962,7 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
915
962
  .toArray();
916
963
 
917
964
  const candidateTables = candidateDocs.map((doc) =>
918
- sourceTableFromDocument(doc, source.connectionTag, syncConfig, mapping, eventById)
965
+ sourceTableFromDocument(doc, source.connectionTag, syncConfig, mapping, eventById, this.options.rust ?? null)
919
966
  );
920
967
  const candidates = candidateTables.map((table) => table.clone());
921
968
  const resolution = await reconcile({ source, candidates });
@@ -935,7 +982,8 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
935
982
  mapping,
936
983
  desired: sourceTableDesiredResolution(syncConfig, source, mapping, eventById),
937
984
  sourceCompatibleTables: resolution.compatibleTables,
938
- newTableSourceMetadata: resolution.newTableValues.sourceMetadata
985
+ newTableSourceMetadata: resolution.newTableValues.sourceMetadata,
986
+ rust: this.options.rust ?? null
939
987
  };
940
988
 
941
989
  // Plan record reuse, membership changes, creation, and removal.
@@ -973,7 +1021,7 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
973
1021
  result = {
974
1022
  tables: plan.tables,
975
1023
  dropTables: plan.dropDocs.map((doc) =>
976
- sourceTableFromDocument(doc, context.connectionTag, syncConfig, mapping, eventById)
1024
+ sourceTableFromDocument(doc, context.connectionTag, syncConfig, mapping, eventById, context.rust)
977
1025
  )
978
1026
  };
979
1027
  }, session);
@@ -996,7 +1044,8 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
996
1044
  table.ref.connectionTag,
997
1045
  this.sync_rules,
998
1046
  this.mapping,
999
- this.options.parsedSyncConfig.eventById
1047
+ this.options.parsedSyncConfig.eventById,
1048
+ this.options.rust ?? null
1000
1049
  );
1001
1050
  }
1002
1051
 
@@ -0,0 +1,64 @@
1
+ import { ReplicationAssertionError } from '@powersync/lib-services-framework';
2
+ import { RustAddon } from '@powersync/service-core';
3
+ import { HydratedSyncConfig, RustInputBatchBuilder, RustRowEvaluator } from '@powersync/service-sync-rules';
4
+ import { MAX_ROW_SIZE } from '../MongoBucketBatchShared.js';
5
+ import { RecordOperation } from '../OperationBatch.js';
6
+
7
+ export interface RustEvaluatorOptions {
8
+ addon: typeof RustAddon;
9
+ /** Whether using the Rust evaluator is forced, meaning that we should reject inputs not supported by Rust. */
10
+ force: boolean;
11
+ }
12
+
13
+ /** Result for documents that didn't produce any rows, parameters or errors. */
14
+ const EMPTY_RESULT = {
15
+ rows: [],
16
+ parameters: [],
17
+ errors: []
18
+ } as const;
19
+
20
+ export class MongoRustEvaluator {
21
+ readonly #eval: RustRowEvaluator;
22
+
23
+ constructor(
24
+ readonly options: RustEvaluatorOptions,
25
+ readonly syncConfig: HydratedSyncConfig
26
+ ) {
27
+ this.#eval = new RustRowEvaluator(options.addon, syncConfig.compatibility, MAX_ROW_SIZE);
28
+ }
29
+
30
+ /**
31
+ * Evaluates all undecoded operations without a result on a background thread, storing outputs in
32
+ * {@link RecordOperation.rustResult}.
33
+ */
34
+ async evaluate(operations: readonly RecordOperation[]): Promise<void> {
35
+ const pending: RecordOperation[] = [];
36
+ for (const op of operations) {
37
+ if (op.undecodedAfter != null && op.rustResult == null) {
38
+ pending.push(op);
39
+ }
40
+ }
41
+ if (pending.length == 0) {
42
+ return;
43
+ }
44
+
45
+ const builder = new RustInputBatchBuilder<RecordOperation>(pending.length);
46
+ for (const op of pending) {
47
+ const table = op.record.sourceTable.rustSourceTable;
48
+ if (table == null) {
49
+ // We don't currently support a hybrid Rust/JS implementation
50
+ throw new ReplicationAssertionError(`No Rust source table for ${op.record.sourceTable.qualifiedName}`);
51
+ }
52
+ builder.addBsonDocument(op, table, op.undecodedAfter!);
53
+ }
54
+
55
+ for (const { document, rows, parameters, errors } of await this.#eval.evaluateAsync(builder)) {
56
+ document.rustResult = { rows, parameters, errors };
57
+ }
58
+
59
+ // Outputs only include documents that produced rows, parameters or errors.
60
+ for (const op of pending) {
61
+ op.rustResult ??= EMPTY_RESULT;
62
+ }
63
+ }
64
+ }
@@ -1,6 +1,6 @@
1
1
  import * as lib_mongo from '@powersync/lib-service-mongodb';
2
2
  import { mongo } from '@powersync/lib-service-mongodb';
3
- import { ServiceAssertionError } from '@powersync/lib-services-framework';
3
+ import { container, ErrorCode, ServiceAssertionError, ServiceError } from '@powersync/lib-services-framework';
4
4
  import {
5
5
  CheckpointChanges,
6
6
  CompactInitialReplicationOptions,
@@ -10,6 +10,7 @@ import {
10
10
  internalToExternalOpId,
11
11
  ParameterSetLimitExceededError,
12
12
  ProtocolOpId,
13
+ RustModule,
13
14
  SingleSyncConfigBucketDefinitionMapping,
14
15
  storage,
15
16
  utils
@@ -17,6 +18,7 @@ import {
17
18
  import { JSONBig } from '@powersync/service-jsonbig';
18
19
  import { ParameterLookupRows, ScopedParameterLookup, SqliteJsonRow } from '@powersync/service-sync-rules';
19
20
  import * as bson from 'bson';
21
+ import { RustEvaluationPreference } from '../../../types/types.js';
20
22
  import { mapOpEntry, readSingleBatch, setSessionSnapshotTime } from '../../../utils/util.js';
21
23
  import { MongoBucketStorage } from '../../MongoBucketStorage.js';
22
24
  import { BucketDataDoc } from '../common/BucketDataDoc.js';
@@ -47,6 +49,7 @@ import { MongoBucketBatchV3 } from './MongoBucketBatchV3.js';
47
49
  import { MongoChecksumsV3 } from './MongoChecksumsV3.js';
48
50
  import { MongoCompactorV3 } from './MongoCompactorV3.js';
49
51
  import { MongoParameterCompactorV3 } from './MongoParameterCompactorV3.js';
52
+ import { RustEvaluatorOptions } from './MongoRustEvaluator.js';
50
53
  import { MongoStoppedSyncConfigCleanup } from './MongoStoppedSyncConfigCleanup.js';
51
54
  import { MongoWriteCheckpointAPIV3 } from './MongoWriteCheckpointAPIV3.js';
52
55
  import { hydrateBucketDataDocuments } from './object-storage/BucketDataObjectStorage.js';
@@ -118,10 +121,30 @@ function extractRowsFromDocument(
118
121
  return rows;
119
122
  }
120
123
 
124
+ /** Resolves the Rust addon from the service container if Rust evaluation is enabled. */
125
+ function resolveRustEvaluatorOptions(preference: RustEvaluationPreference): RustEvaluatorOptions | null {
126
+ if (preference == 'disable') {
127
+ return null;
128
+ }
129
+
130
+ const addon = container.getOptional(RustModule.id);
131
+ const force = preference == 'force';
132
+ if (addon == null) {
133
+ if (force) {
134
+ throw new ServiceError(
135
+ ErrorCode.PSYNC_S1006,
136
+ `storage.rust_evaluation is set to '${preference}', but the Rust addon is not loaded.`
137
+ );
138
+ }
139
+
140
+ return null;
141
+ }
142
+ return { addon, force };
143
+ }
144
+
121
145
  export class MongoSyncBucketStorageV3 extends MongoSyncBucketStorage {
122
146
  declare readonly db: VersionedPowerSyncMongoV3;
123
147
  declare readonly checksums: MongoChecksumsV3;
124
-
125
148
  constructor(
126
149
  factory: MongoBucketStorage,
127
150
  replicationStreamId: number,
@@ -246,6 +269,7 @@ export class MongoSyncBucketStorageV3 extends MongoSyncBucketStorage {
246
269
 
247
270
  protected async createWriterImpl(options: storage.CreateWriterOptions): Promise<storage.BucketStorageBatch> {
248
271
  const batchOptions = this.writerBatchOptions(options);
272
+ const rust = resolveRustEvaluatorOptions(this.rustEvaluation);
249
273
  const doc = await this.syncRulesCollection.findOne(
250
274
  { _id: this.replicationStreamId },
251
275
  { projection: { resume_lsn: 1 } }
@@ -256,7 +280,8 @@ export class MongoSyncBucketStorageV3 extends MongoSyncBucketStorage {
256
280
  // The stream-level replication position - per-config checkpoint LSNs are consistency
257
281
  // markers and do not affect where replication resumes.
258
282
  resumeFromLsn: doc?.resume_lsn ?? null,
259
- syncConfigIds: this.syncConfigIds
283
+ syncConfigIds: this.syncConfigIds,
284
+ rust
260
285
  });
261
286
  }
262
287
 
@@ -1,7 +1,12 @@
1
1
  import { mongo } from '@powersync/lib-service-mongodb';
2
2
  import { ReplicationAssertionError } from '@powersync/lib-services-framework';
3
3
  import { BucketDefinitionMapping, InternalOpId, storage } from '@powersync/service-core';
4
- import { BucketDefinitionId } from '@powersync/service-sync-rules';
4
+ import {
5
+ BucketDefinitionId,
6
+ ParameterIndexLookupCreator,
7
+ SqliteJsonValue,
8
+ SqliteRow
9
+ } from '@powersync/service-sync-rules';
5
10
  import * as bson from 'bson';
6
11
  import { mongoTableId } from '../../../utils/util.js';
7
12
  import { BatchOperationBuffer } from '../common/BatchOperationBuffer.js';
@@ -213,8 +218,21 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
213
218
  }
214
219
 
215
220
  for (let result of evaluated) {
216
- const sourceDefinitionId = this.mapping.parameterLookupId(result.lookup.source);
217
- const binLookup = serializeParameterLookup(result.lookup);
221
+ let source: ParameterIndexLookupCreator;
222
+ let binLookup: bson.Binary;
223
+ let outputParameters: SqliteRow<SqliteJsonValue>[];
224
+
225
+ if ('inputs' in result) {
226
+ source = result.scope.source;
227
+ binLookup = new bson.Binary(result.inputs);
228
+ outputParameters = result.outputs;
229
+ } else {
230
+ source = result.lookup.source;
231
+ binLookup = serializeParameterLookup(result.lookup);
232
+ outputParameters = result.bucketParameters;
233
+ }
234
+
235
+ const sourceDefinitionId = this.mapping.parameterLookupId(source);
218
236
  remaining_lookups.delete(`${sourceDefinitionId}.${binLookup.toString('base64')}`);
219
237
 
220
238
  const op_id = data.op_seq.next();
@@ -226,7 +244,7 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
226
244
  k: sourceKey
227
245
  },
228
246
  lookup: binLookup,
229
- bucket_parameters: result.bucketParameters
247
+ bucket_parameters: outputParameters
230
248
  };
231
249
  this.operations.bucketParameters.push({
232
250
  ...values,
@@ -2,7 +2,7 @@ import * as lib_mongo from '@powersync/lib-service-mongodb';
2
2
  import { mongo } from '@powersync/lib-service-mongodb';
3
3
  import { Logger } from '@powersync/lib-services-framework';
4
4
  import { BucketDefinitionMapping, storage } from '@powersync/service-core';
5
- import { EvaluatedParameters, EvaluatedRow } from '@powersync/service-sync-rules';
5
+ import { EvaluatedParameters, EvaluatedRow, RustParameter, RustRow } from '@powersync/service-sync-rules';
6
6
  import * as bson from 'bson';
7
7
  import { retryOnMongoMaxTimeMSExpired } from '../../../utils/util.js';
8
8
  import { REPLICATION_READ_OPTIONS, REPLICATION_WRITE_OPTIONS } from '../MongoReplicationOptions.js';
@@ -29,20 +29,30 @@ export class SourceRecordStoreV3 implements SourceRecordStore {
29
29
  private readonly mapping: BucketDefinitionMapping
30
30
  ) {}
31
31
 
32
- mapEvaluatedBuckets(evaluated: EvaluatedRow[]): LoadedSourceRecord['buckets'] {
32
+ mapEvaluatedBuckets(evaluated: (EvaluatedRow | RustRow)[]): LoadedSourceRecord['buckets'] {
33
33
  return evaluated.map((entry) => ({
34
- definitionId: this.mapping.bucketSourceId(entry.source),
34
+ definitionId: this.mapping.bucketSourceId('scope' in entry ? entry.scope.source : entry.source),
35
35
  bucket: entry.bucket,
36
36
  table: entry.table,
37
37
  id: entry.id
38
38
  }));
39
39
  }
40
40
 
41
- mapParameterLookups(paramEvaluated: EvaluatedParameters[]): LoadedSourceRecord['lookups'] {
42
- return paramEvaluated.map((entry) => ({
43
- indexId: this.mapping.parameterLookupId(entry.lookup.source),
44
- lookup: serializeParameterLookup(entry.lookup)
45
- }));
41
+ mapParameterLookups(paramEvaluated: (EvaluatedParameters | RustParameter)[]): LoadedSourceRecord['lookups'] {
42
+ return paramEvaluated.map((entry) => {
43
+ if ('inputs' in entry) {
44
+ // Evaluated in Rust, which serializes inputs in the same format as serializeParameterLookup.
45
+ return {
46
+ indexId: this.mapping.parameterLookupId(entry.scope.source),
47
+ lookup: new bson.Binary(entry.inputs)
48
+ };
49
+ }
50
+
51
+ return {
52
+ indexId: this.mapping.parameterLookupId(entry.lookup.source),
53
+ lookup: serializeParameterLookup(entry.lookup)
54
+ };
55
+ });
46
56
  }
47
57
 
48
58
  private createLoadedDocument(
@@ -6,13 +6,16 @@ import {
6
6
  EventDefinitionId,
7
7
  HydratedEventDescriptor,
8
8
  HydratedSyncConfig,
9
+ MatchingRustSources,
9
10
  MatchingSources,
10
11
  ParameterIndexId,
11
12
  ParameterIndexLookupCreator,
13
+ RustSourceTable,
12
14
  SourceTableRef
13
15
  } from '@powersync/service-sync-rules';
14
16
  import * as bson from 'bson';
15
17
  import { ReplicaIdColumn, SourceTableDocumentV3 } from './models.js';
18
+ import type { RustEvaluatorOptions } from './MongoRustEvaluator.js';
16
19
 
17
20
  export interface SourceTableIdentity {
18
21
  schema: string;
@@ -49,6 +52,7 @@ export interface SourceTableReconciliationContext {
49
52
  * Source metadata for records created by this resolution.
50
53
  */
51
54
  newTableSourceMetadata: JsonValue;
55
+ rust: RustEvaluatorOptions | null;
52
56
  }
53
57
 
54
58
  export interface SourceTableReconciliationPlan {
@@ -251,13 +255,14 @@ class SourceTableReconciliationPlanner {
251
255
  }
252
256
 
253
257
  private sourceTableFor(doc: SourceTableDocumentV3, memberships: SourceTableMembershipIds): storage.SourceTable {
254
- const { connectionTag, syncConfig, mapping, desired, storeCurrentData } = this.context;
258
+ const { connectionTag, syncConfig, mapping, desired, storeCurrentData, rust } = this.context;
255
259
  const built = sourceTableFromDocument(
256
260
  doc,
257
261
  connectionTag,
258
262
  syncConfig,
259
263
  mapping,
260
264
  desired.eventDefinitionById,
265
+ rust,
261
266
  matchingSourcesFor(desired, memberships),
262
267
  memberships
263
268
  );
@@ -297,7 +302,8 @@ export function createNewSourceTable(
297
302
  mapping,
298
303
  desired,
299
304
  storeCurrentData,
300
- newTableSourceMetadata
305
+ newTableSourceMetadata,
306
+ rust
301
307
  } = context;
302
308
  const doc: SourceTableDocumentV3 = {
303
309
  _id: id,
@@ -320,6 +326,7 @@ export function createNewSourceTable(
320
326
  syncConfig,
321
327
  mapping,
322
328
  desired.eventDefinitionById,
329
+ rust,
323
330
  matchingSourcesFor(desired, memberships),
324
331
  memberships
325
332
  );
@@ -346,16 +353,38 @@ function sourceTableMembershipsFromDocument(
346
353
  };
347
354
  }
348
355
 
356
+ function rustSourceTableFor(
357
+ syncConfig: HydratedSyncConfig,
358
+ rust: RustEvaluatorOptions | null,
359
+ memberships: MatchingSources,
360
+ ref: SourceTableRef
361
+ ): RustSourceTable | undefined {
362
+ if (rust == null) {
363
+ return undefined;
364
+ }
365
+ if (memberships.bucketDataSources.length == 0 && memberships.parameterLookupSources.length == 0) {
366
+ return undefined;
367
+ }
368
+
369
+ return MatchingRustSources.prepare(syncConfig, rust.addon, memberships)?.table(ref);
370
+ }
371
+
349
372
  export function sourceTableFromDocument(
350
373
  doc: SourceTableDocumentV3,
351
374
  connectionTag: string,
352
375
  syncConfig: HydratedSyncConfig,
353
376
  mapping: BucketDefinitionMapping,
354
377
  eventById: ReadonlyMap<EventDefinitionId, HydratedEventDescriptor>,
378
+ rust: RustEvaluatorOptions | null,
355
379
  memberships?: MatchingSources,
356
380
  membershipIds?: SourceTableMembershipIds
357
381
  ): storage.SourceTable {
358
382
  const resolvedMemberships = memberships ?? sourceTableMembershipsFromDocument(doc, syncConfig, mapping);
383
+ const ref: SourceTableRef = {
384
+ connectionTag,
385
+ schema: doc.schema_name,
386
+ name: doc.table_name
387
+ };
359
388
  const resolvedMembershipIds = membershipIds ?? {
360
389
  bucketDataSourceIds: resolvedMemberships.bucketDataSources.map((source) => mapping.bucketSourceId(source)),
361
390
  parameterLookupSourceIds: resolvedMemberships.parameterLookupSources.map((source) =>
@@ -365,11 +394,7 @@ export function sourceTableFromDocument(
365
394
  };
366
395
  const table = new storage.SourceTable({
367
396
  id: doc._id,
368
- ref: {
369
- connectionTag,
370
- schema: doc.schema_name,
371
- name: doc.table_name
372
- },
397
+ ref,
373
398
  objectId: doc.relation_id,
374
399
  replicaIdColumns:
375
400
  doc.replica_id_columns?.map(
@@ -381,7 +406,8 @@ export function sourceTableFromDocument(
381
406
  bucketDataSourceIds: new Set(resolvedMembershipIds.bucketDataSourceIds),
382
407
  parameterLookupSourceIds: new Set(resolvedMembershipIds.parameterLookupSourceIds),
383
408
  eventDefinitionIds: new Set(resolvedMembershipIds.eventDefinitionIds),
384
- sourceMetadata: doc.source_metadata ?? null
409
+ sourceMetadata: doc.source_metadata ?? null,
410
+ rustSourceTable: rustSourceTableFor(syncConfig, rust, resolvedMemberships, ref)
385
411
  });
386
412
  table.syncData = table.bucketDataSources.length > 0;
387
413
  table.syncParameters = table.parameterLookupSources.length > 0;
@@ -48,6 +48,20 @@ export type MongoStorageReadPreference = t.Encoded<typeof MongoStorageReadPrefer
48
48
  export const MongoReplicationBatchSize = service_types.enumLiteral('small', 'medium', 'large');
49
49
  export type MongoReplicationBatchSize = t.Encoded<typeof MongoReplicationBatchSize>;
50
50
 
51
+ /**
52
+ * Whether to process source rows with a Rust implementation of Sync Streams instead of in JavaScript.
53
+ *
54
+ * - `disable`: Always use the JavaScript evaluator.
55
+ * - `force`: Evaluate all rows with Rust, throwing if that is not possible (e.g. because the addon isn't loaded,
56
+ * legacy Sync Rules are deployed, or the source module doesn't emit undecoded BSON buffers).
57
+ *
58
+ * We may add a default hybrid mode opting in to Rust where supported in the future. For now, we either don't use Rust
59
+ * or fail loudly if it's unsupported.
60
+ */
61
+ export const RustEvaluationPreference = service_types.enumLiteral('disable', 'force');
62
+
63
+ export type RustEvaluationPreference = t.Encoded<typeof RustEvaluationPreference>;
64
+
51
65
  export const MongoStorageConfig = service_types.configFile.BaseStorageConfig.and(lib_mongo.BaseMongoConfig).and(
52
66
  t.object({
53
67
  /**
@@ -81,7 +95,9 @@ export const MongoStorageConfig = service_types.configFile.BaseStorageConfig.and
81
95
  /** Larger batches improve throughput at the cost of retained memory. Default: medium. */
82
96
  replication_batch_size: MongoReplicationBatchSize.optional(),
83
97
 
84
- object_storage: S3ObjectStorageConfig.optional()
98
+ object_storage: S3ObjectStorageConfig.optional(),
99
+
100
+ rust_evaluation: RustEvaluationPreference.optional()
85
101
  })
86
102
  );
87
103
 
@@ -29,7 +29,8 @@ export function mongoTestStorageFactoryGenerator(factoryOptions: MongoTestStorag
29
29
  objectStorage: factoryOptions.objectStorage,
30
30
  chunkCompactionConcurrency: factoryOptions.chunkCompactionConcurrency,
31
31
  replicationBatchSize: factoryOptions.replicationBatchSize,
32
- inlineThresholdBytes: factoryOptions.inlineThresholdBytes
32
+ inlineThresholdBytes: factoryOptions.inlineThresholdBytes,
33
+ rustEvaluation: factoryOptions.rustEvaluation
33
34
  });
34
35
  },
35
36
  tableIdStrings: false