refactor: 각 어댑터터별 리펙토링 진행

This commit is contained in:
DongHyeonka
2026-08-24 18:26:40 +09:00
parent 16e33ce986
commit a261df2a2b
100 changed files with 7072 additions and 902 deletions
@@ -13,7 +13,6 @@ import dev.caskeleton.messaging.api.TraceContext;
import dev.caskeleton.messaging.api.delivery.DeliveryMetadata;
import dev.caskeleton.messaging.api.destination.DestinationName;
import dev.caskeleton.messaging.api.error.MessageValidationException;
import dev.caskeleton.messaging.api.header.MessageHeaders;
import dev.caskeleton.messaging.api.header.ReservedHeaders;
import dev.caskeleton.messaging.schema.EncodedMessage;
import java.time.Instant;
@@ -87,12 +86,13 @@ public final class RabbitDeliveryMapper {
contentType,
Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.PARTITION_KEY)),
Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.ORDERING_KEY)),
Optional.<TenantContext>empty(),
Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.TENANT))
.map(TenantContext::new),
new TraceContext(
Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.TRACEPARENT)),
Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.TRACESTATE)),
Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.BAGGAGE))),
MessageHeaders.empty(),
headerMapper.carriedForward(properties),
new EncodedMessage(payload, contentType, Optional.empty()));
}
@@ -1,6 +1,7 @@
package dev.caskeleton.messaging.rabbit;
import dev.caskeleton.messaging.api.MessageEnvelope;
import dev.caskeleton.messaging.api.header.CanonicalEnvelopeHeaders;
import dev.caskeleton.messaging.api.header.HeaderName;
import dev.caskeleton.messaging.api.header.HeaderValue;
import dev.caskeleton.messaging.api.header.MessageHeaders;
@@ -68,6 +69,11 @@ public final class RabbitHeaderMapper {
envelope
.orderingKey()
.ifPresent(value -> setHeader(properties, ReservedHeaders.ORDERING_KEY, value));
// Written for the same reason as on the other broker: an AMQP message carries no ambient
// tenant, so a tenant left off the wire is a tenant the consumed envelope does not have.
envelope
.tenantContext()
.ifPresent(value -> setHeader(properties, ReservedHeaders.TENANT, value.tenantId()));
envelope
.traceContext()
.traceparent()
@@ -81,21 +87,25 @@ public final class RabbitHeaderMapper {
.baggage()
.ifPresent(value -> setHeader(properties, ReservedHeaders.BAGGAGE, value));
// Application headers are written last, so an unchecked one would overwrite the canonical
// The envelope's header map is written last, so an unchecked name would overwrite the canonical
// reserved value the platform just wrote. A forged `msg.id` corrupts another message's inbox
// deduplication, not merely its own delivery.
//
// Only names that restate an envelope field are refused. Retry attempt, failure and redrive
// bookkeeping have no envelope field to be read back from, so refusing them would make every
// retry-queue and dead-letter re-publish fail on the guard meant to protect identity.
envelope
.headers()
.asMap()
.forEach(
(name, value) -> {
if (dev.caskeleton.messaging.api.header.ReservedHeaders.isReserved(name.value())) {
if (CanonicalEnvelopeHeaders.restatesEnvelopeField(name.value())) {
throw new dev.caskeleton.messaging.api.error.MessagingConfigurationException(
"RESERVED_HEADER_FORGED",
"application header '"
"header '"
+ name.value()
+ "' uses the reserved namespace; the canonical value is written by the"
+ " platform and must not be overridable by message content");
+ "' restates a value the envelope already carries; the canonical value is"
+ " written by the platform and must not be overridable by message content");
}
setHeader(properties, name.value(), value.value());
});
@@ -123,6 +133,35 @@ public final class RabbitHeaderMapper {
return MessageHeaders.platform(values);
}
/**
* Reads back the headers a rebuilt envelope keeps.
*
* <p>Everything except the names that were hoisted into envelope fields: the application's own
* headers, which were dropped entirely and so never survived a broker hop, and the platform's
* retry and redrive bookkeeping, whose loss restarted the attempt counter at one on every
* redelivery and left the retry budget capping nothing.
*
* <p>The hoisted names are excluded rather than kept alongside their fields, because a duplicate
* that can drift from the field is how the same message ends up with two different ids depending
* on which one the reader trusts.
*
* @param properties the message properties
* @return the headers to carry on the rebuilt envelope
*/
public MessageHeaders carriedForward(MessageProperties properties) {
Objects.requireNonNull(properties, "properties must not be null");
Map<HeaderName, HeaderValue> values = new LinkedHashMap<>();
properties
.getHeaders()
.forEach(
(name, value) -> {
if (value != null && !CanonicalEnvelopeHeaders.restatesEnvelopeField(name)) {
values.put(new HeaderName(name), new HeaderValue(String.valueOf(value)));
}
});
return MessageHeaders.platform(values);
}
/**
* Reads one header value.
*
@@ -0,0 +1,152 @@
package dev.caskeleton.messaging.rabbit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.messaging.api.ContentType;
import dev.caskeleton.messaging.api.CorrelationId;
import dev.caskeleton.messaging.api.MessageEnvelope;
import dev.caskeleton.messaging.api.MessageId;
import dev.caskeleton.messaging.api.MessageType;
import dev.caskeleton.messaging.api.ProducerId;
import dev.caskeleton.messaging.api.SchemaVersion;
import dev.caskeleton.messaging.api.TraceContext;
import dev.caskeleton.messaging.api.error.MessagingConfigurationException;
import dev.caskeleton.messaging.api.header.HeaderName;
import dev.caskeleton.messaging.api.header.HeaderValue;
import dev.caskeleton.messaging.api.header.MessageHeaders;
import dev.caskeleton.messaging.api.header.ReservedHeaders;
import dev.caskeleton.messaging.schema.EncodedMessage;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
/**
* What an envelope still holds after it has been through RabbitMQ.
*
* <p>The publish and delivery mappers were written against each other's headers but never checked
* as one trip, so the application's own headers were dropped on the way back and the retry
* bookkeeping went with them — an attempt counter that restarts on every hop caps no redeliveries
* at all.
*/
class RabbitEnvelopeRoundTripTest {
private static final Instant NOW = Instant.parse("2026-08-15T10:00:00Z");
private final RabbitHeaderMapper headerMapper = new RabbitHeaderMapper();
private final RabbitDeliveryMapper deliveryMapper = new RabbitDeliveryMapper(headerMapper);
@Test
@DisplayName("an application header survives the trip through the broker")
void anApplicationHeaderSurvivesTheTrip() {
MessageEnvelope<EncodedMessage> published =
envelope(
MessageHeaders.application(
Map.of(new HeaderName("x-source-system"), new HeaderValue("erp"))));
MessageEnvelope<EncodedMessage> delivered = roundTrip(published);
assertThat(delivered.headers().find("x-source-system"))
.map(HeaderValue::value)
.as("a header the producer wrote and the consumer cannot read is a header nobody has")
.hasValue("erp");
}
@Test
@DisplayName("the tenant survives the trip instead of arriving as no tenant at all")
void theTenantSurvivesTheTrip() {
MessageEnvelope<EncodedMessage> published =
envelope(MessageHeaders.empty())
.withTenant(new dev.caskeleton.messaging.api.TenantContext("acme"));
MessageEnvelope<EncodedMessage> delivered = roundTrip(published);
assertThat(delivered.tenantContext())
.as("an AMQP message carries no ambient tenant, so an unwritten tenant is an absent one")
.contains(new dev.caskeleton.messaging.api.TenantContext("acme"));
}
@Test
@DisplayName("the retry attempt survives the trip instead of restarting at one")
void theRetryAttemptSurvivesTheTrip() {
MessageEnvelope<EncodedMessage> delivered = roundTrip(retryStamped(3));
assertThat(delivered.headers().find(ReservedHeaders.RETRY_ATTEMPT))
.map(HeaderValue::value)
.as("an attempt counter that resets on every hop caps nothing")
.hasValue("3");
}
@Test
@DisplayName("a retry-stamped envelope can be published to its retry queue")
void aRetryStampedEnvelopeCanBePublished() {
assertThatCode(() -> headerMapper.toProperties(retryStamped(2)))
.as("the platform's own bookkeeping is not message content forging an identity")
.doesNotThrowAnyException();
}
@Test
@DisplayName("a header restating the message id is still refused")
void aForgedMessageIdIsStillRefused() {
MessageEnvelope<EncodedMessage> forged =
envelope(
MessageHeaders.platform(
Map.of(new HeaderName(ReservedHeaders.MESSAGE_ID), new HeaderValue("forged"))));
assertThatThrownBy(() -> headerMapper.toProperties(forged))
.isInstanceOf(MessagingConfigurationException.class);
}
@Test
@DisplayName("identity is read from its field, not duplicated into the header map")
void identityIsNotDuplicatedIntoTheHeaderMap() {
MessageEnvelope<EncodedMessage> delivered = roundTrip(envelope(MessageHeaders.empty()));
assertThat(delivered.headers().find(ReservedHeaders.MESSAGE_ID))
.as("a copy that can drift from the field gives the same message two identities")
.isEmpty();
}
private MessageEnvelope<EncodedMessage> roundTrip(MessageEnvelope<EncodedMessage> published) {
MessageProperties properties = headerMapper.toProperties(published);
return deliveryMapper.toEnvelope(new Message(published.payload().bytes(), properties));
}
private static MessageEnvelope<EncodedMessage> retryStamped(int attempt) {
Map<HeaderName, HeaderValue> headers = new LinkedHashMap<>();
headers.put(
new HeaderName(ReservedHeaders.RETRY_ATTEMPT), new HeaderValue(Integer.toString(attempt)));
headers.put(new HeaderName(ReservedHeaders.LAST_FAILURE_AT), new HeaderValue(NOW.toString()));
return envelope(MessageHeaders.platform(headers));
}
private static MessageEnvelope<EncodedMessage> envelope(MessageHeaders headers) {
return new MessageEnvelope<>(
MessageId.newId(),
new MessageType("order.created"),
new SchemaVersion(1),
NOW,
Optional.of(NOW),
new ProducerId("order-api"),
Optional.of(new CorrelationId("wf-1")),
Optional.empty(),
ContentType.JSON,
Optional.empty(),
Optional.empty(),
Optional.empty(),
TraceContext.none(),
headers,
new EncodedMessage(
"{\"orderId\":\"o-1\"}".getBytes(StandardCharsets.UTF_8),
ContentType.JSON,
Optional.empty()));
}
}