review-followup Wave 3 라운드 2(P26): HTTP client·JPA 구조 정리
- httpclient: 호출 준비 `CallSetup` 하나(Dynamic Target 포함 — deadline·admission 누락 P26-new-1 수정), 예외가 자기 category, 구현 1개 내부 인터페이스 2개·죽은 표면(`withAdditional`, `SafeHttpLogEvent`, tag policy bean) 삭제, `secret://` 파싱 하나 - JPA: ddl-auto 검사 하나(P26-new-2 수정), SQLSTATE 표 하나, `isProdActive` wrapper 삭제, durable_operation 리포지토리 축소 - E-6b는 멱등성·outbox 리포지토리가 남음(P18 이동 뒤 P19) 검증: ./gradlew check architectureCheck verifyDependencyLocks --continue 통과(597 task), 묶음 worktree에서 jpaPlatformContractTest 217·jpaPlatformFailureTest 3·postgresql*IntegrationTest 88 통과 Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
c4a066df41
commit
4fb7943b85
@@ -368,3 +368,13 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap
|
||||
| `GraphQlPlatformRejectionMapper` (instanceof 사슬) | `src/adapter/inbound/graphql/.../runtime/GraphQlPlatformRejectionMapper.java` | `016597ac` | S5-#6d: 예외가 `GraphQlPlatformRejection` 구현 |
|
||||
| `runtime/GraphQlWireErrorMapper`, `runtime/GraphQlWireErrors` (이동) | `src/adapter/inbound/graphql/.../runtime/` → `.../error/` | `016597ac` | 삭제가 아니라 `error/` 패키지로 이동(S5-#6d). `classificationOf`·`category`·`clientMessage` switch는 `RENDERINGS` 표로 대체 |
|
||||
| sample publisher별 JSON escape 사본 3개 | `PosterEventPublisher`·`PosterImagePublicationEventPublisher`·`WorkLogReservedIntegrationEventMapper`(`escape`/`field`/`jsonField`) | `016597ac` | X2-P1-6: `EventJson` 하나로 |
|
||||
| `SensitiveHeaderStripper.withAdditional` | `src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/security/SensitiveHeaderStripper.java` | `c4a066df` | H-4b. main 호출자 0, executor는 `alsoStripping` 사용 |
|
||||
| `SafeHttpLogEvent`, `HttpClientTagPolicyTest.safeLogEventCarriesNoSecretOrExpandedUrl` | `src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/observation/SafeHttpLogEvent.java` | `c4a066df` | S3-#8b. 테스트만 참조 |
|
||||
| `HttpClientTagPolicy` bean(`httpClientTagPolicy`) | `.../httpclient/autoconfigure/HttpClientObservationAutoConfiguration.java` | `c4a066df` | S3-#6. 소비처 0, override 불가 |
|
||||
| `RetryCoordinator` 인터페이스(구현 `BlockingRetryCoordinator` → `RetryCoordinator` 개명) | `.../httpclient/resilience/RetryCoordinator.java` | `c4a066df` | S3-#7. 구현 1개, fake 없음 |
|
||||
| `ExecutionEvidenceClassifier` 인터페이스(구현 `DefaultExecutionEvidenceClassifier` → `ExecutionEvidenceClassifier` 개명) | `.../httpclient/resilience/ExecutionEvidenceClassifier.java` | `c4a066df` | S3-#7. 구현 1개, fake 없음 |
|
||||
| `BlockingAttemptExecutor.categoryOf` (`getSimpleName()` switch) | `.../httpclient/restclient/BlockingAttemptExecutor.java` | `c4a066df` | H-7a. 예외가 자기 category를 구현 |
|
||||
| `BlockingExecutionSupport`(→ `ExecutionSupport` 개명) | `.../httpclient/restclient/BlockingExecutionSupport.java` | `c4a066df` | S3-#6. blocking만 남아 접두어 무의미 |
|
||||
| `JpaSchemaSafetyValidator`, `JpaSchemaSafetyValidatorTest` | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaSchemaSafetyValidator.java` | `93251e76` | S6-#3c. guard와 중복, guard보다 늦게 돌아 발동한 적 없음 |
|
||||
| `isProdActive()` wrapper 4개 | `persistence-jpa/.../startup/{FlywayProdSafetyValidator,PersistenceVendorProdSafetyValidator,PostgreSqlTransportSecurityValidator}.java`, `app-bootstrap/.../runtime/SecretSourceValidator.java` | `93251e76` | S6-#3d. `RuntimeProfileSnapshot.isProduction()` 1줄 위임 |
|
||||
| `DurableOperationJpaRepository`의 `JpaRepository` 상속(findAll/deleteAll 등) | `persistence-jpa/.../operation/DurableOperationJpaRepository.java` | `93251e76` | E-6b. tenant 범위 없는 bulk 메서드 노출 |
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
## 행 결과
|
||||
| ID | 결과 | 근거 |
|
||||
|---|---|---|
|
||||
| E-6b | 남음 | 일부 완료(커밋 `27958d6c`): `DurableOperationJpaRepository`를 `Repository` marker + 사용 메서드(`findById` 포함)만으로 축소. `DurableOperationJpaRepositoryShapeTest.repositoryExposesNoUnscopedBulkReadOrDelete` FAIL(`Expecting empty but was: ["findAll","deleteAllInBatch","deleteAllByIdInBatch","findAllById","deleteAll","deleteAllById","count"]`)→PASS. `persistence-jpa/.../operation/DurableOperationJpaRepository.java:25`. 남은 것: `IdempotencyRecordJpaRepository`·`OutboxEventJpaRepository`는 이 묶음 지시상 제외(같은 라운드의 P18이 persistence-jpa outbox·멱등성 패키지를 이동 중). P18 통합 후 같은 방식(`Repository` marker + 쓰는 메서드만, 같은 모양의 shape 테스트)으로 처리 |
|
||||
| H-4b | 완료 | `SensitiveHeaderStripper.withAdditional` 삭제(main·test 호출자 0, P14의 cross-origin allowlist(결정 23) 적용 뒤 현재 코드로 확인). 남은 공개 확장은 executor가 쓰는 `alsoStripping`(`HC/security/SensitiveHeaderStripper.java:45`). 커밋 `93251e76`. 삭제만이라 재현 테스트 없음 |
|
||||
| H-7a | 완료 | `HttpClientException`에 `public abstract FailureCategory category()`(`HC/api/error/HttpClientException.java:40`), 하위 예외 23개가 각자 구현. `BlockingAttemptExecutor`의 `getSimpleName()` switch 삭제, `stable.category()` 사용(`HC/restclient/BlockingAttemptExecutor.java:106,120`). reactive 쪽 switch는 결정 9로 이미 없음. 기존 switch가 UNKNOWN으로 두던 타입(Ambiguous·RetryBudgetExhausted·RuntimeDraining·UnknownTransport)은 UNKNOWN 유지, `HttpRemoteErrorException`은 REMOTE_STATUS(내부 catch가 이미 그렇게 처리). 테스트 `StableExceptionTest.eachStableFailureNamesItsOwnCategoryRatherThanItsClassName`: 새 API라 FAIL 단계는 컴파일 실패 → PASS |
|
||||
| S2-#3b | 완료 | SQL 표준 코드 5개를 `StandardSqlStateErrorMapping` 상수로 한 번 정의(`persistence-jpa/.../failure/StandardSqlStateErrorMapping.java:20-33`). `PostgreSqlState`의 표준 멤버가 그 상수를 참조(`postgresql/error/PostgreSqlState.java:24-42`)하고, `PostgreSqlSqlStateErrorMapping`은 코드를 `PostgreSqlState.*.code()`에서 읽음(`postgresql/PostgreSqlSqlStateErrorMapping.java:17-23`). 방향 조정: 계획은 "`SqlStateErrorMapping`이 `PostgreSqlState`를 참조"였으나 vendor-neutral `failure` 패키지는 `postgresql`을 참조할 수 없음(ArchUnit `PERSISTENCE_RDBMS_STAYS_VENDOR_NEUTRAL`)이라 표준 코드는 neutral 쪽에 두고 vendor enum이 그쪽을 참조. 새 테스트 `PostgreSqlSqlStateErrorMappingTest.everyCodeAPostgreSqlDeploymentMapsIsAStateOfTheOnePostgreSqlTable`(리팩터, 기존 코드에서도 PASS). 공개 타입 변경 없음(상수 추가만), `verifyJpaApiSurface` 통과 |
|
||||
| S3-#2b | 완료 | `CallSetup.prepare(lease, operation)`이 blocking runtime·metadata·target policy·deadline(+guard)을 준비하고 `admit()`·`credentials()`·`credentialRequest()` 제공(`HC/restclient/CallSetup.java:49,79`). generic(`DefaultGenericHttpGateway.java:69`)과 streaming(`BlockingStreamingGateway.java:50`) 진입점이 사용. Dynamic Target은 target 준비(SSRF 핀)가 달라 `CallSetup.guardedDeadline`과 admission permit만 공유(`dynamic/DefaultDynamicTargetGateway.java:104`) — 이 과정에서 P26-new-1 발견·수정. reactive 진입점 3개는 결정 9로 이미 삭제. service(H1)는 generic gateway를 경유 |
|
||||
| S3-#6 | 완료 | `HttpClientObservationAutoConfiguration`의 `HttpClientTagPolicy` bean 삭제(소비처 0, private 생성자라 override 불가). `BlockingExecutionSupport` → `ExecutionSupport` 개명(`HC/restclient/ExecutionSupport.java`, bean `httpClientExecutionSupport` `HttpClientObservationAutoConfiguration.java:24`). 커밋 `93251e76` |
|
||||
| S3-#7 | 완료 | 삭제: `RetryCoordinator` 인터페이스(구현 `BlockingRetryCoordinator`를 `RetryCoordinator`로 개명, `HC/resilience/RetryCoordinator.java:20`, 테스트 `RetryCoordinatorTest`), `ExecutionEvidenceClassifier` 인터페이스(`DefaultExecutionEvidenceClassifier`를 그 이름으로, `HC/resilience/ExecutionEvidenceClassifier.java:12`). 유지(근거): `RetryEligibilityEngine` — `DefaultGenericHttpGatewayTest:287,311`이 lambda fake를 넣고 `TestGateways.forProfile(.., RetryEligibilityEngine)`이 교체 지점; `BackoffStrategy` — `RetryCoordinatorTest.ambiguousOutcomeIsRaisedRatherThanRetried`·`exhaustedBudgetStopsRetryingImmediately`가 `(a, r, d) -> Duration.ZERO` fake를 씀(삭제 시도 시 컴파일 실패로 확인) |
|
||||
| S3-#8b | 완료 | `SafeHttpLogEvent`와 전용 테스트 메서드 `HttpClientTagPolicyTest.safeLogEventCarriesNoSecretOrExpandedUrl` 삭제. `MultipartReplayability`는 결정 9 reactive 삭제(`6d27356e` 이전 커밋)로 이미 없음. http3 유지 |
|
||||
| S3-#10 | 완료 | `HttpClientPlatformSettings`의 enum 필드 7개(`mode`·`transport`·`protocols`·`authentication.type`·`retry.jitter`·`retry.retryAfter`·`proxy.type`)를 enum 타입으로 선언(`HC/autoconfigure/HttpClientPlatformSettings.java:127,131,134,212,225,226,255`), binder가 대소문자 변환. `HttpClientProfileFactory`의 `valueOf(toUpperCase())` 7곳 삭제, 복사 구조 유지. 동작 보존 리팩터라 새 FAIL 테스트 없음 — 기존 `HttpClientPlatformEnvManifestTest`·`UnsafeStartupConfigurationTest`(`SIMPLE`·`HTTP_3`)·`HttpClientPlatformActivationTest.detailSettingsAreNotBoundWhileTheCapabilityIsOff`(`NOT_A_TRANSPORT`) 통과. prefix·strict 바인딩(3-B, S3-lead-2)은 건드리지 않음 |
|
||||
| S3-lead-5 | 완료 | `application-core` `SecretReference`(record source/name, `parse`·`isReference`, `application-core/.../outbound/SecretReference.java:47`)를 `SecretSourcePort` 옆에 추가. httpclient(`HttpClientAuthenticationAutoConfiguration.java:60-64`)와 cache-redis(`RedisKeys.java:83`)가 사용 — 둘 다 기존 edge(application-core) 안, registry 변경 없음. mongo·redis-runtime은 지시대로 유지. 테스트 `SecretReferenceTest` 6개(새 타입이라 FAIL은 컴파일 실패). cache-redis는 이름이 빈 `secret://src/`를 빈 키로 port에 넘기던 것이 이제 거부됨(`referenceWhoseNameIsBlankIsRejected`) |
|
||||
| S6-#3c | 완료 | `JpaSchemaSafetyValidator`(+테스트) 삭제, `JpaDangerousConfigurationGuard`가 유일한 ddl-auto 검사. 기존 validator 테스트의 성질(prod 거부·blank 거부·대소문자·local 허용·`APP_DATASOURCE_DDL_AUTO` 명시·`PROFILE_MISMATCH`)을 guard 테스트로 옮김. `JpaDangerousConfigurationGuardTest.productionRefusesASchemaMutatingDdlAutoAsAProfileMismatchNamingTheEnvironmentKey` 등 10건 FAIL(guard가 `IllegalStateException`을 던짐)→PASS. `persistence-jpa/.../startup/JpaDangerousConfigurationGuard.java:46-66`. README 3곳 갱신 |
|
||||
| S6-#3d | 완료 | 1줄 wrapper 삭제, 호출부에서 `RuntimeProfileSnapshot.from(environment).isProduction()` 직접 호출: `FlywayProdSafetyValidator`, `PersistenceVendorProdSafetyValidator`, `PostgreSqlTransportSecurityValidator`, `bootstrap/runtime/SecretSourceValidator`. `JpaSchemaSafetyValidator` 몫은 S6-#3c 삭제로 해소. `shared-contract` `RuntimeEnvironment.isProductionActive` 문서의 "isProdActive() copies" 언급은 역사 설명이라 유지. 동작 동일, 기존 테스트 통과 |
|
||||
|
||||
## 제거된 코드
|
||||
| 대상 | 경로 | 마지막으로 존재한 커밋 | 이유 |
|
||||
|---|---|---|---|
|
||||
| `SensitiveHeaderStripper.withAdditional` | `src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/security/SensitiveHeaderStripper.java` | `c4a066df` | H-4b. main 호출자 0, executor는 `alsoStripping` 사용 |
|
||||
| `SafeHttpLogEvent`, `HttpClientTagPolicyTest.safeLogEventCarriesNoSecretOrExpandedUrl` | `src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/observation/SafeHttpLogEvent.java` | `c4a066df` | S3-#8b. 테스트만 참조 |
|
||||
| `HttpClientTagPolicy` bean(`httpClientTagPolicy`) | `.../httpclient/autoconfigure/HttpClientObservationAutoConfiguration.java` | `c4a066df` | S3-#6. 소비처 0, override 불가 |
|
||||
| `RetryCoordinator` 인터페이스(구현 `BlockingRetryCoordinator` → `RetryCoordinator` 개명) | `.../httpclient/resilience/RetryCoordinator.java` | `c4a066df` | S3-#7. 구현 1개, fake 없음 |
|
||||
| `ExecutionEvidenceClassifier` 인터페이스(구현 `DefaultExecutionEvidenceClassifier` → `ExecutionEvidenceClassifier` 개명) | `.../httpclient/resilience/ExecutionEvidenceClassifier.java` | `c4a066df` | S3-#7. 구현 1개, fake 없음 |
|
||||
| `BlockingAttemptExecutor.categoryOf` (`getSimpleName()` switch) | `.../httpclient/restclient/BlockingAttemptExecutor.java` | `c4a066df` | H-7a. 예외가 자기 category를 구현 |
|
||||
| `BlockingExecutionSupport`(→ `ExecutionSupport` 개명) | `.../httpclient/restclient/BlockingExecutionSupport.java` | `c4a066df` | S3-#6. blocking만 남아 접두어 무의미 |
|
||||
| `JpaSchemaSafetyValidator`, `JpaSchemaSafetyValidatorTest` | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaSchemaSafetyValidator.java` | `93251e76` | S6-#3c. guard와 중복, guard보다 늦게 돌아 발동한 적 없음 |
|
||||
| `isProdActive()` wrapper 4개 | `persistence-jpa/.../startup/{FlywayProdSafetyValidator,PersistenceVendorProdSafetyValidator,PostgreSqlTransportSecurityValidator}.java`, `app-bootstrap/.../runtime/SecretSourceValidator.java` | `93251e76` | S6-#3d. `RuntimeProfileSnapshot.isProduction()` 1줄 위임 |
|
||||
| `DurableOperationJpaRepository`의 `JpaRepository` 상속(findAll/deleteAll 등) | `persistence-jpa/.../operation/DurableOperationJpaRepository.java` | `93251e76` | E-6b. tenant 범위 없는 bulk 메서드 노출 |
|
||||
|
||||
## 새로 발견한 결함
|
||||
- `P26-new-1` (고침): Dynamic Target(H3) 호출이 deadline 검사도 admission permit도 거치지 않았다 — 만료된 deadline에도 hop을 보냈고 profile 동시성 한도 밖에서 돌았다(과거 streaming download와 같은 drift). `HC/dynamic/DefaultDynamicTargetGateway.java:104`에서 `CallSetup.guardedDeadline` + admission permit을 호출 전체에 걸고, hop마다 deadline을 다시 확인. `DefaultDynamicTargetGatewayTest.expiredDeadlineIsRefusedBeforeAnyHopIsSent` FAIL(예외 없이 요청 전송, `thrown`이 null → NPE)→PASS.
|
||||
- `P26-new-2` (고침): prod에서 schema를 바꾸는 `ddl-auto`의 실제 거부가 문서(README "`PROFILE_MISMATCH`로 부팅 중단")와 달리 `IllegalStateException`이었다. `JpaDangerousConfigurationGuard`(`InitializingBean`)가 `JpaSchemaSafetyValidator`(`SmartInitializingSingleton`)보다 먼저 돌아서 후자는 발동한 적이 없다. S6-#3c에서 guard가 `ProfileMismatchException`을 던지도록 고침.
|
||||
- `P26-new-3` (고침): cache-redis `RedisKeys.secretName`이 `secret://src/`(이름 빈 참조)를 통과시켜 `SecretSourcePort.resolve("")`를 호출했다. `SecretReference.parse`가 거부.
|
||||
|
||||
## 검증
|
||||
- `./gradlew :adapter:outbound:httpclient:check :application-core:check :adapter:outbound:cache-redis:check --max-workers=2` — BUILD SUCCESSFUL (httpclient check에 `httpClientSecurityTest`·`httpClientStableContractTest`·`spring62ApiSurfaceScan` 포함)
|
||||
- `./gradlew :adapter:outbound:persistence-jpa:check :app-bootstrap:check --max-workers=2` — BUILD SUCCESSFUL
|
||||
- PG lane(Docker): `jpaPlatformContractTest` 217/0 실패, `jpaPlatformFailureTest` 3/0, `postgresql*IntegrationTest` readiness 17개 lane 합계 88/0 실패·0 skip, `verifyJpaApiSurface` 통과 — BUILD SUCCESSFUL
|
||||
- `./gradlew architectureCheck --max-workers=2` — BUILD SUCCESSFUL
|
||||
- 의존성·env 키·migration 변경 없음(lockfile·verifyEnvKeys 대상 아님). 새 migration 버전 없음
|
||||
@@ -282,7 +282,7 @@ Wave 1–2 구현 중 나온 질문에 대해 받은 7건(2026-09-28):
|
||||
| E-5b | Required | gate가 `tenant_scope`·`aggregate_type`을 안 봐 다른 tenant/type의 같은 `aggregate_id` DEAD row가 서로 영구 차단 | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): 실제 PG `aDeadCanonicalRowOfAnotherTenantOrTypeDoesNotBlockTheSameAggregateId` FAIL(`[]`)→PASS. E-5a와 같은 SQL 변경(canonical 쌍은 tenant_scope·aggregate_type까지 같아야 같은 aggregate) | - | canonical row의 gate 키를 `(tenant_scope, aggregate_type, aggregate_id)`로(E-5a와 같은 SQL 변경, PostgreSQL·H2 두 곳) |
|
||||
| E-5c | Required | README가 "한 배치에 aggregate 당 최대 한 row"라고 적음(같은 `occurred_at`이면 거짓) | 남음 | `src/adapter/outbound/persistence-jpa/README.md:248-249` | W5 | E-5a 수정 후 README를 실제 보장에 맞춤 |
|
||||
| E-6a | Required | H10 tenant 규칙이 필드 이름 `tenantId`로만 판정("Structural" Javadoc과 반대) → `tenant`, `tenantScope` 엔티티 누락 | 남음 | `src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/TenantScopedRepositoryPredicate.java:12-19,49` | W4 | `tenant*` 필드 전부(또는 marker annotation)로 판정 |
|
||||
| E-6b | Required | tenant 컬럼을 가진 세 리포지토리가 `JpaRepository`를 상속해 범위 없는 `findAll`/`deleteAll` 노출 | 남음 | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationJpaRepository.java:25-26`, `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyRecordJpaRepository.java:12-13`, `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxEventJpaRepository.java:16` | W3 | 세 리포지토리를 `Repository` marker + 쓰는 메서드만 선언으로 축소 |
|
||||
| E-6b | Required | tenant 컬럼을 가진 세 리포지토리가 `JpaRepository`를 상속해 범위 없는 `findAll`/`deleteAll` 노출 | 남음 | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationJpaRepository.java:25-26`, `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyRecordJpaRepository.java:12-13`, `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxEventJpaRepository.java:16`<br>Wave 3 W3-P26: 미완 — 일부 완료(커밋 `27958d6c`): `DurableOperationJpaRepository`를 `Repository` marker + 사용 메서드(`findById` 포함)만으로 축소. `DurableOperationJpaRepositoryShapeTest.repositoryExposesNoUnscopedBulkReadOrDelete` FAIL(`Expecting empty but was: ["findAll","deleteAllInBatch","deleteAllByIdInBatch","findAllById","deleteAll","deleteAllById","count"]`)→PASS. `persistence-jpa/.../operation/DurableOperationJpaRepository.java:25`. 남은 것: `IdempotencyRecordJpaRepository`·`OutboxEventJpaRepository`는 이 묶음 지시상 제외(같은 라운드의 P18이 persistence-jpa outbox·멱등성 패키지를 이동 중). P18 통합 후 같은 방식(`Repository` marker + 쓰는 메서드만, 같은 모양의 shape 테스트)으로 처리 | W3 | 세 리포지토리를 `Repository` marker + 쓰는 메서드만 선언으로 축소 |
|
||||
| E-7 | Consider | 잘못된 canonical row 하나가 `claimBatch` 매핑에서 예외 → claim 트랜잭션 전체 롤백 → 매 주기 같은 row 재선택으로 relay 정지 | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): `OutboxStoreAdapterTest.claimBatchMovesAnUnreadableRowToDeadAndClaimsTheRestOfTheBatch` FAIL(IllegalStateException partial canonical)→PASS, 실제 PG `anUnreadableCanonicalRowDoesNotStopTheRestOfTheBatchFromBeingClaimed`·`anUnreadableCanonicalRowIsMovedToDeadByTheClaim` FAIL(projection mismatch 예외)→PASS. `.../outbox/OutboxStoreAdapter.java:84-110` 매핑 실패 row는 DEAD·lease 해제 후 배치에서 제외(legacy로 낮추지 않으므로 fail-closed 유지) | - | 매핑 실패 row는 DEAD로 전이하고 배치의 나머지는 계속 |
|
||||
| E-8a | Consider | outbox 지표 쿼리가 매 poll(PT5S)마다 테이블 전체를 status별로 셈(7일치 PUBLISHED 포함) | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): 실제 PG `countByStatusLeavesPublishedRowsUncounted` FAIL(`{PENDING=1, PUBLISHED=1}`)→PASS. `countGroupedByStatus`에 `where e.status <> 'PUBLISHED'`(`.../outbox/OutboxEventJpaRepository.java`), fake `InMemoryOutboxStore.countByStatus` 동일, 포트 문서 갱신, `OutboxMetrics`는 PUBLISHED 시리즈를 내보내지 않음(0 고정 시리즈 방지). lifecycle PG 테스트의 PUBLISHED 카운트 단언 3곳은 row 상태 직접 조회로 교체 | - | `countGroupedByStatus`에 `where e.status <> 'PUBLISHED'` |
|
||||
| E-8b | Consider | `OutboxReaper`가 PUBLISHED 삭제를 한도 없는 단일 트랜잭션 DELETE로 실행 | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): `OutboxReaperTest` 3건 FAIL(컴파일: `deletePublishedBatch` 없음)→PASS. native `DELETE … WHERE event_id IN (SELECT … LIMIT n)`(ctid 대신 PG·H2 공통 SQL)를 repository 메서드 `@Transactional`로 배치마다 커밋, 덜 찬 배치에서 종료: `.../outbox/OutboxEventJpaRepository.java:19-35`, `.../outbox/OutboxReaper.java`(배치 1,000, `ponytail:` 주석). 실제 PG `reaperDeletesOldPublishedRowsOutsideAnyCallerTransaction`, H2 `theReaperBatchDeleteRunsOnH2AndStopsAtItsLimit` PASS | - | native `DELETE … WHERE ctid IN (SELECT … LIMIT n)`를 0건 될 때까지 배치별 트랜잭션으로 반복 |
|
||||
@@ -378,13 +378,13 @@ Wave 1–2 구현 중 나온 질문에 대해 받은 7건(2026-09-28):
|
||||
| H-3c | Required | Dynamic redirect가 cross-origin hop에서 호출자 헤더(`X-Api-Key` 등 `HeaderPolicy` 허용 헤더)를 그대로 전달 | 완료 | Wave 1–2 P11 (fcddab7e·Wave 2 커밋): `DefaultDynamicTargetGatewayTest.crossOriginHopDropsTheCallerSuppliedApiKey` FAIL(`[true, true]` ≠ `[true, false]`)→PASS. `HC/dynamic/DefaultDynamicTargetGateway.java:162`. 수정 방향대로 `SensitiveHeaderStripper` 표준 이름만 제거함 — 관례 밖 이름의 호출자 헤더는 P11-new-4 | - | origin이 바뀌면 `SensitiveHeaderStripper.stripForCrossOrigin`으로 헤더 정리 후 다음 hop 준비 |
|
||||
| H-3d | Required | `DefaultDynamicTargetGateway.exchange`를 호출하는 테스트 0건 | 남음 | httpclient 전체에서 `DefaultDynamicTargetGateway` 참조는 main 2파일(`DefaultDynamicTargetGateway.java`, `DynamicTargetAutoConfiguration.java`)뿐 | W4 | httpclient `src/test`에 redirect 계약 테스트(303 body 제거, 307 1회, cross-origin 헤더 제거, trace off) 추가 |
|
||||
| H-4a | Required | 허용된 API-key 헤더 `X-Client-Key`가 cross-origin redirect에서 제거되지 않음 | 완료 | Wave 1–2 P11 (fcddab7e·Wave 2 커밋): `BlockingRedirectCoordinatorTest.crossOriginHopDropsTheProfileCredentialHeader` FAIL(`[true, true]` ≠ `[true, false]`)→PASS. `HC/restclient/BlockingAttemptExecutor.java:187`(붙인 자격증명 헤더 이름을 stripper에 추가), `HC/security/SensitiveHeaderStripper.java:61`(`alsoStripping`, `withAdditional`은 이것에 위임 — H-4b(W3) 삭제 대상은 그대로). 참고: 기동 검증이 API key + `allowCrossOrigin`을 이미 거부하므로 방어 계층 수정 | - | `BlockingRedirectCoordinator`의 cross-origin 처리에서 실제 해석된 `RequestCredentials.headers().keySet()`도 함께 제거 |
|
||||
| H-4b | Required | `SensitiveHeaderStripper.withAdditional` main 호출자 0 | 남음 | `src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/security/SensitiveHeaderStripper.java:47-55` | W3 | H-4a 적용 후 `withAdditional` 삭제 |
|
||||
| H-4b | Required | `SensitiveHeaderStripper.withAdditional` main 호출자 0 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): `SensitiveHeaderStripper.withAdditional` 삭제(main·test 호출자 0, P14의 cross-origin allowlist(결정 23) 적용 뒤 현재 코드로 확인). 남은 공개 확장은 executor가 쓰는 `alsoStripping`(`HC/security/SensitiveHeaderStripper.java:45`). 커밋 `93251e76`. 삭제만이라 재현 테스트 없음 | - | H-4a 적용 후 `withAdditional` 삭제 |
|
||||
| H-5a | Required | reactive 경로가 실패 단계를 기록하지 않아 전송 후 실패도 `VALIDATION`(NOT_SENT)으로 분류 → 호출자가 실행된 POST를 재전송 | 해당 없음(코드 삭제) | Wave 1–2 P11 (fcddab7e·Wave 2 커밋): D `06764fcb`에서 `webclient/ReactiveAttemptExecutor` 삭제. blocking은 단계 기록함: `HC/restclient/BlockingAttemptExecutor.java:233,238`(`tracker.enter(REQUEST_BODY/RESPONSE_HEADERS)`)이 classifier로 전달 | - | `exchangeToMono` 안에서 요청 전송 뒤 `REQUEST_BODY`, 응답 수신 시 `RESPONSE_HEADERS`/`RESPONSE_BODY`를 기록해 classifier에 넘김 |
|
||||
| H-5b | Required | `DataBufferLimitException`(응답 크기 초과)이 어디서도 매핑되지 않아 NOT_SENT/connect 실패로 보고 | 해당 없음(코드 삭제) | Wave 1–2 P11 (fcddab7e·Wave 2 커밋): D `06764fcb`에서 `WebClientResponseMapper`·`ReactorFailureClassifier` 삭제. blocking은 크기 초과를 `HC/restclient/ResponseSizeLimiter.java:42,50`에서 `HttpResponseTooLargeException`으로 던지고 `BlockingAttemptExecutor.java:303`이 `RESPONSE_TOO_LARGE`로 분류 | - | `WebClientResponseMapper`에서 `DataBufferLimitException`을 `HttpResponseTooLargeException`으로 변환 |
|
||||
| H-5c | Required | 모르는 transport 실패가 mapper `default`에서 `HttpConnectException`이 됨 | 완료 | Wave 1–2 P11 (fcddab7e·Wave 2 커밋): blocking 결함(`StableBlockingExceptionMapper`)이라 W2에서 수정. `StableBlockingExceptionMapperTest.unknownTransportFailureIsNotReportedAsAConnectFailure` FAIL(`expected HttpUnknownTransportException but was HttpConnectException`)→PASS. `HC/restclient/StableBlockingExceptionMapper.java:40`, 새 타입 `HC/api/error/HttpUnknownTransportException.java`. reactive 쪽 테스트는 코드 삭제로 없음 | - | `default`를 전용 unknown 예외 타입으로 바꾸고 blocking·reactive 둘 다 테스트 |
|
||||
| H-6a | Required | OAuth2 토큰 네트워크 조회가 `ConcurrentHashMap.compute` 안에서 실행돼 같은 bin 호출자가 모니터에서 대기(N번째 ≈ N×10s) | 완료 | Wave 1–2 P11 (fcddab7e·Wave 2 커밋): `OAuth2CredentialProviderTest.aSlowRefreshDoesNotHoldUpAnotherRegistrationThatSharesItsBin` FAIL(`java.util.concurrent.TimeoutException` — 같은 bin의 다른 registration이 느린 refresh 뒤에서 대기)→PASS. `HC/auth/OAuth2CredentialProvider.java:65-69`(`cache.get` → lock 밖 `tokenLoader.load` → `cache.put`) | - | `cache.get` + 만료 검사 → lock 밖에서 `tokenLoader.load(key)` → `cache.put`(single-flight는 loader가 이미 보장) |
|
||||
| H-6b | Required | timeout 난 호출자가 공유 future를 `cancel(true)` → 뒤늦은 합류자는 raw `CancellationException`, pool 스레드는 인터럽트 안 됨 | 완료 | Wave 1–2 P11 (fcddab7e·Wave 2 커밋): `SingleFlightTokenLoaderTest.aCallerThatJoinedLaterStillGetsTheTokenAfterAnEarlierCallerTimedOut` FAIL(`ExecutionException: CancellationException`)→PASS. timeout·interrupt 분기에서 `cancel(true)` 제거 `HC/auth/SingleFlightTokenLoader.java:81`, `CancellationException`→`HttpAuthenticationException` `:113` | - | 호출자 timeout에서는 cancel하지 않고 `inFlight`에서만 제거, `CancellationException`을 `HttpAuthenticationException`으로 변환 |
|
||||
| H-7a | Consider | `categoryOf`가 `getSimpleName()` 문자열 switch로 blocking·reactive에 중복 | 남음 | `src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingAttemptExecutor.java:291-312`, `webclient/ReactiveAttemptExecutor.java:182-200` | W3 | `HttpClientException`에 `FailureCategory category()`를 두고 각 하위 예외가 구현, 두 switch 삭제 |
|
||||
| H-7a | Consider | `categoryOf`가 `getSimpleName()` 문자열 switch로 blocking·reactive에 중복 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): `HttpClientException`에 `public abstract FailureCategory category()`(`HC/api/error/HttpClientException.java:40`), 하위 예외 23개가 각자 구현. `BlockingAttemptExecutor`의 `getSimpleName()` switch 삭제, `stable.category()` 사용(`HC/restclient/BlockingAttemptExecutor.java:106,120`). reactive 쪽 switch는 결정 9로 이미 없음. 기존 switch가 UNKNOWN으로 두던 타입(Ambiguous·RetryBudgetExhausted·RuntimeDraining·UnknownTransport)은 UNKNOWN 유지, `HttpRemoteErrorException`은 REMOTE_STATUS(내부 catch가 이미 그렇게 처리). 테스트 `StableExceptionTest.eachStableFailureNamesItsOwnCategoryRatherThanItsClassName`: 새 API라 FAIL 단계는 컴파일 실패 → PASS | - | `HttpClientException`에 `FailureCategory category()`를 두고 각 하위 예외가 구현, 두 switch 삭제 |
|
||||
| H-7b | Consider | reactive `categoryOf`에 CircuitOpen·RateLimitRejected·BulkheadRejected가 없어 telemetry가 `UNKNOWN` | 해당 없음(코드 삭제) | Wave 1–2 P11 (fcddab7e·Wave 2 커밋): D `06764fcb`에서 `ReactiveAttemptExecutor` 삭제. blocking `categoryOf`에는 세 case 있음 `HC/restclient/BlockingAttemptExecutor.java:308-310` | - | H-7a로 해결. 별도로 하면 reactive switch에 세 case 추가 |
|
||||
| H-8 | Consider | bridge `prepare`가 모든 `RuntimeException`을 cause 없이 `REJECTED_BEFORE_SEND`로 바꿈 | 완료 | Wave 1–2 P11 (fcddab7e·Wave 2 커밋): `PlatformIntegrationEventPublishAdapterTest.aFailureOtherThanAnIncompatibleValueIsNotTurnedIntoARefusal` FAIL(`Expecting actual not to be null` — NPE가 REJECTED_BEFORE_SEND로 바뀜)→PASS. catch를 `IllegalArgumentException`으로 좁힘 `MSG/platformbridge/PlatformIntegrationEventPublishAdapter.java:62`; 나머지 예외는 전파되어 relay가 실제 원인 타입으로 재시도·보고. 수정 방향 중 "cause를 거부 결과에 싣기"는 하지 않음: 포트가 `OutboxPublishOutcome` enum만 돌려줘 원인을 실을 자리가 없고, 실으려면 application-core 포트·relay 변경(계층 밖)이 필요. 로그로 남기는 것도 예외 메시지를 운영 로그에 쓰지 않는 규칙(`Slf4jOutboxRelayFailureReportAdapter`)과 충돌 | - | catch를 `IllegalArgumentException`으로 좁히고 cause를 `OutboxRelayFailureReport`(또는 거부 예외)로 전달 |
|
||||
| H-9 | Consider | Kafka seam이 `InterruptedException`을 삼켜 종료 중에도 relay가 항목당 최대 30s 계속 처리 | 완료 | Wave 1–2 P11 (fcddab7e·Wave 2 커밋): `KafkaSenderInterruptionTest.anInterruptedAcknowledgementWaitRethrowsWithTheInterruptFlagRestored` FAIL(`[InterruptedException, false]`)→PASS, `OutboundMessagePublisherTest.anInterruptedSendIsSwallowedWithTheInterruptFlagKept`·`OutboxMessagePublishAdapterTest$FailClosedPath.anInterruptedSendKeepsTheRelayThreadInterrupted` FAIL(`Expecting value to be true but was false`)→PASS. `src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSenderAutoConfiguration.java:115`, `MSG/core/OutboundMessagePublisher.java:41`, `MSG/outbox/OutboxMessagePublishAdapter.java:100`(삼키는 지점 두 곳 모두 복원) | - | `kafkaSender` 람다에서 `InterruptedException`을 잡아 `Thread.currentThread().interrupt()` 후 재던지기, `OutboundMessagePublisher`는 interrupt 상태를 보존 |
|
||||
@@ -802,7 +802,7 @@ Wave 1–2 구현 중 나온 질문에 대해 받은 7건(2026-09-28):
|
||||
| S2-#2a | Required | Mongo: 바인딩 안 되는 `advanced.*.enabled`, 구현 없는 인터페이스 10개, reactive·change stream | 해당 없음(코드 삭제) | 「제거된 코드」 Mongo advanced 바인딩·search/vector·time series·GridFS·`MongoDataKeyResolver` 등·reactive·change stream 행. 인터페이스 9개 grep 0, `MongoTenantMigrationCheckpointStore`는 구현 생김(`MongoTenantMigrationCoordinator.java:96`) | - | - |
|
||||
| S2-#2b | Required | persistence-mongo 약 23k줄 플랫폼에 소비자 없음 | 완료 | 소유자 결정(계획 Wave 3 "분류 2는 완성해서 포장")으로 라이브러리 유지: `adapter/outbound/persistence-mongo/README.md:135` 라이브러리 API 표, 한 줄 조립 주석 `app-bootstrap/build.gradle:146`. main 23.2k→18.6k줄 | - | - |
|
||||
| S2-#3a | Required | 두 번째 트랜잭션·재시도 엔진, 거짓 Javadoc | 해당 없음(코드 삭제) | 「제거된 코드」 "JPA 두 번째 트랜잭션·재시도 엔진 19종", `JpaTransactionAutoConfiguration`, retry 계열 행. `persistence/transaction/`에 `SpringTransactionPort` 하나, CLAUDE.md:91-92가 "retries nothing"으로 갱신 | - | - |
|
||||
| S2-#3b | Required | SQLSTATE 표 두 벌 | 남음 | `failure/StandardSqlStateErrorMapping.java:17`·`postgresql/PostgreSqlSqlStateErrorMapping.java:15` vs `postgresql/error/PostgreSqlState.java:18,24`(`PostgreSqlFailureClassifier`·lock translator가 사용). 40001이 두 곳 | W3 | vendor당 SQLSTATE enum 하나(`PostgreSqlState`)로 두고 `SqlStateErrorMapping`이 그 enum을 참조 |
|
||||
| S2-#3b | Required | SQLSTATE 표 두 벌 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): SQL 표준 코드 5개를 `StandardSqlStateErrorMapping` 상수로 한 번 정의(`persistence-jpa/.../failure/StandardSqlStateErrorMapping.java:20-33`). `PostgreSqlState`의 표준 멤버가 그 상수를 참조(`postgresql/error/PostgreSqlState.java:24-42`)하고, `PostgreSqlSqlStateErrorMapping`은 코드를 `PostgreSqlState.*.code()`에서 읽음(`postgresql/PostgreSqlSqlStateErrorMapping.java:17-23`). 방향 조정: 계획은 "`SqlStateErrorMapping`이 `PostgreSqlState`를 참조"였으나 vendor-neutral `failure` 패키지는 `postgresql`을 참조할 수 없음(ArchUnit `PERSISTENCE_RDBMS_STAYS_VENDOR_NEUTRAL`)이라 표준 코드는 neutral 쪽에 두고 vendor enum이 그쪽을 참조. 새 테스트 `PostgreSqlSqlStateErrorMappingTest.everyCodeAPostgreSqlDeploymentMapsIsAStateOfTheOnePostgreSqlTable`(리팩터, 기존 코드에서도 PASS). 공개 타입 변경 없음(상수 추가만), `verifyJpaApiSurface` 통과 | - | vendor당 SQLSTATE enum 하나(`PostgreSqlState`)로 두고 `SqlStateErrorMapping`이 그 enum을 참조 |
|
||||
| S2-#4a | Required | JPA outbox V2·inbox·멱등성 v1 공존 | 해당 없음(코드 삭제) | 「제거된 코드」 JPA outbox V2 adapter·migration stream·통합 테스트, same-store inbox, JPA v1 멱등성 store 행 | - | - |
|
||||
| S2-#5 | Required | Mongo reactive 쌍둥이 스택 (= F-3, F-7) | 해당 없음(코드 삭제) | 「제거된 코드」 Mongo reactive 경로·change stream 행. `mongo/reactive`·`changestream` 디렉터리 없음, main의 reactor 참조 0 | - | - |
|
||||
| S2-#6a | Required | owner-lease claim 절차·`digestFields` 복사(inbox·polling) | 해당 없음(코드 삭제) | `PostgreSqlSameStoreInboxAdapter`·`PostgreSqlPollingDeliveryAdapter`·`PostgreSqlImmutableOutboxAppendAdapter` 삭제(「제거된 코드」 same-store inbox, JPA outbox V2 adapter 행). claim 절차는 멱등성 store에만 남음 | - | - |
|
||||
@@ -828,18 +828,18 @@ Wave 1–2 구현 중 나온 질문에 대해 받은 7건(2026-09-28):
|
||||
| S2-lead-6 | 권고 | JPA 조립이 leaf와 bootstrap에 나뉨 | 완료 | 「제거된 코드」 `JpaPlatformAutoConfiguration`·`JpaPlatformRuntimeAutoConfiguration` 행, 조립은 `persistence-jpa/src/main/resources/META-INF/spring/...AutoConfiguration.imports`(3개)에만, `app-bootstrap/.../autoconfigure/`에 jpa 없음 | - | - |
|
||||
| S3-#1 | Required | httpclient blocking/reactive 병렬 스택이 이미 갈라짐 (= H-5, H-7) | 완료 | Wave 1–2 P11 (fcddab7e·Wave 2 커밋): D 커밋 `06764fcb`에서 reactive 스택(WebClient·Reactor Netty)과 webflux·reactor·reactor-netty·reactor-test·blockhound 의존 삭제. blocking(RestClient) 경로 하나만 남음. `clients[N].api` 설정 키·`ClientApiType`·`TransportType.REACTOR_NETTY` 삭제, env-fields.yaml 행 삭제, lockfile 재생성(httpclient·app-bootstrap). Jetty HTTP/3 실험 transport는 reactive SPI에 묶여 있어 blocking SPI(`JettyClientHttpRequestFactory`)로 옮김(자동 조립 안 됨은 그대로) `HC/http3/JettyHttp3TransportProvider.java:49` | - | 결정(2026-09-25): D4를 outbound에도 적용 — httpclient reactive(WebClient·Reactor Netty) 스택과 webflux·reactor 의존 삭제 |
|
||||
| S3-#2a | Required | reactive streaming 요청이 admission·deadline·credential 없이 나감 | 해당 없음(코드 삭제) | Wave 1–2 P11 (fcddab7e·Wave 2 커밋): D `06764fcb`에서 `webclient/ReactiveStreamingGateway` 삭제. blocking 스트리밍은 deadline·credential·admission 적용 `HC/restclient/BlockingStreamingGateway.java:69,82,106` | - | S3-#1에서 reactive를 지우면 함께 삭제, 유지하면 blocking과 같은 credential·admission·deadline 단계 적용 + 동작 테스트 |
|
||||
| S3-#2b | Required | 진입점 6개가 호출 파이프라인을 각자 조립 | 남음 | `CallSetup` 등 공통 조립 없음(grep 0), `DefaultDynamicTargetGateway`·`DefaultReactiveSseGateway`·`BlockingStreamingGateway`·`ReactiveStreamingGateway`가 각자 조립 | W3 | `CallSetup.prepare(lease, operation)`이 metadata/prepared/deadline/admission/credentials 반환, 진입점은 전송만 다르게 |
|
||||
| S3-#2b | Required | 진입점 6개가 호출 파이프라인을 각자 조립 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): `CallSetup.prepare(lease, operation)`이 blocking runtime·metadata·target policy·deadline(+guard)을 준비하고 `admit()`·`credentials()`·`credentialRequest()` 제공(`HC/restclient/CallSetup.java:49,79`). generic(`DefaultGenericHttpGateway.java:69`)과 streaming(`BlockingStreamingGateway.java:50`) 진입점이 사용. Dynamic Target은 target 준비(SSRF 핀)가 달라 `CallSetup.guardedDeadline`과 admission permit만 공유(`dynamic/DefaultDynamicTargetGateway.java:104`) — 이 과정에서 P26-new-1 발견·수정. reactive 진입점 3개는 결정 9로 이미 삭제. service(H1)는 generic gateway를 경유 | - | `CallSetup.prepare(lease, operation)`이 metadata/prepared/deadline/admission/credentials 반환, 진입점은 전송만 다르게 |
|
||||
| S3-#3a | Required | 118개 메서드 `RedisCommandGateway`, runtime이 SDK 개념에 역의존 (= G-7) | 남음 | `redis-runtime/.../lettuce/operations/RedisCommandGateway.java`(1,227줄, 메서드 118), `:1107-1134` `sendApprovedRaw/sendAdminDiagnostic/sendExtension`, `lettuce/connection/RedisConnectionKind.java:25-33` BLOCKING·TRANSACTION·PUBSUB lane, `:64` `forCommand(RedisCommandDescriptor)` | W3 | runtime 계약은 semantic adapter가 쓰는 8개(`SemanticRedisCommands`)로, 나머지는 redis-sdk 확장 인터페이스로 이동(redis-sdk 유지 결정 반영), lane은 REGULAR·SCRIPT만 |
|
||||
| S3-#3b | Required | runtime이 `Sdk` 이름·`...redis.sdk` 패키지를 쓰고 redis-sdk와 split package | 남음 | `redis-runtime/.../sdk/config/RedisSdkSettings.java`(670줄), `RedisSdkAutoConfiguration.java`, redis-runtime·redis-sdk 공유 패키지 9개 | W3 | `RedisRuntimeSettings`로 개명, runtime 패키지를 `...redis.runtime.*`로, SDK 전용 설정 섹션은 redis-sdk로 |
|
||||
| S3-#4a | Required | cache-redis에서 "안 보냄/보냈는지 모름" 구분을 rate-limit만 함 | 완료 | Wave 1–2 P6 (fcddab7e·Wave 2 커밋): 멱등성·lease는 NEW-5c 수정. cache는 현황표 근거("lane 거절도 Indeterminate")가 사실과 다름: cache는 이미 lane 거절을 `DEGRADED_UNAVAILABLE`(=안 보냄)로 돌려준다. 빠진 쪽은 반대 방향이었다 — 보낸 뒤 응답을 잃은 쓰기도 `DEGRADED_UNAVAILABLE`였다. `RedisCacheRegionAdapter.java:241,294,314,328`에 `sent` 플래그를 두어 쓰기 명령을 보낸 뒤의 실패는 `INDETERMINATE`, 그 전(lane 거절·연결·generation 조회)은 `DEGRADED_UNAVAILABLE`. 테스트 `RedisCacheRegionAdapterTest.aWriteWhoseReplyWasLostIsIndeterminate`/`anInvalidationWhoseReplyWasLostIsIndeterminate`/`aRegionInvalidationWhoseReplyWasLostIsIndeterminate` FAIL(`expected: INDETERMINATE but was: DEGRADED_UNAVAILABLE`)→PASS, 가드 `aWriteThatFailedBeforeItsSetWasSentDegrades` PASS | - | 멱등성·lease·cache의 실패 분류에 `metadata().ambiguousExecution()`로 NOT_SENT/AMBIGUOUS 구분 추가 |
|
||||
| S3-#4b | Required | "lease 빌림 → `.get(timeout)` → 예외 처리" 틀 복사, Lua 응답 디코더 3벌 | 남음 | `catch (InterruptedException` 16곳(멱등성 6·lease 4·cache 4·rate-limit 1·probe 1), 디코더 `idempotency/IdempotencyScripts.java:273`, `lease/LeaseScripts.java:162`, `ratelimit/RateLimitScripts.java:280` | W3 | `SemanticRedisCall.run(...)` 공통 틀 + 응답 디코딩을 등록 스크립트 쪽 한 곳으로 |
|
||||
| S3-#5 | Consider | `RedisIdempotencyStoreAdapter.transition` 인자 14~15개, 상태 문자열 switch 반복 | 남음 | `cache-redis/.../idempotency/RedisIdempotencyStoreAdapter.java:164-180`(`transition` 호출 14개 인자), `:137-157` 등 문자열 switch | W3 | `IdempotencyScripts.Reply`에서 `enum ScriptStatus`로 한 번 파싱, 호출부는 `Map<ScriptStatus,O>` |
|
||||
| S3-#6 | Consider | 대체 불가능한 확장 지점(`HttpClientTagPolicy` bean) | 남음 | `httpclient/.../autoconfigure/HttpClientObservationAutoConfiguration.java:23-27` bean 소비처 0, `restclient/BlockingExecutionSupport.java:77`이 `HttpClientTagPolicy.standard()`를 다시 생성, `observation/HttpClientTagPolicy.java:32` private 생성자라 override 자체 불가 | W3 | bean 삭제, `BlockingExecutionSupport`는 `ExecutionSupport`로 개명 |
|
||||
| S3-#7 | Consider | 구현 1개짜리 인터페이스 4개 | 남음 | `httpclient/.../resilience/RetryCoordinator`(구현 `BlockingRetryCoordinator`), `RetryEligibilityEngine`/`Default…`, `ExecutionEvidenceClassifier`/`Default…`, `BackoffStrategy`/`ExponentialFullJitterBackoff` | W3 | 인터페이스 삭제, 구현체를 인터페이스 이름으로 개명 |
|
||||
| S3-#6 | Consider | 대체 불가능한 확장 지점(`HttpClientTagPolicy` bean) | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): `HttpClientObservationAutoConfiguration`의 `HttpClientTagPolicy` bean 삭제(소비처 0, private 생성자라 override 불가). `BlockingExecutionSupport` → `ExecutionSupport` 개명(`HC/restclient/ExecutionSupport.java`, bean `httpClientExecutionSupport` `HttpClientObservationAutoConfiguration.java:24`). 커밋 `93251e76` | - | bean 삭제, `BlockingExecutionSupport`는 `ExecutionSupport`로 개명 |
|
||||
| S3-#7 | Consider | 구현 1개짜리 인터페이스 4개 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): 삭제: `RetryCoordinator` 인터페이스(구현 `BlockingRetryCoordinator`를 `RetryCoordinator`로 개명, `HC/resilience/RetryCoordinator.java:20`, 테스트 `RetryCoordinatorTest`), `ExecutionEvidenceClassifier` 인터페이스(`DefaultExecutionEvidenceClassifier`를 그 이름으로, `HC/resilience/ExecutionEvidenceClassifier.java:12`). 유지(근거): `RetryEligibilityEngine` — `DefaultGenericHttpGatewayTest:287,311`이 lambda fake를 넣고 `TestGateways.forProfile(.., RetryEligibilityEngine)`이 교체 지점; `BackoffStrategy` — `RetryCoordinatorTest.ambiguousOutcomeIsRaisedRatherThanRetried`·`exhaustedBudgetStopsRetryingImmediately`가 `(a, r, d) -> Duration.ZERO` fake를 씀(삭제 시도 시 컴파일 실패로 확인) | - | 인터페이스 삭제, 구현체를 인터페이스 이름으로 개명 |
|
||||
| S3-#8a | Consider | `BoundedErrorBody`·`spring7/*`·`migration/*` 도달 불가 | 해당 없음(코드 삭제) | 「제거된 코드」 httpclient `BoundedErrorBody`, Spring 7 service group·`RestTemplate` 이행 패키지 행 | - | - |
|
||||
| S3-#8b | Consider | `MultipartReplayability`·`SafeHttpLogEvent`는 테스트만 참조 | 남음 | `httpclient/.../webclient/MultipartReplayability.java`(참조 `FirstByteRetryBoundaryTest`뿐), `observation/SafeHttpLogEvent.java`(참조 `HttpClientTagPolicyTest`뿐) | W3 | 두 클래스와 전용 테스트 삭제(http3는 유지) |
|
||||
| S3-#8b | Consider | `MultipartReplayability`·`SafeHttpLogEvent`는 테스트만 참조 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): `SafeHttpLogEvent`와 전용 테스트 메서드 `HttpClientTagPolicyTest.safeLogEventCarriesNoSecretOrExpandedUrl` 삭제. `MultipartReplayability`는 결정 9 reactive 삭제(`6d27356e` 이전 커밋)로 이미 없음. http3 유지 | - | 두 클래스와 전용 테스트 삭제(http3는 유지) |
|
||||
| S3-#9 | Consider | `RedisTopologyClientFactory` 662줄 역할 과다 | 남음 | `redis-runtime/.../lettuce/connection/RedisTopologyClientFactory.java` 662줄(변화 없음) | W3 | `RuntimeClient` 구현 3개·`SharedClientResources`를 package-private top-level 클래스로 이동 |
|
||||
| S3-#10 | Consider | settings → profile 필드 단위 복사, `valueOf(toUpperCase())` 반복 | 남음 | `httpclient/.../autoconfigure/HttpClientProfileFactory.java` 153줄, `toUpperCase` 8회 | W3 | settings 필드를 enum 타입으로 선언(binder가 대소문자 변환), 복사 구조는 유지 |
|
||||
| S3-#10 | Consider | settings → profile 필드 단위 복사, `valueOf(toUpperCase())` 반복 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): `HttpClientPlatformSettings`의 enum 필드 7개(`mode`·`transport`·`protocols`·`authentication.type`·`retry.jitter`·`retry.retryAfter`·`proxy.type`)를 enum 타입으로 선언(`HC/autoconfigure/HttpClientPlatformSettings.java:127,131,134,212,225,226,255`), binder가 대소문자 변환. `HttpClientProfileFactory`의 `valueOf(toUpperCase())` 7곳 삭제, 복사 구조 유지. 동작 보존 리팩터라 새 FAIL 테스트 없음 — 기존 `HttpClientPlatformEnvManifestTest`·`UnsafeStartupConfigurationTest`(`SIMPLE`·`HTTP_3`)·`HttpClientPlatformActivationTest.detailSettingsAreNotBoundWhileTheCapabilityIsOff`(`NOT_A_TRANSPORT`) 통과. prefix·strict 바인딩(3-B, S3-lead-2)은 건드리지 않음 | - | settings 필드를 enum 타입으로 선언(binder가 대소문자 변환), 복사 구조는 유지 |
|
||||
| S3-#11 | Nit | 이력 서술 주석·inline FQN | 남음 | 재측정 "used to/no longer": httpclient 27·redis-runtime 6·redis-sdk 9·cache-redis 7줄, `cache-redis/.../capability/RedisCapabilityConfig.java:30-32` "376 lines … (BOOT-007)", httpclient inline FQN 약 91줄 | W5 | 불변 조건만 남기고 이력은 git/ADR로, FQN은 import로(`HttpMethod`/`HttpStatus` 충돌만 예외) |
|
||||
| S3-#12a | Nit | `CacheKeys`가 가변 generation 상태 보유, `KeyDigest`가 설정 패키지에 | 남음 | `cache-redis/.../cache/RedisCacheRegionAdapter.java:375,430`(`CacheKeys.observeGeneration`), `capability/RedisKeys.java:37` `KeyDigest` | W5 | `RegionGeneration` 분리, `KeyDigest`를 keyspace 패키지로 옮기고 `RedisNamespace.prefix()` 사용 |
|
||||
| S3-#12b | Nit | cache-redis CLAUDE.md의 "legacy cache router"는 존재하지 않음 | 남음 | `adapter/outbound/cache-redis/CLAUDE.md:22` | W5 | 해당 줄 삭제 |
|
||||
@@ -850,7 +850,7 @@ Wave 1–2 구현 중 나온 질문에 대해 받은 7건(2026-09-28):
|
||||
| S3-lead-2 | 권고 | `HttpClientEnvironmentKeys`(리플렉션 env 이름 역산) vs `StrictSettingsBinder` (= X2 P1-3) | 남음 | `httpclient/.../autoconfigure/HttpClientEnvironmentKeys.java`(179줄, `RecordComponent` 순회), `HttpClientPlatformSettingsBinder.java:27`만 사용. 다른 capability는 env 오타 검사 없음 | W3 | env 이름 역산 검사를 support `StrictSettingsBinder` 옵션으로 옮겨 모든 capability가 같은 방식으로 오타 env를 거부 |
|
||||
| S3-lead-3 | 권고 | TLS material 로딩이 Redis와 httpclient에 따로 | 완료 | 문제 아님: Redis는 Lettuce `SslOptions`에 PEM 위치만 넘김(`RedisTopologyClientFactory.java:327-362`), httpclient는 JSSE `KeyStore`·`TrustManagerFactory` 구성(`security/TlsMaterialProvider.java`). 클라이언트 API가 달라 공유할 코드가 없고 redis-runtime은 의존 edge 0 | - | - |
|
||||
| S3-lead-4 | 권고 | `ca-skeleton.capabilities.*` selector 문자열이 여러 leaf에 흩어짐 | 남음 | main 13파일(sample, app-bootstrap 3, web 1, persistence-jpa 3, redis-runtime `RedisCorrectnessRoles.java`, cache-redis 4), `...idempotency.provider` 30회 | W3 | 역할별 selector 키를 한 곳(멱등성은 S1-lead-3의 composition 모듈, Redis는 `RedisCorrectnessRoles`)에 상수로 두고 나머지는 그 상수/조건 클래스를 사용 |
|
||||
| S3-lead-5 | 권고 | `secret://<source>/<name>` 파싱이 다른 leaf에도 | 남음 | 4곳: `httpclient/.../HttpClientAuthenticationAutoConfiguration.java:61-64`, `cache-redis/.../capability/RedisKeys.java:82-88`, `redis-runtime/.../RedisCredentialResolver.java:24`, `persistence-mongo/.../security/MongoCredentialReference.java:22` | W3 | application-core `SecretSourcePort` 옆에 `SecretReference.parse` 하나, httpclient·cache-redis가 사용(mongo·redis-runtime은 edge 없어 유지) |
|
||||
| S3-lead-5 | 권고 | `secret://<source>/<name>` 파싱이 다른 leaf에도 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): `application-core` `SecretReference`(record source/name, `parse`·`isReference`, `application-core/.../outbound/SecretReference.java:47`)를 `SecretSourcePort` 옆에 추가. httpclient(`HttpClientAuthenticationAutoConfiguration.java:60-64`)와 cache-redis(`RedisKeys.java:83`)가 사용 — 둘 다 기존 edge(application-core) 안, registry 변경 없음. mongo·redis-runtime은 지시대로 유지. 테스트 `SecretReferenceTest` 6개(새 타입이라 FAIL은 컴파일 실패). cache-redis는 이름이 빈 `secret://src/`를 빈 키로 port에 넘기던 것이 이제 거부됨(`referenceWhoseNameIsBlankIsRejected`) | - | application-core `SecretSourcePort` 옆에 `SecretReference.parse` 하나, httpclient·cache-redis가 사용(mongo·redis-runtime은 edge 없어 유지) |
|
||||
|
||||
**조사 메모**
|
||||
|
||||
@@ -958,8 +958,8 @@ Wave 1–2 구현 중 나온 질문에 대해 받은 7건(2026-09-28):
|
||||
| S6-#2d | Required | `capabilities.idempotency.provider` 기본값이 `disabled`/`jdbc`로 갈림 | 완료 | 모두 `disabled`: `BS/runtime/SecretSourceValidator.java:151`, `BS/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java:34`, `SP/bootstrap/idempotency/SampleIdempotencyConfig.java:34`; `jdbc` 값 main 0건, `6d27356e` | - | - |
|
||||
| S6-#3a | Required | startup validator가 3 lifecycle·여러 패키지에 흩어짐, `StartupRule` 목록 없음 | 남음 | 19 → 16개: bootstrap 7(`BS/runtime/*Validator` 5, `OutboxCanonicalTransportRequirementValidator`, `TracingSamplingEnvironmentPostProcessor`), persistence-jpa 8(`JS/*Validator` 7, `JpaActivationEnvironmentPostProcessor`), cache-redis 1(`RedisReadinessGroupPostProcessor`). EPP 4, `InitializingBean` 1, `SmartInitializingSingleton` 11. `StartupRule` 타입 없음 | W3 | 모듈마다 `StartupRule { List<String> violations(Environment) }` 목록 + runner 1개; bean이 필요한 검사만 bean으로 |
|
||||
| S6-#3b | Required | OSIV 검사 2벌, 뒤 검사의 local 예외는 죽은 코드 | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): 행동 보존 정리(FAIL→PASS 대상 아님): `OpenInViewSafetyValidator`(모든 profile 거부)를 정본으로 두고 `JpaDangerousConfigurationGuard`의 OSIV 분기·`OPEN_IN_VIEW_KEY` 삭제(`.../startup/JpaDangerousConfigurationGuard.java`), `JpaPlatformReport`는 validator 상수 사용. `OpenInViewSafetyValidatorTest.openInViewTrueFailsStartupUnderALocalConvenienceProfileToo` 추가(수정 전후 모두 PASS = guard의 local 예외가 죽은 코드였다는 증거). guard 테스트는 ddl-auto만 검사하도록 재작성. 학습 문서 `docs/study/postgresql-jpa-walkthrough.ko.md` 표 갱신 | - | 하나로: local 예외를 정책으로 쓸지 정해 `OpenInViewSafetyValidator`를 삭제하거나 guard의 OSIV 분기를 삭제 |
|
||||
| S6-#3c | Required | ddl-auto 검사 2벌 | 남음 | `JS/JpaSchemaSafetyValidator.java:28-50`(prod) vs `JS/JpaDangerousConfigurationGuard.java:62-65`(non-local, prod 포함) | W3 | guard 한 곳으로 합치고 `JpaSchemaSafetyValidator` 삭제 |
|
||||
| S6-#3d | Required | `isProdActive()` 5곳 복사 | 남음 | `JS/FlywayProdSafetyValidator.java:57`, `JS/JpaSchemaSafetyValidator.java:51`, `JS/PersistenceVendorProdSafetyValidator.java:81`, `JS/PostgreSqlTransportSecurityValidator.java:86`, `BS/runtime/SecretSourceValidator.java:175`. 본문은 모두 `RuntimeProfileSnapshot.isProduction()` 1줄 위임 | W3 | 1줄 wrapper 삭제하고 호출부에서 직접 호출(S6-#3a와 함께) |
|
||||
| S6-#3c | Required | ddl-auto 검사 2벌 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): `JpaSchemaSafetyValidator`(+테스트) 삭제, `JpaDangerousConfigurationGuard`가 유일한 ddl-auto 검사. 기존 validator 테스트의 성질(prod 거부·blank 거부·대소문자·local 허용·`APP_DATASOURCE_DDL_AUTO` 명시·`PROFILE_MISMATCH`)을 guard 테스트로 옮김. `JpaDangerousConfigurationGuardTest.productionRefusesASchemaMutatingDdlAutoAsAProfileMismatchNamingTheEnvironmentKey` 등 10건 FAIL(guard가 `IllegalStateException`을 던짐)→PASS. `persistence-jpa/.../startup/JpaDangerousConfigurationGuard.java:46-66`. README 3곳 갱신 | - | guard 한 곳으로 합치고 `JpaSchemaSafetyValidator` 삭제 |
|
||||
| S6-#3d | Required | `isProdActive()` 5곳 복사 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): 1줄 wrapper 삭제, 호출부에서 `RuntimeProfileSnapshot.from(environment).isProduction()` 직접 호출: `FlywayProdSafetyValidator`, `PersistenceVendorProdSafetyValidator`, `PostgreSqlTransportSecurityValidator`, `bootstrap/runtime/SecretSourceValidator`. `JpaSchemaSafetyValidator` 몫은 S6-#3c 삭제로 해소. `shared-contract` `RuntimeEnvironment.isProductionActive` 문서의 "isProdActive() copies" 언급은 역사 설명이라 유지. 동작 동일, 기존 테스트 통과 | - | 1줄 wrapper 삭제하고 호출부에서 직접 호출(S6-#3a와 함께) |
|
||||
| S6-#3e | Required | vocabulary 패키지 `runtime/startup/`에 guard 3개 | 완료 | bootstrap `BS/runtime/startup/`에는 `StartupFailureExceptionReporter`만. 어휘는 `SST/`, Flyway·RequiredEnvironment 검사는 `JS/`로 이동, `6d27356e` | - | - |
|
||||
| S6-#3f | Required | CDV가 EPP와 `CapabilityDependencyStartupCheck`에서 두 번 실행 | 해당 없음(코드 삭제) | `CS:249` | - | - |
|
||||
| S6-#4 | Required | root가 넓게 scan한 뒤 다른 leaf 패키지를 regex로 제외 | 완료 | `BS/CaSkeletonApplication.java` 전체가 `@SpringBootApplication` + bootstrap 패키지 5개 `@ConfigurationPropertiesScan`. regex 삭제(`CS:250`), web은 자기 imports로 공개(`src/adapter/inbound/web/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports:1`), `6d27356e` | - | - |
|
||||
@@ -1175,3 +1175,6 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검
|
||||
| P15-new-2 | 발견 | GraphQL body-limit 필터가 mapper를 거치지 않고 하드코딩 JSON(`REQUEST_ERROR`)을 썼다. | 완료 | Wave 3 P15: `PAYLOAD_TOO_LARGE` + 공용 문구 + `retryable:false` | - | - |
|
||||
| P15-new-3 | 발견 | `OperationalError.INTERNAL_ERROR`가 레지스트리에서 `retryable: true` — SCHEMA_MISMATCH·DATA_CORRUPTION 같은 결정적 내부 실패도 재시도를 권한다. | 남음 | Wave 3 P15 결과 파일 | W3 | 결정 필요: `INTERNAL_ERROR`를 non-retryable로 바꾸거나 결정적 실패에 별도 코드 |
|
||||
| P15-new-4 | 발견 | gRPC status description이 코드 문자열에서 한국어 공용 문구로 바뀜(결정 11) — description을 코드로 파싱하던 클라이언트는 `error-code` trailer를 봐야 한다. | 남음 | Wave 3 P15 결과 파일 | W5 | 이행 안내를 gRPC adapter README·에러 계약 문서에 |
|
||||
| P26-new-1 | 발견 | Dynamic Target 호출이 deadline 검사와 admission permit을 거치지 않았다(만료 deadline에도 hop 전송). | 완료 | Wave 3 P26: `CallSetup` 공유, 재현 테스트 FAIL→PASS | - | - |
|
||||
| P26-new-2 | 발견 | prod의 schema 변경 `ddl-auto` 거부가 문서의 `PROFILE_MISMATCH`가 아니라 `IllegalStateException`이었다. | 완료 | Wave 3 P26: 검사 하나로 합치며 수정 | - | - |
|
||||
| P26-new-3 | 발견 | cache-redis가 `secret://src/`(빈 이름)를 `SecretSourcePort.resolve("")`로 넘겼다. | 완료 | Wave 3 P26: `SecretReference.parse`가 거부 | - | - |
|
||||
|
||||
+1
-1
@@ -547,7 +547,7 @@ docker compose -f docker-compose.yml -f docker-compose.local.yml up -d --wait db
|
||||
- **`APP_DATASOURCE_USERNAME`** / **`APP_DATASOURCE_PASSWORD`** — DB 접속 계정.
|
||||
- **`APP_DATASOURCE_DRIVER`** — Hibernate dialect 에 맞는 드라이버(예: `org.postgresql.Driver`).
|
||||
- **`APP_DATASOURCE_DDL_AUTO`** — `none` | `validate` | `update` | `create` | `create-drop`. **prod
|
||||
는 `validate` 또는 `none`**(`JpaSchemaSafetyValidator` 가 기동 시 강제). `local` 은 이 값을 쓰지
|
||||
는 `validate` 또는 `none`**(`JpaDangerousConfigurationGuard` 가 기동 시 강제). `local` 은 이 값을 쓰지
|
||||
않습니다 — `application-local.yml` 이 `create-drop` 으로 고정합니다.
|
||||
- **`APP_DATASOURCE_SHOW_SQL`** — `true` 면 SQL 을 로그로 echo.
|
||||
- **`APP_DATASOURCE_FORMAT_SQL`** — SQL pretty-print(`SHOW_SQL=true` 일 때만 의미 있음).
|
||||
|
||||
+4
-3
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings;
|
||||
import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException;
|
||||
import dev.caskeleton.application.outbound.SecretReference;
|
||||
import dev.caskeleton.application.outbound.SecretSourcePort;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
@@ -78,8 +79,9 @@ final class RedisKeys {
|
||||
throw new CapabilityStartupValidationException(
|
||||
"the Redis " + capability + " capability needs a key-digest secret reference");
|
||||
}
|
||||
int separator = reference.lastIndexOf('/');
|
||||
if (!reference.startsWith("secret://") || separator < 0) {
|
||||
try {
|
||||
return SecretReference.parse(reference).name();
|
||||
} catch (IllegalArgumentException malformed) {
|
||||
throw new CapabilityStartupValidationException(
|
||||
"the Redis "
|
||||
+ capability
|
||||
@@ -87,7 +89,6 @@ final class RedisKeys {
|
||||
+ reference
|
||||
+ "' must be secret://<source>/<name>");
|
||||
}
|
||||
return reference.substring(separator + 1);
|
||||
}
|
||||
|
||||
String of(String key) {
|
||||
|
||||
+7
@@ -1,5 +1,7 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/**
|
||||
* A non-idempotent request was sent but no response arrived: the remote outcome is unknown (design
|
||||
* §33).
|
||||
@@ -8,6 +10,11 @@ public final class HttpAmbiguousExecutionException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.UNKNOWN;
|
||||
}
|
||||
|
||||
public HttpAmbiguousExecutionException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** Credential materialization or token refresh failed before the request could be authorized. */
|
||||
public final class HttpAuthenticationException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.AUTHENTICATION;
|
||||
}
|
||||
|
||||
public HttpAuthenticationException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** The attempt bulkhead had no permit available for this physical attempt. */
|
||||
public final class HttpBulkheadRejectedException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.BULKHEAD_REJECTED;
|
||||
}
|
||||
|
||||
public HttpBulkheadRejectedException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** The upstream circuit breaker is open; no rate or bulkhead permit was consumed. */
|
||||
public final class HttpCircuitOpenException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.CIRCUIT_OPEN;
|
||||
}
|
||||
|
||||
public HttpCircuitOpenException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+12
@@ -1,5 +1,6 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
@@ -26,4 +27,15 @@ public abstract class HttpClientException extends RuntimeException {
|
||||
public final HttpFailureMetadata metadata() {
|
||||
return metadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* The stable failure category this exception stands for.
|
||||
*
|
||||
* <p>Each subtype names its own. The executor used to recover it with a switch over {@code
|
||||
* getClass().getSimpleName()}, so renaming an exception silently turned its category into {@code
|
||||
* UNKNOWN} — and with it the retry decision.
|
||||
*
|
||||
* @return the category retry eligibility and observation branch on
|
||||
*/
|
||||
public abstract FailureCategory category();
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** Profile, operation, or capability configuration is invalid (design §19). Never retried. */
|
||||
public final class HttpConfigurationException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.CONFIGURATION;
|
||||
}
|
||||
|
||||
public HttpConfigurationException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** Socket connect failed; the request was never sent. */
|
||||
public final class HttpConnectException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.CONNECT;
|
||||
}
|
||||
|
||||
public HttpConnectException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** The effective deadline for the whole logical call was reached. */
|
||||
public final class HttpDeadlineExceededException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.DEADLINE_EXCEEDED;
|
||||
}
|
||||
|
||||
public HttpDeadlineExceededException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** Hostname resolution failed or timed out; the request was never sent. */
|
||||
public final class HttpDnsException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.DNS;
|
||||
}
|
||||
|
||||
public HttpDnsException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** Connection or HTTP/2 stream could not be acquired within the pending-acquire budget. */
|
||||
public final class HttpPoolAcquireTimeoutException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.POOL_ACQUIRE_TIMEOUT;
|
||||
}
|
||||
|
||||
public HttpPoolAcquireTimeoutException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,5 +1,7 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/**
|
||||
* Proxy connect, CONNECT tunnel, or proxy authentication failed, distinctly from target failures.
|
||||
*/
|
||||
@@ -7,6 +9,11 @@ public final class HttpProxyException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.PROXY;
|
||||
}
|
||||
|
||||
public HttpProxyException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** The local attempt rate limiter rejected this physical attempt. */
|
||||
public final class HttpRateLimitRejectedException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.RATE_LIMIT_REJECTED;
|
||||
}
|
||||
|
||||
public HttpRateLimitRejectedException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** A redirect hop violated hop count, origin, method, or body replay policy. */
|
||||
public final class HttpRedirectRejectedException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.REDIRECT_REJECTED;
|
||||
}
|
||||
|
||||
public HttpRedirectRejectedException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+6
@@ -1,6 +1,7 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.HttpStatus;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/**
|
||||
* Non-success HTTP status returned by the upstream (design §19).
|
||||
@@ -12,6 +13,11 @@ public class HttpRemoteErrorException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.REMOTE_STATUS;
|
||||
}
|
||||
|
||||
public HttpRemoteErrorException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** Request headers or body could not be fully written; execution evidence is conservative. */
|
||||
public final class HttpRequestWriteException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.REQUEST_WRITE;
|
||||
}
|
||||
|
||||
public HttpRequestWriteException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** Final response headers or a body chunk did not arrive inside the configured stage timeout. */
|
||||
public final class HttpResponseTimeoutException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.RESPONSE_TIMEOUT;
|
||||
}
|
||||
|
||||
public HttpResponseTimeoutException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** Wire or decoded response bytes exceeded the profile hard limit; the connection was reclaimed. */
|
||||
public final class HttpResponseTooLargeException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.RESPONSE_TOO_LARGE;
|
||||
}
|
||||
|
||||
public HttpResponseTooLargeException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** The response ended before the declared or expected body was complete. */
|
||||
public final class HttpResponseTruncatedException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.RESPONSE_TRUNCATED;
|
||||
}
|
||||
|
||||
public HttpResponseTruncatedException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,5 +1,7 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/**
|
||||
* The per-upstream retry budget refused a further attempt after a retryable failure.
|
||||
*
|
||||
@@ -10,6 +12,11 @@ public final class HttpRetryBudgetExhaustedException extends HttpClientException
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.UNKNOWN;
|
||||
}
|
||||
|
||||
public HttpRetryBudgetExhaustedException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,5 +1,7 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/**
|
||||
* The profile's runtime generation was retired during this call and refused a further attempt.
|
||||
*
|
||||
@@ -10,6 +12,11 @@ public final class HttpRuntimeDrainingException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.UNKNOWN;
|
||||
}
|
||||
|
||||
public HttpRuntimeDrainingException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** Request encoding or response decoding failed; the payload itself is never included. */
|
||||
public final class HttpSerializationException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.SERIALIZATION;
|
||||
}
|
||||
|
||||
public HttpSerializationException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** Target URI, host, port, header, or address policy rejected the request before it was sent. */
|
||||
public final class HttpTargetRejectedException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.TARGET_REJECTED;
|
||||
}
|
||||
|
||||
public HttpTargetRejectedException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,10 +1,17 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/** TLS handshake failed. Trust, hostname, and expiry failures are permanent (design §21.3). */
|
||||
public final class HttpTlsException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.TLS_PERMANENT;
|
||||
}
|
||||
|
||||
public HttpTlsException(String safeMessage, HttpFailureMetadata metadata) {
|
||||
super(safeMessage, metadata);
|
||||
}
|
||||
|
||||
+7
@@ -1,5 +1,7 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
|
||||
/**
|
||||
* The engine failed in a way no stable category describes.
|
||||
*
|
||||
@@ -11,6 +13,11 @@ public final class HttpUnknownTransportException extends HttpClientException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public FailureCategory category() {
|
||||
return FailureCategory.UNKNOWN;
|
||||
}
|
||||
|
||||
public HttpUnknownTransportException(
|
||||
String safeMessage, HttpFailureMetadata metadata, Throwable cause) {
|
||||
super(safeMessage, metadata, cause);
|
||||
|
||||
+5
-6
@@ -7,6 +7,7 @@ import dev.caskeleton.adapter.outbound.httpclient.auth.NoAuthCredentialProvider;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.auth.OAuth2CredentialProvider;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.auth.StaticBearerCredentialProvider;
|
||||
import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException;
|
||||
import dev.caskeleton.application.outbound.SecretReference;
|
||||
import dev.caskeleton.application.outbound.SecretSourcePort;
|
||||
import java.time.Clock;
|
||||
import java.util.Set;
|
||||
@@ -56,17 +57,15 @@ public class HttpClientAuthenticationAutoConfiguration {
|
||||
if (reference == null || reference.isBlank()) {
|
||||
throw new CapabilityStartupValidationException("HTTP credential reference must be non-blank");
|
||||
}
|
||||
if (!reference.startsWith("secret://")) {
|
||||
if (!SecretReference.isReference(reference)) {
|
||||
return reference;
|
||||
}
|
||||
String path = reference.substring("secret://".length());
|
||||
int separator = path.lastIndexOf('/');
|
||||
String key = separator >= 0 ? path.substring(separator + 1) : path;
|
||||
if (key.isBlank()) {
|
||||
try {
|
||||
return SecretReference.parse(reference).name();
|
||||
} catch (IllegalArgumentException blankName) {
|
||||
throw new CapabilityStartupValidationException(
|
||||
"HTTP credential reference '" + reference + "' does not name a secret");
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
+3
-11
@@ -1,7 +1,6 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.autoconfigure;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.observation.HttpClientTagPolicy;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.restclient.BlockingExecutionSupport;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.restclient.ExecutionSupport;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import java.time.Clock;
|
||||
@@ -22,15 +21,8 @@ public class HttpClientObservationAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
HttpClientTagPolicy httpClientTagPolicy() {
|
||||
return HttpClientTagPolicy.standard();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
BlockingExecutionSupport httpClientExecutionSupport(
|
||||
ExecutionSupport httpClientExecutionSupport(
|
||||
Clock clock, ObjectProvider<MeterRegistry> meterRegistry) {
|
||||
return BlockingExecutionSupport.standard(
|
||||
clock, meterRegistry.getIfAvailable(SimpleMeterRegistry::new));
|
||||
return ExecutionSupport.standard(clock, meterRegistry.getIfAvailable(SimpleMeterRegistry::new));
|
||||
}
|
||||
}
|
||||
|
||||
+14
-7
@@ -1,5 +1,12 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.autoconfigure;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.AuthenticationType;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.ClientMode;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.HttpProtocol;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.JitterStrategy;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.ProxyType;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.RetryAfterPolicy;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.TransportType;
|
||||
import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
@@ -117,14 +124,14 @@ public record HttpClientPlatformSettings(
|
||||
*/
|
||||
public record ClientSettings(
|
||||
String name,
|
||||
@DefaultValue("TRUSTED") String mode,
|
||||
@DefaultValue("TRUSTED") ClientMode mode,
|
||||
String baseUrl,
|
||||
@DefaultValue List<String> allowedHosts,
|
||||
@DefaultValue List<Integer> allowedPorts,
|
||||
@DefaultValue("APACHE") String transport,
|
||||
@DefaultValue("APACHE") TransportType transport,
|
||||
// The default transport is Apache, whose classic client is HTTP/1.1 only. A profile that
|
||||
// wants HTTP/2 declares it together with a transport that can deliver it.
|
||||
@DefaultValue({"HTTP_1_1"}) List<String> protocols,
|
||||
@DefaultValue({"HTTP_1_1"}) List<HttpProtocol> protocols,
|
||||
@DefaultValue Pool pool,
|
||||
@DefaultValue Timeout timeout,
|
||||
@DefaultValue Redirect redirect,
|
||||
@@ -202,7 +209,7 @@ public record HttpClientPlatformSettings(
|
||||
|
||||
/** Declared authentication (design §20.1). */
|
||||
public record Authentication(
|
||||
@DefaultValue("NONE") String type,
|
||||
@DefaultValue("NONE") AuthenticationType type,
|
||||
String registrationId,
|
||||
@DefaultValue List<String> scopes,
|
||||
String audience,
|
||||
@@ -215,8 +222,8 @@ public record HttpClientPlatformSettings(
|
||||
@DefaultValue("1") int maxAttempts,
|
||||
@DefaultValue("50ms") Duration baseBackoff,
|
||||
@DefaultValue("200ms") Duration maxBackoff,
|
||||
@DefaultValue("FULL") String jitter,
|
||||
@DefaultValue("HONOR") String retryAfter,
|
||||
@DefaultValue("FULL") JitterStrategy jitter,
|
||||
@DefaultValue("HONOR") RetryAfterPolicy retryAfter,
|
||||
String budget) {}
|
||||
|
||||
/** Per-profile observability switches (design §25). */
|
||||
@@ -245,7 +252,7 @@ public record HttpClientPlatformSettings(
|
||||
@DefaultValue("false") boolean enabled,
|
||||
@DefaultValue("") String host,
|
||||
@DefaultValue("0") int port,
|
||||
@DefaultValue("HTTP") String type,
|
||||
@DefaultValue("HTTP") ProxyType type,
|
||||
String credentialProvider,
|
||||
@DefaultValue("500ms") Duration connectTimeout,
|
||||
@DefaultValue("false") boolean importAmbientNoProxy) {}
|
||||
|
||||
+2
-2
@@ -11,7 +11,7 @@ import dev.caskeleton.adapter.outbound.httpclient.profile.RuntimeEnvironment;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.RuntimeGeneration;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.TransportType;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.ResilienceRegistry;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.restclient.BlockingExecutionSupport;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.restclient.ExecutionSupport;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.restclient.RestClientRuntimeFactory;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.security.TlsPolicyValidator;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.security.TlsRuntimeRotationCoordinator;
|
||||
@@ -65,7 +65,7 @@ public class HttpClientProfileAutoConfiguration {
|
||||
Map<TransportType, BlockingTransportProvider> httpClientBlockingTransportProviders,
|
||||
ResilienceRegistry resilienceRegistry,
|
||||
CredentialProviderRegistry credentialProviders,
|
||||
BlockingExecutionSupport executionSupport,
|
||||
ExecutionSupport executionSupport,
|
||||
TransportLifecycleListener lifecycleListener) {
|
||||
return new RestClientRuntimeFactory(
|
||||
httpClientBlockingTransportProviders,
|
||||
|
||||
+11
-18
@@ -2,30 +2,21 @@ package dev.caskeleton.adapter.outbound.httpclient.autoconfigure;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.ClientProfileName;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.AuthenticationSettings;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.AuthenticationType;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.ClientMode;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.ClientObservabilitySettings;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.ClientProfile;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.HttpProtocol;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.JitterStrategy;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.PoolSettings;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.ProxySettings;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.ProxyType;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.RedirectSettings;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.RequestLimits;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.ResponseLimits;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.RetryAfterPolicy;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.RetrySettings;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.TimeoutSettings;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.TlsSettings;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.TransportType;
|
||||
import java.net.URI;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Turns bound properties into immutable profiles (design §11).
|
||||
@@ -33,6 +24,10 @@ import java.util.stream.Collectors;
|
||||
* <p>Conversion never repairs a configuration. An absent host allowlist stays absent so the
|
||||
* validator can report it, rather than being silently derived from the base URL — which would make
|
||||
* an unstated security decision on the operator's behalf.
|
||||
*
|
||||
* <p>Enumerated settings arrive already typed: the binder converts {@code apache}, {@code APACHE}
|
||||
* and {@code Apache} alike, and rejects an unknown value with the property name attached, which the
|
||||
* {@code valueOf(toUpperCase())} this class used to repeat could not do.
|
||||
*/
|
||||
public final class HttpClientProfileFactory {
|
||||
|
||||
@@ -47,14 +42,12 @@ public final class HttpClientProfileFactory {
|
||||
public ClientProfile toProfile(HttpClientPlatformSettings.ClientSettings client) {
|
||||
return new ClientProfile(
|
||||
new ClientProfileName(client.name()),
|
||||
ClientMode.valueOf(client.mode().toUpperCase(Locale.ROOT)),
|
||||
client.mode(),
|
||||
client.baseUrl() == null ? null : URI.create(client.baseUrl()),
|
||||
Set.copyOf(client.allowedHosts()),
|
||||
Set.copyOf(client.allowedPorts()),
|
||||
TransportType.valueOf(client.transport().toUpperCase(Locale.ROOT)),
|
||||
client.protocols().stream()
|
||||
.map(protocol -> HttpProtocol.valueOf(protocol.toUpperCase(Locale.ROOT)))
|
||||
.collect(Collectors.toUnmodifiableSet()),
|
||||
client.transport(),
|
||||
Set.copyOf(client.protocols()),
|
||||
pool(client.pool()),
|
||||
timeout(client.timeout()),
|
||||
new RedirectSettings(
|
||||
@@ -108,7 +101,7 @@ public final class HttpClientProfileFactory {
|
||||
private AuthenticationSettings authentication(
|
||||
HttpClientPlatformSettings.Authentication authentication) {
|
||||
return new AuthenticationSettings(
|
||||
AuthenticationType.valueOf(authentication.type().toUpperCase(Locale.ROOT)),
|
||||
authentication.type(),
|
||||
Optional.ofNullable(authentication.registrationId()),
|
||||
Set.copyOf(authentication.scopes()),
|
||||
Optional.ofNullable(authentication.audience()),
|
||||
@@ -122,8 +115,8 @@ public final class HttpClientProfileFactory {
|
||||
retry.maxAttempts(),
|
||||
retry.baseBackoff(),
|
||||
retry.maxBackoff(),
|
||||
JitterStrategy.valueOf(retry.jitter().toUpperCase(Locale.ROOT)),
|
||||
RetryAfterPolicy.valueOf(retry.retryAfter().toUpperCase(Locale.ROOT)),
|
||||
retry.jitter(),
|
||||
retry.retryAfter(),
|
||||
Optional.ofNullable(retry.budget()));
|
||||
}
|
||||
|
||||
@@ -143,7 +136,7 @@ public final class HttpClientProfileFactory {
|
||||
proxy.enabled(),
|
||||
proxy.host(),
|
||||
proxy.port(),
|
||||
ProxyType.valueOf(proxy.type().toUpperCase(Locale.ROOT)),
|
||||
proxy.type(),
|
||||
Optional.ofNullable(proxy.credentialProvider()),
|
||||
proxy.connectTimeout(),
|
||||
proxy.importAmbientNoProxy());
|
||||
|
||||
+106
-69
@@ -15,8 +15,11 @@ import dev.caskeleton.adapter.outbound.httpclient.observation.HttpClientObservat
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.ClientRuntimeLease;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.ClientRuntimeRegistry;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.AttemptOutcome;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.Deadline;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.DeadlineGuard;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.restclient.BlockingAttemptExecutor;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.restclient.BlockingClientRuntime;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.restclient.CallSetup;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.restclient.StatusHandlingPolicy;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.security.HeaderPolicy;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.security.PlatformHeaderPropagation;
|
||||
@@ -95,79 +98,113 @@ public final class DefaultDynamicTargetGateway implements DynamicTargetGateway {
|
||||
operation.method(),
|
||||
operation.uriTemplate(),
|
||||
operation.body().replayability());
|
||||
|
||||
// Cross-origin hops are allowed — every hop is revalidated below — so the redirect policy
|
||||
// only bounds the hop count and refuses to resend a body that cannot be produced again.
|
||||
RedirectPolicy redirectPolicy = new RedirectPolicy(true, policy.maxRedirectHops(), true);
|
||||
URI current = target;
|
||||
HttpOperation hopOperation = operation;
|
||||
for (int hop = 0; ; hop++) {
|
||||
PinnedTarget pinned = validate(policy, resolver, current);
|
||||
PreparedOperation prepared =
|
||||
prepare(runtime, hopOperation, pinned, policy.tracePropagation(), metadata);
|
||||
RequestCredentials credentials = credentialsFor(pinned.target());
|
||||
|
||||
// The pin is what makes the validation above binding. Without it the transport resolved the
|
||||
// hostname a second time and could land anywhere; with it the socket may only reach an
|
||||
// address this hop actually approved. Scoped to the hop, so the next redirect re-validates
|
||||
// and re-pins rather than inheriting an earlier decision.
|
||||
AttemptOutcome<T> outcome;
|
||||
try (CallScopedDnsPin pin =
|
||||
CallScopedDnsPin.open(pinned.target().host(), pinned.approvedAddresses())) {
|
||||
Objects.requireNonNull(pin, "dns pin");
|
||||
outcome =
|
||||
executor.execute(
|
||||
runtime,
|
||||
prepared,
|
||||
responseType,
|
||||
StatusHandlingPolicy.RETURN_RESULT,
|
||||
credentials,
|
||||
1,
|
||||
runtime.support().clock().instant(),
|
||||
metadata);
|
||||
}
|
||||
|
||||
HttpCallResult<T> result =
|
||||
outcome.result().orElseThrow(() -> outcome.failure().orElseThrow());
|
||||
Optional<URI> location = redirectLocation(result, pinned);
|
||||
if (location.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
int status = result.status().value();
|
||||
RedirectDecision decision =
|
||||
runtime
|
||||
.support()
|
||||
.redirectEvaluator()
|
||||
.evaluate(
|
||||
RedirectContext.of(
|
||||
redirectPolicy,
|
||||
hop,
|
||||
status,
|
||||
hopOperation.body(),
|
||||
PreparedTarget.of(pinned.target().toUri(), operation.uriTemplate()),
|
||||
location.get()));
|
||||
if (decision instanceof RedirectDecision.Reject reject) {
|
||||
recordRejection(runtime, policyName, reject.code());
|
||||
throw new HttpRedirectRejectedException(
|
||||
"dynamic target redirect rejected: " + reject.code(), metadata);
|
||||
}
|
||||
RedirectDecision.Follow follow = (RedirectDecision.Follow) decision;
|
||||
// 303 turns the follow-up into a GET without the body; every other redirect keeps both.
|
||||
if (status == 303) {
|
||||
hopOperation = hopOperation.withMethod(HttpMethod.GET).withBody(EmptyBody.instance());
|
||||
}
|
||||
// Headers the caller chose for the first origin do not travel to an origin the upstream
|
||||
// chose. Not a list of names known to carry credentials — a caller's X-Client-Key is one
|
||||
// under any name — but an allowlist: only content-negotiation headers survive the hop.
|
||||
// The next loop iteration revalidates the new target from scratch.
|
||||
if (follow.crossOrigin()) {
|
||||
hopOperation = hopOperation.withHeaders(safeForCrossOrigin(hopOperation.headers()));
|
||||
}
|
||||
current = follow.target();
|
||||
// The deadline and the admission permit are the profile's, whatever the target. This path
|
||||
// used to take neither, so a Dynamic Target ran past an expired deadline and outside the
|
||||
// profile's concurrency bound — the same drift the streaming download once had.
|
||||
Deadline deadline = CallSetup.guardedDeadline(runtime, operation, metadata);
|
||||
try (AutoCloseable admission = runtime.admissionLimiter().admit(metadata)) {
|
||||
Objects.requireNonNull(admission, "admission permit");
|
||||
return follow(
|
||||
policyName,
|
||||
target,
|
||||
operation,
|
||||
responseType,
|
||||
policy,
|
||||
resolver,
|
||||
runtime,
|
||||
metadata,
|
||||
deadline);
|
||||
} catch (RuntimeException failure) {
|
||||
throw failure;
|
||||
} catch (Exception unexpected) {
|
||||
throw new IllegalStateException("dynamic target call could not complete", unexpected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private <T> HttpCallResult<T> follow(
|
||||
DynamicTargetPolicyName policyName,
|
||||
URI target,
|
||||
HttpOperation operation,
|
||||
ResponseType<T> responseType,
|
||||
DynamicTargetPolicy policy,
|
||||
ValidatedDnsResolver resolver,
|
||||
BlockingClientRuntime runtime,
|
||||
HttpFailureMetadata metadata,
|
||||
Deadline deadline) {
|
||||
// Cross-origin hops are allowed — every hop is revalidated below — so the redirect policy
|
||||
// only bounds the hop count and refuses to resend a body that cannot be produced again.
|
||||
RedirectPolicy redirectPolicy = new RedirectPolicy(true, policy.maxRedirectHops(), true);
|
||||
URI current = target;
|
||||
HttpOperation hopOperation = operation;
|
||||
for (int hop = 0; ; hop++) {
|
||||
// Each hop spends the same deadline; a redirect chain does not buy itself more time.
|
||||
new DeadlineGuard(runtime.support().clock()).requireTimeRemaining(deadline, metadata);
|
||||
PinnedTarget pinned = validate(policy, resolver, current);
|
||||
PreparedOperation prepared =
|
||||
prepare(runtime, hopOperation, pinned, policy.tracePropagation(), metadata);
|
||||
RequestCredentials credentials = credentialsFor(pinned.target());
|
||||
|
||||
// The pin is what makes the validation above binding. Without it the transport resolved the
|
||||
// hostname a second time and could land anywhere; with it the socket may only reach an
|
||||
// address this hop actually approved. Scoped to the hop, so the next redirect re-validates
|
||||
// and re-pins rather than inheriting an earlier decision.
|
||||
AttemptOutcome<T> outcome;
|
||||
try (CallScopedDnsPin pin =
|
||||
CallScopedDnsPin.open(pinned.target().host(), pinned.approvedAddresses())) {
|
||||
Objects.requireNonNull(pin, "dns pin");
|
||||
outcome =
|
||||
executor.execute(
|
||||
runtime,
|
||||
prepared,
|
||||
responseType,
|
||||
StatusHandlingPolicy.RETURN_RESULT,
|
||||
credentials,
|
||||
1,
|
||||
runtime.support().clock().instant(),
|
||||
metadata);
|
||||
}
|
||||
|
||||
HttpCallResult<T> result =
|
||||
outcome.result().orElseThrow(() -> outcome.failure().orElseThrow());
|
||||
Optional<URI> location = redirectLocation(result, pinned);
|
||||
if (location.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
int status = result.status().value();
|
||||
RedirectDecision decision =
|
||||
runtime
|
||||
.support()
|
||||
.redirectEvaluator()
|
||||
.evaluate(
|
||||
RedirectContext.of(
|
||||
redirectPolicy,
|
||||
hop,
|
||||
status,
|
||||
hopOperation.body(),
|
||||
PreparedTarget.of(pinned.target().toUri(), operation.uriTemplate()),
|
||||
location.get()));
|
||||
if (decision instanceof RedirectDecision.Reject reject) {
|
||||
recordRejection(runtime, policyName, reject.code());
|
||||
throw new HttpRedirectRejectedException(
|
||||
"dynamic target redirect rejected: " + reject.code(), metadata);
|
||||
}
|
||||
RedirectDecision.Follow follow = (RedirectDecision.Follow) decision;
|
||||
// 303 turns the follow-up into a GET without the body; every other redirect keeps both.
|
||||
if (status == 303) {
|
||||
hopOperation = hopOperation.withMethod(HttpMethod.GET).withBody(EmptyBody.instance());
|
||||
}
|
||||
// Headers the caller chose for the first origin do not travel to an origin the upstream
|
||||
// chose. Not a list of names known to carry credentials — a caller's X-Client-Key is one
|
||||
// under any name — but an allowlist: only content-negotiation headers survive the hop.
|
||||
// The next loop iteration revalidates the new target from scratch.
|
||||
if (follow.crossOrigin()) {
|
||||
hopOperation = hopOperation.withHeaders(safeForCrossOrigin(hopOperation.headers()));
|
||||
}
|
||||
current = follow.target();
|
||||
}
|
||||
}
|
||||
|
||||
/** The caller headers that describe the content, not the caller; nothing else crosses origins. */
|
||||
private static final Set<String> CROSS_ORIGIN_SAFE_HEADERS =
|
||||
Set.of("accept", "accept-language", "content-type", "content-language");
|
||||
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.observation;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.ClientProfileName;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.HttpStatus;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.OperationName;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence;
|
||||
import java.time.Duration;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* The only shape an outbound HTTP failure is logged in (design §25.4).
|
||||
*
|
||||
* <p>There is deliberately no component for a body, an {@code Authorization} or {@code Cookie}
|
||||
* value, a query string, or an expanded URL — a field that does not exist cannot be logged by
|
||||
* accident.
|
||||
*/
|
||||
public record SafeHttpLogEvent(
|
||||
ClientProfileName clientName,
|
||||
OperationName operationName,
|
||||
String method,
|
||||
String uriTemplate,
|
||||
Optional<HttpStatus> status,
|
||||
ExecutionEvidence evidence,
|
||||
AttemptStage stage,
|
||||
int attempts,
|
||||
Duration elapsed,
|
||||
Optional<String> traceId) {
|
||||
|
||||
public SafeHttpLogEvent {
|
||||
Objects.requireNonNull(clientName, "client name");
|
||||
Objects.requireNonNull(operationName, "operation name");
|
||||
Objects.requireNonNull(method, "method");
|
||||
Objects.requireNonNull(uriTemplate, "uri template");
|
||||
Objects.requireNonNull(status, "status");
|
||||
Objects.requireNonNull(evidence, "evidence");
|
||||
Objects.requireNonNull(stage, "stage");
|
||||
Objects.requireNonNull(elapsed, "elapsed");
|
||||
Objects.requireNonNull(traceId, "trace id");
|
||||
}
|
||||
|
||||
/** Structured single-line rendering used for the one final failure log per logical call. */
|
||||
public String render() {
|
||||
return "outbound-http client="
|
||||
+ clientName.value()
|
||||
+ " operation="
|
||||
+ operationName.value()
|
||||
+ " method="
|
||||
+ method
|
||||
+ " uriTemplate="
|
||||
+ uriTemplate
|
||||
+ " status="
|
||||
+ status.map(HttpStatus::toString).orElse("none")
|
||||
+ " evidence="
|
||||
+ evidence
|
||||
+ " stage="
|
||||
+ stage
|
||||
+ " attempts="
|
||||
+ attempts
|
||||
+ " elapsedMs="
|
||||
+ elapsed.toMillis()
|
||||
+ traceId.map(value -> " traceId=" + value).orElse("");
|
||||
}
|
||||
}
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.resilience;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.result.HttpCallResult;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Blocking retry driver (design §17, §18).
|
||||
*
|
||||
* <p>Two properties are load-bearing:
|
||||
*
|
||||
* <ul>
|
||||
* <li>the backoff sleep happens <em>outside</em> the attempt, so no connection or bulkhead permit
|
||||
* is held while waiting (design §17.5);
|
||||
* <li>the budget token is consumed only after a retry has actually been granted, so denied
|
||||
* retries do not drain the upstream's budget.
|
||||
* </ul>
|
||||
*/
|
||||
public final class BlockingRetryCoordinator implements RetryCoordinator {
|
||||
|
||||
private final RetryEligibilityEngine eligibility;
|
||||
private final BackoffStrategy backoff;
|
||||
private final RetryBudget budget;
|
||||
private final Sleeper sleeper;
|
||||
private final Clock clock;
|
||||
|
||||
public BlockingRetryCoordinator(
|
||||
RetryEligibilityEngine eligibility,
|
||||
BackoffStrategy backoff,
|
||||
RetryBudget budget,
|
||||
Sleeper sleeper,
|
||||
Clock clock) {
|
||||
this.eligibility = Objects.requireNonNull(eligibility, "retry eligibility engine");
|
||||
this.backoff = Objects.requireNonNull(backoff, "backoff strategy");
|
||||
this.budget = Objects.requireNonNull(budget, "retry budget");
|
||||
this.sleeper = Objects.requireNonNull(sleeper, "sleeper");
|
||||
this.clock = Objects.requireNonNull(clock, "clock");
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> HttpCallResult<T> execute(BlockingLogicalCall<T> call) {
|
||||
Objects.requireNonNull(call, "logical call");
|
||||
budget.recordLogicalCall();
|
||||
for (int attempt = 1; ; attempt++) {
|
||||
AttemptOutcome<T> outcome = call.attempt(attempt);
|
||||
RetryDecision decision = eligibility.decide(call.context(outcome, attempt));
|
||||
|
||||
if (decision instanceof RetryAllowed allowed) {
|
||||
if (!budget.tryConsume()) {
|
||||
throw call.retryExhausted(attempt);
|
||||
}
|
||||
call.onRetryGranted(allowed, attempt);
|
||||
Duration remaining = call.deadline().remaining(clock);
|
||||
sleeper.sleep(backoff.delay(attempt, allowed.retryAfter(), remaining));
|
||||
continue;
|
||||
}
|
||||
if (decision instanceof AmbiguousFailure) {
|
||||
throw call.ambiguous(outcome, attempt);
|
||||
}
|
||||
return call.finish(outcome, attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.resilience;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence;
|
||||
|
||||
/**
|
||||
* Conservative evidence rules (design §16.3).
|
||||
*
|
||||
* <p>Ordering matters and is deliberate: delivered body bytes beat a received header, a received
|
||||
* header beats a started write, and only a pre-send stage failure — or explicit protocol proof —
|
||||
* may claim {@code NOT_SENT}.
|
||||
*/
|
||||
public final class DefaultExecutionEvidenceClassifier implements ExecutionEvidenceClassifier {
|
||||
|
||||
@Override
|
||||
public ExecutionEvidence classify(AttemptProgress progress, ProtocolEvidence protocolEvidence) {
|
||||
if (protocolEvidence.peerDidNotProcess()) {
|
||||
return ExecutionEvidence.NOT_SENT;
|
||||
}
|
||||
if (progress.responseBytesDelivered() > 0 || progress.firstByteDelivered()) {
|
||||
return ExecutionEvidence.PARTIAL_RESPONSE;
|
||||
}
|
||||
if (progress.responseHeadersReceived()) {
|
||||
return ExecutionEvidence.RESPONSE_RECEIVED;
|
||||
}
|
||||
if (progress.requestWriteStarted()) {
|
||||
return ExecutionEvidence.SENT_NO_RESPONSE;
|
||||
}
|
||||
return progress.stage().provesNotSent()
|
||||
? ExecutionEvidence.NOT_SENT
|
||||
: ExecutionEvidence.SENT_NO_RESPONSE;
|
||||
}
|
||||
}
|
||||
+25
-4
@@ -2,9 +2,30 @@ package dev.caskeleton.adapter.outbound.httpclient.resilience;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence;
|
||||
|
||||
/** Turns observed attempt progress into public execution evidence (design §16). */
|
||||
@FunctionalInterface
|
||||
public interface ExecutionEvidenceClassifier {
|
||||
/**
|
||||
* Conservative evidence rules (design §16.3).
|
||||
*
|
||||
* <p>Ordering matters and is deliberate: delivered body bytes beat a received header, a received
|
||||
* header beats a started write, and only a pre-send stage failure — or explicit protocol proof —
|
||||
* may claim {@code NOT_SENT}.
|
||||
*/
|
||||
public final class ExecutionEvidenceClassifier {
|
||||
|
||||
ExecutionEvidence classify(AttemptProgress progress, ProtocolEvidence protocolEvidence);
|
||||
public ExecutionEvidence classify(AttemptProgress progress, ProtocolEvidence protocolEvidence) {
|
||||
if (protocolEvidence.peerDidNotProcess()) {
|
||||
return ExecutionEvidence.NOT_SENT;
|
||||
}
|
||||
if (progress.responseBytesDelivered() > 0 || progress.firstByteDelivered()) {
|
||||
return ExecutionEvidence.PARTIAL_RESPONSE;
|
||||
}
|
||||
if (progress.responseHeadersReceived()) {
|
||||
return ExecutionEvidence.RESPONSE_RECEIVED;
|
||||
}
|
||||
if (progress.requestWriteStarted()) {
|
||||
return ExecutionEvidence.SENT_NO_RESPONSE;
|
||||
}
|
||||
return progress.stage().provesNotSent()
|
||||
? ExecutionEvidence.NOT_SENT
|
||||
: ExecutionEvidence.SENT_NO_RESPONSE;
|
||||
}
|
||||
}
|
||||
|
||||
+57
-3
@@ -1,9 +1,63 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.resilience;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.result.HttpCallResult;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Objects;
|
||||
|
||||
/** Drives physical attempts for one logical call (design §18). */
|
||||
public interface RetryCoordinator {
|
||||
/**
|
||||
* Blocking retry driver (design §17, §18).
|
||||
*
|
||||
* <p>Two properties are load-bearing:
|
||||
*
|
||||
* <ul>
|
||||
* <li>the backoff sleep happens <em>outside</em> the attempt, so no connection or bulkhead permit
|
||||
* is held while waiting (design §17.5);
|
||||
* <li>the budget token is consumed only after a retry has actually been granted, so denied
|
||||
* retries do not drain the upstream's budget.
|
||||
* </ul>
|
||||
*/
|
||||
public final class RetryCoordinator {
|
||||
|
||||
<T> HttpCallResult<T> execute(BlockingLogicalCall<T> call);
|
||||
private final RetryEligibilityEngine eligibility;
|
||||
private final BackoffStrategy backoff;
|
||||
private final RetryBudget budget;
|
||||
private final Sleeper sleeper;
|
||||
private final Clock clock;
|
||||
|
||||
public RetryCoordinator(
|
||||
RetryEligibilityEngine eligibility,
|
||||
BackoffStrategy backoff,
|
||||
RetryBudget budget,
|
||||
Sleeper sleeper,
|
||||
Clock clock) {
|
||||
this.eligibility = Objects.requireNonNull(eligibility, "retry eligibility engine");
|
||||
this.backoff = Objects.requireNonNull(backoff, "backoff strategy");
|
||||
this.budget = Objects.requireNonNull(budget, "retry budget");
|
||||
this.sleeper = Objects.requireNonNull(sleeper, "sleeper");
|
||||
this.clock = Objects.requireNonNull(clock, "clock");
|
||||
}
|
||||
|
||||
public <T> HttpCallResult<T> execute(BlockingLogicalCall<T> call) {
|
||||
Objects.requireNonNull(call, "logical call");
|
||||
budget.recordLogicalCall();
|
||||
for (int attempt = 1; ; attempt++) {
|
||||
AttemptOutcome<T> outcome = call.attempt(attempt);
|
||||
RetryDecision decision = eligibility.decide(call.context(outcome, attempt));
|
||||
|
||||
if (decision instanceof RetryAllowed allowed) {
|
||||
if (!budget.tryConsume()) {
|
||||
throw call.retryExhausted(attempt);
|
||||
}
|
||||
call.onRetryGranted(allowed, attempt);
|
||||
Duration remaining = call.deadline().remaining(clock);
|
||||
sleeper.sleep(backoff.delay(attempt, allowed.retryAfter(), remaining));
|
||||
continue;
|
||||
}
|
||||
if (decision instanceof AmbiguousFailure) {
|
||||
throw call.ambiguous(outcome, attempt);
|
||||
}
|
||||
return call.finish(outcome, attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-27
@@ -47,7 +47,7 @@ public final class BlockingAttemptExecutor {
|
||||
HttpFailureMetadata baseMetadata) {
|
||||
|
||||
Objects.requireNonNull(runtime, "runtime");
|
||||
BlockingExecutionSupport support = runtime.support();
|
||||
ExecutionSupport support = runtime.support();
|
||||
AttemptProgressTracker tracker = new AttemptProgressTracker();
|
||||
AttemptObservation observation =
|
||||
AttemptObservation.start(
|
||||
@@ -103,7 +103,7 @@ public final class BlockingAttemptExecutor {
|
||||
} catch (HttpClientException stable) {
|
||||
return AttemptOutcome.<T>failed(
|
||||
stable,
|
||||
categoryOf(stable),
|
||||
stable.category(),
|
||||
Optional.empty(),
|
||||
tracker.firstByteDelivered());
|
||||
}
|
||||
@@ -117,7 +117,7 @@ public final class BlockingAttemptExecutor {
|
||||
} catch (HttpClientException stable) {
|
||||
AttemptOutcome<T> outcome =
|
||||
AttemptOutcome.failed(
|
||||
stable, categoryOf(stable), Optional.empty(), tracker.firstByteDelivered());
|
||||
stable, stable.category(), Optional.empty(), tracker.firstByteDelivered());
|
||||
stopObservation(observation, outcome);
|
||||
return outcome;
|
||||
} catch (RuntimeException engineFailure) {
|
||||
@@ -289,28 +289,4 @@ public final class BlockingAttemptExecutor {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private FailureCategory categoryOf(HttpClientException failure) {
|
||||
return switch (failure.getClass().getSimpleName()) {
|
||||
case "HttpDnsException" -> FailureCategory.DNS;
|
||||
case "HttpPoolAcquireTimeoutException" -> FailureCategory.POOL_ACQUIRE_TIMEOUT;
|
||||
case "HttpConnectException" -> FailureCategory.CONNECT;
|
||||
case "HttpProxyException" -> FailureCategory.PROXY;
|
||||
case "HttpTlsException" -> FailureCategory.TLS_PERMANENT;
|
||||
case "HttpRequestWriteException" -> FailureCategory.REQUEST_WRITE;
|
||||
case "HttpResponseTimeoutException" -> FailureCategory.RESPONSE_TIMEOUT;
|
||||
case "HttpResponseTruncatedException" -> FailureCategory.RESPONSE_TRUNCATED;
|
||||
case "HttpResponseTooLargeException" -> FailureCategory.RESPONSE_TOO_LARGE;
|
||||
case "HttpSerializationException" -> FailureCategory.SERIALIZATION;
|
||||
case "HttpTargetRejectedException" -> FailureCategory.TARGET_REJECTED;
|
||||
case "HttpRedirectRejectedException" -> FailureCategory.REDIRECT_REJECTED;
|
||||
case "HttpAuthenticationException" -> FailureCategory.AUTHENTICATION;
|
||||
case "HttpCircuitOpenException" -> FailureCategory.CIRCUIT_OPEN;
|
||||
case "HttpRateLimitRejectedException" -> FailureCategory.RATE_LIMIT_REJECTED;
|
||||
case "HttpBulkheadRejectedException" -> FailureCategory.BULKHEAD_REJECTED;
|
||||
case "HttpDeadlineExceededException" -> FailureCategory.DEADLINE_EXCEEDED;
|
||||
case "HttpConfigurationException" -> FailureCategory.CONFIGURATION;
|
||||
default -> FailureCategory.UNKNOWN;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -37,7 +37,7 @@ public final class BlockingClientRuntime extends ClientRuntime {
|
||||
private final RetryBudget retryBudget;
|
||||
private final Supplier<BackoffStrategy> backoffFactory;
|
||||
private final RequestCredentialProvider credentialProvider;
|
||||
private final BlockingExecutionSupport support;
|
||||
private final ExecutionSupport support;
|
||||
|
||||
public BlockingClientRuntime(
|
||||
ClientProfile profile,
|
||||
@@ -51,7 +51,7 @@ public final class BlockingClientRuntime extends ClientRuntime {
|
||||
RetryBudget retryBudget,
|
||||
Supplier<BackoffStrategy> backoffFactory,
|
||||
RequestCredentialProvider credentialProvider,
|
||||
BlockingExecutionSupport support) {
|
||||
ExecutionSupport support) {
|
||||
super(profile, generation, resourceCloser);
|
||||
this.restClient = Objects.requireNonNull(restClient, "rest client");
|
||||
this.transportId = Objects.requireNonNull(transportId, "transport id");
|
||||
@@ -126,7 +126,7 @@ public final class BlockingClientRuntime extends ClientRuntime {
|
||||
return credentialProvider;
|
||||
}
|
||||
|
||||
public BlockingExecutionSupport support() {
|
||||
public ExecutionSupport support() {
|
||||
return support;
|
||||
}
|
||||
}
|
||||
|
||||
+11
-45
@@ -7,11 +7,9 @@ import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpRemoteErrorExcep
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.result.BlockingStreamingResponse;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.auth.CredentialRequest;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.auth.RequestCredentials;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.ClientRuntimeLease;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.ClientRuntimeRegistry;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.DeadlineGuard;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.security.PreparedOperation;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
@@ -44,51 +42,19 @@ public final class BlockingStreamingGateway {
|
||||
ClientRuntimeLease lease = runtimes.acquire(profileName);
|
||||
boolean handedOff = false;
|
||||
try {
|
||||
if (!(lease.runtime() instanceof BlockingClientRuntime runtime)) {
|
||||
throw new IllegalStateException(
|
||||
"profile " + profileName.value() + " is not configured for the blocking api");
|
||||
}
|
||||
HttpFailureMetadata metadata =
|
||||
HttpFailureMetadata.validation(
|
||||
profileName,
|
||||
operation.operationName(),
|
||||
operation.method(),
|
||||
operation.uriTemplate(),
|
||||
operation.body().replayability());
|
||||
PreparedOperation prepared = runtime.targetPolicy().prepare(operation);
|
||||
// A streaming download is a call, not an exemption. This path used to apply target policy and
|
||||
// the wire-byte limit and nothing else: no credential was resolved, no admission permit
|
||||
// taken, no deadline checked. A profile whose upstream was down could therefore be hammered
|
||||
// indefinitely through its streaming surface while its non-streaming surface sat behind an
|
||||
// open circuit. CallSetup is the same front half the generic gateway runs.
|
||||
CallSetup setup = CallSetup.prepare(lease, operation);
|
||||
BlockingClientRuntime runtime = setup.runtime();
|
||||
HttpFailureMetadata metadata = setup.metadata();
|
||||
PreparedOperation prepared = setup.prepared();
|
||||
ResponseSizeLimiter limiter =
|
||||
new ResponseSizeLimiter(
|
||||
prepared.maxResponseWireBytes(), prepared.maxResponseDecodedBytes(), metadata);
|
||||
|
||||
// A streaming download is a call, not an exemption. This path used to apply target policy and
|
||||
// the wire-byte limit and nothing else: no credential was resolved, no admission permit
|
||||
// taken,
|
||||
// no deadline checked, no breaker or rate limiter entered. A profile whose upstream was down
|
||||
// could therefore be hammered indefinitely through its streaming surface while its
|
||||
// non-streaming surface sat behind an open circuit.
|
||||
new DeadlineGuard(runtime.support().clock())
|
||||
.requireTimeRemaining(
|
||||
runtime
|
||||
.support()
|
||||
.deadlineCalculator()
|
||||
.effective(
|
||||
operation.deadline(),
|
||||
runtime.profile().timeout().totalCall(),
|
||||
runtime.support().clock()),
|
||||
metadata);
|
||||
|
||||
RequestCredentials credentials =
|
||||
runtime
|
||||
.credentialProvider()
|
||||
.resolve(
|
||||
new CredentialRequest(
|
||||
runtime.name(),
|
||||
operation.operationName(),
|
||||
runtime.profile().authentication(),
|
||||
prepared.target().uri(),
|
||||
java.util.Optional.empty(),
|
||||
runtime.profile().tls().keyMaterialReference(),
|
||||
false));
|
||||
RequestCredentials credentials = setup.credentials(false);
|
||||
|
||||
Map<String, List<String>> headers = new LinkedHashMap<>(prepared.headers());
|
||||
credentials.headers().forEach((name, value) -> headers.put(name, List.of(value)));
|
||||
@@ -103,7 +69,7 @@ public final class BlockingStreamingGateway {
|
||||
// The admission permit is held for the life of the stream, not just the request: a streamed
|
||||
// body occupies a connection until the caller closes it, and counting only the handshake made
|
||||
// the limiter blind to exactly the calls that hold resources longest.
|
||||
AutoCloseable admission = runtime.admissionLimiter().admit(metadata);
|
||||
AutoCloseable admission = setup.admit();
|
||||
BlockingStreamingResponse response;
|
||||
try {
|
||||
response =
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package dev.caskeleton.adapter.outbound.httpclient.restclient;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpFailureMetadata;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.auth.CredentialRequest;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.auth.RequestCredentials;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.ClientRuntimeLease;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.Deadline;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.DeadlineGuard;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.security.PreparedOperation;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* The front half of every profile call, assembled once: blocking runtime → validation metadata →
|
||||
* target policy → effective deadline, plus the admission permit and credentials.
|
||||
*
|
||||
* <p>Each entry point used to assemble this sequence itself, and the copies drifted — the streaming
|
||||
* download once applied target policy and nothing else. Entry points now differ only in how they
|
||||
* send: the generic gateway retries through the coordinator, the streaming gateway hands the body
|
||||
* to the caller.
|
||||
*
|
||||
* @param runtime the leased blocking runtime
|
||||
* @param metadata failure metadata for anything raised before an attempt exists
|
||||
* @param prepared the operation after the profile's target policy
|
||||
* @param deadline the effective deadline, already verified to have time remaining
|
||||
*/
|
||||
public record CallSetup(
|
||||
BlockingClientRuntime runtime,
|
||||
HttpFailureMetadata metadata,
|
||||
PreparedOperation prepared,
|
||||
Deadline deadline) {
|
||||
|
||||
public CallSetup {
|
||||
Objects.requireNonNull(runtime, "runtime");
|
||||
Objects.requireNonNull(metadata, "metadata");
|
||||
Objects.requireNonNull(prepared, "prepared operation");
|
||||
Objects.requireNonNull(deadline, "deadline");
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares one call on the leased runtime.
|
||||
*
|
||||
* @param lease the lease the caller keeps open for the life of the call
|
||||
* @param operation the operation as the caller described it
|
||||
* @return the prepared call
|
||||
* @throws IllegalStateException when the profile is not served by the blocking stack
|
||||
*/
|
||||
public static CallSetup prepare(ClientRuntimeLease lease, HttpOperation operation) {
|
||||
Objects.requireNonNull(lease, "lease");
|
||||
Objects.requireNonNull(operation, "operation");
|
||||
if (!(lease.runtime() instanceof BlockingClientRuntime runtime)) {
|
||||
throw new IllegalStateException(
|
||||
"profile " + lease.runtime().name().value() + " is not configured for the blocking api");
|
||||
}
|
||||
HttpFailureMetadata metadata =
|
||||
HttpFailureMetadata.validation(
|
||||
runtime.name(),
|
||||
operation.operationName(),
|
||||
operation.method(),
|
||||
operation.uriTemplate(),
|
||||
operation.body().replayability());
|
||||
PreparedOperation prepared = runtime.targetPolicy().prepare(operation);
|
||||
return new CallSetup(
|
||||
runtime, metadata, prepared, guardedDeadline(runtime, operation, metadata));
|
||||
}
|
||||
|
||||
/**
|
||||
* The operation's effective deadline, refused when it has already passed.
|
||||
*
|
||||
* <p>Shared with the Dynamic Target gateway, whose target preparation differs but whose deadline
|
||||
* must not.
|
||||
*
|
||||
* @param runtime the runtime whose profile bounds the total call
|
||||
* @param operation the operation that may carry a tighter deadline
|
||||
* @param metadata the metadata a refusal carries
|
||||
* @return the effective deadline
|
||||
*/
|
||||
public static Deadline guardedDeadline(
|
||||
BlockingClientRuntime runtime, HttpOperation operation, HttpFailureMetadata metadata) {
|
||||
ExecutionSupport support = runtime.support();
|
||||
Deadline deadline =
|
||||
support
|
||||
.deadlineCalculator()
|
||||
.effective(
|
||||
operation.deadline(), runtime.profile().timeout().totalCall(), support.clock());
|
||||
new DeadlineGuard(support.clock()).requireTimeRemaining(deadline, metadata);
|
||||
return deadline;
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a logical-call admission permit; closing it releases the permit.
|
||||
*
|
||||
* @return the permit
|
||||
*/
|
||||
public AutoCloseable admit() {
|
||||
return runtime.admissionLimiter().admit(metadata);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the profile's credentials for this call's target.
|
||||
*
|
||||
* @param forceRefresh whether a cached credential must be bypassed
|
||||
* @return the credentials to attach
|
||||
*/
|
||||
public RequestCredentials credentials(boolean forceRefresh) {
|
||||
return runtime.credentialProvider().resolve(credentialRequest(forceRefresh));
|
||||
}
|
||||
|
||||
/**
|
||||
* The request the credential provider keys on for this call.
|
||||
*
|
||||
* @param forceRefresh whether a cached credential must be bypassed
|
||||
* @return the credential request
|
||||
*/
|
||||
public CredentialRequest credentialRequest(boolean forceRefresh) {
|
||||
return new CredentialRequest(
|
||||
runtime.name(),
|
||||
prepared.operation().operationName(),
|
||||
runtime.profile().authentication(),
|
||||
prepared.target().uri(),
|
||||
Optional.empty(),
|
||||
runtime.profile().tls().keyMaterialReference(),
|
||||
forceRefresh);
|
||||
}
|
||||
}
|
||||
+23
-65
@@ -10,7 +10,6 @@ import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidenc
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.result.HttpCallResult;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.auth.CredentialRequest;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.auth.RequestCredentials;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.auth.UnauthorizedRetryContext;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.observation.LogicalCallObservation;
|
||||
@@ -19,11 +18,11 @@ import dev.caskeleton.adapter.outbound.httpclient.profile.ClientRuntimeRegistry;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.AttemptBudgetCalculator;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.AttemptOutcome;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.BlockingLogicalCall;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.BlockingRetryCoordinator;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.Deadline;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.DeadlineGuard;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.RetryAllowed;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.RetryContext;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.RetryCoordinator;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.Sleeper;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.security.PreparedOperation;
|
||||
import java.time.Duration;
|
||||
@@ -34,9 +33,10 @@ import java.util.Optional;
|
||||
/**
|
||||
* H2 Generic Exchange over the blocking stack (design §9.3, §7.1).
|
||||
*
|
||||
* <p>The logical call is assembled here and then handed to the retry coordinator: lease → admission
|
||||
* → target policy → deadline → credentials → attempts. Every one of those is a place a caller could
|
||||
* otherwise bypass a profile guarantee, which is why none of them are optional.
|
||||
* <p>{@link CallSetup} assembles the front of the call — lease → target policy → deadline →
|
||||
* admission → credentials — and this gateway hands it to the retry coordinator. Every one of those
|
||||
* is a place a caller could otherwise bypass a profile guarantee, which is why none of them are
|
||||
* optional.
|
||||
*/
|
||||
public final class DefaultGenericHttpGateway implements GenericHttpGateway {
|
||||
|
||||
@@ -66,29 +66,14 @@ public final class DefaultGenericHttpGateway implements GenericHttpGateway {
|
||||
Objects.requireNonNull(responseType, "response type");
|
||||
|
||||
try (ClientRuntimeLease lease = runtimes.acquire(profileName)) {
|
||||
BlockingClientRuntime runtime = requireBlockingRuntime(lease);
|
||||
BlockingExecutionSupport support = runtime.support();
|
||||
HttpFailureMetadata metadata =
|
||||
HttpFailureMetadata.validation(
|
||||
profileName,
|
||||
operation.operationName(),
|
||||
operation.method(),
|
||||
operation.uriTemplate(),
|
||||
operation.body().replayability());
|
||||
CallSetup setup = CallSetup.prepare(lease, operation);
|
||||
BlockingClientRuntime runtime = setup.runtime();
|
||||
ExecutionSupport support = runtime.support();
|
||||
|
||||
try (AutoCloseable admission = runtime.admissionLimiter().admit(metadata);
|
||||
try (AutoCloseable admission = setup.admit();
|
||||
AutoCloseable context =
|
||||
BlockingOperationContext.set(profileName, operation.operationName())) {
|
||||
|
||||
PreparedOperation prepared = runtime.targetPolicy().prepare(operation);
|
||||
|
||||
Deadline deadline =
|
||||
support
|
||||
.deadlineCalculator()
|
||||
.effective(
|
||||
operation.deadline(), runtime.profile().timeout().totalCall(), support.clock());
|
||||
new DeadlineGuard(support.clock()).requireTimeRemaining(deadline, metadata);
|
||||
|
||||
LogicalCallObservation observation =
|
||||
LogicalCallObservation.start(
|
||||
support.meterRegistry(),
|
||||
@@ -98,8 +83,8 @@ public final class DefaultGenericHttpGateway implements GenericHttpGateway {
|
||||
operation.method().name(),
|
||||
operation.uriTemplate());
|
||||
|
||||
BlockingRetryCoordinator coordinator =
|
||||
new BlockingRetryCoordinator(
|
||||
RetryCoordinator coordinator =
|
||||
new RetryCoordinator(
|
||||
support.eligibilityEngine(),
|
||||
runtime.newBackoff(),
|
||||
runtime.retryBudget(),
|
||||
@@ -107,14 +92,7 @@ public final class DefaultGenericHttpGateway implements GenericHttpGateway {
|
||||
support.clock());
|
||||
|
||||
GenericLogicalCall<T> call =
|
||||
new GenericLogicalCall<>(
|
||||
runtime,
|
||||
prepared,
|
||||
responseType,
|
||||
statusHandlingPolicy,
|
||||
deadline,
|
||||
metadata,
|
||||
observation);
|
||||
new GenericLogicalCall<>(setup, responseType, statusHandlingPolicy, observation);
|
||||
try {
|
||||
HttpCallResult<T> result = coordinator.execute(call);
|
||||
observation.stop(Optional.of(result.status()), result.evidence(), "success");
|
||||
@@ -135,17 +113,10 @@ public final class DefaultGenericHttpGateway implements GenericHttpGateway {
|
||||
}
|
||||
}
|
||||
|
||||
private BlockingClientRuntime requireBlockingRuntime(ClientRuntimeLease lease) {
|
||||
if (lease.runtime() instanceof BlockingClientRuntime blocking) {
|
||||
return blocking;
|
||||
}
|
||||
throw new IllegalStateException(
|
||||
"profile " + lease.runtime().name().value() + " is not configured for the blocking api");
|
||||
}
|
||||
|
||||
/** Bridges one prepared operation to the retry coordinator (design §7.1 steps 8-13). */
|
||||
private final class GenericLogicalCall<T> implements BlockingLogicalCall<T> {
|
||||
|
||||
private final CallSetup setup;
|
||||
private final BlockingClientRuntime runtime;
|
||||
private final PreparedOperation prepared;
|
||||
private final ResponseType<T> responseType;
|
||||
@@ -159,19 +130,17 @@ public final class DefaultGenericHttpGateway implements GenericHttpGateway {
|
||||
private int credentialRefreshes;
|
||||
|
||||
private GenericLogicalCall(
|
||||
BlockingClientRuntime runtime,
|
||||
PreparedOperation prepared,
|
||||
CallSetup setup,
|
||||
ResponseType<T> responseType,
|
||||
StatusHandlingPolicy statusHandlingPolicy,
|
||||
Deadline deadline,
|
||||
HttpFailureMetadata metadata,
|
||||
LogicalCallObservation observation) {
|
||||
this.runtime = runtime;
|
||||
this.prepared = prepared;
|
||||
this.setup = setup;
|
||||
this.runtime = setup.runtime();
|
||||
this.prepared = setup.prepared();
|
||||
this.responseType = responseType;
|
||||
this.statusHandlingPolicy = statusHandlingPolicy;
|
||||
this.deadline = deadline;
|
||||
this.metadata = metadata;
|
||||
this.deadline = setup.deadline();
|
||||
this.metadata = setup.metadata();
|
||||
this.observation = observation;
|
||||
this.startedAt = runtime.support().clock().instant();
|
||||
this.credentials = resolveCredentials(false);
|
||||
@@ -188,7 +157,7 @@ public final class DefaultGenericHttpGateway implements GenericHttpGateway {
|
||||
// expired and run to its own transport timeout — the caller's deadline was a suggestion the
|
||||
// second attempt onwards ignored. AttemptBudgetCalculator and DeadlineGuard both existed for
|
||||
// this and neither was on the execution path.
|
||||
BlockingExecutionSupport attemptSupport = runtime.support();
|
||||
ExecutionSupport attemptSupport = runtime.support();
|
||||
DeadlineGuard guard = new DeadlineGuard(attemptSupport.clock());
|
||||
guard.requireTimeRemaining(deadline, metadata.withAttempt(attemptNumber));
|
||||
guard.requireAttemptBudget(
|
||||
@@ -209,7 +178,7 @@ public final class DefaultGenericHttpGateway implements GenericHttpGateway {
|
||||
|
||||
@Override
|
||||
public RetryContext context(AttemptOutcome<T> outcome, int attemptNumber) {
|
||||
BlockingExecutionSupport support = runtime.support();
|
||||
ExecutionSupport support = runtime.support();
|
||||
boolean unauthorized = outcome.status().map(status -> status.value() == 401).orElse(false);
|
||||
boolean refreshAllowed =
|
||||
unauthorized
|
||||
@@ -222,7 +191,7 @@ public final class DefaultGenericHttpGateway implements GenericHttpGateway {
|
||||
credentialRefreshes,
|
||||
true));
|
||||
if (refreshAllowed) {
|
||||
runtime.credentialProvider().invalidate(credentialRequest(false));
|
||||
runtime.credentialProvider().invalidate(setup.credentialRequest(false));
|
||||
credentials = resolveCredentials(true);
|
||||
credentialRefreshes++;
|
||||
}
|
||||
@@ -288,18 +257,7 @@ public final class DefaultGenericHttpGateway implements GenericHttpGateway {
|
||||
}
|
||||
|
||||
private RequestCredentials resolveCredentials(boolean forceRefresh) {
|
||||
return runtime.credentialProvider().resolve(credentialRequest(forceRefresh));
|
||||
}
|
||||
|
||||
private CredentialRequest credentialRequest(boolean forceRefresh) {
|
||||
return new CredentialRequest(
|
||||
runtime.name(),
|
||||
prepared.operation().operationName(),
|
||||
runtime.profile().authentication(),
|
||||
prepared.target().uri(),
|
||||
Optional.empty(),
|
||||
runtime.profile().tls().keyMaterialReference(),
|
||||
forceRefresh);
|
||||
return setup.credentials(forceRefresh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+5
-6
@@ -5,7 +5,6 @@ import dev.caskeleton.adapter.outbound.httpclient.auth.UnauthorizedRetryPolicy;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.observation.HttpClientTagPolicy;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.AttemptBudgetCalculator;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.DeadlineCalculator;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.DefaultExecutionEvidenceClassifier;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.DefaultRetryEligibilityEngine;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.ExecutionEvidenceClassifier;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.Http2EvidenceMapper;
|
||||
@@ -25,7 +24,7 @@ import java.util.Set;
|
||||
* <p>Grouped into one value so a runtime's constructor stays readable and so the whole set is
|
||||
* replaced atomically when a generation is rebuilt.
|
||||
*/
|
||||
public record BlockingExecutionSupport(
|
||||
public record ExecutionSupport(
|
||||
Clock clock,
|
||||
MeterRegistry meterRegistry,
|
||||
HttpClientTagPolicy tagPolicy,
|
||||
@@ -46,7 +45,7 @@ public record BlockingExecutionSupport(
|
||||
Duration cleanupReserve,
|
||||
Set<Integer> transientServerErrorStatuses) {
|
||||
|
||||
public BlockingExecutionSupport {
|
||||
public ExecutionSupport {
|
||||
Objects.requireNonNull(clock, "clock");
|
||||
Objects.requireNonNull(meterRegistry, "meter registry");
|
||||
Objects.requireNonNull(tagPolicy, "tag policy");
|
||||
@@ -69,13 +68,13 @@ public record BlockingExecutionSupport(
|
||||
transientServerErrorStatuses = Set.copyOf(transientServerErrorStatuses);
|
||||
}
|
||||
|
||||
public static BlockingExecutionSupport standard(Clock clock, MeterRegistry meterRegistry) {
|
||||
public static ExecutionSupport standard(Clock clock, MeterRegistry meterRegistry) {
|
||||
RestClientResponseReader reader = new RestClientResponseReader();
|
||||
return new BlockingExecutionSupport(
|
||||
return new ExecutionSupport(
|
||||
clock,
|
||||
meterRegistry,
|
||||
HttpClientTagPolicy.standard(),
|
||||
new DefaultExecutionEvidenceClassifier(),
|
||||
new ExecutionEvidenceClassifier(),
|
||||
// The blocking transport is Apache HC5, so its failures are the ones that can carry a
|
||||
// readable frame. A deployment on another engine gets ProtocolEvidenceReader.none() and the
|
||||
// ordinary classification, which is what it had before this seam existed.
|
||||
+2
-2
@@ -39,7 +39,7 @@ public final class RestClientRuntimeFactory implements ClientRuntimeFactory {
|
||||
new TransportCapabilityValidator();
|
||||
private final ResilienceRegistry resilienceRegistry;
|
||||
private final CredentialProviderRegistry credentialProviders;
|
||||
private final BlockingExecutionSupport support;
|
||||
private final ExecutionSupport support;
|
||||
private final TransportLifecycleListener lifecycleListener;
|
||||
private final RandomGenerator random;
|
||||
|
||||
@@ -47,7 +47,7 @@ public final class RestClientRuntimeFactory implements ClientRuntimeFactory {
|
||||
Map<TransportType, BlockingTransportProvider> providers,
|
||||
ResilienceRegistry resilienceRegistry,
|
||||
CredentialProviderRegistry credentialProviders,
|
||||
BlockingExecutionSupport support,
|
||||
ExecutionSupport support,
|
||||
TransportLifecycleListener lifecycleListener,
|
||||
RandomGenerator random) {
|
||||
Objects.requireNonNull(providers, "transport providers").forEach(this.providers::put);
|
||||
|
||||
-16
@@ -32,22 +32,6 @@ public final class SensitiveHeaderStripper {
|
||||
return new SensitiveHeaderStripper(CONVENTIONAL_API_KEY_HEADERS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds profile-specific credential headers to the conventional set.
|
||||
*
|
||||
* <p>It adds rather than replaces, which its name always claimed and its behaviour did not. A
|
||||
* profile that named a custom API-key header — {@code X-Client-Key}, say — produced a stripper
|
||||
* that dropped only that one and forwarded {@code X-Api-Key} across an origin boundary, so
|
||||
* configuring a custom header made the default headers <em>less</em> protected than leaving it
|
||||
* alone.
|
||||
*
|
||||
* @param headerNames additional credential-bearing header names, case-insensitive
|
||||
* @return a stripper covering the conventional names plus these
|
||||
*/
|
||||
public static SensitiveHeaderStripper withAdditional(Set<String> headerNames) {
|
||||
return standard().alsoStripping(headerNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* This stripper, also removing the given header names.
|
||||
*
|
||||
|
||||
+33
@@ -2,8 +2,12 @@ package dev.caskeleton.adapter.outbound.httpclient.api.error;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.HttpStatus;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.result.RemoteProblem;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.testkit.CoreFixtures;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class StableExceptionTest {
|
||||
@@ -29,6 +33,35 @@ class StableExceptionTest {
|
||||
.hasCauseInstanceOf(RuntimeException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachStableFailureNamesItsOwnCategoryRatherThanItsClassName() {
|
||||
// given
|
||||
HttpFailureMetadata metadata = CoreFixtures.notSentMetadata();
|
||||
List<HttpClientException> failures =
|
||||
List.of(
|
||||
new HttpDnsException("dns failed", metadata),
|
||||
new HttpTlsException("tls failed", metadata),
|
||||
new HttpDeadlineExceededException("deadline exceeded", metadata),
|
||||
new HttpProblemDetailException(
|
||||
"problem",
|
||||
CoreFixtures.metadataWithStatus(409),
|
||||
RemoteProblem.empty(new HttpStatus(409))),
|
||||
new HttpAmbiguousExecutionException("unknown", metadata));
|
||||
|
||||
// when
|
||||
List<FailureCategory> categories =
|
||||
failures.stream().map(HttpClientException::category).toList();
|
||||
|
||||
// then
|
||||
assertThat(categories)
|
||||
.containsExactly(
|
||||
FailureCategory.DNS,
|
||||
FailureCategory.TLS_PERMANENT,
|
||||
FailureCategory.DEADLINE_EXCEEDED,
|
||||
FailureCategory.REMOTE_STATUS,
|
||||
FailureCategory.UNKNOWN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void remoteErrorExposesWireStatus() {
|
||||
HttpRemoteErrorException exception =
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.httpclient.autoconfigure;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.HttpProtocol;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
@@ -80,7 +81,7 @@ class HttpClientPlatformEnvManifestTest {
|
||||
assertThat(client.baseUrl()).isEqualTo("https://payment.test");
|
||||
assertThat(client.allowedHosts()).containsExactly("payment.test");
|
||||
assertThat(client.allowedPorts()).containsExactly(443);
|
||||
assertThat(client.protocols()).containsExactly("HTTP_2");
|
||||
assertThat(client.protocols()).containsExactly(HttpProtocol.HTTP_2);
|
||||
assertThat(client.request().maxBodyBytes()).isEqualTo(1048576L);
|
||||
assertThat(client.timeout().totalCall()).hasSeconds(6);
|
||||
assertThat(client.tls().profileId()).isEqualTo("payment");
|
||||
|
||||
+6
-3
@@ -3,6 +3,9 @@ package dev.caskeleton.adapter.outbound.httpclient.autoconfigure;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.ClientMode;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.HttpProtocol;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.TransportType;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -102,12 +105,12 @@ class HttpClientPlatformSettingsTest {
|
||||
private static HttpClientPlatformSettings.ClientSettings client(String name) {
|
||||
return new HttpClientPlatformSettings.ClientSettings(
|
||||
name,
|
||||
"TRUSTED",
|
||||
ClientMode.TRUSTED,
|
||||
null,
|
||||
List.of(),
|
||||
List.of(),
|
||||
"APACHE",
|
||||
List.of("HTTP_1_1"),
|
||||
TransportType.APACHE,
|
||||
List.of(HttpProtocol.HTTP_1_1),
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
|
||||
+37
@@ -6,10 +6,13 @@ import static org.assertj.core.api.Assertions.tuple;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.HttpMethod;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.OperationName;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.body.EmptyBody;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.body.ObjectBody;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.body.OneShotStreamBody;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpDeadlineExceededException;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpRedirectRejectedException;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.OperationIdempotency;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.auth.CredentialProviderRegistry;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.profile.ClientMode;
|
||||
@@ -23,8 +26,10 @@ import java.net.InetAddress;
|
||||
import java.net.URI;
|
||||
import java.net.UnknownHostException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalLong;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -155,6 +160,38 @@ class DefaultDynamicTargetGatewayTest {
|
||||
.containsExactly(tuple(true, true), tuple(false, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredDeadlineIsRefusedBeforeAnyHopIsSent() {
|
||||
// given
|
||||
transport.json(200, USER);
|
||||
HttpOperation expired =
|
||||
new HttpOperation(
|
||||
new OperationName("ping"),
|
||||
HttpMethod.GET,
|
||||
"/ping",
|
||||
Map.of(),
|
||||
Map.of(),
|
||||
EmptyBody.instance(),
|
||||
OperationIdempotency.STANDARD_IDEMPOTENT,
|
||||
Optional.empty(),
|
||||
Optional.of(Instant.now().minusSeconds(1)));
|
||||
|
||||
// when
|
||||
Throwable thrown =
|
||||
catchThrowable(
|
||||
() ->
|
||||
gateway(false)
|
||||
.exchange(
|
||||
POLICY,
|
||||
URI.create("https://a.example/ping"),
|
||||
expired,
|
||||
ResponseType.of(UserResponse.class)));
|
||||
|
||||
// then
|
||||
assertThat(List.of(thrown.getClass(), transport.sent().size()))
|
||||
.containsExactly(HttpDeadlineExceededException.class, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void traceHeadersStayOffTheWireWhenThePolicyDisablesPropagation() {
|
||||
// given
|
||||
|
||||
-22
@@ -6,11 +6,9 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.ClientProfileName;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.HttpStatus;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.OperationName;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -62,24 +60,4 @@ class HttpClientTagPolicyTest {
|
||||
assertThat(registry.get(HttpClientObservationNames.RETRY_COUNT).counter().count())
|
||||
.isEqualTo(1.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void safeLogEventCarriesNoSecretOrExpandedUrl() {
|
||||
SafeHttpLogEvent event =
|
||||
new SafeHttpLogEvent(
|
||||
new ClientProfileName("payment"),
|
||||
new OperationName("create-payment"),
|
||||
"POST",
|
||||
"/payments/{id}",
|
||||
Optional.of(new HttpStatus(500)),
|
||||
ExecutionEvidence.RESPONSE_RECEIVED,
|
||||
AttemptStage.RESPONSE_HEADERS,
|
||||
2,
|
||||
Duration.ofMillis(120),
|
||||
Optional.of("trace-1"));
|
||||
assertThat(event.render())
|
||||
.contains("uriTemplate=/payments/{id}")
|
||||
.doesNotContain("https://")
|
||||
.doesNotContain("Bearer");
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test;
|
||||
|
||||
class ExecutionEvidenceClassifierTest {
|
||||
|
||||
private final ExecutionEvidenceClassifier classifier = new DefaultExecutionEvidenceClassifier();
|
||||
private final ExecutionEvidenceClassifier classifier = new ExecutionEvidenceClassifier();
|
||||
|
||||
@Test
|
||||
void poolTimeoutIsNotSent() {
|
||||
|
||||
+1
-1
@@ -43,7 +43,7 @@ class Http2EvidenceMapperTest {
|
||||
0,
|
||||
false);
|
||||
assertThat(
|
||||
new DefaultExecutionEvidenceClassifier()
|
||||
new ExecutionEvidenceClassifier()
|
||||
.classify(progress, mapper.map(Http2ProtocolEvidence.refusedStream(3))))
|
||||
.isEqualTo(
|
||||
dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence.NOT_SENT);
|
||||
|
||||
+7
-7
@@ -26,7 +26,7 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.random.RandomGenerator;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class BlockingRetryCoordinatorTest {
|
||||
class RetryCoordinatorTest {
|
||||
|
||||
private final Clock clock = Clock.fixed(Instant.parse("2026-08-08T00:00:00Z"), ZoneOffset.UTC);
|
||||
|
||||
@@ -37,8 +37,8 @@ class BlockingRetryCoordinatorTest {
|
||||
RecordingSleeper sleeper = new RecordingSleeper();
|
||||
sleeper.onSleep(() -> observedDuringSleep.set(activeAttemptResources.get()));
|
||||
|
||||
BlockingRetryCoordinator coordinator =
|
||||
new BlockingRetryCoordinator(
|
||||
RetryCoordinator coordinator =
|
||||
new RetryCoordinator(
|
||||
new DefaultRetryEligibilityEngine(),
|
||||
new ExponentialFullJitterBackoff(
|
||||
Duration.ofMillis(10),
|
||||
@@ -60,8 +60,8 @@ class BlockingRetryCoordinatorTest {
|
||||
|
||||
@Test
|
||||
void ambiguousOutcomeIsRaisedRatherThanRetried() {
|
||||
BlockingRetryCoordinator coordinator =
|
||||
new BlockingRetryCoordinator(
|
||||
RetryCoordinator coordinator =
|
||||
new RetryCoordinator(
|
||||
new DefaultRetryEligibilityEngine(),
|
||||
(attempts, retryAfter, remaining) -> Duration.ZERO,
|
||||
RetryBudget.unlimited(),
|
||||
@@ -90,8 +90,8 @@ class BlockingRetryCoordinatorTest {
|
||||
return RetryBudgetSnapshot.unlimited();
|
||||
}
|
||||
};
|
||||
BlockingRetryCoordinator coordinator =
|
||||
new BlockingRetryCoordinator(
|
||||
RetryCoordinator coordinator =
|
||||
new RetryCoordinator(
|
||||
new DefaultRetryEligibilityEngine(),
|
||||
(attempts, retryAfter, remaining) -> Duration.ZERO,
|
||||
exhausted,
|
||||
+5
-6
@@ -11,8 +11,8 @@ import dev.caskeleton.adapter.outbound.httpclient.profile.TransportType;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.ResilienceRegistry;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.resilience.RetryEligibilityEngine;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.restclient.BlockingAttemptExecutor;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.restclient.BlockingExecutionSupport;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.restclient.DefaultGenericHttpGateway;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.restclient.ExecutionSupport;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.restclient.GenericHttpGateway;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.restclient.RestClientRuntimeFactory;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.transport.BlockingTransportProvider;
|
||||
@@ -121,8 +121,7 @@ public final class TestGateways {
|
||||
Map<TransportType, BlockingTransportProvider> providers,
|
||||
Optional<RetryEligibilityEngine> eligibility) {
|
||||
MeterRegistry meterRegistry = new SimpleMeterRegistry();
|
||||
BlockingExecutionSupport standard =
|
||||
BlockingExecutionSupport.standard(Clock.systemUTC(), meterRegistry);
|
||||
ExecutionSupport standard = ExecutionSupport.standard(Clock.systemUTC(), meterRegistry);
|
||||
RestClientRuntimeFactory factory =
|
||||
new RestClientRuntimeFactory(
|
||||
providers,
|
||||
@@ -141,9 +140,9 @@ public final class TestGateways {
|
||||
profile);
|
||||
}
|
||||
|
||||
private static BlockingExecutionSupport withEligibility(
|
||||
BlockingExecutionSupport support, RetryEligibilityEngine eligibility) {
|
||||
return new BlockingExecutionSupport(
|
||||
private static ExecutionSupport withEligibility(
|
||||
ExecutionSupport support, RetryEligibilityEngine eligibility) {
|
||||
return new ExecutionSupport(
|
||||
support.clock(),
|
||||
support.meterRegistry(),
|
||||
support.tagPolicy(),
|
||||
|
||||
@@ -613,11 +613,12 @@ holder 가 락을 잡을 수 있다.
|
||||
으로 한 번만 검사하고, 값이 *없으면* Spring Boot 기본(이 스켈레톤은 `application.yml`에서 OSIV off
|
||||
가 기본)에 맡기며 *있는 `true`*만 거부한다.
|
||||
|
||||
### JpaSchemaSafetyValidator
|
||||
- **Flyway를 production physical schema의 유일한 writer로 유지한다.** `prod` profile에서는
|
||||
### JpaDangerousConfigurationGuard (ddl-auto)
|
||||
- **Flyway를 physical schema의 유일한 writer로 유지한다.** local convenience profile만으로 이뤄진
|
||||
profile 집합이 아니면(`prod`, `staging`, profile 없음, `local`+`prod` 혼합 모두)
|
||||
`spring.jpa.hibernate.ddl-auto`가 `none` 또는 `validate`일 때만 허용한다. `update`, `create`,
|
||||
`create-drop` 또는 그 밖의 값이면 `APP_DATASOURCE_DDL_AUTO`를 이름으로 포함한
|
||||
`PROFILE_MISMATCH`로 부팅을 중단한다.
|
||||
- **local 개발 편의와 production 권위를 분리한다.** non-prod profile의 `update`/`create`는 이
|
||||
validator가 막지 않는다. prod profile 비교와 mode 비교는 대소문자를 무시해 `PROD`/`UPDATE`
|
||||
같은 변형도 guard를 우회하지 못한다.
|
||||
`create-drop`, 빈 값, 그 밖의 값이면 `APP_DATASOURCE_DDL_AUTO`를 이름으로 포함한
|
||||
`PROFILE_MISMATCH`로 부팅을 중단한다. mode 비교는 대소문자를 무시한다.
|
||||
- **검사는 이 guard 하나다.** prod만 보던 `JpaSchemaSafetyValidator`는 이 guard보다 늦게 돌아 한
|
||||
번도 발동하지 않았고, 실제 prod 거부는 `PROFILE_MISMATCH`가 아닌 `IllegalStateException`이었다.
|
||||
두 검사를 합치면서 guard가 `PROFILE_MISMATCH`를 던진다.
|
||||
|
||||
+24
-5
@@ -8,17 +8,36 @@ import org.springframework.stereotype.Component;
|
||||
* Core {@link SqlStateErrorMapping}: the portable, vendor-neutral SQLState rows every RDBMS
|
||||
* 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.
|
||||
*/
|
||||
@Component
|
||||
public class StandardSqlStateErrorMapping implements SqlStateErrorMapping {
|
||||
|
||||
/** {@code 40001} serialization_failure. */
|
||||
public static final String SERIALIZATION_FAILURE = "40001";
|
||||
|
||||
/** {@code 23502} not_null_violation. */
|
||||
public static final String NOT_NULL_VIOLATION = "23502";
|
||||
|
||||
/** {@code 23503} foreign_key_violation. */
|
||||
public static final String FOREIGN_KEY_VIOLATION = "23503";
|
||||
|
||||
/** {@code 23505} unique_violation. */
|
||||
public static final String UNIQUE_VIOLATION = "23505";
|
||||
|
||||
/** {@code 23514} check_violation. */
|
||||
public static final String CHECK_VIOLATION = "23514";
|
||||
|
||||
private static final Map<String, OperationalError> MAPPINGS =
|
||||
Map.of(
|
||||
"40001", OperationalError.DB_SERIALIZATION_FAILURE,
|
||||
"23502", OperationalError.DB_NULL_VIOLATION,
|
||||
"23503", OperationalError.DB_FK_VIOLATION,
|
||||
"23505", OperationalError.DB_UNIQUE_VIOLATION,
|
||||
"23514", OperationalError.DB_CHECK_VIOLATION);
|
||||
SERIALIZATION_FAILURE, OperationalError.DB_SERIALIZATION_FAILURE,
|
||||
NOT_NULL_VIOLATION, OperationalError.DB_NULL_VIOLATION,
|
||||
FOREIGN_KEY_VIOLATION, OperationalError.DB_FK_VIOLATION,
|
||||
UNIQUE_VIOLATION, OperationalError.DB_UNIQUE_VIOLATION,
|
||||
CHECK_VIOLATION, OperationalError.DB_CHECK_VIOLATION);
|
||||
|
||||
@Override
|
||||
public Map<String, OperationalError> exactMappings() {
|
||||
|
||||
+12
-3
@@ -4,9 +4,9 @@ import dev.caskeleton.adapter.outbound.persistence.operation.entity.DurableOpera
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.Repository;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
/**
|
||||
@@ -22,8 +22,17 @@ import org.springframework.data.repository.query.Param;
|
||||
* able to record a result over the worker that took over; the update simply matches nothing, and
|
||||
* the caller learns it lost the lease from the count.
|
||||
*/
|
||||
public interface DurableOperationJpaRepository
|
||||
extends JpaRepository<DurableOperationEntity, String> {
|
||||
public interface DurableOperationJpaRepository extends Repository<DurableOperationEntity, String> {
|
||||
|
||||
/**
|
||||
* Reads the row a worker has just claimed.
|
||||
*
|
||||
* <p>Not tenant-scoped on purpose: the claim itself picked the row across tenants, and this reads
|
||||
* back only the id the claim returned. There is no {@code findAll} or {@code deleteAll} here —
|
||||
* the rows belong to tenants, and a bulk statement without a tenant in it has no caller that is
|
||||
* entitled to it.
|
||||
*/
|
||||
Optional<DurableOperationEntity> findById(String operationId);
|
||||
|
||||
/** Reads an operation a specific caller is entitled to see. */
|
||||
Optional<DurableOperationEntity> findByOperationIdAndPrincipal(
|
||||
|
||||
+9
-4
@@ -1,21 +1,26 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.postgresql;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* PostgreSQL-specific {@link SqlStateErrorMapping} contributing vendor-only SQLState codes. See the
|
||||
* module README for the code/category/retryable table.
|
||||
*
|
||||
* <p>The codes come from {@link PostgreSqlState}, the one PostgreSQL SQLSTATE table; this class
|
||||
* only says which of them become which operational error.
|
||||
*/
|
||||
public class PostgreSqlSqlStateErrorMapping implements SqlStateErrorMapping {
|
||||
|
||||
private static final Map<String, OperationalError> MAPPINGS =
|
||||
Map.of(
|
||||
"40P01", OperationalError.DB_DEADLOCK,
|
||||
"55P03", OperationalError.DB_LOCK_TIMEOUT,
|
||||
"25P03", OperationalError.DB_IDLE_IN_TX_TIMEOUT,
|
||||
"57014", OperationalError.DB_QUERY_CANCELED);
|
||||
PostgreSqlState.DEADLOCK_DETECTED.code(), OperationalError.DB_DEADLOCK,
|
||||
PostgreSqlState.LOCK_NOT_AVAILABLE.code(), OperationalError.DB_LOCK_TIMEOUT,
|
||||
PostgreSqlState.IDLE_IN_TRANSACTION_TIMEOUT.code(),
|
||||
OperationalError.DB_IDLE_IN_TX_TIMEOUT,
|
||||
PostgreSqlState.QUERY_CANCELED.code(), OperationalError.DB_QUERY_CANCELED);
|
||||
|
||||
@Override
|
||||
public Map<String, OperationalError> exactMappings() {
|
||||
|
||||
+11
-5
@@ -1,5 +1,6 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.postgresql.error;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -11,11 +12,16 @@ import java.util.stream.Stream;
|
||||
* <p>SQLSTATE is the contract, not the message. Server messages are localized and reworded between
|
||||
* releases, so a classifier that matches on text is a classifier that silently stops working after
|
||||
* an upgrade or on a server with a different {@code lc_messages}.
|
||||
*
|
||||
* <p>This enum is the PostgreSQL SQLSTATE table: the classifier, the lock translator and {@link
|
||||
* dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlSqlStateErrorMapping} all read
|
||||
* their codes from it. The SQL-standard members take theirs from {@link
|
||||
* StandardSqlStateErrorMapping}, so no code is spelled twice.
|
||||
*/
|
||||
public enum PostgreSqlState {
|
||||
|
||||
/** {@code 40001} serialization_failure. */
|
||||
SERIALIZATION_FAILURE("40001"),
|
||||
SERIALIZATION_FAILURE(StandardSqlStateErrorMapping.SERIALIZATION_FAILURE),
|
||||
|
||||
/** {@code 40003} statement_completion_unknown. */
|
||||
STATEMENT_COMPLETION_UNKNOWN("40003"),
|
||||
@@ -24,16 +30,16 @@ public enum PostgreSqlState {
|
||||
DEADLOCK_DETECTED("40P01"),
|
||||
|
||||
/** {@code 23505} unique_violation. */
|
||||
UNIQUE_VIOLATION("23505"),
|
||||
UNIQUE_VIOLATION(StandardSqlStateErrorMapping.UNIQUE_VIOLATION),
|
||||
|
||||
/** {@code 23503} foreign_key_violation. */
|
||||
FOREIGN_KEY_VIOLATION("23503"),
|
||||
FOREIGN_KEY_VIOLATION(StandardSqlStateErrorMapping.FOREIGN_KEY_VIOLATION),
|
||||
|
||||
/** {@code 23514} check_violation. */
|
||||
CHECK_VIOLATION("23514"),
|
||||
CHECK_VIOLATION(StandardSqlStateErrorMapping.CHECK_VIOLATION),
|
||||
|
||||
/** {@code 23502} not_null_violation. */
|
||||
NOT_NULL_VIOLATION("23502"),
|
||||
NOT_NULL_VIOLATION(StandardSqlStateErrorMapping.NOT_NULL_VIOLATION),
|
||||
|
||||
/** {@code 55P03} lock_not_available. */
|
||||
LOCK_NOT_AVAILABLE("55P03"),
|
||||
|
||||
+1
-5
@@ -24,7 +24,7 @@ class FlywayProdSafetyValidator implements SmartInitializingSingleton {
|
||||
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
if (!isProdActive()) {
|
||||
if (!RuntimeProfileSnapshot.from(environment).isProduction()) {
|
||||
return;
|
||||
}
|
||||
StartupValidationContext violations =
|
||||
@@ -53,8 +53,4 @@ class FlywayProdSafetyValidator implements SmartInitializingSingleton {
|
||||
String value = environment.getProperty(key);
|
||||
return value != null && "false".equalsIgnoreCase(value.trim());
|
||||
}
|
||||
|
||||
private boolean isProdActive() {
|
||||
return RuntimeProfileSnapshot.from(environment).isProduction();
|
||||
}
|
||||
}
|
||||
|
||||
+21
-3
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.persistence.startup;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy;
|
||||
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import org.springframework.core.env.Environment;
|
||||
@@ -13,7 +14,8 @@ import org.springframework.core.env.Environment;
|
||||
* <p>{@code update} never drops or narrows anything, so it produces a schema that is neither the
|
||||
* old one nor the one the migrations describe — and it does so silently, on whichever instance
|
||||
* starts first. This guard holds the whole non-local profile set to that rule, so a staging
|
||||
* deployment is held to the same rule as production.
|
||||
* deployment is held to the same rule as production. It is the only {@code ddl-auto} check; the
|
||||
* production-only copy that ran after it, and so never fired, is gone.
|
||||
*
|
||||
* <p>Open Session In View is not checked here. {@link OpenInViewSafetyValidator} refuses it in
|
||||
* every profile, local included; the local exception this guard used to carry could never be
|
||||
@@ -24,6 +26,9 @@ final class JpaDangerousConfigurationGuard {
|
||||
/** The property that decides whether Hibernate may change the schema. */
|
||||
public static final String DDL_AUTO_KEY = "spring.jpa.hibernate.ddl-auto";
|
||||
|
||||
/** The environment variable operators set it through. */
|
||||
static final String DDL_AUTO_ENV_KEY = "APP_DATASOURCE_DDL_AUTO";
|
||||
|
||||
private final JpaSafetySettings safety;
|
||||
private final FlywaySchemaPolicy schemaPolicy;
|
||||
|
||||
@@ -35,13 +40,26 @@ final class JpaDangerousConfigurationGuard {
|
||||
/**
|
||||
* Validates the resolved environment.
|
||||
*
|
||||
* @throws IllegalStateException naming the unsafe property and the approved alternatives
|
||||
* @throws dev.caskeleton.adapter.outbound.support.startup.ProfileMismatchException naming the
|
||||
* unsafe property, its environment key and the approved alternatives
|
||||
*/
|
||||
public void validate(Environment environment) {
|
||||
Objects.requireNonNull(environment, "environment");
|
||||
String ddlAuto = environment.getProperty(DDL_AUTO_KEY);
|
||||
if (ddlAuto != null && !isLocalConvenience(environment)) {
|
||||
if (ddlAuto == null || isLocalConvenience(environment)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
schemaPolicy.requirePermittedDdlAuto(ddlAuto);
|
||||
} catch (IllegalStateException refused) {
|
||||
// A profile mismatch, not a generic failure: the value is fine for local convenience and
|
||||
// wrong for this profile set, and operators key the exit code and runbook on that category.
|
||||
throw StartupFailures.profileMismatch(
|
||||
DDL_AUTO_ENV_KEY
|
||||
+ " ("
|
||||
+ DDL_AUTO_KEY
|
||||
+ ") must be none or validate outside a local convenience profile: "
|
||||
+ refused.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-54
@@ -1,54 +0,0 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.startup;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
/**
|
||||
* Prevents Hibernate from becoming a production schema writer. Flyway owns the physical schema;
|
||||
* production may only disable Hibernate DDL or validate the schema.
|
||||
*/
|
||||
class JpaSchemaSafetyValidator implements SmartInitializingSingleton {
|
||||
|
||||
static final String DDL_AUTO_KEY = "spring.jpa.hibernate.ddl-auto";
|
||||
static final String DDL_AUTO_ENV_KEY = "APP_DATASOURCE_DDL_AUTO";
|
||||
|
||||
private static final Set<String> PROD_ALLOWED_MODES = Set.of("none", "validate");
|
||||
|
||||
private final Environment environment;
|
||||
|
||||
public JpaSchemaSafetyValidator(Environment environment) {
|
||||
this.environment = environment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
if (!isProdActive()) {
|
||||
return;
|
||||
}
|
||||
|
||||
String rawMode = environment.getProperty(DDL_AUTO_KEY);
|
||||
if (rawMode == null) {
|
||||
return;
|
||||
}
|
||||
String mode = rawMode.trim().toLowerCase(Locale.ROOT);
|
||||
if (!PROD_ALLOWED_MODES.contains(mode)) {
|
||||
throw StartupFailures.profileMismatch(
|
||||
"prod profile requires "
|
||||
+ DDL_AUTO_ENV_KEY
|
||||
+ " ("
|
||||
+ DDL_AUTO_KEY
|
||||
+ ") to be none or validate"
|
||||
+ ", but was "
|
||||
+ (mode.isEmpty() ? "<blank>" : mode)
|
||||
+ "; Flyway is the production schema writer");
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isProdActive() {
|
||||
return RuntimeProfileSnapshot.from(environment).isProduction();
|
||||
}
|
||||
}
|
||||
-5
@@ -73,11 +73,6 @@ class JpaStartupAutoConfiguration {
|
||||
return new OpenInViewSafetyValidator(environment);
|
||||
}
|
||||
|
||||
@Bean
|
||||
JpaSchemaSafetyValidator jpaSchemaSafetyValidator(Environment environment) {
|
||||
return new JpaSchemaSafetyValidator(environment);
|
||||
}
|
||||
|
||||
@Bean
|
||||
PostgreSqlTransportSecurityValidator postgreSqlTransportSecurityValidator(
|
||||
Environment environment) {
|
||||
|
||||
+1
-5
@@ -47,7 +47,7 @@ final class PersistenceVendorProdSafetyValidator implements SmartInitializingSin
|
||||
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
if (!isProdActive()) {
|
||||
if (!RuntimeProfileSnapshot.from(environment).isProduction()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -77,8 +77,4 @@ final class PersistenceVendorProdSafetyValidator implements SmartInitializingSin
|
||||
private static String normalized(String value) {
|
||||
return value == null ? null : value.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private boolean isProdActive() {
|
||||
return RuntimeProfileSnapshot.from(environment).isProduction();
|
||||
}
|
||||
}
|
||||
|
||||
+1
-5
@@ -35,7 +35,7 @@ final class PostgreSqlTransportSecurityValidator implements SmartInitializingSin
|
||||
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
if (!isProdActive()) {
|
||||
if (!RuntimeProfileSnapshot.from(environment).isProduction()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -82,8 +82,4 @@ final class PostgreSqlTransportSecurityValidator implements SmartInitializingSin
|
||||
private static void reject(String message) {
|
||||
throw StartupFailures.profileMismatch(message);
|
||||
}
|
||||
|
||||
private boolean isProdActive() {
|
||||
return RuntimeProfileSnapshot.from(environment).isProduction();
|
||||
}
|
||||
}
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.operation;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* {@code durable_operation} rows belong to a tenant, so its repository offers no statement that
|
||||
* reads or deletes across tenants.
|
||||
*
|
||||
* <p>Extending {@code JpaRepository} used to put {@code findAll} and {@code deleteAll} on the one
|
||||
* interface every caller holds: nothing in the adapter used them, and nothing stopped the next
|
||||
* caller from doing so.
|
||||
*/
|
||||
class DurableOperationJpaRepositoryShapeTest {
|
||||
|
||||
private static final Set<String> UNSCOPED_BULK_METHODS =
|
||||
Set.of(
|
||||
"findAll",
|
||||
"findAllById",
|
||||
"deleteAll",
|
||||
"deleteAllById",
|
||||
"deleteAllInBatch",
|
||||
"deleteAllByIdInBatch",
|
||||
"count");
|
||||
|
||||
@Test
|
||||
void repositoryExposesNoUnscopedBulkReadOrDelete() {
|
||||
// when
|
||||
List<String> exposed =
|
||||
Arrays.stream(DurableOperationJpaRepository.class.getMethods())
|
||||
.map(Method::getName)
|
||||
.filter(UNSCOPED_BULK_METHODS::contains)
|
||||
.distinct()
|
||||
.toList();
|
||||
|
||||
// then
|
||||
assertThat(exposed).isEmpty();
|
||||
}
|
||||
}
|
||||
+18
@@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator;
|
||||
import dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping;
|
||||
import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping;
|
||||
import dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlState;
|
||||
import dev.caskeleton.shared.error.Category;
|
||||
import dev.caskeleton.shared.error.OperationalError;
|
||||
import dev.caskeleton.shared.error.PersistenceFailureException;
|
||||
@@ -12,6 +13,7 @@ import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
@@ -35,6 +37,22 @@ class PostgreSqlSqlStateErrorMappingTest {
|
||||
assertThat(codes).containsOnlyKeys("40P01", "55P03", "25P03", "57014");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyCodeAPostgreSqlDeploymentMapsIsAStateOfTheOnePostgreSqlTable() {
|
||||
// given
|
||||
Stream<String> mapped =
|
||||
Stream.concat(
|
||||
new StandardSqlStateErrorMapping().exactMappings().keySet().stream(),
|
||||
pgMapping.exactMappings().keySet().stream());
|
||||
|
||||
// when
|
||||
List<String> unclassified =
|
||||
mapped.filter(code -> PostgreSqlState.fromCode(code).isEmpty()).toList();
|
||||
|
||||
// then
|
||||
assertThat(unclassified).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deadlock40P01MapsToDbDeadlockConflictRetryable() {
|
||||
Optional<PersistenceFailureException> result = translator.translate(daoWithSqlState("40P01"));
|
||||
|
||||
+94
-25
@@ -1,17 +1,23 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.startup;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy;
|
||||
import java.util.Set;
|
||||
import dev.caskeleton.adapter.outbound.support.startup.ProfileMismatchException;
|
||||
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.mock.env.MockEnvironment;
|
||||
|
||||
/**
|
||||
* Plan Task 11 — a schema-mutating {@code ddl-auto} fails startup outside a local convenience
|
||||
* The one {@code ddl-auto} check: a schema-mutating value fails startup outside a local convenience
|
||||
* profile (design §31). Open Session In View is {@link OpenInViewSafetyValidatorTest}'s.
|
||||
*
|
||||
* <p>{@code JpaSchemaSafetyValidator} used to repeat this for {@code prod} alone. It ran after this
|
||||
* guard, so it never fired, and the refusal a production deployment actually got was a plain {@code
|
||||
* IllegalStateException} rather than the documented {@code PROFILE_MISMATCH}.
|
||||
*/
|
||||
class JpaDangerousConfigurationGuardTest {
|
||||
|
||||
@@ -19,59 +25,122 @@ class JpaDangerousConfigurationGuardTest {
|
||||
new JpaDangerousConfigurationGuard(
|
||||
JpaSafetySettings.defaults(), FlywaySchemaPolicy.standard());
|
||||
|
||||
@Test
|
||||
void productionRejectsASchemaMutatingDdlAuto() {
|
||||
MockEnvironment ddlUpdate = environment("prod");
|
||||
ddlUpdate.setProperty(JpaDangerousConfigurationGuard.DDL_AUTO_KEY, "update");
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"update", "create", "create-drop"})
|
||||
void productionRefusesASchemaMutatingDdlAutoAsAProfileMismatchNamingTheEnvironmentKey(
|
||||
String ddlAuto) {
|
||||
// given
|
||||
MockEnvironment production = environment("prod");
|
||||
production.setProperty(JpaDangerousConfigurationGuard.DDL_AUTO_KEY, ddlAuto);
|
||||
|
||||
assertThatThrownBy(() -> guard.validate(ddlUpdate))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> guard.validate(production));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(ProfileMismatchException.class)
|
||||
.hasMessageContaining("APP_DATASOURCE_DDL_AUTO")
|
||||
.hasMessageContaining("Flyway owns schema change");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {" ", "\t"})
|
||||
void productionRefusesAPresentButBlankDdlAuto(String ddlAuto) {
|
||||
// given
|
||||
MockEnvironment production = environment("prod");
|
||||
production.setProperty(JpaDangerousConfigurationGuard.DDL_AUTO_KEY, ddlAuto);
|
||||
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> guard.validate(production));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(ProfileMismatchException.class)
|
||||
.hasMessageContaining("APP_DATASOURCE_DDL_AUTO");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"PROD", "Prod"})
|
||||
void productionProfileAndDdlAutoAreComparedIgnoringCase(String profile) {
|
||||
// given
|
||||
MockEnvironment production = environment(profile);
|
||||
production.setProperty(JpaDangerousConfigurationGuard.DDL_AUTO_KEY, "UPDATE");
|
||||
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> guard.validate(production));
|
||||
|
||||
// then
|
||||
assertThat(thrown).isInstanceOf(ProfileMismatchException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("staging is held to the same rule as production")
|
||||
void stagingIsHeldToTheSameRule() {
|
||||
// given
|
||||
MockEnvironment staging = environment("staging");
|
||||
staging.setProperty(JpaDangerousConfigurationGuard.DDL_AUTO_KEY, "update");
|
||||
|
||||
assertThatThrownBy(() -> guard.validate(staging)).isInstanceOf(IllegalStateException.class);
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> guard.validate(staging));
|
||||
|
||||
// then
|
||||
assertThat(thrown).isInstanceOf(ProfileMismatchException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void localConvenienceProfileMayUseASchemaMutatingDdlAuto() {
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"update", "create"})
|
||||
void localConvenienceProfileMayUseASchemaMutatingDdlAuto(String ddlAuto) {
|
||||
// given
|
||||
MockEnvironment local = environment("local");
|
||||
local.setProperty(JpaDangerousConfigurationGuard.DDL_AUTO_KEY, "update");
|
||||
local.setProperty(JpaDangerousConfigurationGuard.DDL_AUTO_KEY, ddlAuto);
|
||||
|
||||
assertThatCode(() -> guard.validate(local)).doesNotThrowAnyException();
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> guard.validate(local));
|
||||
|
||||
// then
|
||||
assertThat(thrown).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a profile set mixing local and production is not local convenience")
|
||||
void mixedProfileSetIsNotLocalConvenience() {
|
||||
// given
|
||||
MockEnvironment mixed = environment("local", "prod");
|
||||
mixed.setProperty(JpaDangerousConfigurationGuard.DDL_AUTO_KEY, "update");
|
||||
|
||||
assertThatThrownBy(() -> guard.validate(mixed)).isInstanceOf(IllegalStateException.class);
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> guard.validate(mixed));
|
||||
|
||||
// then
|
||||
assertThat(thrown).isInstanceOf(ProfileMismatchException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("no active profile is not local convenience either")
|
||||
void noActiveProfileIsNotLocalConvenience() {
|
||||
// given
|
||||
MockEnvironment none = new MockEnvironment();
|
||||
none.setProperty(JpaDangerousConfigurationGuard.DDL_AUTO_KEY, "update");
|
||||
|
||||
assertThatThrownBy(() -> guard.validate(none)).isInstanceOf(IllegalStateException.class);
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> guard.validate(none));
|
||||
|
||||
// then
|
||||
assertThat(thrown).isInstanceOf(ProfileMismatchException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("validate and none are permitted everywhere")
|
||||
void permittedDdlAutoValuesPass() {
|
||||
for (String permitted : Set.of("validate", "none")) {
|
||||
MockEnvironment production = environment("prod");
|
||||
production.setProperty(JpaDangerousConfigurationGuard.DDL_AUTO_KEY, permitted);
|
||||
assertThatCode(() -> guard.validate(production)).doesNotThrowAnyException();
|
||||
}
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"validate", "none"})
|
||||
void productionPermitsTheDdlAutoValuesThatLeaveTheSchemaToFlyway(String permitted) {
|
||||
// given
|
||||
MockEnvironment production = environment("prod");
|
||||
production.setProperty(JpaDangerousConfigurationGuard.DDL_AUTO_KEY, permitted);
|
||||
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> guard.validate(production));
|
||||
|
||||
// then
|
||||
assertThat(thrown).isNull();
|
||||
}
|
||||
|
||||
private static MockEnvironment environment(String... profiles) {
|
||||
|
||||
-91
@@ -1,91 +0,0 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.startup;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.startup.ProfileMismatchException;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
class JpaSchemaSafetyValidatorTest {
|
||||
|
||||
private final ApplicationContextRunner runner =
|
||||
new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class);
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"update", "create", "create-drop"})
|
||||
void prodRejectsHibernateSchemaMutationModes(String ddlAuto) {
|
||||
runner
|
||||
.withInitializer(context -> context.getEnvironment().setActiveProfiles("prod"))
|
||||
.withPropertyValues("spring.jpa.hibernate.ddl-auto=" + ddlAuto)
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasFailed();
|
||||
assertThat(context.getStartupFailure())
|
||||
.isInstanceOf(ProfileMismatchException.class)
|
||||
.hasStackTraceContaining("APP_DATASOURCE_DDL_AUTO")
|
||||
.hasStackTraceContaining("none")
|
||||
.hasStackTraceContaining("validate");
|
||||
});
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"none", "validate"})
|
||||
void prodAllowsNonMutatingSchemaModes(String ddlAuto) {
|
||||
runner
|
||||
.withInitializer(context -> context.getEnvironment().setActiveProfiles("prod"))
|
||||
.withPropertyValues("spring.jpa.hibernate.ddl-auto=" + ddlAuto)
|
||||
.run(context -> assertThat(context).hasNotFailed());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {" ", "\t"})
|
||||
void prodRejectsPresentButBlankDdlMode(String ddlAuto) {
|
||||
runner
|
||||
.withInitializer(context -> context.getEnvironment().setActiveProfiles("prod"))
|
||||
.withPropertyValues("spring.jpa.hibernate.ddl-auto=" + ddlAuto)
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasFailed();
|
||||
assertThat(context.getStartupFailure())
|
||||
.isInstanceOf(ProfileMismatchException.class)
|
||||
.hasStackTraceContaining("APP_DATASOURCE_DDL_AUTO");
|
||||
});
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"update", "create"})
|
||||
void nonProdMayUseLocalSchemaConvenienceModes(String ddlAuto) {
|
||||
runner
|
||||
.withInitializer(context -> context.getEnvironment().setActiveProfiles("local"))
|
||||
.withPropertyValues("spring.jpa.hibernate.ddl-auto=" + ddlAuto)
|
||||
.run(context -> assertThat(context).hasNotFailed());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"PROD", "Prod"})
|
||||
void profileAndDdlModeComparisonIsCaseInsensitive(String profile) {
|
||||
runner
|
||||
.withInitializer(context -> context.getEnvironment().setActiveProfiles(profile))
|
||||
.withPropertyValues("spring.jpa.hibernate.ddl-auto=UPDATE")
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasFailed();
|
||||
assertThat(context.getStartupFailure())
|
||||
.isInstanceOf(ProfileMismatchException.class)
|
||||
.hasStackTraceContaining("APP_DATASOURCE_DDL_AUTO");
|
||||
});
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class ValidatorConfig {
|
||||
|
||||
@Bean
|
||||
JpaSchemaSafetyValidator jpaSchemaSafetyValidator(Environment environment) {
|
||||
return new JpaSchemaSafetyValidator(environment);
|
||||
}
|
||||
}
|
||||
}
|
||||
-1
@@ -44,7 +44,6 @@ class JpaStartupAutoConfigurationTest {
|
||||
.hasSingleBean(JpaPlatformEndpoint.class)
|
||||
.hasSingleBean(JpaSafetySettings.class)
|
||||
.hasSingleBean(OpenInViewSafetyValidator.class)
|
||||
.hasSingleBean(JpaSchemaSafetyValidator.class)
|
||||
.hasSingleBean(PostgreSqlTransportSecurityValidator.class)
|
||||
.hasSingleBean(PersistenceVendorProdSafetyValidator.class)
|
||||
.hasSingleBean(HikariPoolConstraintValidator.class)
|
||||
|
||||
@@ -151,7 +151,7 @@ README의 "startup" 절에 있다.
|
||||
"PROD"를 통과시킨다).
|
||||
|
||||
관계형 설정 가드(`HikariPoolConstraintValidator`, `OpenInViewSafetyValidator`,
|
||||
`JpaSchemaSafetyValidator`, `PostgreSqlTransportSecurityValidator`,
|
||||
`JpaDangerousConfigurationGuard`, `PostgreSqlTransportSecurityValidator`,
|
||||
`PersistenceVendorProdSafetyValidator`)는 `adapter:outbound:persistence-jpa`로 옮겼다. 풀 크기
|
||||
하한(`APP_DATASOURCE_POOL_MAX_SIZE >= 1`, `APP_DATASOURCE_POOL_MIN_IDLE >= 0`)도 이제 그쪽
|
||||
`HikariPoolConstraintValidator`가 검사한다.
|
||||
|
||||
+1
-5
@@ -69,7 +69,7 @@ public class SecretSourceValidator implements SmartInitializingSingleton {
|
||||
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
if (!isProdActive()) {
|
||||
if (!RuntimeProfileSnapshot.from(environment).isProduction()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -172,10 +172,6 @@ public class SecretSourceValidator implements SmartInitializingSingleton {
|
||||
return selecting.equalsIgnoreCase(environment.getProperty(property, fallback));
|
||||
}
|
||||
|
||||
private boolean isProdActive() {
|
||||
return RuntimeProfileSnapshot.from(environment).isProduction();
|
||||
}
|
||||
|
||||
private boolean isRelationalPersistenceOn() {
|
||||
return Boolean.parseBoolean(
|
||||
environment.getProperty(RELATIONAL_PERSISTENCE_PROPERTY, "false").trim());
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package dev.caskeleton.application.outbound;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A {@code secret://<source>/<name>} reference, the one spelling capabilities use to name a secret
|
||||
* in configuration instead of carrying its value.
|
||||
*
|
||||
* <p>Only {@link #name()} reaches {@link SecretSourcePort#resolve(String)}: which backend holds the
|
||||
* secret is deployment policy, so the source segment is informational and may be omitted ({@code
|
||||
* secret://<name>}). Every capability used to parse this itself, and the copies had drifted — one
|
||||
* accepted a reference whose name was blank and passed an empty key to the port.
|
||||
*
|
||||
* @param source the source segment, empty when the reference names none
|
||||
* @param name the non-blank secret key handed to {@link SecretSourcePort}
|
||||
*/
|
||||
public record SecretReference(String source, String name) {
|
||||
|
||||
/** The scheme every secret reference starts with. */
|
||||
public static final String SCHEME = "secret://";
|
||||
|
||||
public SecretReference {
|
||||
Objects.requireNonNull(source, "source");
|
||||
Objects.requireNonNull(name, "name");
|
||||
if (name.isBlank()) {
|
||||
throw new IllegalArgumentException("a secret reference must name a secret");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the value is written as a secret reference rather than as a plain key.
|
||||
*
|
||||
* @param value a configured value, possibly null
|
||||
* @return true when it starts with {@link #SCHEME}
|
||||
*/
|
||||
public static boolean isReference(String value) {
|
||||
return value != null && value.startsWith(SCHEME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses {@code secret://<source>/<name>} or {@code secret://<name>}.
|
||||
*
|
||||
* @param reference the configured reference
|
||||
* @return the parsed reference
|
||||
* @throws IllegalArgumentException when the value is not a reference or names no secret
|
||||
*/
|
||||
public static SecretReference parse(String reference) {
|
||||
if (!isReference(reference)) {
|
||||
throw new IllegalArgumentException(
|
||||
"a secret reference must have the form " + SCHEME + "<source>/<name>");
|
||||
}
|
||||
String path = reference.substring(SCHEME.length());
|
||||
int separator = path.lastIndexOf('/');
|
||||
return separator < 0
|
||||
? new SecretReference("", path)
|
||||
: new SecretReference(path.substring(0, separator), path.substring(separator + 1));
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package dev.caskeleton.application.outbound;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SecretReferenceTest {
|
||||
|
||||
@Test
|
||||
void referenceWithSourceSplitsIntoSourceAndName() {
|
||||
// when
|
||||
SecretReference reference = SecretReference.parse("secret://vault/payment-api-key");
|
||||
|
||||
// then
|
||||
assertThat(reference).isEqualTo(new SecretReference("vault", "payment-api-key"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void referenceWithoutSourceKeepsTheWholePathAsName() {
|
||||
// when
|
||||
SecretReference reference = SecretReference.parse("secret://payment-api-key");
|
||||
|
||||
// then
|
||||
assertThat(reference).isEqualTo(new SecretReference("", "payment-api-key"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void referenceWhoseNameIsBlankIsRejected() {
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> SecretReference.parse("secret://vault/"));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage("a secret reference must name a secret");
|
||||
}
|
||||
|
||||
@Test
|
||||
void valueWithoutTheSchemeIsNotAReference() {
|
||||
// when
|
||||
Throwable thrown = catchThrowable(() -> SecretReference.parse("payment-api-key"));
|
||||
|
||||
// then
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage("a secret reference must have the form secret://<source>/<name>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlySchemePrefixedValuesAreReferences() {
|
||||
assertThat(SecretReference.isReference("secret://a/b")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullAndPlainValuesAreNotReferences() {
|
||||
// when
|
||||
boolean nullIsReference = SecretReference.isReference(null);
|
||||
boolean plainIsReference = SecretReference.isReference("plain-key");
|
||||
|
||||
// then
|
||||
assertThat(new boolean[] {nullIsReference, plainIsReference}).containsExactly(false, false);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user