-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransaction-log.test.ts
More file actions
1446 lines (1250 loc) · 52.2 KB
/
transaction-log.test.ts
File metadata and controls
1446 lines (1250 loc) · 52.2 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 { RocksDatabase, Transaction } from '../src/index.js';
import { constants, type TransactionLog } from '../src/load-binding.js';
import { parseTransactionLog } from '../src/parse-transaction-log.js';
import { withResolvers } from '../src/util.js';
import { createWorkerBootstrapScript, dbRunner, generateDBPath } from './lib/util.js';
import assert from 'node:assert';
import { existsSync, readFileSync, statSync } from 'node:fs';
import { mkdir, readdir, stat, utimes, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { Worker } from 'node:worker_threads';
import { describe, expect, it } from 'vitest';
const {
TRANSACTION_LOG_FILE_HEADER_SIZE,
TRANSACTION_LOG_ENTRY_HEADER_SIZE,
TRANSACTION_LOG_TOKEN,
} = constants;
describe('Transaction Log', () => {
describe('useLog()', () => {
it('should detect existing transaction logs', () =>
dbRunner({ skipOpen: true }, async ({ db, dbPath }) => {
await mkdir(join(dbPath, 'transaction_logs', 'foo'), { recursive: true });
await writeFile(join(dbPath, 'transaction_logs', 'foo', '1.txnlog'), '');
db.open();
expect(db.listLogs()).toEqual(['foo']);
const fooLog = db.useLog('foo');
expect(fooLog).toBeDefined();
expect(fooLog.path).toBe(join(dbPath, 'transaction_logs', 'foo'));
const barLog = db.useLog('bar');
expect(barLog).toBeDefined();
expect(barLog).not.toBe(fooLog);
const fooLog2 = db.useLog('foo');
expect(fooLog2).toBe(fooLog);
expect(db.listLogs()).toEqual(['bar', 'foo']);
}));
it('should support numeric log names', () =>
dbRunner(async ({ db }) => {
db.open();
expect(db.listLogs()).toEqual([]);
const fooLog = db.useLog(612);
expect(fooLog).toBeDefined();
const fooLog2 = db.useLog(612);
expect(fooLog2).toBe(fooLog);
expect(db.listLogs()).toEqual(['612']);
}));
it('should emit "new-transaction-log" event when a new log is created', () =>
dbRunner(async ({ db }) => {
const events: { name: string }[] = [];
let eventResolver: (() => void) | undefined;
let eventPromise = new Promise<void>((resolve) => {
eventResolver = resolve;
});
const listener = (name: string) => {
events.push({ name });
eventResolver?.();
};
db.addListener('new-transaction-log', listener);
// First call should create the log and emit the event with log name
const log1 = db.useLog('foo');
expect(log1).toBeDefined();
await eventPromise;
expect(events.length).toBe(1);
expect(events[0].name).toBe('foo');
// Second call should reuse existing log and not emit
const log2 = db.useLog('foo');
expect(log2).toBe(log1);
await delay(10); // Give time for any potential event
expect(events.length).toBe(1);
// Creating a different log should emit again with the new log name
eventPromise = new Promise<void>((resolve) => {
eventResolver = resolve;
});
const log3 = db.useLog('bar');
expect(log3).toBeDefined();
expect(log3).not.toBe(log1);
await eventPromise;
expect(events.length).toBe(2);
expect(events[1].name).toBe('bar');
db.removeListener('new-transaction-log', listener);
}));
it.skipIf(!globalThis.gc)('should cleanup transaction log instance on GC', () =>
dbRunner(async ({ db }) => {
let weakRef: WeakRef<TransactionLog> | undefined;
await new Promise<void>((resolve) => {
const log = db.useLog('foo');
weakRef = new WeakRef(log);
resolve();
});
assert(weakRef);
assert(globalThis.gc);
// this is flaky
const until = Date.now() + 3000;
while (Date.now() < until) {
globalThis.gc();
await delay(250);
globalThis.gc();
await delay(250);
if (!weakRef.deref()) {
break;
}
}
expect(weakRef.deref()).toBeUndefined();
})
);
it('should error if log already bound to a transaction', () =>
dbRunner(async ({ db }) => {
const log1 = db.useLog('log1');
const log2 = db.useLog('log2');
await db.transaction(async (txn) => {
log1.addEntry(Buffer.from('hello'), txn.id);
log1.addEntry(Buffer.from('world'), txn.id);
expect(() => log2.addEntry(Buffer.from('nope'), txn.id)).toThrowError(
new Error('Log already bound to a transaction')
);
});
await db.transaction(async (txn) => {
txn.useLog('log3');
txn.useLog('log3'); // do it twice
expect(() => txn.useLog('log4')).toThrowError(
new Error('Log already bound to a transaction')
);
});
}));
it('should isolate transaction logs between different database paths', () =>
dbRunner(
{ dbOptions: [{ path: generateDBPath() }, { path: generateDBPath() }] },
async ({ db, dbPath }, { db: db2, dbPath: dbPath2 }) => {
expect(dbPath).not.toBe(dbPath2);
const value = Buffer.alloc(10000, 'a');
const log1 = db.useLog('foo');
for (let i = 0; i < 20; i++) {
await db.transaction(async (txn) => {
log1.addEntry(value, txn.id);
});
}
expect(db.listLogs()).toContain('foo');
expect(db2.listLogs()).not.toContain('foo');
const getSize = async (logPath: string) => {
let size = 0;
for (const file of await readdir(logPath)) {
const info = await stat(join(logPath, file)).catch(() => undefined);
if (info) {
size += info.size;
}
}
return size;
};
let size = await getSize(join(dbPath, 'transaction_logs', 'foo'));
expect(size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + (TRANSACTION_LOG_ENTRY_HEADER_SIZE + 10000) * 20
);
const log2 = db2.useLog('foo');
for (let i = 0; i < 20; i++) {
await db2.transaction(async (txn) => {
log2.addEntry(value, txn.id);
});
}
size = await getSize(join(dbPath, 'transaction_logs', 'foo'));
expect(size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + (TRANSACTION_LOG_ENTRY_HEADER_SIZE + 10000) * 20
);
size = await getSize(join(dbPath2, 'transaction_logs', 'foo'));
expect(size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + (TRANSACTION_LOG_ENTRY_HEADER_SIZE + 10000) * 20
);
}
));
});
describe('_getLastCommittedPosition()/_getMemoryMapOfFile', () => {
it('should get a list of sequence files and get a memory map', () =>
dbRunner(async ({ db }) => {
const log = db.useLog('foo-seq');
const value = Buffer.alloc(10, 'a');
await db.transaction(async (txn) => {
log.addEntry(value, txn.id);
});
const positionBuffer = log._getLastCommittedPosition();
const dataView = new DataView(positionBuffer.buffer);
expect(dataView.getUint32(0)).toBeGreaterThan(10);
const sequenceNumber = dataView.getUint32(1);
expect(sequenceNumber).toBe(1);
const buffer = log._getMemoryMapOfFile(1);
expect(buffer).toBeDefined();
expect(buffer?.subarray(0, 4).toString()).toBe('WOOF');
}));
});
describe('Transaction log visibility after commits', () => {
it('Should not treat transaction logs as visible until successfully committed', () =>
dbRunner(async ({ db }) => {
const log = db.useLog('foo');
db.putSync('key1', 'value1');
let firstTransactionCompletions: Promise<void>[] = [];
let fullTransactionCompletions: Promise<void>[] = [];
for (let i = 0; i < 3; i++) {
let transaction = new Transaction(db.store);
let firstTxnCommit = (async () => {
db.getSync('key1', { transaction });
const value = Buffer.alloc(10, i.toString());
log.addEntry(value, transaction.id);
await delay(10);
// should be a conflicted write
db.putSync('key1', 'updated' + i, { transaction });
await transaction.commit();
})();
firstTransactionCompletions.push(firstTxnCommit);
const catchFailedCommit = async (error) => {
if (error.code === 'ERR_BUSY') {
db.getSync('key1', { transaction });
await delay(10);
db.putSync('key1', 'updated' + i, { transaction });
await transaction.commit().catch(catchFailedCommit);
} else {
throw error;
}
};
let fullTxnCompletion = firstTxnCommit.catch(catchFailedCommit);
fullTransactionCompletions.push(fullTxnCompletion);
}
let transactionResults = await Promise.allSettled(firstTransactionCompletions);
expect(
transactionResults.filter((result) => result.status === 'rejected').length
).toBeGreaterThanOrEqual(1); // at least one should fail
expect(Array.from(log.query({ start: 0 })).length).toBeLessThan(3); // The entries should not be all visible at this point (only one)
await Promise.all(fullTransactionCompletions); // wait for all the retries to finish
expect(Array.from(log.query({ start: 0 })).length).toBe(3); // now all the transactions should be visible in the log
}));
});
describe('query() from TransactionLog', () => {
it('should query an empty transaction log', () =>
dbRunner(async ({ db }) => {
const log = db.useLog('foo');
const queryIterable = log.query({ start: 1 });
const queryResults = Array.from(queryIterable);
expect(queryResults.length).toBe(0);
}));
it('should query a transaction log', () =>
dbRunner(async ({ db }) => {
const log = db.useLog('foo');
const value = Buffer.alloc(10, 'a');
const startTime = Date.now() - 1000;
await db.transaction(async (txn) => {
log.addEntry(value, txn.id);
});
const queryIterable = log.query({ start: startTime, end: Date.now() + 1000 });
const queryResults = Array.from(queryIterable);
expect(queryResults.length).toBe(1);
}));
it('should query a transaction log with different options', () =>
dbRunner(async ({ db }) => {
const log = db.useLog('foo');
const value = Buffer.alloc(10, 'a');
for (let i = 0; i < 5; i++) {
await db.transaction(async (txn) => {
log.addEntry(value, txn.id);
});
}
let allTimestamps = Array.from(log.query({ start: 0 })).map(({ timestamp }) => timestamp);
expect(Array.from(log.query({ start: allTimestamps[1] })).length).toBe(4);
expect(
Array.from(log.query({ start: allTimestamps[1], exclusiveStart: true })).length
).toBe(3);
expect(Array.from(log.query({ start: allTimestamps[1], exactStart: true })).length).toBe(4);
expect(
Array.from(
log.query({ start: allTimestamps[1], exactStart: true, end: allTimestamps[4] })
).length
).toBe(3);
}));
it('should query an out-of-order transaction log with different options', () =>
dbRunner(async ({ db }) => {
const log = db.useLog('foo');
const value = Buffer.alloc(10, 'a');
const start = Date.now();
for (let i = 0; i < 5; i++) {
await db.transaction(async (txn) => {
txn.setTimestamp(start - i);
log.addEntry(value, txn.id);
});
}
expect(Array.from(log.query({ start: start - 1 })).length).toBe(2);
expect(Array.from(log.query({ start: start - 1, exclusiveStart: true })).length).toBe(1);
expect(Array.from(log.query({ start: start - 1, exactStart: true })).length).toBe(4);
expect(
Array.from(log.query({ start: start - 1, exactStart: true, exclusiveStart: true })).length
).toBe(3);
expect(
Array.from(log.query({ start: start - 1, exactStart: true, end: start - 2 })).length
).toBe(3);
}));
it('should query a transaction log with multiple log instances', () =>
dbRunner(async ({ db }) => {
const log = db.useLog('foo');
const value = Buffer.alloc(10, 'a');
const startTime = Date.now() - 1000;
await db.transaction(async (txn) => {
log.addEntry(value, txn.id);
});
const log2 = db.useLog('foo');
let queryResults = Array.from(log.query({ start: startTime, end: Date.now() + 1000 }));
expect(queryResults.length).toBe(1);
queryResults = Array.from(log2.query({ start: startTime, end: Date.now() + 1000 }));
expect(queryResults.length).toBe(1);
queryResults = Array.from(log2.query({ start: startTime, end: Date.now() + 1000 }));
expect(queryResults.length).toBe(1);
expect(queryResults[0].data).toEqual(value);
expect(queryResults[0].endTxn).toBe(true);
}));
it('should query a transaction log after re-opening database', () =>
dbRunner(async ({ db, dbPath }) => {
try {
let log = db.useLog('foo');
const value = Buffer.alloc(10, 'a');
const startTime = Date.now() - 1000;
await db.transaction(async (txn) => {
log.addEntry(value, txn.id);
});
let queryResults = Array.from(log.query({ start: startTime, end: Date.now() + 1000 }));
expect(queryResults.length).toBe(1);
db.close();
db = RocksDatabase.open(dbPath);
let log2 = db.useLog('foo');
log._getMemoryMapOfFile(1);
let queryResults2 = Array.from(
log2.query({ start: startTime, end: Date.now() + 1000, readUncommitted: true })
);
expect(queryResults2.length).toBe(1);
queryResults = Array.from(log.query({ start: startTime, end: Date.now() + 1000 }));
expect(queryResults.length).toBe(1);
} finally {
db.close();
}
}));
it('should be able to reuse a query iterator to resume reading a transaction log', () =>
dbRunner({ dbOptions: [{ transactionLogMaxSize: 1000 }] }, async ({ db }) => {
const log = db.useLog('foo');
const value = Buffer.alloc(100, 'a');
for (let i = 0; i < 10; i++) {
const queryIterator = log.query({});
const queryIterator2 = log.query({ start: 0 });
await db.transaction(async (txn) => {
log.addEntry(value, txn.id);
});
expect(Array.from(queryIterator).length).toBe(1); // this should be starting after the last commit
expect(Array.from(queryIterator2).length).toBe(i * 11 + 1); // this should be starting after the last commit
let count = 0;
let count2 = 0;
for (let j = 0; j < 10; j++) {
const txnPromise = db.transaction(async (txn) => {
log.addEntry(value, txn.id);
});
count += Array.from(queryIterator).length;
count2 += Array.from(queryIterator2).length;
await txnPromise;
}
count += Array.from(queryIterator).length;
count2 += Array.from(queryIterator2).length;
expect(count).toBe(10);
expect(count2).toBe(10);
}
}));
it('should be able to reuse a query iterator to resume reading a transaction log with multiple entries', () =>
dbRunner({ dbOptions: [{ transactionLogMaxSize: 1000 }] }, async ({ db }) => {
let log = db.useLog('foo');
const value = Buffer.alloc(100, 'a');
await db.transaction(async (txn) => {
log.addEntry(value, txn.id);
});
let queryIterator = log.query({});
let queryIterator2 = log.query({ start: 0 });
expect(Array.from(queryIterator).length).toBe(0); // this should be starting after the last commit
expect(Array.from(queryIterator2).length).toBe(1); // this should be starting after the last commit
let count = 0;
let count2 = 0;
for (let i = 0; i < 200; i++) {
let txnPromise = db.transaction(async (txn) => {
log.addEntry(value, txn.id);
log.addEntry(value, txn.id);
});
count += Array.from(queryIterator).length;
count2 += Array.from(queryIterator2).length;
await txnPromise;
}
count += Array.from(queryIterator).length;
count2 += Array.from(queryIterator2).length;
expect(count).toBe(400);
expect(count2).toBe(400);
}));
it('should be able to reuse a query iterator that starts after the latest log', () =>
dbRunner({ dbOptions: [{ transactionLogMaxSize: 1000 }] }, async ({ db }) => {
const log = db.useLog('foo');
const value = Buffer.alloc(100, 'a');
await db.transaction(async (txn) => {
log.addEntry(value, txn.id);
});
let queryIterator = log.query({ start: 0 });
const start = Array.from(queryIterator)[0].timestamp + 1;
queryIterator = log.query({ start });
expect(Array.from(queryIterator).length).toBe(0); // shouldn't return anything because we are staring after last log
await delay(2);
await db.transaction(async (txn) => {
log.addEntry(value, txn.id);
});
expect(Array.from(queryIterator).length).toBe(1); // latest should show up now
}));
});
describe('addEntry()', () => {
it('should add a single small entry within a single block', () =>
dbRunner(async ({ db, dbPath }) => {
const log = db.useLog('foo');
const value = Buffer.alloc(10, 'a');
await db.transaction(async (txn) => {
log.addEntry(value, txn.id);
});
const logPath = join(dbPath, 'transaction_logs', 'foo', '1.txnlog');
const info = parseTransactionLog(logPath);
expect(info.size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + TRANSACTION_LOG_ENTRY_HEADER_SIZE + 10
);
expect(info.version).toBe(1);
expect(info.entries.length).toBe(1);
expect(info.entries[0].timestamp).toBeGreaterThanOrEqual(Date.now() - 1000);
expect(info.entries[0].length).toBe(10);
expect(info.entries[0].data).toEqual(value);
const queryResults = Array.from(log.query({ start: 0 }));
expect(queryResults.length).toBe(1);
expect(queryResults[0].data).toEqual(value);
expect(queryResults[0].timestamp).toBeGreaterThanOrEqual(Date.now() - 1000);
expect(queryResults[0].endTxn).toBe(true);
}));
it('should add multiple small entries within a single file', () =>
dbRunner(async ({ db, dbPath }) => {
const log = db.useLog('foo');
const valueA = Buffer.alloc(10, 'a');
const valueB = Buffer.alloc(10, 'b');
const valueC = Buffer.alloc(10, 'c');
const startTime = Date.now() - 1000;
await db.transaction(async (txn) => {
log.addEntry(valueA, txn.id);
log.addEntry(valueB, txn.id);
log.addEntry(valueC, txn.id);
});
const logPath = join(dbPath, 'transaction_logs', 'foo', '1.txnlog');
const info = parseTransactionLog(logPath);
expect(info.size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + (TRANSACTION_LOG_ENTRY_HEADER_SIZE + 10) * 3
);
expect(info.version).toBe(1);
expect(info.entries.length).toBe(3);
expect(info.entries[0].timestamp).toBeGreaterThanOrEqual(Date.now() - 1000);
expect(info.entries[0].length).toBe(10);
expect(info.entries[0].data).toEqual(valueA);
expect(info.entries[1].timestamp).toBeGreaterThanOrEqual(Date.now() - 1000);
expect(info.entries[1].length).toBe(10);
expect(info.entries[1].data).toEqual(valueB);
expect(info.entries[2].timestamp).toBeGreaterThanOrEqual(Date.now() - 1000);
expect(info.entries[2].length).toBe(10);
expect(info.entries[2].data).toEqual(valueC);
const queryResults = Array.from(log.query({ start: startTime, end: Date.now() + 1000 }));
expect(queryResults.length).toBe(3);
expect(queryResults[0].data).toEqual(valueA);
expect(queryResults[0].endTxn).toBe(false);
expect(queryResults[1].data).toEqual(valueB);
expect(queryResults[1].endTxn).toBe(false);
expect(queryResults[2].data).toEqual(valueC);
expect(queryResults[2].endTxn).toBe(true);
}));
it('should rotate to next sequence number', () =>
dbRunner({ dbOptions: [{ transactionLogMaxSize: 1000 }] }, async ({ db, dbPath }) => {
const log = db.useLog('foo');
const value = Buffer.alloc(100, 'a');
const startTime = Date.now() - 1000;
for (let i = 0; i < 20; i++) {
await db.transaction(async (txn) => {
log.addEntry(value, txn.id);
});
}
const logStorePath = join(dbPath, 'transaction_logs', 'foo');
const logFiles = await readdir(logStorePath);
expect(logFiles.sort()).toEqual(['1.txnlog', '2.txnlog', '3.txnlog']);
const queryResults = Array.from(log.query({ start: startTime, end: Date.now() + 1000 }));
expect(queryResults.length).toBe(20);
expect(queryResults[0].data).toEqual(value);
expect(queryResults[1].data).toEqual(value);
expect(queryResults[19].data).toEqual(value);
const file1Size =
TRANSACTION_LOG_FILE_HEADER_SIZE + (TRANSACTION_LOG_ENTRY_HEADER_SIZE + 100) * 8;
const file2Size =
TRANSACTION_LOG_FILE_HEADER_SIZE + (TRANSACTION_LOG_ENTRY_HEADER_SIZE + 100) * 8;
const file3Size =
TRANSACTION_LOG_FILE_HEADER_SIZE + (TRANSACTION_LOG_ENTRY_HEADER_SIZE + 100) * 4;
expect(log.getLogFileSize()).toBe(file1Size + file2Size + file3Size);
expect(() => log.getLogFileSize(0)).toThrow(
'Expected sequence number to be a positive integer greater than 0'
);
expect(log.getLogFileSize(1)).toBe(file1Size);
expect(log.getLogFileSize(2)).toBe(file2Size);
expect(log.getLogFileSize(3)).toBe(file3Size);
expect(log.getLogFileSize(4)).toBe(0);
const log1Path = join(dbPath, 'transaction_logs', 'foo', '1.txnlog');
const log2Path = join(dbPath, 'transaction_logs', 'foo', '2.txnlog');
const log3Path = join(dbPath, 'transaction_logs', 'foo', '3.txnlog');
const info1 = parseTransactionLog(log1Path);
const info2 = parseTransactionLog(log2Path);
const info3 = parseTransactionLog(log3Path);
expect(info1.size).toBe(file1Size);
expect(info1.entries.length).toBe(8);
for (const { length, data } of info1.entries) {
expect(length).toBe(100);
expect(data).toEqual(value);
}
expect(info2.size).toBe(file2Size);
expect(info2.entries.length).toBe(8);
for (const { length, data } of info2.entries) {
expect(length).toBe(100);
expect(data).toEqual(value);
}
expect(info3.size).toBe(file3Size);
expect(info3.entries.length).toBe(4);
for (const { length, data } of info3.entries) {
expect(length).toBe(100);
expect(data).toEqual(value);
}
}));
it('should allow unlimited transaction log size', () =>
dbRunner({ dbOptions: [{ transactionLogMaxSize: 0 }] }, async ({ db, dbPath }) => {
const log = db.useLog('foo');
const value = Buffer.alloc(10000, 'a');
for (let i = 0; i < 2000; i++) {
await db.transaction(async (txn) => {
log.addEntry(value, txn.id);
});
}
const totalSize =
TRANSACTION_LOG_FILE_HEADER_SIZE + (TRANSACTION_LOG_ENTRY_HEADER_SIZE + 10000) * 2000;
const logStorePath = join(dbPath, 'transaction_logs', 'foo');
const logFiles = await readdir(logStorePath);
expect(logFiles).toEqual(['1.txnlog']);
expect(statSync(join(dbPath, 'transaction_logs', 'foo', '1.txnlog')).size).toBe(totalSize);
}));
it('should not commit the log if the transaction is aborted', () =>
dbRunner(async ({ db, dbPath }) => {
const log = db.useLog('foo');
const value = Buffer.alloc(100, 'a');
await db.transaction(async (txn) => {
log.addEntry(value, txn.id);
expect(txn.abort()).toBeUndefined();
// second call should detect already aborted and return `undefined`
expect(txn.abort()).toBeUndefined();
});
const logPath = join(dbPath, 'transaction_logs', 'foo', '1.txnlog');
expect(existsSync(logPath)).toBe(false);
const queryResults = Array.from(log.query({ start: 0 }));
expect(queryResults.length).toBe(0);
}));
it('should add multiple entries from separate transactions', () =>
dbRunner(async ({ db, dbPath }) => {
const log = db.useLog('foo');
const valueA = Buffer.alloc(10, 'a');
const valueB = Buffer.alloc(10, 'b');
await db.transaction(async (txn) => {
log.addEntry(valueA, txn.id);
});
await db.transaction(async (txn) => {
log.addEntry(valueB, txn.id);
});
const logPath = join(dbPath, 'transaction_logs', 'foo', '1.txnlog');
const info = parseTransactionLog(logPath);
expect(info.size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + (TRANSACTION_LOG_ENTRY_HEADER_SIZE + 10) * 2
);
expect(info.version).toBe(1);
expect(info.entries.length).toBe(2);
expect(info.entries[0].timestamp).toBeGreaterThanOrEqual(Date.now() - 1000);
expect(info.entries[0].length).toBe(10);
expect(info.entries[0].data).toEqual(valueA);
expect(info.entries[1].timestamp).toBeGreaterThanOrEqual(Date.now() - 1000);
expect(info.entries[1].length).toBe(10);
expect(info.entries[1].data).toEqual(valueB);
const queryResults = Array.from(log.query({ start: 0 }));
expect(queryResults.length).toBe(2);
}));
it('should rotate if not enough room for the next transaction header', () =>
dbRunner({ dbOptions: [{ transactionLogMaxSize: 1000 }] }, async ({ db, dbPath }) => {
const log = db.useLog('foo');
for (let i = 0; i < 2; i++) {
await db.transaction(async (txn) => {
log.addEntry(Buffer.alloc(990, 'a'), txn.id);
});
}
const logStorePath = join(dbPath, 'transaction_logs', 'foo');
const logFiles = await readdir(logStorePath);
expect(logFiles.sort()).toEqual(['1.txnlog', '2.txnlog']);
const log1Path = join(dbPath, 'transaction_logs', 'foo', '1.txnlog');
const log2Path = join(dbPath, 'transaction_logs', 'foo', '2.txnlog');
const info1 = parseTransactionLog(log1Path);
const info2 = parseTransactionLog(log2Path);
expect(info1.size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + TRANSACTION_LOG_ENTRY_HEADER_SIZE + 990
);
expect(info1.entries.length).toBe(1);
expect(info1.entries[0].length).toBe(990);
expect(info1.entries[0].data).toEqual(Buffer.alloc(990, 'a'));
expect(info2.size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + TRANSACTION_LOG_ENTRY_HEADER_SIZE + 990
);
expect(info2.entries.length).toBe(1);
expect(info2.entries[0].length).toBe(990);
expect(info2.entries[0].data).toEqual(Buffer.alloc(990, 'a'));
}));
it('should rotate if room for the transaction header, but not the entry', () =>
dbRunner({ dbOptions: [{ transactionLogMaxSize: 1000 }] }, async ({ db, dbPath }) => {
const log = db.useLog('foo');
// fill up the first file with just enough space for the next
// transaction header
const targetSize = 1000 - TRANSACTION_LOG_ENTRY_HEADER_SIZE;
const targetData = Buffer.alloc(targetSize, 'a');
await db.transaction(async (txn) => {
log.addEntry(targetData, txn.id);
});
// add a second entry which writes the header to the first file and
// continues in the second file
await db.transaction(async (txn) => {
log.addEntry(Buffer.alloc(100, 'a'), txn.id);
});
const logStorePath = join(dbPath, 'transaction_logs', 'foo');
const logFiles = await readdir(logStorePath);
expect(logFiles.sort()).toEqual(['1.txnlog', '2.txnlog']);
const log1Path = join(dbPath, 'transaction_logs', 'foo', '1.txnlog');
const log2Path = join(dbPath, 'transaction_logs', 'foo', '2.txnlog');
const info1 = parseTransactionLog(log1Path);
const info2 = parseTransactionLog(log2Path);
expect(info1.size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + TRANSACTION_LOG_ENTRY_HEADER_SIZE + targetSize
);
expect(info1.entries.length).toBe(1);
expect(info1.entries[0].length).toBe(targetSize);
expect(info1.entries[0].data).toEqual(targetData);
expect(info2.size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + TRANSACTION_LOG_ENTRY_HEADER_SIZE + 100
);
expect(info2.entries.length).toBe(1);
expect(info2.entries[0].length).toBe(100);
expect(info2.entries[0].data).toEqual(Buffer.alloc(100, 'a'));
const queryResults = Array.from(log.query({ start: 0 }));
expect(queryResults.length).toBe(2);
}));
it('should continue batch in next file', () =>
dbRunner({ dbOptions: [{ transactionLogMaxSize: 1000 }] }, async ({ db, dbPath }) => {
const log = db.useLog('foo');
const value = Buffer.alloc(100, 'a');
await db.transaction(async (txn) => {
for (let i = 0; i < 15; i++) {
log.addEntry(value, txn.id);
}
});
const logStorePath = join(dbPath, 'transaction_logs', 'foo');
const logFiles = await readdir(logStorePath);
expect(logFiles.sort()).toEqual(['1.txnlog', '2.txnlog']);
const log1Path = join(dbPath, 'transaction_logs', 'foo', '1.txnlog');
const log2Path = join(dbPath, 'transaction_logs', 'foo', '2.txnlog');
const info1 = parseTransactionLog(log1Path);
const info2 = parseTransactionLog(log2Path);
expect(info1.size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + (TRANSACTION_LOG_ENTRY_HEADER_SIZE + 100) * 8
);
expect(info1.entries.length).toBe(8);
expect(info1.entries[0].length).toBe(100);
expect(info1.entries[0].data).toEqual(Buffer.alloc(100, 'a'));
expect(info2.size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + (TRANSACTION_LOG_ENTRY_HEADER_SIZE + 100) * 7
);
expect(info2.entries.length).toBe(7);
expect(info2.entries[0].length).toBe(100);
expect(info2.entries[0].data).toEqual(Buffer.alloc(100, 'a'));
const queryResults = Array.from(log.query({ start: 0 }));
expect(queryResults.length).toBe(15);
expect(queryResults[0].endTxn).toBe(false);
expect(queryResults[14].endTxn).toBe(true);
}));
it('should be able to rotate with entries that span a transaction', () =>
dbRunner({ dbOptions: [{ transactionLogMaxSize: 1000 }] }, async ({ db, dbPath }) => {
let log = db.useLog('foo');
const value = Buffer.alloc(100, 'a');
await db.transaction(async (txn) => {
log.addEntry(value, txn.id);
});
for (let i = 0; i < 5; i++) {
await db.transaction(async (txn) => {
log.addEntry(value, txn.id);
log.addEntry(value, txn.id);
});
}
const logStorePath = join(dbPath, 'transaction_logs', 'foo');
const logFiles = await readdir(logStorePath);
expect(logFiles.sort()).toEqual(['1.txnlog', '2.txnlog']);
const log1Path = join(dbPath, 'transaction_logs', 'foo', '1.txnlog');
const log2Path = join(dbPath, 'transaction_logs', 'foo', '2.txnlog');
const info1 = parseTransactionLog(log1Path);
const info2 = parseTransactionLog(log2Path);
expect(info1.size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + (TRANSACTION_LOG_ENTRY_HEADER_SIZE + 100) * 8
);
expect(info1.entries.length).toBe(8);
expect(info1.entries[0].length).toBe(100);
expect(info1.entries[0].data).toEqual(Buffer.alloc(100, 'a'));
expect(info2.size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + (TRANSACTION_LOG_ENTRY_HEADER_SIZE + 100) * 3
);
expect(info2.entries.length).toBe(3);
expect(info2.entries[0].length).toBe(100);
expect(info2.entries[0].data).toEqual(Buffer.alloc(100, 'a'));
const queryResults = Array.from(log.query({ start: 0 }));
expect(queryResults.length).toBe(11);
}));
it(
'should write to same log from multiple workers',
() =>
dbRunner(async ({ db, dbPath }) => {
const worker = new Worker(
createWorkerBootstrapScript('./test/workers/transaction-log-worker.mts'),
{ eval: true, workerData: { path: dbPath } }
);
let resolver = withResolvers<void>();
await new Promise<void>((resolve, reject) => {
worker.on('error', reject);
worker.on('message', (event) => {
try {
if (event.started) {
resolve();
} else if (event.done) {
resolver.resolve();
}
} catch (error) {
reject(error);
}
});
worker.on('exit', () => resolver.resolve());
});
worker.postMessage({ addManyEntries: true, count: 500 });
for (let i = 0; i < 500; i++) {
const log = db.useLog('foo');
await db.transaction(async (txn) => {
log.addEntry(Buffer.from('hello'), txn.id);
});
if (i > 0 && i % 10 === 0) {
db.purgeLogs({ destroy: true });
}
}
await resolver.promise;
resolver = withResolvers<void>();
worker.postMessage({ close: true });
if (process.versions.deno) {
// deno doesn't emit an `exit` event when the worker quits, but
// `terminate()` will trigger the `exit` event
await delay(100);
worker.terminate();
}
await resolver.promise;
}),
60000
);
it('should rotate if file exceeds max age threshold', () =>
dbRunner(
{
dbOptions: [{ transactionLogRetention: 2000, transactionLogMaxAgeThreshold: 0.9 }],
},
async ({ db, dbPath }) => {
// we need to add the entry within 3 seconds
const log = db.useLog('foo');
await db.transaction(async (txn) => {
log.addEntry(Buffer.alloc(10, 'a'), txn.id);
});
await delay(250);
// File should now be 250ms old, exceeding the rotation threshold of
// 200ms (2000ms retention × (1 - 0.9 threshold) = 200ms)
await db.transaction(async (txn) => {
log.addEntry(Buffer.alloc(10, 'a'), txn.id);
});
const logStorePath = join(dbPath, 'transaction_logs', 'foo');
const logFiles = await readdir(logStorePath);
expect(logFiles.sort()).toEqual(['1.txnlog', '2.txnlog']);
const log1Path = join(dbPath, 'transaction_logs', 'foo', '1.txnlog');
const log2Path = join(dbPath, 'transaction_logs', 'foo', '2.txnlog');
const info1 = parseTransactionLog(log1Path);
const info2 = parseTransactionLog(log2Path);
expect(info1.size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + TRANSACTION_LOG_ENTRY_HEADER_SIZE + 10
);
expect(info1.version).toBe(1);
expect(info1.entries.length).toBe(1);
expect(info1.entries[0].timestamp).toBeGreaterThanOrEqual(Date.now() - 10000);
expect(info1.entries[0].length).toBe(10);
expect(info1.entries[0].data).toEqual(Buffer.alloc(10, 'a'));
expect(info2.size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + TRANSACTION_LOG_ENTRY_HEADER_SIZE + 10
);
expect(info2.version).toBe(1);
expect(info2.entries.length).toBe(1);
expect(info2.entries[0].timestamp).toBeGreaterThanOrEqual(Date.now() - 1000);
expect(info2.entries[0].length).toBe(10);
expect(info2.entries[0].data).toEqual(Buffer.alloc(10, 'a'));
}
));
it('should append to existing log file', () =>
dbRunner(async ({ db, dbPath }) => {
const log = db.useLog('foo');
const valueA = Buffer.alloc(10, 'a');
const valueB = Buffer.alloc(10, 'b');
await db.transaction(async (txn) => {
log.addEntry(valueA, txn.id);
});
const logPath = join(dbPath, 'transaction_logs', 'foo', '1.txnlog');
let info = parseTransactionLog(logPath);
expect(info.size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + TRANSACTION_LOG_ENTRY_HEADER_SIZE + 10
);
expect(info.version).toBe(1);
expect(info.entries.length).toBe(1);
expect(info.entries[0].timestamp).toBeGreaterThanOrEqual(Date.now() - 1000);
expect(info.entries[0].length).toBe(10);
expect(info.entries[0].data).toEqual(valueA);
db.close();
db.open();
await db.transaction(async (txn) => {
log.addEntry(valueB, txn.id);
});
info = parseTransactionLog(logPath);
expect(info.size).toBe(
TRANSACTION_LOG_FILE_HEADER_SIZE + (TRANSACTION_LOG_ENTRY_HEADER_SIZE + 10) * 2
);
expect(info.version).toBe(1);
expect(info.entries.length).toBe(2);
expect(info.entries[0].timestamp).toBeGreaterThanOrEqual(Date.now() - 10000);
expect(info.entries[0].length).toBe(10);
expect(info.entries[0].data).toEqual(valueA);
expect(info.entries[1].timestamp).toBeGreaterThanOrEqual(Date.now() - 1000);
expect(info.entries[1].length).toBe(10);
expect(info.entries[1].data).toEqual(valueB);
const queryResults = Array.from(log.query({ start: 0 }));
expect(queryResults.length).toBe(2);
}));
it('should write earliest timestamp in file headers', () =>
dbRunner({ dbOptions: [{ transactionLogMaxSize: 1000 }] }, async ({ db, dbPath }) => {
const log = db.useLog('foo');
await Promise.all([
db.transaction(async (txn) => {
// this transaction started first, but will take longer
await delay(100);
log.addEntry(Buffer.alloc(990, 'a'), txn.id); // 2.txnlog
}),
db.transaction(async (txn) => {
log.addEntry(Buffer.alloc(990, 'a'), txn.id); // 1.txnlog
}),
]);
const log1Path = join(dbPath, 'transaction_logs', 'foo', '1.txnlog');
const log2Path = join(dbPath, 'transaction_logs', 'foo', '2.txnlog');
const info1 = parseTransactionLog(log1Path);
const info2 = parseTransactionLog(log2Path);
expect(info1.timestamp).toBe(info2.timestamp);
await db.transaction(async (txn) => {
log.addEntry(Buffer.alloc(990, 'a'), txn.id); // 3.txnlog
});
const log3Path = join(dbPath, 'transaction_logs', 'foo', '3.txnlog');
const info3 = parseTransactionLog(log3Path);
expect(info3.timestamp).toBeGreaterThan(info2.timestamp);
await Promise.all([
db.transaction(async (txn) => {