feat: add messaging R2 polling producer

This commit is contained in:
donghyeon-ka
2026-07-31 23:48:43 +09:00
parent b3add0162d
commit e5af291269
93 changed files with 19617 additions and 139 deletions
+5
View File
@@ -23,6 +23,9 @@ envelope shape, metric cardinality bounds, tracing seam, domain-context propagat
`tracing/SpanErrorRecorder`) — W3C `traceparent` value type, baggage allowlist,
and the span-error-recording seam (feature-distributed-tracing-contract; the OTel
tracer runtime is a fork-activated seam, so these stay Java-stdlib-only).
- Generic messaging envelope schema resources under `contracts/messaging/envelope/`.
They own transport-neutral envelope metadata only; feature payload schemas remain in their
feature-owner modules. Resource presence is not runtime discovery or registration.
## Allowed
- Java standard library ONLY. No Spring, no Jackson, no JPA imports.
@@ -30,6 +33,8 @@ envelope shape, metric cardinality bounds, tracing seam, domain-context propagat
## Forbidden
- business/domain concept (domain error codes belong in the consuming module).
- framework imports (HTTP status is expressed as transport-neutral `int`; the web module maps it).
- claiming Draft 2020-12 validator compatibility before the messaging adapter's Task 6 validator
qualification exists.
## Test
```bash
+14
View File
@@ -14,6 +14,20 @@ persistence·outbound)이 프레임워크 충돌 없이 이 타입들을 공유
---
## messaging — generic envelope schema resource
- `contracts/messaging/envelope/v1.schema.json` 은 비즈니스 필드를 모르는 공통 envelope v1의
저장소 소유 Draft 2020-12 리소스다. root와 aggregate metadata는 닫혀 있고, `payload`는 object
크기만 제한한다. 실제 payload 필드와 닫힘 정책은 feature owner의 별도 schema가 소유한다.
- `.schema.sha256`은 schema 파일의 exact bytes SHA-256이다. 같은 version의 schema bytes를 바꾸면
digest도 의도적으로 갱신하고 compatibility 검토를 다시 해야 한다.
- 이 단계의 테스트는 UTF-8, 정본 구조, digest, remote `$ref` 금지만 JDK로 검사한다. Task 6의
실제 Draft 2020-12 validator가 붙기 전까지 validator compatibility가 증명된 것은 아니다.
- classpath resource가 존재한다는 사실은 runtime discovery나 자동 등록을 의미하지 않는다.
contract catalog와 encoder가 명시적으로 조립되기 전에는 어떤 publisher도 이 리소스를 읽지 않는다.
---
## error — 에러 코드 계약
### ApiErrorCode (인터페이스)
@@ -0,0 +1,100 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:dev-caskeleton:contracts:messaging:envelope:v1",
"title": "Messaging envelope v1",
"type": "object",
"required": [
"envelopeVersion",
"eventId",
"contractId",
"payloadVersion",
"logicalDestination",
"aggregate",
"occurredAt",
"correlationId",
"contentType",
"payload"
],
"properties": {
"envelopeVersion": {
"const": 1
},
"eventId": {
"type": "string",
"minLength": 1,
"maxLength": 96,
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
},
"contractId": {
"type": "string",
"minLength": 3,
"maxLength": 160,
"pattern": "^(?!.*(?:\\.|-)v[0-9]+$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?:\\.[a-z][a-z0-9]*(?:-[a-z0-9]+)*)+$"
},
"payloadVersion": {
"type": "integer",
"minimum": 1,
"maximum": 2147483647
},
"logicalDestination": {
"type": "string",
"minLength": 1,
"maxLength": 96,
"pattern": "^(?!.*-v[0-9]+$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"
},
"aggregate": {
"type": "object",
"required": [
"type",
"id",
"sequence",
"eventIndex"
],
"properties": {
"type": {
"type": "string",
"minLength": 1,
"maxLength": 64,
"pattern": "^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$"
},
"id": {
"type": "string",
"minLength": 1,
"maxLength": 160,
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
},
"sequence": {
"type": "integer",
"minimum": 1,
"maximum": 9223372036854775807
},
"eventIndex": {
"type": "integer",
"minimum": 0,
"maximum": 2147483647
}
},
"unevaluatedProperties": false
},
"occurredAt": {
"type": "string",
"minLength": 20,
"maxLength": 64,
"format": "date-time"
},
"correlationId": {
"type": "string",
"minLength": 1,
"maxLength": 96,
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
},
"contentType": {
"const": "application/json"
},
"payload": {
"type": "object",
"maxProperties": 64
}
},
"unevaluatedProperties": false
}
@@ -0,0 +1 @@
bf6f2e13fafe01b8ef4cbb73d7ba3f5703bfc68d145bdfe43190bf606dbd00b1
@@ -0,0 +1,274 @@
package dev.caskeleton.shared.contract.messaging;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.List;
import org.junit.jupiter.api.Test;
class MessagingEnvelopeSchemaResourceTest {
private static final String SCHEMA_RESOURCE = "contracts/messaging/envelope/v1.schema.json";
private static final String DIGEST_RESOURCE = "contracts/messaging/envelope/v1.schema.sha256";
private static final String CONTRACT_ID_PATTERN =
"^(?!.*(?:\\.|-)v[0-9]+$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*"
+ "(?:\\.[a-z][a-z0-9]*(?:-[a-z0-9]+)*)+$";
private static final String LOGICAL_DESTINATION_PATTERN =
"^(?!.*-v[0-9]+$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*$";
private static final BigInteger INT_MAXIMUM = BigInteger.valueOf(Integer.MAX_VALUE);
private static final BigInteger LONG_MAXIMUM = BigInteger.valueOf(Long.MAX_VALUE);
@Test
void envelopeV1IsTheCanonicalBusinessFreeClosedResource() throws Exception {
String schema = strictUtf8(readResource(SCHEMA_RESOURCE));
assertThat(schema)
.isEqualTo(
"""
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:dev-caskeleton:contracts:messaging:envelope:v1",
"title": "Messaging envelope v1",
"type": "object",
"required": [
"envelopeVersion",
"eventId",
"contractId",
"payloadVersion",
"logicalDestination",
"aggregate",
"occurredAt",
"correlationId",
"contentType",
"payload"
],
"properties": {
"envelopeVersion": {
"const": 1
},
"eventId": {
"type": "string",
"minLength": 1,
"maxLength": 96,
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
},
"contractId": {
"type": "string",
"minLength": 3,
"maxLength": 160,
"pattern": "^(?!.*(?:\\\\.|-)v[0-9]+$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?:\\\\.[a-z][a-z0-9]*(?:-[a-z0-9]+)*)+$"
},
"payloadVersion": {
"type": "integer",
"minimum": 1,
"maximum": 2147483647
},
"logicalDestination": {
"type": "string",
"minLength": 1,
"maxLength": 96,
"pattern": "^(?!.*-v[0-9]+$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"
},
"aggregate": {
"type": "object",
"required": [
"type",
"id",
"sequence",
"eventIndex"
],
"properties": {
"type": {
"type": "string",
"minLength": 1,
"maxLength": 64,
"pattern": "^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$"
},
"id": {
"type": "string",
"minLength": 1,
"maxLength": 160,
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
},
"sequence": {
"type": "integer",
"minimum": 1,
"maximum": 9223372036854775807
},
"eventIndex": {
"type": "integer",
"minimum": 0,
"maximum": 2147483647
}
},
"unevaluatedProperties": false
},
"occurredAt": {
"type": "string",
"minLength": 20,
"maxLength": 64,
"format": "date-time"
},
"correlationId": {
"type": "string",
"minLength": 1,
"maxLength": 96,
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
},
"contentType": {
"const": "application/json"
},
"payload": {
"type": "object",
"maxProperties": 64
}
},
"unevaluatedProperties": false
}
""");
assertThat(schema)
.doesNotContain(
"\"workLogId\"", "\"portfolio.worklog.reserved\"", "\"topic\"", "\"bootstrapServers\"");
assertThat(URI.create("urn:dev-caskeleton:contracts:messaging:envelope:v1").isAbsolute())
.isTrue();
assertThat(schema).doesNotContainPattern("\"type\"\\s*:\\s*\\[[^]]*\"null\"");
assertThat(schema).doesNotContain("\"$ref\"");
}
@Test
void identifierPatternsStayInParityWithTaskThreeValueObjects() throws Exception {
String schema = strictUtf8(readResource(SCHEMA_RESOURCE));
assertThat(schema)
.contains(
"\"pattern\": \"" + jsonEscape(CONTRACT_ID_PATTERN) + "\"",
"\"pattern\": \"" + jsonEscape(LOGICAL_DESTINATION_PATTERN) + "\"");
assertThat(List.of("portfolio.worklog.reserved", "portfolio-v1.worklog.reserved"))
.allMatch(value -> value.matches(CONTRACT_ID_PATTERN));
assertThat(List.of("portfolio.worklog.v1", "portfolio.worklog-v1"))
.noneMatch(value -> value.matches(CONTRACT_ID_PATTERN));
assertThat(List.of("portfolio-domain-events", "events"))
.allMatch(value -> value.matches(LOGICAL_DESTINATION_PATTERN));
assertThat(List.of("events-v2")).noneMatch(value -> value.matches(LOGICAL_DESTINATION_PATTERN));
}
@Test
void numericConstraintsFreezeJavaBoundaryAndOverBoundaryVectors() throws Exception {
String schema = strictUtf8(readResource(SCHEMA_RESOURCE));
assertThat(countOccurrences(schema, "\"maximum\": 2147483647")).isEqualTo(2);
assertThat(countOccurrences(schema, "\"maximum\": 9223372036854775807")).isEqualTo(1);
assertThat(withinRange("2147483647", BigInteger.ONE, INT_MAXIMUM)).isTrue();
assertThat(withinRange("2147483648", BigInteger.ONE, INT_MAXIMUM)).isFalse();
assertThat(withinRange("2147483647", BigInteger.ZERO, INT_MAXIMUM)).isTrue();
assertThat(withinRange("2147483648", BigInteger.ZERO, INT_MAXIMUM)).isFalse();
assertThat(withinRange("9223372036854775807", BigInteger.ONE, LONG_MAXIMUM)).isTrue();
assertThat(withinRange("9223372036854775808", BigInteger.ONE, LONG_MAXIMUM)).isFalse();
}
@Test
void checkedInDigestMatchesExactSchemaBytesAndCanonicalManifestFormat() throws Exception {
byte[] schemaBytes = readResource(SCHEMA_RESOURCE);
byte[] manifestBytes = readResource(DIGEST_RESOURCE);
String manifest = strictUtf8(manifestBytes);
assertThat(manifestBytes).endsWith((byte) '\n');
assertThat(manifest).matches("[0-9a-f]{64}\\n");
assertThat(manifest).isEqualTo(HexFormat.of().formatHex(sha256(schemaBytes)) + "\n");
}
@Test
void utf8DecoderRejectsMalformedResourceBytes() {
byte[] malformed = {(byte) 0xc3, (byte) 0x28};
assertThatThrownBy(() -> strictUtf8(malformed)).isInstanceOf(CharacterCodingException.class);
}
@Test
void frozenEnvelopeExampleRetainsTheDesignValuesWithoutOwningBusinessSchema() {
String frozenExample =
"""
{
"envelopeVersion": 1,
"eventId": "event-1",
"contractId": "portfolio.worklog.reserved",
"payloadVersion": 1,
"logicalDestination": "portfolio-domain-events",
"aggregate": {
"type": "worklog",
"id": "worklog-42",
"sequence": 17,
"eventIndex": 0
},
"occurredAt": "2026-07-28T05:10:30.123Z",
"correlationId": "corr-1",
"contentType": "application/json",
"payload": {
"workLogId": "worklog-42"
}
}
""";
assertThat(frozenExample)
.contains(
"\"envelopeVersion\": 1",
"\"eventId\": \"event-1\"",
"\"contractId\": \"portfolio.worklog.reserved\"",
"\"logicalDestination\": \"portfolio-domain-events\"",
"\"sequence\": 17",
"\"eventIndex\": 0",
"\"occurredAt\": \"2026-07-28T05:10:30.123Z\"",
"\"correlationId\": \"corr-1\"",
"\"contentType\": \"application/json\"",
"\"workLogId\": \"worklog-42\"");
}
private static byte[] readResource(String resource) throws IOException {
try (InputStream input =
MessagingEnvelopeSchemaResourceTest.class.getClassLoader().getResourceAsStream(resource)) {
if (input == null) {
throw new IOException("Missing classpath resource: " + resource);
}
return input.readAllBytes();
}
}
private static String strictUtf8(byte[] bytes) throws CharacterCodingException {
return StandardCharsets.UTF_8
.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes))
.toString();
}
private static byte[] sha256(byte[] bytes) throws NoSuchAlgorithmException {
return MessageDigest.getInstance("SHA-256").digest(bytes);
}
private static String jsonEscape(String value) {
return value.replace("\\", "\\\\");
}
private static int countOccurrences(String value, String fragment) {
return (value.length() - value.replace(fragment, "").length()) / fragment.length();
}
private static boolean withinRange(String candidate, BigInteger minimum, BigInteger maximum) {
BigInteger value = new BigInteger(candidate);
return value.compareTo(minimum) >= 0 && value.compareTo(maximum) <= 0;
}
}