-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathMongoBucketBatch.ts
More file actions
1562 lines (1397 loc) · 49.4 KB
/
Copy pathMongoBucketBatch.ts
File metadata and controls
1562 lines (1397 loc) · 49.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { mongo } from '@powersync/lib-service-mongodb';
import {
RowProcessor,
SourceTableInterface,
SqlEventDescriptor,
SqliteRow,
SqliteValue
} from '@powersync/service-sync-rules';
import * as bson from 'bson';
import {
BaseObserver,
container,
logger as defaultLogger,
ErrorCode,
errors,
Logger,
ReplicationAssertionError,
ServiceError
} from '@powersync/lib-services-framework';
import {
BucketStorageMarkRecordUnavailable,
deserializeBson,
InternalOpId,
isCompleteRow,
maxLsn,
SaveOperationTag,
SourceTable,
SourceTableId,
storage,
SyncRuleState,
utils
} from '@powersync/service-core';
import * as timers from 'node:timers/promises';
import { idPrefixFilter, mongoTableId } from '../../utils/util.js';
import { BucketDefinitionMapping } from './BucketDefinitionMapping.js';
import { PowerSyncMongo } from './db.js';
import { CurrentBucket, CurrentDataDocument, SourceKey, SourceTableDocument, SyncRuleDocument } from './models.js';
import { MongoIdSequence } from './MongoIdSequence.js';
import { MongoPersistedSyncRules } from './MongoPersistedSyncRules.js';
import { batchCreateCustomWriteCheckpoints } from './MongoWriteCheckpointAPI.js';
import { cacheKey, OperationBatch, RecordOperation } from './OperationBatch.js';
import { PersistedBatch } from './PersistedBatch.js';
/**
* 15MB
*/
export const MAX_ROW_SIZE = 15 * 1024 * 1024;
// Currently, we can only have a single flush() at a time, since it locks the op_id sequence.
// While the MongoDB transaction retry mechanism handles this okay, using an in-process Mutex
// makes it more fair and has less overhead.
//
// In the future, we can investigate allowing multiple replication streams operating independently.
const replicationMutex = new utils.Mutex();
export const EMPTY_DATA = new bson.Binary(bson.serialize({}));
export interface MongoWriterOptions {
db: PowerSyncMongo;
slotName: string;
storeCurrentData: boolean;
rowProcessor: RowProcessor;
mapping: BucketDefinitionMapping;
/**
* Set to true for initial replication.
*/
skipExistingRows: boolean;
markRecordUnavailable: BucketStorageMarkRecordUnavailable | undefined;
logger?: Logger;
}
interface MongoBucketBatchOptions {
db: PowerSyncMongo;
syncRules: MongoPersistedSyncRules;
lastCheckpointLsn: string | null;
keepaliveOp: InternalOpId | null;
resumeFromLsn: string | null;
logger: Logger;
writer: MongoBucketDataWriter;
}
export interface ForSyncRulesOptions {
syncRules: MongoPersistedSyncRules;
lastCheckpointLsn: string | null;
resumeFromLsn: string | null;
keepaliveOp: InternalOpId | null;
}
export class MongoBucketDataWriter implements storage.BucketDataWriter {
private batch: OperationBatch | null = null;
public readonly rowProcessor: RowProcessor;
write_checkpoint_batch: storage.CustomWriteCheckpointOptions[] = [];
private readonly client: mongo.MongoClient;
public readonly db: PowerSyncMongo;
public readonly session: mongo.ClientSession;
private readonly logger: Logger;
private readonly slot_name: string;
private readonly storeCurrentData: boolean;
private readonly skipExistingRows: boolean;
private readonly mapping: BucketDefinitionMapping;
private markRecordUnavailable: BucketStorageMarkRecordUnavailable | undefined;
public subWriters: MongoBucketBatch[] = [];
constructor(options: MongoWriterOptions) {
this.db = options.db;
this.client = this.db.client;
this.session = this.client.startSession();
this.slot_name = options.slotName;
this.mapping = options.mapping;
this.rowProcessor = options.rowProcessor;
this.storeCurrentData = options.storeCurrentData;
this.skipExistingRows = options.skipExistingRows;
this.logger = options.logger ?? defaultLogger;
this.markRecordUnavailable = options.markRecordUnavailable;
}
forSyncRules(options: ForSyncRulesOptions): MongoBucketBatch {
const batch = new MongoBucketBatch({
db: this.db,
syncRules: options.syncRules,
lastCheckpointLsn: options.lastCheckpointLsn,
keepaliveOp: options.keepaliveOp,
resumeFromLsn: options.resumeFromLsn,
logger: this.logger,
writer: this
});
this.subWriters.push(batch);
return batch;
}
async [Symbol.asyncDispose](): Promise<void> {
await this.session.endSession();
for (let batch of this.subWriters) {
await batch[Symbol.asyncDispose]();
}
}
get resumeFromLsn(): string | null {
// FIXME: check the logic here when there are multiple batches
let lsn: string | null = null;
for (let sub of this.subWriters) {
// TODO: should this be min instead?
lsn = maxLsn(lsn, sub.resumeFromLsn);
}
return lsn;
}
async keepaliveAll(lsn: string): Promise<boolean> {
let didAny = false;
for (let batch of this.subWriters) {
const didBatchKeepalive = await batch.keepalive(lsn);
didAny ||= didBatchKeepalive;
}
return didAny;
}
async commitAll(lsn: string, options?: storage.BucketBatchCommitOptions): Promise<boolean> {
let didCommit = false;
for (let batch of this.subWriters) {
const didWriterCommit = await batch.commit(lsn, options);
didCommit ||= didWriterCommit;
}
return didCommit;
}
async setAllResumeLsn(lsn: string): Promise<void> {
for (let batch of this.subWriters) {
await batch.setResumeLsn(lsn);
}
}
private findMatchingSubWriters(tables: SourceTableDocument[]) {
return this.subWriters.filter((subWriter) => {
return tables.some((table) => subWriter.hasTable(table));
});
}
async markTableSnapshotDone(tables: storage.SourceTable[], no_checkpoint_before_lsn?: string) {
const session = this.session;
const ids = tables.map((table) => mongoTableId(table.id));
await this.withTransaction(async () => {
await this.db.source_tables.updateMany(
{ _id: { $in: ids } },
{
$set: {
snapshot_done: true
},
$unset: {
snapshot_status: 1
}
},
{ session }
);
const updatedTables = await this.db.source_tables.find({ _id: { $in: ids } }, { session }).toArray();
if (no_checkpoint_before_lsn != null) {
const affectedSubWriters = this.findMatchingSubWriters(updatedTables);
await this.db.sync_rules.updateOne(
{
_id: { $in: affectedSubWriters.map((w) => w.group_id) }
},
{
$set: {
last_keepalive_ts: new Date()
},
$max: {
no_checkpoint_before: no_checkpoint_before_lsn
}
},
{ session: this.session }
);
}
});
return tables.map((table) => {
const copy = table.clone();
copy.snapshotComplete = true;
return copy;
});
}
async markTableSnapshotRequired(table: SourceTable): Promise<void> {
const doc = await this.db.source_tables.findOne({ _id: mongoTableId(table.id) });
if (doc == null) {
return;
}
const subWriters = this.findMatchingSubWriters([doc]);
await this.db.sync_rules.updateOne(
{
_id: { $in: subWriters.map((w) => w.group_id) }
},
{
$set: {
snapshot_done: false
}
},
{ session: this.session }
);
}
async markAllSnapshotDone(no_checkpoint_before_lsn: string): Promise<void> {
await this.db.sync_rules.updateOne(
{
_id: { $in: this.subWriters.map((w) => w.group_id) },
snapshot_done: { $ne: true }
},
{
$set: {
snapshot_done: true,
last_keepalive_ts: new Date()
},
$max: {
no_checkpoint_before: no_checkpoint_before_lsn
}
},
{ session: this.session }
);
}
async getTable(ref: SourceTable): Promise<storage.SourceTable | null> {
const doc = await this.db.source_tables.findOne({ _id: mongoTableId(ref.id) });
if (doc == null) {
return null;
}
const sourceTable = new storage.SourceTable({
id: doc._id,
objectId: doc.relation_id,
schema: doc.schema_name,
connectionTag: ref.connectionTag,
name: doc.table_name,
replicaIdColumns: ref.replicaIdColumns,
snapshotComplete: doc.snapshot_done ?? true,
bucketDataSourceIds: doc.bucket_data_source_ids ?? [],
parameterLookupSourceIds: doc.parameter_lookup_source_ids ?? [],
pattern: ref.pattern
});
sourceTable.snapshotStatus =
doc.snapshot_status == null
? undefined
: {
lastKey: doc.snapshot_status.last_key?.buffer ?? null,
totalEstimatedCount: doc.snapshot_status.total_estimated_count,
replicatedCount: doc.snapshot_status.replicated_count
};
sourceTable.syncData = doc.bucket_data_source_ids.length > 0;
sourceTable.syncParameters = doc.parameter_lookup_source_ids.length > 0;
// FIXME: implement sourceTable.syncEvent
return sourceTable;
}
async resolveTables(options: storage.ResolveTablesOptions): Promise<storage.ResolveTablesResult> {
const sources = this.rowProcessor.getMatchingSources(options.pattern);
const bucketDataSourceIds = sources.bucketDataSources.map((source) => this.mapping.bucketSourceId(source));
const parameterLookupSourceIds = sources.parameterIndexLookupCreators.map((source) =>
this.mapping.parameterLookupId(source)
);
const { connection_id, connection_tag, entity_descriptor } = options;
const { schema, name, objectId, replicaIdColumns } = entity_descriptor;
const normalizedReplicaIdColumns = replicaIdColumns.map((column) => ({
name: column.name,
type: column.type,
type_oid: column.typeId
}));
let result: storage.ResolveTablesResult | null = null;
await this.db.client.withSession(async (session) => {
const col = this.db.source_tables;
let filter: mongo.Filter<SourceTableDocument> = {
connection_id: connection_id,
schema_name: schema,
table_name: name,
replica_id_columns2: normalizedReplicaIdColumns
};
if (objectId != null) {
filter.relation_id = objectId;
}
let docs = await col.find(filter, { session }).toArray();
let matchingDocs: SourceTableDocument[] = [];
let coveredBucketDataSourceIds = new Set<number>();
let coveredParameterLookupSourceIds = new Set<number>();
for (let doc of docs) {
const matchingBucketDataSourceIds = doc.bucket_data_source_ids.filter((id) => bucketDataSourceIds.includes(id));
const matchingParameterLookupSourceIds = doc.parameter_lookup_source_ids.filter((id) =>
parameterLookupSourceIds.includes(id)
);
if (matchingBucketDataSourceIds.length == 0 && matchingParameterLookupSourceIds.length == 0) {
// Not relevant
continue;
}
matchingDocs.push(doc);
for (let id of matchingBucketDataSourceIds) {
coveredBucketDataSourceIds.add(id);
}
for (let id of matchingParameterLookupSourceIds) {
coveredParameterLookupSourceIds.add(id);
}
}
const pendingBucketDataSourceIds = bucketDataSourceIds.filter((id) => !coveredBucketDataSourceIds.has(id));
const pendingParameterLookupSourceIds = parameterLookupSourceIds.filter(
(id) => !coveredParameterLookupSourceIds.has(id)
);
if (pendingBucketDataSourceIds.length > 0 || pendingParameterLookupSourceIds.length > 0) {
const doc: SourceTableDocument = {
_id: new bson.ObjectId(),
connection_id: connection_id,
relation_id: objectId,
schema_name: schema,
table_name: name,
replica_id_columns: null,
replica_id_columns2: normalizedReplicaIdColumns,
snapshot_done: false,
snapshot_status: undefined,
bucket_data_source_ids: pendingBucketDataSourceIds,
parameter_lookup_source_ids: pendingParameterLookupSourceIds
};
await col.insertOne(doc, { session });
matchingDocs.push(doc);
}
const sourceTables = matchingDocs.map((doc) => {
const sourceTable = new storage.SourceTable({
id: doc._id,
connectionTag: connection_tag,
objectId: objectId,
schema: schema,
name: name,
replicaIdColumns: replicaIdColumns,
snapshotComplete: doc.snapshot_done ?? true,
bucketDataSourceIds: doc.bucket_data_source_ids ?? [],
parameterLookupSourceIds: doc.parameter_lookup_source_ids ?? [],
pattern: options.pattern
});
sourceTable.snapshotStatus =
doc.snapshot_status == null
? undefined
: {
lastKey: doc.snapshot_status.last_key?.buffer ?? null,
totalEstimatedCount: doc.snapshot_status.total_estimated_count,
replicatedCount: doc.snapshot_status.replicated_count
};
sourceTable.syncData = doc.bucket_data_source_ids.length > 0;
sourceTable.syncParameters = doc.parameter_lookup_source_ids.length > 0;
// FIXME: implement sourceTable.syncEvent
return sourceTable;
});
// FIXME: dropTables
// let dropTables: storage.SourceTable[] = [];
// // Detect tables that are either renamed, or have different replica_id_columns
// let truncateFilter = [{ schema_name: schema, table_name: name }] as any[];
// if (objectId != null) {
// // Only detect renames if the source uses relation ids.
// truncateFilter.push({ relation_id: objectId });
// }
// const truncate = await col
// .find(
// {
// group_id: group_id,
// connection_id: connection_id,
// _id: { $ne: doc._id },
// $or: truncateFilter
// },
// { session }
// )
// .toArray();
// dropTables = truncate.map(
// (doc) =>
// new storage.SourceTable({
// id: doc._id,
// connectionTag: connection_tag,
// objectId: doc.relation_id,
// schema: doc.schema_name,
// name: doc.table_name,
// replicaIdColumns:
// doc.replica_id_columns2?.map((c) => ({ name: c.name, typeOid: c.type_oid, type: c.type })) ?? [],
// snapshotComplete: doc.snapshot_done ?? true
// })
// );
result = {
tables: sourceTables,
dropTables: []
};
});
return result!;
}
async flush(options?: storage.BatchBucketFlushOptions): Promise<storage.FlushedResult | null> {
let result: storage.FlushedResult | null = null;
// One flush may be split over multiple transactions.
// Each flushInner() is one transaction.
while (this.batch != null || this.write_checkpoint_batch.length > 0) {
let r = await this.flushInner(options);
if (r) {
result = r;
}
}
return result;
}
private async flushInner(options?: storage.BatchBucketFlushOptions): Promise<storage.FlushedResult | null> {
const batch = this.batch;
let last_op: InternalOpId | null = null;
let resumeBatch: OperationBatch | null = null;
await this.withReplicationTransaction(`Flushing ${batch?.length ?? 0} ops`, async (session, opSeq) => {
if (batch != null) {
resumeBatch = await this.replicateBatch(session, batch, opSeq, options);
}
if (this.write_checkpoint_batch.length > 0) {
this.logger.info(`Writing ${this.write_checkpoint_batch.length} custom write checkpoints`);
await batchCreateCustomWriteCheckpoints(this.db, session, this.write_checkpoint_batch, opSeq.next());
this.write_checkpoint_batch = [];
}
last_op = opSeq.last();
});
// null if done, set if we need another flush
this.batch = resumeBatch;
if (last_op == null) {
throw new ReplicationAssertionError('Unexpected last_op == null');
}
for (let batch of this.subWriters) {
batch.persisted_op = last_op;
batch.last_flushed_op = last_op;
}
return { flushed_op: last_op };
}
private async replicateBatch(
session: mongo.ClientSession,
batch: OperationBatch,
op_seq: MongoIdSequence,
options?: storage.BucketBatchCommitOptions
): Promise<OperationBatch | null> {
let sizes: Map<string, number> | undefined = undefined;
if (this.storeCurrentData && !this.skipExistingRows) {
// We skip this step if we don't store current_data, since the sizes will
// always be small in that case.
// With skipExistingRows, we don't load the full documents into memory,
// so we can also skip the size lookup step.
// Find sizes of current_data documents, to assist in intelligent batching without
// exceeding memory limits.
//
// A previous attempt tried to do batching by the results of the current_data query
// (automatically limited to 48MB(?) per batch by MongoDB). The issue is that it changes
// the order of processing, which then becomes really tricky to manage.
// This now takes 2+ queries, but doesn't have any issues with order of operations.
const sizeLookups: SourceKey[] = batch.batch.map((r) => {
return { g: 0, t: mongoTableId(r.record.sourceTable.id), k: r.beforeId };
});
sizes = new Map<string, number>();
const sizeCursor: mongo.AggregationCursor<{ _id: SourceKey; size: number }> = this.db.current_data.aggregate(
[
{
$match: {
_id: { $in: sizeLookups }
}
},
{
$project: {
_id: 1,
size: { $bsonSize: '$$ROOT' }
}
}
],
{ session }
);
for await (let doc of sizeCursor.stream()) {
const key = cacheKey(doc._id.t, doc._id.k);
sizes.set(key, doc.size);
}
}
// If set, we need to start a new transaction with this batch.
let resumeBatch: OperationBatch | null = null;
let transactionSize = 0;
let didFlush = false;
// Now batch according to the sizes
// This is a single batch if storeCurrentData == false
for await (let b of batch.batched(sizes)) {
if (resumeBatch) {
for (let op of b) {
resumeBatch.push(op);
}
continue;
}
const lookups: SourceKey[] = b.map((r) => {
return { g: 0, t: mongoTableId(r.record.sourceTable.id), k: r.beforeId };
});
let current_data_lookup = new Map<string, CurrentDataDocument>();
// With skipExistingRows, we only need to know whether or not the row exists.
const projection = this.skipExistingRows ? { _id: 1 } : undefined;
const cursor = this.db.current_data.find(
{
_id: { $in: lookups }
},
{ session, projection }
);
for await (let doc of cursor.stream()) {
current_data_lookup.set(cacheKey(doc._id.t, doc._id.k), doc);
}
let persistedBatch: PersistedBatch | null = new PersistedBatch(transactionSize, {
logger: this.logger,
mapping: this.mapping
});
for (let op of b) {
if (resumeBatch) {
resumeBatch.push(op);
continue;
}
const currentData = current_data_lookup.get(op.internalBeforeKey) ?? null;
if (currentData != null) {
// If it will be used again later, it will be set again using nextData below
current_data_lookup.delete(op.internalBeforeKey);
}
const nextData = this.saveOperation(persistedBatch!, op, currentData, op_seq);
if (nextData != null) {
// Update our current_data and size cache
current_data_lookup.set(op.internalAfterKey!, nextData);
sizes?.set(op.internalAfterKey!, nextData.data.length());
}
if (persistedBatch!.shouldFlushTransaction()) {
// Transaction is getting big.
// Flush, and resume in a new transaction.
const { flushedAny } = await persistedBatch!.flush(this.db, this.session, options);
didFlush ||= flushedAny;
persistedBatch = null;
// Computing our current progress is a little tricky here, since
// we're stopping in the middle of a batch.
// We create a new batch, and push any remaining operations to it.
resumeBatch = new OperationBatch();
}
}
if (persistedBatch) {
transactionSize = persistedBatch.currentSize;
const { flushedAny } = await persistedBatch.flush(this.db, this.session, options);
didFlush ||= flushedAny;
}
}
if (didFlush) {
for (let batch of this.subWriters) {
await batch.clearError();
}
}
return resumeBatch?.hasData() ? resumeBatch : null;
}
private saveOperation(
batch: PersistedBatch,
operation: RecordOperation,
current_data: CurrentDataDocument | null,
opSeq: MongoIdSequence
) {
const record = operation.record;
const beforeId = operation.beforeId;
const afterId = operation.afterId;
let after = record.after;
const sourceTable = record.sourceTable;
let existing_buckets: CurrentBucket[] = [];
let new_buckets: CurrentBucket[] = [];
let existing_lookups: bson.Binary[] = [];
let new_lookups: bson.Binary[] = [];
const before_key: SourceKey = { g: 0, t: mongoTableId(record.sourceTable.id), k: beforeId };
if (this.skipExistingRows) {
if (record.tag == SaveOperationTag.INSERT) {
if (current_data != null) {
// Initial replication, and we already have the record.
// This may be a different version of the record, but streaming replication
// will take care of that.
// Skip the insert here.
return null;
}
} else {
throw new ReplicationAssertionError(`${record.tag} not supported with skipExistingRows: true`);
}
}
if (record.tag == SaveOperationTag.UPDATE) {
const result = current_data;
if (result == null) {
// Not an error if we re-apply a transaction
existing_buckets = [];
existing_lookups = [];
if (!isCompleteRow(this.storeCurrentData, after!)) {
if (this.markRecordUnavailable != null) {
// This will trigger a "resnapshot" of the record.
// This is not relevant if storeCurrentData is false, since we'll get the full row
// directly in the replication stream.
this.markRecordUnavailable(record);
} else {
// Log to help with debugging if there was a consistency issue
this.logger.warn(
`Cannot find previous record for update on ${record.sourceTable.qualifiedName}: ${beforeId} / ${record.before?.id}`
);
}
}
} else {
existing_buckets = result.buckets;
existing_lookups = result.lookups;
if (this.storeCurrentData) {
const data = deserializeBson((result.data as mongo.Binary).buffer) as SqliteRow;
after = storage.mergeToast<SqliteValue>(after!, data);
}
}
} else if (record.tag == SaveOperationTag.DELETE) {
const result = current_data;
if (result == null) {
// Not an error if we re-apply a transaction
existing_buckets = [];
existing_lookups = [];
// Log to help with debugging if there was a consistency issue
if (this.storeCurrentData && this.markRecordUnavailable == null) {
this.logger.warn(
`Cannot find previous record for delete on ${record.sourceTable.qualifiedName}: ${beforeId} / ${record.before?.id}`
);
}
} else {
existing_buckets = result.buckets;
existing_lookups = result.lookups;
}
}
let afterData: bson.Binary | undefined;
if (afterId != null && !this.storeCurrentData) {
afterData = EMPTY_DATA;
} else if (afterId != null) {
try {
// This will fail immediately if the record is > 16MB.
afterData = new bson.Binary(bson.serialize(after!));
// We additionally make sure it's <= 15MB - we need some margin for metadata.
if (afterData.length() > MAX_ROW_SIZE) {
throw new ServiceError(ErrorCode.PSYNC_S1002, `Row too large: ${afterData.length()}`);
}
} catch (e) {
// Replace with empty values, equivalent to TOAST values
after = Object.fromEntries(
Object.entries(after!).map(([key, value]) => {
return [key, undefined];
})
);
afterData = new bson.Binary(bson.serialize(after!));
container.reporter.captureMessage(
`Data too big on ${record.sourceTable.qualifiedName}.${record.after?.id}: ${e.message}`,
{
level: errors.ErrorSeverity.WARNING,
metadata: {
replication_slot: this.slot_name,
table: record.sourceTable.qualifiedName
}
}
);
}
}
// 2. Save bucket data
if (beforeId != null && (afterId == null || !storage.replicaIdEquals(beforeId, afterId))) {
// Source ID updated
if (sourceTable.syncData) {
// Delete old record
batch.saveBucketData({
op_seq: opSeq,
sourceKey: beforeId,
table: sourceTable,
before_buckets: existing_buckets,
evaluated: []
});
// Clear this, so we don't also try to REMOVE for the new id
existing_buckets = [];
}
if (sourceTable.syncParameters) {
// Delete old parameters
batch.saveParameterData({
op_seq: opSeq,
sourceKey: beforeId,
sourceTable,
evaluated: [],
existing_lookups
});
existing_lookups = [];
}
}
// If we re-apply a transaction, we can end up with a partial row.
//
// We may end up with toasted values, which means the record is not quite valid.
// However, it will be valid by the end of the transaction.
//
// In this case, we don't save the op, but we do save the current data.
if (afterId && after && utils.isCompleteRow(this.storeCurrentData, after)) {
// Insert or update
if (sourceTable.syncData) {
const { results: evaluated, errors: syncErrors } = this.rowProcessor.evaluateRowWithErrors({
record: after,
sourceTable
});
for (let error of syncErrors) {
container.reporter.captureMessage(
`Failed to evaluate data query on ${record.sourceTable.qualifiedName}.${record.after?.id}: ${error.error}`,
{
level: errors.ErrorSeverity.WARNING,
metadata: {
replication_slot: this.slot_name,
table: record.sourceTable.qualifiedName
}
}
);
this.logger.error(
`Failed to evaluate data query on ${record.sourceTable.qualifiedName}.${record.after?.id}: ${error.error}`
);
}
// Save new one
batch.saveBucketData({
op_seq: opSeq,
sourceKey: afterId,
evaluated,
table: sourceTable,
before_buckets: existing_buckets
});
new_buckets = evaluated.map((e) => {
const sourceDefinitionId = this.mapping.bucketSourceId(e.source);
return {
def: sourceDefinitionId,
bucket: e.bucket,
table: e.table,
id: e.id
};
});
}
if (sourceTable.syncParameters) {
// Parameters
const { results: paramEvaluated, errors: paramErrors } = this.rowProcessor.evaluateParameterRowWithErrors(
sourceTable,
after
);
for (let error of paramErrors) {
container.reporter.captureMessage(
`Failed to evaluate parameter query on ${record.sourceTable.qualifiedName}.${record.after?.id}: ${error.error}`,
{
level: errors.ErrorSeverity.WARNING,
metadata: {
replication_slot: this.slot_name,
table: record.sourceTable.qualifiedName
}
}
);
this.logger.error(
`Failed to evaluate parameter query on ${record.sourceTable.qualifiedName}.${after.id}: ${error.error}`
);
}
batch.saveParameterData({
op_seq: opSeq,
sourceKey: afterId,
sourceTable,
evaluated: paramEvaluated,
existing_lookups
});
new_lookups = paramEvaluated.map((p) => {
return storage.serializeLookup(p.lookup);
});
}
}
let result: CurrentDataDocument | null = null;
// 5. TOAST: Update current data and bucket list.
if (afterId) {
// Insert or update
const after_key: SourceKey = { g: 0, t: mongoTableId(sourceTable.id), k: afterId };
batch.upsertCurrentData(after_key, {
data: afterData,
buckets: new_buckets,
lookups: new_lookups
});
result = {
_id: after_key,
data: afterData!,
buckets: new_buckets,
lookups: new_lookups
};
}
if (afterId == null || !storage.replicaIdEquals(beforeId, afterId)) {
// Either a delete (afterId == null), or replaced the old replication id
// Note that this is a soft delete.
// We don't specifically need a new or unique op_id here, but it must be greater than the
// last checkpoint, so we use next().
batch.softDeleteCurrentData(before_key, opSeq.next());
}
return result;
}
async withTransaction(cb: () => Promise<void>) {
await replicationMutex.exclusiveLock(async () => {
await this.session.withTransaction(
async () => {
try {
await cb();
} catch (e: unknown) {
if (e instanceof mongo.MongoError && e.hasErrorLabel('TransientTransactionError')) {
// Likely write conflict caused by concurrent write stream replicating
} else {
this.logger.warn('Transaction error', e as Error);
}
await timers.setTimeout(Math.random() * 50);
throw e;
}
},
{ maxCommitTimeMS: 10000 }
);
});
}
async withReplicationTransaction(
description: string,
callback: (session: mongo.ClientSession, opSeq: MongoIdSequence) => Promise<void>
): Promise<void> {
let flushTry = 0;
const start = Date.now();
const lastTry = start + 90000;
const session = this.session;
await this.withTransaction(async () => {
flushTry += 1;
if (flushTry % 10 == 0) {
this.logger.info(`${description} - try ${flushTry}`);
}
if (flushTry > 20 && Date.now() > lastTry) {
throw new ServiceError(ErrorCode.PSYNC_S1402, 'Max transaction tries exceeded');
}
const next_op_id_doc = await this.db.op_id_sequence.findOneAndUpdate(
{
_id: 'main'
},
{
$setOnInsert: { op_id: 0n },
$set: {
// Force update to ensure we get a mongo lock
ts: Date.now()
}
},
{
upsert: true,
returnDocument: 'after',
session
}
);
const opSeq = new MongoIdSequence(next_op_id_doc?.op_id ?? 0n);
await callback(session, opSeq);
await this.db.op_id_sequence.updateOne(
{
_id: 'main'
},
{
$set: {
op_id: opSeq.last()
}
},
{
session
}
);
// FIXME: Do we need this?
// await this.db.sync_rules.updateOne(
// {
// _id: this.group_id
// },
// {
// $set: {
// last_keepalive_ts: new Date()
// }
// },
// { session }
// );
// We don't notify checkpoint here - we don't make any checkpoint updates directly
});
}
async save(record: storage.SaveOptions): Promise<storage.FlushedResult | null> {
const { after, before, sourceTable, tag } = record;
for (const event of this.getTableEvents(sourceTable)) {
for (let batch of this.subWriters) {
batch.iterateListeners((cb) =>
cb.replicationEvent?.({
batch: batch,
table: sourceTable,
data: {
op: tag,
after: after && utils.isCompleteRow(this.storeCurrentData, after) ? after : undefined,
before: before && utils.isCompleteRow(this.storeCurrentData, before) ? before : undefined
},
event
})
);
}
}
/**
* Return if the table is just an event table
*/
if (!sourceTable.syncData && !sourceTable.syncParameters) {
return null;
}
this.logger.debug(`Saving ${record.tag}:${record.before?.id}/${record.after?.id}`);