@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
@@ -1,8 +1,12 @@
1
1
  import { mongo } from '@powersync/lib-service-mongodb';
2
2
  import {
3
+ EvaluatedParameters,
4
+ EvaluatedRow,
3
5
  EventDefinitionId,
4
6
  HydratedEventDescriptor,
5
7
  HydratedSyncConfig,
8
+ RustParameter,
9
+ RustRow,
6
10
  SqliteRow,
7
11
  SqliteValue
8
12
  } from '@powersync/service-sync-rules';
@@ -42,11 +46,19 @@ import { MongoParsedSyncConfigSet } from './MongoParsedSyncConfigSet.js';
42
46
  import { REPLICATION_WRITE_OPTIONS } from './MongoReplicationOptions.js';
43
47
  import { MongoSyncRulesLock } from './MongoSyncRulesLock.js';
44
48
  import { MongoWriteBatch } from './MongoWriteBatch.js';
45
- import { OperationBatch, RecordOperation } from './OperationBatch.js';
49
+ import { OperationBatch, RecordOperation, RustEvaluationResult } from './OperationBatch.js';
46
50
  import { ReplicationBatchLimits } from './ReplicationBatchLimits.js';
51
+ import type { RustEvaluatorOptions } from './v3/MongoRustEvaluator.js';
47
52
  import { ObjectStorage } from './v3/object-storage/ObjectStorage.js';
48
53
  import { createObjectStorageUsageWriterId } from './v3/object-storage/ObjectStorageUsage.js';
49
54
 
55
+ /** Row and parameter outputs obtained by evaluating a source document against the sync config. */
56
+ interface EvaluatedSourceRow {
57
+ // these fields are undefined when a source table doesn't sync rows or parameters
58
+ rows?: readonly (EvaluatedRow | RustRow)[];
59
+ parameters?: readonly (EvaluatedParameters | RustParameter)[];
60
+ }
61
+
50
62
  export interface MongoBucketBatchOptions {
51
63
  batchLimits: ReplicationBatchLimits;
52
64
  replicationLock: MongoSyncRulesLock;
@@ -87,6 +99,9 @@ export interface MongoBucketBatchOptions {
87
99
 
88
100
  objectStorage?: ObjectStorage;
89
101
  inlineThresholdBytes?: number;
102
+
103
+ /** When set, evaluate rows with the Rust addon. */
104
+ rust?: RustEvaluatorOptions | null;
90
105
  }
91
106
 
92
107
  export abstract class MongoBucketBatch
@@ -276,13 +291,19 @@ export abstract class MongoBucketBatch
276
291
  onRecordUnavailable: BucketStorageMarkRecordUnavailable | undefined
277
292
  ) {
278
293
  const record = operation.record;
294
+ // Undecoded rows (raw BSON) are evaluated in Rust instead of JS, before this method is called.
295
+ const decoded = operation.undecodedAfter == null ? (record as storage.SaveOptions) : null;
279
296
  const beforeId = operation.beforeId;
280
297
  const afterId = operation.afterId;
281
- let after = record.after;
298
+ let after = decoded?.after;
282
299
  const sourceTable = record.sourceTable;
283
300
  // Effective per-record flag: store current_data only if both the batch (source-level,
284
301
  // e.g. Postgres) and the table (e.g. non-FULL replica identity) require it.
285
302
  const storeCurrentData = this.storeCurrentData && sourceTable.storeCurrentData;
303
+ if (decoded == null && storeCurrentData) {
304
+ // We'd need to decode rows to store them. Sources passing undecoded rows always send complete rows.
305
+ throw new ReplicationAssertionError('Undecoded rows are not supported for sources requiring current data');
306
+ }
286
307
 
287
308
  let existing_buckets: LoadedSourceRecord['buckets'] = [];
288
309
  let new_buckets: LoadedSourceRecord['buckets'] = [];
@@ -319,7 +340,7 @@ export abstract class MongoBucketBatch
319
340
  after = storage.mergeToast<SqliteValue>(after!, data);
320
341
  }
