refactor: 각 어댑터터별 리펙토링 진행
This commit is contained in:
+78
-25
@@ -182,23 +182,45 @@ public final class DefaultMessagePublisher implements MessagePublisher {
|
||||
return rejected("PUBLISH_PREPARATION_FAILED", sanitized(beforeTheWire), startedAt);
|
||||
}
|
||||
|
||||
Duration remaining = remainingBudget(options.timeout(), startedAt);
|
||||
if (remaining.isZero() || remaining.isNegative()) {
|
||||
// The budget was spent resolving and encoding, so nothing has been transmitted and the
|
||||
// outcome is still definite. Sending anyway would start a message the caller has already
|
||||
// stopped waiting for.
|
||||
return rejected(
|
||||
"PUBLISH_DEADLINE_EXCEEDED",
|
||||
"the "
|
||||
+ options.timeout().toMillis()
|
||||
+ "ms publish deadline passed before the message reached the transport",
|
||||
startedAt);
|
||||
}
|
||||
|
||||
admission.admit(destination.name().value(), encoded.payload().bytes().length);
|
||||
MessagingRuntimeLease lease = null;
|
||||
try {
|
||||
lease = runtimes.acquire(profile.broker());
|
||||
MessagingRuntimeLease held = lease;
|
||||
return transport
|
||||
.publish(new TransportPublishRequest(profile, encoded, options))
|
||||
return withDeadline(
|
||||
transport.publish(new TransportPublishRequest(profile, encoded, options)), remaining)
|
||||
.<PublishResult>handle(
|
||||
(result, failure) -> {
|
||||
// One release per acquisition, whatever happened. A permit that leaks on the
|
||||
// failure path is a limiter that shrinks by one per failure until it accepts
|
||||
// nothing.
|
||||
held.close();
|
||||
admission.complete();
|
||||
admission.complete(destination.name().value());
|
||||
if (failure != null) {
|
||||
// The request was on the wire when this failed, so the broker may hold it.
|
||||
PublishResult ambiguous = ambiguousResult(sanitized(failure), startedAt);
|
||||
PublishResult ambiguous =
|
||||
isDeadline(failure)
|
||||
? ambiguousResult(
|
||||
"PUBLISH_DEADLINE_EXCEEDED",
|
||||
"no broker outcome within the "
|
||||
+ options.timeout().toMillis()
|
||||
+ "ms publish deadline",
|
||||
startedAt)
|
||||
: ambiguousResult(
|
||||
"PUBLISH_OUTCOME_UNKNOWN", sanitized(failure), startedAt);
|
||||
observe(profile, ambiguous, startedAt);
|
||||
return ambiguous;
|
||||
}
|
||||
@@ -209,7 +231,7 @@ public final class DefaultMessagePublisher implements MessagePublisher {
|
||||
if (lease != null) {
|
||||
lease.close();
|
||||
}
|
||||
admission.complete();
|
||||
admission.complete(destination.name().value());
|
||||
return rejected("PUBLISH_RUNTIME_UNAVAILABLE", sanitized(beforeTheSend), startedAt);
|
||||
}
|
||||
}
|
||||
@@ -217,22 +239,13 @@ public final class DefaultMessagePublisher implements MessagePublisher {
|
||||
/**
|
||||
* Refuses options the destination cannot honour, before anything is encoded or sent.
|
||||
*
|
||||
* <p>The transports read {@code request.options()} for nothing: the timeout, the confirmation
|
||||
* requirement, the deduplication request and the broker hints were all accepted and ignored. A
|
||||
* caller asking for broker-side deduplication got a publish with no deduplication and no error,
|
||||
* and then skipped the idempotency it would otherwise have written — which is exactly the case
|
||||
* {@code PublishDeduplication}'s own javadoc says must be a startup failure rather than a silent
|
||||
* no-op.
|
||||
* <p>The transports accept {@code request.options()} and read nothing from it, so an option this
|
||||
* destination cannot honour has to be refused here or it is honoured nowhere. A caller asking for
|
||||
* broker-side deduplication got a publish with no deduplication and no error, and then skipped
|
||||
* the idempotency it would otherwise have written — which is exactly the case {@code
|
||||
* PublishDeduplication}'s own javadoc says must be a startup failure rather than a silent no-op.
|
||||
*/
|
||||
private void requireSupportedOptions(DestinationProfile profile, PublishOptions options) {
|
||||
if (!options.isM1Compatible()) {
|
||||
// isM1Compatible existed and nothing called it, so an ordinary caller could attach M3 broker
|
||||
// hints to an M1 publish and have them dropped.
|
||||
throw new dev.caskeleton.messaging.api.error.MessagingConfigurationException(
|
||||
"PUBLISH_BROKER_HINTS_UNSUPPORTED",
|
||||
"broker hints are an M3 surface and this publish path does not forward them; passing"
|
||||
+ " them here would drop them silently");
|
||||
}
|
||||
if (options.deduplication().isPresent()
|
||||
&& !transport.capabilities(profile.name()).capabilities().deduplicatedPublish()) {
|
||||
throw new dev.caskeleton.messaging.api.error.MessagingConfigurationException(
|
||||
@@ -276,7 +289,7 @@ public final class DefaultMessagePublisher implements MessagePublisher {
|
||||
FailureCategory.CONFIGURATION, code, false, reason, Optional.empty()))));
|
||||
}
|
||||
|
||||
private PublishResult ambiguousResult(String reason, long startedAt) {
|
||||
private PublishResult ambiguousResult(String code, String reason, long startedAt) {
|
||||
return new PublishResult(
|
||||
PublishCompletion.AMBIGUOUS,
|
||||
PublishEvidence.ambiguous(),
|
||||
@@ -286,11 +299,51 @@ public final class DefaultMessagePublisher implements MessagePublisher {
|
||||
elapsedSince(startedAt),
|
||||
Optional.of(
|
||||
new FailureDescriptor(
|
||||
FailureCategory.AMBIGUOUS,
|
||||
"PUBLISH_OUTCOME_UNKNOWN",
|
||||
true,
|
||||
reason,
|
||||
Optional.empty())));
|
||||
FailureCategory.AMBIGUOUS, code, true, reason, Optional.empty())));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns what is left of the caller's deadline.
|
||||
*
|
||||
* <p>Measured from the call, not from the send. {@code PublishOptions.timeout()} is documented as
|
||||
* the publish operation's deadline, so a slow destination lookup or a large encode spends the
|
||||
* same budget the broker wait does; timing only the transport call would let the total exceed the
|
||||
* deadline by however long preparation took.
|
||||
*/
|
||||
private Duration remainingBudget(Duration timeout, long startedAt) {
|
||||
return timeout.minus(elapsedSince(startedAt));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounds the wait for a broker outcome.
|
||||
*
|
||||
* <p>The transports accepted {@code request.options()} and read nothing from it, so the deadline
|
||||
* belonged to whatever the broker client happened to be configured with — a Rabbit publish
|
||||
* waiting on a confirm that never arrives had no deadline at all, and the caller's thread was
|
||||
* pinned to a stage that could not complete.
|
||||
*
|
||||
* <p>The bound is applied to a copy so that expiry never completes the transport's own stage: the
|
||||
* adapter still owns its in-flight publish and its own bookkeeping. The permit and the runtime
|
||||
* lease are released when the copy completes, which is deliberate — holding them until a stalled
|
||||
* broker answers is how a rotation waits forever on a generation nobody is using.
|
||||
*/
|
||||
private static CompletableFuture<dev.caskeleton.messaging.transport.TransportPublishResult>
|
||||
withDeadline(
|
||||
CompletionStage<dev.caskeleton.messaging.transport.TransportPublishResult> inFlight,
|
||||
Duration remaining) {
|
||||
return inFlight
|
||||
.toCompletableFuture()
|
||||
.copy()
|
||||
.orTimeout(remaining.toMillis(), java.util.concurrent.TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
/** Reports whether a stage failed because the deadline passed rather than because of a broker. */
|
||||
private static boolean isDeadline(Throwable failure) {
|
||||
Throwable cause =
|
||||
failure instanceof java.util.concurrent.CompletionException && failure.getCause() != null
|
||||
? failure.getCause()
|
||||
: failure;
|
||||
return cause instanceof java.util.concurrent.TimeoutException;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+78
-22
@@ -162,6 +162,66 @@ class DefaultMessagePublisherTest {
|
||||
assertThat(admission.inFlight()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a broker that never answers is ambiguous at the caller's deadline")
|
||||
void aStalledBrokerIsAmbiguousAtTheDeadline() {
|
||||
transport.stall();
|
||||
|
||||
CompletableFuture<PublishResult> pending =
|
||||
publisher(allowOrders())
|
||||
.publish(
|
||||
new MessageDestination<>(ORDERS, new MessageType("order.created"), String.class),
|
||||
envelope(),
|
||||
withTimeout(Duration.ofMillis(120)))
|
||||
.toCompletableFuture();
|
||||
|
||||
// Bounded rather than joined: with no deadline of its own this stage never completes, and a
|
||||
// test that waits forever reports a hang instead of the missing deadline.
|
||||
assertThat(pending).succeedsWithin(Duration.ofSeconds(5));
|
||||
PublishResult result = pending.join();
|
||||
|
||||
assertThat(result.completion())
|
||||
.as("the message reached the transport, so the broker may hold it")
|
||||
.isEqualTo(PublishCompletion.AMBIGUOUS);
|
||||
assertThat(result.failure().orElseThrow().code()).isEqualTo("PUBLISH_DEADLINE_EXCEEDED");
|
||||
assertThat(admission.inFlight())
|
||||
.as("a permit held until a stalled broker answers is a permit never returned")
|
||||
.isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a deadline spent before the send rejects instead of publishing")
|
||||
void aDeadlineSpentBeforeTheSendRejects() {
|
||||
// Preparation is inside the deadline, not before it: resolution and encoding spend the same
|
||||
// budget the broker wait does.
|
||||
AtomicInteger reads = new AtomicInteger();
|
||||
DefaultMessagePublisher publisher =
|
||||
new DefaultMessagePublisher(
|
||||
registry(),
|
||||
allowOrders(),
|
||||
new SingleCodecRegistry(),
|
||||
admission,
|
||||
new FixedRuntimeRegistry(transport),
|
||||
transport,
|
||||
() -> Duration.ofSeconds(6L * reads.getAndIncrement()).toNanos());
|
||||
|
||||
PublishResult result =
|
||||
publisher
|
||||
.publish(
|
||||
new MessageDestination<>(ORDERS, new MessageType("order.created"), String.class),
|
||||
envelope(),
|
||||
withTimeout(Duration.ofSeconds(5)))
|
||||
.toCompletableFuture()
|
||||
.join();
|
||||
|
||||
assertThat(result.completion())
|
||||
.as("nothing was transmitted, so the outcome is definite")
|
||||
.isEqualTo(PublishCompletion.REJECTED);
|
||||
assertThat(result.failure().orElseThrow().code()).isEqualTo("PUBLISH_DEADLINE_EXCEEDED");
|
||||
assertThat(transport.published()).isZero();
|
||||
assertThat(admission.inFlight()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("an unavailable runtime releases the permit it took")
|
||||
void anUnavailableRuntimeReleasesThePermit() {
|
||||
@@ -262,8 +322,7 @@ class DefaultMessagePublisherTest {
|
||||
.REPLICATION_OR_PERSISTENCE_ACK,
|
||||
java.util.Optional.of(
|
||||
new dev.caskeleton.messaging.api.publish.PublishDeduplication(
|
||||
"order-1", java.time.Duration.ofMinutes(5))),
|
||||
Map.of()))
|
||||
"order-1", java.time.Duration.ofMinutes(5)))))
|
||||
.toCompletableFuture()
|
||||
.join();
|
||||
|
||||
@@ -273,26 +332,12 @@ class DefaultMessagePublisherTest {
|
||||
assertThat(transport.published()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("M3 broker hints are refused on the M1 path")
|
||||
void brokerHintsAreRefused() {
|
||||
PublishResult result =
|
||||
publisher(allowOrders())
|
||||
.publish(
|
||||
new MessageDestination<>(ORDERS, new MessageType("order.created"), String.class),
|
||||
envelope(),
|
||||
new PublishOptions(
|
||||
java.time.Duration.ofSeconds(5),
|
||||
dev.caskeleton.messaging.api.destination.ConfirmationRequirement
|
||||
.REPLICATION_OR_PERSISTENCE_ACK,
|
||||
java.util.Optional.empty(),
|
||||
Map.of("linger.ms", "50")))
|
||||
.toCompletableFuture()
|
||||
.join();
|
||||
|
||||
assertThat(result.completion())
|
||||
.as("isM1Compatible existed and nothing ever called it")
|
||||
.isEqualTo(PublishCompletion.REJECTED);
|
||||
private static PublishOptions withTimeout(Duration timeout) {
|
||||
return new PublishOptions(
|
||||
timeout,
|
||||
dev.caskeleton.messaging.api.destination.ConfirmationRequirement
|
||||
.REPLICATION_OR_PERSISTENCE_ACK,
|
||||
Optional.empty());
|
||||
}
|
||||
|
||||
private static DestinationAccessPolicy allowOrders() {
|
||||
@@ -384,15 +429,26 @@ class DefaultMessagePublisherTest {
|
||||
|
||||
private RuntimeException failure;
|
||||
|
||||
private boolean stalled;
|
||||
|
||||
private void failWith(RuntimeException failure) {
|
||||
this.failure = failure;
|
||||
}
|
||||
|
||||
/** A broker that took the message and never says what happened to it. */
|
||||
private void stall() {
|
||||
this.stalled = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletionStage<TransportPublishResult> publish(TransportPublishRequest request) {
|
||||
if (failure != null) {
|
||||
return CompletableFuture.failedFuture(failure);
|
||||
}
|
||||
if (stalled) {
|
||||
published.incrementAndGet();
|
||||
return new CompletableFuture<>();
|
||||
}
|
||||
published.incrementAndGet();
|
||||
return CompletableFuture.completedFuture(
|
||||
new TransportPublishResult(
|
||||
|
||||
Reference in New Issue
Block a user