fix!: 성숙도 리뷰의 High·P1 결함 19건을 고친다

문제: 2026-11-01 성숙도 리뷰에서 High 21건·P1 25건이 나왔다. 결과를
모르는 일을 "확실함"으로 기록했다(발송 중 죽은 알림 재발송, 커밋 중
끊긴 쓰기를 재시도 가능으로 응답, 재시도 가능한 거부를 DEAD로). 중복을
DB가 아니라 코드 순서로 막았다(정산 job, 포스터 제목). 짝 프론트와
wire 계약이 달랐고(처리 중 409, Envelope null), JWT audience 검증이
기본으로 꺼져 있었고, 트레이스가 나가지 않았고, CI가 strict lane 14개를
한 번도 돌리지 않았다.

방법: 발견마다 실패하는 테스트를 먼저 쓰고 고쳤다. 주요 선택:
- 알림 attempt는 처음부터 "시작 여부 모름"으로 쓴다(호출 직전 갱신은
  쓰기가 하나 늘어 버림).
- 정산 job claim은 lease·fence를 갱신하는 UPDATE 한 문장(처리 전체를
  트랜잭션으로 감싸는 안은 외부 호출 동안 잠금을 잡아 버림).
- 커밋 단계 연결 끊김은 DB_COMPLETION_UNKNOWN(재시도 불가).
- 처리 중 409는 retryable=true + Retry-After: 2, Envelope null 필드는
  web Jackson mixin으로 생략(shared-contract는 stdlib only).
- 트레이싱은 자체 Tracer를 지우고 Boot 4 tracing·OTLP로.
- strict lane을 단계에 연결하고 verifyStrictLaneStages가 고아를 막는다.
발견별 RED·GREEN·버린 대안은 리뷰 README 13절 표에 있다.

위험·한계: JWT 모드는 APP_SECURITY_JWT_AUDIENCE가 없으면 기동하지
않는다. 짝 프론트는 409 retryable과 Envelope 키 규칙을 맞춰야 한다.
이 커밋 시점에는 MinIO 공식 이미지가 사라져 MinIO 2 lane이 실패한다
(다음 커밋에서 대체 이미지로 해결).

검증: ci 통과. mainCheck·integrationCheck는 MinIO 2 lane만 실패(이미지
pull 거부). -p optional-platforms ci integrationCheck, performanceCheck,
releaseCheck(-PgitRevision) 통과.

