-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathlocking.test.ts
More file actions
992 lines (863 loc) · 31.9 KB
/
locking.test.ts
File metadata and controls
992 lines (863 loc) · 31.9 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
import { createRedisClient } from "@internal/redis";
import { redisTest } from "@internal/testcontainers";
import { expect } from "vitest";
import { RunLocker, LockAcquisitionTimeoutError } from "../locking.js";
import { trace } from "@internal/tracing";
import { Logger } from "@trigger.dev/core/logger";
describe("RunLocker", () => {
redisTest("Test acquiring a lock works", { timeout: 60_000 }, async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
});
try {
expect(runLock.isInsideLock()).toBe(false);
await runLock.lock("test-lock", ["test-1"], async () => {
expect(runLock.isInsideLock()).toBe(true);
});
expect(runLock.isInsideLock()).toBe(false);
} finally {
await runLock.quit();
}
});
redisTest("Test double locking works", { timeout: 15_000 }, async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({ redis, logger, tracer: trace.getTracer("RunLockTest") });
try {
expect(runLock.isInsideLock()).toBe(false);
await runLock.lock("test-lock", ["test-1"], async () => {
expect(runLock.isInsideLock()).toBe(true);
//should be able to "lock it again"
await runLock.lock("test-lock", ["test-1"], async () => {
expect(runLock.isInsideLock()).toBe(true);
});
});
expect(runLock.isInsideLock()).toBe(false);
} finally {
await runLock.quit();
}
});
redisTest(
"Test lock throws when callback throws",
{ timeout: 15_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({ redis, logger, tracer: trace.getTracer("RunLockTest") });
try {
expect(runLock.isInsideLock()).toBe(false);
await expect(
runLock.lock("test-lock", ["test-1"], async () => {
throw new Error("Test error");
})
).rejects.toThrow("Test error");
// Verify the lock was released
expect(runLock.isInsideLock()).toBe(false);
} finally {
await runLock.quit();
}
}
);
redisTest(
"Test nested lock throws when inner callback throws",
{ timeout: 15_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({ redis, logger, tracer: trace.getTracer("RunLockTest") });
try {
expect(runLock.isInsideLock()).toBe(false);
await expect(
runLock.lock("test-lock", ["test-1"], async () => {
expect(runLock.isInsideLock()).toBe(true);
// Nested lock with same resource
await runLock.lock("test-lock", ["test-1"], async () => {
expect(runLock.isInsideLock()).toBe(true);
throw new Error("Inner lock error");
});
})
).rejects.toThrow("Inner lock error");
// Verify all locks were released
expect(runLock.isInsideLock()).toBe(false);
} finally {
await runLock.quit();
}
}
);
redisTest("Test lock throws when it times out", { timeout: 45_000 }, async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
retryConfig: {
maxAttempts: 3,
baseDelay: 100,
maxTotalWaitTime: 2000, // 2 second timeout for faster test
},
});
try {
// First, ensure we can acquire the lock normally
let firstLockAcquired = false;
await runLock.lock("test-lock", ["test-1"], async () => {
firstLockAcquired = true;
});
//wait for 20ms
await new Promise((resolve) => setTimeout(resolve, 20));
expect(firstLockAcquired).toBe(true);
// Now create a long-running lock
const lockPromise1 = runLock.lock("test-lock", ["test-1"], async () => {
// Hold the lock longer than the retry timeout
await new Promise((resolve) => setTimeout(resolve, 10000));
});
// Try to acquire same lock immediately - should timeout with LockAcquisitionTimeoutError
await expect(
runLock.lock("test-lock", ["test-1"], async () => {
// This should never execute
expect(true).toBe(false);
})
).rejects.toThrow(LockAcquisitionTimeoutError);
// Complete the first lock
await lockPromise1;
// Verify final state
expect(runLock.isInsideLock()).toBe(false);
} finally {
await runLock.quit();
}
});
redisTest(
"Test nested lock with same resources doesn't timeout",
{ timeout: 15_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({ redis, logger, tracer: trace.getTracer("RunLockTest") });
try {
await runLock.lock("test-lock", ["test-1"], async () => {
// First lock acquired
expect(runLock.isInsideLock()).toBe(true);
// Try to acquire the same resource with a very short timeout
// This should work because we already hold the lock
await runLock.lock("test-lock", ["test-1"], async () => {
expect(runLock.isInsideLock()).toBe(true);
// Wait longer than the timeout to prove it doesn't matter
await new Promise((resolve) => setTimeout(resolve, 500));
});
});
// Verify final state
expect(runLock.isInsideLock()).toBe(false);
} finally {
await runLock.quit();
}
}
);
redisTest(
"Test nested lock with same resource works regardless of retries",
{ timeout: 15_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({ redis, logger, tracer: trace.getTracer("RunLockTest") });
try {
// First verify we can acquire the lock normally
let firstLockAcquired = false;
await runLock.lock("test-lock", ["test-1"], async () => {
firstLockAcquired = true;
});
expect(firstLockAcquired).toBe(true);
// Now test the nested lock behavior
let outerLockExecuted = false;
let innerLockExecuted = false;
await runLock.lock("test-lock", ["test-1"], async () => {
outerLockExecuted = true;
expect(runLock.isInsideLock()).toBe(true);
expect(runLock.getCurrentResources()).toBe("test-1");
// Try to acquire the same resource in a nested lock
// This should work immediately without any retries
// because we already hold the lock
await runLock.lock("test-lock", ["test-1"], async () => {
innerLockExecuted = true;
expect(runLock.isInsideLock()).toBe(true);
expect(runLock.getCurrentResources()).toBe("test-1");
// Sleep longer than retry attempts would normally take
// This proves the nested lock doesn't go through the retry logic
await new Promise((resolve) => setTimeout(resolve, 5000));
});
});
// Verify both locks executed
expect(outerLockExecuted).toBe(true);
expect(innerLockExecuted).toBe(true);
expect(runLock.isInsideLock()).toBe(false);
} finally {
await runLock.quit();
}
}
);
redisTest(
"Test configurable retry settings work",
{ timeout: 15_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
retryConfig: {
maxAttempts: 2,
baseDelay: 50,
maxDelay: 200,
backoffMultiplier: 2.0,
jitterFactor: 0.1,
maxTotalWaitTime: 1000,
},
});
try {
// Verify configuration is set correctly
const config = runLock.getRetryConfig();
expect(config.maxAttempts).toBe(2);
expect(config.baseDelay).toBe(50);
expect(config.maxDelay).toBe(200);
expect(config.backoffMultiplier).toBe(2.0);
expect(config.jitterFactor).toBe(0.1);
expect(config.maxTotalWaitTime).toBe(1000);
// Test that the lock still works normally
await runLock.lock("test-lock", ["test-config"], async () => {
expect(runLock.isInsideLock()).toBe(true);
});
expect(runLock.isInsideLock()).toBe(false);
} finally {
await runLock.quit();
}
}
);
redisTest(
"Test LockAcquisitionTimeoutError contains correct information",
{ timeout: 25_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
retryConfig: {
maxAttempts: 2,
baseDelay: 50,
maxTotalWaitTime: 500, // Shorter timeout to ensure failure
},
});
try {
// Create a long-running lock that will definitely outlast the retry timeout
const lockPromise = runLock.lock("test-lock", ["test-error"], async () => {
await new Promise((resolve) => setTimeout(resolve, 15000)); // Hold for 15 seconds
});
// Wait a bit to ensure the first lock is acquired
await new Promise((resolve) => setTimeout(resolve, 100));
// Try to acquire same lock and capture the timeout error
try {
await runLock.lock("test-lock", ["test-error"], async () => {
expect(true).toBe(false); // Should never execute
});
expect(true).toBe(false); // Should not reach here
} catch (error) {
expect(error).toBeInstanceOf(LockAcquisitionTimeoutError);
if (error instanceof LockAcquisitionTimeoutError) {
expect(error.resources).toEqual(["test-error"]);
expect(error.attempts).toBeGreaterThan(0);
expect(error.attempts).toBeLessThanOrEqual(3); // maxAttempts + 1
expect(error.totalWaitTime).toBeGreaterThan(0);
expect(error.totalWaitTime).toBeLessThanOrEqual(800); // Some tolerance
expect(error.name).toBe("LockAcquisitionTimeoutError");
expect(error.message).toContain("test-error");
expect(error.message).toContain(`${error.attempts} attempts`);
}
}
// Complete the first lock
await lockPromise;
} finally {
await runLock.quit();
}
}
);
redisTest("Test default configuration values", { timeout: 15_000 }, async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
// No retryConfig provided - should use defaults
});
try {
const config = runLock.getRetryConfig();
expect(config.maxAttempts).toBe(10);
expect(config.baseDelay).toBe(200);
expect(config.maxDelay).toBe(5000);
expect(config.backoffMultiplier).toBe(1.5);
expect(config.jitterFactor).toBe(0.1);
expect(config.maxTotalWaitTime).toBe(30000);
// Test that it still works
await runLock.lock("test-lock", ["test-default"], async () => {
expect(runLock.isInsideLock()).toBe(true);
});
} finally {
await runLock.quit();
}
});
redisTest(
"Test partial configuration override",
{ timeout: 15_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
retryConfig: {
maxAttempts: 5,
maxTotalWaitTime: 10000,
// Other values should use defaults
},
});
try {
const config = runLock.getRetryConfig();
expect(config.maxAttempts).toBe(5); // Overridden
expect(config.maxTotalWaitTime).toBe(10000); // Overridden
expect(config.baseDelay).toBe(200); // Default
expect(config.maxDelay).toBe(5000); // Default
expect(config.backoffMultiplier).toBe(1.5); // Default
expect(config.jitterFactor).toBe(0.1); // Default
} finally {
await runLock.quit();
}
}
);
redisTest("Test lockIf functionality", { timeout: 15_000 }, async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
});
try {
let executedWithLock = false;
let executedWithoutLock = false;
// Test with condition = true (should acquire lock)
await runLock.lockIf(true, "test-lock", ["test-lockif"], async () => {
executedWithLock = true;
expect(runLock.isInsideLock()).toBe(true);
expect(runLock.getCurrentResources()).toBe("test-lockif");
});
expect(executedWithLock).toBe(true);
expect(runLock.isInsideLock()).toBe(false);
// Test with condition = false (should not acquire lock)
await runLock.lockIf(false, "test-lock", ["test-lockif"], async () => {
executedWithoutLock = true;
expect(runLock.isInsideLock()).toBe(false);
expect(runLock.getCurrentResources()).toBeUndefined();
});
expect(executedWithoutLock).toBe(true);
} finally {
await runLock.quit();
}
});
redisTest(
"Test concurrent locks on different resources",
{ timeout: 15_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
});
try {
const results: string[] = [];
// Start multiple concurrent locks on different resources
const lock1Promise = runLock.lock("test-lock", ["resource-1"], async () => {
results.push("lock1-start");
await new Promise((resolve) => setTimeout(resolve, 100));
results.push("lock1-end");
return "result1";
});
const lock2Promise = runLock.lock("test-lock", ["resource-2"], async () => {
results.push("lock2-start");
await new Promise((resolve) => setTimeout(resolve, 100));
results.push("lock2-end");
return "result2";
});
const lock3Promise = runLock.lock("test-lock", ["resource-3"], async () => {
results.push("lock3-start");
await new Promise((resolve) => setTimeout(resolve, 100));
results.push("lock3-end");
return "result3";
});
const [result1, result2, result3] = await Promise.all([
lock1Promise,
lock2Promise,
lock3Promise,
]);
expect(result1).toBe("result1");
expect(result2).toBe("result2");
expect(result3).toBe("result3");
// All locks should have started (concurrent execution)
expect(results).toContain("lock1-start");
expect(results).toContain("lock2-start");
expect(results).toContain("lock3-start");
expect(results).toContain("lock1-end");
expect(results).toContain("lock2-end");
expect(results).toContain("lock3-end");
} finally {
await runLock.quit();
}
}
);
redisTest(
"Test multiple resources in single lock",
{ timeout: 15_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
});
try {
await runLock.lock("test-lock", ["resource-a", "resource-b", "resource-c"], async () => {
expect(runLock.isInsideLock()).toBe(true);
// Resources should be sorted and joined
expect(runLock.getCurrentResources()).toBe("resource-a,resource-b,resource-c");
});
// Test that resource order doesn't matter (should be normalized)
await runLock.lock("test-lock", ["resource-c", "resource-a", "resource-b"], async () => {
expect(runLock.getCurrentResources()).toBe("resource-a,resource-b,resource-c");
});
} finally {
await runLock.quit();
}
}
);
redisTest(
"Test different lock names on same resources don't interfere",
{ timeout: 15_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
});
try {
const results: string[] = [];
// These should be able to run concurrently despite same resources
// because they have different lock names
const promise1 = runLock.lock("lock-type-1", ["shared-resource"], async () => {
results.push("type1-start");
await new Promise((resolve) => setTimeout(resolve, 200));
results.push("type1-end");
});
const promise2 = runLock.lock("lock-type-2", ["shared-resource"], async () => {
results.push("type2-start");
await new Promise((resolve) => setTimeout(resolve, 200));
results.push("type2-end");
});
await Promise.all([promise1, promise2]);
// Both should have executed (different lock names don't block each other)
expect(results).toContain("type1-start");
expect(results).toContain("type1-end");
expect(results).toContain("type2-start");
expect(results).toContain("type2-end");
} finally {
await runLock.quit();
}
}
);
redisTest(
"Test default duration configuration",
{ timeout: 15_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
// Test with custom default duration
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
duration: 8000,
});
try {
// Test that the default duration is set correctly
expect(runLock.getDuration()).toBe(8000);
// Test lock without specifying duration (should use default)
const startTime = Date.now();
await runLock.lock("test-lock", ["default-duration-test"], async () => {
expect(runLock.isInsideLock()).toBe(true);
// Sleep for a bit to ensure the lock is working
await new Promise((resolve) => setTimeout(resolve, 100));
});
const elapsed = Date.now() - startTime;
expect(elapsed).toBeGreaterThan(90); // Should have completed successfully
// Test lockIf without duration (should use default)
await runLock.lockIf(true, "test-lock", ["lockif-default"], async () => {
expect(runLock.isInsideLock()).toBe(true);
});
} finally {
await runLock.quit();
}
}
);
redisTest(
"Test automatic extension threshold configuration",
{ timeout: 15_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
// Test with custom automatic extension threshold
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
automaticExtensionThreshold: 200, // Custom threshold
duration: 800,
});
try {
// Test that the threshold is set correctly
expect(runLock.getAutomaticExtensionThreshold()).toBe(200);
expect(runLock.getDuration()).toBe(800); // Should use configured value
// Test lock extension with custom threshold
// Use a short lock duration but longer operation to trigger extension
await runLock.lock("test-lock", ["extension-threshold-test"], async () => {
expect(runLock.isInsideLock()).toBe(true);
// Sleep longer than lock duration to ensure extension works
await new Promise((resolve) => setTimeout(resolve, 1200));
});
} finally {
await runLock.quit();
}
}
);
redisTest("Test Redlock retry configuration", { timeout: 10_000 }, async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
// Test that we can configure all settings
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
duration: 3000,
automaticExtensionThreshold: 300,
retryConfig: {
maxAttempts: 5,
baseDelay: 150,
},
});
try {
// Verify all configurations are set
expect(runLock.getDuration()).toBe(3000);
expect(runLock.getAutomaticExtensionThreshold()).toBe(300);
const retryConfig = runLock.getRetryConfig();
expect(retryConfig.maxAttempts).toBe(5);
expect(retryConfig.baseDelay).toBe(150);
// Test basic functionality with all custom configs
await runLock.lock("test-lock", ["all-config-test"], async () => {
expect(runLock.isInsideLock()).toBe(true);
});
} finally {
await runLock.quit();
}
});
redisTest(
"Test production-optimized configuration",
{ timeout: 15_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
// Test with production-optimized settings (similar to RunEngine)
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
duration: 10000,
automaticExtensionThreshold: 2000,
retryConfig: {
maxAttempts: 15,
baseDelay: 100,
maxDelay: 3000,
backoffMultiplier: 1.8,
jitterFactor: 0.15,
maxTotalWaitTime: 25000,
},
});
try {
// Verify production configuration
expect(runLock.getDuration()).toBe(10000);
expect(runLock.getAutomaticExtensionThreshold()).toBe(2000);
const retryConfig = runLock.getRetryConfig();
expect(retryConfig.maxAttempts).toBe(15);
expect(retryConfig.baseDelay).toBe(100);
expect(retryConfig.maxDelay).toBe(3000);
expect(retryConfig.backoffMultiplier).toBe(1.8);
expect(retryConfig.jitterFactor).toBe(0.15);
expect(retryConfig.maxTotalWaitTime).toBe(25000);
// Test lock with default duration (should use 10 seconds)
const startTime = Date.now();
await runLock.lock("test-lock", ["production-config"], async () => {
expect(runLock.isInsideLock()).toBe(true);
// Simulate a typical operation duration
await new Promise((resolve) => setTimeout(resolve, 200));
});
const elapsed = Date.now() - startTime;
expect(elapsed).toBeGreaterThan(190);
expect(elapsed).toBeLessThan(1000); // Should complete quickly for successful operation
} finally {
await runLock.quit();
}
}
);
redisTest("Test configuration edge cases", { timeout: 15_000 }, async ({ redisOptions }) => {
const logger = new Logger("RunLockTest", "debug");
// Test with maxAttempts = 0
const redis1 = createRedisClient(redisOptions);
const runLock1 = new RunLocker({
redis: redis1,
logger,
tracer: trace.getTracer("RunLockTest"),
retryConfig: {
maxAttempts: 0,
baseDelay: 100,
maxTotalWaitTime: 1000,
},
});
try {
const config = runLock1.getRetryConfig();
expect(config.maxAttempts).toBe(0);
// Should work for successful acquisitions
await runLock1.lock("test-lock", ["test-edge"], async () => {
expect(runLock1.isInsideLock()).toBe(true);
});
} finally {
await runLock1.quit();
}
// Test with very small delays
const redis2 = createRedisClient(redisOptions);
const runLock2 = new RunLocker({
redis: redis2,
logger,
tracer: trace.getTracer("RunLockTest"),
retryConfig: {
maxAttempts: 2,
baseDelay: 1,
maxDelay: 10,
backoffMultiplier: 2.0,
jitterFactor: 0.5,
maxTotalWaitTime: 100,
},
});
try {
const config = runLock2.getRetryConfig();
expect(config.baseDelay).toBe(1);
expect(config.maxDelay).toBe(10);
expect(config.jitterFactor).toBe(0.5);
await runLock2.lock("test-lock", ["test-small"], async () => {
expect(runLock2.isInsideLock()).toBe(true);
});
} finally {
await runLock2.quit();
}
});
redisTest("Test total wait time configuration", { timeout: 10_000 }, async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
retryConfig: {
maxAttempts: 100, // High retry count
baseDelay: 100,
maxTotalWaitTime: 500, // But low total wait time
},
});
try {
// Test that total wait time configuration is properly applied
const config = runLock.getRetryConfig();
expect(config.maxAttempts).toBe(100);
expect(config.maxTotalWaitTime).toBe(500);
expect(config.baseDelay).toBe(100);
// Basic functionality test with the configuration
await runLock.lock("test-lock", ["test-timing-config"], async () => {
expect(runLock.isInsideLock()).toBe(true);
});
expect(runLock.isInsideLock()).toBe(false);
} finally {
await runLock.quit();
}
});
redisTest(
"Test quit functionality and cleanup",
{ timeout: 15_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
});
// Acquire some locks to create state
await runLock.lock("test-lock", ["quit-test-1"], async () => {
expect(runLock.isInsideLock()).toBe(true);
});
// Verify we can still acquire locks
await runLock.lock("test-lock", ["quit-test-2"], async () => {
expect(runLock.isInsideLock()).toBe(true);
});
// Now quit should clean everything up
await runLock.quit();
// After quit, should be able to create new instance and acquire locks
const newRedis = createRedisClient(redisOptions);
const newRunLock = new RunLocker({
redis: newRedis,
logger,
tracer: trace.getTracer("RunLockTest"),
});
try {
await newRunLock.lock("test-lock", ["quit-test-1"], async () => {
expect(newRunLock.isInsideLock()).toBe(true);
});
} finally {
await newRunLock.quit();
}
}
);
redisTest(
"Test lock extension during long operations",
{ timeout: 20_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
duration: 1000,
});
try {
let lockExtended = false;
const startTime = Date.now();
// Acquire lock with short duration but long operation
await runLock.lock("test-lock", ["extension-test"], async () => {
// Operation longer than lock duration - should trigger extension
await new Promise((resolve) => setTimeout(resolve, 2500));
const elapsed = Date.now() - startTime;
expect(elapsed).toBeGreaterThan(2000);
// If we get here, extension must have worked
lockExtended = true;
});
expect(lockExtended).toBe(true);
} finally {
await runLock.quit();
}
}
);
redisTest(
"Test getCurrentResources in various states",
{ timeout: 15_000 },
async ({ redisOptions }) => {
const redis = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock = new RunLocker({
redis,
logger,
tracer: trace.getTracer("RunLockTest"),
});
try {
// Outside any lock
expect(runLock.getCurrentResources()).toBeUndefined();
expect(runLock.isInsideLock()).toBe(false);
await runLock.lock("test-lock", ["resource-x", "resource-y"], async () => {
// Inside lock
expect(runLock.getCurrentResources()).toBe("resource-x,resource-y");
expect(runLock.isInsideLock()).toBe(true);
await runLock.lock("test-lock", ["resource-x", "resource-y"], async () => {
// Nested lock with same resources
expect(runLock.getCurrentResources()).toBe("resource-x,resource-y");
expect(runLock.isInsideLock()).toBe(true);
});
});
// Outside lock again
expect(runLock.getCurrentResources()).toBeUndefined();
expect(runLock.isInsideLock()).toBe(false);
} finally {
await runLock.quit();
}
}
);
redisTest(
"Test retry behavior with exact timing",
{ timeout: 25_000 },
async ({ redisOptions }) => {
const redis1 = createRedisClient(redisOptions);
const redis2 = createRedisClient(redisOptions);
const logger = new Logger("RunLockTest", "debug");
const runLock1 = new RunLocker({
redis: redis1,
logger,
tracer: trace.getTracer("RunLockTest"),
});
const runLock2 = new RunLocker({
redis: redis2,
logger,
tracer: trace.getTracer("RunLockTest"),
duration: 30000,
retryConfig: {
maxAttempts: 3,
baseDelay: 100,
maxDelay: 500,
backoffMultiplier: 2.0,
jitterFactor: 0, // No jitter for predictable timing
maxTotalWaitTime: 10000,
},
});
try {
// Create blocking lock with first instance - make it last much longer than retry logic
const blockingPromise = runLock1.lock("test-lock", ["timing-test"], async () => {
await new Promise((resolve) => setTimeout(resolve, 15000));
});
await new Promise((resolve) => setTimeout(resolve, 200));
const startTime = Date.now();
try {
await runLock2.lock("test-lock", ["timing-test"], async () => {
expect(true).toBe(false);
});
expect(true).toBe(false); // Should not reach here
} catch (error) {
const elapsed = Date.now() - startTime;
expect(error).toBeInstanceOf(LockAcquisitionTimeoutError);
if (error instanceof LockAcquisitionTimeoutError) {
expect(error.attempts).toBe(4); // 0 + 3 retries
// With backoff: 100ms + 200ms + 400ms = 700ms total wait time
expect(error.totalWaitTime).toBeGreaterThan(600);
expect(error.totalWaitTime).toBeLessThan(800);
expect(elapsed).toBeGreaterThan(600);
}
}
await blockingPromise;
} finally {
await runLock1.quit();
await runLock2.quit();
}
}
);
});