321
342
  }
322
- if (!isCompleteRow(storeCurrentData, after!)) {
343
+ if (decoded != null && !isCompleteRow(storeCurrentData, after!)) {
323
344
  if (onRecordUnavailable != null) {
324
345
  // This will trigger a "resnapshot" of the record.
325
346
  // This is not relevant if storeCurrentData is false, since we'll get the full row
@@ -329,11 +350,11 @@ export abstract class MongoBucketBatch
329
350
  // fails. Its source position has not advanced, so WAL replay must
330
351
  // request repair again rather than treating mere record existence as
331
352
  // proof that the missing TOAST values have been recovered.
332
- onRecordUnavailable(record);
353
+ onRecordUnavailable(decoded as storage.SaveUpdate);
333
354
  } else if (result == null) {
334
355
  // Log to help with debugging if there was a consistency issue
335
356
  this.logger.warn(
336
- `Cannot find previous record for update on ${record.sourceTable.qualifiedName}: ${beforeId} / ${record.before?.id}`
357
+ `Cannot find previous record for update on ${record.sourceTable.qualifiedName}: ${beforeId} / ${decoded.before?.id}`
337
358
  );
338
359
  }
339
360
  }
@@ -378,7 +399,7 @@ export abstract class MongoBucketBatch
378
399
  afterData = new bson.Binary(bson.serialize(after!));
379
400
 
380
401
  container.reporter.captureMessage(
381
- `Data too big on ${record.sourceTable.qualifiedName}.${record.after?.id}: ${e.message}`,
402
+ `Data too big on ${record.sourceTable.qualifiedName}.${decoded?.after?.id}: ${e.message}`,
382
403
  {
383
404
  level: errors.ErrorSeverity.WARNING,
384
405
  metadata: {
@@ -425,75 +446,40 @@ export abstract class MongoBucketBatch
425
446
  // However, it will be valid by the end of the transaction.
426
447
  //
427
448
  // In this case, we don't save the op, but we do save the current data.
428
- if (afterId && after && utils.isCompleteRow(storeCurrentData, after)) {
429
- // Insert or update
430
- if (sourceTable.syncData) {
431
- const { results, errors: syncErrors } = this.sync_rules.evaluateRowWithErrors({
432
- record: after,
433
- sourceTable: sourceTable.ref,
434
- bucketDataSources: sourceTable.bucketDataSources
435
- });
436
- const evaluated = results;
437
-
438
- for (let error of syncErrors) {
439
- container.reporter.captureMessage(
440
- `Failed to evaluate data query on ${record.sourceTable.qualifiedName}.${record.after?.id}: ${error.error}`,
441
- {
442
- level: errors.ErrorSeverity.WARNING,
443
- metadata: {
444
- replication_slot: this.replicationStreamName,
445
- table: record.sourceTable.qualifiedName
446
- }
447
- }
448
- );
449
- this.logger.error(
450
- `Failed to evaluate data query on ${record.sourceTable.qualifiedName}.${record.after?.id}: ${error.error}`
451
- );
452
- }
449
+ let evaluated: EvaluatedSourceRow | null = null;
450
+ if (afterId) {
451
+ if (operation.rustResult != null) {
452
+ evaluated = this.useRustResult(sourceTable, operation, operation.rustResult);
453
+ } else if (decoded == null) {
454
+ throw new ReplicationAssertionError('Undecoded row has not been evaluated in Rust');
455
+ } else if (after && utils.isCompleteRow(storeCurrentData, after)) {
456
+ evaluated = this.evaluateSourceRow(sourceTable, decoded, after);
457
+ }
458
+ }
459
+
460
+ if (evaluated != null) {
461
+ const { rows, parameters } = evaluated;
453
462
 
454
- // Save new one
463
+ if (rows != null) {
455
464
  batch.saveBucketData({
456
465
  op_seq: opSeq,
457
466
  sourceKey: afterId,
458
- evaluated,
467
+ evaluated: rows,
459
468
  table: sourceTable,
460
469
  before_buckets: existing_buckets
461
470
  });
462
- new_buckets = this.sourceRecordStore.mapEvaluatedBuckets(evaluated);
471
+ new_buckets = this.sourceRecordStore.mapEvaluatedBuckets(rows);
463
472
  }
464
473
 
465
- if (sourceTable.syncParameters) {
466
- // Parameters
467
- const { results: paramEvaluated, errors: paramErrors } = this.sync_rules.evaluateParameterRowWithErrors(
468
- sourceTable.ref,
469
- after,
470
- { parameterLookupSources: sourceTable.parameterLookupSources }
471
- );
472
-
473
- for (let error of paramErrors) {
474
- container.reporter.captureMessage(
475
- `Failed to evaluate parameter query on ${record.sourceTable.qualifiedName}.${record.after?.id}: ${error.error}`,
476
- {
477
- level: errors.ErrorSeverity.WARNING,
478
- metadata: {
479
- replication_slot: this.replicationStreamName,
480
- table: record.sourceTable.qualifiedName
481
- }
482
- }
483
- );
484
- this.logger.error(
485
- `Failed to evaluate parameter query on ${record.sourceTable.qualifiedName}.${after.id}: ${error.error}`
486
- );
487
- }
488
-
474
+ if (parameters != null) {
489
475
  batch.saveParameterData({
490
476
  op_seq: opSeq,
491
477
  sourceKey: afterId,
492
478
  sourceTable,
493
- evaluated: paramEvaluated,
479
+ evaluated: parameters,
494
480
  existing_lookups
495
481
  });
496
- new_lookups = this.sourceRecordStore.mapParameterLookups(paramEvaluated);
482
+ new_lookups = this.sourceRecordStore.mapParameterLookups(parameters);
497
483
  }
498
484
  }
499
485
 
@@ -529,6 +515,92 @@ export abstract class MongoBucketBatch
529
515
  return result;
530
516
  }
531
517
 
518
+ /** Evaluates a source row on the current sync config in JavaScript, logging errors. */
519
+ private evaluateSourceRow(
520
+ sourceTable: storage.SourceTable,
521
+ record: storage.SaveOptions,
522
+ after: SqliteRow
523
+ ): EvaluatedSourceRow {
524
+ let rows: EvaluatedRow[] | undefined = undefined;
525
+ let parameters: EvaluatedParameters[] | undefined = undefined;
526
+
527
+ if (sourceTable.syncData) {
528
+ const { results, errors: syncErrors } = this.sync_rules.evaluateRowWithErrors({
529
+ record: after,
530
+ sourceTable: sourceTable.ref,
531
+ bucketDataSources: sourceTable.bucketDataSources
532
+ });
533
+ rows = results;
534
+
535
+ for (let error of syncErrors) {
536
+ this.reportEvaluationError(sourceTable, 'evaluate data query', record.after?.id, error.error);
537
+ }
538
+ }
539
+
540
+ if (sourceTable.syncParameters) {
541
+ // Parameters
542
+ const { results: paramEvaluated, errors: paramErrors } = this.sync_rules.evaluateParameterRowWithErrors(
543
+ sourceTable.ref,
544
+ after,
545
+ { parameterLookupSources: sourceTable.parameterLookupSources }
546
+ );
547
+ parameters = paramEvaluated;
548
+
549
+ for (let error of paramErrors) {
550
+ this.reportEvaluationError(sourceTable, 'evaluate parameter query', after.id, error.error);
551
+ }
552
+ }
553
+
554
+ return { rows, parameters };
555
+ }
556
+
557
+ /**
558
+ * Uses outputs of evaluating an undecoded source row in Rust, logging evaluation errors.
559
+ */
560
+ private useRustResult(
561
+ sourceTable: storage.SourceTable,
562
+ operation: RecordOperation,
563
+ result: RustEvaluationResult
564
+ ): EvaluatedSourceRow {
565
+ for (const error of result.errors) {
566
+ if (error.element == null) {
567
+ // Errors without an element can only happen for global issues like malformed BSON. The JavaScript
568
+ // implementation would have thrown earlier for those, we should make this fatal too (we don't want to treat
569
+ // this as zero evaluated rows, which would then add REMOVE operations).
570
+ throw new ServiceError(
571
+ ErrorCode.PSYNC_S1006,
572
+ `Failed to decode source row on ${sourceTable.qualifiedName}.${operation.afterId} with Rust: ${error.message}`
573
+ );
574
+ }
575
+
576
+ let action: string;
577
+ if (Array.isArray(error.element)) {
578
+ action = 'evaluate data query';
579
+ } else {
580
+ action = 'evaluate parameter query';
581
+ }
582
+
583
+ this.reportEvaluationError(sourceTable, action, operation.afterId, error.message);
584
+ }
585
+
586
+ return {
587
+ rows: sourceTable.syncData ? result.rows : undefined,
588
+ parameters: sourceTable.syncParameters ? result.parameters : undefined
589
+ };
590
+ }
591
+
592
+ private reportEvaluationError(sourceTable: storage.SourceTable, action: string, rowId: unknown, error: string) {
593
+ const message = `Failed to ${action} on ${sourceTable.qualifiedName}.${rowId}: ${error}`;
594
+ container.reporter.captureMessage(message, {
595
+ level: errors.ErrorSeverity.WARNING,
596
+ metadata: {
597
+ replication_slot: this.replicationStreamName,
598
+ table: sourceTable.qualifiedName
599
+ }
600
+ });
601
+ this.logger.error(message);
602
+ }
603
+
532
604
  protected async fence(session = this.session, projection?: mongo.Document) {
533
605
  // Graceful cancellation belongs to the source connector's page/batch boundary.
534
606
  // It must still be able to persist progress for rows already flushed. Lease
@@ -662,7 +734,39 @@ export abstract class MongoBucketBatch
662
734
  abstract save(record: storage.SaveOptions): Promise<storage.FlushedResult | null>;
663
735
 
664
736
  /** Buffer one complete input event synchronously, including its custom checkpoints. */
665
- protected bufferRecord(record: storage.SaveOptions): boolean {
737
+ protected bufferRecord(record: storage.SaveOptions | storage.SaveUndecodedOptions): boolean {
738
+ const { sourceTable, tag } = record;
739
+ // Is this an undecoded source row?
740
+ if (record.after instanceof Uint8Array) {
741
+ if (sourceTable.syncEvent) {
742
+ throw new ServiceError(
743
+ ErrorCode.PSYNC_S1006,
744
+ `Table ${sourceTable.qualifiedName} is used in events, which are not supported with Rust evaluation yet.`
745
+ );
746
+ }
747
+ if ((sourceTable.syncData || sourceTable.syncParameters) && sourceTable.rustSourceTable == null) {
748
+ throw new ServiceError(
749
+ ErrorCode.PSYNC_S1006,
750
+ `A legacy bucket definition on ${sourceTable.qualifiedName} is not supported by Rust evaluation.`
751
+ );
752
+ }
753
+ } else {
754
+ this.emitReplicationEvents(record as storage.SaveOptions);
755
+ }
756
+
757
+ // Event-only tables can still buffer custom checkpoints. Only data/parameter
758
+ // rows need source-record lookup and evaluation, but both kinds of input can flush.
759
+ if (sourceTable.syncData || sourceTable.syncParameters) {
760
+ this.logger.debug(`Saving ${tag}:${record.beforeReplicaId}/${record.afterReplicaId}`);
761
+
762
+ this.batch ??= new OperationBatch(this.options.batchLimits);
763
+ this.batch.push(new RecordOperation(record));
764
+ }
765
+
766
+ return this.batch?.shouldFlush() ?? false;
767
+ }
768
+
769
+ private emitReplicationEvents(record: storage.SaveOptions) {
666
770
  const { after, before, sourceTable, tag } = record;
667
771
  const storeCurrentData = this.storeCurrentData && sourceTable.storeCurrentData;
668
772
  // V3 source tables own disjoint event-definition ids for each physical table. Multiple
@@ -686,17 +790,6 @@ export abstract class MongoBucketBatch
686
790
  );
687
791
  }
688
792
  }
689
-
690
- // Event-only tables can still buffer custom checkpoints. Only data/parameter
691
- // rows need source-record lookup and evaluation, but both kinds of input can flush.
692
- if (sourceTable.syncData || sourceTable.syncParameters) {
693
- this.logger.debug(`Saving ${record.tag}:${record.before?.id}/${record.after?.id}`);
694
-
695
- this.batch ??= new OperationBatch(this.options.batchLimits);
696
- this.batch.push(new RecordOperation(record));
697
- }
698
-
699
- return this.batch?.shouldFlush() ?? false;
700
793
  }
701
794
 
702
795
  protected abstract automaticFlush(): Promise<storage.FlushedResult | null>;
@@ -92,7 +92,8 @@ export class MongoStorageProvider implements storage.StorageProvider {
92
92
  supportsMultipleSyncConfigs: resolvedConfig.connections?.[0]?.type == lib_mongo.MONGO_CONNECTION_TYPE,
93
93
 
94
94
  objectStorage,
95
- inlineThresholdBytes: decodedConfig.object_storage?.inline_threshold_bytes
95
+ inlineThresholdBytes: decodedConfig.object_storage?.inline_threshold_bytes,
96
+ rustEvaluation: decodedConfig.rust_evaluation
96
97
  });
97
98
 
98
99
  // Storage factory for reports
@@ -28,7 +28,7 @@ import { HydratedSyncConfig, ParameterLookupRows, ScopedParameterLookup } from '
28
28
  import * as bson from 'bson';
29
29
  import { LRUCache } from 'lru-cache';
30
30
  import * as timers from 'timers/promises';
31
- import { DEFAULT_CLEAR_BATCH_THROTTLE_RATE } from '../../types/types.js';
31
+ import { DEFAULT_CLEAR_BATCH_THROTTLE_RATE, RustEvaluationPreference } from '../../types/types.js';
32
32
  import { MongoBucketStorage } from '../MongoBucketStorage.js';
33
33
  import {
34
34
  MongoGetCheckpointChangesOptions,
@@ -55,6 +55,7 @@ export interface MongoSyncBucketStorageOptions {
55
55
  storageConfig: StorageConfig;
56
56
  objectStorage?: ObjectStorage;
57
57
  inlineThresholdBytes?: number;
58
+ rustEvaluation?: RustEvaluationPreference;
58
59
  }
59
60
 
60
61
  /**
@@ -115,6 +116,8 @@ export abstract class MongoSyncBucketStorage
115
116
  */
116
117
  private readonly replicationLock: MongoSyncRulesLock | null;
117
118
 
119
+ protected readonly rustEvaluation: RustEvaluationPreference;
120
+
118
121
  constructor(
119
122
  public readonly factory: MongoBucketStorage,
120
123
  public readonly replicationStreamId: number,
@@ -125,6 +128,7 @@ export abstract class MongoSyncBucketStorage
125
128
  ) {
126
129
  super();
127
130
  this.replicationLock = replicationStream.current_lock;
131
+ this.rustEvaluation = options.rustEvaluation ?? 'disable';
128
132
  this.storageConfig = options.storageConfig;
129
133
  this.objectStorage = options.objectStorage;
130
134
  // Keep small chunks inline in MongoDB rather than offloading them to S3.
@@ -1,4 +1,4 @@
1
- import { ToastableSqliteRow } from '@powersync/service-sync-rules';
1
+ import { RustError, RustParameter, RustRow, ToastableSqliteRow } from '@powersync/service-sync-rules';
2
2
  import * as bson from 'bson';
3
3
 
4
4
  import { storage } from '@powersync/service-core';
@@ -22,6 +22,13 @@ export class OperationBatch {
22
22
  readonly customWriteCheckpoints: storage.CustomWriteCheckpointOptions[] = [];
23
23
  currentSize: number = 0;
24
24
 
25
+ /**
26
+ * Pending evaluation of undecoded rows in this batch, started when the batch is captured for a flush.
27
+ *
28
+ * Once resolved, all undecoded operations in this batch have {@link RecordOperation.rustResult} set.
29
+ */
30
+ rustEvaluation: Promise<void> | null = null;
31
+
25
32
  constructor(private readonly limits: ReplicationBatchLimits = DEFAULT_REPLICATION_BATCH_LIMITS) {}
26
33
 
27
34
  /** Row count only: custom checkpoints bypass source-record lookup and repair. */
@@ -83,6 +90,13 @@ export class OperationBatch {
83
90
  }
84
91
  }
85
92
 
93
+ /** Outputs of evaluating an undecoded source row in Rust. */
94
+ export interface RustEvaluationResult {
95
+ readonly rows: readonly RustRow[];
96
+ readonly parameters: readonly RustParameter[];
97
+ readonly errors: readonly RustError[];
98
+ }
99
+
86
100
  export class RecordOperation {
87
101
  public readonly afterId: storage.ReplicaId | null;
88
102
  public readonly beforeId: storage.ReplicaId;
@@ -90,7 +104,15 @@ export class RecordOperation {
90
104
  public readonly internalAfterKey: string | null;
91
105
  public readonly estimatedSize: number;
92
106
 
93
- constructor(public readonly record: storage.SaveOptions) {
107
+ /**
108
+ * For undecoded rows, the result of evaluating the row in Rust.
109
+ *
110
+ * This is set by `MongoRustEvaluator.evaluate` before the operation is prepared. Operations moved into a resume
111
+ * batch keep their results, so they're only evaluated once.
112
+ */
113
+ public rustResult: RustEvaluationResult | null = null;
114
+
115
+ constructor(public readonly record: storage.SaveOptions | storage.SaveUndecodedOptions) {
94
116
  const afterId = record.afterReplicaId ?? null;
95
117
  const beforeId = record.beforeReplicaId ?? record.afterReplicaId;
96
118
  this.afterId = afterId;
@@ -98,7 +120,15 @@ export class RecordOperation {
98
120
  this.internalBeforeKey = cacheKey(mongoTableId(record.sourceTable.id), beforeId);
99
121
  this.internalAfterKey = afterId ? cacheKey(mongoTableId(record.sourceTable.id), afterId) : null;
100
122
 
101
- this.estimatedSize = estimateRowSize(record.before) + estimateRowSize(record.after);
123
+ const after = record.after;
124
+ this.estimatedSize =
125
+ estimateRowSize(record.before) + (after instanceof Uint8Array ? 12 + after.byteLength : estimateRowSize(after));
126
+ }
127
+
128
+ /** The raw BSON document for undecoded inserts and updates, or null for decoded rows and deletes. */
129
+ get undecodedAfter(): Uint8Array | null {
130
+ const after = this.record.after;
131
+ return after instanceof Uint8Array ? after : null;
102
132
  }
103
133
  }
104
134
 
@@ -65,7 +65,22 @@ export class BatchOperationBuffer {
65
65
  const dchecksum = BigInt(utils.hashDelete(subkey));
66
66
 
67
67
  for (const evaluated of options.evaluated) {
68
- const definitionId = this.definitions.getBucketDefinitionId(evaluated.source);
68
+ let recordData: string;
69
+ let checksum: number;
70
+ let source: BucketDataSource;
71
+
72
+ if ('scope' in evaluated) {
73
+ // Evaluated in Rust, we don't need to compute the checksum here.
74
+ recordData = evaluated.row;
75
+ checksum = evaluated.checksum;
76
+ source = evaluated.scope.source;
77
+ } else {
78
+ recordData = JSONBig.stringify(evaluated.data);
79
+ checksum = utils.hashData(evaluated.table, evaluated.id, recordData);
80
+ source = evaluated.source;
81
+ }
82
+
83
+ const definitionId = this.definitions.getBucketDefinitionId(source);
69
84
  const key = currentBucketKey({
70
85
  definitionId: definitionId,
71
86
  bucket: evaluated.bucket,
@@ -73,8 +88,6 @@ export class BatchOperationBuffer {
73
88
  id: evaluated.id
74
89
  });
75
90
 
76
- const recordData = JSONBig.stringify(evaluated.data);
77
- const checksum = utils.hashData(evaluated.table, evaluated.id, recordData);
78
91
  if (recordData.length > MAX_ROW_SIZE) {
79
92
  const message = `Row ${key} too large: ${recordData.length} bytes. Removing.`;
80
93
  this.logger.error(message);
@@ -1,6 +1,12 @@
1
1
  import { Logger } from '@powersync/lib-services-framework';
2
2
  import { InternalOpId, storage } from '@powersync/service-core';
3
- import { BucketDefinitionId, EvaluatedParameters, EvaluatedRow } from '@powersync/service-sync-rules';
3
+ import {
4
+ BucketDefinitionId,
5
+ EvaluatedParameters,
6
+ EvaluatedRow,
7
+ RustParameter,
8
+ RustRow
9
+ } from '@powersync/service-sync-rules';
4
10
  import * as bson from 'bson';
5
11
  import { MongoIdSequence } from '../MongoIdSequence.js';
6
12
  import { ReplicationBatchLimits } from '../ReplicationBatchLimits.js';
@@ -10,7 +16,7 @@ export interface SaveBucketDataOptions {
10
16
  op_seq: MongoIdSequence;
11
17
  sourceKey: storage.ReplicaId;
12
18
  table: storage.SourceTable;
13
- evaluated: EvaluatedRow[];
19
+ evaluated: readonly (EvaluatedRow | RustRow)[];
14
20
  before_buckets: SourceRecordBucketState[];
15
21
  }
16
22
 
@@ -18,7 +24,7 @@ export interface SaveParameterDataOptions {
18
24
  op_seq: MongoIdSequence;
19
25
  sourceKey: storage.ReplicaId;
20
26
  sourceTable: storage.SourceTable;
21
- evaluated: EvaluatedParameters[];
27
+ evaluated: readonly (EvaluatedParameters | RustParameter)[];
22
28
  existing_lookups: SourceRecordLookupState[];
23
29
  }
24
30
 
@@ -1,6 +1,13 @@
1
1
  import { mongo } from '@powersync/lib-service-mongodb';
2
2
  import { storage } from '@powersync/service-core';
3
- import { BucketDefinitionId, EvaluatedParameters, EvaluatedRow, ParameterIndexId } from '@powersync/service-sync-rules';
3
+ import {
4
+ BucketDefinitionId,
5
+ EvaluatedParameters,
6
+ EvaluatedRow,
7
+ ParameterIndexId,
8
+ RustParameter,
9
+ RustRow
10
+ } from '@powersync/service-sync-rules';
4
11
  import * as bson from 'bson';
5
12
 
6
13
  export interface SourceRecordLookupEntry {
@@ -30,8 +37,8 @@ export interface LoadedSourceRecord {
30
37
  }
31
38
 
32
39
  export interface SourceRecordStore {
33
- mapEvaluatedBuckets(evaluated: EvaluatedRow[]): SourceRecordBucketState[];
34
- mapParameterLookups(paramEvaluated: EvaluatedParameters[]): SourceRecordLookupState[];
40
+ mapEvaluatedBuckets(evaluated: readonly (EvaluatedRow | RustRow)[]): SourceRecordBucketState[];
41
+ mapParameterLookups(paramEvaluated: readonly (EvaluatedParameters | RustParameter)[]): SourceRecordLookupState[];
35
42
  loadSizes(session: mongo.ClientSession, entries: SourceRecordLookupEntry[]): Promise<Map<string, number>>;
36
43
  loadDocuments(
37
44
  session: mongo.ClientSession,
@@ -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 { ErrorCode, ServiceAssertionError, ServiceError } from '@powersync/lib-services-framework';
4
4
  import {
5
5
  CheckpointChanges,
6
6
  CompactInitialReplicationOptions,
@@ -94,6 +94,10 @@ export class MongoSyncBucketStorageV1 extends MongoSyncBucketStorage {
94
94
  }
95
95
 
96
96
  protected async createWriterImpl(options: storage.CreateWriterOptions): Promise<storage.BucketStorageBatch> {
97
+ if (this.rustEvaluation == 'force') {
98
+ throw new ServiceError(ErrorCode.PSYNC_S1006, 'Rust evaluation is not supported with storage versions 1 and 2.');
99
+ }
100
+
97
101
  const doc = (await this.db.sync_rules.findOne(
98
102
  {
99
103
  _id: this.replicationStreamId
@@ -102,6 +102,10 @@ export class PersistedBatchV1 implements PersistedBatch {
102
102
  }
103
103
 
104
104
  for (let result of evaluated) {
105
+ if (!('bucketParameters' in result)) {
106
+ throw new ReplicationAssertionError('Unexpected Rust evaluated parameter in v1');
107
+ }
108
+
105
109
  const binLookup = storage.serializeLookup(result.lookup);
106
110
  remaining_lookups.delete(binLookup.toString('base64'));
107
111
 
@@ -1,6 +1,7 @@
1
1
  import { mongo } from '@powersync/lib-service-mongodb';
2
+ import { ReplicationAssertionError } from '@powersync/lib-services-framework';
2
3
  import { storage } from '@powersync/service-core';
3
- import { EvaluatedParameters, EvaluatedRow } from '@powersync/service-sync-rules';
4
+ import { EvaluatedParameters, EvaluatedRow, RustParameter, RustRow } from '@powersync/service-sync-rules';
4
5
  import * as bson from 'bson';
5
6
  import { idPrefixFilter } from '../../../utils/util.js';
6
7
  import { cacheKey } from '../OperationBatch.js';
@@ -20,7 +21,7 @@ export class SourceRecordStoreV1 implements SourceRecordStore {
20
21
  private readonly groupId: number
21
22
  ) {}
22
23
 
23
- mapEvaluatedBuckets(evaluated: EvaluatedRow[]): LoadedSourceRecord['buckets'] {
24
+ mapEvaluatedBuckets(evaluated: (EvaluatedRow | RustRow)[]): LoadedSourceRecord['buckets'] {
24
25
  return evaluated.map((entry) => ({
25
26
  definitionId: null,
26
27
  bucket: entry.bucket,
@@ -29,11 +30,17 @@ export class SourceRecordStoreV1 implements SourceRecordStore {
29
30
  }));
30
31
  }
31
32
 
32
- mapParameterLookups(paramEvaluated: EvaluatedParameters[]): SourceRecordLookupState[] {
33
- return paramEvaluated.map((entry) => ({
34
- indexId: null,
35
- lookup: storage.serializeLookup(entry.lookup)
36
- }));
33
+ mapParameterLookups(paramEvaluated: (EvaluatedParameters | RustParameter)[]): SourceRecordLookupState[] {
34
+ return paramEvaluated.map((entry) => {
35
+ if ('inputs' in entry) {
36
+ throw new ReplicationAssertionError('Unexpected Rust evaluated parameter in v1');
37
+ }
38
+
39
+ return {
40
+ indexId: null,
41
+ lookup: storage.serializeLookup(entry.lookup)
42
+ };
43
+ });
37
44
  }
38
45
 
39
46
  private createId(sourceTableId: bson.ObjectId, replicaId: storage.ReplicaId): SourceKey {