feat: jpa, messaging, notification, mongo, graphql 어댑터터 구현체 추가

This commit is contained in:
DongHyeonka
2026-08-15 13:01:58 +09:00
parent e23ed9486e
commit f56dd3e4eb
174 changed files with 10338 additions and 1274 deletions
@@ -6,9 +6,12 @@ import dev.caskeleton.messaging.api.SchemaVersion;
import dev.caskeleton.messaging.api.error.MessageSerializationException;
import dev.caskeleton.messaging.api.error.MessageTooLargeException;
import dev.caskeleton.messaging.api.error.MessageValidationException;
import dev.caskeleton.messaging.schema.BoundedByteSink;
import dev.caskeleton.messaging.schema.EncodedMessage;
import dev.caskeleton.messaging.schema.MessageCodec;
import dev.caskeleton.messaging.schema.MessageContractKey;
import dev.caskeleton.messaging.schema.SchemaReference;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
@@ -45,10 +48,10 @@ public final class JacksonMessageCodec implements MessageCodec {
private static final int MAX_NUMBER_DIGITS = 1_000;
private final ObjectMapper mapper;
private final Map<MessageType, Class<?>> registry;
private final Map<MessageContractKey, Class<?>> registry;
private final int maxBytes;
private JacksonMessageCodec(Map<MessageType, Class<?>> registry, int maxBytes) {
private JacksonMessageCodec(Map<MessageContractKey, Class<?>> registry, int maxBytes) {
this.registry = Map.copyOf(registry);
this.maxBytes = maxBytes;
this.mapper = strictMapper(maxBytes);
@@ -57,33 +60,47 @@ public final class JacksonMessageCodec implements MessageCodec {
/**
* Creates a codec over an explicit message-type registry.
*
* @param registry the closed map of message type to payload class
* @param registry the closed map of message contract to payload class
* @return a codec with the default one mebibyte limit
*/
public static JacksonMessageCodec of(Map<MessageType, Class<?>> registry) {
public static JacksonMessageCodec of(Map<MessageContractKey, Class<?>> registry) {
return new JacksonMessageCodec(registry, DEFAULT_MAX_BYTES);
}
/**
* Creates a codec over an explicit registry and byte limit.
*
* @param registry the closed map of message type to payload class
* @param registry the closed map of message contract to payload class
* @param maxBytes the maximum encoded size
* @return a codec
*/
public static JacksonMessageCodec of(Map<MessageType, Class<?>> registry, int maxBytes) {
public static JacksonMessageCodec of(Map<MessageContractKey, Class<?>> registry, int maxBytes) {
return new JacksonMessageCodec(registry, maxBytes);
}
/**
* Creates a single-entry codec for focused tests, registered at version one.
*
* @param type the catalog message type
* @param payloadType the payload class
* @return a codec registering exactly one contract, {@code type v1}
*/
public static JacksonMessageCodec testingDefault(MessageType type, Class<?> payloadType) {
return testingDefault(type, new SchemaVersion(1), payloadType);
}
/**
* Creates a single-entry codec for focused tests.
*
* @param type the catalog message type
* @param version the schema version to register
* @param payloadType the payload class
* @return a codec registering exactly one type
* @return a codec registering exactly one contract
*/
public static JacksonMessageCodec testingDefault(MessageType type, Class<?> payloadType) {
return new JacksonMessageCodec(Map.of(type, payloadType), DEFAULT_MAX_BYTES);
public static JacksonMessageCodec testingDefault(
MessageType type, SchemaVersion version, Class<?> payloadType) {
return new JacksonMessageCodec(
Map.of(new MessageContractKey(type, version), payloadType), DEFAULT_MAX_BYTES);
}
@Override
@@ -93,8 +110,7 @@ public final class JacksonMessageCodec implements MessageCodec {
@Override
public EncodedMessage encode(MessageType type, SchemaVersion version, Object payload) {
Class<?> registered = requireRegistered(type);
Objects.requireNonNull(version, "schemaVersion must not be null");
Class<?> registered = requireRegistered(type, version);
Objects.requireNonNull(payload, "payload must not be null");
if (!registered.isInstance(payload)) {
throw new MessageValidationException(
@@ -102,27 +118,25 @@ public final class JacksonMessageCodec implements MessageCodec {
"payload does not match the registered type for " + type.value());
}
byte[] bytes;
// Streamed into a bounded sink: Jackson writes incrementally, so a payload whose serialized
// form is far larger than the limit stops at the limit instead of after the whole graph has
// been rendered into a buffer nobody bounded.
BoundedByteSink sink = BoundedByteSink.of(maxBytes, "PAYLOAD_TOO_LARGE");
try {
bytes = mapper.writeValueAsBytes(payload);
mapper.writeValue(sink, payload);
} catch (JacksonException exception) {
throw new MessageSerializationException(
"JSON_ENCODE_FAILED", "payload could not be encoded as JSON", exception);
}
if (bytes.length > maxBytes) {
throw new MessageTooLargeException(
"PAYLOAD_TOO_LARGE",
"encoded payload is " + bytes.length + " bytes, limit is " + maxBytes);
throw unwrapTooLarge(exception);
}
return new EncodedMessage(
bytes, ContentType.JSON, Optional.of(SchemaReference.of(type.value(), version)));
sink.toByteArray(),
ContentType.JSON,
Optional.of(SchemaReference.of(type.value(), version)));
}
@Override
public <T> T decode(
MessageType type, SchemaVersion version, byte[] encoded, Class<T> payloadType) {
Class<?> registered = requireRegistered(type);
Objects.requireNonNull(version, "schemaVersion must not be null");
Class<?> registered = requireRegistered(type, version);
Objects.requireNonNull(encoded, "encoded bytes must not be null");
Objects.requireNonNull(payloadType, "payloadType must not be null");
if (!registered.equals(payloadType)) {
@@ -144,14 +158,50 @@ public final class JacksonMessageCodec implements MessageCodec {
}
}
private Class<?> requireRegistered(MessageType type) {
Objects.requireNonNull(type, "messageType must not be null");
Class<?> registered = registry.get(type);
if (registered == null) {
throw new MessageValidationException(
"UNKNOWN_MESSAGE_TYPE", "message type is not registered: " + type.value());
private Class<?> requireRegistered(MessageType type, SchemaVersion version) {
MessageContractKey key = new MessageContractKey(type, version);
Class<?> registered = registry.get(key);
if (registered != null) {
return registered;
}
return registered;
boolean typeIsKnown = registry.keySet().stream().anyMatch(known -> known.type().equals(type));
if (typeIsKnown) {
// Deliberately not falling back to another version's class: decoding v999 bytes with the v1
// class is exactly the silent type confusion the version-keyed registry exists to stop.
throw new MessageValidationException(
"SCHEMA_VERSION_NOT_REGISTERED",
"no contract is registered for "
+ key.describe()
+ "; registered versions: "
+ registeredVersions(type));
}
throw new MessageValidationException(
"UNKNOWN_MESSAGE_TYPE", "message type is not registered: " + type.value());
}
private List<Integer> registeredVersions(MessageType type) {
return registry.keySet().stream()
.filter(known -> known.type().equals(type))
.map(known -> known.version().value())
.sorted()
.toList();
}
/**
* Surfaces a bound violation as itself rather than as a generic encoding failure.
*
* <p>Jackson wraps stream failures, so the size refusal would otherwise reach the caller as
* {@code JSON_ENCODE_FAILED} — indistinguishable from a payload the mapper genuinely could not
* render, and the two need different operator responses.
*/
private static RuntimeException unwrapTooLarge(JacksonException exception) {
for (Throwable cause = exception; cause != null; cause = cause.getCause()) {
if (cause instanceof MessageTooLargeException tooLarge) {
return tooLarge;
}
}
return new MessageSerializationException(
"JSON_ENCODE_FAILED", "payload could not be encoded as JSON", exception);
}
private static ObjectMapper strictMapper(int maxBytes) {
@@ -0,0 +1,114 @@
package dev.caskeleton.messaging.schema.json;
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.MessageType;
import dev.caskeleton.messaging.api.SchemaVersion;
import dev.caskeleton.messaging.api.error.MessageTooLargeException;
import dev.caskeleton.messaging.api.error.MessageValidationException;
import dev.caskeleton.messaging.schema.MessageContractKey;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* What the registry key is, and where the size limit takes effect.
*
* <p>Two defects met in this codec. The registry was keyed on message type alone, so a message
* labelled v999 was decoded with the v1 class and kept its v999 label — the compatibility gate and
* the audit record then both described a contract that was never registered. And the size limit was
* applied to the finished byte array, which reports an oversized payload rather than preventing
* one.
*/
class JsonContractRegistryTest {
private static final MessageType ORDER_CREATED = new MessageType("order.created");
private static final SchemaVersion V1 = new SchemaVersion(1);
private static final SchemaVersion V2 = new SchemaVersion(2);
record OrderCreated(String orderId, long amount) {}
record OrderCreatedV2(String orderId, long amount, String channel) {}
private final JacksonMessageCodec codec =
JacksonMessageCodec.of(
Map.of(
new MessageContractKey(ORDER_CREATED, V1), OrderCreated.class,
new MessageContractKey(ORDER_CREATED, V2), OrderCreatedV2.class));
@Test
@DisplayName("each registered version decodes with its own class")
void eachVersionDecodesWithItsOwnClass() {
byte[] v1 = codec.encode(ORDER_CREATED, V1, new OrderCreated("o-1", 10)).bytes();
byte[] v2 = codec.encode(ORDER_CREATED, V2, new OrderCreatedV2("o-1", 10, "APP")).bytes();
assertThat(codec.decode(ORDER_CREATED, V1, v1, OrderCreated.class).orderId()).isEqualTo("o-1");
assertThat(codec.decode(ORDER_CREATED, V2, v2, OrderCreatedV2.class).channel())
.isEqualTo("APP");
}
@Test
@DisplayName("an unregistered version is refused, not decoded with a neighbour's class")
void anUnregisteredVersionIsRefused() {
byte[] v1 = codec.encode(ORDER_CREATED, V1, new OrderCreated("o-1", 10)).bytes();
assertThatThrownBy(() -> codec.decode(ORDER_CREATED, new SchemaVersion(999), v1, Object.class))
.isInstanceOf(MessageValidationException.class)
.hasMessageContaining("order.created v999")
.hasMessageContaining("[1, 2]");
}
@Test
@DisplayName("the requested class must be the one registered for that exact version")
void theRequestedClassMustMatchTheVersion() {
byte[] v1 = codec.encode(ORDER_CREATED, V1, new OrderCreated("o-1", 10)).bytes();
assertThatThrownBy(() -> codec.decode(ORDER_CREATED, V1, v1, OrderCreatedV2.class))
.isInstanceOf(MessageValidationException.class);
}
@Test
@DisplayName("an unknown message type is still distinguished from an unknown version")
void anUnknownTypeIsDistinguishedFromAnUnknownVersion() {
assertThatThrownBy(
() -> codec.encode(new MessageType("order.cancelled"), V1, new OrderCreated("o", 1)))
.isInstanceOf(MessageValidationException.class)
.hasMessageContaining("message type is not registered");
}
@Test
@DisplayName("a payload far larger than the limit stops at the limit")
void aPayloadFarLargerThanTheLimitStopsAtTheLimit() {
MessageType largeList = new MessageType("text.list");
JacksonMessageCodec bounded =
JacksonMessageCodec.of(Map.of(new MessageContractKey(largeList, V1), List.class), 1_024);
// Roughly twenty mebibytes of JSON. The old codec rendered all of it into a byte array and
// only then compared the length with 1024.
List<String> payload = java.util.Collections.nCopies(200_000, "x".repeat(100));
assertThatThrownBy(() -> bounded.encode(largeList, V1, payload))
.isInstanceOf(MessageTooLargeException.class)
.hasMessageContaining("1024")
.hasMessageContaining("refused at byte");
}
@Test
@DisplayName("a payload at exactly the limit is still accepted")
void aPayloadAtExactlyTheLimitIsAccepted() {
MessageType text = new MessageType("text.exact");
int exact =
JacksonMessageCodec.testingDefault(text, String.class)
.encode(text, V1, "a".repeat(100))
.bytes()
.length;
JacksonMessageCodec bounded =
JacksonMessageCodec.of(Map.of(new MessageContractKey(text, V1), String.class), exact);
assertThatCode(() -> bounded.encode(text, V1, "a".repeat(100))).doesNotThrowAnyException();
assertThatThrownBy(() -> bounded.encode(text, V1, "a".repeat(101)))
.isInstanceOf(MessageTooLargeException.class);
}
}