Refs: docs/reviews/2026-11-01-maturity-review/README.md 2·13절
BREAKING CHANGE: JWT 모드에서 APP_SECURITY_JWT_AUDIENCE가 필수가 되고 role은
audience client와 realm 것만 읽는다. IDEMPOTENT_IN_FLIGHT가 retryable=true,
Retry-After: 2로 바뀌고 Envelope는 null 필드를 보내지 않는다.
This commit is contained in:
DongHyeonka
2026-11-03 19:52:06 +09:00
parent 01a8a2a70f
commit 34565130e0
253 changed files with 13849 additions and 1140 deletions
+6 -2
View File
@@ -27,8 +27,10 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇
| `configContractCheck` | `:app-bootstrap:verifyEnvKeys`로 환경 설정 계약을 검사 |
| `qualificationCheck` | 전체 기동(system) 레인과 보조 source set Checkstyle을 실행 |
| `integrationCheck` | 선언된 strict integration lane(sample 포함)을 실행. 대부분 container runtime이 필요. 입력이 필요한 lane(Redis topology: `-Predis.topology.mode`, AWS: 보호 자격 증명 env)은 입력이 없으면 빠지고 집계가 그 이유를 출력 |
| `performanceCheck` | 선언된 strict performance lane(부하·종료·pool·자원 상한)을 실행. 실서버·container가 필요. `integration-main.yml` `performance-check`가 main·nightly에 돌림 |
| `verifyStrictLaneStages` | `--dry-run` 전용. `explicitOnly`가 아닌 strict lane이 workflow가 실제 실행하는 단계(`ci`·`:sample-portfolio:check`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`) 중 하나의 계획에 있는지, 각 단계를 workflow가 `--dry-run` 없이 실행하는지 검사. PR 게이트가 돌림 |
| `ci` | PR 게이트: 모든 leaf `check`(API surface 검사 포함, 소유자 결정 20) + `architectureCheck` + `qualityCheck` |
| `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + sample web 계약 + `verifyPublicPathSnapshot` + 전송·메시징 qualification 레인 + 각 leaf의 `mainCheck`(문서 대조 레인 `*DocumentContractTest`, objectstorage MinIO 레인) |
| `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + sample web 계약 + sample 전체 기동(`:sample-portfolio:systemTest`) + `verifyPublicPathSnapshot` + 전송·메시징 qualification 레인 + 각 leaf의 `mainCheck`(문서 대조 레인 `*DocumentContractTest`, objectstorage MinIO 레인) |
| `releaseCheck` | tag 전용 검사: `verifyReleaseProvenance` + `verifyPublicPathSnapshot`(`ci`를 다시 돌리지 않음) |
따라서 로컬에서 한 모듈만 수정했다면 `./gradlew :domain-core:check`처럼 focused task를
@@ -489,7 +491,9 @@ Boot 기본값이 바뀌어도 wire 계약이 조용히 깨지지 않게 합니
- **`APP_SECURITY_JWT_ISSUER`** — OIDC issuer URI(Keycloak realm, Auth0 tenant 등). **필수** — 없으면
기동 실패. 예: `https://keycloak.example.com/realms/ca-skeleton`.
- **`APP_SECURITY_JWT_AUDIENCE`** — 기대하는 `aud` claim. 빈 값으로 두면 audience 검증을 건너뜁니다.
- **`APP_SECURITY_JWT_AUDIENCE`** — 기대하는 `aud` claim(쉼표 목록 가능, 하나라도 맞으면 통과).
JWT 모드에서 **필수** — 비어 있으면 기동 실패. 이 목록의 client 에 대한 `resource_access` role 만
권한으로 읽습니다. 예: `ca-skeleton-api`.
- **`SECURITY_PUBLIC_PATHS`** — 인증을 우회하는 경로 CSV. `api-base-path` 뒤의 full path 를 씁니다(예:
`/api/healthcheck`). 이 값의 변경은 `verifyPublicPathSnapshot` 게이트가 감시합니다(위 build.gradle
설명 참조).
+35
View File
@@ -188,6 +188,41 @@ data 다. GraphQL over HTTP 초안의 status 294 는 쓰지 않는다. 이 leaf
모델(`GraphQlHttpStatusMapper`, `GraphQlHttpProfile` 등)은 요청 경로에 없어서 2026-09-25 에
삭제했다(`docs/capability-status.md` 제거 표).
## 목록을 돌려주는 필드는 클라이언트가 어떻게 물어도 원소 수만큼 곱한다
복잡도 점수(`cost/GraphQlDocumentComplexityScorer`)는 실행 전에 매긴다. 목록 필드의 하위 비용에
곱하는 수는 이렇게 정한다.
| 필드 | 곱하는 수 |
| --- | --- |
| page 필드 — 스키마에 `first`/`last` 인자가 있거나 catalog 에 `connection=true` 로 등록 | 리터럴 → 요청 변수 → 연산의 변수 기본값 → 스키마 인자 기본값 순서로 찾은 page. 없으면 기본 page 크기(`defaultPageSize`). 찾은 값은 모두 `maximum-page-size` 로 검사하고, `first`·`last` 를 둘 다 주면 큰 쪽 |
| page 인자가 없는 일반 list | catalog 의 `GraphQlFieldCostDescriptor.estimatedListSize`, 선언이 없으면 기본 page 크기. `[[T]]` 는 차원마다 한 번 |
| page 필드가 돌려준 connection 객체 바로 안의 list(`edges`·`nodes`) | 곱하지 않는다. connection 이 이미 page 만큼 곱했다 |
2026-11-01 리뷰(03-01) 전에는 인자가 값으로 보일 때만 곱했다. `items(first: 20)` 은 410 점,
`items` 는 40 점, list 4단 중첩은 100 점이었고 `query($n: Int = 100000)` 은 상한 검사 없이
통과했다. 예산(기본 10,000)과 page 상한(기본 100)이 목록 필드가 생기는 순간 꺼져 있었다.
**도입하는 서비스에 미치는 영향.** 크기를 선언하지 않은 일반 list 는 이제 원소 20 개로 계산된다.
작은 고정 목록(예: 태그 몇 개)이 예산을 많이 먹으면 `GraphQlCostCatalog` 빈에
`new GraphQlFieldCostDescriptor("Item.tags", base, weight, false, 5)` 처럼 추정 크기를 선언한다.
점수가 커지는 쪽으로만 바뀌므로, 이전에 통과하던 깊은 목록 쿼리가 `GRAPHQL_COMPLEXITY_EXCEEDED` 로
거부될 수 있다.
**고른 방법과 버린 대안.**
- 변수 기본값은 연산 문서의 `VariableDefinition` 기본값을 직접 읽는다. graphql-java 의
`ValuesResolver.coerceVariableValues` 로 강제 변환한 값을 쓰는 방법은 버렸다. 그 호출은 잘못된
변수에서 예외를 던지므로, 지금 실행 단계가 내는 변수 오류가 비용 단계에서 다른 모양으로 나오게
된다. page 크기에 필요한 것은 Int 하나라서 직접 읽는 쪽이 오류 계약을 건드리지 않는다.
- 일반 list 의 크기는 스키마 지시어(`@listSize` 등)가 아니라 기존 cost catalog 에 선언한다. 비용
정책이 이미 catalog 한 곳에 있고, 지시어는 스키마 파일과 SDL 처리 경로를 하나 더 만든다.
- graphql-java 기본 `MaxQueryComplexityInstrumentation` 은 쓰지 않는다. 그것도 list 배수를 모르는
필드 개수 합이라 같은 구멍이 남고, 점수가 두 벌이 된다.
- 점수가 `long` 을 넘으면 `Long.MAX_VALUE` 에서 멈춘다(포화 산술). 목록마다 곱하면 적대적인 문서
몇 단으로 `long` 끝에 닿는데, 그때 `ArithmeticException` 이 내부 오류로 새지 않고 예산 초과로
거부되게 하기 위해서다.
## 요청 단위 DB 트랜잭션을 열지 않는다
GraphQL 한 요청은 여러 root field 를 담을 수 있고, 각 root 는 자기 use case 를 호출한다.
@@ -23,7 +23,8 @@ public final class GraphQlComplexityCalculator {
* Creates the calculator.
*
* @param catalog registered field costs
* @param defaultPageSize page size assumed when a connection omits {@code first}/{@code last}
* @param defaultPageSize page size assumed when a connection omits {@code first}/{@code last},
* and the element count of a list whose size was never declared
* @param maximumPageSize largest page size a client may request
*/
public GraphQlComplexityCalculator(
@@ -39,24 +40,63 @@ public final class GraphQlComplexityCalculator {
/**
* Cost of a connection field.
*
* <p>Both page arguments are checked against the maximum, and the larger one is the multiplier:
* which of the two a resolver honours is its business, and pricing the smaller one would let
* {@code first: 1, last: 100000} through on the strength of the argument it ignores.
*
* @param coordinate schema coordinate of the connection field
* @param first requested forward page size, or {@code null}
* @param last requested backward page size, or {@code null}
* @param childCost cost of one child subtree
* @throws GraphQlComplexityRejectedException when the requested page exceeds the maximum
* @throws GraphQlComplexityRejectedException when a requested page exceeds the maximum
*/
public GraphQlComplexityResult connectionCost(
String coordinate, Integer first, Integer last, long childCost) {
int requested = first != null ? first : last != null ? last : defaultPageSize;
if (requested > maximumPageSize) {
throw new GraphQlComplexityRejectedException("page size exceeds maximum");
}
if (requested < 1) {
throw new GraphQlComplexityRejectedException("page size must be positive");
}
requireAllowedPage(first);
requireAllowedPage(last);
int requested =
first != null && last != null
? Math.max(first, last)
: first != null ? first : last != null ? last : defaultPageSize;
long root = catalog.require(coordinate).baseCost();
return new GraphQlComplexityResult(
Math.addExact(root, Math.multiplyExact((long) requested, childCost)));
return new GraphQlComplexityResult(saturatedAdd(root, saturatedMultiply(requested, childCost)));
}
/**
* Cost of a list-returning field that takes no page arguments.
*
* <p>A plain list is not one child, it is as many children as it holds. The registered {@link
* GraphQlFieldCostDescriptor#estimatedListSize()} is that count when the adopter declared one;
* otherwise the default page size stands in for it, because a list nobody sized is exactly the
* one whose size nobody bounded. A list of lists multiplies once per dimension.
*
* @param coordinate schema coordinate
* @param dimensions how many list wrappers the field type has, at least one
* @param childCost cost of one element's subtree
*/
public GraphQlComplexityResult listCost(String coordinate, int dimensions, long childCost) {
if (dimensions < 1) {
throw new IllegalArgumentException("a list field has at least one dimension");
}
GraphQlFieldCostDescriptor descriptor = catalog.require(coordinate);
int size =
descriptor.estimatedListSize() == GraphQlFieldCostDescriptor.UNDECLARED_LIST_SIZE
? defaultPageSize
: descriptor.estimatedListSize();
long elements = childCost;
for (int dimension = 0; dimension < dimensions; dimension++) {
elements = saturatedMultiply(size, elements);
}
return new GraphQlComplexityResult(saturatedAdd(descriptor.weightedCost(), elements));
}
/**
* Whether a coordinate is registered as a paginated connection.
*
* <p>Such a field is priced at the default page even when its schema declares no page argument.
*/
public boolean connection(String coordinate) {
return catalog.require(coordinate).connection();
}
/**
@@ -67,7 +107,7 @@ public final class GraphQlComplexityCalculator {
*/
public GraphQlComplexityResult fieldCost(String coordinate, long childCost) {
GraphQlFieldCostDescriptor descriptor = catalog.require(coordinate);
return new GraphQlComplexityResult(Math.addExact(descriptor.weightedCost(), childCost));
return new GraphQlComplexityResult(saturatedAdd(descriptor.weightedCost(), childCost));
}
/**
@@ -85,4 +125,36 @@ public final class GraphQlComplexityCalculator {
public int effectivePageSize(Integer first, Integer last) {
return first != null ? first : last != null ? last : defaultPageSize;
}
private void requireAllowedPage(Integer requested) {
if (requested == null) {
return;
}
if (requested > maximumPageSize) {
throw new GraphQlComplexityRejectedException("page size exceeds maximum");
}
if (requested < 1) {
throw new GraphQlComplexityRejectedException("page size must be positive");
}
}
/**
* Addition that stops at {@link Long#MAX_VALUE}.
*
* <p>Scores multiply with every nested list, so a few levels of a hostile document reach the end
* of {@code long}. Overflow must read as "over any budget", not as an arithmetic error that
* escapes the rejection path as an internal failure.
*/
static long saturatedAdd(long left, long right) {
long sum = left + right;
return ((left ^ sum) & (right ^ sum)) < 0 ? Long.MAX_VALUE : sum;
}
/** Multiplication of non-negative values that stops at {@link Long#MAX_VALUE}. */
static long saturatedMultiply(long left, long right) {
if (left == 0 || right == 0) {
return 0;
}
return left > Long.MAX_VALUE / right ? Long.MAX_VALUE : left * right;
}
}
@@ -12,7 +12,9 @@ import graphql.language.OperationDefinition;
import graphql.language.Selection;
import graphql.language.SelectionSet;
import graphql.language.Value;
import graphql.language.VariableDefinition;
import graphql.language.VariableReference;
import graphql.schema.GraphQLArgument;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLFieldsContainer;
import graphql.schema.GraphQLList;
@@ -20,6 +22,8 @@ import graphql.schema.GraphQLNonNull;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLType;
import graphql.schema.InputValueWithState;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayDeque;
import java.util.Deque;
@@ -36,10 +40,24 @@ import java.util.Objects;
* against the schema. Guessing it from the operation root would price {@code order { customer {
* orders { … } } }} as three root fields and miss the multiplication entirely.
*
* <p>Cardinality comes from the request, not from the schema: a connection's children are
* multiplied by the effective page size, and a page size supplied through a variable is resolved
* from the request variables rather than assumed to be the default. That is the difference between
* a budget and a suggestion — {@code first: $n} would otherwise cost the same at 1 and at 1000.
* <p>Every field that returns many things multiplies its children, however the client phrased the
* request:
*
* <ul>
* <li>A paginated field — one whose schema declares {@code first}/{@code last}, or one registered
* as a connection — multiplies by the page it will be asked for. That page is the literal, or
* the request variable, or the operation's variable default, or the schema argument default,
* in that order; when none applies it is the default page size, never one. Each of these is
* checked against the maximum page size, so {@code ($n: Int = 100000)} is refused exactly as
* the literal would be.
* <li>A list-returning field without page arguments multiplies by its registered estimated size,
* or the default page size, once per list dimension.
* <li>The list fields directly inside a paginated object (a Relay connection's {@code edges} or
* {@code nodes}) are the page the connection already paid for, and are not multiplied again.
* </ul>
*
* <p>Pricing an omitted argument as one row was the bypass: {@code items(first: 20)} scored 410
* while {@code items} scored 40, and four nested lists added up instead of multiplying.
*
* <p>Traversal is bounded, and fragment cycles are cut by tracking the expansion path. This runs on
* documents that have passed validation, but the bound stays because the scorer is also used from
@@ -50,6 +68,9 @@ public final class GraphQlDocumentComplexityScorer {
/** Prefix that marks an introspection field, which is gated rather than priced. */
public static final String INTROSPECTION_FIELD_PREFIX = "__";
private static final String FIRST = "first";
private static final String LAST = "last";
private final GraphQlComplexityCalculator calculator;
private final int maximumVisitedNodes;
@@ -79,7 +100,8 @@ public final class GraphQlDocumentComplexityScorer {
* @param schema schema the document was validated against
* @param document the parsed document
* @param operation the selected operation
* @param variables the request variables, used to resolve page sizes
* @param variables the request variables as the client sent them, used to resolve page sizes; the
* operation's own variable defaults fill in what the client left out
* @throws GraphQlComplexityRejectedException when a requested page exceeds the maximum
* @throws GraphQlStructuralLimitException when traversal exceeds the node budget
*/
@@ -112,9 +134,10 @@ public final class GraphQlDocumentComplexityScorer {
root,
operation.getSelectionSet(),
fragments,
variables == null ? Map.of() : variables,
PageVariables.of(operation, variables),
new Counter(),
new ArrayDeque<>());
new ArrayDeque<>(),
false);
return new GraphQlComplexityResult(total);
}
@@ -123,9 +146,10 @@ public final class GraphQlDocumentComplexityScorer {
GraphQLFieldsContainer parent,
SelectionSet selectionSet,
Map<String, FragmentDefinition> fragments,
Map<String, Object> variables,
PageVariables variables,
Counter counter,
Deque<String> expansionPath) {
Deque<String> expansionPath,
boolean listsAreThePage) {
if (selectionSet == null || parent == null) {
return 0;
@@ -137,16 +161,24 @@ public final class GraphQlDocumentComplexityScorer {
if (selection instanceof Field field) {
total =
Math.addExact(
GraphQlComplexityCalculator.saturatedAdd(
total,
fieldCost(schema, parent, field, fragments, variables, counter, expansionPath));
fieldCost(
schema,
parent,
field,
fragments,
variables,
counter,
expansionPath,
listsAreThePage));
} else if (selection instanceof InlineFragment inlineFragment) {
GraphQLFieldsContainer target =
inlineFragment.getTypeCondition() == null
? parent
: fieldsContainer(schema, inlineFragment.getTypeCondition().getName());
total =
Math.addExact(
GraphQlComplexityCalculator.saturatedAdd(
total,
selectionSetCost(
schema,
@@ -155,7 +187,8 @@ public final class GraphQlDocumentComplexityScorer {
fragments,
variables,
counter,
expansionPath));
expansionPath,
listsAreThePage));
} else if (selection instanceof FragmentSpread spread) {
FragmentDefinition fragment = fragments.get(spread.getName());
// A fragment already on this path is a cycle. Validation rejects it, but the scorer must
@@ -169,7 +202,7 @@ public final class GraphQlDocumentComplexityScorer {
: fieldsContainer(schema, fragment.getTypeCondition().getName());
expansionPath.push(spread.getName());
total =
Math.addExact(
GraphQlComplexityCalculator.saturatedAdd(
total,
selectionSetCost(
schema,
@@ -178,7 +211,8 @@ public final class GraphQlDocumentComplexityScorer {
fragments,
variables,
counter,
expansionPath));
expansionPath,
listsAreThePage));
expansionPath.pop();
}
}
@@ -190,9 +224,10 @@ public final class GraphQlDocumentComplexityScorer {
GraphQLFieldsContainer parent,
Field field,
Map<String, FragmentDefinition> fragments,
Map<String, Object> variables,
PageVariables variables,
Counter counter,
Deque<String> expansionPath) {
Deque<String> expansionPath,
boolean listsAreThePage) {
if (field.getName().startsWith(INTROSPECTION_FIELD_PREFIX)) {
// Introspection is an allow/deny decision made by the authorization stage. Pricing it here
@@ -202,53 +237,110 @@ public final class GraphQlDocumentComplexityScorer {
GraphQLFieldDefinition definition = parent.getFieldDefinition(field.getName());
String coordinate = parent.getName() + "." + field.getName();
GraphQLFieldsContainer childContainer =
definition == null ? null : fieldsContainer(unwrap(definition.getType()));
if (definition == null) {
// Validation rejects an unknown field; price what is there rather than invent a type.
return calculator.fieldCost(coordinate, 0).total();
}
int dimensions = listDimensions(definition.getType());
boolean paginated =
definition.getArgument(FIRST) != null
|| definition.getArgument(LAST) != null
|| calculator.connection(coordinate);
long childCost =
selectionSetCost(
schema,
childContainer,
fieldsContainer(definition.getType()),
field.getSelectionSet(),
fragments,
variables,
counter,
expansionPath);
expansionPath,
// A connection object's own lists are the page it was charged for.
paginated && dimensions == 0);
Integer first = pageArgument(field, "first", variables);
Integer last = pageArgument(field, "last", variables);
if (first != null || last != null) {
if (paginated) {
Integer first = pageArgument(definition, field, FIRST, variables);
Integer last = pageArgument(definition, field, LAST, variables);
return calculator.connectionCost(coordinate, first, last, childCost).total();
}
if (dimensions > 0 && !listsAreThePage) {
return calculator.listCost(coordinate, dimensions, childCost).total();
}
return calculator.fieldCost(coordinate, childCost).total();
}
private static Integer pageArgument(Field field, String name, Map<String, Object> variables) {
/**
* The page a field will be asked for, or {@code null} when nothing names one.
*
* <p>An argument the document leaves out still reaches the resolver as the schema default, so
* that default is the page; an explicit {@code null} is not replaced by it.
*/
private static Integer pageArgument(
GraphQLFieldDefinition definition, Field field, String name, PageVariables variables) {
for (Argument argument : field.getArguments()) {
if (!argument.getName().equals(name)) {
continue;
if (argument.getName().equals(name)) {
return intValue(argument.getValue(), variables);
}
return intValue(argument.getValue(), variables);
}
return null;
GraphQLArgument declared = definition.getArgument(name);
if (declared == null || !declared.hasSetDefaultValue()) {
return null;
}
InputValueWithState fallback = declared.getArgumentDefaultValue();
if (fallback.isLiteral() && fallback.getValue() instanceof Value<?> literal) {
return intValue(literal, variables);
}
return fallback.isExternal() ? intValue(fallback.getValue()) : null;
}
private static Integer intValue(Value<?> value, Map<String, Object> variables) {
private static Integer intValue(Value<?> value, PageVariables variables) {
if (value instanceof IntValue intValue) {
BigInteger raw = intValue.getValue();
// A literal outside int range cannot be a page size; treating it as the maximum lets the
// calculator reject it rather than silently overflowing to something affordable.
return raw.bitLength() >= Integer.SIZE ? Integer.MAX_VALUE : raw.intValue();
if (raw.bitLength() >= Integer.SIZE) {
return raw.signum() < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
return raw.intValue();
}
if (value instanceof VariableReference reference) {
Object supplied = variables.get(reference.getName());
if (supplied instanceof Number number) {
long asLong = number.longValue();
return asLong > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) asLong;
}
return variables.resolve(reference.getName());
}
return null;
}
private static Integer intValue(Object supplied) {
if (!(supplied instanceof Number number)) {
// Not an Int: coercion rejects it after this stage, and pricing it as no page is the same
// answer the resolver would give an absent argument.
return null;
}
BigDecimal exact = new BigDecimal(number.toString());
if (exact.compareTo(BigDecimal.valueOf(Integer.MAX_VALUE)) > 0) {
return Integer.MAX_VALUE;
}
if (exact.compareTo(BigDecimal.valueOf(Integer.MIN_VALUE)) < 0) {
return Integer.MIN_VALUE;
}
return exact.intValue();
}
private static int listDimensions(GraphQLType type) {
int dimensions = 0;
GraphQLType current = type;
while (true) {
if (current instanceof GraphQLNonNull nonNull) {
current = nonNull.getWrappedType();
} else if (current instanceof GraphQLList list) {
dimensions++;
current = list.getWrappedType();
} else {
return dimensions;
}
}
}
private static GraphQLObjectType rootType(GraphQLSchema schema, OperationDefinition operation) {
OperationDefinition.Operation kind =
operation.getOperation() == null
@@ -282,6 +374,36 @@ public final class GraphQlDocumentComplexityScorer {
return current;
}
/**
* The values a variable reference can stand for, before graphql-java coerces them.
*
* <p>The request map holds only what the client sent. A variable it left out takes the
* operation's declared default, which is the value the resolver will see — reading the request
* map alone priced {@code ($n: Int = 100000)} as if no page had been asked for. A variable the
* client sent as {@code null} stays {@code null}; it does not fall back to the default.
*/
private record PageVariables(Map<String, Object> supplied, Map<String, Value<?>> defaults) {
static PageVariables of(OperationDefinition operation, Map<String, Object> supplied) {
Map<String, Value<?>> defaults = new LinkedHashMap<>();
for (VariableDefinition definition : operation.getVariableDefinitions()) {
if (definition.getDefaultValue() != null) {
defaults.put(definition.getName(), definition.getDefaultValue());
}
}
return new PageVariables(supplied == null ? Map.of() : supplied, defaults);
}
Integer resolve(String name) {
if (supplied.containsKey(name)) {
return intValue(supplied.get(name));
}
Value<?> fallback = defaults.get(name);
// A default is a constant literal by the grammar, so it cannot refer to another variable.
return fallback instanceof IntValue ? intValue(fallback, this) : null;
}
}
private static final class Counter {
private int visited;
@@ -9,10 +9,20 @@ import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate;
* @param baseCost fixed cost of resolving the field once
* @param resolverWeight what the resolver actually does
* @param connection whether the field returns a paginated connection, whose children multiply by
* page size
* page size even when it declares no {@code first}/{@code last} argument
* @param estimatedListSize how many elements a list-returning field without page arguments is
* expected to hold, multiplied into its children's cost; {@link #UNDECLARED_LIST_SIZE} means
* "not declared" and the client policy's default page size is used instead
*/
public record GraphQlFieldCostDescriptor(
String coordinate, long baseCost, GraphQlResolverWeight resolverWeight, boolean connection) {
String coordinate,
long baseCost,
GraphQlResolverWeight resolverWeight,
boolean connection,
int estimatedListSize) {
/** No list size was declared; a plain list is then priced at the default page size. */
public static final int UNDECLARED_LIST_SIZE = 0;
public GraphQlFieldCostDescriptor {
GraphQlSchemaCoordinate.parse(coordinate);
@@ -22,6 +32,15 @@ public record GraphQlFieldCostDescriptor(
if (resolverWeight == null) {
throw new IllegalArgumentException("resolver weight is required");
}
if (estimatedListSize < UNDECLARED_LIST_SIZE) {
throw new IllegalArgumentException("estimated list size cannot be negative");
}
}
/** A descriptor that leaves a plain list's size to the default page size. */
public GraphQlFieldCostDescriptor(
String coordinate, long baseCost, GraphQlResolverWeight resolverWeight, boolean connection) {
this(coordinate, baseCost, resolverWeight, connection, UNDECLARED_LIST_SIZE);
}
/** Base cost plus resolver weight, before any cardinality multiplier. */
@@ -17,8 +17,10 @@ import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.IntStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@@ -187,6 +189,48 @@ class GraphQlPlatformExecutionPathTest {
assertThatRejected(response, "GRAPHQL_COMPLEXITY_EXCEEDED");
}
@Test
@DisplayName("page 인자를 생략한 list 는 기본 page 크기로 곱해져 resolver 전에 복잡도 초과로 거부된다")
void aPageOmittedListIsPricedAtTheDefaultPageAndRejected() {
// when
ResponseEntity<String> response = post("{ platformPage { id } }");
// then
assertThatRejected(response, "GRAPHQL_COMPLEXITY_EXCEEDED");
}
@Test
@DisplayName("page 인자가 없는 일반 list 를 중첩하면 원소 수만큼 곱해져 resolver 전에 거부된다")
void aNestedPlainListIsMultipliedAndRejected() {
// when
ResponseEntity<String> response = post("{ platformNodes { id child { id } } }");
// then
assertThatRejected(response, "GRAPHQL_COMPLEXITY_EXCEEDED");
}
@Test
@DisplayName("변수 기본값으로 숨긴 page 크기가 상한을 넘으면 resolver 전에 거부된다")
void aPageSizeHiddenInAVariableDefaultIsRejected() {
// when
ResponseEntity<String> response =
post("query P($n: Int = 100000) { platformPage(first: $n) { id } }");
// then
assertThatRejected(response, "GRAPHQL_COMPLEXITY_EXCEEDED");
}
@Test
@DisplayName("예산 안의 작은 page 는 list resolver 까지 도달한다")
void aSmallPageWithinTheBudgetReachesTheResolver() {
// when
ResponseEntity<String> response = post("{ platformPage(first: 2) { id } }");
// then
assertThat(response.getBody()).contains("\"platformPage\":[{\"id\":\"p-0\"},{\"id\":\"p-1\"}]");
assertThat(RESOLVER_INVOCATIONS).hasValue(1);
}
@Test
void anUnauthorizedCoordinateIsRejectedBeforeAnyResolverRuns() {
ResponseEntity<String> response = post("{ platformSecret }");
@@ -376,6 +420,21 @@ class GraphQlPlatformExecutionPathTest {
return "must-never-be-returned";
}
@QueryMapping
List<PlatformNode> platformPage(@Argument Integer first) {
RESOLVER_INVOCATIONS.incrementAndGet();
int size = first == null ? 0 : first;
return IntStream.range(0, size)
.mapToObj(index -> new PlatformNode("p-" + index, "page-" + index, null))
.toList();
}
@QueryMapping
List<PlatformNode> platformNodes() {
RESOLVER_INVOCATIONS.incrementAndGet();
return List.of();
}
/** Reports which of the three variable cases actually reached coercion. */
@QueryMapping
String platformEcho(@Argument String value) {
@@ -429,7 +488,7 @@ class GraphQlPlatformExecutionPathTest {
}
/**
* A deny-by-default policy with three coordinates opened.
* A deny-by-default policy with the coordinates under test opened.
*
* <p>Deliberately the fail-closed shape an adopter is expected to ship, so the denial test is
* exercising the same configuration a production deployment would have rather than a special
@@ -445,6 +504,8 @@ class GraphQlPlatformExecutionPathTest {
.allow(GraphQlSchemaCoordinate.parse("Query.platformNode"), anonymous)
.allow(GraphQlSchemaCoordinate.parse("Query.platformStamp"), anonymous)
.allow(GraphQlSchemaCoordinate.parse("Query.platformEcho"), anonymous)
.allow(GraphQlSchemaCoordinate.parse("Query.platformPage"), anonymous)
.allow(GraphQlSchemaCoordinate.parse("Query.platformNodes"), anonymous)
.build();
}
}
@@ -1,8 +1,9 @@
# Schema used by the execution-path evidence test.
#
# Shaped to exercise the policies the platform claims to enforce: a self-referencing type for depth,
# a repeatable field for alias budgets, a coordinate the authorization policy denies, and a custom
# scalar so wiring and coercion are proved on a real request rather than in a unit test.
# a repeatable field for alias budgets, a coordinate the authorization policy denies, a custom
# scalar so wiring and coercion are proved on a real request rather than in a unit test, and two
# list fields — one paginated, one plain — so list cardinality is priced on the real path.
scalar Instant
@@ -14,6 +15,9 @@ extend type Query {
# The argument default is what makes the three variable cases distinguishable at the resolver:
# an omitted variable falls back to it, an explicit null does not.
platformEcho(value: String = "default-applied"): String!
platformPage(first: Int): [PlatformNode!]!
platformNodes: [PlatformNode!]!
}
type PlatformNode {
@@ -0,0 +1,262 @@
package dev.caskeleton.adapter.inbound.graphql.cost;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import graphql.language.Document;
import graphql.language.OperationDefinition;
import graphql.parser.Parser;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* A list-returning field costs its children once per element, however the client asks for it.
*
* <p>Every number below is priced against the production default: an empty catalogue, so each field
* is the conservative unregistered weight (base 10, weighted 20), a default page of 20 and a
* maximum page of 100. The review probe (2026-11-01, 03-01) measured {@code items(first: 20)} at
* 410 while {@code items} alone was 40 and four nested lists were 100 — the omitted argument, the
* variable default and the plain list each skipped the multiplication the explicit literal got.
*/
class GraphQlDocumentComplexityScorerTest {
private static final String SDL =
"""
type Query {
items(first: Int, last: Int): [Item!]!
pagedWithDefault(first: Int = 50): [Item!]!
itemConnection(first: Int): ItemConnection
node: Item
}
type Item {
name: String!
children: [Item!]!
grid: [[Item!]!]!
}
type ItemConnection {
edges: [ItemEdge!]!
}
type ItemEdge {
node: Item!
}
""";
private static final GraphQLSchema SCHEMA =
new SchemaGenerator()
.makeExecutableSchema(
new SchemaParser().parse(SDL), RuntimeWiring.newRuntimeWiring().build());
private static final long BUDGET = 10_000;
private final GraphQlComplexityCalculator calculator =
new GraphQlComplexityCalculator(GraphQlCostCatalog.of(), 20, 100);
@Test
@DisplayName("first 를 명시한 page 는 하위 비용을 그 크기만큼 곱한다")
void anExplicitPageMultipliesChildrenByThePageSize() {
// when
long score = score("query Q { items(first: 20) { name } }", Map.of());
// then
assertThat(score).isEqualTo(10L + 20L * 20L);
}
@Test
@DisplayName("first 를 생략한 page 는 기본 page 크기로 곱해서 명시한 기본 page 와 같은 점수다")
void anOmittedPageArgumentCostsTheDefaultPage() {
// when
long score = score("query Q { items { name } }", Map.of());
// then
assertThat(score).isEqualTo(score("query Q { items(first: 20) { name } }", Map.of()));
}
@Test
@DisplayName("first 에 명시한 null 은 생략과 같아서 기본 page 크기로 곱한다")
void anExplicitNullPageArgumentCostsTheDefaultPage() {
// when
long score = score("query Q { items(first: null) { name } }", Map.of());
// then
assertThat(score).isEqualTo(10L + 20L * 20L);
}
@Test
@DisplayName("일반 list 를 4단 중첩하면 점수가 단마다 곱으로 늘어 예산을 넘는다")
void nestedPlainListsMultiplyRatherThanAdd() {
// given
String document = "query Q { items { children { children { children { name } } } } }";
// when
long score = score(document, Map.of());
// then
long innermost = 20L + 20L * 20L;
long second = 20L + 20L * innermost;
long first = 20L + 20L * second;
assertThat(score).isEqualTo(10L + 20L * first);
assertThatThrownBy(() -> calculator.verify(new GraphQlComplexityResult(score), BUDGET))
.isInstanceOf(GraphQlComplexityRejectedException.class);
}
@Test
@DisplayName("변수 기본값으로 숨긴 page 크기도 상한을 넘으면 page size exceeds maximum 으로 거부된다")
void aPageSizeHiddenInAVariableDefaultIsCheckedAgainstTheMaximum() {
// given
String document = "query Q($n: Int = 100000) { items(first: $n) { name } }";
// when
Throwable thrown = catchThrowable(() -> score(document, Map.of()));
// then
assertThat(thrown)
.isInstanceOf(GraphQlComplexityRejectedException.class)
.hasMessageContaining("page size exceeds maximum");
}
@Test
@DisplayName("요청이 보낸 변수 값은 변수 기본값보다 우선한다")
void aSuppliedVariableOverridesItsDefault() {
// when
long score = score("query Q($n: Int = 100000) { items(first: $n) { name } }", Map.of("n", 5));
// then
assertThat(score).isEqualTo(10L + 5L * 20L);
}
@Test
@DisplayName("요청이 변수에 명시한 null 은 기본값을 쓰지 않고 기본 page 크기로 곱한다")
void anExplicitNullVariableCostsTheDefaultPage() {
// given
Map<String, Object> variables = new HashMap<>();
variables.put("n", null);
// when
long score = score("query Q($n: Int = 100000) { items(first: $n) { name } }", variables);
// then
assertThat(score).isEqualTo(10L + 20L * 20L);
}
@Test
@DisplayName("스키마가 page 인자에 준 기본값은 생략했을 때 resolver 가 받는 값이라 그 크기로 곱한다")
void aSchemaArgumentDefaultIsThePageAnOmittedArgumentGets() {
// when
long score = score("query Q { pagedWithDefault { name } }", Map.of());
// then
assertThat(score).isEqualTo(10L + 50L * 20L);
}
@Test
@DisplayName("last 만 상한을 넘어도 first 가 있다는 이유로 통과하지 않는다")
void bothPageArgumentsAreCheckedAgainstTheMaximum() {
// given
String document = "query Q { items(first: 1, last: 100000) { name } }";
// when
Throwable thrown = catchThrowable(() -> score(document, Map.of()));
// then
assertThat(thrown)
.isInstanceOf(GraphQlComplexityRejectedException.class)
.hasMessageContaining("page size exceeds maximum");
}
@Test
@DisplayName("cost catalog 에 선언한 list 추정 크기가 기본 page 크기 대신 곱해진다")
void aDeclaredListSizeReplacesTheDefaultMultiplier() {
// given
var declared =
new GraphQlComplexityCalculator(
GraphQlCostCatalog.of(
new GraphQlFieldCostDescriptor(
"Item.children", 2, GraphQlResolverWeight.PROPERTY, false, 3)),
20,
100);
// when
long score = score(declared, "query Q { items(first: 1) { children { name } } }", Map.of());
// then
assertThat(score).isEqualTo(10L + 1L * ((2L + 1L) + 3L * 20L));
}
@Test
@DisplayName("list 안의 list 는 차원마다 한 번씩 곱한다")
void eachListDimensionMultipliesOnce() {
// when
long score = score("query Q { node { grid { name } } }", Map.of());
// then
assertThat(score).isEqualTo(20L + (20L + 20L * 20L * 20L));
}
@Test
@DisplayName("connection 객체 안의 edges 는 connection 이 이미 곱한 그 page 라서 다시 곱하지 않는다")
void aConnectionsEdgesAreThePageTheConnectionAlreadyPaidFor() {
// when
long score =
score("query Q { itemConnection(first: 5) { edges { node { name } } } }", Map.of());
// then
assertThat(score).isEqualTo(10L + 5L * (20L + (20L + 20L)));
}
@Test
@DisplayName("page 인자를 생략한 connection 은 기본 page 크기로 곱한다")
void anOmittedConnectionPageCostsTheDefaultPage() {
// when
long score = score("query Q { itemConnection { edges { node { name } } } }", Map.of());
// then
assertThat(score).isEqualTo(10L + 20L * (20L + (20L + 20L)));
}
@Test
@DisplayName("곱이 long 범위를 넘을 만큼 깊은 list 도 산술 오류가 아니라 예산 초과로 거부된다")
void anOverflowingScoreSaturatesAndIsRejectedByTheBudget() {
// given
String document =
"query Q { items { " + "children { ".repeat(20) + "name" + " }".repeat(21) + " }";
// when
long score = score(document, Map.of());
// then
assertThat(score).isEqualTo(Long.MAX_VALUE);
assertThatThrownBy(() -> calculator.verify(new GraphQlComplexityResult(score), BUDGET))
.isInstanceOf(GraphQlComplexityRejectedException.class);
}
@Test
@DisplayName("list 가 아닌 단일 객체 필드는 하위 비용을 곱하지 않고 더한다")
void aSingleObjectFieldAddsItsChildrenOnce() {
// when
long score = score("query Q { node { name } }", Map.of());
// then
assertThat(score).isEqualTo(20L + 20L);
}
private long score(String source, Map<String, Object> variables) {
return score(calculator, source, variables);
}
private static long score(
GraphQlComplexityCalculator calculator, String source, Map<String, Object> variables) {
Document document = Parser.parse(source);
OperationDefinition operation =
document.getDefinitionsOfType(OperationDefinition.class).getFirst();
return new GraphQlDocumentComplexityScorer(calculator)
.score(SCHEMA, document, operation, variables)
.total();
}
}
@@ -38,3 +38,9 @@ strictTestLanes {
jvmArgs '-Duser.timezone=UTC'
}
}
// The tests run in `test` already; the main stage runs the lane so its fail-closed selection is
// proven before release.yml names it, not first there (review 2026-11-01 08-01).
tasks.named('mainCheck') {
dependsOn 'webAdvancedTest'
}
+3 -2
View File
@@ -24,8 +24,9 @@ Package root: `dev.caskeleton.adapter.inbound.web`.
Every service ships this leaf, so it holds only what the servlet production path reaches: its
`AutoConfiguration.imports` roots (`WebAdapterAutoConfiguration` imports the envelope, filters,
health and rate-limit beans; `WebSecurityAutoConfiguration` imports the JWT chain, method security
and permission port, so an application with its own posture excludes only that root; nobody scans
health and rate-limit beans; `WebSecurityAutoConfiguration` imports the JWT chain, so an application
with its own posture excludes only that root; `WebMethodSecurityAutoConfiguration` imports method
security and the permission port and stays when the chain is replaced; nobody scans
this leaf), and the types
`app-bootstrap`, `sample-portfolio`, `web-fileserver` and `composition:fileserver-platform` name —
plus their transitive references. Library code that no production path reaches (streaming, virtual
+26 -5
View File
@@ -41,8 +41,14 @@ production configuration and compare the result with the committed snapshot.
- Spring Boot auto-config decoder 를 대체해 validator chain 을 기본값 의존이 아닌 **명시적 구성**으로 만든다.
- **D2 — clock skew 60s 명시 고정**(`JwtTimestampValidator`). framework 기본값에 의존하면 Spring
업그레이드로 기본값이 바뀔 때 silent-drift 위험이 있어 여기서 못박는다.
- **D4 — issuer 검증**(`SecuritySettings.issuerUri()`). **D3 — audience 검증**(`SecuritySettings.audience()`),
단 blank audience 면 검사 건너뜀(기존 settings 계약과 일치).
- **D4 — issuer 검증**(`SecuritySettings.issuerUri()`). **D3 — audience 검증**(`SecuritySettings.audience()`).
JWT 모드에서 audience 는 필수이고(비면 기동 실패, 메시지에 `APP_SECURITY_JWT_AUDIENCE`), 쉼표 목록을
받는다. 토큰 `aud` 가 설정 목록 중 하나라도 담으면 통과한다. "비우면 검사 생략"은 없앴다 — 같은
issuer 의 다른 client 용 토큰이 통과하기 때문이다(2026-11-01 리뷰 02-03·07-05, 소유자 결정 대안 A).
버린 대안: prod 프로필에서만 필수(dev·staging 이 열리고 보안이 프로필 이름에 걸린다), 문서 강조만.
- **role 범위**: `JwtToAuthenticatedPrincipalConverter` 는 `realm_access.roles` 와, `resource_access` 중
**audience 목록에 있는 client** 의 roles 만 읽는다. 다른 client 가 같은 이름의 role 을 정의해도 이
서비스 권한이 되지 않는다. client id 와 audience 가 다른 IdP 구성이 생기면 별도 키를 둔다(지금은 없음).
- **JWKS lazy discovery** (`SupplierJwtDecoder`): 기동 시 IdP 가 reachable 일 필요가 없고, 첫 decode
시점에 issuer-uri/`.well-known` 네트워크 호출이 일어난다(Spring Boot auto-config 와 동일한 lazy 동작).
lazy 초기화 중 외부 discovery/JWKS I/O 실패는 필터 밖 runtime exception으로 탈출시키지 않고
@@ -121,6 +127,14 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
## authz — 인가 (`@RequiresPermission` 강제)
### WebMethodSecurityAutoConfiguration — 인가는 인증 체인과 따로 켜진다
- `MethodSecurityConfig`·`AuthorizationAdapter`·`RolePermissionRegistry`·`RolePermissionPolicy`(`app.authz`)는
`WebSecurityAutoConfiguration`(JWT/session 체인)이 아니라 이 auto-configuration이 들여온다.
- 이유: 인증 방식(체인)을 바꾸는 애플리케이션은 `WebSecurityAutoConfiguration`만 뺀다. 둘이 한 root에
있을 때는 체인을 빼면 advisor도 같이 빠져서, 그 애플리케이션의 `@RequiresPermission`이 아무 경고 없이
주석이 됐다(샘플이 그랬다 — 익명 삭제 가능). 이제 체인을 바꿔도 권한 검사는 남는다.
- 메서드 보안까지 끄려면 이 클래스를 따로 exclude 해야 한다. 그 결정은 exclude 목록에 이름으로 드러난다.
### MethodSecurityConfig
- `RequiresPermission` 강제 지점을 Spring method security 에 배선한다.
- `@EnableMethodSecurity(prePostEnabled = false)` — method-security 인프라는 켜되 `@PreAuthorize`/
@@ -213,8 +227,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
| `PageValidationException` | `VALIDATION_FAILED` | 400 | D18/D20/D21: 계약 범위 밖 페이지/정렬/필터 파라미터. field + reasonCode 를 details 로 |
| `IdempotencyUnavailableException` | `IDEMPOTENCY_UNAVAILABLE` | 503 (retryable=true) | 조정 저장소가 응답하지 않아 action 전에 거부. carrier 분기 |
| `IdempotencyRecoveryRequiredException` | `IDEMPOTENCY_RECOVERY_REQUIRED` | 500 (retryable=false) | 이전 시도의 외부 효과 여부를 판단할 수 없음. carrier 분기 |
| `IdempotencyInFlightException` | `IDEMPOTENT_IN_FLIGHT` | 409 (retryable=false) | 같은 scope 의 다른 시도가 아직 처리 중(executor 는 기다리지 않는다). 진단정보(scope digest)는 클라이언트 미도달 |
| `IdempotencyRequestMismatchException` | `IDEMPOTENT_REQUEST_MISMATCH` | 422 | D8: `Idempotency-Key` 를 다른 본문으로 재사용. fingerprint/scope 노출 금지 |
| `IdempotencyInFlightException` | `IDEMPOTENT_IN_FLIGHT` | 409 (retryable=true, `Retry-After: 2`) | 같은 scope 의 다른 시도가 아직 처리 중(executor 는 기다리지 않는다). 클라이언트 행동: 결과 불명. 같은 `Idempotency-Key`로 `Retry-After` 뒤 재전송. 새 키 금지(`docs/web/http-contract.md` §2). 진단정보(scope digest)는 클라이언트 미도달 |
| `IdempotencyRequestMismatchException` | `IDEMPOTENT_REQUEST_MISMATCH` | 422 (retryable=false) | D8: `Idempotency-Key` 를 다른 본문으로 재사용. 다시 보내지 않는다(`docs/web/http-contract.md` §2). fingerprint/scope 노출 금지 |
| `PersistenceFailureException` (JPA `JpaPersistenceException` 포함) | `ex.errorCode()` (사전분류 `DB_*`) | 코드 결정 | adapter-persistence translator 가 SQLState→`DB_*` 로 이미 분류, JPA 예외는 `FailureCategory`→`DB_*`. 클라이언트 메시지는 category 문구, **절대 `ex.getMessage()` 아님**(SQLState/제약명 담음, 서버 로그 전용) |
| `DependencyFailureException` | `ex.errorCode()` (사전분류 `DEPENDENCY_*`) | 코드 결정 | adapter-outbound `OutboundHttpErrorMapper` 가 upstream 실패를 분류. 클라이언트 메시지는 category 문구, **절대 `ex.getMessage()` 아님**. retryable + `retry_after_seconds` 있으면 `RetryAfterAdvisor` 로 `Retry-After` 부착 |
| `HttpRequestMethodNotSupportedException` | `METHOD_NOT_ALLOWED` | 405 | D12: 405 는 지원 메서드를 나열한 `Allow` 헤더 필수 |
@@ -238,7 +252,12 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
### EnvelopeBodyAdvice
- 컨트롤러는 도메인/DTO 타입을 반환하고, 이 advice 가 와이어 형태를 항상
`{success, data | error, traceId}` 로 보장한다.
`{success, data | error, meta}` 로 보장한다.
- **null 필드는 키째 생략한다.** 성공에는 `error` 키가, 실패에는 `data` 키가, 단일 아이템 `meta` 에는
`page` 키가 없다. 빈 목록은 생략하지 않는다. 규칙은 `EnvelopeWireFormatConfig` 의 Jackson mix-in 이
Boot `JsonMapper` 에 등록한다(shared-contract 는 Jackson 에 의존하지 않으므로 타입에 애너테이션을
달지 않는다). 키 목록과 근거는 `docs/web/http-contract.md` §1, 원문 키 집합 단언은
`EnvelopeWireShapeTest`.
- 위치: sample 모듈이 아니라 adapter-web. 실행 앱은 adapter-web 에 의존하지만 sample-portfolio 에는 의존하지
않으므로, 응답 래핑이 실제로 동작하려면 여기 있어야 한다.
@@ -417,6 +436,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
- 필드 `RETRY_AFTER_SECONDS` 는 error-codes.yaml 의 `retry_after_seconds` 컬럼 미러.
이 advisor 가 유일한 Retry-After 노출 지점이라 여기 중앙화한다.
`DEPENDENCY_4XX_CLIENT` 는 비재시도(retryable=false)라 `shouldAdvise` 가드로 empty 반환.
- `IDEMPOTENT_IN_FLIGHT` 는 2초: 기본 processing lease(30s)보다 짧아 첫 시도가 끝날 수 있는 동안
같은 키로 다시 묻게 한다. 근거와 클라이언트 행동은 `docs/web/http-contract.md` §2.
---
@@ -24,9 +24,9 @@ import org.springframework.web.client.RestClientException;
/**
* Custom {@link JwtDecoder} for the resource server with an explicit validator chain: timestamp
* (60s clock skew) + issuer, plus an optional audience check when configured. JWKS discovery is
* deferred via {@link SupplierJwtDecoder} so startup does not require the IdP to be reachable. See
* README for the design rationale.
* (60s clock skew) + issuer + audience (required). JWKS discovery is deferred via {@link
* SupplierJwtDecoder} so startup does not require the IdP to be reachable. See README for the
* design rationale.
*/
@Configuration
@ConditionalOnProperty(name = "app.security.auth-mode", havingValue = "jwt", matchIfMissing = true)
@@ -70,16 +70,21 @@ public class JwtDecoderConfig {
return false;
}
/** The explicit validator chain: timestamp (60s skew) + issuer + optional audience. */
static OAuth2TokenValidator<Jwt> jwtValidator(String issuerUri, String audience) {
/**
* The explicit validator chain: timestamp (60s skew) + issuer + audience. The token's {@code aud}
* must name at least one configured audience; an empty list is refused, never read as "skip".
*/
static OAuth2TokenValidator<Jwt> jwtValidator(String issuerUri, List<String> audiences) {
if (audiences.isEmpty()) {
throw new IllegalArgumentException(
"APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required");
}
List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
validators.add(
taggedValidator(
new JwtTimestampValidator(Duration.ofSeconds(60)), ERROR_TIMESTAMP_INVALID));
validators.add(taggedValidator(new JwtIssuerValidator(issuerUri), ERROR_ISSUER_MISMATCH));
if (audience != null && !audience.isBlank()) {
validators.add(audienceValidator(audience));
}
validators.add(audienceValidator(List.copyOf(audiences)));
return new DelegatingOAuth2TokenValidator<>(validators);
}
@@ -98,9 +103,10 @@ public class JwtDecoderConfig {
};
}
private static OAuth2TokenValidator<Jwt> audienceValidator(String audience) {
private static OAuth2TokenValidator<Jwt> audienceValidator(List<String> audiences) {
return jwt -> {
if (jwt.getAudience() != null && jwt.getAudience().contains(audience)) {
List<String> tokenAudience = jwt.getAudience();
if (tokenAudience != null && audiences.stream().anyMatch(tokenAudience::contains)) {
return OAuth2TokenValidatorResult.success();
}
OAuth2Error error =
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.inbound.web.auth;
import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings;
import dev.caskeleton.application.tenant.TenantId;
import java.util.ArrayList;
import java.util.Collection;
@@ -22,8 +23,12 @@ import org.springframework.stereotype.Component;
/**
* Maps an OIDC JWT to a JwtAuthenticationToken whose principal is our {@link
* AuthenticatedPrincipal}. We pull {@code sub} as the IdP user id and union Keycloak-style {@code
* realm_access.roles} with {@code resource_access[*].roles} into a single role set. Roles also
* become Spring authorities (ROLE_*).
* realm_access.roles} with {@code resource_access.<client>.roles} into a single role set. Roles
* also become Spring authorities (ROLE_*).
*
* <p>Only the clients named by {@code app.security.audience} contribute {@code resource_access}
* roles. Another client of the same issuer may define a role with the same name (for example {@code
* operation-submit}); reading every client would hand that role to this service.
*/
@Component
public class JwtToAuthenticatedPrincipalConverter
@@ -37,6 +42,13 @@ public class JwtToAuthenticatedPrincipalConverter
*/
public static final String TENANT_CLAIM = "tenant_id";
/** The clients whose {@code resource_access} roles this service honours: its own audiences. */
private final Set<String> roleClients;
public JwtToAuthenticatedPrincipalConverter(SecuritySettings settings) {
this.roleClients = Set.copyOf(settings.audience());
}
@Override
public AbstractAuthenticationToken convert(Jwt jwt) {
Set<String> roles = extractRoles(jwt);
@@ -79,8 +91,8 @@ public class JwtToAuthenticatedPrincipalConverter
}
Map<String, Object> resourceAccess = jwt.getClaimAsMap("resource_access");
if (resourceAccess != null) {
for (Object client : resourceAccess.values()) {
if (client instanceof Map<?, ?> clientMap
for (String clientId : roleClients) {
if (resourceAccess.get(clientId) instanceof Map<?, ?> clientMap
&& clientMap.get("roles") instanceof Collection<?> rolesCol) {
rolesCol.forEach(x -> roles.add(String.valueOf(x)));
}
@@ -0,0 +1,38 @@
package dev.caskeleton.adapter.inbound.web.envelope;
import com.fasterxml.jackson.annotation.JsonInclude;
import dev.caskeleton.shared.response.ApiError;
import dev.caskeleton.shared.response.BulkEnvelope;
import dev.caskeleton.shared.response.Envelope;
import dev.caskeleton.shared.response.ResponseMeta;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tools.jackson.databind.module.SimpleModule;
/**
* Leaves a {@code null} field of the response envelope types off the wire: a success body carries
* no {@code error} key, a failure body no {@code data} key, a single item no {@code meta.page}, and
* an error without details no {@code details}. An empty list is not {@code null} and stays.
*
* <p>The rule lives here, not as {@code @JsonInclude} on the records, because {@code
* shared-contract} depends on the Java standard library only. Boot registers every {@link
* SimpleModule} bean on its {@code JsonMapper}, which every HTTP writer in this adapter uses — the
* MVC converters and the filter-level writers alike. The wire contract this produces is {@code
* docs/web/http-contract.md}.
*/
@Configuration
public class EnvelopeWireFormatConfig {
@Bean
public SimpleModule envelopeWireFormatModule() {
SimpleModule module = new SimpleModule("EnvelopeWireFormatModule");
module.setMixInAnnotation(Envelope.class, OmitNullFields.class);
module.setMixInAnnotation(BulkEnvelope.class, OmitNullFields.class);
module.setMixInAnnotation(ApiError.class, OmitNullFields.class);
module.setMixInAnnotation(ResponseMeta.class, OmitNullFields.class);
return module;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
private abstract static class OmitNullFields {}
}
@@ -5,6 +5,7 @@ import dev.caskeleton.adapter.inbound.web.config.OpenApiContractConfig;
import dev.caskeleton.adapter.inbound.web.config.PresentationWebConfig;
import dev.caskeleton.adapter.inbound.web.controller.HealthcheckController;
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice;
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeWireFormatConfig;
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
import dev.caskeleton.adapter.inbound.web.filter.CacheControlFilter;
import dev.caskeleton.adapter.inbound.web.filter.RequestLoggingFilter;
@@ -20,8 +21,9 @@ import org.springframework.core.Ordered;
/**
* The HTTP adapter this leaf ships, minus its security posture: error envelope, filters, health
* endpoint, rate limiting and their settings. The JWT security chain and method security are {@link
* WebSecurityAutoConfiguration}, a separate root an application can exclude on its own.
* endpoint, rate limiting and their settings. The JWT security chain is {@link
* WebSecurityAutoConfiguration}, a separate root an application can exclude on its own; method
* security is {@link WebMethodSecurityAutoConfiguration}, which stays when the chain is replaced.
*
* <p>These used to be found by the composition root's component scan of the whole {@code
* dev.caskeleton} tree. Registering them here means an application gets them from this module being
@@ -44,6 +46,7 @@ import org.springframework.core.Ordered;
PresentationWebConfig.class,
HealthcheckController.class,
EnvelopeBodyAdvice.class,
EnvelopeWireFormatConfig.class,
GlobalExceptionHandler.class,
CacheControlFilter.class,
RequestLoggingFilter.class,
@@ -0,0 +1,25 @@
package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure;
import dev.caskeleton.adapter.inbound.web.authz.AuthorizationAdapter;
import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionPolicy;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
/**
* The enforcement of {@code @RequiresPermission}: the method-security advisor, the
* role-to-permission authorization port and the {@code app.authz} policy it reads.
*
* <p>Separate from {@link WebSecurityAutoConfiguration} because the two answer different questions.
* That root decides how a request is authenticated (the JWT or session chain) and an application
* with its own posture replaces it. This one decides whether an authenticated caller may run a use
* case, and replacing the way callers authenticate must not switch it off. While both lived in one
* root, excluding the chain removed the advisor too, and every {@code @RequiresPermission} in that
* application became a comment that nothing reported.
*/
@AutoConfiguration
@EnableConfigurationProperties(RolePermissionPolicy.class)
@Import({AuthorizationAdapter.class, MethodSecurityConfig.class, RolePermissionRegistry.class})
public class WebMethodSecurityAutoConfiguration {}
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure;
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
import dev.caskeleton.adapter.inbound.web.mvc.filter.JsonBodyLimitFilter;
import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter;
import dev.caskeleton.shared.tracing.ActiveTrace;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
@@ -51,13 +52,19 @@ public class WebMvcPlatformAutoConfiguration {
return new GlobalExceptionHandler(spanErrorRecorderProvider);
}
/** Assigns the correlation identifiers, validating anything a caller proposed. */
/**
* Assigns the correlation identifiers, validating anything a caller proposed. With a tracer in
* the composition the trace id is the tracer's: the filter runs inside Boot's server observation
* ({@code HIGHEST_PRECEDENCE + 1}), whose span is then the active one.
*/
@Bean
@ConditionalOnMissingBean
public WebMvcRequestIdFilter webMvcRequestIdFilter(WebMvcPlatformSettings properties) {
public WebMvcRequestIdFilter webMvcRequestIdFilter(
WebMvcPlatformSettings properties, ObjectProvider<ActiveTrace> activeTrace) {
return new WebMvcRequestIdFilter(
properties.trustInboundRequestId(),
org.springframework.core.Ordered.HIGHEST_PRECEDENCE + 10);
org.springframework.core.Ordered.HIGHEST_PRECEDENCE + 10,
activeTrace.getIfAvailable(() -> ActiveTrace.NONE));
}
/** Refuses a JSON body over the configured ceiling before the converter reads it. */
@@ -4,10 +4,6 @@ import dev.caskeleton.adapter.inbound.web.auth.JwtDecoderConfig;
import dev.caskeleton.adapter.inbound.web.auth.JwtToAuthenticatedPrincipalConverter;
import dev.caskeleton.adapter.inbound.web.auth.RedisSessionWebConfig;
import dev.caskeleton.adapter.inbound.web.auth.SecurityConfig;
import dev.caskeleton.adapter.inbound.web.authz.AuthorizationAdapter;
import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionPolicy;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry;
import dev.caskeleton.adapter.inbound.web.settings.CorsSettings;
import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings;
import org.springframework.boot.autoconfigure.AutoConfiguration;
@@ -17,13 +13,15 @@ import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
/**
* The production security posture this leaf ships: the JWT security filter chain, method security,
* the role-to-permission authorization port and their settings.
* How a request is authenticated in production: the JWT (or session) security filter chain, the
* envelope entry point and access-denied handler, CORS and their settings.
*
* <p>Separate from {@link WebAdapterAutoConfiguration} so an application that brings its own
* posture — the public demo sample, a contract fixture — excludes exactly this class and still gets
* the error envelope, filters, health endpoint and rate limiting from the web root. Before the
* split the only way to drop the security chain was to drop the whole root and component-scan the
* posture — the demo sample, a contract fixture — excludes exactly this class and still gets the
* error envelope, filters, health endpoint and rate limiting from the web root. Excluding it does
* not switch off {@code @RequiresPermission}: that is {@link WebMethodSecurityAutoConfiguration},
* which an application keeps while it replaces the chain. Before this root was split from the web
* root, the only way to drop the security chain was to drop the whole root and component-scan the
* leaf back in minus two classes, and every new controller in the leaf then arrived in that scan
* whether it was meant to or not.
*
@@ -33,18 +31,11 @@ import org.springframework.core.Ordered;
*/
@AutoConfiguration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@EnableConfigurationProperties({
CorsSettings.class,
RolePermissionPolicy.class,
SecuritySettings.class
})
@EnableConfigurationProperties({CorsSettings.class, SecuritySettings.class})
@Import({
JwtDecoderConfig.class,
JwtToAuthenticatedPrincipalConverter.class,
RedisSessionWebConfig.class,
SecurityConfig.class,
AuthorizationAdapter.class,
MethodSecurityConfig.class,
RolePermissionRegistry.class
SecurityConfig.class
})
public class WebSecurityAutoConfiguration {}
@@ -4,6 +4,7 @@ import dev.caskeleton.adapter.inbound.web.core.WebRequestId;
import dev.caskeleton.adapter.inbound.web.core.WebTraceId;
import dev.caskeleton.adapter.inbound.web.observability.HeaderSanitizer;
import dev.caskeleton.shared.observability.MdcKeys;
import dev.caskeleton.shared.tracing.ActiveTrace;
import dev.caskeleton.shared.tracing.TraceParent;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
@@ -31,7 +32,10 @@ import org.springframework.web.filter.OncePerRequestFilter;
* investigation ends up reading somebody else's exchange.
*
* <p>The trace id is different: propagating an inbound {@code traceparent} is the entire point of
* distributed tracing, so it is honoured when it parses, and replaced when it does not.
* distributed tracing, so it is honoured when it parses, and replaced when it does not. When a
* tracer is running, its server span already made that decision — it continued a valid inbound
* trace or started a new one — and the filter takes the span's context as it is, so the id in the
* response and the logs is the id the exported spans carry.
*
* <p>This is the one place the identifiers are made. It puts them on MDC and on the response before
* anything else runs — Spring Security included, so a {@code 401}/{@code 403} written inside the
@@ -65,6 +69,7 @@ public final class WebMvcRequestIdFilter extends OncePerRequestFilter implements
private final boolean trustInboundRequestId;
private final int order;
private final ActiveTrace activeTrace;
/** A filter that mints its own request ids and propagates a valid inbound trace. */
public WebMvcRequestIdFilter() {
@@ -79,8 +84,21 @@ public final class WebMvcRequestIdFilter extends OncePerRequestFilter implements
* @param order the filter order
*/
public WebMvcRequestIdFilter(boolean trustInboundRequestId, int order) {
this(trustInboundRequestId, order, ActiveTrace.NONE);
}
/**
* A filter that takes the trace context from a running tracer when one has a span active.
*
* @param trustInboundRequestId whether a client may choose the request id
* @param order the filter order; it must run inside the tracer's server observation for the
* active span to be the request's
* @param activeTrace the tracer's active span, or {@link ActiveTrace#NONE} without a tracer
*/
public WebMvcRequestIdFilter(boolean trustInboundRequestId, int order, ActiveTrace activeTrace) {
this.trustInboundRequestId = trustInboundRequestId;
this.order = order;
this.activeTrace = activeTrace;
}
@Override
@@ -145,7 +163,11 @@ public final class WebMvcRequestIdFilter extends OncePerRequestFilter implements
.orElseGet(() -> new WebRequestId(UUID.randomUUID().toString()));
}
private static TraceParent resolveTrace(HttpServletRequest request) {
private TraceParent resolveTrace(HttpServletRequest request) {
Optional<TraceParent> traced = activeTrace.current();
if (traced.isPresent()) {
return traced.get();
}
// A malformed traceparent is replaced rather than rejected: refusing the request would let an
// upstream misconfiguration take an API down, and the platform still needs a correlation id.
return TraceParent.parse(request.getHeader(TRACEPARENT_HEADER))
@@ -14,6 +14,9 @@ public final class RetryAfterAdvisor {
private static final Map<String, Integer> RETRY_AFTER_SECONDS =
Map.of(
"RATE_LIMIT_EXCEEDED", 1,
// Below the default processing lease (30s): the resend arrives while the first attempt
// can still finish, and an early resend costs one more 409. docs/web/http-contract.md.
"IDEMPOTENT_IN_FLIGHT", 2,
"AUTH_KID_UNKNOWN", 5,
"AUTH_JWKS_UNAVAILABLE", 30,
"DEPENDENCY_TIMEOUT", 2,
@@ -1,29 +1,29 @@
package dev.caskeleton.adapter.inbound.web.settings;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.ConstructorBinding;
/**
* Exclusive JWT or Redis-backed browser-session security policy bound from {@code app.security.*}.
*
* <p>In JWT mode both {@code issuerUri} and {@code audience} are required. {@code audience} is a
* comma-separated list: a token passes when its {@code aud} names any of them, and only those
* clients' {@code resource_access} roles are read.
*/
@ConfigurationProperties(prefix = "app.security")
public record SecuritySettings(
AuthenticationMode authMode,
String issuerUri,
String audience,
List<String> audience,
List<String> publicPaths,
SessionCookieSettings session) {
private static final Logger log = LoggerFactory.getLogger(SecuritySettings.class);
@ConstructorBinding
public SecuritySettings(
AuthenticationMode authMode,
String issuerUri,
String audience,
List<String> audience,
List<String> publicPaths,
SessionCookieSettings session) {
this.authMode = authMode == null ? AuthenticationMode.JWT : authMode;
@@ -32,13 +32,15 @@ public record SecuritySettings(
"APP_SECURITY_JWT_ISSUER (app.security.issuer-uri) is required");
}
this.issuerUri = issuerUri == null ? "" : issuerUri.trim();
if (audience == null) {
if (this.authMode == AuthenticationMode.JWT) {
log.warn("APP_SECURITY_JWT_AUDIENCE is missing; skipping audience validation");
}
this.audience = "";
} else {
this.audience = audience.trim();
this.audience =
audience == null
? List.of()
: audience.stream().map(String::trim).filter(value -> !value.isEmpty()).toList();
if (this.authMode == AuthenticationMode.JWT && this.audience.isEmpty()) {
// No "skip the check" default: a token minted for another client of the same issuer must
// not authenticate here.
throw new IllegalArgumentException(
"APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required");
}
if (publicPaths == null) {
this.publicPaths = List.of();
@@ -48,7 +50,7 @@ public record SecuritySettings(
this.session = session == null ? SessionCookieSettings.defaults() : session;
}
public SecuritySettings(String issuerUri, String audience, List<String> publicPaths) {
public SecuritySettings(String issuerUri, List<String> audience, List<String> publicPaths) {
this(AuthenticationMode.JWT, issuerUri, audience, publicPaths, null);
}
@@ -1,3 +1,4 @@
dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration
dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration
dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMethodSecurityAutoConfiguration
dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMvcPlatformAutoConfiguration
@@ -1,11 +1,14 @@
package dev.caskeleton.adapter.inbound.web.auth;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jwt.Jwt;
@@ -21,7 +24,7 @@ class JwtDecoderConfigTest {
private static final String AUDIENCE = "ca-skeleton-api";
private final OAuth2TokenValidator<Jwt> validator =
JwtDecoderConfig.jwtValidator(ISSUER, AUDIENCE);
JwtDecoderConfig.jwtValidator(ISSUER, List.of(AUDIENCE));
private Jwt.Builder validJwt() {
Instant now = Instant.now();
@@ -76,11 +79,44 @@ class JwtDecoderConfigTest {
}
@Test
void blankAudienceSkipsTheAudienceCheck() {
OAuth2TokenValidator<Jwt> noAud = JwtDecoderConfig.jwtValidator(ISSUER, "");
Jwt jwt = validJwt().audience(List.of("anything")).build();
assertThat(noAud.validate(jwt).hasErrors())
.as("a blank configured audience disables audience validation")
.isFalse();
@DisplayName("설정한 audience 목록 중 하나라도 토큰 aud에 있으면 통과한다")
void aTokenNamingAnyConfiguredAudiencePasses() {
// given
OAuth2TokenValidator<Jwt> listed =
JwtDecoderConfig.jwtValidator(ISSUER, List.of("ca-skeleton-admin", AUDIENCE));
Jwt jwt = validJwt().audience(List.of("account", AUDIENCE)).build();
// when
OAuth2TokenValidatorResult result = listed.validate(jwt);
// then
assertThat(result.hasErrors()).isFalse();
}
@Test
@DisplayName("토큰에 aud claim이 없으면 AUTH_AUDIENCE_MISMATCH 오류 코드로 거부한다")
void aTokenWithoutAnAudClaimIsRejectedAsAudienceMismatch() {
// given
Jwt jwt = validJwt().claims(claims -> claims.remove("aud")).build();
// when
OAuth2TokenValidatorResult result = validator.validate(jwt);
// then
assertThat(result.getErrors())
.extracting(OAuth2Error::getErrorCode)
.containsExactly(JwtDecoderConfig.ERROR_AUDIENCE_MISMATCH);
}
@Test
@DisplayName("audience 목록이 비면 검사를 건너뛰지 않고 검증기 조립을 거부한다")
void anEmptyAudienceListIsRefusedInsteadOfSkippingTheCheck() {
// when
Throwable thrown = catchThrowable(() -> JwtDecoderConfig.jwtValidator(ISSUER, List.of()));
// then
assertThat(thrown)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("APP_SECURITY_JWT_AUDIENCE");
}
}
@@ -3,9 +3,11 @@ package dev.caskeleton.adapter.inbound.web.auth;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings;
import dev.caskeleton.application.tenant.TenantId;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.security.core.GrantedAuthority;
@@ -14,6 +16,8 @@ import org.springframework.security.oauth2.server.resource.InvalidBearerTokenExc
class JwtToAuthenticatedPrincipalConverterTest {
private static final String OWN_CLIENT = "ca-skeleton-api";
@Test
void roleAuthoritiesUseLocaleIndependentUppercase() {
Locale originalDefault = Locale.getDefault();
@@ -26,7 +30,7 @@ class JwtToAuthenticatedPrincipalConverterTest {
.claim("roles", List.of("admin"))
.build();
var authentication = new JwtToAuthenticatedPrincipalConverter().convert(jwt);
var authentication = converter().convert(jwt);
assertThat(authentication.getAuthorities())
.extracting(GrantedAuthority::getAuthority)
@@ -42,7 +46,7 @@ class JwtToAuthenticatedPrincipalConverterTest {
Jwt jwt = token().claim(JwtToAuthenticatedPrincipalConverter.TENANT_CLAIM, "acme").build();
// when
var authentication = new JwtToAuthenticatedPrincipalConverter().convert(jwt);
var authentication = converter().convert(jwt);
// then
assertThat(((AuthenticatedPrincipal) authentication.getPrincipal()).tenant())
@@ -52,7 +56,7 @@ class JwtToAuthenticatedPrincipalConverterTest {
@Test
void aTokenWithoutATenantClaimHasNoTenant() {
// when
var authentication = new JwtToAuthenticatedPrincipalConverter().convert(token().build());
var authentication = converter().convert(token().build());
// then
assertThat(((AuthenticatedPrincipal) authentication.getPrincipal()).tenant()).isEmpty();
@@ -65,8 +69,7 @@ class JwtToAuthenticatedPrincipalConverterTest {
Jwt jwt = token().claim(JwtToAuthenticatedPrincipalConverter.TENANT_CLAIM, "ac me").build();
// when
Throwable thrown =
catchThrowable(() -> new JwtToAuthenticatedPrincipalConverter().convert(jwt));
Throwable thrown = catchThrowable(() -> converter().convert(jwt));
// then
assertThat(thrown)
@@ -74,6 +77,56 @@ class JwtToAuthenticatedPrincipalConverterTest {
.hasMessage("the token's tenant claim is malformed");
}
@Test
@DisplayName("같은 issuer의 다른 client role은 이 서비스의 권한이 되지 않는다")
void anotherClientsRolesGrantNoAuthority() {
// given
Jwt jwt =
token()
.claim(
"resource_access",
Map.of("other-app", Map.of("roles", List.of("operation-submit"))))
.build();
// when
var authentication = converter().convert(jwt);
// then
assertThat(authentication.getAuthorities()).isEmpty();
assertThat(((AuthenticatedPrincipal) authentication.getPrincipal()).roles()).isEmpty();
}
@Test
@DisplayName("설정한 client의 role과 realm role은 권한이 된다")
void theOwnClientsRolesAndRealmRolesBecomeAuthorities() {
// given
Jwt jwt =
token()
.claim("realm_access", Map.of("roles", List.of("user")))
.claim(
"resource_access",
Map.of(
OWN_CLIENT,
Map.of("roles", List.of("operation-submit")),
"other-app",
Map.of("roles", List.of("file-admin"))))
.build();
// when
var authentication = converter().convert(jwt);
// then
assertThat(authentication.getAuthorities())
.extracting(GrantedAuthority::getAuthority)
.containsExactlyInAnyOrder("ROLE_USER", "ROLE_OPERATION-SUBMIT");
}
private static JwtToAuthenticatedPrincipalConverter converter() {
return new JwtToAuthenticatedPrincipalConverter(
new SecuritySettings(
"https://issuer.example/realms/ca-skeleton", List.of(OWN_CLIENT), List.of()));
}
private static Jwt.Builder token() {
return Jwt.withTokenValue("token").header("alg", "none").subject("user-1");
}
@@ -23,7 +23,9 @@ class RedisSessionWebConfigTest {
void jwtModeCreatesNoSessionFilterOrCookieSerializer() {
runner
.withPropertyValues(
"app.security.auth-mode=jwt", "app.security.issuer-uri=https://issuer.example")
"app.security.auth-mode=jwt",
"app.security.issuer-uri=https://issuer.example",
"app.security.audience=ca-skeleton-api")
.run(
context -> {
assertThat(context).hasNotFailed();
@@ -157,6 +157,7 @@ class SecurityModeWebContractTest {
.withPropertyValues(
"app.security.auth-mode=jwt",
"app.security.issuer-uri=https://issuer.example",
"app.security.audience=ca-skeleton-api",
"app.security.public-paths=/probe",
"app.cors.enabled=false")
.run(
@@ -177,6 +178,7 @@ class SecurityModeWebContractTest {
.withPropertyValues(
"app.security.auth-mode=jwt",
"app.security.issuer-uri=https://issuer.example",
"app.security.audience=ca-skeleton-api",
"app.cors.enabled=false")
.run(
context -> {
@@ -1,6 +1,9 @@
package dev.caskeleton.adapter.inbound.web.envelope;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -25,7 +28,11 @@ import org.springframework.web.bind.annotation.RestController;
controllers = EnvelopeBodyAdviceTest.Probe.class,
excludeAutoConfiguration = SecurityAutoConfiguration.class)
@AutoConfigureMockMvc(addFilters = false)
@Import({EnvelopeBodyAdviceTest.Probe.class, EnvelopeBodyAdvice.class})
@Import({
EnvelopeBodyAdviceTest.Probe.class,
EnvelopeBodyAdvice.class,
EnvelopeWireFormatConfig.class
})
class EnvelopeBodyAdviceTest {
@Autowired MockMvc mvc;
@@ -54,7 +61,7 @@ class EnvelopeBodyAdviceTest {
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.data.k").value("v"))
.andExpect(jsonPath("$.error").doesNotExist());
.andExpect(content().string(not(containsString("\"error\""))));
}
@Test
@@ -79,7 +86,7 @@ class EnvelopeBodyAdviceTest {
.andExpect(status().isOk())
.andExpect(jsonPath("$.results[0].k").value("v"))
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.data").doesNotExist());
.andExpect(content().string(not(containsString("\"data\""))));
}
@SpringBootConfiguration
@@ -0,0 +1,195 @@
package dev.caskeleton.adapter.inbound.web.envelope;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
import dev.caskeleton.application.idempotency.IdempotencyInFlightException;
import dev.caskeleton.shared.observability.MdcKeys;
import dev.caskeleton.shared.response.BulkEnvelope;
import dev.caskeleton.shared.response.BulkItemResult;
import dev.caskeleton.shared.response.Envelope;
import dev.caskeleton.shared.response.PageMeta;
import dev.caskeleton.shared.response.ResponseMeta;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.security.autoconfigure.SecurityAutoConfiguration;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
/**
* The raw JSON keys a client receives — the wire contract in {@code docs/web/http-contract.md}.
*
* <p>Asserted on the response text, never with {@code jsonPath(..).doesNotExist()}: that matcher
* passes for a key that is present with a {@code null} value, which is exactly the difference a
* strict client rejects.
*/
@WebMvcTest(
controllers = EnvelopeWireShapeTest.Probe.class,
excludeAutoConfiguration = SecurityAutoConfiguration.class)
@AutoConfigureMockMvc(addFilters = false)
@Import({
EnvelopeWireShapeTest.Probe.class,
EnvelopeBodyAdvice.class,
GlobalExceptionHandler.class,
EnvelopeWireFormatConfig.class
})
class EnvelopeWireShapeTest {
private static final JsonMapper READER = JsonMapper.builder().build();
@Autowired MockMvc mvc;
@RestController
static class Probe {
@GetMapping("/probe/item")
public Map<String, String> item() {
ids(true);
return Map.of("k", "v");
}
@GetMapping("/probe/empty-list")
public List<String> emptyList() {
ids(true);
return List.of();
}
@GetMapping("/probe/page")
public Envelope<List<String>> page() {
return Envelope.ok(
List.of("a"),
new ResponseMeta("req-1", "trace-1", "corr-1").withPage(new PageMeta(0, 20, 1, "id")));
}
@GetMapping("/probe/in-flight")
public Map<String, String> inFlight() {
ids(false);
throw IdempotencyInFlightException.forScopeDigest("CREATE::v1::" + "a".repeat(64));
}
@GetMapping("/probe/bulk-ok")
public BulkEnvelope<String> bulkOk() {
return BulkEnvelope.allOk(List.of(), new ResponseMeta("req-1", "trace-1", "corr-1"));
}
@GetMapping("/probe/bulk-partial")
public BulkEnvelope<String> bulkPartial() {
return BulkEnvelope.partial(
List.<BulkItemResult>of(), new ResponseMeta("req-1", "trace-1", "corr-1"));
}
private static void ids(boolean withCorrelation) {
MDC.put(MdcKeys.REQUEST_ID, "req-1");
MDC.put(MdcKeys.TRACE_ID, "trace-1");
if (withCorrelation) {
MDC.put(MdcKeys.CORRELATION_ID, "corr-1");
}
}
}
@AfterEach
void clearMdc() {
MDC.clear();
}
@Test
@DisplayName("성공 응답 원문에는 success·data·meta 키만 있고 error 키는 없다")
void successBodyCarriesOnlySuccessDataAndMetaKeys() throws Exception {
// when
JsonNode body = rawBody("/probe/item");
// then
assertThat(keys(body)).containsExactlyInAnyOrder("success", "data", "meta");
assertThat(keys(body.get("meta")))
.containsExactlyInAnyOrder("requestId", "traceId", "correlationId");
}
@Test
@DisplayName("빈 목록 data는 생략되지 않고 빈 배열로 나간다")
void emptyListDataIsKeptAsAnEmptyArray() throws Exception {
// when
JsonNode body = rawBody("/probe/empty-list");
// then
assertThat(keys(body)).containsExactlyInAnyOrder("success", "data", "meta");
assertThat(body.get("data").isArray() && body.get("data").isEmpty()).isTrue();
}
@Test
@DisplayName("목록 응답의 meta에만 page 키가 있다")
void pagedBodyCarriesPageInMeta() throws Exception {
// when
JsonNode body = rawBody("/probe/page");
// then
assertThat(keys(body.get("meta")))
.containsExactlyInAnyOrder("requestId", "traceId", "correlationId", "page");
}
@Test
@DisplayName("실패 응답 원문에는 success·error·meta 키만 있고 data·null 필드는 없다")
void failureBodyCarriesOnlySuccessErrorAndMetaKeys() throws Exception {
// when
JsonNode body = rawBody("/probe/in-flight");
// then
assertThat(keys(body)).containsExactlyInAnyOrder("success", "error", "meta");
assertThat(keys(body.get("error")))
.containsExactlyInAnyOrder("code", "category", "message", "retryable");
assertThat(keys(body.get("meta"))).containsExactlyInAnyOrder("requestId", "traceId");
}
@Test
@DisplayName("bulk 전체 성공은 빈 results를 남기고 error 키를 싣지 않는다")
void bulkSuccessKeepsEmptyResultsWithoutErrorKey() throws Exception {
// when
JsonNode body = rawBody("/probe/bulk-ok");
// then
assertThat(keys(body)).containsExactlyInAnyOrder("success", "results", "meta");
assertThat(body.get("results").isArray() && body.get("results").isEmpty()).isTrue();
}
@Test
@DisplayName("bulk 부분 실패는 results 키 없이 error의 빈 details 목록을 남긴다")
void bulkPartialFailureCarriesErrorWithoutResultsKey() throws Exception {
// when
JsonNode body = rawBody("/probe/bulk-partial");
// then
assertThat(keys(body)).containsExactlyInAnyOrder("success", "error", "meta");
JsonNode details = body.get("error").get("details");
assertThat(details.isArray() && details.isEmpty()).isTrue();
}
private JsonNode rawBody(String path) throws Exception {
String text = mvc.perform(get(path)).andReturn().getResponse().getContentAsString();
return READER.readTree(text);
}
private static Set<String> keys(JsonNode node) {
Set<String> keys = new TreeSet<>();
node.properties().forEach(entry -> keys.add(entry.getKey()));
return keys;
}
@SpringBootConfiguration
@EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)
static class TestBootstrap {}
}
@@ -2,12 +2,14 @@ package dev.caskeleton.adapter.inbound.web.error;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.web.http.ApiHeaders;
import dev.caskeleton.application.idempotency.IdempotencyInFlightException;
import dev.caskeleton.application.idempotency.IdempotencyRequestMismatchException;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import dev.caskeleton.shared.response.Envelope;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.http.ResponseEntity;
@@ -18,7 +20,8 @@ class IdempotencyExceptionMappingTest {
private final GlobalExceptionHandler handler = new GlobalExceptionHandler(SpanErrorRecorder.NOOP);
@Test
void inFlightMapsToNonRetryable409ConflictWithTheConflictMessage() {
@DisplayName("처리 중 409는 retryable=true와 Retry-After를 실어 같은 키 재전송을 알린다")
void inFlightMapsToRetryable409WithRetryAfterSoTheClientResendsTheSameKey() {
// given
IdempotencyInFlightException inFlight =
IdempotencyInFlightException.forScopeDigest(SCOPE_DIAGNOSTIC);
@@ -30,19 +33,22 @@ class IdempotencyExceptionMappingTest {
assertThat(response)
.extracting(
r -> r.getStatusCode().value(),
r -> r.getHeaders().getFirst(ApiHeaders.RETRY_AFTER),
r -> r.getBody().error().code(),
r -> r.getBody().error().category(),
r -> r.getBody().error().retryable(),
r -> r.getBody().error().message())
.containsExactly(
409,
"2",
"IDEMPOTENT_IN_FLIGHT",
"CONFLICT",
false,
true,
ClientErrorMessages.of(Category.CONFLICT));
}
@Test
@DisplayName("다른 본문으로 키를 재사용하면 Retry-After 없는 재시도 불가 422다")
void mismatchMapsToNonRetryable422ValidationWithTheValidationMessage() {
// given
IdempotencyRequestMismatchException mismatch =
@@ -55,12 +61,14 @@ class IdempotencyExceptionMappingTest {
assertThat(response)
.extracting(
r -> r.getStatusCode().value(),
r -> r.getHeaders().getFirst(ApiHeaders.RETRY_AFTER),
r -> r.getBody().error().code(),
r -> r.getBody().error().category(),
r -> r.getBody().error().retryable(),
r -> r.getBody().error().message())
.containsExactly(
422,
null,
"IDEMPOTENT_REQUEST_MISMATCH",
"VALIDATION",
false,
@@ -37,6 +37,7 @@ class WebAutoConfigurationRegistrationTest {
List.of(
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration",
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration",
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMethodSecurityAutoConfiguration",
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMvcPlatformAutoConfiguration");
@Test
@@ -76,6 +76,31 @@ class WebMvcRequestIdFilterTest {
.isPresent();
}
@Test
@DisplayName("tracer가 span을 열어 두었으면 응답·MDC의 trace id는 그 span의 것이다")
void theActiveSpanOfARunningTracerNamesTheTrace() throws Exception {
// given
TraceParent serverSpan =
TraceParent.of("4bf92f3577b34da6a3ce929d0e0e4736", "00f067aa0ba902b7", true);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(WebMvcRequestIdFilter.TRACEPARENT_HEADER, "garbage");
MockHttpServletResponse response = new MockHttpServletResponse();
Map<String, String> duringChain = new HashMap<>();
// when
new WebMvcRequestIdFilter(false, 0, () -> java.util.Optional.of(serverSpan))
.doFilter(request, response, (rq, rs) -> duringChain.putAll(mdc()));
// then
assertThat(WebMvcRequestIdFilter.traceId(request).orElseThrow().value())
.isEqualTo(serverSpan.traceId());
assertThat(duringChain)
.containsEntry(MdcKeys.TRACE_ID, serverSpan.traceId())
.containsEntry(MdcKeys.SPAN_ID, serverSpan.spanId());
assertThat(response.getHeader(WebMvcRequestIdFilter.TRACEPARENT_HEADER))
.isEqualTo(serverSpan.toHeader());
}
@ParameterizedTest
@ValueSource(
strings = {
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.web.observability;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.shared.error.OperationalError;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class RetryAfterAdvisorTest {
@@ -45,10 +46,17 @@ class RetryAfterAdvisorTest {
@Test
void nonRetryableCodeHasNoRetryAfterValue() {
assertThat(RetryAfterAdvisor.retryAfterSeconds(OperationalError.IDEMPOTENT_IN_FLIGHT))
assertThat(RetryAfterAdvisor.retryAfterSeconds(OperationalError.IDEMPOTENT_REQUEST_MISMATCH))
.isEmpty();
}
@Test
@DisplayName("처리 중 409는 기본 processing lease(30s)보다 짧은 2초 Retry-After를 준다")
void idempotentInFlightHasRetryAfter2s() {
assertThat(RetryAfterAdvisor.retryAfterSeconds(OperationalError.IDEMPOTENT_IN_FLIGHT))
.hasValue(2);
}
// feature-outbound-http-client-baseline D12: dependency codes — rows 636~711 in
// docs/registries/error-codes.yaml, retry_after_seconds column.
@@ -4,15 +4,12 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.annotation.Configuration;
@ExtendWith(OutputCaptureExtension.class)
class SecuritySettingsTest {
private final ApplicationContextRunner runner =
@@ -29,15 +26,59 @@ class SecuritySettingsTest {
}
@Test
void audienceMissingWarnsAndDefaultsToEmpty(CapturedOutput output) {
runner
.withPropertyValues("app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton")
.run(
context -> {
assertThat(context).hasNotFailed();
assertThat(context.getBean(SecuritySettings.class).audience()).isEmpty();
assertThat(output.getOut()).contains("APP_SECURITY_JWT_AUDIENCE is missing");
});
@DisplayName("JWT 모드에서 audience가 없으면 env 키 이름을 담아 기동을 거부한다")
void aJwtModeWithoutAnAudienceFailsStartupNamingTheEnvKey() {
// given
var withoutAudience =
runner.withPropertyValues(
"app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton");
// when
withoutAudience.run(
context -> {
// then
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.hasStackTraceContaining("APP_SECURITY_JWT_AUDIENCE");
});
}
@Test
@DisplayName("JWT 모드에서 audience가 빈 값이거나 공백 항목뿐이면 기동을 거부한다")
void aJwtModeWithABlankAudienceFailsStartup() {
// given
var blankAudience =
runner.withPropertyValues(
"app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton",
"app.security.audience= , ");
// when
blankAudience.run(
context -> {
// then
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.hasStackTraceContaining("APP_SECURITY_JWT_AUDIENCE");
});
}
@Test
@DisplayName("audience는 쉼표 목록을 받아 공백을 다듬은 목록으로 묶는다")
void aCommaSeparatedAudienceBindsAsATrimmedList() {
// given
var listedAudiences =
runner.withPropertyValues(
"app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton",
"app.security.audience=ca-skeleton-api, ca-skeleton-admin");
// when
listedAudiences.run(
context -> {
// then
assertThat(context).hasNotFailed();
assertThat(context.getBean(SecuritySettings.class).audience())
.containsExactly("ca-skeleton-api", "ca-skeleton-admin");
});
}
@Test
@@ -60,7 +101,8 @@ class SecuritySettingsTest {
List<String> paths = new ArrayList<>(List.of("/healthcheck"));
SecuritySettings settings =
new SecuritySettings("http://localhost:8081/realms/ca-skeleton", "ca-skeleton-api", paths);
new SecuritySettings(
"http://localhost:8081/realms/ca-skeleton", List.of("ca-skeleton-api"), paths);
paths.add("/admin/**");
assertThat(settings.publicPaths()).containsExactly("/healthcheck");
@@ -83,6 +125,7 @@ class SecuritySettingsTest {
assertThat(settings.authMode())
.isEqualTo(SecuritySettings.AuthenticationMode.REDIS_SESSION);
assertThat(settings.issuerUri()).isEmpty();
assertThat(settings.audience()).isEmpty();
assertThat(settings.session().cookieName()).isEqualTo("APP_SESSION");
assertThat(settings.session().sameSite()).isEqualTo("Strict");
});
@@ -29,7 +29,8 @@ import org.springframework.security.web.SecurityFilterChain;
* production security chain and its JWT settings) and {@link WebAdapterAutoConfiguration} (the
* request-logging filter and the composition-root pseudonymizer that filter needs). Together they
* are the "sum of the leaf" the paragraph above keeps out. Excluded by class, so a rename breaks
* compilation rather than the gate.
* compilation rather than the gate. The third root, {@code WebMethodSecurityAutoConfiguration}, is
* left in: no fixture route runs a permissioned use case, so it decides nothing here.
*/
// Outside `dev.caskeleton.adapter.inbound.web`, which the composition root component-scans.
// A fixture application under that root is loaded into the real deployment: its permit-all
+31 -1
View File
@@ -122,7 +122,10 @@ Redis checks a script's inner commands against the ACL only when they run, so a
nothing proved `EVALSHA` and nothing else: an account granted by category (`@read`/`@write`) lacks
`TIME` and failed every rate-limit and idempotency request after a clean start. A deployment whose
effective Redis account lacks script permissions fails during startup rather than at the first
request. Cache-only deployments do not run this probe.
request. Cache-only deployments do not run this probe, although the cache's conditional intents
(`ONLY_IF_OBSERVED`, `ONLY_IF_SOURCE_REVISION_NEWER`) also run on the SCRIPT lane: a cache-only
deployment whose script-lane account lacks `EVALSHA` finds out as `INDETERMINATE` conditional
writes, not at startup.
At runtime, `redisRequired` (redis-runtime) probes the SCRIPT lane too when a script role is
selected, so a broken advanced-account credential makes the pod unready instead of leaving the
@@ -153,6 +156,24 @@ script to perform:
inside one Redis execution. A stale source load therefore cannot overwrite a value written between
observation and replacement.
`ONLY_IF_SOURCE_REVISION_NEWER` is an atomic server-side revision comparison. The source revision
must be a non-negative decimal integer without leading zeros (a row version, an offset, epoch
millis); any other revision is refused with `IllegalArgumentException` before anything is sent,
because text order would rank revision `10` below `9`. The script reads the stored envelope's
schema version, revision and generation and writes only when:
- nothing is stored, or the stored entry is from an older region generation (already invalidated);
- otherwise, the stored revision is a decimal integer and the caller's is strictly greater.
Everything else — an equal or smaller revision, a stored revision with no numeric order (for
example one written by `UPSERT` as `rev-1`), another schema version, a generation newer than the
writer knows — is `NOT_RECORDED_CONDITION`.
Both conditional intents run registered scripts, so they borrow the SCRIPT lane (the advanced
account when one is configured, the application account otherwise). The application account is not
granted `EVALSHA`; on the REGULAR lane every conditional write came back `INDETERMINATE`. `UPSERT`
and `ONLY_IF_ABSENT` stay on the REGULAR lane.
### Region invalidation
Region invalidation increments a generation key; it never scans/deletes the keyspace.
@@ -184,6 +205,15 @@ programs atomically. `RedisIdempotencyConfig` contributes only the `IdempotencyS
revision) come from app-bootstrap `IdempotencySettings`. This leaf reads only `key-version` and
`command-timeout` under `app.capabilities.idempotency`.
`renew` has its own program rather than the generic transition. Renewal keeps the record in
`EXECUTING`, and the transition answers "already in the target state" before it reads the revision
(that answer exists for a retry whose first reply was lost), so a renewal sent through it was always
`ALREADY_RENEWED_SAME_OPERATION` and never moved the lease. The renew program checks owner,
operation, revision and state, then extends `leaseUntil` from Redis `TIME` and bumps the revision.
A lost renewal reply is recognised by what the renewal recorded — the revision it started from and
the lease it asked for: the same lease is `ALREADY_RENEWED_SAME_OPERATION` with the current handle,
a different lease is `OPERATION_CONFLICT`.
Redis `TIME` determines lease deadlines. A failure after a command may have executed is returned
as an indeterminate outcome; the adapter does not convert an ambiguous write into a clean
unavailable result that would invite duplicate execution.
@@ -22,9 +22,88 @@ final class CacheScripts {
return 1
""";
/**
* Replaces the entry only when the caller's source revision is strictly newer than the stored
* one.
*
* <p>Revisions are canonical non-negative decimal integers, compared by length and then digit by
* digit, so the order is numeric at any length (no 2^53 limit, no locale collation). The stored
* envelope header is {@code digest|version|revision|generation|...}; the digest is not
* re-verified here, the reader does that on lookup.
*
* <p>The write applies when nothing is stored, or when the stored entry belongs to an older
* region generation (semantically invalidated). It is refused when the stored entry has another
* schema version, a newer generation than the writer knows, or a revision that has no numeric
* order: nothing proves the caller's revision is newer than any of those.
*/
private static final String REPLACE_IF_REVISION_NEWER =
"""
local function canonicalDecimal(text)
return string.match(text, '^%d+$') ~= nil
and (string.len(text) == 1 or string.sub(text, 1, 1) ~= '0')
end
local function strictlyNewer(candidate, stored)
if string.len(candidate) ~= string.len(stored) then
return string.len(candidate) > string.len(stored)
end
for i = 1, string.len(candidate) do
local a = string.byte(candidate, i)
local b = string.byte(stored, i)
if a ~= b then
return a > b
end
end
return false
end
local current = redis.call('GET', KEYS[1])
if current ~= false then
if string.sub(current, 65, 65) ~= '|' then
return 0
end
local fields = {}
local cursor = 66
for i = 1, 3 do
local stop = string.find(current, '|', cursor, true)
if stop == nil then
return 0
end
fields[i] = string.sub(current, cursor, stop - 1)
cursor = stop + 1
end
if fields[1] ~= ARGV[4] then
return 0
end
local storedGeneration = tonumber(fields[3])
local writerGeneration = tonumber(ARGV[5])
if storedGeneration == nil or storedGeneration > writerGeneration then
return 0
end
if storedGeneration == writerGeneration then
if not canonicalDecimal(fields[2]) or not strictlyNewer(ARGV[1], fields[2]) then
return 0
end
end
end
redis.call('SET', KEYS[1], ARGV[2], 'PX', ARGV[3])
return 1
""";
private final RegisteredLuaScript replaceIfObserved =
new RegisteredLuaScript(REPLACE_IF_OBSERVED);
private final RegisteredLuaScript replaceIfRevisionNewer =
new RegisteredLuaScript(REPLACE_IF_REVISION_NEWER);
/**
* Whether a revision has the numeric order {@link #replaceIfRevisionNewer} compares by.
*
* @param revision the source revision
* @return true for a canonical non-negative decimal integer
*/
static boolean hasNumericOrder(String revision) {
return revision.matches("0|[1-9][0-9]*");
}
CompletionStage<Boolean> replaceIfObserved(
SemanticRedisCommands commands,
byte[] key,
@@ -40,4 +119,24 @@ final class CacheScripts {
.evaluateForLong(commands, key, arguments)
.thenApply(applied -> applied != null && applied == 1L);
}
CompletionStage<Boolean> replaceIfRevisionNewer(
SemanticRedisCommands commands,
byte[] key,
String sourceRevision,
byte[] replacement,
long ttlMillis,
int schemaVersion,
long writerGeneration) {
List<byte[]> arguments =
List.of(
sourceRevision.getBytes(StandardCharsets.US_ASCII),
replacement,
Long.toString(ttlMillis).getBytes(StandardCharsets.US_ASCII),
Integer.toString(schemaVersion).getBytes(StandardCharsets.US_ASCII),
Long.toString(writerGeneration).getBytes(StandardCharsets.US_ASCII));
return replaceIfRevisionNewer
.evaluateForLong(commands, key, arguments)
.thenApply(applied -> applied != null && applied == 1L);
}
}
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.cache;
import dev.caskeleton.adapter.outbound.cache.redis.SemanticRedisCall;
import dev.caskeleton.adapter.outbound.cache.redis.keyspace.CapabilityKeyspace;
import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence;
import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind;
import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner;
import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace;
@@ -54,6 +55,12 @@ public final class RedisCacheRegionAdapter<K, V> implements CacheRegionPort<K, V
private final SemanticRedisCall call;
/**
* The conditional writes, which are registered programs and so run on the SCRIPT lane: the
* application account the REGULAR lane authenticates as is not granted {@code EVALSHA}.
*/
private final SemanticRedisCall scriptCall;
private final CacheKeys keys;
private final Function<K, String> keyDigest;
@@ -103,6 +110,8 @@ public final class RedisCacheRegionAdapter<K, V> implements CacheRegionPort<K, V
RedisConnectionKind.REGULAR,
Objects.requireNonNull(commandTimeout, "command timeout must be non-null"),
"cache");
this.scriptCall =
new SemanticRedisCall(owner, RedisConnectionKind.SCRIPT, commandTimeout, "cache");
this.keys = Objects.requireNonNull(keys, "keys must be non-null");
this.keyDigest = Objects.requireNonNull(keyDigest, "key digest must be non-null");
this.encoder = Objects.requireNonNull(encoder, "encoder must be non-null");
@@ -215,55 +224,79 @@ public final class RedisCacheRegionAdapter<K, V> implements CacheRegionPort<K, V
K key, byte[] payload, String absence, CacheRecordMetadata metadata, Duration ttl) {
Objects.requireNonNull(key, "key must be non-null");
Objects.requireNonNull(metadata, "metadata must be non-null");
CacheRecordIntent intent = metadata.intent();
if (intent == CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER
&& !CacheScripts.hasNumericOrder(metadata.sourceRevision())) {
// Refused before anything is sent. "Newer" needs an order, and this provider orders
// revisions as non-negative decimal integers only; text order would rank revision 10 below
// revision 9. A caller error, so it fails loudly rather than degrading like an outage.
throw new IllegalArgumentException(
"ONLY_IF_SOURCE_REVISION_NEWER needs a source revision that is a non-negative decimal"
+ " integer without leading zeros");
}
Instant now = clock.instant();
Duration effectiveSoft = softTtl.compareTo(ttl) > 0 ? ttl : softTtl;
byte[] physicalKey = keys.entryKey(keyDigest.apply(key));
boolean scripted =
intent == CacheRecordIntent.ONLY_IF_OBSERVED
|| intent == CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER;
// The write is marked sent only when the write command itself is handed to the driver. A
// failure before that point — lane refusal, connection, the generation read — wrote nothing.
return call.run(
"record",
session -> {
resolveGeneration(session, now);
CacheEnvelope envelope =
new CacheEnvelope(
CacheEnvelope.CURRENT_SCHEMA_VERSION,
metadata.sourceRevision(),
keys.generation(),
now.plus(effectiveSoft),
now.plus(ttl),
absence,
payload);
session.markSent();
Boolean applied =
metadata.intent() == CacheRecordIntent.ONLY_IF_OBSERVED
// Compare and replacement are one server-side execution. A GET followed by SET
// would let a concurrent writer land between them and then be overwritten by
// this stale source load.
? session.await(
scripts.replaceIfObserved(
session.commands(),
physicalKey,
metadata.observedToken().value(),
envelope.encode(),
ttl.toMillis()))
// The physical TTL is the hard expiry and nothing else.
: session.await(
session
.commands()
.set(physicalKey, envelope.encode(), presenceOf(metadata.intent()), ttl));
return Boolean.TRUE.equals(applied)
? CacheRecordOutcome.RECORDED
: CacheRecordOutcome.NOT_RECORDED_CONDITION;
},
() -> CacheRecordOutcome.DEGRADED_UNAVAILABLE,
() -> CacheRecordOutcome.INDETERMINATE);
}
private static dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence
presenceOf(CacheRecordIntent intent) {
return intent == CacheRecordIntent.ONLY_IF_ABSENT
? dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence.IF_ABSENT
: dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence.ALWAYS;
return (scripted ? scriptCall : call)
.run(
"record",
session -> {
resolveGeneration(session, now);
CacheEnvelope envelope =
new CacheEnvelope(
CacheEnvelope.CURRENT_SCHEMA_VERSION,
metadata.sourceRevision(),
keys.generation(),
now.plus(effectiveSoft),
now.plus(ttl),
absence,
payload);
session.markSent();
// Each condition is checked and applied in one server-side execution. A GET followed
// by SET would let a concurrent writer land between them and then be overwritten by
// this stale source load. The physical TTL is the hard expiry and nothing else.
Boolean applied =
switch (intent) {
case ONLY_IF_OBSERVED ->
session.await(
scripts.replaceIfObserved(
session.commands(),
physicalKey,
metadata.observedToken().value(),
envelope.encode(),
ttl.toMillis()));
case ONLY_IF_SOURCE_REVISION_NEWER ->
session.await(
scripts.replaceIfRevisionNewer(
session.commands(),
physicalKey,
metadata.sourceRevision(),
envelope.encode(),
ttl.toMillis(),
CacheEnvelope.CURRENT_SCHEMA_VERSION,
keys.generation()));
case ONLY_IF_ABSENT ->
session.await(
session
.commands()
.set(physicalKey, envelope.encode(), WritePresence.IF_ABSENT, ttl));
case UPSERT ->
session.await(
session
.commands()
.set(physicalKey, envelope.encode(), WritePresence.ALWAYS, ttl));
};
return Boolean.TRUE.equals(applied)
? CacheRecordOutcome.RECORDED
: CacheRecordOutcome.NOT_RECORDED_CONDITION;
},
() -> CacheRecordOutcome.DEGRADED_UNAVAILABLE,
() -> CacheRecordOutcome.INDETERMINATE);
}
@Override
@@ -130,6 +130,56 @@ public final class IdempotencyScripts {
return {'APPLIED', attempt, rev + 1, owner, '', ''}
""";
/**
* Renew: extend the processing lease of an EXECUTING record, and nothing else.
*
* <p>Not the generic {@link #TRANSITION}. Renewal does not change the state, so the transition's
* "already in the target state" answer — which exists for a retry whose first reply was lost —
* would match every renewal before the revision was ever read, and the lease would never move.
*
* <p>A lost renewal reply is recognised by what the renewal itself recorded instead: the revision
* it started from and the lease it asked for. A retry from that revision with the same lease is
* the same renewal; with a different lease it is a different request, because confirming it would
* leave the caller believing it holds the record for a lease the record does not carry.
*/
private static final String RENEW =
"""
local state = redis.call('HGET', KEYS[1], 'state')
if state == false then
return {'ABSENT', 0, 0, '', '', ''}
end
local owner = redis.call('HGET', KEYS[1], 'owner')
local rev = tonumber(redis.call('HGET', KEYS[1], 'rev'))
local attempt = tonumber(redis.call('HGET', KEYS[1], 'attempt'))
local op = redis.call('HGET', KEYS[1], 'op')
if owner ~= ARGV[1] then
return {'NOT_OWNER', attempt, rev, owner, '', ''}
end
if op ~= ARGV[3] then
return {'OPERATION_CONFLICT', attempt, rev, owner, '', ''}
end
local handleRev = tonumber(ARGV[2])
if rev ~= handleRev then
if state == 'EXECUTING' and rev == handleRev + 1
and redis.call('HGET', KEYS[1], 'renewedFromRev') == ARGV[2] then
if redis.call('HGET', KEYS[1], 'renewedLease') == ARGV[4] then
return {'ALREADY', attempt, rev, owner, '', ''}
end
return {'OPERATION_CONFLICT', attempt, rev, owner, '', ''}
end
return {'NOT_OWNER', attempt, rev, owner, '', ''}
end
if state ~= 'EXECUTING' then
return {'WRONG_STATE', attempt, rev, owner, state, ''}
end
local t = redis.call('TIME')
local nowMillis = (tonumber(t[1]) * 1000) + math.floor(tonumber(t[2]) / 1000)
redis.call('HSET', KEYS[1],
'leaseUntil', nowMillis + tonumber(ARGV[4]), 'rev', rev + 1,
'renewedFromRev', ARGV[2], 'renewedLease', ARGV[4])
return {'APPLIED', attempt, rev + 1, owner, '', ''}
""";
/** Release before execution: only from CLAIMED, and only by the owner that holds it. */
private static final String RELEASE =
"""
@@ -184,6 +234,7 @@ public final class IdempotencyScripts {
private final RegisteredLuaScript claim = new RegisteredLuaScript(CLAIM);
private final RegisteredLuaScript transition = new RegisteredLuaScript(TRANSITION);
private final RegisteredLuaScript renew = new RegisteredLuaScript(RENEW);
private final RegisteredLuaScript release = new RegisteredLuaScript(RELEASE);
private final RegisteredLuaScript inspect = new RegisteredLuaScript(INSPECT);
@@ -196,6 +247,10 @@ public final class IdempotencyScripts {
return run(transition, commands, key, arguments);
}
CompletionStage<Reply> renew(SemanticRedisCommands commands, byte[] key, List<String> arguments) {
return run(renew, commands, key, arguments);
}
CompletionStage<Reply> release(
SemanticRedisCommands commands, byte[] key, List<String> arguments) {
return run(release, commands, key, arguments);
@@ -32,6 +32,8 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import java.util.function.Predicate;
/**
@@ -183,11 +185,19 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort
public IdempotencyMutationResult<IdempotencyRenewOutcome> renew(
IdempotencyOwner ownerHandle, Duration processingLeaseTtl, OperationId operationId) {
Objects.requireNonNull(processingLeaseTtl, "processing lease TTL must be non-null");
return transition(
// Its own program, not the generic transition: EXECUTING -> EXECUTING is "already in the
// target state" to the transition, which answered ALREADY without ever extending the lease.
return ownerMutation(
ownerHandle,
operationId,
new Transition(
"EXECUTING", "EXECUTING", "", Long.toString(processingLeaseTtl.toMillis()), ""),
session ->
scripts.renew(
session.commands(),
keys.recordKey(ownerHandle.scope()),
List.of(
ownerHandle.ownerToken(),
Long.toString(ownerHandle.stateRevision()),
operationId.value(),
Long.toString(processingLeaseTtl.toMillis()))),
Map.of(
ScriptStatus.APPLIED, IdempotencyRenewOutcome.RENEWED,
ScriptStatus.ALREADY, IdempotencyRenewOutcome.ALREADY_RENEWED_SAME_OPERATION,
@@ -429,15 +439,34 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort
O indeterminate,
O unavailable,
Predicate<O> carriesOwner) {
return ownerMutation(
ownerHandle,
session ->
scripts.transition(
session.commands(),
keys.recordKey(ownerHandle.scope()),
transition.arguments(ownerHandle, operationId)),
outcomes,
indeterminate,
unavailable,
carriesOwner);
}
/**
* Runs one owner-checked program and maps its verdict, carrying the refreshed handle when the
* outcome leaves the caller still owning the record.
*/
private <O extends Enum<O>> IdempotencyMutationResult<O> ownerMutation(
IdempotencyOwner ownerHandle,
Function<SemanticRedisCall.Session, CompletionStage<IdempotencyScripts.Reply>> program,
Map<ScriptStatus, O> outcomes,
O indeterminate,
O unavailable,
Predicate<O> carriesOwner) {
return call.effect(
"transition",
session -> {
IdempotencyScripts.Reply reply =
session.await(
scripts.transition(
session.commands(),
keys.recordKey(ownerHandle.scope()),
transition.arguments(ownerHandle, operationId)));
IdempotencyScripts.Reply reply = session.await(program.apply(session));
O outcome = outcomes.getOrDefault(reply.status(), indeterminate);
return new IdempotencyMutationResult<>(
outcome,
@@ -27,6 +27,8 @@ import dev.caskeleton.application.cache.CacheRegionPort;
import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt;
import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome;
import dev.caskeleton.application.idempotency.IdempotencyClaimRequest;
import dev.caskeleton.application.idempotency.IdempotencyOwner;
import dev.caskeleton.application.idempotency.IdempotencyRenewOutcome;
import dev.caskeleton.application.idempotency.IdempotencyScopeDigest;
import dev.caskeleton.application.idempotency.RequestFingerprint;
import dev.caskeleton.application.lease.LeaseAcquireOutcome;
@@ -126,6 +128,83 @@ class LiveRedisSemanticPortsTest {
assertThat(((CacheLookup.Hit<String>) lookup).value()).isEqualTo("payload");
}
private CacheRegionPort<String, String> conditionalCache() {
return new RedisCacheRegionAdapter<>(
runtime(true),
new RedisCacheRegionAdapter.CacheKeys(NAMESPACE, "orders", 1),
key -> "hv1:" + Integer.toHexString(key.hashCode()),
value -> value.getBytes(StandardCharsets.UTF_8),
stored -> new String(stored, StandardCharsets.UTF_8),
Clock.systemUTC(),
Duration.ofSeconds(30),
Duration.ofMinutes(5),
Duration.ofSeconds(10),
Duration.ofSeconds(2));
}
@Test
@DisplayName("실제 Redis에서 ONLY_IF_SOURCE_REVISION_NEWER는 저장된 것보다 작은 revision을 거부한다")
void theRevisionConditionRefusesAnOlderRevisionOnARealServer() {
// given
CacheRegionPort<String, String> cache = conditionalCache();
String key = "order-" + UUID.randomUUID();
cache.record(key, "fresh", new CacheRecordMetadata("7", CacheRecordIntent.UPSERT));
// when
CacheRecordOutcome outcome =
cache.record(
key,
"stale",
new CacheRecordMetadata("6", CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER));
// then
assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
assertThat(((CacheLookup.Hit<String>) cache.lookup(key)).value()).isEqualTo("fresh");
}
@Test
@DisplayName("실제 Redis에서 ONLY_IF_SOURCE_REVISION_NEWER는 숫자로 더 큰 revision을 기록한다")
void theRevisionConditionRecordsANumericallyNewerRevisionOnARealServer() {
// given
CacheRegionPort<String, String> cache = conditionalCache();
String key = "order-" + UUID.randomUUID();
cache.record(key, "old", new CacheRecordMetadata("9", CacheRecordIntent.UPSERT));
// when
// DEGRADED_UNAVAILABLE or INDETERMINATE here means EVALSHA was refused on the lane it ran on.
CacheRecordOutcome outcome =
cache.record(
key,
"new",
new CacheRecordMetadata("10", CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER));
// then
assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED);
assertThat(((CacheLookup.Hit<String>) cache.lookup(key)).value()).isEqualTo("new");
}
@Test
@DisplayName("실제 Redis의 ACL 계정 구성에서 ONLY_IF_OBSERVED 조건부 교체가 실행된다")
void theObservedConditionRunsUnderTheDeploymentAccounts() {
// given
CacheRegionPort<String, String> cache = conditionalCache();
String key = "order-" + UUID.randomUUID();
cache.record(key, "first", new CacheRecordMetadata("rev-1", CacheRecordIntent.UPSERT));
CacheLookup.Hit<String> observed = (CacheLookup.Hit<String>) cache.lookup(key);
// when
// On the REGULAR lane the application account has no EVALSHA, and this degraded every time.
CacheRecordOutcome outcome =
cache.record(
key,
"second",
new CacheRecordMetadata(
"rev-2", CacheRecordIntent.ONLY_IF_OBSERVED, observed.observationToken()));
// then
assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED);
}
// =========================================================================
// Rate limit / idempotency / lease: the script lane, the advanced account
// =========================================================================
@@ -369,6 +448,51 @@ class LiveRedisSemanticPortsTest {
.isInstanceOf(IdempotencyClaimOutcome.InProgress.class);
}
@Test
@DisplayName("실제 Redis에서 renew한 처리 lease는 원래 lease가 지난 뒤에도 다른 claim을 막는다")
void aRenewedProcessingLeaseOutlivesTheOriginalLeaseOnARealServer() throws InterruptedException {
// given
RedisIdempotencyStoreAdapter store =
new RedisIdempotencyStoreAdapter(
runtime(true),
new RedisIdempotencyStoreAdapter.IdempotencyKeys(NAMESPACE, 1),
new IdempotencyScripts(),
Clock.systemUTC(),
Duration.ofSeconds(2));
IdempotencyScopeDigest scope =
new IdempotencyScopeDigest(
UUID.randomUUID().toString().replace("-", "")
+ UUID.randomUUID().toString().replace("-", ""),
1,
"CHARGE_CARD");
IdempotencyClaimAttempt first = store.newClaimAttempt(new OperationId("operation-renew-aaaa"));
IdempotencyOwner claimed =
((IdempotencyClaimOutcome.Acquired)
store.claim(
new IdempotencyClaimRequest(
scope,
new RequestFingerprint("0".repeat(64)),
first,
Duration.ofSeconds(1),
Duration.ofHours(1),
"json-v2",
1)))
.owner();
IdempotencyOwner executing =
store.markExecutionStarted(claimed, first.operationId()).owner().orElseThrow();
assertThat(store.renew(executing, Duration.ofSeconds(30), first.operationId()).outcome())
.isEqualTo(IdempotencyRenewOutcome.RENEWED);
// Past the one-second lease the claim was taken with; Redis TIME decides, not this JVM.
Thread.sleep(1500);
// when
IdempotencyClaimOutcome other =
store.claim(claim(scope, store.newClaimAttempt(new OperationId("operation-renew-bbbb"))));
// then
assertThat(other).isInstanceOf(IdempotencyClaimOutcome.InProgress.class);
}
private static IdempotencyClaimRequest claim(
IdempotencyScopeDigest scope, IdempotencyClaimAttempt attempt) {
return new IdempotencyClaimRequest(
@@ -311,6 +311,123 @@ class RedisCacheRegionAdapterTest {
.isEqualTo(CacheRecordOutcome.RECORDED);
}
private static CacheRecordMetadata newerThan(String sourceRevision) {
return new CacheRecordMetadata(sourceRevision, CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER);
}
@Test
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 저장된 것보다 작은 revision을 기록하지 않는다")
void onlyIfSourceRevisionNewerRefusesAnOlderRevision() {
// given
RedisCacheRegionAdapter<String, String> cache = cache(T0);
cache.record("order-1", "fresh", new CacheRecordMetadata("7", CacheRecordIntent.UPSERT));
// when
// A slow loader that read the source at revision 6 finishes after the revision-7 write.
CacheRecordOutcome outcome = cache.record("order-1", "stale", newerThan("6"));
// then
assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
assertThat(((CacheLookup.Hit<String>) cache.lookup("order-1")).value()).isEqualTo("fresh");
}
@Test
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 저장된 것과 같은 revision을 기록하지 않는다")
void onlyIfSourceRevisionNewerRefusesTheSameRevision() {
// given
RedisCacheRegionAdapter<String, String> cache = cache(T0);
cache.record("order-1", "first", new CacheRecordMetadata("7", CacheRecordIntent.UPSERT));
// when
CacheRecordOutcome outcome = cache.record("order-1", "second", newerThan("7"));
// then
assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
assertThat(((CacheLookup.Hit<String>) cache.lookup("order-1")).value()).isEqualTo("first");
}
@Test
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 더 큰 revision을 숫자 순서로 판단해 기록한다")
void onlyIfSourceRevisionNewerRecordsANumericallyNewerRevision() {
// given
RedisCacheRegionAdapter<String, String> cache = cache(T0);
cache.record("order-1", "old", new CacheRecordMetadata("9", CacheRecordIntent.UPSERT));
// when
// "10" sorts before "9" as text. The order is numeric, or revision 10 could never replace 9.
CacheRecordOutcome outcome = cache.record("order-1", "new", newerThan("10"));
// then
assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED);
CacheLookup.Hit<String> hit = (CacheLookup.Hit<String>) cache.lookup("order-1");
assertThat(hit.value()).isEqualTo("new");
assertThat(hit.sourceRevision()).isEqualTo("10");
}
@Test
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 비어 있는 키에 기록한다")
void onlyIfSourceRevisionNewerRecordsIntoAnAbsentKey() {
// given
RedisCacheRegionAdapter<String, String> cache = cache(T0);
// when
CacheRecordOutcome outcome = cache.record("order-1", "first", newerThan("1"));
// then
assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED);
assertThat(((CacheLookup.Hit<String>) cache.lookup("order-1")).value()).isEqualTo("first");
}
@Test
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 region 무효화 전 세대의 항목을 revision과 관계없이 교체한다")
void onlyIfSourceRevisionNewerReplacesAnEntryFromAnInvalidatedGeneration() {
// given
RedisCacheRegionAdapter<String, String> cache = cache(T0);
cache.record("order-1", "before", new CacheRecordMetadata("9", CacheRecordIntent.UPSERT));
cache.invalidateRegion();
// when
// The invalidated entry is semantically gone; its revision is no longer a fact to defend.
CacheRecordOutcome outcome = cache.record("order-1", "after", newerThan("3"));
// then
assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED);
assertThat(((CacheLookup.Hit<String>) cache.lookup("order-1")).value()).isEqualTo("after");
}
@Test
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 순서를 비교할 수 없는 저장 revision을 덮어쓰지 않는다")
void onlyIfSourceRevisionNewerRefusesWhenTheStoredRevisionIsNotComparable() {
// given
RedisCacheRegionAdapter<String, String> cache = cache(T0);
cache.record("order-1", "upserted", upsert());
// when
// "rev-1" has no numeric order, so nothing proves revision 2 is newer than it.
CacheRecordOutcome outcome = cache.record("order-1", "conditional", newerThan("2"));
// then
assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION);
assertThat(((CacheLookup.Hit<String>) cache.lookup("order-1")).value()).isEqualTo("upserted");
}
@Test
@DisplayName("ONLY_IF_SOURCE_REVISION_NEWER에 10진 정수가 아닌 revision을 주면 Redis에 보내기 전에 거부한다")
void onlyIfSourceRevisionNewerRejectsARevisionWithoutANumericOrder() {
// given
RedisCacheRegionAdapter<String, String> cache = cache(T0);
// when
Throwable refused =
org.assertj.core.api.Assertions.catchThrowable(
() -> cache.record("order-1", "payload", newerThan("rev-2")));
// then
assertThat(refused)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("ONLY_IF_SOURCE_REVISION_NEWER");
}
@Test
@DisplayName("an unreachable Redis degrades: the cache is bypassed, nothing fails")
void anUnreachableRedisDegrades() {
@@ -257,6 +257,116 @@ class RedisIdempotencyStoreAdapterTest {
.isEqualTo(IdempotencyReleaseOutcome.EXECUTION_ALREADY_STARTED);
}
@Test
@DisplayName("renew는 RENEWED와 함께 더 새 revision의 owner 핸들을 돌려준다")
void renewReturnsAHandleAtTheNewRevision() {
// given
IdempotencyOwner executing = executing();
// when
var renewed = store.renew(executing, Duration.ofSeconds(30), OPERATION);
// then
assertThat(renewed.outcome()).isEqualTo(IdempotencyRenewOutcome.RENEWED);
assertThat(renewed.owner().orElseThrow().stateRevision())
.isGreaterThan(executing.stateRevision());
}
@Test
@DisplayName("renew한 처리 lease는 원래 lease가 지난 뒤에도 다른 요청의 claim을 IN_PROGRESS로 막는다")
void aRenewedLeaseStillExcludesAnotherClaimPastTheOriginalExpiry() {
// given
IdempotencyOwner executing = executing();
gateway.advance(Duration.ofSeconds(20));
store.renew(executing, Duration.ofSeconds(30), OPERATION);
// 40 seconds after the claim: past the original 30-second lease, inside the renewed one.
gateway.advance(Duration.ofSeconds(20));
// when
IdempotencyClaimOutcome other = store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
// then
// TAKEN_OVER here would hand a running operation to a second worker: the effect happens twice.
assertThat(other).isInstanceOf(IdempotencyClaimOutcome.InProgress.class);
}
@Test
@DisplayName("renew 응답을 잃고 같은 핸들로 다시 renew하면 ALREADY_RENEWED와 현재 revision 핸들을 받는다")
void aRenewRetriedAfterALostReplyIsAlreadyRenewed() {
// given
IdempotencyOwner executing = executing();
var first = store.renew(executing, Duration.ofSeconds(30), OPERATION);
// when
// The first reply was lost, so the caller still holds the pre-renewal handle.
var retried = store.renew(executing, Duration.ofSeconds(30), OPERATION);
// then
assertThat(retried.outcome()).isEqualTo(IdempotencyRenewOutcome.ALREADY_RENEWED_SAME_OPERATION);
assertThat(retried.owner().orElseThrow().stateRevision())
.isEqualTo(first.owner().orElseThrow().stateRevision());
}
@Test
@DisplayName("lost reply 재시도가 다른 lease 길이를 요청하면 이미 적용된 renew로 확인하지 않는다")
void aRenewRetryAskingForADifferentLeaseIsAConflict() {
// given
IdempotencyOwner executing = executing();
store.renew(executing, Duration.ofSeconds(30), OPERATION);
// when
var retried = store.renew(executing, Duration.ofSeconds(90), OPERATION);
// then
// Confirming it would leave the caller believing it holds the record for 90 seconds.
assertThat(retried.outcome()).isEqualTo(IdempotencyRenewOutcome.OPERATION_CONFLICT);
}
@Test
@DisplayName("renew한 뒤 받은 핸들로 complete할 수 있다")
void theRenewedHandleCanComplete() {
// given
IdempotencyOwner renewed =
store.renew(executing(), Duration.ofSeconds(30), OPERATION).owner().orElseThrow();
// when
IdempotencyCompleteOutcome outcome =
store.complete(renewed, new StoredResponse("{}"), Duration.ofHours(1), OPERATION);
// then
assertThat(outcome).isEqualTo(IdempotencyCompleteOutcome.COMPLETED);
}
@Test
@DisplayName("실행을 시작하지 않은 claim은 renew할 수 없다")
void renewBeforeExecutionStartedIsNotInProgress() {
// given
IdempotencyOwner claimed =
((IdempotencyClaimOutcome.Acquired) store.claim(claim(store.newClaimAttempt(OPERATION))))
.owner();
// when
var renewed = store.renew(claimed, Duration.ofSeconds(30), OPERATION);
// then
assertThat(renewed.outcome()).isEqualTo(IdempotencyRenewOutcome.NOT_IN_PROGRESS);
}
@Test
@DisplayName("lease를 넘겨받은 뒤 이전 owner는 renew할 수 없다")
void aTakenOverOwnerCannotRenew() {
// given
IdempotencyOwner executing = executing();
gateway.advance(Duration.ofSeconds(60));
store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
// when
var renewed = store.renew(executing, Duration.ofSeconds(30), OPERATION);
// then
assertThat(renewed.outcome()).isEqualTo(IdempotencyRenewOutcome.NOT_OWNER);
}
@Test
@DisplayName("an expired processing lease can be taken over, and the attempt increments")
void anExpiredLeaseIsTakenOver() {
+7 -1
View File
@@ -37,7 +37,10 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d
## What the platform decides for you
- **Time.** One effective deadline covers pool acquire, DNS, connect, TLS, write, read, and every
retry backoff. Streaming splits setup, idle, and total lifetime.
retry backoff. It is checked before each attempt and also ends an attempt still in flight: Apache
cancels the request at the deadline, the JDK transport bounds its exchange timeout by the time
left, and the caller gets `HttpDeadlineExceededException`. Streaming splits setup, idle, and total
lifetime.
- **Evidence.** Each attempt reports `NOT_SENT`, `SENT_NO_RESPONSE`, `RESPONSE_RECEIVED`, or
`PARTIAL_RESPONSE`. `NOT_SENT` is only claimed when a stage failure proves it.
- **Retry.** Never from the HTTP method alone. Idempotency, body replayability, evidence, deadline,
@@ -45,6 +48,9 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d
raises `HttpAmbiguousExecutionException` instead of being retried or reported as a plain failure.
- **Order.** Every physical attempt passes Circuit Breaker → Rate Limiter → Bulkhead, and holds no
permit while a backoff waits.
- **Circuit.** The breaker counts transport failures and 5xx, 408, and 429 against the upstream.
Any other 4xx (404, 409, 422 …) is a healthy answer, even when it reaches the caller as
`HttpRemoteErrorException`.
- **Resources.** Connections and buffers are reclaimed after success, error, decode failure, size
rejection, and cancellation alike.
- **Secrets.** No URL, query value, path variable, token, cookie, or idempotency key reaches a log,
@@ -237,6 +237,14 @@ strictTestLanes {
// httpClientFailureInjectionTest (needs Docker), httpClientPerformanceTest (machine-dependent
// bounds) and jmh (minutes) stay out deliberately. Attaching them would make `check` fail on a
// laptop without Docker, which teaches people to skip `check`.
// spring70CompatibilityTest selects the same tagged suite httpClientStableContractTest runs in
// `check`, under the name the release gate and the support matrix quote. The main stage runs it so the
// name's fail-closed selection is proven before a release tag, not first on one (review 2026-11-01
// 08-01).
tasks.named('mainCheck') {
dependsOn 'spring70CompatibilityTest'
}
tasks.named('check') {
dependsOn 'httpClientStableContractTest',
'httpClientSecurityTest',
@@ -21,7 +21,6 @@ import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
/**
* Blocking default transport (design D-06, §13.4).
@@ -84,7 +83,7 @@ public final class ApacheBlockingTransportProvider implements BlockingTransportP
meterRegistry.ifPresent(
registry -> ApachePoolMetricsBinder.bind(registry, profile.name(), runtime.pool()));
listener.onRuntimeCreated(profile.name(), ID);
return new HttpComponentsClientHttpRequestFactory(runtime.client());
return new DeadlineAwareApacheRequestFactory(runtime.client());
}
/** Live pool statistics; the pool-saturation and leak suites assert on these. */
@@ -0,0 +1,34 @@
package dev.caskeleton.adapter.outbound.httpclient.apache;
import dev.caskeleton.adapter.outbound.httpclient.transport.AttemptDeadline;
import java.net.URI;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.core5.concurrent.Cancellable;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
/**
* Spring's Apache request factory with every request cancellable at the attempt deadline.
*
* <p>The classic client's timeouts are all per-gap (connect, response header, socket read idle), so
* none of them bounds a slow-drip response. Apache's own answer is request cancellation: {@code
* HttpUriRequestBase.cancel()} cancels a pending pool lease or closes the leased connection
* immediately, which wakes the blocked read on the caller's thread. The request is registered with
* {@link AttemptDeadline} when it is created, on the caller's thread, inside the attempt scope.
*/
final class DeadlineAwareApacheRequestFactory extends HttpComponentsClientHttpRequestFactory {
DeadlineAwareApacheRequestFactory(HttpClient httpClient) {
super(httpClient);
}
@Override
protected ClassicHttpRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
ClassicHttpRequest request = super.createHttpUriRequest(httpMethod, uri);
if (request instanceof Cancellable cancellable) {
AttemptDeadline.abortOnExpiry(() -> cancellable.cancel());
}
return request;
}
}
@@ -162,6 +162,7 @@ public final class DefaultDynamicTargetGateway implements DynamicTargetGateway {
credentials,
1,
runtime.support().clock().instant(),
deadline,
metadata);
}
@@ -0,0 +1,44 @@
package dev.caskeleton.adapter.outbound.httpclient.jdk;
import dev.caskeleton.adapter.outbound.httpclient.transport.AttemptDeadline;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.Executor;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.JdkClientHttpRequestFactory;
/**
* Spring's JDK request factory with the exchange timeout bounded by the attempt deadline.
*
* <p>Spring's JDK request enforces its read timeout over the whole exchange: when it fires it
* cancels the pending response or closes the body stream, which also ends a slow-drip body. That
* timeout is fixed per factory, so a factory is made per request with {@code min(response-header
* timeout, remaining deadline)} from {@link AttemptDeadline}. The factory only holds references;
* the client and the write executor are shared.
*/
final class DeadlineAwareJdkRequestFactory implements ClientHttpRequestFactory {
private final HttpClient client;
private final Executor writeExecutor;
private final Duration exchangeTimeout;
DeadlineAwareJdkRequestFactory(HttpClient client, Duration exchangeTimeout) {
this.client = Objects.requireNonNull(client, "jdk http client");
this.exchangeTimeout = Objects.requireNonNull(exchangeTimeout, "exchange timeout");
// The executor Spring would pick itself, chosen once instead of once per request.
this.writeExecutor = client.executor().orElseGet(SimpleAsyncTaskExecutor::new);
}
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
JdkClientHttpRequestFactory delegate = new JdkClientHttpRequestFactory(client, writeExecutor);
delegate.setReadTimeout(AttemptDeadline.bound(exchangeTimeout));
return delegate.createRequest(uri, httpMethod);
}
}
@@ -16,7 +16,6 @@ import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.JdkClientHttpRequestFactory;
/**
* Lightweight blocking alternative (design D-06, §13.5).
@@ -62,8 +61,8 @@ public final class JdkBlockingTransportProvider implements BlockingTransportProv
HttpClient client = clientFactory.create(profile, tlsMaterialResolver.apply(profile));
clients.put(new TransportResourceKey(profile.name(), generation), client);
JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(client);
factory.setReadTimeout(profile.timeout().responseHeader());
ClientHttpRequestFactory factory =
new DeadlineAwareJdkRequestFactory(client, profile.timeout().responseHeader());
listener.onRuntimeCreated(profile.name(), ID);
return factory;
}
@@ -0,0 +1,33 @@
package dev.caskeleton.adapter.outbound.httpclient.resilience;
import dev.caskeleton.adapter.outbound.httpclient.api.HttpStatus;
import java.util.Objects;
/**
* Which upstream status codes the circuit breaker records as a failure (design §18.1).
*
* <p>The breaker protects callers from an upstream that is failing or overloaded. A status counts
* against the upstream only when it says exactly that: a 5xx, a 408 (the server gave up waiting),
* or a 429 (the server is shedding load). Every other 4xx is the upstream working correctly and
* answering a request it judged — a 404 for a missing record, a 409 for a conflict, a 422 for a
* rejected payload — and is recorded as a success. Counting those used to open the breaker on a
* perfectly healthy lookup API and reject every call of the profile for the breaker's wait time.
*
* <p>Transport failures (connect, timeout, reset) never reach this policy: they are exceptions, and
* the pipeline records every exception as a failure.
*/
public final class CircuitBreakerStatusPolicy {
private static final int REQUEST_TIMEOUT = 408;
private static final int TOO_MANY_REQUESTS = 429;
private CircuitBreakerStatusPolicy() {}
/** Whether this status is evidence that the upstream itself is failing or overloaded. */
public static boolean countsAsUpstreamFailure(HttpStatus status) {
Objects.requireNonNull(status, "status");
return status.serverError()
|| status.value() == REQUEST_TIMEOUT
|| status.value() == TOO_MANY_REQUESTS;
}
}
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.httpclient.restclient;
import dev.caskeleton.adapter.outbound.httpclient.api.HttpMethod;
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpClientException;
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpDeadlineExceededException;
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpFailureMetadata;
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpRemoteErrorException;
import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage;
@@ -11,9 +12,12 @@ import dev.caskeleton.adapter.outbound.httpclient.auth.RequestCredentials;
import dev.caskeleton.adapter.outbound.httpclient.observation.AttemptObservation;
import dev.caskeleton.adapter.outbound.httpclient.resilience.AttemptOutcome;
import dev.caskeleton.adapter.outbound.httpclient.resilience.AttemptProgressTracker;
import dev.caskeleton.adapter.outbound.httpclient.resilience.CircuitBreakerStatusPolicy;
import dev.caskeleton.adapter.outbound.httpclient.resilience.Deadline;
import dev.caskeleton.adapter.outbound.httpclient.resilience.ProtocolEvidence;
import dev.caskeleton.adapter.outbound.httpclient.security.PreparedOperation;
import dev.caskeleton.adapter.outbound.httpclient.security.PreparedTarget;
import dev.caskeleton.adapter.outbound.httpclient.transport.AttemptDeadline;
import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailure;
import java.net.URI;
import java.time.Duration;
@@ -44,9 +48,41 @@ public final class BlockingAttemptExecutor {
RequestCredentials credentials,
int attemptNumber,
Instant startedAt,
Deadline deadline,
HttpFailureMetadata baseMetadata) {
Objects.requireNonNull(runtime, "runtime");
Objects.requireNonNull(deadline, "deadline");
ExecutionSupport support = runtime.support();
// The deadline scope is what lets the effective deadline end an attempt that is already in
// flight. Before it, the deadline was only checked before an attempt started, and a slow-drip
// upstream kept a started attempt alive past the total budget for as long as no single gap
// reached a stage timeout. The transport reads the scope (see AttemptDeadline).
try (AttemptDeadline.Scope scope = AttemptDeadline.open(deadline.remaining(support.clock()))) {
return executeWithin(
scope,
runtime,
prepared,
responseType,
statusHandlingPolicy,
credentials,
attemptNumber,
startedAt,
baseMetadata);
}
}
private <T> AttemptOutcome<T> executeWithin(
AttemptDeadline.Scope scope,
BlockingClientRuntime runtime,
PreparedOperation prepared,
ResponseType<T> responseType,
StatusHandlingPolicy statusHandlingPolicy,
RequestCredentials credentials,
int attemptNumber,
Instant startedAt,
HttpFailureMetadata baseMetadata) {
ExecutionSupport support = runtime.support();
AttemptProgressTracker tracker = new AttemptProgressTracker();
AttemptObservation observation =
@@ -108,18 +144,14 @@ public final class BlockingAttemptExecutor {
tracker.firstByteDelivered());
}
},
outcome ->
outcome.failureCategory() == FailureCategory.REMOTE_STATUS
? outcome.failure().map(failure -> (Throwable) failure)
: Optional.empty());
stopObservation(observation, attemptOutcome);
return attemptOutcome;
BlockingAttemptExecutor::upstreamFailure);
return finish(observation, scope, attemptOutcome);
} catch (HttpClientException stable) {
AttemptOutcome<T> outcome =
return finish(
observation,
scope,
AttemptOutcome.failed(
stable, stable.category(), Optional.empty(), tracker.firstByteDelivered());
stopObservation(observation, outcome);
return outcome;
stable, stable.category(), Optional.empty(), tracker.firstByteDelivered()));
} catch (RuntimeException engineFailure) {
TransportFailure classified =
runtime.failureClassifier().classify(engineFailure, tracker.stage());
@@ -137,14 +169,64 @@ public final class BlockingAttemptExecutor {
.withStage(classified.stage());
HttpClientException mapped =
support.exceptionMapper().map(classified, metadata, engineFailure);
AttemptOutcome<T> outcome =
return finish(
observation,
scope,
AttemptOutcome.failed(
mapped, classified.category(), Optional.empty(), tracker.firstByteDelivered());
stopObservation(observation, outcome);
return outcome;
mapped, classified.category(), Optional.empty(), tracker.firstByteDelivered()));
}
}
/**
* Stops the observation with the attempt's outcome, naming the deadline when it ended the
* attempt.
*
* <p>A deadline abort reaches the executor as whatever the engine threw when its connection was
* closed — a reset, a truncated body, a read timeout. Reported as that, a caller would see a
* transport fault on a healthy upstream and the retry policy would judge the wrong cause. A
* failure that ends after the deadline passed is therefore reported as the deadline. Two outcomes
* keep their own meaning: a response that completed stays a success, and a complete error
* response (a remote status) stays the upstream's answer — both arrived, whatever the clock says.
*/
private <T> AttemptOutcome<T> finish(
AttemptObservation observation, AttemptDeadline.Scope scope, AttemptOutcome<T> outcome) {
AttemptOutcome<T> reported = outcome;
if (!outcome.successful()
&& outcome.failureCategory() != FailureCategory.REMOTE_STATUS
&& scope.expired()) {
HttpClientException cause = outcome.failure().orElseThrow();
reported =
AttemptOutcome.failed(
new HttpDeadlineExceededException(
"effective deadline reached while the attempt was in flight",
cause.metadata(),
cause),
FailureCategory.DEADLINE_EXCEEDED,
Optional.empty(),
outcome.firstByteDelivered());
}
stopObservation(observation, reported);
return reported;
}
/**
* The failure the circuit breaker records for a returned outcome, if any.
*
* <p>Only a remote status that {@link CircuitBreakerStatusPolicy} counts against the upstream is
* a breaker failure. A 404 thrown to the caller as {@code HttpRemoteErrorException} is still a
* healthy answer for the breaker.
*/
private static Optional<Throwable> upstreamFailure(AttemptOutcome<?> outcome) {
if (outcome.failureCategory() != FailureCategory.REMOTE_STATUS) {
return Optional.empty();
}
boolean countsAgainstUpstream =
outcome.status().map(CircuitBreakerStatusPolicy::countsAsUpstreamFailure).orElse(true);
return countsAgainstUpstream
? outcome.failure().map(failure -> (Throwable) failure)
: Optional.empty();
}
private void stopObservation(AttemptObservation observation, AttemptOutcome<?> outcome) {
if (outcome.failureCategory() == FailureCategory.RESPONSE_TIMEOUT
|| outcome.failureCategory() == FailureCategory.POOL_ACQUIRE_TIMEOUT
@@ -173,6 +173,7 @@ public final class DefaultGenericHttpGateway implements GenericHttpGateway {
credentials,
attemptNumber,
startedAt,
deadline,
metadata.withAttempt(attemptNumber));
}
@@ -0,0 +1,158 @@
package dev.caskeleton.adapter.outbound.httpclient.transport;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
/**
* The time the physical attempt running on this thread has left before the logical call's effective
* deadline (design D-10, §15.2).
*
* <p>The gateway checks the deadline before an attempt starts, but a stage timeout only bounds one
* gap: an upstream that sends a byte every second never trips a three-second read-idle timeout and
* can hold the caller, its virtual thread and a pooled connection indefinitely. The gateway opens a
* {@link Scope} around each attempt and the transport — the only party that can actually stop an
* exchange — reads it:
*
* <ul>
* <li>a transport with a cancellable request registers the cancel with {@link
* #abortOnExpiry(Runnable)}, and the scope runs it when the deadline passes;
* <li>a transport whose engine already enforces a whole-exchange timeout bounds that timeout with
* {@link #bound(Duration)}.
* </ul>
*
* <p>The scope is thread-confined because a blocking attempt runs on the caller's thread from
* request creation to the last body byte. When no scope is open — a transport used outside the
* gateway — both methods leave the transport's own behaviour unchanged.
*/
public final class AttemptDeadline {
private static final ThreadLocal<Scope> CURRENT = new ThreadLocal<>();
private AttemptDeadline() {}
/**
* Opens the deadline scope for one attempt on the current thread.
*
* @param remaining the time left before the logical call's effective deadline
*/
public static Scope open(Duration remaining) {
Objects.requireNonNull(remaining, "remaining deadline");
Scope scope = new Scope(remaining.isNegative() ? Duration.ZERO : remaining, CURRENT.get());
CURRENT.set(scope);
return scope;
}
/** The current attempt's remaining time, or empty when no attempt scope is open. */
public static Optional<Duration> remaining() {
return Optional.ofNullable(CURRENT.get()).map(Scope::remaining);
}
/** A stage timeout no longer than the current attempt's remaining time. */
public static Duration bound(Duration stageTimeout) {
Objects.requireNonNull(stageTimeout, "stage timeout");
return remaining()
.filter(remaining -> remaining.compareTo(stageTimeout) < 0)
.orElse(stageTimeout);
}
/**
* Registers how to abort the exchange the current attempt is about to start.
*
* <p>Runs the abort at once if the deadline has already passed. Does nothing when no scope is
* open.
*/
public static void abortOnExpiry(Runnable abort) {
Objects.requireNonNull(abort, "abort");
Scope scope = CURRENT.get();
if (scope != null) {
scope.register(abort);
}
}
/** One attempt's deadline; closing it cancels the pending abort and restores the outer scope. */
public static final class Scope implements AutoCloseable {
private final long endNanos;
private final Scope outer;
private final CompletableFuture<Void> timer = new CompletableFuture<>();
private final CompletableFuture<Void> expiry;
private final List<Runnable> aborts = new ArrayList<>();
private boolean fired;
private boolean closed;
private Scope(Duration remaining, Scope outer) {
this.endNanos = System.nanoTime() + remaining.toNanos();
this.outer = outer;
// The JDK's shared delay scheduler, the same one Spring's JDK request uses for its timeout.
// Completing the future on close() also cancels the scheduled task, so a finished attempt
// leaves nothing behind.
this.expiry =
timer
.completeOnTimeout(null, remaining.toNanos(), TimeUnit.NANOSECONDS)
.thenRun(this::expire);
}
/** Whether the deadline passed while this attempt was running. */
public boolean expired() {
synchronized (this) {
if (fired) {
return true;
}
}
return System.nanoTime() - endNanos >= 0;
}
Duration remaining() {
long left = endNanos - System.nanoTime();
return left > 0 ? Duration.ofNanos(left) : Duration.ZERO;
}
private void register(Runnable abort) {
boolean runNow;
synchronized (this) {
runNow = fired;
if (!runNow && !closed) {
aborts.add(abort);
}
}
if (runNow) {
abort.run();
}
}
private void expire() {
List<Runnable> toRun;
synchronized (this) {
if (closed) {
return;
}
fired = true;
toRun = List.copyOf(aborts);
aborts.clear();
}
toRun.forEach(Runnable::run);
}
@Override
public void close() {
synchronized (this) {
closed = true;
aborts.clear();
}
timer.complete(null);
expiry.cancel(false);
if (CURRENT.get() == this) {
if (outer == null) {
CURRENT.remove();
} else {
CURRENT.set(outer);
}
}
}
}
}
@@ -0,0 +1,41 @@
package dev.caskeleton.adapter.outbound.httpclient.resilience;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.httpclient.api.HttpStatus;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class CircuitBreakerStatusPolicyTest {
@ParameterizedTest(name = "{0} -> {1}")
@CsvSource({
"400, false",
"401, false",
"403, false",
"404, false",
"409, false",
"410, false",
"422, false",
"408, true",
"429, true",
"500, true",
"501, true",
"502, true",
"503, true",
"504, true",
"599, true"
})
@DisplayName("5xx·408·429만 상대 서버 장애로 세고 나머지 4xx는 정상 응답으로 센다")
void onlyServerSideStatusesCountAgainstTheUpstream(int status, boolean upstreamFailure) {
// given
HttpStatus answered = new HttpStatus(status);
// when
boolean counted = CircuitBreakerStatusPolicy.countsAsUpstreamFailure(answered);
// then
assertThat(counted).isEqualTo(upstreamFailure);
}
}
@@ -0,0 +1,81 @@
package dev.caskeleton.adapter.outbound.httpclient.restclient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.outbound.httpclient.api.OperationName;
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpDeadlineExceededException;
import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation;
import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType;
import dev.caskeleton.adapter.outbound.httpclient.profile.TimeoutSettings;
import dev.caskeleton.adapter.outbound.httpclient.profile.TransportType;
import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles;
import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer;
import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways;
import java.time.Duration;
import java.util.Map;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
/**
* The total-call budget ends an attempt that is still in flight (finding 05-06, design D-10).
*
* <p>The upstream answers at once and then sends one body byte every 50 ms. No gap reaches the
* read-idle (3 s) or response-header (2 s) timeout, and the whole body would take 5 s, so only the
* one-second total budget can end the call on time.
*/
class AttemptDeadlineEnforcementTest {
private static final Duration TOTAL_CALL = Duration.ofSeconds(1);
private static final Duration TOLERANCE = Duration.ofMillis(500);
@ParameterizedTest(name = "{0}")
@EnumSource(
value = TransportType.class,
names = {"APACHE", "JDK"})
@DisplayName("바이트를 조금씩 흘리는 상대 서버라도 호출은 전체 시간 예산 안에 deadline 초과로 끝난다")
void aSlowDripResponseIsCutOffAtTheTotalDeadline(TransportType transport) throws Exception {
try (MockHttpServer server = MockHttpServer.start();
TestGateways.Harness harness =
TestGateways.forProfile(
ClientProfiles.builder("slow")
.baseUrl(server.uri("/"))
.transport(transport)
.timeout(withTotalCall(TOTAL_CALL))
.build())) {
// given
server.enqueueSlowDripBody(200, 100, Duration.ofMillis(50));
long started = System.nanoTime();
// when
Throwable failure =
catchThrowable(
() ->
harness
.gateway()
.exchange(
harness.profile().name(),
HttpOperation.get(new OperationName("slow-read"), "/slow", Map.of()),
ResponseType.of(String.class)));
// then
Duration elapsed = Duration.ofNanos(System.nanoTime() - started);
assertThat(failure).isInstanceOf(HttpDeadlineExceededException.class);
assertThat(elapsed).isLessThan(TOTAL_CALL.plus(TOLERANCE));
}
}
private static TimeoutSettings withTotalCall(Duration totalCall) {
TimeoutSettings base = ClientProfiles.timeouts();
return new TimeoutSettings(
base.dns(),
base.connect(),
base.tlsHandshake(),
base.proxyConnect(),
base.requestWriteIdle(),
base.responseHeader(),
base.readIdle(),
totalCall);
}
}
@@ -0,0 +1,89 @@
package dev.caskeleton.adapter.outbound.httpclient.restclient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.outbound.httpclient.api.OperationName;
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpCircuitOpenException;
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpRemoteErrorException;
import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation;
import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType;
import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer;
import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* What the per-profile circuit breaker counts as an upstream failure, end to end (finding 05-05).
*
* <p>The library defaults are kept on purpose (a 100-call window, a 50% failure threshold), so 200
* calls are enough to open the breaker twice over if a status were miscounted.
*/
class CircuitBreakerStatusAccountingTest {
private static final int CALLS = 200;
private static final int LIBRARY_DEFAULT_WINDOW = 100;
@Test
@DisplayName("정상 응답인 404가 200번 이어져도 circuit이 열리지 않고 모든 호출이 상대 서버에 닿는다")
void aRunOfNotFoundAnswersNeverOpensTheCircuit() throws Exception {
try (MockHttpServer server = MockHttpServer.start();
TestGateways.Harness harness = TestGateways.apache(server.uri("/"))) {
// given
for (int i = 0; i < CALLS; i++) {
server.enqueueStatus(404);
}
List<Throwable> failures = new ArrayList<>();
// when
for (int i = 0; i < CALLS; i++) {
failures.add(catchThrowable(() -> getUser(harness)));
}
// then
assertThat(failures)
.hasSize(CALLS)
.allSatisfy(
failure ->
assertThat(failure)
.isExactlyInstanceOf(HttpRemoteErrorException.class)
.isNotInstanceOf(HttpCircuitOpenException.class));
assertThat(server.requestCount()).isEqualTo(CALLS);
}
}
@Test
@DisplayName("503이 창 하나를 채우면 circuit이 열려 다음 호출은 상대 서버에 보내지 않고 거절한다")
void aWindowOfServiceUnavailableAnswersOpensTheCircuit() throws Exception {
try (MockHttpServer server = MockHttpServer.start();
TestGateways.Harness harness = TestGateways.apache(server.uri("/"))) {
// given
List<Throwable> windowFailures = new ArrayList<>();
for (int i = 0; i < LIBRARY_DEFAULT_WINDOW; i++) {
server.enqueueStatus(503);
windowFailures.add(catchThrowable(() -> getUser(harness)));
}
assertThat(windowFailures)
.allSatisfy(f -> assertThat(f).isInstanceOf(HttpRemoteErrorException.class));
// when
Throwable next = catchThrowable(() -> getUser(harness));
// then
assertThat(next).isInstanceOf(HttpCircuitOpenException.class);
assertThat(server.requestCount()).isEqualTo(LIBRARY_DEFAULT_WINDOW);
}
}
private static void getUser(TestGateways.Harness harness) {
harness
.gateway()
.exchange(
harness.profile().name(),
HttpOperation.get(new OperationName("get-user"), "/users/1", Map.of()),
ResponseType.of(String.class));
}
}
@@ -0,0 +1,96 @@
package dev.caskeleton.adapter.outbound.httpclient.transport;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class AttemptDeadlineTest {
@Test
@DisplayName("attempt scope가 없으면 단계 timeout을 그대로 둔다")
void withoutAScopeTheStageTimeoutIsUnchanged() {
// given
Duration stage = Duration.ofSeconds(2);
// when
Duration bounded = AttemptDeadline.bound(stage);
// then
assertThat(bounded).isEqualTo(stage);
assertThat(AttemptDeadline.remaining()).isEmpty();
}
@Test
@DisplayName("남은 deadline이 단계 timeout보다 짧으면 단계 timeout을 남은 시간으로 줄인다")
void aShorterRemainingDeadlineBoundsTheStageTimeout() {
try (AttemptDeadline.Scope scope = AttemptDeadline.open(Duration.ofMillis(300))) {
// given
Duration stage = Duration.ofSeconds(2);
// when
Duration bounded = AttemptDeadline.bound(stage);
// then
assertThat(bounded).isLessThanOrEqualTo(Duration.ofMillis(300)).isPositive();
assertThat(scope.expired()).isFalse();
}
}
@Test
@DisplayName("deadline이 지나면 등록된 중단 동작을 실행하고 scope는 만료로 보고한다")
void theRegisteredAbortRunsWhenTheDeadlinePasses() throws Exception {
try (AttemptDeadline.Scope scope = AttemptDeadline.open(Duration.ofMillis(50))) {
// given
CountDownLatch aborted = new CountDownLatch(1);
AttemptDeadline.abortOnExpiry(aborted::countDown);
// when
boolean ran = aborted.await(2, TimeUnit.SECONDS);
// then
assertThat(ran).isTrue();
assertThat(scope.expired()).isTrue();
}
}
@Test
@DisplayName("deadline 전에 attempt가 끝나면 중단 동작은 실행되지 않고 scope도 풀린다")
void closingTheScopeBeforeTheDeadlineCancelsTheAbort() throws Exception {
// given
AtomicInteger aborts = new AtomicInteger();
AttemptDeadline.Scope scope = AttemptDeadline.open(Duration.ofMillis(100));
AttemptDeadline.abortOnExpiry(aborts::incrementAndGet);
// when
scope.close();
// then
Thread.sleep(300);
assertThat(aborts).hasValue(0);
assertThat(AttemptDeadline.remaining()).isEmpty();
}
@Test
@DisplayName("이미 지난 deadline에 등록한 중단 동작은 바로 실행된다")
void anAbortRegisteredAfterExpiryRunsAtOnce() throws Exception {
try (AttemptDeadline.Scope scope = AttemptDeadline.open(Duration.ZERO)) {
// given
CountDownLatch expired = new CountDownLatch(1);
AttemptDeadline.abortOnExpiry(expired::countDown);
assertThat(expired.await(2, TimeUnit.SECONDS)).isTrue();
AtomicInteger late = new AtomicInteger();
// when
AttemptDeadline.abortOnExpiry(late::incrementAndGet);
// then
assertThat(late).hasValue(1);
assertThat(scope.expired()).isTrue();
}
}
}
@@ -151,6 +151,21 @@ public final class MockHttpServer implements AutoCloseable {
.setBodyDelay(delay.toMillis(), TimeUnit.MILLISECONDS));
}
/**
* Sends headers at once, then the body one byte per {@code gap}; drives total-deadline tests.
*
* <p>Every gap stays shorter than any idle timeout a test profile uses, so only a whole-call
* budget can end the exchange before the body is complete.
*/
public void enqueueSlowDripBody(int status, int bodyBytes, Duration gap) {
server.enqueue(
new MockResponse()
.setResponseCode(status)
.setHeader("Content-Type", "text/plain")
.setBody("x".repeat(bodyBytes))
.throttleBody(1, gap.toMillis(), TimeUnit.MILLISECONDS));
}
public RecordedHttpRequest takeRequest(Duration timeout) throws InterruptedException {
RecordedRequest recorded = server.takeRequest(timeout.toMillis(), TimeUnit.MILLISECONDS);
if (recorded == null) {
+10 -3
View File
@@ -31,9 +31,16 @@ seam과 그 위의 `MessagePublisher`·`OutboxEnvelopeJson`은 outbox를 canonic
있을 때만 생성된다. exact `ValidatedIntegrationEvent.envelopeBytes()`를 보존하고 platform의 중앙
publish pipeline을 탄다. producer id는 host/pod/process 이름에서 추측하지 않는다.
`OutboxMessagePublishAdapter`는 claim된 row의 validated event를 그대로 bridge에 넘기고 platform의
네 가지 결과(CONFIRMED·AMBIGUOUS·REJECTED_BEFORE_SEND·REJECTED_AFTER_BROKER)를 relay에 돌려준다.
다시 직렬화하지 않는다.
`OutboxMessagePublishAdapter`는 claim된 row의 validated event를 그대로 bridge에 넘기고 platform
결과를 application 결과(CONFIRMED·AMBIGUOUS·REJECTED_BEFORE_SEND·REJECTED_AFTER_BROKER·
REJECTED_RETRYABLE)로 번역해 relay에 돌려준다. 다시 직렬화하지 않는다.
platform `REJECTED` 중 `FailureDescriptor.retryable()`이 true인 것(종료 중 `SHUTTING_DOWN`, permit
대기 초과, `PUBLISH_RUNTIME_UNAVAILABLE`, `KAFKA_TRANSPORT_CLOSED`, Kafka 인증·인가 실패)은
`REJECTED_RETRYABLE`로 번역한다. relay는 이 값을 DEAD로 보내지 않고 재시도한다. 확정 거부 두 값으로
번역하면 "같은 payload는 또 거부된다"로 읽혀 커밋된 이벤트와 그 aggregate의 뒤 이벤트가 바로
멈춘다(2026-11-01 리뷰 06-01). `AMBIGUOUS`로 번역하지 않은 이유: 동작은 같지만 "전송됐을 수
있음"이라는 거짓 정보가 남아 중복 경고를 오염시킨다.
## outbox 발행 포트에는 대역이 없다
@@ -15,6 +15,7 @@ import dev.caskeleton.messaging.api.TenantContext;
import dev.caskeleton.messaging.api.TraceContext;
import dev.caskeleton.messaging.api.destination.DestinationName;
import dev.caskeleton.messaging.api.destination.MessageDestination;
import dev.caskeleton.messaging.api.error.FailureDescriptor;
import dev.caskeleton.messaging.api.header.HeaderName;
import dev.caskeleton.messaging.api.header.HeaderValue;
import dev.caskeleton.messaging.api.header.MessageHeaders;
@@ -137,6 +138,16 @@ public final class PlatformIntegrationEventPublishAdapter implements Integration
return new CausationId(canonicalMessageId(value));
}
/**
* Translates the platform's result into the application's outcome.
*
* <p>A platform rejection carries a {@code retryable} flag, and the platform sets it on refusals
* that are about the moment — shutting down, permits exhausted, transport closed, credentials
* refused. The application reads both of its definite rejections as "the same payload is refused
* again" and dead-letters at once, so a retryable rejection translated into one of them parks a
* committed event, and its aggregate behind it, for a cause that clears on its own. It gets its
* own value instead.
*/
private static OutboxPublishOutcome mapOutcome(PublishResult result) {
Objects.requireNonNull(result, "publish result must not be null");
if (result.completion() == PublishCompletion.CONFIRMED) {
@@ -145,6 +156,9 @@ public final class PlatformIntegrationEventPublishAdapter implements Integration
if (result.completion() == PublishCompletion.AMBIGUOUS) {
return OutboxPublishOutcome.AMBIGUOUS;
}
if (result.failure().map(FailureDescriptor::retryable).orElse(false)) {
return OutboxPublishOutcome.REJECTED_RETRYABLE;
}
return result.evidence().transmission() == TransmissionEvidence.NOT_TRANSMITTED
? OutboxPublishOutcome.REJECTED_BEFORE_SEND
: OutboxPublishOutcome.REJECTED_AFTER_BROKER;
@@ -33,6 +33,7 @@ import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class PlatformIntegrationEventPublishAdapterTest {
@@ -102,6 +103,50 @@ class PlatformIntegrationEventPublishAdapterTest {
.isEqualTo(OutboxPublishOutcome.REJECTED_AFTER_BROKER);
}
@Test
@DisplayName("platform이 다시 시도해도 된다고 표시한 거부는 확정 거부로 번역하지 않는다")
void aRefusalThePlatformMarksRetryableIsNotTranslatedIntoADefiniteRejection() {
// given: the runtime refused because it is shutting down, and said a retry may succeed
RecordingPublisher publisher =
new RecordingPublisher(
PublishResult.rejected(
Duration.ZERO,
FailureDescriptor.of(
FailureCategory.TRANSIENT_INFRASTRUCTURE,
"SHUTTING_DOWN",
"the messaging runtime stopped accepting new publishes")));
PlatformIntegrationEventPublishAdapter bridge =
new PlatformIntegrationEventPublishAdapter(publisher, "portfolio-service");
// when
OutboxPublishOutcome outcome =
bridge.publish(event(EVENT_ID, Optional.empty())).toCompletableFuture().join();
// then
assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_RETRYABLE);
}
@Test
@DisplayName("다시 시도해도 같은 결과인 거부는 지금처럼 확정 거부로 번역한다")
void aRefusalThePlatformMarksFinalStaysADefiniteRejection() {
// given: the runtime refused a destination this application may not publish to
RecordingPublisher publisher =
new RecordingPublisher(
PublishResult.rejected(
Duration.ZERO,
FailureDescriptor.of(
FailureCategory.CONFIGURATION, "PUBLISH_FORBIDDEN", "not allowed")));
PlatformIntegrationEventPublishAdapter bridge =
new PlatformIntegrationEventPublishAdapter(publisher, "portfolio-service");
// when
OutboxPublishOutcome outcome =
bridge.publish(event(EVENT_ID, Optional.empty())).toCompletableFuture().join();
// then
assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_BEFORE_SEND);
}
@Test
void incompatibleApplicationIdentityFailsClosedBeforePublisherInvocation() {
RecordingPublisher publisher = new RecordingPublisher(confirmed());
@@ -70,6 +70,10 @@ class NotificationPlatformWorkerConfig {
reconciliation::reconcile,
clock,
properties.leaseDuration(),
// The claim lease reuses the delivery lease rather than adding a setting. One pass asks
// up to claimBatchSize providers in turn, so a pass slower than the lease lets another
// instance re-ask its remaining jobs; the claim fence keeps those answers recorded once.
properties.leaseDuration(),
properties.claimBatchSize(),
properties.maxAdditionalAttempts() + 1);
}
@@ -22,6 +22,11 @@ import java.util.function.Function;
* will not change, so the job is completed and the attempt stays visibly ambiguous for an operator
* — a busy loop against a capability that does not exist is how a background worker burns a
* connection pool while achieving nothing.
*
* <p>Every instance runs this worker, so the claim is a lease: the jobs a pass takes are this
* instance's until {@code claimLease} has passed, and no transaction is held while the provider is
* asked. A pass that outlives its lease may find a job taken over by another instance; the store
* then ignores this pass's write for it, so the job is asked about twice but recorded once.
*/
public final class ReconciliationJobWorker {
@@ -32,6 +37,7 @@ public final class ReconciliationJobWorker {
reconciler;
private final Clock clock;
private final Duration retryBackoff;
private final Duration claimLease;
private final int batchSize;
private final int maxAttempts;
@@ -42,6 +48,7 @@ public final class ReconciliationJobWorker {
* @param reconciler asks one attempt's provider
* @param clock the clock
* @param retryBackoff how long to wait before asking again
* @param claimLease how long one pass owns the jobs it claimed; must cover the whole pass
* @param batchSize how many jobs one pass handles
* @param maxAttempts how many times one job may ask before it is left to an operator
*/
@@ -53,6 +60,7 @@ public final class ReconciliationJobWorker {
reconciler,
Clock clock,
Duration retryBackoff,
Duration claimLease,
int batchSize,
int maxAttempts) {
this.jobs = Objects.requireNonNull(jobs, "jobs");
@@ -62,6 +70,10 @@ public final class ReconciliationJobWorker {
if (retryBackoff.isNegative() || retryBackoff.isZero()) {
throw new IllegalArgumentException("retryBackoff must be positive and finite");
}
this.claimLease = Objects.requireNonNull(claimLease, "claimLease");
if (claimLease.isNegative() || claimLease.isZero()) {
throw new IllegalArgumentException("claimLease must be positive");
}
if (batchSize < 1) {
throw new IllegalArgumentException("batchSize");
}
@@ -78,7 +90,7 @@ public final class ReconciliationJobWorker {
* @return how many jobs reached a terminal decision
*/
public int reconcileOnce() {
List<ReconciliationJob> due = jobs.claimDue(batchSize, clock.instant());
List<ReconciliationJob> due = jobs.claimDue(batchSize, clock.instant(), claimLease);
int settled = 0;
for (ReconciliationJob job : due) {
// One job's failure is not the pass's: a provider that is refusing connections would
@@ -33,12 +33,14 @@ class ReconciliationJobWorkerTest {
private static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z");
private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC);
private static final Duration CLAIM_LEASE = Duration.ofMinutes(2);
private final RecordingJobs jobs = new RecordingJobs();
private final Map<DeliveryAttemptId, ReconciliationResult> answers = new java.util.HashMap<>();
private final ReconciliationJobWorker worker =
new ReconciliationJobWorker(jobs, answers::get, CLOCK, Duration.ofMinutes(5), 10, 3);
new ReconciliationJobWorker(
jobs, answers::get, CLOCK, Duration.ofMinutes(5), CLAIM_LEASE, 10, 3);
@Test
@DisplayName("a confirmed outcome completes the job")
@@ -125,6 +127,21 @@ class ReconciliationJobWorkerTest {
assertThat(jobs.rescheduled.get(0).getKey()).isEqualTo(failing.id());
}
@Test
@DisplayName("한 번의 pass는 설정된 lease 동안 소유하도록 job을 claim한다")
void aPassClaimsItsJobsForTheConfiguredLease() {
// given
due(0);
// when
worker.reconcileOnce();
// then
assertThat(jobs.claimLeases)
.as("without a lease the claim ends with the statement and every instance takes the job")
.containsExactly(CLAIM_LEASE);
}
private ReconciliationJob due(int attempts) {
ReconciliationJob job =
new ReconciliationJob(
@@ -135,7 +152,8 @@ class ReconciliationJobWorkerTest {
attempts,
Optional.empty(),
NOW,
NOW);
NOW,
1);
jobs.due.add(job);
return job;
}
@@ -155,6 +173,7 @@ class ReconciliationJobWorkerTest {
private final List<ReconciliationJob> due = new ArrayList<>();
private final List<UUID> completed = new ArrayList<>();
private final List<Map.Entry<UUID, Instant>> rescheduled = new ArrayList<>();
private final List<Duration> claimLeases = new ArrayList<>();
@Override
public ReconciliationJob schedule(
@@ -163,7 +182,8 @@ class ReconciliationJobWorkerTest {
}
@Override
public List<ReconciliationJob> claimDue(int limit, Instant now) {
public List<ReconciliationJob> claimDue(int limit, Instant now, Duration lease) {
claimLeases.add(lease);
return List.copyOf(due);
}
@@ -91,3 +91,30 @@ composition side effects/lifecycle, routing replay/read behavior, and the readin
cd src
./gradlew :adapter:outbound:objectstorage:check --console=plain
```
### MinIO qualification lanes
`objectStorageMinioContractTest` and `objectStorageMinioFaultTest` (in `mainCheck`) run a real MinIO
and Toxiproxy. Their images are read from one file,
`src/test/resources/object-storage/minio-provider-evidence.json`, whose `image` digest is the
release the `status`, `excludedProfiles` and `limitations` beside it were measured on.
`MinioQualificationImage` (in `src/test`, checked by the leaf's `test` without Docker) reads it.
- The image is pulled before any container is built. If it cannot be pulled the lane fails with
`pinned image unavailable: <reference>`: a supply failure, not an adapter defect. The lane does
not skip, because a skipped vendor lane would be green with no vendor evidence.
- A mirror of the same digest is set with `OBJECT_STORAGE_MINIO_IMAGE` or
`-PobjectStorageMinioImage=<registry>/<repo>@sha256:<evidence digest>`. A value that does not end
in the evidence digest is refused: a different build is a new measurement, made by re-running the
lanes and rewriting the evidence file (image and findings together).
- The local compose runtime (`docker-compose.infra.yml`, `LOCAL_MINIO_IMAGE`) is a different, later
release and is not evidence; the comment there says why.
As of 2026-11-01 a pull of `minio/minio` from Docker Hub answers "repository does not exist", so
these lanes fail with the message above until a mirror or a re-measured replacement is chosen
(review 05-09; the choice is an open owner decision).
```bash
cd src
./gradlew :adapter:outbound:objectstorage:objectStorageMinioContractTest --console=plain
```
@@ -35,6 +35,12 @@ testing {
}
}
}
// The MinIO lanes read their images from the one evidence file in src/test/resources
// (object-storage/minio-provider-evidence.json) through MinioQualificationImage in src/test, which
// the leaf's `test` checks without Docker. The integration runtime therefore sees the test output;
// its own tests are still only the classes each lane `requires`.
sourceSets.integrationTest.compileClasspath += sourceSets.test.output
sourceSets.integrationTest.runtimeClasspath += sourceSets.test.output
configurations {
integrationTestImplementation.extendsFrom testImplementation
integrationTestRuntimeOnly.extendsFrom testRuntimeOnly
@@ -82,14 +88,24 @@ tasks.named('test') {
systemProperty 'objectstorage.readiness.registry', objectStorageReadinessRegistry.absolutePath
}
// A mirror of the measured MinIO digest, for when the origin registry stops serving it (review
// 05-09). Either spelling reaches the lanes as one system property; MinioQualificationImage refuses
// a value that does not end in the evidence digest, because another build is a new measurement and
// is made by editing the evidence file, not by an override.
def minioImageOverride = (findProperty('objectStorageMinioImage')
?: providers.environmentVariable('OBJECT_STORAGE_MINIO_IMAGE').getOrElse('')).toString()
strictTestLanes {
lane('objectStorageMinioContractTest') {
integration()
sourceSet = 'integrationTest'
description = 'Runs the non-skipping exact-release MinIO managed object contract.'
description = 'Runs the non-skipping MinIO managed object contract on the evidence-pinned image.'
requires 'dev.caskeleton.adapter.outbound.objectstorage.qualification.MinioManagedObjectContractTest'
rejectSkipped = true
jvmArgs '-Duser.timezone=UTC'
if (minioImageOverride) {
systemProperty 'objectstorage.minio.image', minioImageOverride
}
shouldRunAfter 'test'
}
lane('objectStorageMinioFaultTest') {
@@ -99,6 +115,9 @@ strictTestLanes {
requires 'dev.caskeleton.adapter.outbound.objectstorage.qualification.MinioManagedObjectFaultTest'
rejectSkipped = true
jvmArgs '-Duser.timezone=UTC'
if (minioImageOverride) {
systemProperty 'objectstorage.minio.image', minioImageOverride
}
shouldRunAfter 'objectStorageMinioContractTest'
}
lane('objectStorageAwsQualificationTest') {
@@ -17,7 +17,6 @@ import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.utility.DockerImageName;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.async.AsyncRequestBody;
@@ -48,8 +47,6 @@ import software.amazon.awssdk.services.s3.model.VersioningConfiguration;
class MinioManagedObjectContractTest {
private static final String MINIO_IMAGE =
"minio/minio@sha256:4c4a4876193f030c81f57aabb22bcb9a73462010eb61fcab66908e03e5484af8";
private static final String REGION = "us-east-1";
private static final String BUCKET = "object-storage-contract";
private static final String VERSIONED_BUCKET = "object-storage-versioned";
@@ -68,7 +65,7 @@ class MinioManagedObjectContractTest {
SECURE_RANDOM.nextBytes(keyBytes);
String kmsKey = "contract-key:" + Base64.getEncoder().encodeToString(keyBytes);
minio =
new GenericContainer<>(DockerImageName.parse(MINIO_IMAGE))
new GenericContainer<>(QualificationImages.minio())
.withExposedPorts(9000)
.withEnv("MINIO_ROOT_USER", accessKey)
.withEnv("MINIO_ROOT_PASSWORD", secretKey)
@@ -34,25 +34,18 @@ class MinioManagedObjectFaultTest {
private static final String CUT_CONNECTION_DOWNSTREAM = "CUT_CONNECTION_DOWNSTREAM";
private static final String CUT_CONNECTION_UPSTREAM = "CUT_CONNECTION_UPSTREAM";
private static final DockerImageName MINIO_IMAGE =
DockerImageName.parse(
"minio/minio@sha256:4c4a4876193f030c81f57aabb22bcb9a73462010eb61fcab66908e03e5484af8");
private static final DockerImageName TOXIPROXY_IMAGE =
DockerImageName.parse(
"ghcr.io/shopify/toxiproxy@sha256:"
+ "9378ed52a28bc50edc1350f936f518f31fa95f0d15917d6eb40b8e376d1a214e")
.asCompatibleSubstituteFor("shopify/toxiproxy");
// Every container below is declared in try-with-resources; the fluent `withX` chain returns the
// same instance, which the compiler reads as a second, unclosed resource.
@SuppressWarnings("resource")
@Test
void connectionCutProducesABoundedFailureAndRecoveryWithoutMutationReplay() throws Exception {
DockerImageName minioImage = QualificationImages.minio();
DockerImageName toxiproxyImage = QualificationImages.toxiproxy();
String accessKey = "a" + UUID.randomUUID().toString().replace("-", "");
String secretKey = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID();
try (Network network = Network.newNetwork();
GenericContainer<?> minio =
new GenericContainer<>(MINIO_IMAGE)
new GenericContainer<>(minioImage)
.withNetwork(network)
.withNetworkAliases("qualified-minio")
.withExposedPorts(9000)
@@ -60,7 +53,7 @@ class MinioManagedObjectFaultTest {
.withEnv("MINIO_ROOT_PASSWORD", secretKey)
.withCommand("server", "/data");
ToxiproxyContainer toxiproxy =
new ToxiproxyContainer(TOXIPROXY_IMAGE)
new ToxiproxyContainer(toxiproxyImage)
.withNetwork(network)
.withExposedPorts(TOXIPROXY_CONTROL_PORT, TOXIPROXY_PROXY_PORT)) {
minio.start();
@@ -0,0 +1,34 @@
package dev.caskeleton.adapter.outbound.objectstorage.qualification;
import org.testcontainers.images.RemoteDockerImage;
import org.testcontainers.utility.DockerImageName;
/**
* The MinIO lanes' images, pulled before any container is built.
*
* <p>The references come from the evidence file through {@link MinioQualificationImage}; this class
* only supplies the pull, Testcontainers' own image resolution, so a missing image fails here as
* {@code pinned image unavailable: <reference>} instead of inside a container start.
*/
final class QualificationImages {
private QualificationImages() {}
// Loaded per call, not in a static initializer: a refused override then reads as its own
// message instead of an ExceptionInInitializerError.
static DockerImageName minio() {
MinioQualificationImage images = MinioQualificationImage.load();
return pulled(images, images.minio());
}
static DockerImageName toxiproxy() {
MinioQualificationImage images = MinioQualificationImage.load();
return pulled(images, images.toxiproxy()).asCompatibleSubstituteFor("shopify/toxiproxy");
}
private static DockerImageName pulled(MinioQualificationImage images, String reference) {
return DockerImageName.parse(
images.requireAvailable(
reference, ref -> new RemoteDockerImage(DockerImageName.parse(ref)).get()));
}
}
@@ -1,25 +0,0 @@
{
"schema": 1,
"providerType": "s3-compatible-minio-community-release-2024-01-16t16-07-38z",
"providerVersion": "release-2024-01-16t16-07-38z-sdk-2.30.0",
"image": "minio/minio@sha256:4c4a4876193f030c81f57aabb22bcb9a73462010eb61fcab66908e03e5484af8",
"toxiproxyImage": "ghcr.io/shopify/toxiproxy@sha256:9378ed52a28bc50edc1350f936f518f31fa95f0d15917d6eb40b8e376d1a214e",
"profile": "managed-common",
"status": "UNSUPPORTED",
"excludedProfiles": [
"managed-single-create-only",
"conditional-control-create",
"managed-multipart-create-only",
"direct-single-create-only",
"direct-multipart-create-only"
],
"limitations": [
"PutObject If-None-Match was accepted and overwrote an existing object",
"stale PutObject If-Match returned HTTP 412 but create-if-absent control CAS is not safe",
"CompleteMultipartUpload accepted If-None-Match despite a pre-existing target and overwrote it",
"managed immutable create, conditional control creation, and multipart create-only are disabled",
"local single-node container evidence only",
"not AWS evidence",
"not production TLS or deployment-topology evidence"
]
}
@@ -0,0 +1,138 @@
package dev.caskeleton.adapter.outbound.objectstorage.qualification;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
/**
* The images the MinIO qualification lanes run, read from the one file that records what they were
* measured on.
*
* <p>{@code object-storage/minio-provider-evidence.json} is the source: its {@code image} is the
* release the {@code status}, {@code excludedProfiles} and {@code limitations} beside it describe.
* The contract and fault lanes used to repeat that digest in their own constants, and the evidence
* file existed twice (test and integrationTest). When Docker Hub stopped serving the repository
* there were four places to change and nothing to say they had to agree.
*
* <p>An operator may point the lane at a mirror with {@value #OVERRIDE_PROPERTY} or {@value
* #OVERRIDE_ENV}, but only at the same digest: a mirror of the measured bytes keeps the evidence
* true, any other build does not. A different build is a new measurement, so it is made by editing
* the evidence file — image and findings together — not by an override that would leave the old
* findings standing against new bytes.
*
* <p>A pull that fails is reported as {@link PinnedImageUnavailableException} before any container
* starts, so a vanished image reads as a supply failure and not as a broken adapter. The lane still
* fails; skipping would turn missing vendor evidence green.
*/
final class MinioQualificationImage {
static final String OVERRIDE_PROPERTY = "objectstorage.minio.image";
static final String OVERRIDE_ENV = "OBJECT_STORAGE_MINIO_IMAGE";
private static final String EVIDENCE_RESOURCE = "/object-storage/minio-provider-evidence.json";
private static final String EVIDENCE_FILE = "minio-provider-evidence.json";
private final String minio;
private final String toxiproxy;
private MinioQualificationImage(String minio, String toxiproxy) {
this.minio = minio;
this.toxiproxy = toxiproxy;
}
/** The committed evidence, with the operator's mirror if one is set. */
static MinioQualificationImage load() {
return load(operatorOverride());
}
static MinioQualificationImage load(Optional<String> override) {
try (InputStream in = MinioQualificationImage.class.getResourceAsStream(EVIDENCE_RESOURCE)) {
if (in == null) {
throw new IllegalStateException("evidence resource missing: " + EVIDENCE_RESOURCE);
}
return fromEvidence(new String(in.readAllBytes(), StandardCharsets.UTF_8), override);
} catch (IOException failure) {
throw new UncheckedIOException("cannot read " + EVIDENCE_RESOURCE, failure);
}
}
static MinioQualificationImage fromEvidence(String json, Optional<String> override) {
JsonNode evidence = JsonMapper.builder().build().readTree(json);
String measured = requireDigestPinned(evidence, "image");
String toxiproxy = requireDigestPinned(evidence, "toxiproxyImage");
String digest = digestOf(measured);
String minio =
override
.map(String::strip)
.filter(value -> !value.isEmpty())
.map(
mirror -> {
if (!mirror.endsWith("@" + digest)) {
throw new IllegalStateException(
"MinIO image override "
+ mirror
+ " does not carry the evidence digest "
+ digest
+ ". A mirror must serve the measured bytes; a different build needs "
+ "re-measured evidence written to "
+ EVIDENCE_FILE
+ " (image, status, excludedProfiles and limitations together).");
}
return mirror;
})
.orElse(measured);
return new MinioQualificationImage(minio, toxiproxy);
}
String minio() {
return minio;
}
String toxiproxy() {
return toxiproxy;
}
/**
* Pulls {@code reference} (a no-op when it is already local) and returns it, or fails with a
* message that names the supply failure rather than whatever the container start would have
* thrown.
*/
String requireAvailable(String reference, ImagePull pull) {
try {
pull.pull(reference);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new PinnedImageUnavailableException(reference, interrupted);
} catch (Exception failure) {
throw new PinnedImageUnavailableException(reference, failure);
}
return reference;
}
private static Optional<String> operatorOverride() {
return Optional.ofNullable(System.getProperty(OVERRIDE_PROPERTY))
.or(() -> Optional.ofNullable(System.getenv(OVERRIDE_ENV)));
}
private static String requireDigestPinned(JsonNode evidence, String field) {
String reference = evidence.path(field).asString("");
if (!reference.matches("[^@\\s]+@sha256:[0-9a-f]{64}")) {
throw new IllegalStateException(
EVIDENCE_FILE + " field " + field + " must pin an image by sha256 digest: " + reference);
}
return reference;
}
private static String digestOf(String reference) {
return reference.substring(reference.indexOf('@') + 1);
}
/** The pull step; the lanes pass Testcontainers' image resolution, unit tests a stand-in. */
@FunctionalInterface
interface ImagePull {
void pull(String reference) throws Exception;
}
}
@@ -0,0 +1,105 @@
package dev.caskeleton.adapter.outbound.objectstorage.qualification;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class MinioQualificationImageTest {
private static final String DIGEST =
"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
private static final String EVIDENCE =
"""
{
"image": "minio/minio@%s",
"toxiproxyImage": "ghcr.io/shopify/toxiproxy@sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
}
"""
.formatted(DIGEST);
@Test
void anImageThatCannotBePulledFailsAsPinnedImageUnavailableRatherThanAsACodeDefect() {
// given
MinioQualificationImage images =
MinioQualificationImage.fromEvidence(EVIDENCE, Optional.empty());
RuntimeException registryAnswer = new RuntimeException("repository does not exist");
// when
Throwable thrown =
catchThrowable(
() ->
images.requireAvailable(
images.minio(),
reference -> {
throw registryAnswer;
}));
// then
assertThat(thrown)
.isInstanceOf(PinnedImageUnavailableException.class)
.hasMessage("pinned image unavailable: minio/minio@" + DIGEST)
.hasCause(registryAnswer);
}
@Test
void aPulledImageIsTheReferenceTheContainerStartsFrom() {
// given
MinioQualificationImage images =
MinioQualificationImage.fromEvidence(EVIDENCE, Optional.empty());
// when
String started = images.requireAvailable(images.minio(), reference -> {});
// then
assertThat(started).isEqualTo("minio/minio@" + DIGEST);
}
@Test
void aMirrorOverrideCarryingTheEvidenceDigestReplacesTheRegistry() {
// given
String mirror = "registry.example.internal/mirror/minio@" + DIGEST;
// when
MinioQualificationImage images =
MinioQualificationImage.fromEvidence(EVIDENCE, Optional.of(mirror));
// then
assertThat(images.minio()).isEqualTo(mirror);
}
@ParameterizedTest
@ValueSource(
strings = {
"minio/minio@sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
"minio/minio:RELEASE.2024-01-16T16-07-38Z"
})
void anOverrideThatDoesNotCarryTheEvidenceDigestIsRejectedUntilTheEvidenceIsRemeasured(
String override) {
// when
Throwable thrown =
catchThrowable(() -> MinioQualificationImage.fromEvidence(EVIDENCE, Optional.of(override)));
// then
assertThat(thrown)
.isInstanceOf(IllegalStateException.class)
.hasMessageContainingAll(
override,
"does not carry the evidence digest " + DIGEST,
"minio-provider-evidence.json");
}
@Test
void theCommittedEvidencePinsBothQualificationImagesByDigest() {
// when
MinioQualificationImage images = MinioQualificationImage.load(Optional.empty());
// then
assertThat(List.of(images.minio(), images.toxiproxy()))
.allMatch(reference -> reference.matches("[^@\\s]+@sha256:[0-9a-f]{64}"));
}
}
@@ -0,0 +1,9 @@
package dev.caskeleton.adapter.outbound.objectstorage.qualification;
final class PinnedImageUnavailableException extends IllegalStateException {
private static final long serialVersionUID = 1L;
PinnedImageUnavailableException(String reference, Throwable cause) {
super("pinned image unavailable: " + reference, cause);
}
}
@@ -278,6 +278,14 @@ framework-neutral `shared.error.PersistenceFailureException` carrying one of the
| `23513` | `DB_CHECK_VIOLATION` | H2 (`.h2` package) — H2 reports CHECK as 23513, not the standard 23514 the core table maps |
| `HYT00` | `DB_QUERY_CANCELED` | H2 — H2 collapses statement and lock timeout into one state |
**Commit phase (`translateCommitFailure`, ADR-JPA-003):** once the action has returned and
`SpringTransaction` is committing a write transaction it began, a failure with `08*`, `40003`, a
vendor-contributed termination state (`SqlStateErrorMapping.commitOutcomeUnknownStates()`:
PostgreSQL `57P01`, `57P02`) or a transport break with no SQLState becomes
`TransactionCompletionUnknownException` → `DB_COMPLETION_UNKNOWN` (500, never retryable), not
`DB_UNAVAILABLE`: the server may already have committed. A commit the server definitely rejected
(e.g. a deferred `23505`) keeps its row above; a read-only commit keeps `DB_UNAVAILABLE`.
- A repository adapter that catches a `DataAccessException` calls
`translator.translate(ex)` and rethrows the carrier (`ifPresent(e -> { throw e; })`);
an empty result means an unknown SQLState — rethrow the original so the web catch-all
+11 -1
View File
@@ -194,6 +194,16 @@ failure translation contract 다. 여기서는 SPI 구조와 fallback 근거만
실패시킨다. last-writer-wins merge는 mapping ownership drift를 숨기므로 허용하지 않는다.
- `08*` connection-class prefix → `DB_UNAVAILABLE` 규칙은 맵 엔트리가 아니라 translator 가 직접
처리한다. 따라서 core 매핑 맵에는 `08*` 가 없다.
- **커밋 단계는 따로 분류한다(ADR-JPA-003).** `SpringTransaction` 은 본문이 끝난 뒤 자기가 연
쓰기 트랜잭션을 커밋하다 난 실패를 `translateCommitFailure` 로 보낸다. 여기서 `08*`·`40003`·벤더
종료 상태(`commitOutcomeUnknownStates()`, PostgreSQL 은 `57P01`·`57P02`)·SQLState 없는 전송 단절은
`DB_UNAVAILABLE`(재시도 가능)이 아니라 `DB_COMPLETION_UNKNOWN`(재시도 불가)이 된다. 서버가 이미
커밋했을 수 있어 재시도가 쓰기를 중복시키기 때문이다.
- 커밋 전(연결 획득, 본문 실행) 연결 실패는 그대로 `DB_UNAVAILABLE` 이다. 풀 고갈·재시작까지
결과 불명으로 몰면 운영자가 그 신호를 무시하게 된다(ADR 의 "좁게" 원칙).
- 커밋 단계 안에서 Hibernate flush 실패와 COMMIT 자체 실패는 구분하지 않는다. flush 중 연결 단절은
실제로는 롤백이지만 결과 불명으로 보고된다 — 중복 쓰기보다 불필요한 조정(reconciliation)이 싸다.
- 읽기 전용 트랜잭션과 바깥 트랜잭션에 참여한 호출은 커밋할 쓰기가 없으므로 이 분류를 타지 않는다.
- **Fallback:** 기여된 어떤 row 에도 없는 SQLState — 또는 cause chain 에
`SQLException` 자체가 없는 경우 — 는 `Optional.empty()` 를 반환한다. 호출부는 원본 예외를 web
catch-all 까지 전파시켜 detail 누설 없는 generic `INTERNAL` 엔벨로프로 답하게 한다. translator
@@ -581,7 +591,7 @@ holder 가 락을 잡을 수 있다.
막지 못한다. WARN 은 놓치기 쉬우므로, resolved 값이 `true`면 운영자가 실제 설정한
`APP_DATASOURCE_OPEN_IN_VIEW` 키를 메시지에 담아 부팅을 실패시킨다.
- **읽기만 하고 re-bind 하지 않으며, 부재 값은 Spring 기본에 맡긴다.** `StartupRule`로 위반만
돌려주고 support의 `StartupRuleRunner`가 모든 싱글톤 생성 후 한 번 실행하며, 값이 *없으면* Spring Boot 기본(이 스켈레톤은 `application.yml`에서 OSIV off
돌려주고 support의 `StartupRuleRunner`가 다른 싱글톤(DataSource·Flyway)을 만들기 전에 한 번 실행하며, 값이 *없으면* Spring Boot 기본(이 스켈레톤은 `application.yml`에서 OSIV off
가 기본)에 맡기며 *있는 `true`*만 거부한다.
### JpaDangerousConfigurationGuard (ddl-auto)
@@ -1,14 +1,25 @@
package dev.caskeleton.adapter.outbound.persistence.failure;
import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName;
import dev.caskeleton.adapter.outbound.persistence.api.error.JpaFailureContext;
import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException;
import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.OperationalError;
import dev.caskeleton.shared.error.PersistenceFailureException;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.SQLNonTransientConnectionException;
import java.sql.SQLRecoverableException;
import java.sql.SQLTransientConnectionException;
import java.time.Duration;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.springframework.dao.DataAccessException;
/**
@@ -17,6 +28,10 @@ import org.springframework.dao.DataAccessException;
* {@link Optional#empty()} for an unknown state). Mappings are merged from all {@link
* SqlStateErrorMapping} SPI beans. See README "failure" for the SPI/fallback rationale and
* CLAUDE.md for the SQLState → Error Code matrix.
*
* <p>A failed commit is classified by {@link #translateCommitFailure} instead: the same connection
* loss that is a retryable {@code DB_UNAVAILABLE} before the commit is an undetermined outcome
* during it (ADR-JPA-003).
*/
public class PersistenceExceptionTranslator {
@@ -24,14 +39,19 @@ public class PersistenceExceptionTranslator {
private static final String CONNECTION_CLASS_PREFIX = "08";
private final Map<String, OperationalError> byExactSqlState;
private final Set<String> vendorCommitOutcomeUnknownStates;
public PersistenceExceptionTranslator(Collection<SqlStateErrorMapping> mappings) {
Objects.requireNonNull(mappings, "mappings");
Map<String, OperationalError> merged = new LinkedHashMap<>();
Map<String, String> contributors = new LinkedHashMap<>();
Set<String> commitOutcomeUnknown = new HashSet<>();
for (SqlStateErrorMapping mapping : mappings) {
Objects.requireNonNull(mapping, "mapping");
String contributor = mapping.getClass().getName();
commitOutcomeUnknown.addAll(
Objects.requireNonNull(
mapping.commitOutcomeUnknownStates(), contributor + ".commitOutcomeUnknownStates()"));
Map<String, OperationalError> exactMappings =
Objects.requireNonNull(mapping.exactMappings(), contributor + ".exactMappings()");
for (Map.Entry<String, OperationalError> entry : exactMappings.entrySet()) {
@@ -60,6 +80,7 @@ public class PersistenceExceptionTranslator {
}
}
this.byExactSqlState = Map.copyOf(merged);
this.vendorCommitOutcomeUnknownStates = Set.copyOf(commitOutcomeUnknown);
}
/** Classify {@code ex}, or {@link Optional#empty()} when its SQLState is unmapped or absent. */
@@ -88,6 +109,61 @@ public class PersistenceExceptionTranslator {
code, "persistence failure classified from SQLState=" + sqlState, ex));
}
/**
* Classify a failure raised while committing a write transaction this call began.
*
* <p>A connection-class state ({@code 08*}), {@code 40003}, a vendor-contributed termination
* state, or a transport break with no SQLState at all means the commit request may have reached
* the server and been applied before the acknowledgement was lost. That becomes a {@link
* TransactionCompletionUnknownException} ({@code DB_COMPLETION_UNKNOWN}, never retryable), not
* the retryable {@code DB_UNAVAILABLE} the same state means before the commit. A commit the
* server definitely rejected — a deferred constraint, a serialization failure — keeps its {@link
* #translate(Throwable) ordinary} classification.
*
* @param operation the bounded name the failure is reported under
* @param elapsed how long the transaction ran before the commit failed
*/
public Optional<PersistenceFailureException> translateCommitFailure(
Throwable ex, PersistenceOperationName operation, Duration elapsed) {
Objects.requireNonNull(ex, "ex");
Objects.requireNonNull(operation, "operation");
Objects.requireNonNull(elapsed, "elapsed");
String sqlState = extractSqlState(ex);
if (!leavesCommitOutcomeUnknown(sqlState, ex)) {
return translate(ex);
}
JpaFailureContext context =
JpaFailureContext.completionUnknown(operation, sqlState, 1, elapsed, null);
return Optional.of(
new TransactionCompletionUnknownException(
context, TransactionCompletionEvidence.UNKNOWN, ex));
}
private boolean leavesCommitOutcomeUnknown(String sqlState, Throwable ex) {
if (sqlState == null) {
return hasTransportBreak(ex);
}
return sqlState.startsWith(CONNECTION_CLASS_PREFIX)
|| StandardSqlStateErrorMapping.STATEMENT_COMPLETION_UNKNOWN.equals(sqlState)
|| vendorCommitOutcomeUnknownStates.contains(sqlState);
}
/** A broken socket or a driver connection exception that carried no SQLState. */
private static boolean hasTransportBreak(Throwable ex) {
for (Throwable t = ex; t != null; t = t.getCause()) {
if (t instanceof IOException
|| t instanceof SQLRecoverableException
|| t instanceof SQLTransientConnectionException
|| t instanceof SQLNonTransientConnectionException) {
return true;
}
if (t.getCause() == t) {
break;
}
}
return false;
}
/** The matrix lookup: exact codes first, then the {@code 08*} connection-class prefix. */
private ApiErrorCode classify(String sqlState) {
OperationalError exact = byExactSqlState.get(sqlState);
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.persistence.failure;
import dev.caskeleton.shared.error.OperationalError;
import java.util.Map;
import java.util.Set;
/**
* SPI for contributing exact SQLState → {@link OperationalError} mappings to the {@link
@@ -15,4 +16,16 @@ public interface SqlStateErrorMapping {
* translator's responsibility, not a map entry.
*/
Map<String, OperationalError> exactMappings();
/**
* Vendor SQLStates that, when a commit fails with them, leave the commit outcome undetermined —
* the server may have committed before it reported the failure. Never {@code null}.
*
* <p>The vendor-neutral ones ({@code 08*}, {@code 40003}) and the transport break are the
* translator's own rule. Only a state a vendor reports <em>instead</em> of those belongs here,
* such as PostgreSQL's {@code 57P01} for a backend terminated mid-commit (ADR-JPA-003).
*/
default Set<String> commitOutcomeUnknownStates() {
return Set.of();
}
}
@@ -8,15 +8,22 @@ import java.util.Map;
* returns. Vendor-specific states are contributed by the vendor module. See CLAUDE.md for the
* SQLState → Error Code matrix.
*
* <p>The constants are where these five codes are spelled. A vendor's own SQLSTATE vocabulary —
* {@code PostgreSqlState} — refers to them rather than repeating the literals, so {@code 40001} is
* written once, not once per table that happens to need it.
* <p>The constants are where these codes are spelled. A vendor's own SQLSTATE vocabulary — {@code
* PostgreSqlState} — refers to them rather than repeating the literals, so {@code 40001} is written
* once, not once per table that happens to need it.
*/
public class StandardSqlStateErrorMapping implements SqlStateErrorMapping {
/** {@code 40001} serialization_failure. */
public static final String SERIALIZATION_FAILURE = "40001";
/**
* {@code 40003} statement_completion_unknown. Not an exact row: it means "outcome unknown" only
* when a commit reports it, so {@link PersistenceExceptionTranslator#translateCommitFailure} owns
* it.
*/
public static final String STATEMENT_COMPLETION_UNKNOWN = "40003";
/** {@code 23502} not_null_violation. */
public static final String NOT_NULL_VIOLATION = "23502";
@@ -4,6 +4,7 @@ import dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping;
import dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlState;
import dev.caskeleton.shared.error.OperationalError;
import java.util.Map;
import java.util.Set;
/**
* PostgreSQL-specific {@link SqlStateErrorMapping} contributing vendor-only SQLState codes. See the
@@ -22,8 +23,20 @@ public class PostgreSqlSqlStateErrorMapping implements SqlStateErrorMapping {
OperationalError.DB_IDLE_IN_TX_TIMEOUT,
PostgreSqlState.QUERY_CANCELED.code(), OperationalError.DB_QUERY_CANCELED);
/**
* A backend terminated mid-commit reports {@code 57P01}/{@code 57P02}, not a connection-class
* state, and the commit record may already be in the WAL when it does.
*/
private static final Set<String> COMMIT_OUTCOME_UNKNOWN =
Set.of(PostgreSqlState.ADMIN_SHUTDOWN.code(), PostgreSqlState.CRASH_SHUTDOWN.code());
@Override
public Map<String, OperationalError> exactMappings() {
return MAPPINGS;
}
@Override
public Set<String> commitOutcomeUnknownStates() {
return COMMIT_OUTCOME_UNKNOWN;
}
}
@@ -57,6 +57,9 @@ public final class PostgreSqlFailureClassifier {
case LOCK_NOT_AVAILABLE -> FailureCategory.LOCK_NOT_AVAILABLE;
case QUERY_CANCELED -> FailureCategory.QUERY_TIMEOUT;
case IDLE_IN_TRANSACTION_TIMEOUT -> FailureCategory.TRANSACTION_TIMEOUT;
// The backend is gone; like 08*, whether a commit it was running landed is decided by the
// transaction phase, not here.
case ADMIN_SHUTDOWN, CRASH_SHUTDOWN -> FailureCategory.CONNECTION_UNAVAILABLE;
case UNDEFINED_TABLE, UNDEFINED_COLUMN -> FailureCategory.SCHEMA_MISMATCH;
case INSUFFICIENT_PRIVILEGE -> FailureCategory.UNKNOWN;
};
@@ -24,7 +24,7 @@ public enum PostgreSqlState {
SERIALIZATION_FAILURE(StandardSqlStateErrorMapping.SERIALIZATION_FAILURE),
/** {@code 40003} statement_completion_unknown. */
STATEMENT_COMPLETION_UNKNOWN("40003"),
STATEMENT_COMPLETION_UNKNOWN(StandardSqlStateErrorMapping.STATEMENT_COMPLETION_UNKNOWN),
/** {@code 40P01} deadlock_detected. */
DEADLOCK_DETECTED("40P01"),
@@ -50,6 +50,15 @@ public enum PostgreSqlState {
/** {@code 25P03} idle_in_transaction_session_timeout. */
IDLE_IN_TRANSACTION_TIMEOUT("25P03"),
/**
* {@code 57P01} admin_shutdown — what the driver reports when the backend is terminated,
* including by {@code pg_terminate_backend} while a commit is in flight.
*/
ADMIN_SHUTDOWN("57P01"),
/** {@code 57P02} crash_shutdown — another backend crashed and this one was terminated. */
CRASH_SHUTDOWN("57P02"),
/** {@code 42P01} undefined_table — the schema is not what the provider expects. */
UNDEFINED_TABLE("42P01"),
@@ -27,6 +27,10 @@ import org.springframework.core.env.Environment;
* selects the module gets the guards with it and an application that removes the module keeps none
* of them. Every guard raises a typed startup failure from {@code support.startup}, so exit codes
* and the structured failure log are unchanged.
*
* <p>The environment rules are {@code static} beans: support's runner evaluates them before any
* other singleton exists — before the datasource below opens a connection and before Flyway
* migrates — and a static factory method does not create this class to do so.
*/
@AutoConfiguration
@ConditionalOnProperty(
@@ -58,33 +62,33 @@ class JpaStartupAutoConfiguration {
/** Env-validation (exit 78): datasource connection env present before migration runs. */
@Bean
RequiredEnvironmentValidator requiredEnvironmentValidator() {
static RequiredEnvironmentValidator requiredEnvironmentValidator() {
return new RequiredEnvironmentValidator();
}
/** Profile check (exit 71): forbidden Flyway options stay off under the prod profile. */
@Bean
FlywayProdSafetyValidator flywayProdSafetyValidator() {
static FlywayProdSafetyValidator flywayProdSafetyValidator() {
return new FlywayProdSafetyValidator();
}
@Bean
OpenInViewSafetyValidator openInViewSafetyValidator() {
static OpenInViewSafetyValidator openInViewSafetyValidator() {
return new OpenInViewSafetyValidator();
}
@Bean
PostgreSqlTransportSecurityValidator postgreSqlTransportSecurityValidator() {
static PostgreSqlTransportSecurityValidator postgreSqlTransportSecurityValidator() {
return new PostgreSqlTransportSecurityValidator();
}
@Bean
PersistenceVendorProdSafetyValidator persistenceVendorProdSafetyValidator() {
static PersistenceVendorProdSafetyValidator persistenceVendorProdSafetyValidator() {
return new PersistenceVendorProdSafetyValidator();
}
@Bean
HikariPoolConstraintValidator hikariPoolConstraintValidator() {
static HikariPoolConstraintValidator hikariPoolConstraintValidator() {
return new HikariPoolConstraintValidator();
}
@@ -1,12 +1,17 @@
package dev.caskeleton.adapter.outbound.persistence.transaction;
import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName;
import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator;
import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping;
import dev.caskeleton.application.transaction.Isolation;
import dev.caskeleton.application.transaction.NestedRootTransactionRejectedException;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.shared.error.PersistenceFailureException;
import java.time.Duration;
import java.util.Locale;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
@@ -17,15 +22,21 @@ import org.springframework.transaction.support.TransactionTemplate;
* Spring-backed {@link TransactionPort}: one pre-built {@link TransactionTemplate} per mode, all
* pinned to {@link Isolation#READ_COMMITTED}. See README "transaction" for why the templates are
* pre-built (mutable-template race) and CLAUDE.md for the mode table.
*
* <p>A failure is classified by the phase it happened in. Before and during the action it goes
* through {@link PersistenceExceptionTranslator#translate(Throwable)}; once the action has returned
* and this call is committing a write transaction it began, it goes through {@link
* PersistenceExceptionTranslator#translateCommitFailure}, which reports a lost connection as
* completion-unknown rather than retryable (ADR-JPA-003).
*/
public class SpringTransaction implements TransactionPort {
/** Upper bound on one {@link #inNew} transaction; the former compensation budget. */
static final int REQUIRES_NEW_TIMEOUT_SECONDS = 30;
private final TransactionTemplate writeTemplate;
private final TransactionTemplate readTemplate;
private final TransactionTemplate requiresNewTemplate;
private final ModeTemplate writeTemplate;
private final ModeTemplate readTemplate;
private final ModeTemplate requiresNewTemplate;
private final PersistenceExceptionTranslator exceptionTranslator;
public SpringTransaction(PlatformTransactionManager transactionManager) {
@@ -55,7 +66,7 @@ public class SpringTransaction implements TransactionPort {
false);
// inNew is for outbox, audit and compensation writes, which usually run while the caller's own
// transaction holds a second connection. An unbounded one could pin both for good.
this.requiresNewTemplate.setTimeout(REQUIRES_NEW_TIMEOUT_SECONDS);
this.requiresNewTemplate.template().setTimeout(REQUIRES_NEW_TIMEOUT_SECONDS);
this.exceptionTranslator = exceptionTranslator;
}
@@ -82,27 +93,46 @@ public class SpringTransaction implements TransactionPort {
return execute(requiresNewTemplate, action);
}
private static TransactionTemplate template(
/** One mode's template and the bounded name a failed commit in it is reported under. */
private record ModeTemplate(
TransactionTemplate template, PersistenceOperationName commitOperation) {}
private static ModeTemplate template(
PlatformTransactionManager transactionManager,
TransactionMode mode,
int propagation,
boolean readOnly) {
String modeName = mode.name().toLowerCase(Locale.ROOT);
TransactionTemplate template = new TransactionTemplate(transactionManager);
template.setName("application-" + mode.name().toLowerCase(Locale.ROOT));
template.setName("application-" + modeName);
template.setPropagationBehavior(propagation);
template.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
template.setReadOnly(readOnly);
return template;
return new ModeTemplate(
template,
new PersistenceOperationName("transaction." + modeName.replace('_', '-') + ".commit"));
}
private <T> T execute(TransactionTemplate template, Supplier<T> action) {
private <T> T execute(ModeTemplate mode, Supplier<T> action) {
long startedAt = System.nanoTime();
// Set only once the action has returned in a write transaction this call began: from then on
// the only thing TransactionTemplate.execute still does is commit it.
AtomicBoolean committingOwnWrite = new AtomicBoolean();
try {
return template.execute(status -> action.get());
return mode.template()
.execute(
status -> {
T result = action.get();
committingOwnWrite.set(status.isNewTransaction() && !mode.template().isReadOnly());
return result;
});
} catch (RuntimeException failure) {
throw exceptionTranslator
.translate(failure)
.map(RuntimeException.class::cast)
.orElse(failure);
Optional<PersistenceFailureException> translated =
committingOwnWrite.get()
? exceptionTranslator.translateCommitFailure(
failure, mode.commitOperation(), Duration.ofNanos(System.nanoTime() - startedAt))
: exceptionTranslator.translate(failure);
throw translated.map(RuntimeException.class::cast).orElse(failure);
}
}
@@ -45,7 +45,9 @@ final class NotificationFixtures {
migration("jpa/notification-platform", "V6__notification_projection_facts.sql"),
migration("jpa/notification-platform", "V7__notification_collapse.sql"),
migration("jpa/notification-platform", "V8__notification_admin_claim.sql"),
migration("jpa/notification-platform", "V9__notification_evidence_certainty.sql"));
migration("jpa/notification-platform", "V9__notification_evidence_certainty.sql"),
migration("jpa/notification-platform", "V10__variables_payload_envelope_guard.sql"),
migration("jpa/notification-platform", "V11__notification_reconciliation_claim_lease.sql"));
}
/**
@@ -0,0 +1,257 @@
package dev.caskeleton.adapter.outbound.persistence.notification;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.persistence.notification.platform.JdbcReconciliationJobStore;
import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport;
import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId;
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJob;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* Whether two instances polling the reconciliation table can take the same job, against a real
* PostgreSQL.
*
* <p>Every call runs on its own pooled autocommit connection, as the worker's do: no transaction
* spans the claim and the provider call, so ownership has to be in the row. Row locks and {@code
* SKIP LOCKED} are vendor semantics a fake would only restate.
*/
@Tag("jpa-contract")
class ReconciliationJobClaimContractTest {
private static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z");
private static final String TENANT = "tenant-a";
private static final String PROFILE = "email-main";
private static final Duration LEASE = Duration.ofMinutes(2);
private static JpaPlatformContractSupport support;
@BeforeAll
static void startServer() {
support = JpaPlatformContractSupport.start();
}
@AfterAll
static void stopServer() {
if (support != null) {
support.close();
}
}
@BeforeEach
void migrate() throws SQLException, IOException {
try (Connection connection = support.connection();
Statement statement = connection.createStatement()) {
statement.execute("DROP SCHEMA public CASCADE");
statement.execute("CREATE SCHEMA public");
for (String migration : NotificationFixtures.migrations()) {
statement.execute(migration);
}
}
}
@Test
@DisplayName("한 인스턴스가 가져간 정산 job은 다른 인스턴스의 claim에 다시 나오지 않는다")
void aClaimedJobIsNotHandedToAnotherInstance() throws SQLException {
// given
scheduleDueJob();
JdbcReconciliationJobStore first = store();
JdbcReconciliationJobStore second = store();
List<ReconciliationJob> firstClaim = first.claimDue(10, NOW, LEASE);
// when
List<ReconciliationJob> secondClaim = second.claimDue(10, NOW, LEASE);
// then
assertThat(firstClaim).hasSize(1);
assertThat(secondClaim)
.as(
"the claim commits with its statement; only the lease in the row still says who owns it")
.isEmpty();
}
@Test
@DisplayName("두 연결이 동시에 claim하면 겹쳐서 가져간 job이 없다")
void twoConcurrentClaimsShareNoJob() throws Exception {
// given
for (int i = 0; i < 40; i++) {
scheduleDueJob();
}
CountDownLatch start = new CountDownLatch(1);
Callable<List<UUID>> claimer =
() -> {
start.await();
return store().claimDue(40, NOW, LEASE).stream().map(ReconciliationJob::id).toList();
};
ExecutorService pool = Executors.newFixedThreadPool(2);
List<UUID> a;
List<UUID> b;
try {
Future<List<UUID>> left = pool.submit(claimer);
Future<List<UUID>> right = pool.submit(claimer);
// when
start.countDown();
a = left.get();
b = right.get();
} finally {
pool.shutdownNow();
}
// then
Set<UUID> overlap = new HashSet<>(a);
overlap.retainAll(b);
assertThat(overlap).as("a job taken by both instances is asked about twice").isEmpty();
assertThat(a.size() + b.size()).isEqualTo(40);
}
@Test
@DisplayName("lease가 지난 job은 다른 인스턴스가 다시 가져간다")
void aJobWhoseLeaseHasPassedIsClaimedAgain() throws SQLException {
// given
UUID id = scheduleDueJob();
store().claimDue(10, NOW, LEASE);
// when
List<ReconciliationJob> reclaimed = store().claimDue(10, NOW.plus(LEASE), LEASE);
// then
assertThat(reclaimed)
.as("a holder that died mid-pass must not strand its jobs")
.extracting(ReconciliationJob::id)
.containsExactly(id);
}
@Test
@DisplayName("lease가 1마이크로초라도 남은 job은 다른 인스턴스가 가져가지 못한다")
void aJobWhoseLeaseHasNotPassedIsNotClaimed() throws SQLException {
// given
scheduleDueJob();
store().claimDue(10, NOW, LEASE);
// when
List<ReconciliationJob> early = store().claimDue(10, NOW.plus(LEASE).minusNanos(1_000), LEASE);
// then
assertThat(early).isEmpty();
}
@Test
@DisplayName("다른 인스턴스가 다시 가져간 job은 이전 소유자가 완료해도 지워지지 않는다")
void aSupersededHolderCannotCompleteTheJob() throws SQLException {
// given
UUID id = scheduleDueJob();
ReconciliationJob stale = store().claimDue(10, NOW, LEASE).get(0);
store().claimDue(10, NOW.plus(LEASE), LEASE);
// when
store().complete(stale);
// then
assertThat(rowExists(id)).as("the new holder has not answered yet").isTrue();
}
@Test
@DisplayName("다른 인스턴스가 다시 가져간 job은 이전 소유자의 재예약이 시도 횟수를 올리지 않는다")
void aSupersededHolderCannotRescheduleTheJob() throws SQLException {
// given
UUID id = scheduleDueJob();
ReconciliationJob stale = store().claimDue(10, NOW, LEASE).get(0);
store().claimDue(10, NOW.plus(LEASE), LEASE);
// when
store().reschedule(stale, "STILL_UNKNOWN", NOW.plus(Duration.ofHours(1)));
// then
assertThat(attemptsOf(id))
.as("two holders counting one question would reach the attempt limit early")
.isZero();
}
@Test
@DisplayName("현재 소유자가 재예약하면 claim이 풀려 lease 만료 전이라도 다음 확인 시각에 다시 나온다")
void theHoldersRescheduleReleasesTheClaim() throws SQLException {
// given
UUID id = scheduleDueJob();
ReconciliationJob held = store().claimDue(10, NOW, LEASE).get(0);
Instant nextCheck = NOW.plusSeconds(30);
store().reschedule(held, "STILL_UNKNOWN", nextCheck);
// when
List<ReconciliationJob> next = store().claimDue(10, nextCheck, LEASE);
// then
assertThat(next).extracting(ReconciliationJob::id).containsExactly(id);
assertThat(next.get(0).attempts()).isEqualTo(1);
}
@Test
@DisplayName("현재 소유자가 완료하면 job이 지워진다")
void theHolderCompletesTheJob() throws SQLException {
// given
UUID id = scheduleDueJob();
ReconciliationJob held = store().claimDue(10, NOW, LEASE).get(0);
// when
store().complete(held);
// then
assertThat(rowExists(id)).isFalse();
}
private static boolean rowExists(UUID id) {
Integer rows =
new JdbcTemplate(support.dataSource())
.queryForObject(
"SELECT count(*) FROM notification_reconciliation_job WHERE id = ?",
Integer.class,
id);
return rows != null && rows > 0;
}
private static int attemptsOf(UUID id) {
Integer attempts =
new JdbcTemplate(support.dataSource())
.queryForObject(
"SELECT attempts FROM notification_reconciliation_job WHERE id = ?",
Integer.class,
id);
return attempts == null ? -1 : attempts;
}
private UUID scheduleDueJob() throws SQLException {
UUID attemptId = NotificationFixtures.insertAttempt(support, TENANT, NOW, PROFILE);
return store()
.schedule(new DeliveryAttemptId(attemptId), new ProviderProfileId(PROFILE), NOW)
.id();
}
private static JdbcReconciliationJobStore store() {
return new JdbcReconciliationJobStore(
new JdbcTemplate(support.dataSource()), Clock.fixed(NOW, ZoneOffset.UTC));
}
}
@@ -16,8 +16,11 @@ import org.junit.jupiter.api.Test;
* Pins the Persistence Context semantics an application silently depends on (design §13, §14).
*
* <p>Every assertion here is a bug someone has shipped: merging and then modifying the original,
* expecting flush to commit, modifying a detached instance and wondering why nothing saved, or
* updating the inverse side of an association and getting no {@code UPDATE} at all.
* expecting flush to commit, modifying a detached instance and wondering why nothing saved.
*
* <p>The fixture's association is mapped from the parent's collection only, so the association
* contracts pin that one side: the collection writes the child's foreign key, and removing from it
* deletes the orphan.
*/
@Tag("jpa-contract")
class JpaLifecycleAssociationContractTest {
@@ -145,8 +148,8 @@ class JpaLifecycleAssociationContractTest {
}
@Test
@DisplayName("only the owning side writes the foreign key")
void onlyTheOwningSideWritesTheForeignKey() {
void addingToTheParentCollectionWritesTheChildForeignKey() {
// given
Long parentId =
jpa.inTransaction(
entityManager -> {
@@ -156,12 +159,16 @@ class JpaLifecycleAssociationContractTest {
return parent.id();
});
jpa.inTransactionDo(
entityManager -> {
var parent = entityManager.find(LifecycleParent.class, parentId);
assertThat(parent.children()).hasSize(1);
assertThat(parent.children().get(0).parent().id()).isEqualTo(parentId);
});
// when
var childParentIds =
jpa.inTransaction(
entityManager ->
entityManager.find(LifecycleParent.class, parentId).children().stream()
.map(LifecycleChild::parentId)
.toList());
// then
assertThat(childParentIds).containsExactly(parentId);
}
@Test
@@ -191,7 +198,7 @@ class JpaLifecycleAssociationContractTest {
assertThat(
entityManager
.createQuery(
"select count(c) from LifecycleChild c where c.parent.id = :parentId",
"select count(c) from LifecycleChild c where c.parentId = :parentId",
Long.class)
.setParameter("parentId", parentId)
.getSingleResult())
@@ -13,31 +13,41 @@ import dev.caskeleton.adapter.outbound.persistence.notification.platform.Notific
import dev.caskeleton.adapter.outbound.persistence.notification.platform.ProviderEventJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.notification.platform.RecipientDeliveryJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction;
import dev.caskeleton.application.notification.platform.api.ContactPointId;
import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId;
import dev.caskeleton.application.notification.platform.api.NormalizedEventType;
import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent;
import dev.caskeleton.application.notification.platform.api.ProviderId;
import dev.caskeleton.application.notification.platform.api.ProviderProfileId;
import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId;
import dev.caskeleton.application.notification.platform.api.TemplateSelection;
import dev.caskeleton.application.notification.platform.api.content.EmailContent;
import dev.caskeleton.application.notification.platform.api.content.EmailOptions;
import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome;
import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel;
import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState;
import dev.caskeleton.application.notification.platform.api.routing.Channel;
import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot;
import dev.caskeleton.application.notification.platform.callback.DeliveryProjection;
import dev.caskeleton.application.notification.platform.callback.ProjectionResult;
import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService;
import dev.caskeleton.application.notification.platform.callback.ProviderEventProjector;
import dev.caskeleton.application.notification.platform.callback.ProviderEventRecord;
import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptFactory;
import dev.caskeleton.application.notification.platform.dispatch.LeaseRecoveryService;
import dev.caskeleton.application.notification.platform.dispatch.NotificationRoutingPlanCodecPort;
import dev.caskeleton.application.notification.platform.dispatch.NotificationVariablesCodecPort;
import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord;
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationGatewayPort;
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService;
import dev.caskeleton.application.notification.platform.dispatch.SyntheticEventFingerprint;
import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort;
import dev.caskeleton.application.notification.platform.policy.RouteCandidate;
import dev.caskeleton.application.notification.platform.provider.ProviderCapabilities;
import dev.caskeleton.application.notification.platform.provider.ProviderProfileSnapshot;
import dev.caskeleton.application.notification.platform.provider.ReconciliationResult;
import dev.caskeleton.application.notification.platform.security.NotificationPayloadProtection;
import dev.caskeleton.application.notification.platform.template.RenderedNotificationContent;
import dev.caskeleton.application.transaction.TransactionPort;
import jakarta.persistence.EntityManagerFactory;
import java.sql.Timestamp;
@@ -45,6 +55,7 @@ import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
@@ -198,6 +209,27 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest {
assertThat(eventOf(attempt)).containsExactly("RECONCILIATION", "APPLIED");
}
@Test
void recoveryReconcilesAnAttemptLeftAsTheDispatcherWroteItBeforeTheCall() {
// given
// A worker killed during the SES/SMTP call leaves exactly the row DeliveryAttemptFactory wrote
// and the store persisted: nothing rewrites it until the outcome is recorded.
UUID delivery =
insertDelivery("DISPATCHING", Instant.now().minus(Duration.ofMinutes(10)), null);
UUID attempt = insertAttemptAsTheDispatcherWritesIt(delivery);
// when
recovery().recoverOnce();
// then
assertThat(eventOf(attempt))
.as("the provider may already have the message, so recovery asks it instead of requeuing")
.containsExactly("RECONCILIATION", "APPLIED");
assertThat(deliveryState(delivery))
.as("a requeue would hand the same notification to another worker, which sends it again")
.isNotEqualTo("READY_TO_DISPATCH");
}
@Test
void reconciliationRecordsAConfirmedAnswerOutsideAnyCallerTransaction() {
// given
@@ -346,10 +378,61 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest {
return delivery;
}
/** An attempt that started and never completed: the provider may or may not have it. */
private UUID insertStartedAttempt(UUID delivery, String providerId, String requestHash) {
UUID contact = UUID.randomUUID();
/**
* The pre-call attempt row built by {@link DeliveryAttemptFactory} and inserted through the
* production store, rather than a row written by hand.
*/
private UUID insertAttemptAsTheDispatcherWritesIt(UUID delivery) {
UUID contact = insertContactPoint();
UUID attempt = UUID.randomUUID();
RecipientDeliveryRecord recipient =
deliveries(context.getBean(RecipientDeliveryJpaRepository.class))
.find(new RecipientDeliveryId(delivery))
.orElseThrow();
RouteCandidate route =
new RouteCandidate(
0,
Channel.EMAIL,
new ContactPointId(contact),
new ProviderProfileId(PROFILE),
true,
true);
ProviderProfileSnapshot profile =
new ProviderProfileSnapshot(
new ProviderProfileId(PROFILE),
new ProviderId("ses"),
Channel.EMAIL,
"prod",
1L,
new ProviderCapabilities(
false,
true,
true,
true,
true,
false,
false,
false,
1,
10_000L,
Duration.ofHours(1)),
Map.of());
RenderedNotificationContent content =
new RenderedNotificationContent(
new EmailContent("subject", "body", Optional.empty(), List.of(), EmailOptions.DEFAULT),
"0".repeat(64),
new TemplateSelection("welcome", 1L, Locale.KOREAN),
Locale.KOREAN);
transactions.inWrite(
() ->
attempts.insertDispatching(
new DeliveryAttemptFactory(() -> attempt)
.create(recipient, route, profile, content, 1, clock.instant())));
return attempt;
}
private UUID insertContactPoint() {
UUID contact = UUID.randomUUID();
jdbc.update(
"insert into notification_contact_point (id, tenant_id, owner_ref, type, environment,"
+ " ciphertext, nonce, lookup_hmac, key_id, status, created_at, updated_at)"
@@ -359,6 +442,13 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest {
new byte[] {1, 2, 3},
new byte[] {4, 5, 6},
UUID.randomUUID().toString().replace("-", "").repeat(2));
return contact;
}
/** An attempt that started and never completed: the provider may or may not have it. */
private UUID insertStartedAttempt(UUID delivery, String providerId, String requestHash) {
UUID contact = insertContactPoint();
UUID attempt = UUID.randomUUID();
jdbc.update(
"insert into notification_delivery_attempt (id, recipient_delivery_id, contact_point_id,"
+ " attempt_no, channel, provider_id, provider_profile_id, provider_request_id_hash,"
@@ -98,12 +98,14 @@ final class PostgreSqlOptionalStreamLifecycle {
// row still carrying plaintext fails the migration rather than meeting the mapper at
// runtime,
// where it would look like a decryption bug instead of an un-migrated table.
// V11 gives a reconciliation job claim a lease and a fence, so two instances cannot both
// hold one job.
//
// This list is the stream's contract, not a note about its length: the lifecycle below
// disables, re-enables and interrupts the stream and asserts the applied set is unchanged
// each time. So a migration added to the stream belongs here, and the version that landed
// without being added is why the lane failed the first time anybody ran it.
List.of("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"),
List.of("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"),
List.of());
}
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.persistence.readiness;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException;
import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator;
import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping;
import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlSqlStateErrorMapping;
@@ -34,8 +35,8 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager;
* <p>The port is plain Spring {@code TransactionTemplate} per mode. What a real database adds over
* the unit tests is the part a recording transaction manager cannot show: that a rollback really
* removes the row, that {@code inNew} really commits on its own connection while the caller's
* transaction rolls back, and that a commit the server never acknowledged surfaces as a failure and
* is not replayed.
* transaction rolls back, and that a commit the server never acknowledged surfaces as a
* completion-unknown failure and is not replayed.
*/
class PostgreSqlTransactionIntegrationTest {
@@ -144,7 +145,7 @@ class PostgreSqlTransactionIntegrationTest {
@Test
@Tag("jpa-failure")
@Timeout(15)
void connectionLossDuringCommitSurfacesAsAFailureAndIsNeverRetried() throws Exception {
void connectionLossDuringCommitSurfacesAsCompletionUnknownAndIsNeverRetried() throws Exception {
JdbcTemplate jdbc = new JdbcTemplate(postgres.dataSource());
SpringTransaction port = transactionPort();
AtomicInteger backendPid = new AtomicInteger();
@@ -189,7 +190,12 @@ class PostgreSqlTransactionIntegrationTest {
}));
assertThat(terminated.get(5, TimeUnit.SECONDS)).isTrue();
assertThat(thrown).isInstanceOf(RuntimeException.class);
// The server may have committed before the connection dropped, so the caller must be told
// "outcome unknown, do not retry" — never the retryable DB_UNAVAILABLE (ADR-JPA-003).
assertThat(thrown).isInstanceOf(TransactionCompletionUnknownException.class);
PersistenceFailureException failure = (PersistenceFailureException) thrown;
assertThat(failure.errorCode()).isEqualTo(OperationalError.DB_COMPLETION_UNKNOWN);
assertThat(failure.errorCode().retryable()).isFalse();
assertThat(actionCalls).hasValue(1);
assertThat(jdbc.queryForObject("select count(*) from readiness_commit_uncertain", Long.class))
.isZero();
@@ -3,17 +3,26 @@ package dev.caskeleton.adapter.outbound.persistence.failure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName;
import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.OperationalError;
import dev.caskeleton.shared.error.PersistenceFailureException;
import java.io.EOFException;
import java.sql.SQLException;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.TransactionSystemException;
/**
* feature-persistence-failure-baseline §SQLState → Error Code Matrix (standard rows) + §Edge
@@ -222,6 +231,112 @@ class PersistenceExceptionTranslatorTest {
.hasMessageContaining(OperationalError.DB_DEADLOCK.name());
}
// ---- commit phase (ADR-JPA-003, review 04-01) ----
private static final PersistenceOperationName COMMIT =
new PersistenceOperationName("transaction.write.commit");
private static TransactionSystemException commitFailureWith(Throwable cause) {
return new TransactionSystemException("Could not commit JDBC transaction", cause);
}
@ParameterizedTest
@ValueSource(strings = {"08000", "08003", "08006", "40003"})
@DisplayName("커밋이 연결 계열 상태나 40003으로 실패하면 재시도 불가인 결과 불명으로 분류한다")
void connectionLossDuringCommitIsCompletionUnknown(String sqlState) {
// given
TransactionSystemException failure =
commitFailureWith(new SQLException("connection lost", sqlState));
// when
Optional<PersistenceFailureException> result =
translator.translateCommitFailure(failure, COMMIT, Duration.ofMillis(5));
// then
assertThat(result).containsInstanceOf(TransactionCompletionUnknownException.class);
PersistenceFailureException unknown = result.orElseThrow();
assertThat(unknown.errorCode()).isEqualTo(OperationalError.DB_COMPLETION_UNKNOWN);
assertThat(unknown.errorCode().retryable()).isFalse();
assertThat(((TransactionCompletionUnknownException) unknown).context().sqlState())
.isEqualTo(sqlState);
}
@Test
@DisplayName("SQLState 없이 소켓이 끊겨도 커밋 중이면 결과 불명으로 분류한다")
void transportBreakWithoutSqlStateDuringCommitIsCompletionUnknown() {
// given
TransactionSystemException failure =
commitFailureWith(new EOFException("unexpected end of stream"));
// when
Optional<PersistenceFailureException> result =
translator.translateCommitFailure(failure, COMMIT, Duration.ZERO);
// then
assertThat(result).containsInstanceOf(TransactionCompletionUnknownException.class);
}
@Test
@DisplayName("벤더가 기여한 종료 상태로 커밋이 실패하면 결과 불명으로 분류한다")
void vendorContributedTerminationStateDuringCommitIsCompletionUnknown() {
// given
PersistenceExceptionTranslator withVendor =
new PersistenceExceptionTranslator(
List.of(new StandardSqlStateErrorMapping(), new TerminationStateMapping()));
TransactionSystemException failure =
commitFailureWith(new SQLException("backend terminated", "57P01"));
// when
Optional<PersistenceFailureException> result =
withVendor.translateCommitFailure(failure, COMMIT, Duration.ZERO);
// then
assertThat(result).containsInstanceOf(TransactionCompletionUnknownException.class);
}
@Test
@DisplayName("서버가 커밋을 제약 위반으로 확실히 거절하면 원래 분류를 유지한다")
void commitDefinitelyRejectedKeepsItsOrdinaryClassification() {
// given
TransactionSystemException failure =
commitFailureWith(new SQLException("duplicate key", "23505"));
// when
Optional<PersistenceFailureException> result =
translator.translateCommitFailure(failure, COMMIT, Duration.ZERO);
// then
assertThat(result).isPresent();
assertThat(result.orElseThrow()).isNotInstanceOf(TransactionCompletionUnknownException.class);
assertThat(result.orElseThrow().errorCode()).isEqualTo(OperationalError.DB_UNIQUE_VIOLATION);
}
@Test
@DisplayName("SQLState도 전송 단절도 없는 커밋 실패는 분류하지 않고 비워 둔다")
void commitFailureWithNeitherSqlStateNorTransportBreakIsLeftUnclassified() {
// given
TransactionSystemException failure = new TransactionSystemException("commit failed");
// when
Optional<PersistenceFailureException> result =
translator.translateCommitFailure(failure, COMMIT, Duration.ZERO);
// then
assertThat(result).isEmpty();
}
private record TerminationStateMapping() implements SqlStateErrorMapping {
@Override
public Map<String, OperationalError> exactMappings() {
return Map.of();
}
@Override
public Set<String> commitOutcomeUnknownStates() {
return Set.of("57P01");
}
}
private record FirstMapping(Map<String, OperationalError> exactMappings)
implements SqlStateErrorMapping {}
@@ -2,6 +2,8 @@ package dev.caskeleton.adapter.outbound.persistence.postgresql;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName;
import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException;
import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator;
import dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping;
import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping;
@@ -10,13 +12,16 @@ import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.OperationalError;
import dev.caskeleton.shared.error.PersistenceFailureException;
import java.sql.SQLException;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.TransactionSystemException;
/** Unit tests for {@link PostgreSqlSqlStateErrorMapping}. */
class PostgreSqlSqlStateErrorMappingTest {
@@ -100,4 +105,37 @@ class PostgreSqlSqlStateErrorMappingTest {
assertThat(translator.translate(daoWithSqlState("40001")).orElseThrow().errorCode())
.isEqualTo(OperationalError.DB_SERIALIZATION_FAILURE);
}
@Test
@DisplayName("커밋 중 backend가 종료돼 57P01이 오면 결과 불명으로 분류한다")
void backendTerminatedDuringCommitIsCompletionUnknown() {
// given
TransactionSystemException commitFailure =
new TransactionSystemException(
"JDBC commit failed",
new SQLException("terminating connection due to administrator command", "57P01"));
// when
Optional<PersistenceFailureException> result =
translator.translateCommitFailure(
commitFailure, new PersistenceOperationName("transaction.write.commit"), Duration.ZERO);
// then
assertThat(result).containsInstanceOf(TransactionCompletionUnknownException.class);
assertThat(result.orElseThrow().errorCode()).isEqualTo(OperationalError.DB_COMPLETION_UNKNOWN);
}
@Test
@DisplayName("PostgreSQL이 기여하는 결과 불명 상태는 모두 PostgreSQL 표에 있는 상태다")
void everyCommitOutcomeUnknownStateIsAStateOfThePostgreSqlTable() {
// when
List<String> unclassified =
pgMapping.commitOutcomeUnknownStates().stream()
.filter(code -> PostgreSqlState.fromCode(code).isEmpty())
.toList();
// then
assertThat(pgMapping.commitOutcomeUnknownStates()).containsOnly("57P01", "57P02");
assertThat(unclassified).isEmpty();
}
}
@@ -23,7 +23,9 @@ class PostgreSqlFailureClassifierTest {
"23514,CHECK_CONSTRAINT",
"23502,NOT_NULL_CONSTRAINT",
"55P03,LOCK_NOT_AVAILABLE",
"57014,QUERY_TIMEOUT"
"57014,QUERY_TIMEOUT",
"57P01,CONNECTION_UNAVAILABLE",
"57P02,CONNECTION_UNAVAILABLE"
})
@DisplayName("each registered SQLSTATE maps to its category")
void classifiesBySqlState(String state, FailureCategory expected) {
@@ -5,9 +5,13 @@ import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy;
import dev.caskeleton.adapter.outbound.persistence.security.PostgreSqlRuntimeRoleVerifier;
import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import dev.caskeleton.adapter.outbound.support.startup.StartupRuleAutoConfiguration;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.util.concurrent.atomic.AtomicInteger;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.DisplayName;
@@ -129,6 +133,53 @@ class JpaStartupAutoConfigurationTest {
});
}
@Test
@DisplayName("prod에서 sslmode=disable이면 DataSource를 만들거나 연결을 열기 전에 종료 코드 71로 기동이 실패한다")
void aProdPlaintextDatabaseUrlFailsTheBootBeforeTheDataSourceExists() {
// given
AtomicInteger dataSourcesCreated = new AtomicInteger();
AtomicInteger connectionsOpened = new AtomicInteger();
// when
runner
.withConfiguration(AutoConfigurations.of(StartupRuleAutoConfiguration.class))
.withInitializer(context -> context.getEnvironment().setActiveProfiles("prod"))
.withPropertyValues(
"spring.jpa.open-in-view=false",
"spring.datasource.url=jdbc:postgresql://db.invalid:5432/app?sslmode=disable")
.withBean(
DataSource.class,
() -> {
dataSourcesCreated.incrementAndGet();
return new AbstractDataSource() {
@Override
public Connection getConnection() {
connectionsOpened.incrementAndGet();
throw new IllegalStateException("a guarded boot must not reach the database");
}
@Override
public Connection getConnection(String username, String password) {
return getConnection();
}
};
})
.run(
context -> {
// then
assertThat(context.getStartupFailure())
.isInstanceOfSatisfying(
StartupFailureException.class,
failure -> {
assertThat(failure.errorCode())
.isEqualTo(StartupErrorCode.PROFILE_MISMATCH);
assertThat(failure.getExitCode()).isEqualTo(71);
});
assertThat(dataSourcesCreated).hasValue(0);
assertThat(connectionsOpened).hasValue(0);
});
}
@Test
void safetySettingsDefaultToEnabled() {
runner
@@ -1,12 +1,21 @@
package dev.caskeleton.adapter.outbound.persistence.testkit.arch;
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 static org.assertj.core.api.Assertions.catchThrowable;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.FinalEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseCollectionParentEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseManyToManyEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseOneToOneEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.NoDefaultConstructorEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OrderEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningChildEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningManyToManyEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningOneToOneEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.UnidirectionalCollectionEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.BadOrderController;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.GoodOrderController;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.ListReturningController;
@@ -89,4 +98,96 @@ class JpaArchitectureRulesTest {
assertThatCode(() -> JpaArchitectureRules.entitiesFollowPortableMappingRules().check(classes))
.doesNotThrowAnyException();
}
@Test
void anInverseOneToManyIsRefusedWithThePrincipleAndTheAlternatives() {
// given
var classes =
new ClassFileImporter()
.importClasses(InverseCollectionParentEntity.class, OwningChildEntity.class);
// when
Throwable failure =
catchThrowable(
() -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes));
// then
assertThat(failure)
.isInstanceOf(AssertionError.class)
.hasMessageContaining("InverseCollectionParentEntity.children")
.hasMessageContaining("@OneToMany(mappedBy = \"parent\")")
.hasMessageContaining("one side only")
.hasMessageContaining("ID")
.hasMessageContaining("query");
}
@Test
void anInverseOneToOneIsRefused() {
// given
var classes =
new ClassFileImporter()
.importClasses(InverseOneToOneEntity.class, OwningOneToOneEntity.class);
// when
Throwable failure =
catchThrowable(
() -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes));
// then
assertThat(failure)
.isInstanceOf(AssertionError.class)
.hasMessageContaining("InverseOneToOneEntity.partner")
.hasMessageContaining("@OneToOne(mappedBy = \"partner\")");
}
@Test
void anInverseManyToManyIsRefused() {
// given
var classes =
new ClassFileImporter()
.importClasses(InverseManyToManyEntity.class, OwningManyToManyEntity.class);
// when
Throwable failure =
catchThrowable(
() -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes));
// then
assertThat(failure)
.isInstanceOf(AssertionError.class)
.hasMessageContaining("InverseManyToManyEntity.groups")
.hasMessageContaining("@ManyToMany(mappedBy = \"members\")");
}
@Test
void onlyTheMappedBySideOfABidirectionalPairIsReported() {
// given
var classes =
new ClassFileImporter()
.importClasses(InverseCollectionParentEntity.class, OwningChildEntity.class);
// when
Throwable failure =
catchThrowable(
() -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes));
// then
assertThat(failure)
.isInstanceOf(AssertionError.class)
.hasMessageNotContaining("OwningChildEntity.parent");
}
@Test
void unidirectionalAssociationsPass() {
var classes =
new ClassFileImporter()
.importClasses(
OwningChildEntity.class,
OwningOneToOneEntity.class,
OwningManyToManyEntity.class,
UnidirectionalCollectionEntity.class);
assertThatCode(() -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes))
.doesNotThrowAnyException();
}
}
@@ -0,0 +1,34 @@
package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import java.util.ArrayList;
import java.util.List;
/**
* Refused by the association rule: the inverse side of a bidirectional pair.
*
* <p>{@code mappedBy} declares that {@link OwningChildEntity#parent} writes the foreign key, so
* this list is a second copy of the same link that only an association helper keeps in step.
*/
@Entity
public class InverseCollectionParentEntity {
@Id private Long id;
@OneToMany(mappedBy = "parent")
private List<OwningChildEntity> children = new ArrayList<>();
protected InverseCollectionParentEntity() {}
/** The identifier. */
public Long id() {
return id;
}
/** The inverse collection. */
public List<OwningChildEntity> children() {
return List.copyOf(children);
}
}
@@ -0,0 +1,29 @@
package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import java.util.HashSet;
import java.util.Set;
/** Refused by the association rule: the inverse side of a bidirectional many-to-many. */
@Entity
public class InverseManyToManyEntity {
@Id private Long id;
@ManyToMany(mappedBy = "members")
private Set<OwningManyToManyEntity> groups = new HashSet<>();
protected InverseManyToManyEntity() {}
/** The identifier. */
public Long id() {
return id;
}
/** The inverse collection. */
public Set<OwningManyToManyEntity> groups() {
return Set.copyOf(groups);
}
}
@@ -0,0 +1,27 @@
package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.OneToOne;
/** Refused by the association rule: the inverse side of a bidirectional one-to-one. */
@Entity
public class InverseOneToOneEntity {
@Id private Long id;
@OneToOne(mappedBy = "partner")
private OwningOneToOneEntity partner;
protected InverseOneToOneEntity() {}
/** The identifier. */
public Long id() {
return id;
}
/** The inverse reference. */
public OwningOneToOneEntity partner() {
return partner;
}
}
@@ -0,0 +1,35 @@
package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
/**
* Accepted by the association rule on its own: a unidirectional, lazy {@code @ManyToOne}.
*
* <p>It is the owning side of {@link InverseCollectionParentEntity}'s pair, and the rule reports
* the {@code mappedBy} side, not this one — the foreign key belongs here either way.
*/
@Entity
public class OwningChildEntity {
@Id private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private InverseCollectionParentEntity parent;
protected OwningChildEntity() {}
/** The identifier. */
public Long id() {
return id;
}
/** The owning reference. */
public InverseCollectionParentEntity parent() {
return parent;
}
}
@@ -0,0 +1,28 @@
package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import java.util.HashSet;
import java.util.Set;
/** The owning side of {@link InverseManyToManyEntity}'s pair. */
@Entity
public class OwningManyToManyEntity {
@Id private Long id;
@ManyToMany private Set<InverseManyToManyEntity> members = new HashSet<>();
protected OwningManyToManyEntity() {}
/** The identifier. */
public Long id() {
return id;
}
/** The owning collection. */
public Set<InverseManyToManyEntity> members() {
return Set.copyOf(members);
}
}
@@ -0,0 +1,30 @@
package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToOne;
/** The owning side of {@link InverseOneToOneEntity}'s pair. */
@Entity
public class OwningOneToOneEntity {
@Id private Long id;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "partner_id")
private InverseOneToOneEntity partner;
protected OwningOneToOneEntity() {}
/** The identifier. */
public Long id() {
return id;
}
/** The owning reference. */
public InverseOneToOneEntity partner() {
return partner;
}
}

Some files were not shown because too many files have changed in this diff Show More