Repository navigation
Expand file tree
/
Copy pathAsyncNotificationTest.java
More file actions
2013 lines (1913 loc) · 107 KB
/
Copy pathAsyncNotificationTest.java
File metadata and controls
2013 lines (1913 loc) · 107 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
package dev.jinhyeon.notificationlab.outbox;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.model.PortBinding;
import com.github.dockerjava.api.model.Ports;
import dev.jinhyeon.notificationlab.NotificationLabApplication;
import dev.jinhyeon.notificationlab.config.AsyncProperties;
import dev.jinhyeon.notificationlab.config.TrafficProperties;
import dev.jinhyeon.notificationlab.notification.JdbcNotificationStore;
import dev.jinhyeon.notificationlab.notification.NotificationStatus;
import dev.jinhyeon.notificationlab.provider.PushProvider;
import dev.jinhyeon.notificationlab.provider.MockPushProvider;
import dev.jinhyeon.notificationlab.provider.PushRequest;
import dev.jinhyeon.notificationlab.provider.PushResult;
import dev.jinhyeon.notificationlab.worker.WorkerStore;
import dev.jinhyeon.notificationlab.worker.DeliveryTaskStore;
import io.micrometer.core.instrument.MeterRegistry;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.sql.DriverManager;
import java.time.Duration;
import java.time.Clock;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import dev.jinhyeon.notificationlab.notification.NotificationRequest;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import javax.sql.DataSource;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;
import org.springframework.jdbc.core.RowMapper;
import java.util.function.Function;
import org.apache.kafka.clients.admin.Admin;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.kafka.KafkaContainer;
import org.testcontainers.utility.DockerImageName;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.awaitility.Awaitility.await;
/** Real infrastructure; no skipped Docker tests and no mock Kafka broker. */
@Testcontainers
class AsyncNotificationTest {
@Container
static final MySQLContainer<?> MYSQL = new MySQLContainer<>("mysql:8.4.8")
.withDatabaseName("notification_lab").withUsername("notification_test")
.withPassword(UUID.randomUUID().toString()).withCommand("--default-time-zone=+00:00")
.withUrlParam("connectionTimeZone", "UTC").withUrlParam("forceConnectionTimeZoneToSession", "true")
.withCreateContainerCmdModifier(cmd -> cmd.getHostConfig().withPortBindings(
Arrays.stream(cmd.getExposedPorts()).map(port ->
new PortBinding(Ports.Binding.bindIpAndPort("127.0.0.1", 0), port)).toList()));
@Container
static final KafkaContainer KAFKA = new KafkaContainer(DockerImageName.parse("apache/kafka:4.0.2"))
.withEnv("KAFKA_HEAP_OPTS", "-Xms256m -Xmx512m")
.withCreateContainerCmdModifier(cmd -> cmd.getHostConfig().withPortBindings(
Arrays.stream(cmd.getExposedPorts()).map(port ->
new PortBinding(Ports.Binding.bindIpAndPort("127.0.0.1", 0), port)).toList()));
private ServletWebServerApplicationContext app;
private HttpClient http;
private Admin admin;
private String topic;
private String group;
private static final String PAYLOAD = """
{"recipientId":"synthetic-user","title":"비동기 테스트","body":"가상 데이터"}
""";
@BeforeEach
void start(TestInfo info) {
topic = "notification-test-" + UUID.randomUUID();
group = "worker-test-" + UUID.randomUUID();
boolean experiment = info.getTags().contains("reconciliation");
startApplication(experiment);
jdbc().update("DELETE FROM dead_letter_redrive");
jdbc().update("DELETE FROM delivery_attempt");
jdbc().update("DELETE FROM delivery_task");
jdbc().update("DELETE FROM outbox_event");
jdbc().update("DELETE FROM notification");
http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
admin = Admin.create(java.util.Map.of("bootstrap.servers", KAFKA.getBootstrapServers()));
}
private void startApplication(boolean experiment, String... overrides) {
app = (ServletWebServerApplicationContext) new SpringApplicationBuilder(
NotificationLabApplication.class, ProbeConfiguration.class).run(java.util.stream.Stream.concat(java.util.stream.Stream.of(
"--server.port=0", "--spring.profiles.active=async", "--app.mock.delay-ms=0",
"--spring.datasource.url=" + MYSQL.getJdbcUrl(),
"--spring.datasource.username=" + MYSQL.getUsername(),
"--spring.datasource.password=" + MYSQL.getPassword(),
"--spring.kafka.bootstrap-servers=" + KAFKA.getBootstrapServers(),
"--app.async.topic=" + topic, "--app.async.group=" + group,
"--app.async.worker-enabled=" + experiment,
"--app.delivery.retry-base-delay-ms=" + (experiment ? "1000" : "60000"),
"--app.async.relay-initial-delay-ms=" + (experiment ? "0" : "86400000"),
"--logging.level.org.apache.kafka=WARN", "--logging.level.org.springframework.kafka=WARN"),
Arrays.stream(overrides)).toArray(String[]::new));
assertThat(Arrays.stream(app.getBeanDefinitionNames())
.map(name -> app.getBeanFactory().getBeanDefinition(name).getBeanClassName()).toList())
.doesNotContain("dev.jinhyeon.notificationlab.config.AsyncPropertiesTest$RelayConfiguration");
}
@AfterEach
void close() {
if (http != null) http.close();
if (app != null) app.close();
if (admin != null) admin.close(Duration.ofSeconds(3));
}
@Test
void publishBatchFlushesOnlyAcknowledgedRowsWhenTheNextSendFails() throws Exception {
post(); post();
var pending = new CompletableFuture<SendResult<String, String>>();
var publishing = new CountDownLatch(1);
var sends = new AtomicInteger();
var fake = new KafkaTemplate<String, String>(kafka().getProducerFactory()) {
@Override
public CompletableFuture<SendResult<String, String>> send(String destination, String key, String data) {
assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
if (sends.incrementAndGet() == 1) return CompletableFuture.completedFuture(null);
publishing.countDown();
return pending;
}
};
try (var executor = Executors.newSingleThreadExecutor()) {
var running = executor.submit(() -> batchRelay(fake).relay());
assertThat(publishing.await(5, TimeUnit.SECONDS)).isTrue();
assertThat(jdbc().queryForObject("SELECT COUNT(*) FROM outbox_event WHERE status='PUBLISHED'", Integer.class)).isLessThanOrEqualTo(1);
assertThat(jdbc().queryForObject("SELECT COUNT(*) FROM outbox_event WHERE status='PROCESSING' AND published_at IS NULL", Integer.class)).isPositive();
pending.completeExceptionally(new IllegalStateException("test broker outage"));
running.get(5, TimeUnit.SECONDS);
}
assertThat(jdbc().queryForList("SELECT status FROM outbox_event ORDER BY status", String.class)).containsExactly("PENDING", "PUBLISHED");
assertThat(registry().get("outbox.published").counter().count()).isEqualTo(1);
assertThat(registry().get("notification.pipeline.stage").tag("stage", "relay.ack").timer().count()).isEqualTo(2);
assertThat(probe().attempts.get()).isZero();
}
@Test
void publishBatchFencesEveryRowAgainstAReclaimedLease() throws Exception {
post(); post();
var store = app.getBean(OutboxStore.class);
var first = store.claim(10).orElseThrow();
var second = store.claim(10).orElseThrow();
jdbc().update("UPDATE outbox_event SET available_at=TIMESTAMPADD(SECOND,-1,UTC_TIMESTAMP(6)) WHERE event_id=?", first.eventId());
var reclaimed = store.claim(10).orElseThrow();
assertThat(reclaimed.eventId()).isEqualTo(first.eventId());
assertThat(reclaimed.token()).isNotEqualTo(first.token());
assertThat(store.published(List.of(first, second))).isEqualTo(1);
assertThat(jdbc().queryForObject("SELECT status FROM outbox_event WHERE event_id=?", String.class, first.eventId())).isEqualTo("PROCESSING");
assertThat(store.published(List.of(reclaimed))).isEqualTo(1);
assertThat(jdbc().queryForObject("SELECT COUNT(*) FROM outbox_event WHERE status='PUBLISHED'", Integer.class)).isEqualTo(2);
}
@Test
void failedPublishBatchRollsBackAndReplaysAfterLeaseExpiry() throws Exception {
post(); post();
var store = app.getBean(OutboxStore.class);
var claims = List.of(store.claim(10).orElseThrow(), store.claim(10).orElseThrow());
for (var claim : claims) kafka().send(topic, claim.notificationId(), claim.payload()).get(10, TimeUnit.SECONDS);
root("CREATE TRIGGER reject_publish_batch BEFORE UPDATE ON outbox_event FOR EACH ROW "
+ "BEGIN IF NEW.status = 'PUBLISHED' AND NEW.event_id = '" + claims.getLast().eventId()
+ "' THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'test fault'; END IF; END");
try {
assertThatThrownBy(() -> store.published(claims)).isInstanceOf(org.springframework.dao.DataAccessException.class);
assertThat(jdbc().queryForObject("SELECT COUNT(*) FROM outbox_event WHERE status='PROCESSING' AND published_at IS NULL", Integer.class)).isEqualTo(2);
assertThat(recordsOn(topic, 2)).hasSize(2);
} finally {
root("DROP TRIGGER reject_publish_batch");
}
expireOutbox();
batchRelay(kafka()).relay();
var copies = recordsOn(topic, 4);
assertThat(copies).hasSize(4);
assertThat(copies.stream().collect(java.util.stream.Collectors.groupingBy(r -> r.value(), java.util.stream.Collectors.counting())).values()).containsOnly(2L);
assertThat(jdbc().queryForObject("SELECT COUNT(*) FROM outbox_event WHERE status='PUBLISHED' AND attempt_count=2", Integer.class)).isEqualTo(2);
assertThat(probe().attempts.get()).isZero();
}
@Test
void stoppingPublishBatchFlushesAcknowledgedRowsAndLeavesTheRestDurable() throws Exception {
post(); post(); post();
var sends = new AtomicInteger();
var relay = new AtomicReference<OutboxRelay>();
var fake = new KafkaTemplate<String, String>(kafka().getProducerFactory()) {
@Override
public CompletableFuture<SendResult<String, String>> send(String destination, String key, String data) {
assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
if (sends.incrementAndGet() == 2) relay.get().stopClaiming();
return CompletableFuture.completedFuture(null);
}
};
relay.set(batchRelay(fake));
relay.get().relay();
assertThat(sends.get()).isEqualTo(2);
assertThat(jdbc().queryForObject("SELECT COUNT(*) FROM outbox_event WHERE status='PUBLISHED'", Integer.class)).isEqualTo(2);
assertThat(jdbc().queryForObject("SELECT COUNT(*) FROM outbox_event WHERE status='PENDING' AND attempt_count=0", Integer.class)).isEqualTo(1);
}
private OutboxRelay batchRelay(KafkaTemplate<String, String> template) {
return new OutboxRelay(app.getBean(OutboxStore.class), template, app.getBean(AsyncProperties.class), registry(),
app.getBean(dev.jinhyeon.notificationlab.config.TrafficRouting.class), new dev.jinhyeon.notificationlab.config.RelayProperties(10));
}
@Test
void submissionWindowBoundsOutstandingSendsAndRejectsOverlappingRuns() throws Exception {
for (int i = 0; i < 11; i++) post();
var submitted = new CountDownLatch(10);
var futures = new CopyOnWriteArrayList<CompletableFuture<SendResult<String, String>>>();
var fake = windowTemplate((destination, key, data) -> {
var future = new CompletableFuture<SendResult<String, String>>();
futures.add(future);
submitted.countDown();
if (futures.size() > 10) future.complete(null);
return future;
});
var relay = windowRelay(fake, 10);
try (var executor = Executors.newSingleThreadExecutor()) {
var running = executor.submit(relay::relay);
try {
assertThat(submitted.await(8, TimeUnit.SECONDS)).isTrue();
relay.relay(); // A manual overlapping invocation must not create another window.
assertThat(futures).hasSize(10);
assertThat(outboxCount("PROCESSING", 1)).isEqualTo(10);
assertThat(outboxCount("PENDING", 0)).isEqualTo(1);
assertThat(outboxCount("PUBLISHED", 1)).isZero();
} finally {
futures.forEach(f -> f.complete(null));
}
running.get(8, TimeUnit.SECONDS);
}
assertThat(futures).hasSize(11);
assertThat(outboxCount("PUBLISHED", 1)).isEqualTo(11);
assertThat(probe().attempts.get()).isZero(); // Synthetic ACKs, not actual broker delivery.
}
@Test
void submissionWindowDrainsOutOfOrderAcksAfterPartialFailureWithoutRefilling() throws Exception {
for (int i = 0; i < 4; i++) post();
var submitted = new CountDownLatch(3);
var futures = new CopyOnWriteArrayList<CompletableFuture<SendResult<String, String>>>();
var fake = windowTemplate((destination, key, data) -> {
var future = new CompletableFuture<SendResult<String, String>>();
futures.add(future);
submitted.countDown();
return future;
});
try (var executor = Executors.newSingleThreadExecutor()) {
var running = executor.submit(windowRelay(fake, 3)::relay);
try {
assertThat(submitted.await(8, TimeUnit.SECONDS)).isTrue();
futures.get(2).complete(null);
assertThat(outboxCount("PUBLISHED", 1)).isZero();
futures.get(0).completeExceptionally(new IllegalStateException("synthetic broker failure"));
futures.get(1).complete(null);
running.get(8, TimeUnit.SECONDS);
} finally {
futures.forEach(f -> f.complete(null));
}
}
assertThat(futures).hasSize(3);
assertThat(outboxCount("PUBLISHED", 1)).isEqualTo(2);
assertThat(outboxCount("PENDING", 1)).isEqualTo(1);
assertThat(outboxCount("PENDING", 0)).isEqualTo(1);
}
@Test
void submissionWindowDrainsEarlierSendsWhenSendThrowsSynchronously() throws Exception {
for (int i = 0; i < 4; i++) post();
var submitted = new CountDownLatch(3);
var sends = new AtomicInteger();
var futures = new CopyOnWriteArrayList<CompletableFuture<SendResult<String, String>>>();
var fake = windowTemplate((destination, key, data) -> {
int number = sends.incrementAndGet();
if (number == 3) {
submitted.countDown();
throw new IllegalStateException("synthetic send rejection");
}
var future = new CompletableFuture<SendResult<String, String>>();
futures.add(future);
submitted.countDown();
return future;
});
try (var executor = Executors.newSingleThreadExecutor()) {
var running = executor.submit(windowRelay(fake, 3)::relay);
try {
assertThat(submitted.await(8, TimeUnit.SECONDS)).isTrue();
} finally {
futures.forEach(f -> f.complete(null));
}
running.get(8, TimeUnit.SECONDS);
}
assertThat(sends.get()).isEqualTo(3);
assertThat(outboxCount("PUBLISHED", 1)).isEqualTo(2);
assertThat(outboxCount("PENDING", 1)).isEqualTo(1);
assertThat(outboxCount("PENDING", 0)).isEqualTo(1);
}
@Test
void submissionWindowUsesOneDeadlineAndLateAcksCannotPublishTimedOutLeases() throws Exception {
for (int i = 0; i < 4; i++) post();
var submitted = new CountDownLatch(3);
var futures = new CopyOnWriteArrayList<CompletableFuture<SendResult<String, String>>>();
var fake = windowTemplate((destination, key, data) -> {
var future = new CompletableFuture<SendResult<String, String>>();
futures.add(future);
submitted.countDown();
if (futures.size() > 3) future.complete(null);
return future;
});
// Two missing ACKs share five seconds, rather than waiting five seconds for each.
var relay = new OutboxRelay(app.getBean(OutboxStore.class), fake, app.getBean(AsyncProperties.class), registry(),
app.getBean(dev.jinhyeon.notificationlab.config.TrafficRouting.class),
new dev.jinhyeon.notificationlab.config.RelayProperties(10, 3), Duration.ofSeconds(5));
try (var executor = Executors.newSingleThreadExecutor()) {
var running = executor.submit(relay::relay);
try {
assertThat(submitted.await(8, TimeUnit.SECONDS)).isTrue();
futures.get(2).complete(null);
running.get(8, TimeUnit.SECONDS);
assertThat(outboxCount("PUBLISHED", 1)).isEqualTo(1);
assertThat(outboxCount("PROCESSING", 1)).isEqualTo(2);
assertThat(outboxCount("PENDING", 0)).isEqualTo(1);
assertThat(registry().get("outbox.publish.unconfirmed").counter().count()).isEqualTo(2);
relay.relay();
assertThat(futures).hasSize(3);
assertThat(outboxCount("PENDING", 0)).isEqualTo(1);
} finally {
futures.forEach(f -> f.complete(null));
}
}
assertThat(outboxCount("PROCESSING", 1)).isEqualTo(2);
assertThat(outboxCount("PUBLISHED", 1)).isEqualTo(1);
assertThat(futures).allSatisfy(f -> assertThat(f.isCancelled()).isFalse());
relay.relay(); // Completed late futures free capacity, but are never used as DB ACK callbacks.
assertThat(futures).hasSize(4);
assertThat(outboxCount("PUBLISHED", 1)).isEqualTo(2);
assertThat(outboxCount("PROCESSING", 1)).isEqualTo(2);
}
@Test
void stoppingSubmissionWindowDrainsSubmittedAcksAndLeavesUnclaimedRows() throws Exception {
for (int i = 0; i < 5; i++) post();
var submitted = new CountDownLatch(3);
var futures = new CopyOnWriteArrayList<CompletableFuture<SendResult<String, String>>>();
var fake = windowTemplate((destination, key, data) -> {
var future = new CompletableFuture<SendResult<String, String>>();
futures.add(future);
submitted.countDown();
return future;
});
var relay = windowRelay(fake, 3);
try (var executor = Executors.newSingleThreadExecutor()) {
var running = executor.submit(relay::relay);
try {
assertThat(submitted.await(8, TimeUnit.SECONDS)).isTrue();
relay.stopClaiming();
} finally {
futures.forEach(f -> f.complete(null));
}
running.get(8, TimeUnit.SECONDS);
}
relay.relay();
assertThat(futures).hasSize(3);
assertThat(outboxCount("PUBLISHED", 1)).isEqualTo(3);
assertThat(outboxCount("PENDING", 0)).isEqualTo(2);
}
@Test
void interruptedSubmissionWindowPreservesLeasesAndInterruptFlag() throws Exception {
for (int i = 0; i < 4; i++) post();
var submitted = new CountDownLatch(3);
var thread = new AtomicReference<Thread>();
var futures = new CopyOnWriteArrayList<CompletableFuture<SendResult<String, String>>>();
var fake = windowTemplate((destination, key, data) -> {
var future = new CompletableFuture<SendResult<String, String>>();
futures.add(future);
submitted.countDown();
return future;
});
var relay = windowRelay(fake, 3);
try (var executor = Executors.newSingleThreadExecutor()) {
var running = executor.submit(() -> {
thread.set(Thread.currentThread());
relay.relay();
return Thread.currentThread().isInterrupted();
});
try {
assertThat(submitted.await(8, TimeUnit.SECONDS)).isTrue();
thread.get().interrupt();
assertThat(running.get(8, TimeUnit.SECONDS)).isTrue();
relay.relay();
assertThat(futures).hasSize(3);
assertThat(outboxCount("PENDING", 0)).isEqualTo(1);
} finally {
futures.forEach(f -> f.complete(null));
}
}
assertThat(outboxCount("PROCESSING", 1)).isEqualTo(3);
assertThat(outboxCount("PUBLISHED", 1)).isZero();
assertThat(outboxCount("PENDING", 0)).isEqualTo(1);
}
@Test
void submissionWindowFencesBothAckAndFailureAfterLeaseReclaim() throws Exception {
for (int i = 0; i < 3; i++) post();
var submitted = new CountDownLatch(3);
var keys = new CopyOnWriteArrayList<String>();
var futures = new CopyOnWriteArrayList<CompletableFuture<SendResult<String, String>>>();
var fake = windowTemplate((destination, key, data) -> {
keys.add(key);
var future = new CompletableFuture<SendResult<String, String>>();
futures.add(future);
submitted.countDown();
return future;
});
var store = app.getBean(OutboxStore.class);
var replacements = new java.util.ArrayList<OutboxStore.Claim>();
try (var executor = Executors.newSingleThreadExecutor()) {
var running = executor.submit(windowRelay(fake, 3)::relay);
try {
assertThat(submitted.await(8, TimeUnit.SECONDS)).isTrue();
for (int i = 0; i < 2; i++) {
jdbc().update("UPDATE outbox_event SET available_at=TIMESTAMPADD(SECOND,-1,UTC_TIMESTAMP(6)) WHERE notification_id=?", keys.get(i));
replacements.add(store.claim(10).orElseThrow());
}
futures.get(0).complete(null);
futures.get(1).completeExceptionally(new IllegalStateException("synthetic late failure"));
futures.get(2).complete(null);
running.get(8, TimeUnit.SECONDS);
} finally {
futures.forEach(f -> f.complete(null));
}
}
assertThat(outboxCount("PROCESSING", 2)).isEqualTo(2);
assertThat(outboxCount("PUBLISHED", 1)).isEqualTo(1);
for (var claim : replacements) {
assertThat(jdbc().queryForObject("SELECT lease_token FROM outbox_event WHERE event_id=?", String.class, claim.eventId())).isEqualTo(claim.token());
}
assertThat(registry().get("outbox.published").counter().count()).isEqualTo(1);
}
@Test
void submissionWindowRecoversRealBrokerDuplicatesAfterPublishedCommitFailure() throws Exception {
for (int i = 0; i < 3; i++) post();
String rejected = jdbc().queryForObject("SELECT event_id FROM outbox_event ORDER BY event_id LIMIT 1", String.class);
root("CREATE TRIGGER reject_window_publish BEFORE UPDATE ON outbox_event FOR EACH ROW "
+ "BEGIN IF NEW.status = 'PUBLISHED' AND NEW.event_id = '" + rejected
+ "' THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'synthetic commit failure'; END IF; END");
try {
windowRelay(kafka(), 3).relay();
assertThat(recordsOn(topic, 3)).hasSize(3);
assertThat(outboxCount("PROCESSING", 1)).isEqualTo(3);
assertThat(outboxCount("PUBLISHED", 1)).isZero();
} finally {
root("DROP TRIGGER reject_window_publish");
}
expireOutbox();
windowRelay(kafka(), 3).relay();
var copies = recordsOn(topic, 6);
assertThat(copies).hasSize(6);
assertThat(copies.stream().collect(java.util.stream.Collectors.groupingBy(r -> r.value(), java.util.stream.Collectors.counting())).values()).containsOnly(2L);
assertThat(outboxCount("PUBLISHED", 2)).isEqualTo(3);
startWorker();
await().atMost(Duration.ofSeconds(20)).untilAsserted(() -> {
assertThat(probe().attempts.get()).isEqualTo(3);
assertThat(jdbc().queryForObject("SELECT COUNT(*) FROM notification WHERE status='PROVIDER_ACCEPTED'", Integer.class)).isEqualTo(3);
assertThat(count("delivery_attempt")).isEqualTo(3);
});
awaitCommitted(6);
}
private int outboxCount(String state, int attempts) {
return jdbc().queryForObject("SELECT COUNT(*) FROM outbox_event WHERE status=? AND attempt_count=?", Integer.class, state, attempts);
}
@Test
void submissionWindowRetainsTheFiftyClaimRunLimitAndFlushesTheLastPartialWindow() throws Exception {
for (int i = 0; i < 51; i++) post();
var sends = new AtomicInteger();
var fake = windowTemplate((destination, key, data) -> {
sends.incrementAndGet();
return CompletableFuture.completedFuture(null);
});
windowRelay(fake, 3).relay();
assertThat(sends.get()).isEqualTo(50);
assertThat(outboxCount("PUBLISHED", 1)).isEqualTo(50);
assertThat(outboxCount("PENDING", 0)).isEqualTo(1);
}
@Test
void submissionWindowDrainsSubmittedAcksEvenWhenTheNextClaimFails() throws Exception {
for (int i = 0; i < 3; i++) post();
var delegate = app.getBean(OutboxStore.class);
var claims = new AtomicInteger();
var broken = new OutboxStore(null, null) {
@Override
public java.util.Optional<Claim> claim(int maxAttempts) {
if (claims.incrementAndGet() == 3) throw new IllegalStateException("synthetic claim failure");
return delegate.claim(maxAttempts);
}
@Override
public int published(List<Claim> batch) { return delegate.published(batch); }
};
var submitted = new CountDownLatch(2);
var futures = new CopyOnWriteArrayList<CompletableFuture<SendResult<String, String>>>();
var fake = windowTemplate((destination, key, data) -> {
var future = new CompletableFuture<SendResult<String, String>>();
futures.add(future);
submitted.countDown();
return future;
});
var relay = new OutboxRelay(broken, fake, app.getBean(AsyncProperties.class), registry(),
app.getBean(dev.jinhyeon.notificationlab.config.TrafficRouting.class),
new dev.jinhyeon.notificationlab.config.RelayProperties(10, 3));
try (var executor = Executors.newSingleThreadExecutor()) {
var running = executor.submit(relay::relay);
try {
assertThat(submitted.await(8, TimeUnit.SECONDS)).isTrue();
} finally {
futures.forEach(f -> f.complete(null));
}
running.get(8, TimeUnit.SECONDS);
}
assertThat(claims.get()).isEqualTo(3);
assertThat(outboxCount("PUBLISHED", 1)).isEqualTo(2);
assertThat(outboxCount("PENDING", 0)).isEqualTo(1);
}
private OutboxRelay windowRelay(KafkaTemplate<String, String> template, int size) {
return new OutboxRelay(app.getBean(OutboxStore.class), template, app.getBean(AsyncProperties.class), registry(),
app.getBean(dev.jinhyeon.notificationlab.config.TrafficRouting.class), new dev.jinhyeon.notificationlab.config.RelayProperties(10, size));
}
@FunctionalInterface
private interface WindowSend {
CompletableFuture<SendResult<String, String>> send(String destination, String key, String data);
}
private KafkaTemplate<String, String> windowTemplate(WindowSend sender) {
return new KafkaTemplate<String, String>(kafka().getProducerFactory()) {
@Override
public CompletableFuture<SendResult<String, String>> send(String destination, String key, String data) {
assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
return sender.send(destination, key, data);
}
};
}
@Test
void acceptanceCommitsAllRowsBefore202WithoutCallingProvider() throws Exception {
var response = post();
assertThat(response.statusCode()).isEqualTo(202);
assertThat(json(response).path("status").asText()).isEqualTo("QUEUED");
assertThat(count("notification")).isEqualTo(1);
assertThat(count("outbox_event")).isEqualTo(1);
assertThat(count("delivery_task")).isEqualTo(1);
assertThat(probe().attempts.get()).isZero();
assertThat(jdbc().queryForObject("SELECT payload FROM outbox_event", String.class))
.contains("schemaVersion", "notificationId", "eventId")
.doesNotContain("synthetic-user", "가상 데이터", "비동기 테스트");
var get = http.send(HttpRequest.newBuilder(URI.create(base() + response.headers()
.firstValue("Location").orElseThrow())).GET().build(), HttpResponse.BodyHandlers.ofString());
assertThat(json(get)).isEqualTo(json(response));
}
@Test
void outboxInsertFailureRollsBackNotificationAndReturns503() throws Exception {
root("CREATE TRIGGER reject_outbox BEFORE INSERT ON outbox_event FOR EACH ROW "
+ "SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'sensitive-test-data'");
try {
var response = post();
assertThat(response.statusCode()).isEqualTo(503);
assertThat(response.body()).doesNotContain("sensitive-test-data", "synthetic-user");
assertThat(count("notification")).isZero();
assertThat(count("outbox_event")).isZero();
assertThat(count("delivery_task")).isZero();
assertThat(probe().attempts.get()).isZero();
} finally {
root("DROP TRIGGER reject_outbox");
}
}
@Test
void realtimeClaimLeavesCampaignCandidatesClaimableWithStaleStatistics() throws Exception {
var lane = new TrafficProperties(TrafficProperties.Lane.CAMPAIGN, true, 2, 2);
var tx = new TransactionTemplate(app.getBean(PlatformTransactionManager.class));
var campaignSubmissions = new SubmissionService(app.getBean(JdbcNotificationStore.class),
jdbc(), Clock.systemUTC(), app.getBean(DeliveryTaskStore.class), lane);
root("ALTER TABLE outbox_event STATS_AUTO_RECALC=0");
root("ANALYZE TABLE outbox_event");
try {
for (int i = 0; i < 32; i++) tx.executeWithoutResult(status -> campaignSubmissions.accept(
new NotificationRequest("synthetic-campaign", "campaign", "synthetic body"), null));
jdbc().update("UPDATE outbox_event SET available_at=TIMESTAMPADD(SECOND,-5,UTC_TIMESTAMP(6))");
String realtimeId = json(post()).path("notificationId").asText();
var selected = new CountDownLatch(1);
var release = new CountDownLatch(1);
var observedIsolation = new AtomicReference<String>();
var gated = new JdbcTemplate(app.getBean(DataSource.class)) {
@Override
public <T> List<T> query(String sql, RowMapper<T> mapper, Object... args) {
var rows = super.query(sql, mapper, args);
if (sql.contains("FOR UPDATE SKIP LOCKED") && "PENDING".equals(args[1])) {
observedIsolation.set(queryForObject("SELECT @@transaction_isolation", String.class));
selected.countDown();
try { assertThat(release.await(8, TimeUnit.SECONDS)).isTrue(); }
catch (InterruptedException interrupted) {
Thread.currentThread().interrupt(); throw new IllegalStateException("Claim gate interrupted");
}
}
return rows;
}
};
var realtimeStore = transactionProxy(new OutboxStore(gated, app.getBean(TrafficProperties.class)));
var campaignStore = transactionProxy(new OutboxStore(jdbc(), lane));
try (var executor = Executors.newFixedThreadPool(2)) {
var realtime = executor.submit(() -> realtimeStore.claim(10));
try {
assertThat(selected.await(5, TimeUnit.SECONDS)).isTrue();
// Exercise the production annotation through a real Spring transaction interceptor.
var concurrent = executor.submit(() -> campaignStore.claim(10));
assertThat(concurrent.get(3, TimeUnit.SECONDS)).isPresent();
} finally { release.countDown(); }
assertThat(realtime.get(5, TimeUnit.SECONDS).orElseThrow().notificationId()).isEqualTo(realtimeId);
}
assertThat(observedIsolation.get()).isEqualTo("READ-COMMITTED");
assertThat(jdbc().queryForObject("SELECT @@transaction_isolation", String.class)).isEqualTo("REPEATABLE-READ");
assertThat(jdbc().queryForObject("SELECT COUNT(*) FROM outbox_event WHERE status='PROCESSING' AND attempt_count=1 AND lease_token IS NOT NULL", Integer.class)).isEqualTo(2);
assertThat(probe().attempts.get()).isZero();
} finally {
root("ALTER TABLE outbox_event STATS_AUTO_RECALC=DEFAULT");
}
}
private OutboxStore transactionProxy(OutboxStore store) {
var proxy = new ProxyFactory(store);
proxy.setProxyTargetClass(true);
var interceptor = new TransactionInterceptor();
interceptor.setTransactionManager(app.getBean(PlatformTransactionManager.class));
interceptor.setTransactionAttributeSource(new AnnotationTransactionAttributeSource());
interceptor.afterPropertiesSet();
proxy.addAdvice(interceptor);
return (OutboxStore) proxy.getProxy();
}
@Test
void concurrentClaimsAndExpiredLeasesFenceStalePublisher() throws Exception {
post();
var store = app.getBean(OutboxStore.class);
Callable<java.util.Optional<OutboxStore.Claim>> claim = () -> store.claim(10);
OutboxStore.Claim first;
try (var executor = Executors.newFixedThreadPool(2)) {
var results = executor.invokeAll(List.of(claim, claim));
var claims = results.stream().map(f -> {
try { return f.get(); } catch (Exception e) { throw new RuntimeException(e); }
}).flatMap(java.util.Optional::stream).toList();
assertThat(claims).hasSize(1);
first = claims.getFirst();
}
expireOutbox();
var recovered = store.claim(10).orElseThrow();
assertThat(recovered.attempt()).isEqualTo(2);
assertThat(recovered.token()).isNotEqualTo(first.token());
assertThat(store.published(first)).isFalse();
assertThat(store.published(recovered)).isTrue();
}
@Test
void publishedStateWaitsForFutureAndPublishDoesNotHoldDatabaseTransaction() throws Exception {
post();
CompletableFuture<SendResult<String, String>> ack = new CompletableFuture<>();
AtomicInteger calls = new AtomicInteger();
var fake = new KafkaTemplate<String, String>(kafka().getProducerFactory()) {
@Override
public CompletableFuture<SendResult<String, String>> send(String topic, String key, String data) {
assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
calls.incrementAndGet();
return ack;
}
};
try (var executor = Executors.newSingleThreadExecutor()) {
var running = executor.submit(() -> relay(fake).relay());
await().atMost(Duration.ofSeconds(5)).until(() -> calls.get() == 1);
assertThat(outboxStatus()).isEqualTo("PROCESSING");
ack.complete(null);
running.get(5, TimeUnit.SECONDS);
assertThat(outboxStatus()).isEqualTo("PUBLISHED");
}
}
@Test
void failedPublishBacksOffAndStopsAtAttemptLimitIncludingExpiredFinalLease() throws Exception {
post();
var fake = new KafkaTemplate<String, String>(kafka().getProducerFactory()) {
@Override
public CompletableFuture<SendResult<String, String>> send(String topic, String key, String data) {
return CompletableFuture.failedFuture(new IllegalStateException("test outage"));
}
};
relay(fake).relay();
assertThat(outboxStatus()).isEqualTo("PENDING");
assertThat(jdbc().queryForObject("SELECT available_at > UTC_TIMESTAMP(6) FROM outbox_event", Boolean.class)).isTrue();
assertThat(app.getBean(OutboxStore.class).claim(10)).isEmpty();
jdbc().update("UPDATE outbox_event SET attempt_count = 9");
expireOutbox();
relay(fake).relay();
assertThat(outboxStatus()).isEqualTo("FAILED");
assertThat(jdbc().queryForObject("SELECT attempt_count FROM outbox_event", Integer.class)).isEqualTo(10);
// Also recover a process that died during its last attempt.
jdbc().update("UPDATE outbox_event SET status = 'PROCESSING', lease_token = ?", UUID.randomUUID().toString());
expireOutbox();
assertThat(app.getBean(OutboxStore.class).claim(10)).isEmpty();
assertThat(outboxStatus()).isEqualTo("FAILED");
}
@Test
void realKafkaCompletesBeforeCommittingOffsetAndReplayDoesNotCallProviderAgain() throws Exception {
String id = json(post()).path("notificationId").asText();
probe().behavior = request -> {
assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
assertThat(status(id)).isEqualTo("PROCESSING");
return accepted(request);
};
startWorker();
app.getBean(OutboxRelay.class).relay();
await().atMost(Duration.ofSeconds(20)).untilAsserted(() -> assertThat(status(id)).isEqualTo("PROVIDER_ACCEPTED"));
awaitCommitted(1);
assertThat(probe().attempts.get()).isEqualTo(1);
// Simulates a relay replay after ACK but before its durable PUBLISHED update.
String payload = jdbc().queryForObject("SELECT payload FROM outbox_event", String.class);
kafka().send(topic, id, payload).get(10, TimeUnit.SECONDS);
awaitCommitted(2);
assertThat(probe().attempts.get()).isEqualTo(1);
app.getBean(PipelineMetrics.class).refresh();
assertThat(registry().get("outbox.unpublished").gauge().value()).isZero();
assertThat(registry().get("notification.consumer.lag").gauge().value()).isZero();
}
@Test
void completionFailureStopsConsumerWithoutSkippingOffsetAndCanRecoverExpiredLease() throws Exception {
String id = json(post()).path("notificationId").asText();
root("CREATE TRIGGER reject_completion BEFORE UPDATE ON notification FOR EACH ROW "
+ "BEGIN IF NEW.completed_at IS NOT NULL THEN SIGNAL SQLSTATE '45000' "
+ "SET MESSAGE_TEXT = 'sensitive-test-data'; END IF; END");
try {
startWorker();
app.getBean(OutboxRelay.class).relay();
await().atMost(Duration.ofSeconds(20)).until(() -> !container().isRunning());
assertThat(status(id)).isEqualTo("PROCESSING");
assertThat(committedTotal()).isZero();
} finally {
root("DROP TRIGGER reject_completion");
}
jdbc().update("UPDATE notification SET worker_lease_until = TIMESTAMPADD(SECOND, -1, UTC_TIMESTAMP(6))");
startWorker();
await().atMost(Duration.ofSeconds(20)).untilAsserted(() -> assertThat(status(id)).isEqualTo("PROVIDER_ACCEPTED"));
awaitCommitted(1);
assertThat(probe().attempts.get()).isEqualTo(2); // Ambiguous provider outcome can be attempted twice.
}
@Test
void staleWorkerCannotOverwriteNewLeaseAndActiveLeaseIsNotAcknowledged() throws Exception {
UUID id = UUID.fromString(json(post()).path("notificationId").asText());
UUID eventId = UUID.fromString(jdbc().queryForObject("SELECT event_id FROM outbox_event", String.class));
var store = app.getBean(WorkerStore.class);
var first = store.claim(id, eventId, "old-worker").orElseThrow();
assertThatThrownBy(() -> store.claim(id, eventId, "concurrent-worker")).isInstanceOf(IllegalStateException.class);
jdbc().update("UPDATE notification SET worker_lease_until = TIMESTAMPADD(SECOND, -1, UTC_TIMESTAMP(6))");
var second = store.claim(id, eventId, "new-worker").orElseThrow();
var result = first.notification().completed(NotificationStatus.PROVIDER_ACCEPTED, "mock-result", null, java.time.Instant.now());
assertThatThrownBy(() -> store.complete(result, "old-worker")).isInstanceOf(IllegalStateException.class);
store.complete(second.notification().completed(NotificationStatus.PROVIDER_ACCEPTED, "new-result", null,
java.time.Instant.now()), "new-worker");
assertThat(store.claim(id, eventId, "replay")).isEmpty();
}
@Test
void permanentProviderFailureIsDurableTerminalResultBeforeOffsetCommit() throws Exception {
probe().behavior = request -> new PushResult(PushResult.Outcome.PERMANENT_FAILURE, null, "MOCK_INVALID_TARGET");
String id = json(post()).path("notificationId").asText();
startWorker();
app.getBean(OutboxRelay.class).relay();
awaitCommitted(1);
assertThat(status(id)).isEqualTo("PERMANENT_FAILURE");
assertThat(probe().attempts.get()).isEqualTo(1);
}
@Test
void unsupportedEventStopsWithoutCommittingOffset() throws Exception {
startWorker();
kafka().send(topic, "invalid-key", "{\"schemaVersion\":99}").get(10, TimeUnit.SECONDS);
await().atMost(Duration.ofSeconds(20)).until(() -> !container().isRunning());
assertThat(committedTotal()).isZero();
assertThat(probe().attempts.get()).isZero();
}
@Test
void sameKeyReusesDecodedPayloadDespiteJsonFormattingDifferences() throws Exception {
var first = post(PAYLOAD, "request-1");
var again = post("""
{"body":"가상 데이터","title":"비동기 테스트","recipientId":"synthetic-user"}
""", "request-1");
assertThat(first.statusCode()).isEqualTo(202);
assertThat(again.statusCode()).isEqualTo(200);
assertThat(json(again)).isEqualTo(json(first));
assertThat(again.headers().firstValue("Location")).isEqualTo(first.headers().firstValue("Location"));
assertThat(count("notification")).isEqualTo(1);
assertThat(count("outbox_event")).isEqualTo(1);
assertThat(count("delivery_task")).isEqualTo(1);
assertThat(probe().attempts.get()).isZero();
}
@Test
void sameKeyRejectsAnyChangedFieldWithoutLeakingPayloadOrKey() throws Exception {
post(PAYLOAD, "private-key");
for (String different : List.of(PAYLOAD.replace("synthetic-user", "Synthetic-user"),
PAYLOAD.replace("비동기 테스트", "비동기 테스트 "), PAYLOAD.replace("가상 데이터", "다른 내용"))) {
var conflict = post(different, "private-key");
assertThat(conflict.statusCode()).isEqualTo(409);
assertThat(conflict.body()).doesNotContain("private-key", "synthetic-user", "다른 내용", "가상 데이터");
}
assertThat(count("notification")).isEqualTo(1);
assertThat(count("outbox_event")).isEqualTo(1);
assertThat(count("delivery_task")).isEqualTo(1);
}
@Test
void concurrentSameKeyCreatesExactlyOneNotificationAndOutbox() throws Exception {
CountDownLatch ready = new CountDownLatch(8);
Callable<HttpResponse<String>> send = () -> {
ready.countDown();
assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue();
return post(PAYLOAD, "concurrent-key");
};
try (var executor = Executors.newFixedThreadPool(8)) {
var pending = executor.invokeAll(java.util.Collections.nCopies(8, send));
var responses = new java.util.ArrayList<HttpResponse<String>>();
for (var future : pending) responses.add(future.get());
assertThat(responses.stream().map(HttpResponse::statusCode).toList())
.containsOnly(200, 202).filteredOn(code -> code == 202).hasSize(1);
var ids = new java.util.HashSet<String>();
for (var response : responses) ids.add(json(response).path("notificationId").asText());
assertThat(ids).hasSize(1);
}
assertThat(count("notification")).isEqualTo(1);
assertThat(count("outbox_event")).isEqualTo(1);
assertThat(count("delivery_task")).isEqualTo(1);
}
@Test
void concurrentDifferentPayloadsChooseOneWinnerAndReturnConflicts() throws Exception {
CountDownLatch ready = new CountDownLatch(8);
var tasks = new java.util.ArrayList<Callable<HttpResponse<String>>>();
for (int i = 0; i < 8; i++) {
String payload = i % 2 == 0 ? PAYLOAD : PAYLOAD.replace("가상 데이터", "다른 내용");
tasks.add(() -> {
ready.countDown();
assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue();
return post(payload, "mixed-key");
});
}
try (var executor = Executors.newFixedThreadPool(8)) {
var responses = executor.invokeAll(tasks);
var codes = new java.util.ArrayList<Integer>();
for (var response : responses) codes.add(response.get().statusCode());
assertThat(codes).containsExactlyInAnyOrder(202, 200, 200, 200, 409, 409, 409, 409);
}
assertThat(count("notification")).isEqualTo(1);
assertThat(count("outbox_event")).isEqualTo(1);
assertThat(count("delivery_task")).isEqualTo(1);
}
@Test
void unrelatedDuplicateFailureRollsBackKeyAndAllowsSafeRetry() throws Exception {
root("CREATE TRIGGER reject_keyed_outbox BEFORE INSERT ON outbox_event FOR EACH ROW "
+ "SIGNAL SQLSTATE '23000' SET MYSQL_ERRNO = 1062, MESSAGE_TEXT = 'sensitive-outbox-error'");
try {
var failed = post(PAYLOAD, "rollback-key");
assertThat(failed.statusCode()).isEqualTo(503);
assertThat(failed.body()).doesNotContain("sensitive-outbox-error", "rollback-key");
assertThat(count("notification")).isZero();
assertThat(count("outbox_event")).isZero();
assertThat(count("delivery_task")).isZero();
} finally {
root("DROP TRIGGER reject_keyed_outbox");
}
assertThat(post(PAYLOAD, "rollback-key").statusCode()).isEqualTo(202);
assertThat(post(PAYLOAD, "rollback-key").statusCode()).isEqualTo(200);
assertThat(count("notification")).isEqualTo(1);
assertThat(count("outbox_event")).isEqualTo(1);
assertThat(count("delivery_task")).isEqualTo(1);
}
@Test
void replayAfterCompletionAndApplicationRestartReturnsCurrentResultWithoutResending() throws Exception {
var first = post(PAYLOAD, "persistent-key");
String id = json(first).path("notificationId").asText();
startWorker();
app.getBean(OutboxRelay.class).relay();
awaitCommitted(1);
assertThat(status(id)).isEqualTo("PROVIDER_ACCEPTED");
app.close();
startApplication(false);
var replay = post(PAYLOAD, "persistent-key");
assertThat(replay.statusCode()).isEqualTo(200);
assertThat(json(replay).path("notificationId").asText()).isEqualTo(id);
assertThat(json(replay).path("status").asText()).isEqualTo("PROVIDER_ACCEPTED");
assertThat(probe().attempts.get()).isZero();
assertThat(count("notification")).isEqualTo(1);
assertThat(count("outbox_event")).isEqualTo(1);
assertThat(count("delivery_task")).isEqualTo(1);
assertThat(committedTotal()).isEqualTo(1);
}
@Test
void keylessRequestsStayIndependentAndKeysAreCaseSensitiveWithLengthBoundary() throws Exception {
assertThat(post().statusCode()).isEqualTo(202);
assertThat(post().statusCode()).isEqualTo(202);
assertThat(post(PAYLOAD, "Key").statusCode()).isEqualTo(202);
assertThat(post(PAYLOAD, "key").statusCode()).isEqualTo(202);
assertThat(post(PAYLOAD, "x".repeat(128)).statusCode()).isEqualTo(202);
assertThat(post(PAYLOAD, "x".repeat(128)).statusCode()).isEqualTo(200);
assertThat(count("notification")).isEqualTo(5);
assertThat(count("outbox_event")).isEqualTo(5);
}
@Test
void invalidAndRepeatedKeyHeadersDoNotCreateRows() throws Exception {
for (String key : List.of("", "has space", "has,comma", "x".repeat(129), "quoted\"key")) {
assertThat(post(PAYLOAD, key).statusCode()).isEqualTo(400);
}
assertThat(post(PAYLOAD, "same", "same").statusCode()).isEqualTo(400);
assertThat(post(PAYLOAD, "first", "second").statusCode()).isEqualTo(400);
assertThat(count("notification")).isZero();
assertThat(count("outbox_event")).isZero();
assertThat(count("delivery_task")).isZero();
}
@Test
void invalidPayloadDoesNotReserveKey() throws Exception {
assertThat(post(PAYLOAD.replace("synthetic-user", ""), "validation-key").statusCode()).isEqualTo(400);
assertThat(post(PAYLOAD, "validation-key").statusCode()).isEqualTo(202);
assertThat(count("notification")).isEqualTo(1);
}
@Test
void replayReadsCommittedWinnerOutsideCallersOldSnapshot() {
var tx = new TransactionTemplate(app.getBean(PlatformTransactionManager.class));
tx.executeWithoutResult(status -> {
assertThat(count("notification")).isZero(); // Establish an older repeatable-read snapshot.
var submissions = app.getBean(IdempotentSubmissionService.class);
var request = new NotificationRequest("synthetic", "title", "body");
var first = submissions.submit(request, "transaction-key");
var replay = submissions.submit(request, "transaction-key");
assertThat(first.replayed()).isFalse();
assertThat(replay.replayed()).isTrue();
assertThat(replay.notification()).isEqualTo(first.notification());
status.setRollbackOnly();
});
assertThat(count("notification")).isEqualTo(1);
assertThat(count("outbox_event")).isEqualTo(1);
assertThat(count("delivery_task")).isEqualTo(1);
}
@Test
void taskIdentityIsUniqueStableAndHistorySurvivesCompletedReplay() throws Exception {
String id = json(post(PAYLOAD, "task-key")).path("notificationId").asText();
JsonNode initial = delivery(id);