refactor: 부가 기능을 capability 모듈로 포장하고 기본 조립을 web-only로 전환

설계: docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md
계획/진행 기록: docs/superpowers/plans/2026-09-25-capability-module-packaging.md

- Wave 0: 규칙 고정(AGENTS.md capability 완료 기준·테스트 규칙) + 차단 결함 7건
  (compose overlay 검사, redis-sdk CI job, 적용된 V9/V13 원복 + V16, @EnableScheduling,
  messaging bridge 순서, prod 에러 상세 validator, sample loggers read-only)
- Wave 1: 데이터·보안 Critical 10건 (durable operation 25P02, operation 유스케이스 이동,
  outbox 재인코딩, Kafka TLS/SASL, 알림 트랜잭션, SNS 서명, tus checksum, GraphQL fragment,
  Redis lane, gRPC FAILED_TERMINAL)
- Wave 2: 리팩터링 잔재·실험용 자리 삭제, outbox v1 fencing(V17), 멱등성 V2 정본화
- Wave 3: 라이브러리형 코드 정리(동작하지 않는 설정·인터페이스·gate 제거, web-advanced 분리)
- Wave 4: capability 11개를 "있으면 켜짐" 모듈로 포장, 끄는 장치 제거, 기본 조립 web-only,
  qualificationBootJar 분리
- Wave 5: 빌드 로직 축소(17.2k -> 10.8k줄), sample 테스트 컨벤션 적용

삭제한 코드는 docs/capability-status.md "제거된 코드" 표에 복구 커밋(208077fd)과 함께 기록.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-25 12:49:07 +09:00
co-authored by Claude Opus 5.5
parent 208077fddf
commit 6d27356e2b
2822 changed files with 27992 additions and 166879 deletions
+17 -58
View File
@@ -123,7 +123,9 @@ APP_RATE_LIMIT_REFILL_PERIOD=1s
APP_RATE_LIMIT_MAXIMUM_COST=10
APP_RATE_LIMIT_CLEANUP_GRACE=5s
APP_IDEMPOTENCY_TTL=24h
APP_IDEMPOTENCY_PROVIDER=jdbc
# disabled | redis | postgresql. postgresql refuses a non-PostgreSQL data source, so bootRunH2
# runs with disabled or redis.
APP_IDEMPOTENCY_PROVIDER=disabled
APP_IDEMPOTENCY_REDIS_NAMESPACE_ENVIRONMENT=local
APP_IDEMPOTENCY_PROCESSING_LEASE=30s
APP_IDEMPOTENCY_FAILURE_RETENTION=24h
@@ -131,7 +133,7 @@ APP_LEASE_PROVIDER=disabled
APP_LEASE_REDIS_NAMESPACE_ENVIRONMENT=local
APP_LEASE_REDIS_DRIFT_BUDGET=10ms
APP_CACHE_CANONICAL_DEFAULT_PROVIDER=disabled
APP_REDIS_ENABLED=false
APP_REDIS_ENABLED=true
APP_CACHE_REDIS_POSITIVE_HARD_TTL=5m
APP_CACHE_REDIS_NEGATIVE_TTL=10s
APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT=200ms
@@ -139,33 +141,14 @@ APP_LEASE_REDIS_COMMAND_TIMEOUT=200ms
APP_LEASE_REDIS_CONTENTION_RETRY_AFTER=50ms
APP_REDIS_ADMIN_CREDENTIAL_REFERENCE=
APP_REDIS_ADMIN_ENABLED=false
APP_REDIS_ADVANCED_ENABLED=false
APP_REDIS_ADVANCED_POLICIES=
APP_REDIS_BLOCKING_MAX_BLOCK=30s
APP_REDIS_BLOCKING_MAX_CONNECTIONS=32
APP_REDIS_DATABASE=0
APP_REDIS_LIMITS_MAX_BATCH_COMMANDS=500
APP_REDIS_LIMITS_MAX_BATCH_REPLY_BYTES=16777216
APP_REDIS_LIMITS_MAX_BATCH_REQUEST_BYTES=4194304
APP_REDIS_LIMITS_MAX_BITMAP_OFFSET=10000000
APP_REDIS_LIMITS_MAX_COLLECTION_ELEMENTS=1000
APP_REDIS_LIMITS_MAX_HASH_FIELD_VALUE_BYTES=524288
APP_REDIS_LIMITS_MAX_KEY_BYTES=512
APP_REDIS_LIMITS_MAX_SCAN_COUNT=500
APP_REDIS_LIMITS_MAX_STREAM_PAYLOAD_BYTES=262144
APP_REDIS_LIMITS_MAX_VALUE_BYTES=1048576
APP_REDIS_LIMITS_OFFLINE_QUEUE_COMMANDS=1000
APP_REDIS_MODE=standalone
APP_REDIS_NAMESPACE_DOMAIN=shared
APP_REDIS_NAMESPACE_ENVIRONMENT=local
APP_REDIS_NAMESPACE_SERVICE=sample-service
APP_REDIS_NODES=localhost:6379
APP_REDIS_RAW_CREDENTIAL_REFERENCE=
APP_REDIS_RAW_ENABLED=false
APP_REDIS_RAW_POLICY_RESOURCE=classpath:redis-sdk/raw-command-allowlist.yml
APP_REDIS_TIMEOUT_ADMIN=3s
APP_REDIS_TIMEOUT_BATCH=2s
APP_REDIS_TIMEOUT_COLLECTION=2s
APP_REDIS_TIMEOUT_FAST=500ms
APP_REDIS_TIMEOUT_SCRIPT=1s
APP_REDIS_TRANSACTION_MAX_CONNECTIONS=16
@@ -173,10 +156,8 @@ APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE=
APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED=false
APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE=
APP_REDIS_AUTHENTICATION_PUBSUB_CREDENTIAL_REFERENCE=
APP_REDIS_CAPACITY_MAXIMUM_IN_FLIGHT_BYTES=
APP_REDIS_CAPACITY_MAXIMUM_IN_FLIGHT_COMMANDS=64
APP_REDIS_CAPACITY_MAXIMUM_SCRIPT_CONNECTIONS=8
APP_REDIS_CAPACITY_MAXIMUM_REPLY_BYTES=
APP_REDIS_CAPACITY_REJECT_WHEN_DISCONNECTED=true
APP_REDIS_CLUSTER_MAXIMUM_REDIRECTS=5
APP_REDIS_CLUSTER_TOPOLOGY_REFRESH_PERIOD=30s
@@ -186,9 +167,7 @@ APP_REDIS_LIFECYCLE_CONNECT_TIMEOUT=2s
APP_REDIS_LIFECYCLE_DRAIN_TIMEOUT=6s
APP_REDIS_LIFECYCLE_SHUTDOWN_QUIET_PERIOD=100ms
APP_REDIS_LIFECYCLE_SHUTDOWN_TIMEOUT=3s
APP_REDIS_LIFECYCLE_TLS_HANDSHAKE_TIMEOUT=3s
APP_REDIS_PUBSUB_BUFFER_CAPACITY=1024
APP_REDIS_PUBSUB_OVERFLOW_POLICY=error
APP_REDIS_SENTINEL_CREDENTIAL_REFERENCE=
APP_REDIS_SENTINEL_MASTER_NAME=
APP_REDIS_SENTINEL_NODES=app.redis.nodes
@@ -223,20 +202,14 @@ APP_CACHE_REDIS_L1_GENERATION_RECHECK_INTERVAL=5s
APP_CACHE_REDIS_L1_INVALIDATION_QUEUE_CAPACITY=1024
APP_CACHE_DEFAULT_TTL=300s
APP_CACHE_NEGATIVE_TTL=60s
APP_MESSAGING_BROKER=
APP_MESSAGING_BROKER=kafka
APP_MESSAGING_PRODUCER_ID=
APP_MESSAGING_KAFKA_BROKERS=
APP_NOTIFICATION_SLACK_WEBHOOK_ENABLED=false
APP_NOTIFICATION_GOOGLE_EMAIL_ENABLED=false
APP_FILESERVER_ENABLED=false
APP_FILESERVER_LOCAL_ROOT=
APP_FILESERVER_LOCAL_EXPECTED_FILE_STORE_NAME=
APP_FILESERVER_LOCAL_EXPECTED_FILE_STORE_TYPE=
APP_FILESERVER_LOCAL_MOUNT_SENTINEL_SHA256=
APP_FILESERVER_LOCAL_EXPECTED_OWNER=
APP_HTTPCLIENT_ENABLED=false
APP_HTTPCLIENT_ENABLED=true
APP_HTTPCLIENT_ROTATION_DRAIN_TIMEOUT=30s
APP_FILESERVER_PLATFORM_ENABLED=false
APP_FILESERVER_PLATFORM_ENABLED=true
APP_FILESERVER_PLATFORM_INSTANCE_ID=local-node
APP_FILESERVER_PLATFORM_DEFAULT_NAMESPACE=default
APP_FILESERVER_PLATFORM_STORAGE_ROOT=/var/lib/backend/files
@@ -290,19 +263,19 @@ APP_FILESERVER_PLATFORM_OBSERVABILITY_METRICS_ENABLED=true
APP_ASYNC_EXECUTOR_CORE_SIZE=10
APP_ASYNC_EXECUTOR_MAX_SIZE=50
APP_ASYNC_EXECUTOR_QUEUE_CAPACITY=200
APP_PERSISTENCE_JPA_ENABLED=false
APP_PERSISTENCE_JPA_ENABLED=true
APP_JPA_HIBERNATE_BATCH_SIZE=0
APP_JPA_HIBERNATE_ORDER_INSERTS=false
APP_JPA_HIBERNATE_ORDER_UPDATES=false
APP_JPA_HIBERNATE_DEFAULT_BATCH_FETCH_SIZE=0
APP_JPA_HIBERNATE_GENERATE_STATISTICS=false
APP_PERSISTENCE_MONGO_ENABLED=false
APP_PERSISTENCE_MONGO_ENABLED=true
APP_PERSISTENCE_MONGO_ACTIVE_PROFILE=
# Optional standard Boot 4 connection path. When omitted, the selected typed Mongo profile must
# provide uri-secret and the deployment must supply a MongoCredentialResolver.
SPRING_MONGODB_URI=
APP_MESSAGING_ENABLED=false
APP_GRAPHQL_ENABLED=false
APP_MESSAGING_ENABLED=true
APP_GRAPHQL_ENABLED=true
APP_GRAPHQL_DEPLOYMENT_MODE=
APP_GRAPHQL_EXECUTION_PROFILE=BLOCKING_MVC
APP_GRAPHQL_VALIDATION_POLICY_VERSION=v1
@@ -317,31 +290,14 @@ APP_GRAPHQL_PREPARSED_CACHE_EXPIRE_AFTER_ACCESS=30m
# Optional build-composition: these bind only when :adapter:inbound:websocket is present.
# The default bootJar does not contain that leaf.
APP_WEBSOCKET_ENABLED=false
APP_WEBSOCKET_ENABLED=true
APP_WEBSOCKET_ENDPOINT=/ws
APP_WEBSOCKET_ALLOWED_ORIGINS=http://localhost:3000
APP_WEBSOCKET_BROADCAST_DESTINATION=/topic/events
APP_WEBSOCKET_PLATFORM_ENABLED=false
APP_WEBSOCKET_PLATFORM_NODE_ID=local
APP_WEBSOCKET_PLATFORM_ALLOWED_ORIGINS=
APP_WEBSOCKET_PLATFORM_ALLOW_MISSING_ORIGIN=false
APP_WEBSOCKET_PLATFORM_MAX_FRAME_BYTES=65536
APP_WEBSOCKET_PLATFORM_MAX_MESSAGE_BYTES=524288
APP_WEBSOCKET_PLATFORM_MAX_FRAGMENTS=16
APP_WEBSOCKET_PLATFORM_MAX_BUFFERED_OUTBOUND_BYTES_PER_CONNECTION=1048576
APP_WEBSOCKET_PLATFORM_MAX_BUFFERED_OUTBOUND_BYTES_PER_NODE=67108864
APP_WEBSOCKET_PLATFORM_MAX_CONNECTIONS_PER_ACTOR=4
APP_WEBSOCKET_PLATFORM_PING_INTERVAL=15s
APP_WEBSOCKET_PLATFORM_IDLE_TIMEOUT=45s
APP_WEBSOCKET_PLATFORM_MAX_CONNECTION_AGE=4h
APP_WEBSOCKET_PLATFORM_TICKET_LIFETIME=30s
APP_WEBSOCKET_ADVANCED_SOCKJS_ENABLED=false
APP_WEBSOCKET_ADVANCED_STOMP_ENABLED=false
APP_WEBSOCKET_ADVANCED_STOMP_RELAY_ENABLED=false
APP_OUTBOX_ENABLED=false
APP_OUTBOX_RELAY_ENABLED=false
APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED=false
APP_NOTIFICATION_PLATFORM_ENABLED=false
APP_NOTIFICATION_PLATFORM_ENABLED=true
APP_NOTIFICATION_PLATFORM_MODE=SERVING
# OpenAPI exposure. application-prod.yml pins both false regardless of these.
APP_OPENAPI_DOCS_ENABLED=true
@@ -372,6 +328,8 @@ APP_NOTIFICATION_PLATFORM_SES_REGION=us-east-1
APP_NOTIFICATION_PLATFORM_SES_SENDER_IDENTITY=
APP_NOTIFICATION_PLATFORM_SES_ACCESS_KEY_ID=
APP_NOTIFICATION_PLATFORM_SES_CONFIGURATION_SET=
# Comma-separated SNS topic ARNs whose SES events are accepted; required when callbacks are enabled.
APP_NOTIFICATION_PLATFORM_SES_ALLOWED_TOPIC_ARNS=
# SMTP transport security and socket deadlines are Spring Mail's settings. When the SMTP provider
# is enabled, configure the actual JavaMailSender with required STARTTLS (or implicit TLS) and
# positive mail.smtp.connectiontimeout / mail.smtp.timeout / mail.smtp.writetimeout values.
@@ -420,7 +378,8 @@ APP_CACHE_REDIS_KEY_HMAC_SECRET=
APP_FILESERVER_PLATFORM_OBSERVABILITY_FINGERPRINT_KEY=
# The notification platform's eight key purposes. Each is base64 of at least 32 bytes and must
# differ from the other seven; the platform decodes all eight at startup and refuses to boot if one
# is blank, short or shared. Only needed when APP_NOTIFICATION_PLATFORM_ENABLED=true.
# is blank, short or shared. Only needed when the notification module is selected and not switched
# off with APP_NOTIFICATION_PLATFORM_ENABLED=false.
APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY=
APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY=
APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY=
+17 -15
View File
@@ -1,14 +1,15 @@
# =============================================================================
# A local opt-in example: the five adapters are off in the shipped defaults, and this shows what
# turning some of them on looks like. Copy to src/.env.local and edit.
# A local example for a service that selected some capabilities. Copy to src/.env.local and edit.
#
# Each switch here needs the infrastructure its Compose profile provides. Turning one on without
# it is refused at startup by CapabilityDependencyValidator, which names the missing value.
# The default composition is web-only. A capability is on when its runtimeOnly line in
# app-bootstrap/build.gradle is uncommented, and each needs the infrastructure its Compose profile
# provides. The values below are what each one needs once selected; a missing required value is
# refused at startup, naming the key. APP_*_ENABLED=false turns a selected capability off.
# =============================================================================
SPRING_PROFILES_ACTIVE=local
# JPA: needs the PostgreSQL service. Flyway owns the schema from dev onward, and local uses the
# JPA (persistence-jpa line): needs the PostgreSQL service. Flyway owns the schema from dev onward, and local uses the
# same vendor semantics so the two do not diverge.
APP_PERSISTENCE_JPA_ENABLED=true
APP_DATASOURCE_URL=jdbc:postgresql://localhost:5433/ca_skeleton
@@ -16,21 +17,22 @@ APP_DATASOURCE_USERNAME=ca_skeleton
APP_DATASOURCE_PASSWORD=
APP_DATASOURCE_DDL_AUTO=validate
# Messaging: the broker id selects the transport; the switch decides whether there is one at all.
APP_MESSAGING_ENABLED=false
APP_MESSAGING_BROKER=
# Messaging (Kafka): on when app-bootstrap/build.gradle carries
# `runtimeOnly project(':adapter:outbound:messaging-kafka')`; APP_MESSAGING_ENABLED=false turns it off.
APP_MESSAGING_KAFKA_BROKERS=localhost:9092
# Outbox: needs JPA and messaging together, and a broker. relay-enabled only starts the scheduler.
APP_OUTBOX_ENABLED=false
APP_OUTBOX_RELAY_ENABLED=false
# Mongo: active-profile is required when the switch is on, and selects exactly one client.
APP_PERSISTENCE_MONGO_ENABLED=false
APP_PERSISTENCE_MONGO_ACTIVE_PROFILE=
# Mongo: on when its runtimeOnly line is in app-bootstrap/build.gradle. active-profile is required
# and selects exactly one client.
APP_PERSISTENCE_MONGO_ACTIVE_PROFILE=standard-uri
SPRING_MONGODB_URI=mongodb://localhost:27017/ca_skeleton
# GraphQL: the deployment mode must match the runtime environment (local -> LOCAL).
APP_GRAPHQL_ENABLED=false
# GraphQL: on when its runtimeOnly line is in app-bootstrap/build.gradle. The deployment mode must
# match the runtime environment (local -> LOCAL).
APP_GRAPHQL_DEPLOYMENT_MODE=LOCAL
# Notification: stores requests relationally, so it needs JPA on.
APP_NOTIFICATION_PLATFORM_ENABLED=false
# Notification: on when its line and the persistence-jpa line are selected (it stores requests
# relationally). It then needs the eight key purposes and their ids listed in src/.env.example.
+15 -2
View File
@@ -8,6 +8,8 @@
# --build-arg BUILD_VERSION=1.2.3+a1b2c3d4e5f6 \
# --build-arg GIT_SHA=a1b2c3d4e5f6 \
# --build-arg SOURCE_URL=https://github.com/your-org/your-repo
# Add --build-arg COMPOSITION=qualification for the Compose-lane image with every capability
# module on the classpath (see the builder stage). The default is the shipped composition.
#
# Design decisions (feature-container-runtime-contract D2/D3/D4):
# D2 — read-only root filesystem: writable mounts must be declared explicitly.
@@ -60,9 +62,20 @@ RUN test -n "${RELEASE_VERSION}" \
-PreleaseVersion="${RELEASE_VERSION}" -PgitRevision="${GIT_SHA}"
# Copy full source and stage the executable JAR at Gradle's declared Docker output path.
#
# COMPOSITION picks which jar that is. `default` is the composition a service ships (bootJar) and the
# only one a release builds. `qualification` is the same application with every capability module
# on the classpath (qualificationBootJar), for the Compose lanes that turn one on; it is never
# released. Declared here, after the dependency layer, so both share that cache.
ARG COMPOSITION=default
COPY . .
RUN ./gradlew :app-bootstrap:stageDockerJar --no-daemon -x test \
-PreleaseVersion="${RELEASE_VERSION}" -PgitRevision="${GIT_SHA}"
RUN case "${COMPOSITION}" in \
default) ./gradlew :app-bootstrap:stageDockerJar --no-daemon -x test \
-PreleaseVersion="${RELEASE_VERSION}" -PgitRevision="${GIT_SHA}" ;; \
qualification) ./gradlew :app-bootstrap:stageQualificationDockerJar --no-daemon -x test \
-PreleaseVersion="${RELEASE_VERSION}" -PgitRevision="${GIT_SHA}" ;; \
*) echo "COMPOSITION must be default or qualification, got '${COMPOSITION}'" >&2; exit 64 ;; \
esac
# ---- Layer extraction (D8) --------------------------------------------------
# Split the uber JAR into Spring Boot's four layers before it reaches the runtime stage.
+74 -62
View File
@@ -22,17 +22,18 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇
| 게이트 | 하는 일 |
| --- | --- |
| `architectureCheck` | Clean Architecture 의존 방향, runtime membership, application-core purity, Git에 실리지 않는 source package를 검사 |
| `architectureCheck` | Clean Architecture 의존 방향, domain-core·shared-contract·application-* 순수성, Git에 실리지 않는 source package, ArchUnit을 검사 |
| `qualityCheck` | 모든 leaf의 SpotBugs + FindSecBugs를 실행 |
| `configContractCheck` | `:app-bootstrap:verifyEnvKeys`로 환경 설정 계약을 검사 |
| `qualificationCheck` | Gradle TestKit 기반 build/repository behavior 검증을 실행 |
| `qualificationCheck` | 전체 기동(system) 레인과 보조 source set Checkstyle을 실행 |
| `integrationCheck` | 명시적으로 선언된 strict integration lane을 실행. 일부 lane은 container runtime이 필요 |
| `ci` | 모든 leaf `check` + `architectureCheck` + `qualityCheck` + `configContractCheck` + `qualificationCheck` |
| `ci` | PR 게이트: 모든 leaf `check` + `architectureCheck` + `qualityCheck` |
| `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + sample web 계약 + `verifyPublicPathSnapshot` + API surface + 전송·메시징 qualification 레인 + JPA readiness registry |
| `releaseCheck` | `ci`에 release provenance/archive 관련 검증을 추가 |
따라서 로컬에서 한 모듈만 수정했다면 `./gradlew :domain-core:check`처럼 focused task를
먼저 사용합니다. Gradle TestKit qualification은 일반 leaf `check`나 `:app-bootstrap:build`에
매달지 않고 `qualificationCheck`/`ci`에서 실행합니다.
먼저 사용합니다. 전체 기동 qualification은 일반 leaf `check`나 `:app-bootstrap:build`에
매달지 않고 `qualificationCheck`/`mainCheck`에서 실행합니다.
**2026-09에 삭제한 게이트.** `verifyOneTypePerFile`(Checkstyle의 `OneTopLevelClass`가 같은 규칙을
파싱된 파일에 대해 검사한다), `verifyTrivyignore`·`verifyQuarantineSunset`(빈 레지스트리를 지키는
@@ -94,16 +95,9 @@ archive task 자체는 timestamp 비보존·재현 가능한 file order·고정
registry와 `:app-bootstrap:architectureTest`의 관련 ArchUnit 규칙을 함께 갱신해야 합니다. settings와 gate는
같은 registry를 읽고, 등록되지 않은 leaf나 허용되지 않은 edge를 fail-closed로 거부합니다.
### `verifyRuntimeModuleRegistry`
- **하는 일.** `composition_roots`가 가리키는 실제 Gradle `runtimeClasspath`를 resolve해서 그 안의
project dependency가 architecture registry에 등록된 application module인지 확인합니다.
- **SSOT.** 어떤 module이 runtime에 실리는지는 `app-bootstrap/build.gradle`의 Gradle dependency graph가
결정합니다. registry가 같은 membership 목록을 다시 저장하지 않습니다.
- **변경 규칙.** production edge를 추가하거나 제거할 때는 실제 Gradle dependency와
`allowed_dependencies` 같은 architecture policy만 함께 검토합니다. exact runtime snapshot을 두 군데
맞추는 작업은 없습니다.
- 기존 `verifyRuntimeModuleMembership` task는 외부 스크립트 호환성을 위한 alias입니다.
조립 루트가 받는 모듈의 별도 membership 검사는 없습니다. `app-bootstrap`의 `allowed_dependencies`
밖의 모듈은 방향 게이트가 막고, 무엇이 실제로 실리는지는 `app-bootstrap/build.gradle`의 의존성이
정합니다.
세 opt-in inbound transport의 test-only composition, 실제 wire 경계, positive-count/zero-skip 증거는
다음 release-blocking aggregate로 실행합니다.
@@ -127,8 +121,9 @@ Checkstyle은 파싱된 파일에 같은 질문을 하고, leaf 단위로 돕니
- **소유.** app-bootstrap. 이 질문("이 애플리케이션의 배포에 무엇을 줘야 하는가")은 composition
root의 것이고, `./gradlew :domain-core:check`가 알아야 할 사항이 아닙니다. 루트 집계 이름은
`configContractCheck`이고 구현은 `build-logic`의 `ca.config-contract` convention plugin입니다.
- **하는 일.** `docs/registries/env-keys.yaml`, `application*.yml` + `config/*.yml`,
`configContractCheck`이고 구현은 `build-tools`의 `ca.config-contract` plugin입니다.
- **하는 일.** `docs/registries/env-keys.yaml`, app-bootstrap의 `application*.yml` + `config/*.yml`,
capability 모듈이 싣는 `config/*.yml`·`config/module-defaults/*.yml`(기본 조립에 없어도 검사한다),
`src/.env.example`을 lock-step(서로 어긋나지 않게) 으로 유지합니다. `env-keys.yaml` 이 `APP_` 키의 SSOT 이고, drift 가 생기면 빌드를
실패시킵니다.
- **막으려는 것 3가지.** (1) 필수 env 가 조용히 누락되는 것, (2) 더 이상 쓰지 않는 stale env 키가
@@ -177,9 +172,8 @@ Checkstyle은 파싱된 파일에 같은 질문을 하고, leaf 단위로 돕니
처리, 따옴표 제거 — 지키던 파일은 만들어진 이래 계속 비어 있었습니다. 실제 항목이 생기고 그것이
drift하기 시작하면 그때 자동화합니다. 진짜 항목을 상대로, 진짜 YAML 라이브러리로.
**플래키 격리.** 간헐 실패 테스트에 JUnit 기본 `@Tag("quarantine")`를 붙이면 메인 `test`가
`excludeTags 'quarantine'`로 제외하므로 merge를 막지 않고, `./gradlew quarantineTest`(비차단)로만
돕니다. 이 두 줄은 유지됩니다.
**플래키 격리.** `quarantineTest` 버킷과 CI의 비차단 `quarantine` 잡은 삭제했습니다. 격리된
테스트가 한 번도 없었습니다. 간헐 실패 테스트는 고치거나 지웁니다.
`flaky-quarantine.yaml` 레지스트리와 `verifyQuarantineSunset`(14일 sunset + drift 검사)은
삭제했습니다. 250줄짜리 YAML 파서 + Java 렉서(주석과 문자열 리터럴 안의 `@Tag("quarantine")`를
@@ -197,8 +191,9 @@ drift하기 시작하면 그때 자동화합니다. 진짜 항목을 상대로,
서로 같게 유지하는 일을 했습니다. 결과적으로 체크 하나를 추가하려면 Gradle · workflow · 표 ·
검사기 기대값 · Java 계약 테스트 다섯 곳을 같이 고쳐야 했습니다.
- **워크플로.** `.github/workflows/ci-quality-gates.yml` 의 `release-gate` 잡이 모든 release-blocking
게이트의 fan-in(단일 required status check)입니다. 플래키 `quarantine` 잡은 의도적으로 `needs` 에서
제외(비차단)됩니다. 위임 게이트(Trivy SCA/이미지 스캔)는 `dependency-vulnerability.yml` 가 소유하며,
게이트의 fan-in(단일 required status check)입니다. included build 테스트는 경로 필터가 걸린
`build-logic.yml`이, main 단계(`mainCheck`)·configuration-cache·JPA candidate evidence는
`integration-main.yml`이 돌립니다. 위임 게이트(Trivy SCA/이미지 스캔)는 `dependency-vulnerability.yml` 가 소유하며,
GitHub Actions 는 워크플로 간 `needs` 를 못 쓰므로 branch protection 의 required check 합집합으로
묶습니다.
@@ -216,20 +211,26 @@ drift하기 시작하면 그때 자동화합니다. 진짜 항목을 상대로,
- **`SPRING_PROFILES_ACTIVE`** — 활성 Spring profile. 보통 `local` | `dev` | `stage` | `prod`. JSON
로그의 `profile` 필드도 이 값을 씁니다.
### Runtime safety (기동 시 `StartupSafetyValidator` 가 fail-fast 검사, D8)
### Runtime safety (기동 시 fail-fast 검사, D8)
- 내부 error detail 노출과 request/response body logging은 shipped 기능이 아닙니다. 구현되지 않은
기능을 예약 환경 변수로 노출하지 않으며, request logging은 body를 읽지 않는 계약을 검증합니다.
- **`APP_MULTI_INSTANCE_ENABLED`** — `true` 면 인스턴스 협조용 빈 5종(lock / cache-stampede /
leader / rate-limit / migration)이 모두 있어야 하며, 하나라도 없으면 기동이 실패합니다.
- **`APP_SERVER_ERROR_INCLUDE_STACKTRACE` / `APP_SERVER_ERROR_INCLUDE_MESSAGE`** — 로컬 디버깅용.
prod에서 `never`가 아니면 `ErrorDetailExposureSafetyValidator`가 기동을 막습니다(exit 71,
`spring.web.error.include-binding-errors`·`include-exception`도 같음). request logging은 body를
읽지 않는 계약을 검증합니다.
- **`APP_MULTI_INSTANCE_ENABLED`** — `true` 면 cross-instance `DistributedLockPort`
(`distributedLockProvider`)가 조립돼 있어야 하며, 없으면 기동이 실패합니다(exit 72,
`StartupSafetyValidator`).
- **`APP_RATE_LIMIT_ENABLED`** — provider-neutral edge rate-limit interceptor 활성화
(429 + `Retry-After` + `X-RateLimit-*` 응답). 기본값은 `false`이며, `true`로 바꿀 때는
`APP_RATE_LIMIT_PROVIDER=redis`와 canonical coordination role을 함께 구성해야 합니다.
- **`APP_RATE_LIMIT_CLIENT_IP_MODE`** — 클라이언트 IP 판별 방식. `remote-addr-only` |
`forwarded-headers-trusted`. **신뢰된 ingress/LB 가 `X-Forwarded-For` 를 앱 도달 전에 덮어쓸 때만**
`forwarded-headers-trusted` 를 쓰세요. 아니면 IP 위조에 노출됩니다.
- **`APP_IDEMPOTENCY_TTL`** — idempotency 레코드 기본 TTL. duration(예: `24h`, `72h`). 오래 도는 use
case 는 최대 72h 까지 override 가능. (D6)
- **`APP_IDEMPOTENCY_PROVIDER`** — 요청 멱등성 store. `disabled`(기본) | `redis` | `postgresql`.
`postgresql` 은 PostgreSQL data source 가 아니면 기동을 거부하므로 `bootRunH2` 에서는
`disabled` 나 `redis` 를 씁니다.
- **`APP_IDEMPOTENCY_TTL`** — 완료 응답을 재생할 수 있는 기간(`replay-ttl`). duration(예: `24h`).
최대 72h 이고 넘으면 기동을 거부합니다. (D6)
### Async executor
@@ -240,32 +241,42 @@ drift하기 시작하면 그때 자동화합니다. 진짜 항목을 상대로,
- **`APP_ASYNC_EXECUTOR_QUEUE_CAPACITY`** — 백로그 큐 용량. **bounded(유한) 필수, unbounded 금지(D7)**.
1 이상 정수.
### 다섯 master switch (activation SSOT)
### 기능 추가 = 한 줄 + env
한 bootJar가 다섯 어댑터를 모두 싣고, 각각은 아래 스위치 하나로만 켜집니다. **전부 기본 `false`** 이고,
다섯이 모두 꺼진 배포는 외부 자원 없이 기동합니다. 값의 SSOT는
`dev.caskeleton.shared.activation.MasterSwitch`이며 `docs/registries/env-keys.yaml`이 같은 이름을
등록합니다.
기본 조립(`bootJar`)에는 web, 관측(actuator·metrics·tracing·로그), `domain-core`·`application-core`·
`shared-contract`, `adapter:outbound:support`·`adapter:outbound:identifier`만 들어 있습니다. DB·Redis·
Kafka 없이 기동합니다. 나머지 기능은 `app-bootstrap/build.gradle`에 주석 처리된 `runtimeOnly` 한 줄로
있습니다.
| 환경 변수 | Spring property | 기본값 |
|---|---|---|
| `APP_PERSISTENCE_JPA_ENABLED` | `ca-skeleton.persistence-jpa.enabled` | `false` |
| `APP_PERSISTENCE_MONGO_ENABLED` | `ca-skeleton.persistence-mongo.enabled` | `false` |
| `APP_MESSAGING_ENABLED` | `app.messaging.enabled` | `false` |
| `APP_NOTIFICATION_PLATFORM_ENABLED` | `ca-skeleton.notification.platform.enabled` | `false` |
| `APP_GRAPHQL_ENABLED` | `backend.graphql.enabled` | `false` |
- **켜기:** 그 줄의 주석을 풀고, 아래 env를 `src/.env`에 넣습니다. 모듈이 classpath에 있으면 켜집니다.
- **끄기:** 줄을 지웁니다. 모듈의 bean·설정·의존성이 함께 빠집니다. 줄은 두고 잠시 끄려면 "끄는 키"를
`false`로 줍니다(모든 키의 기본값은 `true`).
- **줄을 바꾼 뒤:** strict lock을 갱신합니다.
`./gradlew :app-bootstrap:resolveAndLockAll --write-locks`
- 모든 capability를 한 번에 싣는 jar가 필요하면(compose 레인·CI) `./gradlew :app-bootstrap:qualificationBootJar`를
씁니다. 배포용이 아닙니다.
**어댑터가 꺼진 것과 없는 것은 다릅니다.** 다섯 어댑터의 클래스는 언제나 아티팩트 안에 있고, 운영자는
재빌드 없이 스위치만으로 켭니다. 클래스가 없으면 애초에 켤 수 없습니다.
| capability | `build.gradle` 한 줄 | 켜진 뒤 필요한 env | 끄는 키 |
|---|---|---|---|
| JPA/PostgreSQL (Flyway·outbox store·JDBC 멱등성·분산 락) | `runtimeOnly project(':adapter:outbound:persistence-jpa')` | `APP_DATASOURCE_URL`, `APP_DATASOURCE_USERNAME`, `APP_DATASOURCE_PASSWORD` | `APP_PERSISTENCE_JPA_ENABLED` |
| Redis (cache·rate limit·lease·멱등성) | `runtimeOnly project(':adapter:outbound:cache-redis')` | `APP_REDIS_MODE`, `APP_REDIS_NODES`, `APP_REDIS_NAMESPACE_*`, `APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE`, 쓰는 역할의 선택자(`APP_CACHE_CANONICAL_DEFAULT_PROVIDER`, `APP_RATE_LIMIT_PROVIDER`, `APP_LEASE_PROVIDER`, `APP_IDEMPOTENCY_PROVIDER=redis`) | `APP_REDIS_ENABLED` |
| Kafka 발행 | `runtimeOnly project(':adapter:outbound:messaging-kafka')` | `APP_MESSAGING_KAFKA_BROKERS` (canonical 이벤트를 보내면 `APP_MESSAGING_PRODUCER_ID`) | `APP_MESSAGING_ENABLED` |
| Mongo | `runtimeOnly project(':adapter:outbound:persistence-mongo')` | `APP_PERSISTENCE_MONGO_ACTIVE_PROFILE`, `SPRING_MONGODB_URI`(또는 profile의 `uri-secret`) | `APP_PERSISTENCE_MONGO_ENABLED` |
| GraphQL | `runtimeOnly project(':adapter:inbound:graphql')` | `APP_GRAPHQL_DEPLOYMENT_MODE` (local→`LOCAL`, dev→`DEV`, prod→`PRODUCTION_*`) | `APP_GRAPHQL_ENABLED` |
| 외부 HTTP 호출 | `runtimeOnly project(':adapter:outbound:httpclient')` | client 하나 이상: `APP_HTTPCLIENT_CLIENTS_0_*` (`docs/httpclient/env-fields.yaml`) | `APP_HTTPCLIENT_ENABLED` |
| 객체 저장소 (S3/로컬) | `runtimeOnly project(':adapter:outbound:objectstorage')` | 전용 env 없음. `app.object-storage.*`의 provider·destination을 `application-*.yml`에 적음 | `app.object-storage.enabled` |
| WebSocket (STOMP push) | `runtimeOnly project(':adapter:inbound:websocket')` | 없음(기본값으로 동작). origin은 `APP_WEBSOCKET_ALLOWED_ORIGINS` | `APP_WEBSOCKET_ENABLED` |
| gRPC 서버 | `runtimeOnly project(':adapter:inbound:grpc')` | `CA_SKELETON_GRPC_ALLOW_INSECURE_LOCAL=true` (지금 받는 listener가 loopback plaintext뿐) | `ca-skeleton.grpc.enabled` |
| 파일 서버 (JPA 줄도 필요) | `runtimeOnly project(':composition:fileserver-platform')` | `APP_FILESERVER_PLATFORM_STORAGE_ROOT`, `APP_FILESERVER_PLATFORM_OBSERVABILITY_FINGERPRINT_KEY`, 그리고 `FileAccessPolicy` bean 또는 `APP_FILESERVER_PLATFORM_SECURITY_ACCESS_POLICY=role-based` | `APP_FILESERVER_PLATFORM_ENABLED` |
| 알림 (SMTP/SES, JPA 줄도 필요) | `runtimeOnly project(':composition:notification-platform')` | 키 8종과 각 `_ID`(`APP_NOTIFICATION_PLATFORM_*_KEY`, `*_KEY_ID`), 쓰는 provider 설정(`APP_NOTIFICATION_PLATFORM_SMTP_*` 또는 `_SES_*`) | `APP_NOTIFICATION_PLATFORM_ENABLED` |
켜진 capability가 의존하는 것이 꺼져 있으면 기동이 거부되고, **거부 메시지는 설정해야 할 정확한
property 이름을 말합니다**(`CapabilityDependencyValidator`). 예:
전체 목록과 타입·기본값은 `docs/registries/env-keys.yaml`, 각 모듈이 제공하는 것은 그 모듈 README의
"제공하는 것 · 추가할 한 줄 · env 키" 절에 있습니다. 기능 사이의 의존(알림·파일 서버 → JPA, outbox relay
→ JPA + Kafka)은 설정 검사가 아니라 build 줄로 맞춥니다. 표에 "JPA 줄도 필요"라고 적힌 기능은 두 줄을
함께 넣습니다.
```
This deployment enables capabilities whose dependencies are off:
- ca-skeleton.outbox.enabled=true needs relational persistence to store rows;
set ca-skeleton.persistence-jpa.enabled=true or turn the outbox off.
```
어떤 자동 설정이 켜졌는지는 Spring Boot의 `conditions` endpoint로 봅니다. 기본 노출 목록에는 없으므로
필요할 때 `management.endpoints.web.exposure.include`에 추가합니다.
종속 선택자 둘:
@@ -295,24 +306,24 @@ This deployment enables capabilities whose dependencies are off:
### Optional integration adapters
선택형 Kafka / Redis / Slack / Google Email 어댑터 템플릿입니다. **기본은 전부 비활성**(비활성 = 선택
모듈의 기본값). Layer 1 의 `@ConditionalOnProperty` 가 enabled 일 때만 실제 어댑터를 등록하고, 아니면
fail-fast sentinel 이 포트를 충족합니다(Layer 3).
Kafka·Redis는 위 "기능 추가 = 한 줄 + env" 표의 한 줄로 고릅니다. 모듈이 있으면 켜지고, 없으면 그
포트를 구현하는 bean이 아예 없습니다. 아래는 모듈을 고른 뒤 동작을 고르는 키입니다.
- **`APP_CACHE_REDIS_ENABLED`** — Redis 캐시 어댑터 on/off. `true` | `false`.
- **`APP_CACHE_REDIS_ENABLED`** — deprecated(2026-11-30 제거 예정). 읽는 곳은 `sample-portfolio`뿐이고,
기본 조립에서 Redis를 켜고 끄는 것은 `APP_REDIS_ENABLED`입니다.
- **`APP_CACHE_CANONICAL_DEFAULT_PROVIDER`** — canonical default semantic region 선택.
`disabled`(기본) | `redis`. `redis`는 canonical Redis CACHE role binding을 함께 요구합니다.
- **`APP_CACHE_REDIS_CLIENT_MODE`** — `managed`는 내장 Lettuce runtime, `external`은 프로젝트가
제공한 `RedisClient` bean을 사용합니다.
아래 세 키는 **활성화 스위치가 아니라 선택자**입니다. 어떤 capability가 켜지는지는 위의 master switch가
정하고, 이 값들은 켜진 capability가 *무엇으로* 동작할지만 고릅니다. 예전에는 "빈 값 = 비활성"으로
아래 세 키는 **활성화 스위치가 아니라 선택자**입니다. 어떤 capability가 켜지는지는 위의 build 한 줄과
끄는 키가 정하고, 이 값들은 켜진 capability가 *무엇으로* 동작할지만 고릅니다. 예전에는 "빈 값 = 비활성"으로
설명돼 있었고, 그 문장이 남아 있는 동안 두 개의 활성화 모델이 공존했습니다.
- **`APP_MESSAGING_BROKER`** — 활성 메시지 브로커 id(예: `kafka`). `APP_MESSAGING_ENABLED=true`일 때
**필수**이고, 빈 값이면 기동이 거부되면서 이 키 이름을 지목합니다. 이 키를 비워도 메시징이 꺼지지는
않습니다 — 끄는 것은 master switch입니다.
- **`APP_MESSAGING_KAFKA_BROKERS`** — `host:port` CSV. `APP_MESSAGING_BROKER=kafka` 일 때만 필수,
아니면 빈 값.
- **`APP_MESSAGING_BROKER`** — 활성 메시지 브로커 id. Kafka 모듈의 설정 기본값이 `kafka`(등록된 유일한
broker)라 보통 비워 두지 않습니다. 빈 값을 주면 기동이 거부되면서 이 키 이름을 지목합니다. 이 키를 비워도 메시징이 꺼지지는
않습니다 — 끄는 것은 `APP_MESSAGING_ENABLED=false`입니다.
- **`APP_MESSAGING_KAFKA_BROKERS`** — `host:port` CSV. Kafka 모듈을 고르면 필수. legacy seam과
messaging platform의 Kafka transport(`spring.kafka.bootstrap-servers`)가 같은 값을 씁니다.
- **`APP_NOTIFICATION_SLACK_WEBHOOK_ENABLED`** — Slack webhook R0 provider enable flag. notification 플랫폼이
켜졌을 때 어떤 provider를 쓸지 고르는 값입니다.
- **`APP_NOTIFICATION_GOOGLE_EMAIL_ENABLED`** — Google Email R0 provider enable flag. 위와 같습니다.
@@ -508,7 +519,8 @@ Docker 없이 빠르게 wiring·요청/응답·애플리케이션 로직만 확
`./gradlew :app-bootstrap:bootRunH2`를 명시적으로 사용합니다. 이 태스크만
`APP_PERSISTENCE_VENDOR=h2`, `APP_FLYWAY_ENABLED=false`,
`APP_DATASOURCE_DDL_AUTO=create-drop`을 주입합니다. H2에는 PostgreSQL migration tree가 없으므로
migration/vendor 계약의 증거로 사용하지 않습니다.
migration/vendor 계약의 증거로 사용하지 않습니다. 멱등성 provider(`APP_IDEMPOTENCY_PROVIDER`)는
`disabled`(기본)나 `redis`로 둡니다. `postgresql`은 H2 data source에서 기동을 거부합니다.
`dev` 를 호스트에서 띄우려면(`SPRING_PROFILES_ACTIVE=dev`) PostgreSQL 이 필요합니다.
`docker-compose.local.yml` 의 `db` 서비스가 루프백(`127.0.0.1:5433`)에만 게시하며, 이 주소가
+49 -77
View File
@@ -28,30 +28,23 @@ SSOT(`src/config/architecture/modules.json`)까지 밀어올리지 않는다는
| | 방식 | 경계 강제 |
| --- | --- | --- |
| messaging | 레지스트리에 leaf 등록 | Gradle 의존 게이트 |
| graphql | 단일 leaf 내 sub-package | 아래 경계 테스트 |
| graphql | 단일 leaf 내 sub-package | 아래 ArchUnit 테스트 (전송 경계만) |
어느 쪽으로 통일할지는 **미결 아키텍처 결정**이다. graphql 을 leaf 로 분해하려면 이 문서의
모듈 레코드가 그대로 leaf 명세로 승격될 수 있게 설계해 두었다. 그때까지 모듈 경계는 문서가
아니라 기계가 지킨다:
어느 쪽으로 통일할지는 **미결 아키텍처 결정**이다.
- main 의 `moduleboundary/GraphQlStableModule` · `moduleboundary/GraphQlAdvancedModule` 이 모듈
정체성·purity 등급·허용 의존 edge 를 값으로 선언하고, `moduleboundary/GraphQlModuleBoundary` 가
"이 패키지의 주인은 누구인가 / 이 edge 는 선언됐는가"를 답한다.
- test 의 `moduleboundary/GraphQlBuildModel` 이 실제 소스 트리를 스캔하고,
`moduleboundary/GraphQlModuleBoundaryTest` 가 (a) Stable 패키지의 `...graphql.advanced` import
금지, (b) `CORE` 등급 모듈의 Spring/GraphQL Java/Reactor/Micrometer/Jakarta import 금지,
(c) 선언되지 않은 cross-module edge 금지, (d) 미등록 패키지 금지, (e) 선언만 있고 소스가 없는
모듈 금지를 강제한다. 각 규칙은 **거부되는 합성 트리(negative fixture)** 를 함께 가진다.
sub-package 사이의 경계(Stable↔Advanced 방향, 모듈 레코드)를 값으로 선언하던 `moduleboundary/`
모델과 부팅 때마다 컨트롤러를 리플렉션으로 검사하던 `architecture/` 는 2026-09-25 에 삭제했다
(`docs/capability-status.md` 제거 표). 지금 기계가 지키는 것은 전송 경계 두 가지뿐이다 —
`GraphQlTransportBoundaryArchitectureTest`(ArchUnit, 이 leaf 패키지 대상):
**패키지 이름은 `build` 가 아니라 `moduleboundary` 다.** `src/.gitignore:2` 의 anchor 없는
`build/` 규칙은 Gradle 산출물과 Java 패키지를 구분하지 못해서, 예전에 이 경계 모델 전체를
커밋에서 삼켰다(프로덕션 코드는 계속 import 하고, 작성자 작업본만 컴파일되고, fresh checkout
은 7개 오류로 깨졌다). 레포 전역 `verifyNoIgnoredSourcePackages` 가 이 부류를 막고,
`graphqlStableTest` 의 required-class 검사가 "경계 테스트만 조용히 사라지고 레인은 green" 인
나머지 절반을 막는다.
- resolver(`@SchemaMapping` 계열·`@BatchMapping`) 시그니처는 전송 타입만 쓴다. 반환·인자 타입과
그 제네릭 인자에 raw `Map`, persistence 매핑 타입(`@Entity`/`@Document`/`@Table` 등, 단순명
매칭), domain·outbound adapter·JPA/Hibernate/Spring Data/JDBC/Mongo/AWS/gRPC/Kafka 타입이
오면 실패한다.
- raw `DataFetcher` 구현은 `scalar`·`schema`·`execution` 패키지에만 둔다.
**새 플랫폼 sub-package 를 추가할 때는 반드시 해당 모듈 레코드에 정체성과 허용 edge 를 먼저
등록한다.** 등록 없이 추가된 패키지는 경계 테스트가 실패시킨다.
두 규칙 모두 위반 fixture 로 실제로 잡히는지 같은 테스트가 확인한다. `graphqlStableTest` 의
required-class 검사가 이 테스트가 조용히 사라지는 것을 막는다.
## Responsibility
@@ -59,14 +52,15 @@ SSOT(`src/config/architecture/modules.json`)까지 밀어올리지 않는다는
프로토콜 에러 매핑(`GraphqlExceptionResolver`). Spring for GraphQL 이 스키마와 컨트롤러를
자동 합성/바인딩하도록 얹는 얇은 계층이다.
- 그 위에 **GraphQL API 실행 플랫폼**(`...graphql` 하위 sub-package 군)이 스키마 계약·전송
프로파일·실행 정책·비용 한계·DataLoader·페이지네이션·에러/보안 경계·관측·릴리스 게이트를
프로파일·실행 정책·비용 한계·DataLoader·페이지네이션·에러/보안 경계·관측을
소유한다. 플랫폼은 여전히 **feature-agnostic** 이며 정책·계약·검증 기계만 제공한다.
- feature-agnostic: `classpath:graphql/**` 스키마와 모든 `@Controller` `@QueryMapping`/
`@MutationMapping` 을 generic 하게 합성한다. **WorkLog 등 구체 기능을 이름으로 알지 않는다.**
- shipped-and-gated: `app-bootstrap` production composition 은 이 leaf 를 직접 의존하고,
`APP_GRAPHQL_ENABLED=false` 가 기본이다. 즉 "off"는 classpath 부재가 아니라 GraphQL
auto-configuration/route 부재로 검증한다. 실제 활성화 시 composition root 는 인증/인가·CORS 정책과
GraphiQL/introspection 운영 설정을 함께 명시해야 한다.
- 있으면 켜진다: 서비스가 `app-bootstrap/build.gradle`에 `runtimeOnly project(':adapter:inbound:graphql')`
한 줄로 고른다(기본 조립에는 없다). `APP_GRAPHQL_ENABLED=false`(`backend.graphql.enabled`)만 끄며,
그때 `GraphQlActivationEnvironmentPostProcessor`가 Spring GraphQL 자동 설정도 exclude 한다.
실제 활성화 시 composition root 는 인증/인가·CORS 정책과 GraphiQL/introspection 운영 설정을 함께
명시해야 한다.
## Error-code ownership
@@ -98,9 +92,8 @@ application/platform namespace split.
`spring-boot-starter-security`(HTTP 인증/CORS qualification 용),
`io.micrometer:micrometer-core`(실제 `MeterRegistry` 로 metric label cardinality 를 **측정**).
- `java-test-fixtures` — 계약 스위트·통합 fixture·in-memory 스텁은 `src/testFixtures/java` 가
소유하고 production jar 에 들어가지 않는다. 모듈 경계 스캐너
(`moduleboundary/GraphQlBuildModel`)는 main 과 testFixtures 를 **함께** 스캔한다: 아티팩트가
갈렸다고 패키지 경계 규칙까지 갈리면, 규칙이 조용히 절반만 남는다.
소유하고 production jar 에 들어가지 않는다.
- test scope 에 한해 `archunit-junit5` — 전송 경계 규칙(`GraphQlTransportBoundaryArchitectureTest`).
**서버는 이 leaf 가 고르지 않는다.** production 파일 중 `org.springframework.web`·
`jakarta.servlet`·`org.springframework.http` 을 import 하는 것은 **하나도 없다**. 예전에는
@@ -160,48 +153,29 @@ health 스키마만 소유한다.
| --- | --- | --- |
| 실행 파이프라인 / 인가 / cost 예산 | `wired` | `systemTest/runtime/GraphQlPlatformExecutionPathTest` (random-port, 거부 시 resolver 호출 0회) |
| depth/complexity 제한 (`cost/`) | `wired` | 같은 테스트의 depth/alias/complexity 케이스 |
| graphql-java parser options (`GraphQlParserOptionsFactory`) | `modelled` | parser policy/factory 단위 테스트만. Stable auto-configuration은 static parser defaults를 교체하지 않는다. HTTP/document cap이 현재 request-path 방어다. |
| response runtime budget (`GraphQlRuntimeBudgetTracker`) | `modelled` | incremental transport 모델에서만 사용된다. Stable response path에는 설치되지 않아 complexity budget을 대체하지 않는다. |
| preparsed document cache (`execution/`) | `wired` | `GraphQlPreparsedDocumentAdapter` + 같은 테스트의 캐시 hit 케이스 |
| 커스텀 scalar (`scalar/`) | `wired` | 같은 테스트의 scalar coercion 케이스 |
| schema mapping inspection / parallel schema assembler (`schema/`) | `modelled` | `GraphQlMappingInspectionGate`·`GraphQlSchemaAssembler` 단위 테스트만. Stable runtime은 Spring의 schema assembly를 사용하며 소비자 없는 gate bean을 등록하지 않는다. |
| 요청 크기/Accept 협상 (`http/`) | `wired` | `GraphQlRequestBoundsTest`, `GraphQlAcceptNegotiationTest` |
| 요청 크기 (`http/`, body limit filter) | `wired` | `GraphQlRequestBoundsTest` |
| 관측 tag cardinality (`observation/`) | `wired` | `runtime/GraphQlRequestObservationConventionAdapter` 가 Spring 의 `ExecutionRequestObservationConvention` 을 구현해 Boot 의 `GraphQlObservationAutoConfiguration` 이 이 컨벤션을 가져간다. `autoconfigure/GraphQlObservationWiringTest`(프레임워크가 실제로 해석), `runtime/GraphQlRequestObservationConventionAdapterTest`(실제 `MeterRegistry` 에 임의 이름 10,000개 → series 1개) |
| object 인가 (`security/`) | `modelled` | 답하는 계약은 중립 `dev.caskeleton.application.security.ObjectAccessPolicy` 가 소유하고 이 leaf 는 `ApplicationObjectAuthorization` 매핑만 가진다. 실행 경로에 연결하는 configuration 은 없다 |
| DataLoader/batching (`dataloader/`) | `wired` | `runtime/GraphQlBatchLoaderRegistrationTest` (실제 graphql-java 실행 + Spring `BatchLoaderRegistry`, 50 parent → 3 downstream 호출), `dataloader/GraphQlBatchContractTest` |
| cursor 서명 (`pagination/`) | `modelled` | `HmacGraphQlCursorCodec`·`GraphQlCursorKeyRing` 단위 테스트만. **auto-configuration 이 둘 중 무엇도 생성하지 않는다** — `autoconfigure/GraphQlPolicyRequestPathTest` 가 그 사실을 고정 |
| mutation 멱등성 (`mutation/`) | `modelled` | `GraphQlMutationIdempotencyInterceptor` 를 참조하는 configuration 이 없다. 같은 테스트가 고정 |
| persisted operation (`advanced/persisted/`) | `modelled` | 중립 `OperationalRecordStorePort` 기반 레지스트리 + 방향성 테스트. durable 구현체는 미제공 |
| subscription / SSE / RSocket | `modelled` | GraphQL leaf 는 구독 정책/보안/replay 모델만 소유한다. `graphql-transport-ws` 연결 상태기계와 close-code 전송은 `:adapter:inbound:websocket` 이 소유하며 이 leaf 에 병렬 WebSocket transport 구현을 두지 않는다. SSE/RSocket 은 모델/단위 테스트만 있다. |
| federation / incremental / codegen / compat | `modelled` | 단위 테스트만 |
| 실부하·장애 | 미달성 | `graphqlPerformanceTest` 레인이 자리를 예약, 증거 없으면 릴리스 게이트가 거부 |
| cursor 서명·connection (`pagination/`), fetch profile (`fetch/`) | 라이브러리 | 요청 경로에 없다. 서비스가 직접 호출한다 — README "라이브러리 API". `autoconfigure/GraphQlPolicyRequestPathTest` 가 auto-configuration 이 codec·key ring 을 만들지 않음을 고정 |
| 실부하·장애 | 미달성 | 증거 없음 |
여전히 미구현인 것:
- feature GraphQL schema/resolver — 이 leaf 는 health 표면만 소유한다(변경 없음).
- 실부하 성능/장애 시나리오 증거 — `release/GraphQlPerformanceScenario`,
`GraphQlFaultScenario` 는 시나리오 카탈로그를 정의하고 `GraphQlReleaseGate` 는 그 증거가
없으면 릴리스를 **거부**한다. 증거 자체는 실제 부하 인프라를 요구하므로 이 leaf 밖에서
생성한다(`graphqlPerformanceTest` 레인이 그 자리를 예약해 둔다).
- 실제 datastore 통합 증거 — `testkit/GraphQlJpaIntegrationFixture` /
`GraphQlMongoIntegrationFixture` 가 계약을 정의하고 `GraphQlStorageIntegrationEvidence` 가
증거를 요구한다. 실 datastore 기동은 persistence leaf 의 책임 범위다. 이 testkit 은
**production jar 에 없다** — `src/testFixtures/java` 에 살고 `verifyGraphQlProductionJar` 가
그 사실을 jar 내용으로 확인한다.
- **cursor 서명이 요청 경로에 없다 (GQL-INT-003).** `HmacGraphQlCursorCodec`와
`GraphQlCursorKeyRing`은 `modelled` 부품이고 Stable auto-configuration은 어느 쪽도 생성하지
않는다. 따라서 `backend.graphql.cursor.key-ids`는 adopter가 직접 조립할 때 사용할 수 있는
선언 값일 뿐, production startup requirement도 아니고 활성 보호의 증거도 아니다.
`GraphQlCursorKeyRing.of`는 실제 `Map<String, byte[]>`를 요구하므로 다음 승격 조건은 key material
source와 request-path wiring을 함께 설계하는 것이다. 그 전까지 shipped `APP_GRAPHQL_*` 계약에는
cursor key-id를 노출하지 않는다.
- persisted operation 의 durable 저장 구현체 — 이 leaf 는 중립 계약
`dev.caskeleton.shared.opstore.OperationalRecordStorePort` 에만 의존하고 key/value 매핑만
소유한다. Postgres/Redis 구현체는 **그 중립 계약을** 구현하며, 이 leaf 의 타입을 구현하지
않는다(그랬다면 인프라 → 인바운드 전송으로 의존이 뒤집힌다).
- Advanced capability 는 전부 **기본 비활성**이다(`advanced/bootstrap/GraphQlAdvancedFeatureFlags`).
EXPERIMENTAL 등급(RSocket, incremental delivery, HTTP GET draft)은 명시적 승인 없이는
`GraphQlAdvancedModuleGuard` 가 production 활성화를 거부한다.
- 실부하 성능/장애 시나리오 증거 — 없다. 시나리오 카탈로그와 릴리스 게이트(`release/`,
`advanced/release/`)와 스키마 호환성 비교기(`compat/`)는 호출하는 곳이 없어 2026-09-25 에
삭제했다.
- 실제 datastore 통합 증거 — 없다.
- `advanced/**`(SSE·RSocket·federation·incremental·HTTP GET·persisted operation·subscription
replay 등)는 바인딩되지 않는 feature flag gate 뒤의 모델뿐이어서 2026-09-25 에 삭제했다
(`docs/capability-status.md` 제거 표). 다시 필요하면 Spring GraphQL/graphql-java SPI 를 구현하는
형태로 새로 만든다.
- 요청 단계 거부(`GraphQlPlatformWebInterceptor`, `GraphQlPlatformInstrumentation`)는
`GraphQlWireErrorMapper` 를 거치지 않고 `GraphQlPlatformRejectionMapper.map` 을 직접 부른다.
그래서 요청 단계의 `ApiErrorCarrier` 는 `INTERNAL_ERROR` 가 된다(리뷰 S5 #6, 미해결).
## Test
@@ -211,34 +185,32 @@ cd src
./gradlew :adapter:inbound:graphql:graphqlTransportQualificationTest --console=plain
```
플랫폼 테스트 레인(`ca.graphql-platform` convention plugin 등록). 기본 `test` 는
`quarantine`·`graphql-performance` 태그를 제외한다:
테스트 레인:
```bash
./gradlew :adapter:inbound:graphql:graphqlStableTest --console=plain # 605 tests
./gradlew :adapter:inbound:graphql:graphqlContractTest --console=plain # 9 tests
./gradlew :adapter:inbound:graphql:graphqlAdvancedTest --console=plain # 152 tests
./gradlew :adapter:inbound:graphql:graphqlPerformanceTest --console=plain # 실부하 인프라 필요
./gradlew :adapter:inbound:graphql:graphqlStableTest --console=plain # GraphQlTransportBoundaryArchitectureTest만, skip 금지
./gradlew :adapter:inbound:graphql:systemTest --console=plain # 23 tests (실제 HTTP 서버)
```
`graphqlPerformanceTest` 는 `@Tag("graphql-performance")` 가 하나도 없으면 **실패한다** — 이는
버그가 아니라 "성능 증거 없음"을 통과로 위장하지 않기 위한 fail-closed 설계다.
위 숫자는 `build/test-results/<lane>/*.xml` 의 실제 실행 결과다(기본 `test` 757, transport
qualification 8). 문서에 옮겨 적은 숫자는 반드시 마지막 green 실행에서 다시 읽어 갱신한다 —
컴파일이 깨진 채로 남은 과거 숫자는 통과 증거가 아니라 통과했다는 인상일 뿐이다.
`graphqlStableTest` 는 `GraphQlTransportBoundaryArchitectureTest` 가 실행되지 않거나 skip 되면
실패한다(`build.gradle` 의 strict lane `requires` + `rejectSkipped`). 같은 클래스는 `test` 에서도 돈다.
## 아티팩트 게이트
```bash
./gradlew :adapter:inbound:graphql:verifyGraphQlProductionJar --console=plain
./gradlew :adapter:inbound:graphql:test --tests '*GraphQlProductionClassesTest' --console=plain
./gradlew :adapter:inbound:graphql:verifyGraphQlApiSurface --console=plain
```
- `verifyGraphQlProductionJar` — production jar 에 `testkit`/`InMemory`/`Fixture`/`TestContext`
클래스가 하나라도 있으면 실패한다. 계약 스위트와 in-memory 스텁은 `src/testFixtures/java` 가
소유한다.
- `GraphQlProductionClassesTest` — production 클래스에 `testkit`/`InMemory`/`ForTests`/`Fixture`/
`TestContext` 가 하나라도 있으면 실패한다(`test` 의 일부). 테스트용 request context 헬퍼(`testkit/GraphQlRequestContexts`)는
`src/testFixtures/java` 가 소유한다.
- `verifyGraphQlApiSurface` — `docs/architecture/graphql-api-surface.txt` 스냅샷과 실제 public
타입 목록이 다르면 실패한다. 단일 jar 안에서 `public` 은 모든 adopter 에게 public 이므로,
표면 증가는 리뷰 결정이지 빌드 부산물이 아니다. 승인 후:
`./gradlew :adapter:inbound:graphql:updateGraphQlApiSurface -PapproveGraphQlApiSurfaceChange`.
- mutation 멱등성 — 저장소에 연결된 적 없는 `GraphQlMutationIdempotencyInterceptor`·context·
fingerprint 와 `idempotencyKey` extension 허용을 2026-09-25 에 삭제했다. Stable 기본
`GraphQlExtensionsPolicy` 는 어떤 extension key 도 허용하지 않는다. 요청 재생 멱등성이 필요하면
application `IdempotencyExecutor` 를 use case 안에서 쓴다.
+58 -59
View File
@@ -28,10 +28,28 @@ Spring for GraphQL 은 schema-first 다. 빈 스키마로는 부팅이 실패하
메서드를 바인딩한다. 향후 feature 의 GraphQL controller 는 스켈레톤을 수정하지 않고 등록할 수
있다.
현재 `app-bootstrap` production composition 은 이 leaf 를 **classpath 에 포함**하고
`APP_GRAPHQL_ENABLED=false` 를 기본으로 두는 shipped-and-gated 구조다. 따라서 비활성은 jar 부재가
아니라 runtime route/auto-configuration 비활성으로 증명한다. `sample-portfolio` 에 feature GraphQL
스키마/controller 가 있다는 뜻은 아니며, leaf 자체는 최소 health 스키마로 독립 기동할 수 있다.
## 제공하는 것 · 추가할 한 줄 · env 키
- 제공: `/graphql` HTTP endpoint(Spring for GraphQL), 플랫폼 정책(실행 프로파일·비용 한계·
DataLoader·에러/보안 경계·관측), 최소 health 스키마. 설정 기본값 `config/graphql.yml`을 모듈이
직접 읽는다(`GraphQlActivationEnvironmentPostProcessor`, 우선순위 가장 낮음).
- 추가할 한 줄(기본 조립에는 없다):
```groovy
// app-bootstrap/build.gradle
runtimeOnly project(':adapter:inbound:graphql') // GraphQL
```
이 줄을 지우면 endpoint, 플랫폼 bean, 설정 기본값이 모두 함께 빠진다.
- 켜기와 끄기: 모듈이 있으면 켜진다. `APP_GRAPHQL_ENABLED=false`로만 끈다. 끄면 이 모듈의 bean과
Spring GraphQL 자신의 자동 설정(`org.springframework.boot.graphql.*`)이 함께 빠져 `/graphql`이
열리지 않는다.
- 필요한 env 키(`docs/registries/env-keys.yaml` SSOT): `APP_GRAPHQL_DEPLOYMENT_MODE`(runtime profile과
맞는 값: local→`LOCAL`, dev→`DEV`, prod→`PRODUCTION_INTERNAL`|`PRODUCTION_PUBLIC`). production mode는
`GraphQlAuthorizationPolicy` bean도 필요하다. 나머지 `APP_GRAPHQL_*`는 기본값으로 동작한다.
`sample-portfolio` 에 feature GraphQL 스키마/controller 가 있다는 뜻은 아니며, leaf 자체는 최소
health 스키마로 독립 기동할 수 있다.
## 에러 매핑 — web `GlobalExceptionHandler` / gRPC 인터셉터의 GraphQL 형제
@@ -87,7 +105,7 @@ gRPC 와 달리 spring-graphql / graphql-java 는 Spring Boot BOM 이 관리한
가 소유한다. composition-root `application.yml` 에서 설정하며 모듈별 `yml` 은 없다.
플랫폼 정책은 `spring.graphql.*` 로 표현할 수 없다 — 실행 프로파일, cost/page 한계, preparsed
캐시 경계, cursor 키 링, 관측 label 로 허용할 operation 이름은 전부 이 leaf 의 결정이다. 그래서
캐시 경계, 관측 label 로 허용할 operation 이름은 전부 이 leaf 의 결정이다. 그래서
`GraphQlPlatformProperties` 가 **`backend.graphql`** prefix 로 `@ConfigurationProperties` 를
바인딩한다(`spring.graphql.platform.*` 이 아니다 — 그 prefix 는 존재한 적이 없다).
@@ -109,14 +127,13 @@ backend:
observed-operation-names: [] # 비우면 모든 operation 이름이 `other` 로 접힌다
```
shipped composition에서는 위 wired 설정을 `APP_GRAPHQL_*`로 노출한다. `APP_GRAPHQL_ENABLED`와
이 모듈의 `config/graphql.yml`이 위 wired 설정을 `APP_GRAPHQL_*`로 노출한다. `APP_GRAPHQL_ENABLED`와
`APP_GRAPHQL_DEPLOYMENT_MODE` 외에도 execution profile, console, page/complexity, preparsed-cache
한계와 관측 operation allowlist가 `config/graphql.yml`을 통해 같은 property tree로 들어간다.
한계와 관측 operation allowlist가 같은 property tree로 들어간다.
production mode는 env만으로 완성되지 않는다. 애플리케이션 좌표를 스켈레톤이 알 수 없으므로
**명시적인 `GraphQlAuthorizationPolicy` bean이 반드시 필요**하며, 이것은 의도된 fail-closed
계약이다. 반대로 cursor signing은 아직 요청 경로에 연결되지 않은 `modelled` capability라
`APP_GRAPHQL_CURSOR_KEY_IDS` 같은 운영 키를 제공하지 않고 startup requirement로도 취급하지 않는다.
계약이다. cursor 서명은 설정 키가 없다 — 아래 라이브러리 API로 서비스가 직접 조립한다.
`observed-operation-names` 가 비어 있는 것이 기본값이자 안전한 값이다. operation 이름은 문법만
검증될 뿐 개수가 제한되지 않으므로, 원본을 그대로 metric label 로 쓰면 정상 클라이언트 하나가
@@ -148,49 +165,33 @@ composition root 는 이 leaf 를 채택할 때 인증/인가 및 CORS 정책을
**정직하게 기록해 둘 반례:** 이후 main 에 통합된 자매 플랫폼 messaging 은 정반대로
**24개 leaf 를 레지스트리에 등록**했다(현재 총 43개 leaf). 즉 레지스트리는 닫혀 있지 않았고,
"확장하면 게이트가 깨진다"는 전제는 과했다. 두 플랫폼이 서로 다른 패턴을 쓰고 있으므로
**어느 쪽으로 통일할지는 미결 아키텍처 결정**이다. graphql 쪽은 모듈 레코드
(`GraphQlStableModule`/`GraphQlAdvancedModule`)가 그대로 leaf 명세로 승격될 수 있는 형태라
분해 비용은 낮게 유지했다.
**어느 쪽으로 통일할지는 미결 아키텍처 결정**이다.
어느 패턴이든 "패키지는 경계가 아니다"라는 약점은 기계 검증으로 메웠다 —
`moduleboundary/GraphQlStableModule`·`GraphQlAdvancedModule` 이 모듈 정체성과 허용 edge 를 값으로
선언하고, `GraphQlModuleBoundaryTest` 가 **실제 소스 트리를 스캔**해 Stable→Advanced import,
CORE 모듈의 프레임워크 import, 선언되지 않은 edge, 미등록 패키지를 실패시킨다. Gradle 이
해주던 일을 테스트가 한다.
sub-package 경계를 값으로 선언하던 `moduleboundary/` 모델(소스 텍스트 스캐너 포함)은
2026-09-25 에 삭제했다. 두 플랫폼 중 어느 패턴으로 통일할지 정할 때 다시 설계한다.
스캔은 컴파일된 클래스가 아니라 **소스 텍스트**를 읽는다. 경계가 금지하는 import 는 상수
인라이닝이나 미보존 시그니처로 바이트코드에서 지워지는 경우가 많아서, 바이트코드 스캔은
리뷰어가 읽는 소스가 여전히 경계를 넘는데도 clean 이라고 보고한다. 그리고 스캐너는
**파일을 하나도 못 찾으면 통과가 아니라 실패한다** — 0개 스캔으로 green 이 되는 것이 이
모델이 막으려는 실패 그 자체다.
## 전송 경계 규칙은 빌드 때 ArchUnit 으로 검사한다
## ArchUnit/JPA 없이 아키텍처 규칙을 강제한 방법
`architecture/` 의 규칙(리졸버 경계, 전송 타입, `@Transactional` 금지, Entity/Document 반환 금지)은
**리플렉션 + 단순명(simple name) 매칭**으로 구현했다. 인바운드 어댑터가 자신이 금지하는 대상
(`jakarta.persistence`, `spring-tx`)에 의존해야 그걸 검사할 수 있다면 본말전도이기 때문이다.
`GraphQlControllerTransactionRule` 이 애노테이션 타입이 아니라 단순명 `Transactional` 을 보는 것은
이 때문이며, 의도된 트레이드오프다. `GraphQlResolverBoundaryRules` 는 스캔 대상 패키지가 비어
있으면 **실패한다** — 검사할 게 없어서 통과하는 조용한 무력화를 막는다.
예전에는 `architecture/` 가 부팅할 때마다 모든 `@Controller` 를 리플렉션으로 검사했다. 지금은
`GraphQlTransportBoundaryArchitectureTest` 가 빌드 때 두 가지를 검사한다: resolver 시그니처(제네릭
인자 포함)에 raw `Map`·persistence 매핑 타입·domain/driver 타입이 없을 것, raw `DataFetcher`
구현은 `scalar`·`schema`·`execution` 에만 있을 것. ArchUnit 은 test 의존성이라
production classpath 에는 여전히 JPA/Spring Data 가 없다 — persistence 애노테이션은 단순명으로
매칭한다. 이 leaf 패키지만 검사하므로 adopter 의 컨트롤러는 adopter 가 같은 규칙을 가져가야 한다.
## 부분 실패는 200, 요청 실패는 4xx
`http/GraphQlHttpStatusMapper.V1` 은 검증 통과 후 발생한 필드 에러를 HTTP 200 + partial data 로
매핑한다. GraphQL over HTTP 초안의 status 294 는 **채택하지 않았다**
(`GraphQlHttpProfile.usesDraftPartialResponseStatus()` 가 `false` 로 못 박고, 초안 프로파일은
`advanced/get/GraphQlHttpDraftCompatibilityReport` 가 "의도적 미채택"으로 기록한다). 초안 상태
코드를 프로덕션 와이어 계약에 넣으면 초안이 바뀔 때 클라이언트가 깨진다.
이 때문에 `Map.copyOf` 를 응답 데이터 경로에 쓸 수 없다 — partial data 는 **정당하게 null 값을
가진다**. `GraphQlExecutionOutcome`·`GraphQlHttpResponse`·`GraphQlContractResponse` 는 null 을
허용하는 `LinkedHashMap` 복사를 쓴다.
HTTP 응답은 Spring GraphQL handler가 만든다. 검증 통과 후 발생한 필드 에러는 HTTP 200 + partial
data 다. GraphQL over HTTP 초안의 status 294 는 쓰지 않는다. 이 leaf 가 따로 두던 HTTP 전송
모델(`GraphQlHttpStatusMapper`, `GraphQlHttpProfile` 등)은 요청 경로에 없어서 2026-09-25 에
삭제했다(`docs/capability-status.md` 제거 표).
## 요청 단위 DB 트랜잭션을 열지 않는다
GraphQL 한 요청은 여러 root field 를 담을 수 있고, 각 root 는 자기 use case 를 호출한다.
요청 전체를 하나의 트랜잭션으로 묶으면 커넥션을 요청 수명만큼 점유하고 부분 실패 의미론이
무너진다. `mutation/GraphQlMutationContractValidator.rejectRequestWideTransaction` 이 이를
계약으로 강제하고, `GraphQlControllerTransactionRule` 이 컨트롤러의 `@Transactional` 을 막는다.
계약으로 강제한다.
## 커서는 HMAC 서명된 버전 있는 keyset
@@ -210,30 +211,28 @@ tenant 간 데이터 누출 경로가 된다. `security/GraphQlBatchContext.cach
허용하고, 변수·인자·actor id 는 `GraphQlSensitiveAttributeFilter` 가 걸러낸다. GraphQL 은
카디널리티 폭발이 쉬운 전송이라 이 게이트가 없으면 메트릭 백엔드가 먼저 죽는다.
## Advanced 는 전부 기본 비활성 + 등급제
## 라이브러리 API — 서비스의 어댑터 leaf에서 `implementation`으로 받아 직접 호출
`advanced/bootstrap/GraphQlAdvancedFeatureFlags` 는 기본 전부 off 다. EXPERIMENTAL 등급
(RSocket, incremental delivery, HTTP GET draft)은 명시적 승인 플래그 없이는
`GraphQlAdvancedModuleGuard` 가 production 활성화를 거부한다. 등급 승격은
`advanced/release/GraphQlAdvancedPromotionDecision` 이 ADR 번호·승인자·미해결 증거를 요구한다 —
"조용히 켜짐"을 구조적으로 불가능하게 만든다.
아래 타입은 auto-configuration 이 빈으로 만들지 않는다. 서비스가 자기 GraphQL 어댑터 leaf 에서
`implementation project(':adapter:inbound:graphql')` 로 받아 resolver 안에서 직접 생성·호출한다
(AGENTS.md capability 규칙의 라이브러리형 예외). 켜는 설정 키는 없다.
## 릴리스 게이트는 증거가 없으면 거부한다
| 기능 | 진입점 | 테스트 |
| --- | --- | --- |
| Relay connection 조립 | `pagination/GraphQlConnectionAssembler`, `GraphQlConnectionPolicy`, `GraphQlConnectionRequest` | `pagination/GraphQlConnectionAssemblerTest` |
| 서명된 keyset cursor | `pagination/HmacGraphQlCursorCodec` + `GraphQlCursorKeyRing.of(Map<String, byte[]>)` — 키 material 은 서비스가 secret 저장소에서 넣는다 | `pagination/HmacGraphQlCursorCodecTest` |
| selection set → fetch profile | `fetch/GraphQlFetchProfileRegistry`, `GraphQlFetchProfileClassifier` | `fetch/GraphQlFetchProfileRegistryTest`, `fetch/GraphQlFetchProfileClassifierTest` |
| 객체 단위 인가 | `security/ApplicationObjectAuthorization` (`GraphQlObjectAuthorizationPort` 구현, application-core `ObjectAccessPolicy` 호출) | `security/ApplicationObjectAuthorizationTest` |
| mutation 결과 payload | `mutation/GraphQlMutationResultMapper`, `GraphQlBusinessResult`, `GraphQlMutationPayload` | `mutation/GraphQlMutationResultMapperTest` |
`release/GraphQlReleaseGate` 와 `advanced/release/GraphQlAdvancedReleaseGate` 는 성능·장애·보안·
호환성 증거가 없으면 **통과시키지 않는다**. Advanced 는 Stable 기준선 없이는 릴리스 자체가
불가능하다. 같은 이유로 `graphqlPerformanceTest` 레인은 성능 태그가 하나도 없으면 실패한다 —
증거 부재를 통과로 위장하지 않기 위한 fail-closed 설계다.
`autoconfigure/GraphQlPolicyRequestPathTest` 가 auto-configuration 이 cursor codec·key ring 을
만들지 않는다는 사실을 고정한다.
## 설계서의 내부 불일치 처리
Stable 16번째 모듈이 산문에서는 `graphql-testkit-security`, Task 1 파일 목록과 설계 §5 에서는
`graphql-testkit-integration` 으로 서로 다르게 적혀 있다. **파일 목록 쪽(testkit-integration)을
채택**하고, 보안 계약 표면은 `testkit/GraphQlSecurityContractSuite` 로 제공했다. 둘 다 실제로
존재하므로 어느 쪽 독법이든 표면은 비지 않는다.
예전 `advanced/**`(SSE, RSocket, federation, incremental delivery, HTTP GET, persisted operation,
subscription replay 등)는 모든 진입점이 바인딩되지 않는 feature flag gate 를 거쳤고 Spring
GraphQL/graphql-java SPI 를 구현한 타입이 없어 2026-09-25 에 삭제했다.
## 아직 구현하지 않은 범위
feature GraphQL schema/resolver 는 여전히 이 leaf 밖이다(스켈레톤은 health 표면만 소유).
실부하 성능 증거와 실 datastore 통합 증거도 이 leaf 밖에서 생성해야 한다 — 다만 그 **부재가
릴리스를 막도록** 게이트가 이미 서 있다.
실부하 성능 증거와 실 datastore 통합 증거도 없다.
+20 -12
View File
@@ -3,9 +3,7 @@ plugins {
id 'ca.spring-config'
id 'java-test-fixtures'
id 'ca.auxiliary-source-set'
id 'ca.graphql-platform'
id 'ca.api-surface'
id 'ca.strict-qualification'
}
// Driving adapter: GraphQL API (skeleton machinery, transport-only).
@@ -30,7 +28,7 @@ auxiliarySourceSets {
// from any adopter's runtime code — an in-memory persisted-operation registry is a perfectly
// working bean until the second instance starts, and a `testContext(String)` mints an authenticated
// actor without a credential. A separate test-fixtures artifact keeps them consumable by the tests
// that want them and out of the jar that runs in production; `verifyGraphQlProductionJar` checks
// that want them and out of the jar that runs in production; GraphQlProductionClassesTest checks
// the second half rather than trusting it.
@@ -93,6 +91,10 @@ dependencies {
// micrometer-observation is on the production classpath; a registry that actually stores series
// is what turns "this tag is bounded" into a number a test can fail on.
testImplementation 'io.micrometer:micrometer-core'
// GraphQlTransportBoundaryArchitectureTest: the resolver-signature and raw-DataFetcher rules
// that used to run by reflection at every boot.
testImplementation libs.archunit.junit5
}
@@ -103,17 +105,23 @@ strictTestLanes {
sourceSet = 'systemTest'
description = 'Runs the GraphQL adapter over a real embedded HTTP server.'
}
lane('graphqlTransportQualificationTest') {
sourceSet = 'systemTest'
description = 'Runs exact no-skip GraphQL conditional transport wire evidence.'
requires 'dev.caskeleton.adapter.inbound.graphql.GraphqlHttpBoundaryQualificationTest'
rejectSkipped = true
jvmArgs '-Duser.timezone=UTC'
}
// The transport-boundary ArchUnit suite runs in `test` too; this lane is the guard that it is
// still discovered and not skipped — a missing class leaves `test` green.
lane('graphqlStableTest') {
description = 'Runs the GraphQL transport-boundary architecture suite and fails if it is gone or skipped.'
requires 'dev.caskeleton.adapter.inbound.graphql.GraphQlTransportBoundaryArchitectureTest'
rejectSkipped = true
jvmArgs '-Duser.timezone=UTC'
}
}
extensions.getByName('strictQualification').register(
'graphqlTransportQualificationTest',
sourceSets.systemTest,
[
'dev.caskeleton.adapter.inbound.graphql.GraphqlHttpBoundaryQualificationTest'
],
'Runs exact no-skip GraphQL conditional transport wire evidence.'
)
// verifyGraphQlApiSurface — every public type this leaf exposes is a committed decision.
//
// One jar, 40-odd packages, and a public type in any of them is reachable from every adopter's
@@ -34,6 +34,11 @@ com.graphql-java:java-dataloader:6.0.0=compileClasspath,runtimeClasspath,systemT
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.jayway.jsonpath:json-path:2.10.0=systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
com.tngtech.archunit:archunit-junit5-api:1.3.0=systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
com.tngtech.archunit:archunit-junit5-engine-api:1.3.0=systemTestRuntimeClasspath,testRuntimeClasspath
com.tngtech.archunit:archunit-junit5-engine:1.3.0=systemTestRuntimeClasspath,testRuntimeClasspath
com.tngtech.archunit:archunit-junit5:1.3.0=systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
com.tngtech.archunit:archunit:1.3.0=systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
com.vaadin.external.google:android-json:0.0.20131108.vaadin1=systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
commons-beanutils:commons-beanutils:1.11.0=checkstyle
commons-collections:commons-collections:3.2.2=checkstyle
@@ -1,37 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.admin;
import java.util.Objects;
/**
* A verified administrator, as the transport established them.
*
* <p>The admin service used to take the operator as a bare {@code String} and check it against an
* allowlist. A string is not evidence: any caller that could reach the service could name any
* operator on the list, so the allowlist described who <em>may</em> administer the registry while
* proving nothing about who actually did. The audit trail then recorded that name as fact.
*
* <p>Only the transport can construct this, having verified the credential, and it records whether
* the credential came from the request path. That check used to exist as a method nobody called.
*
* @param operator the verified operator reference
* @param applicationCredential whether the credential is one the request path also holds
*/
public record GraphQlAdminPrincipal(String operator, boolean applicationCredential) {
public GraphQlAdminPrincipal {
Objects.requireNonNull(operator, "operator is required");
if (operator.isBlank()) {
throw new IllegalArgumentException("operator is required");
}
}
/** A principal established from a dedicated operations credential. */
public static GraphQlAdminPrincipal operations(String operator) {
return new GraphQlAdminPrincipal(operator, false);
}
/** A principal established from a credential the request path also holds. */
public static GraphQlAdminPrincipal fromApplicationCredential(String operator) {
return new GraphQlAdminPrincipal(operator, true);
}
}
@@ -1,46 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.admin;
import java.util.Set;
/**
* Who may change the approved-operation registry.
*
* <p>A separate authority from the request path. Application credentials are held by every running
* instance and reachable from any resolver; if one of them could register or block an operation, a
* compromised request path could rewrite what the whole platform is willing to execute.
*/
public final class GraphQlPersistedOperationAdminAuthorization {
private final Set<String> administrators;
/**
* Creates the authorization.
*
* @param administrators operator references permitted to administer the registry
*/
public GraphQlPersistedOperationAdminAuthorization(Set<String> administrators) {
this.administrators = Set.copyOf(administrators);
if (this.administrators.isEmpty()) {
throw new IllegalArgumentException("at least one registry administrator is required");
}
}
/**
* Requires a verified administrator holding an operations credential.
*
* <p>Both halves are checked here now. The credential-kind refusal used to be a separate public
* method that no caller invoked, so an application credential naming an allowlisted operator
* passed — which is the compromise this class exists to prevent, arriving through the door it
* documented.
*
* @throws GraphQlPersistedOperationAdminDeniedException when the principal is absent, not an
* administrator, or authenticated with a credential the request path also holds
*/
public void requireAdministrator(GraphQlAdminPrincipal principal) {
if (principal == null
|| principal.applicationCredential()
|| !administrators.contains(principal.operator())) {
throw new GraphQlPersistedOperationAdminDeniedException();
}
}
}
@@ -1,17 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.admin;
/**
* Raised when a caller may not administer the approved-operation registry.
*
* <p>Carries no operator identity, so a denial cannot be used to enumerate who the administrators
* are.
*/
public class GraphQlPersistedOperationAdminDeniedException extends RuntimeException {
private static final long serialVersionUID = 1L;
/** Creates the failure. */
public GraphQlPersistedOperationAdminDeniedException() {
super("persisted operation administration is denied");
}
}
@@ -1,47 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.admin;
import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperation;
import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationId;
import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationTransition;
/**
* Applies a registry change and records it, as one durable unit.
*
* <p>The two used to be separate steps: the registry was mutated, then an entry was appended to an
* {@code ArrayList} field. A crash between them left a change nobody could account for, a failure
* in the append left a change with no record, and the list itself was not thread-safe, so two
* concurrent administrators could lose an entry outright. An audit trail with any of those
* properties is worse than none, because it is trusted.
*
* <p>A port rather than an implementation: transactional guarantees over both the registry and the
* trail need a store, and which store provides them is a deployment decision.
*/
public interface GraphQlPersistedOperationAdminPort {
/**
* Registers an operation and records it atomically.
*
* @return the stored operation
* @throws dev.caskeleton.adapter.inbound.graphql.advanced.persisted
* .GraphQlPersistedOperationConflictException when the id already holds a different document
*/
GraphQlPersistedOperation register(
GraphQlPersistedOperation operation, GraphQlPersistedOperationAudit audit);
/**
* Applies a transition and records it atomically.
*
* @return the operation as it now stands
* @throws dev.caskeleton.adapter.inbound.graphql.advanced.persisted
* .GraphQlPersistedOperationNotFoundException when the operation does not exist
* @throws dev.caskeleton.adapter.inbound.graphql.advanced.persisted
* .GraphQlPersistedOperationConflictException when the transition is not permitted
*/
GraphQlPersistedOperation apply(
GraphQlPersistedOperationId operationId,
GraphQlPersistedOperationTransition transition,
GraphQlPersistedOperationAudit audit);
/** The recorded trail, oldest first. */
java.util.List<GraphQlPersistedOperationAudit> auditTrail();
}
@@ -1,161 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.admin;
import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperation;
import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationId;
import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationTransition;
import java.time.Clock;
import java.util.List;
import java.util.Objects;
/**
* The G4 operations plane for approved operations (Advanced plan Task 4).
*
* <p>Every change is authorized against a verified principal and recorded in the same durable unit
* as the change itself, because a registry change silently alters what the whole platform will
* execute. Blocking takes effect immediately; retiring has to pass the usage gate first.
*
* <p>Every command returns the stored operation. A command that cannot be applied throws, so the
* audit trail records changes that happened rather than changes that were attempted — the previous
* service wrote {@code ABSENT -> BLOCKED} for operations that did not exist, which is precisely the
* entry an operator would trust during an incident.
*/
public final class GraphQlPersistedOperationAdminService {
private final GraphQlPersistedOperationAdminPort adminPort;
private final GraphQlPersistedOperationAdminAuthorization authorization;
private final GraphQlPersistedOperationRemovalGate removalGate;
private final Clock clock;
/**
* Creates the service.
*
* @param adminPort applies registry changes and their audit entries atomically
* @param authorization who may administer the registry
* @param removalGate the usage gate protecting retirement
* @param clock clock used for audit timestamps and the quiet period
*/
public GraphQlPersistedOperationAdminService(
GraphQlPersistedOperationAdminPort adminPort,
GraphQlPersistedOperationAdminAuthorization authorization,
GraphQlPersistedOperationRemovalGate removalGate,
Clock clock) {
this.adminPort = Objects.requireNonNull(adminPort);
this.authorization = Objects.requireNonNull(authorization);
this.removalGate = Objects.requireNonNull(removalGate);
this.clock = Objects.requireNonNull(clock);
}
/** Registers a new approved operation. */
public GraphQlPersistedOperation register(
GraphQlPersistedOperation operation,
GraphQlAdminPrincipal principal,
String reason,
String traceId) {
authorization.requireAdministrator(principal);
return adminPort.register(
operation,
audit(operation.id(), principal, reason, "ABSENT", operation.status().name(), traceId));
}
/**
* Blocks an operation immediately.
*
* <p>Takes effect on the next request; a cached parse does not keep it executable.
*/
public GraphQlPersistedOperation block(
GraphQlPersistedOperationBlockCommand command, GraphQlAdminPrincipal principal) {
return transition(
command.operationId(),
GraphQlPersistedOperationTransition.BLOCK,
principal,
command.reason(),
command.traceId());
}
/**
* Reverses a block.
*
* <p>Its own command, so leaving the emergency state is an explicit decision with its own audit
* entry. It used to be reachable by marking a blocked operation deprecated, which reads like a
* documentation change and made it executable again.
*/
public GraphQlPersistedOperation unblock(
GraphQlPersistedOperationId operationId,
GraphQlAdminPrincipal principal,
String reason,
String traceId) {
return transition(
operationId, GraphQlPersistedOperationTransition.UNBLOCK, principal, reason, traceId);
}
/** Marks an operation deprecated, which keeps it executable while clients migrate. */
public GraphQlPersistedOperation deprecate(
GraphQlPersistedOperationId operationId,
GraphQlAdminPrincipal principal,
String reason,
String traceId) {
return transition(
operationId, GraphQlPersistedOperationTransition.DEPRECATE, principal, reason, traceId);
}
/**
* Retires an operation once usage evidence permits it.
*
* <p>Named for what it does. It was called {@code remove}, and it blocked rather than deleted —
* an operator reading the method name would have believed the document was gone.
*
* @throws GraphQlPersistedOperationRemovalRejectedException when it was used within the quiet
* period
*/
public GraphQlPersistedOperation retireAndBlock(
GraphQlPersistedOperationId operationId,
GraphQlPersistedOperationUsage usage,
GraphQlAdminPrincipal principal,
String reason,
String traceId) {
authorization.requireAdministrator(principal);
removalGate.verify(usage, clock.instant());
return transition(
operationId, GraphQlPersistedOperationTransition.RETIRE, principal, reason, traceId);
}
/** The audit trail, in order. */
public List<GraphQlPersistedOperationAudit> auditTrail() {
return adminPort.auditTrail();
}
private GraphQlPersistedOperation transition(
GraphQlPersistedOperationId operationId,
GraphQlPersistedOperationTransition transition,
GraphQlAdminPrincipal principal,
String reason,
String traceId) {
authorization.requireAdministrator(principal);
// The audit entry names the state the operation is actually leaving. The port applies both
// together, so a rejected transition leaves no entry at all.
GraphQlPersistedOperation updated =
adminPort.apply(
operationId,
transition,
audit(
operationId,
principal,
reason,
transition.name(),
transition.target().name(),
traceId));
return updated;
}
private GraphQlPersistedOperationAudit audit(
GraphQlPersistedOperationId operationId,
GraphQlAdminPrincipal principal,
String reason,
String before,
String after,
String traceId) {
return new GraphQlPersistedOperationAudit(
operationId.value(), principal.operator(), reason, before, after, clock.instant(), traceId);
}
}
@@ -1,43 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.admin;
import java.time.Instant;
/**
* One audited change to the approved-operation registry.
*
* <p>Records operator, reason, before/after state, time and trace — the questions asked after an
* incident. It never records variables or credentials, so the audit trail itself stays safe to
* retain.
*
* @param operationId the operation that changed
* @param operator who made the change
* @param reason why
* @param before previous state
* @param after new state
* @param at when
* @param traceId correlation identity
*/
public record GraphQlPersistedOperationAudit(
String operationId,
String operator,
String reason,
String before,
String after,
Instant at,
String traceId) {
public GraphQlPersistedOperationAudit {
if (operationId == null || operationId.isBlank()) {
throw new IllegalArgumentException("audited operation id is required");
}
if (operator == null || operator.isBlank()) {
throw new IllegalArgumentException("audited operator is required");
}
if (reason == null || reason.isBlank()) {
throw new IllegalArgumentException("audited reason is required");
}
if (at == null) {
throw new IllegalArgumentException("audit instant is required");
}
}
}
@@ -1,31 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.admin;
import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationId;
/**
* An instruction to block one approved operation immediately.
*
* <p>The incident-response tool: it stops a single expensive or dangerous operation without a
* redeploy and without taking the endpoint down for everyone. Operator and reason are required
* because a block is a production change that someone will have to explain and eventually reverse.
*
* @param operationId the operation to block
* @param operator who is blocking it
* @param reason why
* @param traceId incident correlation identity
*/
public record GraphQlPersistedOperationBlockCommand(
GraphQlPersistedOperationId operationId, String operator, String reason, String traceId) {
public GraphQlPersistedOperationBlockCommand {
if (operationId == null) {
throw new IllegalArgumentException("operation id is required");
}
if (operator == null || operator.isBlank()) {
throw new IllegalArgumentException("blocking operator is required");
}
if (reason == null || reason.isBlank()) {
throw new IllegalArgumentException("blocking reason is required");
}
}
}
@@ -1,45 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.admin;
import java.time.Duration;
import java.time.Instant;
/**
* Refuses to remove an approved operation that is still in use (Advanced plan Task 4).
*
* <p>The quiet period exists because "no traffic right now" is not the same as "no client uses
* this": a monthly report or a mobile build in slow rollout can be silent for weeks and then send
* the operation again.
*/
public final class GraphQlPersistedOperationRemovalGate {
private final Duration quietPeriod;
/**
* Creates the gate.
*
* @param quietPeriod how long an operation must be unused before it may be removed
*/
public GraphQlPersistedOperationRemovalGate(Duration quietPeriod) {
if (quietPeriod == null || quietPeriod.isNegative()) {
throw new IllegalArgumentException("quiet period must not be negative");
}
this.quietPeriod = quietPeriod;
}
/** The configured quiet period. */
public Duration quietPeriod() {
return quietPeriod;
}
/**
* Verifies that removal is safe.
*
* @throws GraphQlPersistedOperationRemovalRejectedException when the operation was used recently
*/
public void verify(GraphQlPersistedOperationUsage usage, Instant now) {
if (usage.executions() > 0 && usage.lastUsedAt().plus(quietPeriod).isAfter(now)) {
throw new GraphQlPersistedOperationRemovalRejectedException(
"persisted operation used within quiet period");
}
}
}
@@ -1,21 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.admin;
/**
* Raised when an approved operation may not be removed yet.
*
* <p>Removing an operation a deployed client still sends breaks that client with no warning and no
* migration path, so the gate refuses until the usage evidence says otherwise.
*/
public class GraphQlPersistedOperationRemovalRejectedException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates the failure.
*
* @param reason why removal is blocked
*/
public GraphQlPersistedOperationRemovalRejectedException(String reason) {
super(reason);
}
}
@@ -1,29 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.admin;
import java.time.Instant;
/**
* Observed usage of one approved operation.
*
* <p>Counts and a last-used instant, never the callers: usage feeds a removal decision, and the
* identity of who ran an operation is not needed to decide whether it is still in use.
*
* @param lastUsedAt when it was last executed, or {@code null} when never
* @param executions executions observed in the window
*/
public record GraphQlPersistedOperationUsage(Instant lastUsedAt, long executions) {
public GraphQlPersistedOperationUsage {
if (executions < 0) {
throw new IllegalArgumentException("executions cannot be negative");
}
if (executions > 0 && lastUsedAt == null) {
throw new IllegalArgumentException("observed executions require a last-used instant");
}
}
/** Measured, and never used. */
public static GraphQlPersistedOperationUsage unused() {
return new GraphQlPersistedOperationUsage(null, 0);
}
}
@@ -1,59 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap;
import java.util.Locale;
/**
* The Advanced and Experimental capabilities, each behind its own flag (Advanced plan Task 1).
*
* <p>Enumerated so a capability cannot activate merely by being on the classpath. Every one of
* these changes the platform's operational shape — a long-lived connection, an approved-operation
* registry, a second schema topology — and each deserves a deliberate decision.
*/
public enum GraphQlAdvancedCapability {
/** Approved operation registry and execution lookup. */
PERSISTED_OPERATION(GraphQlAdvancedCapabilityGrade.ADVANCED_STABLE),
/** {@code graphql-transport-ws} subscriptions. */
WEBSOCKET_SUBSCRIPTION(GraphQlAdvancedCapabilityGrade.ADVANCED_STABLE),
/** Server-sent event subscriptions, one connection per subscription. */
SSE_SUBSCRIPTION(GraphQlAdvancedCapabilityGrade.ADVANCED),
/** Federation subgraph schema and entity resolution. */
FEDERATION_SUBGRAPH(GraphQlAdvancedCapabilityGrade.ADVANCED),
/** Client and transport DTO code generation. */
CODE_GENERATION(GraphQlAdvancedCapabilityGrade.ADVANCED),
/** GraphQL Java 25 chained DataLoader dispatch. */
DATALOADER_CHAINING(GraphQlAdvancedCapabilityGrade.ADVANCED),
/** Messaging-backed subscription replay. */
SUBSCRIPTION_REPLAY(GraphQlAdvancedCapabilityGrade.ADVANCED),
/** RSocket transport. */
RSOCKET(GraphQlAdvancedCapabilityGrade.EXPERIMENTAL),
/** GraphQL over HTTP GET, per the still-moving draft. */
HTTP_GET(GraphQlAdvancedCapabilityGrade.EXPERIMENTAL),
/** Incremental delivery. */
INCREMENTAL_DELIVERY(GraphQlAdvancedCapabilityGrade.EXPERIMENTAL);
private final GraphQlAdvancedCapabilityGrade grade;
GraphQlAdvancedCapability(GraphQlAdvancedCapabilityGrade grade) {
this.grade = grade;
}
/** The capability's support grade. */
public GraphQlAdvancedCapabilityGrade grade() {
return grade;
}
/** The property that enables it. */
public String featureFlag() {
return "backend.graphql.advanced." + name().toLowerCase(Locale.ROOT).replace('_', '-');
}
}
@@ -1,21 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap;
/**
* Raised when a disabled or unapproved capability is used.
*
* <p>Fails loudly rather than degrading: a subscription endpoint that silently does nothing because
* its flag is off is far harder to diagnose than one that refuses to start.
*/
public class GraphQlAdvancedCapabilityDisabledException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates the failure.
*
* @param capabilityName the capability that is not enabled
*/
public GraphQlAdvancedCapabilityDisabledException(String capabilityName) {
super("GraphQL advanced capability is not enabled: " + capabilityName);
}
}
@@ -1,31 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap;
/**
* How far a capability has been proven.
*
* <p>The grade decides what enabling it takes. An Advanced capability needs its feature flag; an
* Experimental one additionally needs an approval profile in production, because the evidence for
* it has not been collected yet and a config change alone should not put it in front of users.
*/
public enum GraphQlAdvancedCapabilityGrade {
/** Proven in production use; enabled by its feature flag. */
ADVANCED_STABLE(false),
/** Supported; enabled by its feature flag. */
ADVANCED(false),
/** Not yet proven; production activation also requires an approval profile. */
EXPERIMENTAL(true);
private final boolean productionApprovalRequired;
GraphQlAdvancedCapabilityGrade(boolean productionApprovalRequired) {
this.productionApprovalRequired = productionApprovalRequired;
}
/** Whether production activation needs approval beyond the feature flag. */
public boolean productionApprovalRequired() {
return productionApprovalRequired;
}
}
@@ -1,52 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap;
import dev.caskeleton.adapter.inbound.graphql.moduleboundary.GraphQlAdvancedModule;
import dev.caskeleton.adapter.inbound.graphql.moduleboundary.GraphQlModuleBoundary;
import dev.caskeleton.adapter.inbound.graphql.moduleboundary.GraphQlStableModule;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* The Stable/Advanced dependency direction (Advanced plan Task 1).
*
* <p>Advanced consumes Stable, never the other way round. If a Stable module depended on an
* Advanced one, every Stable deployment would carry the Advanced capability's code and
* configuration surface — and the feature flag would be the only thing standing between an ordinary
* service and a subscription runtime.
*/
public final class GraphQlAdvancedDependencyRules {
private GraphQlAdvancedDependencyRules() {}
/**
* Verifies that no Stable module declares an Advanced dependency.
*
* @throws IllegalStateException naming the offending edges
*/
public static void verifyStableDoesNotDependOnAdvanced() {
Set<String> advanced = GraphQlAdvancedModule.moduleIds();
List<String> violations = new ArrayList<>();
GraphQlStableModule.dependencyEdges()
.forEach(
(module, dependencies) ->
dependencies.stream()
.filter(advanced::contains)
.forEach(dependency -> violations.add(module + " -> " + dependency)));
if (!violations.isEmpty()) {
throw new IllegalStateException(
"stable graphql modules must not depend on advanced capabilities: " + violations);
}
}
/** Whether a package belongs to an Advanced capability. */
public static boolean advancedPackage(String packageName) {
return packageName != null
&& packageName.startsWith(GraphQlModuleBoundary.PACKAGE_ROOT + ".advanced");
}
/** Every capability that must be flagged before it can run. */
public static Set<GraphQlAdvancedCapability> flaggedCapabilities() {
return Set.of(GraphQlAdvancedCapability.values());
}
}
@@ -1,40 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap;
import java.util.Set;
/**
* Which Advanced capabilities are enabled, and whether experimental approval was granted.
*
* <p>Nothing is on by default. An Advanced capability that arrived because a dependency was added
* is exactly what the Stable/Advanced split exists to prevent.
*
* @param enabled capabilities whose feature flag is set
* @param experimentalApprovedInProduction whether Experimental capabilities may run in production
*/
public record GraphQlAdvancedFeatureFlags(
Set<GraphQlAdvancedCapability> enabled, boolean experimentalApprovedInProduction) {
public GraphQlAdvancedFeatureFlags {
enabled = Set.copyOf(enabled);
}
/** Nothing enabled. */
public static GraphQlAdvancedFeatureFlags disabled() {
return new GraphQlAdvancedFeatureFlags(Set.of(), false);
}
/** The given capabilities enabled, without experimental production approval. */
public static GraphQlAdvancedFeatureFlags enabling(GraphQlAdvancedCapability... capabilities) {
return new GraphQlAdvancedFeatureFlags(Set.of(capabilities), false);
}
/** Whether a capability's flag is set. */
public boolean isEnabled(GraphQlAdvancedCapability capability) {
return enabled.contains(capability);
}
/** Returns a copy with experimental capabilities approved for production. */
public GraphQlAdvancedFeatureFlags withExperimentalApproval() {
return new GraphQlAdvancedFeatureFlags(enabled, true);
}
}
@@ -1,63 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap;
import java.util.Objects;
/**
* The single gate every Advanced capability passes through.
*
* <p>One place to check means a capability cannot be half-enabled: the flag governs whether it
* starts at all, and an Experimental capability additionally needs production approval, so neither
* can be reached by a code path that forgot to ask.
*/
public final class GraphQlAdvancedModuleGuard {
private final GraphQlAdvancedFeatureFlags flags;
private final boolean production;
/**
* Creates a non-production guard.
*
* @param flags the enabled capabilities
*/
public GraphQlAdvancedModuleGuard(GraphQlAdvancedFeatureFlags flags) {
this(flags, false);
}
/**
* Creates the guard.
*
* @param flags the enabled capabilities
* @param production whether production rules apply
*/
public GraphQlAdvancedModuleGuard(GraphQlAdvancedFeatureFlags flags, boolean production) {
this.flags = Objects.requireNonNull(flags);
this.production = production;
}
/**
* Requires a capability to be enabled and, in production, approved.
*
* @throws GraphQlAdvancedCapabilityDisabledException when it is not
*/
public void requireEnabled(GraphQlAdvancedCapability capability) {
if (!flags.isEnabled(capability)) {
throw new GraphQlAdvancedCapabilityDisabledException(capability.name());
}
if (production
&& capability.grade().productionApprovalRequired()
&& !flags.experimentalApprovedInProduction()) {
throw new GraphQlAdvancedCapabilityDisabledException(
capability.name() + " is experimental and requires an approval profile in production");
}
}
/** Whether a capability may run here. */
public boolean enabled(GraphQlAdvancedCapability capability) {
try {
requireEnabled(capability);
return true;
} catch (GraphQlAdvancedCapabilityDisabledException ex) {
return false;
}
}
}
@@ -1,25 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.chaining;
/**
* Whether chained DataLoader dispatch is enabled, and how deep it may chain.
*
* <p>Off by default. Chained dispatch changes when loaders fire, which changes query counts, batch
* sizes and result ordering — all things existing N+1 regression tests assert on. Enabling it is a
* deliberate change with its own regression evidence, not a free improvement.
*
* @param enabled whether chained dispatch is active
* @param maximumDepth deepest dependency chain permitted
*/
public record GraphQlChainedDataLoaderPolicy(boolean enabled, int maximumDepth) {
public GraphQlChainedDataLoaderPolicy {
if (maximumDepth < 1) {
throw new IllegalArgumentException("chained dispatch depth must be positive");
}
}
/** The Stable default: chained dispatch disabled. */
public static GraphQlChainedDataLoaderPolicy disabled() {
return new GraphQlChainedDataLoaderPolicy(false, 1);
}
}
@@ -1,72 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.chaining;
import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability;
import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedModuleGuard;
import java.util.Objects;
/**
* Enables chained dispatch, once the flag, the graph and the depth all allow it (Advanced plan Task
* 11).
*
* <p>Every Stable DataLoader rule still applies: request scope, actor and tenant isolation, and the
* loader's maximum batch size. Chaining changes dispatch timing, nothing else.
*/
public final class GraphQlChainedDispatchConfigurer {
private final GraphQlAdvancedModuleGuard guard;
private final GraphQlDataLoaderCycleDetector cycleDetector;
/**
* Creates the configurer.
*
* @param guard the Advanced capability guard
* @param cycleDetector the dependency cycle check
*/
public GraphQlChainedDispatchConfigurer(
GraphQlAdvancedModuleGuard guard, GraphQlDataLoaderCycleDetector cycleDetector) {
this.guard = Objects.requireNonNull(guard);
this.cycleDetector = Objects.requireNonNull(cycleDetector);
}
/**
* Verifies chained dispatch may be enabled for a graph.
*
* @throws GraphQlDataLoaderDependencyCycleException when the graph has a cycle
* @throws IllegalArgumentException when the graph is deeper than the policy allows
*/
public void configure(
GraphQlChainedDataLoaderPolicy policy, GraphQlDataLoaderDependencyGraph graph) {
if (!policy.enabled()) {
return;
}
guard.requireEnabled(GraphQlAdvancedCapability.DATALOADER_CHAINING);
cycleDetector.verify(graph);
int depth = depthOf(graph);
if (depth > policy.maximumDepth()) {
throw new IllegalArgumentException(
"loader dependency depth "
+ depth
+ " exceeds the configured maximum of "
+ policy.maximumDepth());
}
}
/** The longest dependency chain in the graph. */
public int depthOf(GraphQlDataLoaderDependencyGraph graph) {
cycleDetector.verify(graph);
int deepest = 0;
for (String loader : graph.loaders()) {
deepest = Math.max(deepest, depthFrom(graph, loader));
}
return deepest;
}
private int depthFrom(GraphQlDataLoaderDependencyGraph graph, String loader) {
var dependencies = graph.edges().getOrDefault(loader, java.util.Set.of());
int deepest = 0;
for (String dependency : dependencies) {
deepest = Math.max(deepest, 1 + depthFrom(graph, dependency));
}
return deepest;
}
}
@@ -1,52 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.chaining;
import java.util.concurrent.atomic.AtomicLong;
/**
* Dispatch counters for chained loading.
*
* <p>Query count and batch size are the numbers that prove chaining helped or hurt. Without them,
* enabling chained dispatch is a change whose effect nobody can measure — which is exactly why it
* defaults to off.
*/
public final class GraphQlChainedLoaderMetrics {
private final AtomicLong dispatches = new AtomicLong();
private final AtomicLong keysLoaded = new AtomicLong();
private final AtomicLong chainedDispatches = new AtomicLong();
/**
* Records one dispatch round.
*
* @param keys keys dispatched
* @param chained whether it was triggered by another loader's completion
*/
public void recordDispatch(int keys, boolean chained) {
dispatches.incrementAndGet();
keysLoaded.addAndGet(keys);
if (chained) {
chainedDispatches.incrementAndGet();
}
}
/** Dispatch rounds. */
public long dispatches() {
return dispatches.get();
}
/** Keys loaded in total. */
public long keysLoaded() {
return keysLoaded.get();
}
/** Dispatch rounds triggered by chaining. */
public long chainedDispatches() {
return chainedDispatches.get();
}
/** Average batch size, the number a chaining regression shows up in first. */
public double averageBatchSize() {
long rounds = dispatches.get();
return rounds == 0 ? 0 : (double) keysLoaded.get() / rounds;
}
}
@@ -1,51 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.chaining;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* Finds dependency cycles before chained dispatch is enabled.
*
* <p>A depth-first walk that reports the cycle it found, not just that one exists — with a dozen
* loaders, "there is a cycle somewhere" is not an actionable diagnostic.
*/
public final class GraphQlDataLoaderCycleDetector {
/**
* Verifies the graph is acyclic.
*
* @throws GraphQlDataLoaderDependencyCycleException naming the cycle
*/
public void verify(GraphQlDataLoaderDependencyGraph graph) {
Set<String> settled = new LinkedHashSet<>();
for (String loader : graph.loaders()) {
if (!settled.contains(loader)) {
walk(graph, loader, new LinkedHashSet<>(), settled);
}
}
}
private void walk(
GraphQlDataLoaderDependencyGraph graph,
String loader,
Set<String> path,
Set<String> settled) {
if (path.contains(loader)) {
List<String> cycle = new ArrayList<>(path);
cycle.add(loader);
throw new GraphQlDataLoaderDependencyCycleException(cycle);
}
if (settled.contains(loader)) {
return;
}
path.add(loader);
for (String dependency : graph.edges().getOrDefault(loader, Set.of())) {
walk(graph, dependency, path, settled);
}
path.remove(loader);
settled.add(loader);
}
}
@@ -1,23 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.chaining;
import java.util.List;
/**
* Raised when loaders depend on each other in a cycle.
*
* <p>A cycle has no dispatch order that satisfies it, so chained dispatch would deadlock or never
* dispatch — failing at startup is far cheaper than discovering it under load.
*/
public class GraphQlDataLoaderDependencyCycleException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates the failure.
*
* @param cycle the loaders on the cycle, in order
*/
public GraphQlDataLoaderDependencyCycleException(List<String> cycle) {
super("data loader dependency cycle: " + cycle);
}
}
@@ -1,44 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.chaining;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
* Declared dependencies between loaders.
*
* <p>Declared rather than inferred: chained dispatch changes when each loader fires, and the
* platform cannot discover from bytecode that one loader's keys come from another's results.
*/
public final class GraphQlDataLoaderDependencyGraph {
private final Map<String, Set<String>> edges = new LinkedHashMap<>();
/**
* Declares that one loader depends on another.
*
* @param loader the dependent loader
* @param dependency the loader it needs first
*/
public GraphQlDataLoaderDependencyGraph dependsOn(String loader, String dependency) {
if (loader == null || dependency == null) {
throw new IllegalArgumentException("loader and dependency names are required");
}
edges.computeIfAbsent(loader, ignored -> new LinkedHashSet<>()).add(dependency);
return this;
}
/** The declared edges. */
public Map<String, Set<String>> edges() {
return Collections.unmodifiableMap(edges);
}
/** Loaders that appear in the graph. */
public Set<String> loaders() {
Set<String> loaders = new LinkedHashSet<>(edges.keySet());
edges.values().forEach(loaders::addAll);
return Collections.unmodifiableSet(loaders);
}
}
@@ -1,63 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.codegen;
import java.util.Objects;
/**
* Plans client code generation and validates the operations it would generate from.
*
* <p>Named a plan because that is what it produces: which kinds may be generated and into which
* package. No source writer and no Gradle task exist behind it, and calling it a generator invited
* the reasonable assumption that running it emitted files.
*
* <p>Validation is the part that does real work, and it is most of the value: an operation that no
* longer matches the schema becomes a build failure in the client's repository instead of a runtime
* error in production.
*/
public final class GraphQlClientOperationGenerator {
private final GraphQlCodegenProfile profile;
/**
* Creates the generator.
*
* @param profile what to generate and where
*/
public GraphQlClientOperationGenerator(GraphQlCodegenProfile profile) {
this.profile = Objects.requireNonNull(profile);
}
/**
* Validates that an operation document still matches the schema.
*
* @param sdl the schema
* @param operationDocument the operation to validate
* @throws GraphQlCodegenBoundaryException when the document does not parse or does not match
*/
public void validateOperation(String sdl, String operationDocument) {
validateOperation(sdl, operationDocument, null);
}
/**
* Validates one named operation from a document.
*
* @param sdl the schema
* @param operationDocument the operation document
* @param operationName which operation, when the document declares several
* @throws GraphQlCodegenBoundaryException when the document does not parse, does not match the
* schema, or names no such operation
*/
public void validateOperation(String sdl, String operationDocument, String operationName) {
GraphQlOperationValidator.validate(sdl, operationDocument, operationName);
}
/** The kinds this plan covers. */
public java.util.Set<String> generatedTypes() {
profile.generatedTypes().forEach(GraphQlGeneratedSourceBoundary.standard()::requireAllowed);
return profile.generatedTypes();
}
/** The package generated client sources are written to. */
public String generatedPackage() {
return profile.generatedPackage();
}
}
@@ -1,20 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.codegen;
/**
* Raised when generation is attempted for a kind that must be written by hand.
*
* <p>Fails at build time, where a generated domain type is still cheap to delete.
*/
public class GraphQlCodegenBoundaryException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates the failure.
*
* @param generatedType the kind that may not be generated
*/
public GraphQlCodegenBoundaryException(String generatedType) {
super(generatedType + " must be written by hand, not generated from the GraphQL schema");
}
}
@@ -1,34 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.codegen;
import java.util.List;
import java.util.Set;
/**
* What one generation run produces, and where.
*
* <p>Generated sources go to their own directory and package. Mixing them with hand-written code
* means the next run either overwrites something a person wrote or silently stops regenerating.
*
* @param generatedPackage package generated sources are written to
* @param generatedSourceDirectory directory they are written to
* @param generatedTypes kinds this run produces
* @param scalarMappings custom scalar mappings
*/
public record GraphQlCodegenProfile(
String generatedPackage,
String generatedSourceDirectory,
Set<String> generatedTypes,
List<GraphQlScalarMapping> scalarMappings) {
public GraphQlCodegenProfile {
if (generatedPackage == null || generatedPackage.isBlank()) {
throw new IllegalArgumentException("generated package is required");
}
if (generatedSourceDirectory == null || generatedSourceDirectory.isBlank()) {
throw new IllegalArgumentException("generated source directory is required");
}
generatedTypes = Set.copyOf(generatedTypes);
scalarMappings = List.copyOf(scalarMappings);
generatedTypes.forEach(GraphQlGeneratedSourceBoundary.standard()::requireAllowed);
}
}
@@ -1,38 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.codegen;
import dev.caskeleton.adapter.inbound.graphql.compat.GraphQlChangeKind;
import dev.caskeleton.adapter.inbound.graphql.compat.GraphQlCompatibilityReport;
import dev.caskeleton.adapter.inbound.graphql.compat.GraphQlSchemaChange;
import java.util.List;
/**
* Reports schema changes that are wire-compatible but break generated client source.
*
* <p>The case worth naming: adding an enum value or a union member is additive on the wire, and it
* breaks a generated client whose {@code switch} is exhaustive. The server sees a successful
* release; the client sees a compile error, or worse, a runtime one.
*/
public final class GraphQlGeneratedCompatibilityGate {
private GraphQlGeneratedCompatibilityGate() {}
/** Changes that need a generated-client rebuild or review, in deterministic order. */
public static List<String> generatedClientImpacts(GraphQlCompatibilityReport report) {
return report.changes().stream()
.filter(GraphQlSchemaChange::reviewRequired)
.map(GraphQlSchemaChange::describe)
.toList();
}
/** Whether a change is additive on the wire yet risky for an exhaustive generated client. */
public static boolean exhaustivenessRisk(GraphQlSchemaChange change) {
return change.kind() == GraphQlChangeKind.ENUM_VALUE_ADDED
|| change.kind() == GraphQlChangeKind.UNION_MEMBER_ADDED
|| change.kind() == GraphQlChangeKind.INTERFACE_IMPLEMENTATION_ADDED;
}
/** Whether the report can be released without regenerating clients. */
public static boolean generatedClientsUnaffected(GraphQlCompatibilityReport report) {
return generatedClientImpacts(report).isEmpty();
}
}
@@ -1,45 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.codegen;
import java.util.Set;
/**
* What code generation may and may not produce (design §21.2).
*
* <p>Client and transport types are good candidates: they mirror the schema exactly and carry no
* logic. Domain entities, use cases and repositories are not — they exist to hold behaviour the
* schema does not describe, and generating them from the schema inverts the dependency the whole
* architecture rests on.
*/
public final class GraphQlGeneratedSourceBoundary {
/** Kinds that may be generated. */
public static final Set<String> ALLOWED =
Set.of("CLIENT_REQUEST", "CLIENT_RESPONSE", "TRANSPORT_INPUT", "TRANSPORT_OUTPUT");
/** Kinds that must be written by hand. */
public static final Set<String> FORBIDDEN =
Set.of("DOMAIN_ENTITY", "APPLICATION_USE_CASE", "REPOSITORY", "PERSISTENCE_MODEL");
private GraphQlGeneratedSourceBoundary() {}
/** The standard boundary. */
public static GraphQlGeneratedSourceBoundary standard() {
return new GraphQlGeneratedSourceBoundary();
}
/** Whether a kind may be generated. */
public boolean isAllowed(String generatedType) {
return ALLOWED.contains(generatedType);
}
/**
* Requires a kind to be generatable.
*
* @throws GraphQlCodegenBoundaryException when it is not
*/
public void requireAllowed(String generatedType) {
if (!isAllowed(generatedType)) {
throw new GraphQlCodegenBoundaryException(generatedType);
}
}
}
@@ -1,111 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.codegen;
import graphql.language.Definition;
import graphql.language.Document;
import graphql.language.OperationDefinition;
import graphql.parser.InvalidSyntaxException;
import graphql.parser.Parser;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import graphql.schema.idl.errors.SchemaProblem;
import graphql.validation.ValidationError;
import graphql.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Validates a client operation against the schema it will be compiled for.
*
* <p>The previous check confirmed both strings were non-blank and then compared the schema with
* itself, which is true of every schema. The operation document was never read, so a document with
* invalid syntax, an unknown field, or an argument that does not exist passed validation and became
* generated client code that fails at runtime — in the client's repository, against a schema that
* had already changed.
*
* <p>The schema is compiled to an executable {@link GraphQLSchema} because that is what the
* validator needs: field and argument existence, type compatibility and variable usage are
* questions about types, and a parsed SDL registry alone cannot answer them.
*/
public final class GraphQlOperationValidator {
private GraphQlOperationValidator() {}
/**
* Validates one operation document against a schema.
*
* @param sdl the schema, as SDL
* @param operationDocument the client operation
* @param operationName the operation to validate when the document declares several, or {@code
* null} when it declares one
* @throws GraphQlCodegenBoundaryException when either input is missing, the schema does not
* compile, the document does not parse, the document does not match the schema, or the
* operation to validate is ambiguous
*/
public static void validate(String sdl, String operationDocument, String operationName) {
if (sdl == null || sdl.isBlank() || operationDocument == null || operationDocument.isBlank()) {
throw new GraphQlCodegenBoundaryException("CLIENT_REQUEST");
}
GraphQLSchema schema = compile(sdl);
Document document = parse(operationDocument);
requireUnambiguousOperation(document, operationName);
List<ValidationError> errors = new Validator().validateDocument(schema, document, Locale.ROOT);
if (!errors.isEmpty()) {
List<String> messages = new ArrayList<>();
errors.forEach(error -> messages.add(error.getMessage()));
throw new GraphQlCodegenBoundaryException("CLIENT_REQUEST: " + String.join("; ", messages));
}
}
private static GraphQLSchema compile(String sdl) {
try {
TypeDefinitionRegistry registry = new SchemaParser().parse(sdl);
return new SchemaGenerator().makeExecutableSchema(registry, RuntimeWiring.MOCKED_WIRING);
} catch (SchemaProblem | InvalidSyntaxException invalid) {
throw new GraphQlCodegenBoundaryException("CLIENT_REQUEST: schema does not compile");
}
}
private static Document parse(String operationDocument) {
try {
return Parser.parse(operationDocument);
} catch (InvalidSyntaxException invalid) {
throw new GraphQlCodegenBoundaryException("CLIENT_REQUEST: operation does not parse");
}
}
/**
* Refuses a document whose operation cannot be identified.
*
* <p>Generating from a multi-operation document without being told which one means picking by
* position, and the generated client then changes meaning when someone reorders the file.
*/
private static void requireUnambiguousOperation(Document document, String operationName) {
List<OperationDefinition> operations = new ArrayList<>();
for (Definition<?> definition : document.getDefinitions()) {
if (definition instanceof OperationDefinition operation) {
operations.add(operation);
}
}
if (operations.isEmpty()) {
throw new GraphQlCodegenBoundaryException("CLIENT_REQUEST: document declares no operation");
}
if (operationName == null || operationName.isBlank()) {
if (operations.size() > 1) {
throw new GraphQlCodegenBoundaryException(
"CLIENT_REQUEST: document declares " + operations.size() + " operations");
}
return;
}
boolean found = operations.stream().anyMatch(op -> operationName.equals(op.getName()));
if (!found) {
throw new GraphQlCodegenBoundaryException(
"CLIENT_REQUEST: no operation named " + operationName);
}
}
}
@@ -1,27 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.codegen;
/**
* How a custom scalar maps onto a generated Java type.
*
* <p>Declared explicitly, because a generator that does not know a scalar falls back to {@code
* String} — and a {@code BigDecimal} arriving as a {@code String} in generated client code is
* precisely the precision loss the scalar was defined to prevent.
*
* @param scalarName the GraphQL scalar
* @param javaType the generated Java type
* @param codecId the codec that converts between them
*/
public record GraphQlScalarMapping(String scalarName, String javaType, String codecId) {
public GraphQlScalarMapping {
if (scalarName == null || scalarName.isBlank()) {
throw new IllegalArgumentException("scalar name is required");
}
if (javaType == null || javaType.isBlank()) {
throw new IllegalArgumentException("generated Java type is required");
}
if (codecId == null || codecId.isBlank()) {
throw new IllegalArgumentException("codec id is required");
}
}
}
@@ -1,54 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.codegen;
import java.util.Objects;
import java.util.Set;
/**
* Generates server-side transport DTOs.
*
* <p>Transport types only. A generated type that a resolver maps to and from is fine; a generated
* type the Application layer consumes directly would make every schema change a change to business
* code.
*/
public final class GraphQlTransportTypeGenerator {
private static final Set<String> TRANSPORT_KINDS = Set.of("TRANSPORT_INPUT", "TRANSPORT_OUTPUT");
private final GraphQlCodegenProfile profile;
/**
* Creates the generator.
*
* @param profile what to generate and where
*/
public GraphQlTransportTypeGenerator(GraphQlCodegenProfile profile) {
this.profile = Objects.requireNonNull(profile);
}
/**
* The transport kinds this profile generates.
*
* @throws GraphQlCodegenBoundaryException when the profile asks for a non-transport kind
*/
public Set<String> transportTypes() {
profile.generatedTypes().stream()
.filter(kind -> !TRANSPORT_KINDS.contains(kind) && !kind.startsWith("CLIENT_"))
.findFirst()
.ifPresent(
kind -> {
throw new GraphQlCodegenBoundaryException(kind);
});
return profile.generatedTypes().stream()
.filter(TRANSPORT_KINDS::contains)
.collect(java.util.stream.Collectors.toUnmodifiableSet());
}
/**
* Whether generated sources are separated from hand-written ones.
*
* @param handWrittenSourceDirectory where hand-written sources live
*/
public boolean separatedFrom(String handWrittenSourceDirectory) {
return !profile.generatedSourceDirectory().equals(handWrittenSourceDirectory);
}
}
@@ -1,44 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.composition;
import java.util.ArrayList;
import java.util.List;
/**
* Blocks a federated release without complete evidence.
*
* <p>The gate exists because in a federated topology a mistake is not contained: an entity key
* change or an unbudgeted cross-subgraph call degrades queries the owning team never wrote.
*/
public final class GraphQlFederationCompositionGate {
/**
* Verifies a federated release.
*
* @throws GraphQlFederationReleaseRejectedException naming the missing evidence
*/
public void verify(GraphQlFederationReleaseEvidence evidence) {
List<String> missing = missing(evidence);
if (!missing.isEmpty()) {
throw new GraphQlFederationReleaseRejectedException(
"federation composition evidence incomplete: " + missing);
}
}
/** Which evidence is missing, in a deterministic order. */
public List<String> missing(GraphQlFederationReleaseEvidence evidence) {
List<String> missing = new ArrayList<>();
if (!evidence.compositionPassed()) {
missing.add("composition");
}
if (!evidence.entityContractsPassed()) {
missing.add("entityContracts");
}
if (!evidence.latencyPassed()) {
missing.add("latency");
}
if (!evidence.failureContractsPassed()) {
missing.add("failureContracts");
}
return List.copyOf(missing);
}
}
@@ -1,38 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.composition;
import java.util.List;
/**
* What composition CI reported.
*
* <p>Produced by the router project, consumed here: this repository owns a subgraph and cannot
* compose the supergraph itself, so the result is an input to the gate rather than something it
* computes.
*
* @param composed whether the supergraph composed
* @param supergraphHash hash of the composed supergraph, or {@code null} when composition failed
* @param problems composition problems, empty when it succeeded
*/
public record GraphQlFederationCompositionResult(
boolean composed, String supergraphHash, List<String> problems) {
public GraphQlFederationCompositionResult {
problems = problems == null ? List.of() : List.copyOf(problems);
if (composed && (supergraphHash == null || supergraphHash.isBlank())) {
throw new IllegalArgumentException("a successful composition must report a supergraph hash");
}
if (!composed && problems.isEmpty()) {
throw new IllegalArgumentException("a failed composition must report its problems");
}
}
/** A successful composition. */
public static GraphQlFederationCompositionResult composed(String supergraphHash) {
return new GraphQlFederationCompositionResult(true, supergraphHash, List.of());
}
/** A failed composition. */
public static GraphQlFederationCompositionResult failed(List<String> problems) {
return new GraphQlFederationCompositionResult(false, null, problems);
}
}
@@ -1,42 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.composition;
/**
* Which must deploy first, the subgraph or the router.
*
* <p>Order matters because the two are separate deployments. A subgraph that removes a field before
* the router stops asking for it breaks every query in flight; a router that starts asking for a
* field the subgraph does not have yet breaks just as loudly. Additive changes go subgraph-first,
* removals router-first.
*/
public enum GraphQlFederationDeploymentOrder {
/** Subgraph first: it adds capability the router will start using. */
SUBGRAPH_FIRST,
/** Router first: it must stop using capability the subgraph is removing. */
ROUTER_FIRST;
/**
* The required order for a change.
*
* @param removesCapability whether the change removes a field, key or type
*/
public static GraphQlFederationDeploymentOrder forChange(boolean removesCapability) {
return removesCapability ? ROUTER_FIRST : SUBGRAPH_FIRST;
}
/**
* Verifies a planned deployment order.
*
* @param removesCapability whether the change removes capability
* @param planned the planned order
* @throws GraphQlFederationReleaseRejectedException when the order would break in-flight queries
*/
public static void verify(boolean removesCapability, GraphQlFederationDeploymentOrder planned) {
GraphQlFederationDeploymentOrder required = forChange(removesCapability);
if (required != planned) {
throw new GraphQlFederationReleaseRejectedException(
"this change requires " + required + " deployment, not " + planned);
}
}
}
@@ -1,40 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.composition;
import java.time.Duration;
/**
* The latency a federated query may spend, and how many subgraph hops it may take.
*
* <p>Hops matter as much as time. A query that fans out to four subgraphs pays four network round
* trips before any data is read, and a per-entity downstream call turns that into a cross-subgraph
* N+1 — invisible in any single subgraph's own metrics.
*
* @param maximumTotal end-to-end budget for a federated query
* @param maximumSubgraphHops subgraph calls one query may make
* @param maximumPerEntityCalls per-entity downstream calls permitted
*/
public record GraphQlFederationLatencyBudget(
Duration maximumTotal, int maximumSubgraphHops, int maximumPerEntityCalls) {
public GraphQlFederationLatencyBudget {
if (maximumTotal == null || maximumTotal.isZero() || maximumTotal.isNegative()) {
throw new IllegalArgumentException("federation latency budget must be positive");
}
if (maximumSubgraphHops < 1 || maximumPerEntityCalls < 0) {
throw new IllegalArgumentException("invalid federation call budget");
}
}
/**
* Whether measured behaviour is within budget.
*
* @param observedTotal measured end-to-end latency
* @param observedHops measured subgraph hops
* @param observedPerEntityCalls measured per-entity downstream calls
*/
public boolean within(Duration observedTotal, int observedHops, int observedPerEntityCalls) {
return observedTotal.compareTo(maximumTotal) <= 0
&& observedHops <= maximumSubgraphHops
&& observedPerEntityCalls <= maximumPerEntityCalls;
}
}
@@ -1,25 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.composition;
/**
* The evidence a federated release requires (Advanced plan Task 13).
*
* <p>Composition succeeding is the weakest of the four. It proves the schemas fit together, not
* that entity keys are stable, that cross-subgraph latency is within budget, or that a partial
* subgraph failure produces a sensible response rather than a nulled supergraph.
*
* @param compositionPassed the supergraph composes
* @param entityContractsPassed entity keys and ownership verified
* @param latencyPassed cross-subgraph latency within budget
* @param failureContractsPassed partial-failure behaviour verified
*/
public record GraphQlFederationReleaseEvidence(
boolean compositionPassed,
boolean entityContractsPassed,
boolean latencyPassed,
boolean failureContractsPassed) {
/** Whether every kind of evidence is present. */
public boolean complete() {
return compositionPassed && entityContractsPassed && latencyPassed && failureContractsPassed;
}
}
@@ -1,21 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.composition;
/**
* Raised when a federated release lacks required evidence.
*
* <p>Names what is missing: a federated deployment affects services owned by other teams, so
* "blocked" has to come with the reason.
*/
public class GraphQlFederationReleaseRejectedException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates the failure.
*
* @param reason which evidence is missing
*/
public GraphQlFederationReleaseRejectedException(String reason) {
super(reason);
}
}
@@ -1,29 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.composition;
import java.util.Map;
import java.util.Set;
/**
* Which subgraphs use which of this subgraph's entity fields.
*
* <p>The precondition for changing an entity key: without it, the only way to find out who depended
* on a field is to remove it and wait for another team's incident.
*
* @param consumersByField consuming subgraph names, keyed by entity field
*/
public record GraphQlFederationUsageReport(Map<String, Set<String>> consumersByField) {
public GraphQlFederationUsageReport {
consumersByField = Map.copyOf(consumersByField);
}
/** Subgraphs that consume a field. */
public Set<String> consumersOf(String field) {
return consumersByField.getOrDefault(field, Set.of());
}
/** Whether a field may be changed without coordinating with another team. */
public boolean safeToChange(String field) {
return consumersOf(field).isEmpty();
}
}
@@ -1,41 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.composition;
import dev.caskeleton.adapter.inbound.graphql.advanced.federation.GraphQlFederationEntityKey;
import java.util.List;
/**
* What one subgraph publishes into the supergraph.
*
* <p>An owner is required. In a federated topology an entity key change breaks other teams'
* queries, and "who approves this" has to be answerable before the change is proposed, not after it
* lands.
*
* @param subgraphName the subgraph's name
* @param owner the team that owns it
* @param schemaHash hash of the subgraph's schema
* @param entityKeys entity keys it publishes
*/
public record GraphQlSubgraphContract(
String subgraphName,
String owner,
String schemaHash,
List<GraphQlFederationEntityKey> entityKeys) {
public GraphQlSubgraphContract {
if (subgraphName == null || subgraphName.isBlank()) {
throw new IllegalArgumentException("subgraph name is required");
}
if (owner == null || owner.isBlank()) {
throw new IllegalArgumentException("subgraph owner is required");
}
if (schemaHash == null || schemaHash.isBlank()) {
throw new IllegalArgumentException("subgraph schema hash is required");
}
entityKeys = List.copyOf(entityKeys);
}
/** Whether an entity key changed compared with the deployed contract. */
public boolean entityKeysChangedFrom(GraphQlSubgraphContract deployed) {
return deployed != null && !deployed.entityKeys().equals(entityKeys);
}
}
@@ -1,47 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.federation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Resolves many entity representations as one batch.
*
* <p>A router sends the whole {@code _entities} array at once, so resolving them one at a time
* recreates the N+1 that DataLoader exists to prevent — except now it is one query per entity per
* subgraph per federated request.
*/
public final class GraphQlFederationBatchResolver {
private final GraphQlFederationEntityResolver resolver;
/**
* Creates the batch resolver.
*
* @param resolver the per-representation validator
*/
public GraphQlFederationBatchResolver(GraphQlFederationEntityResolver resolver) {
this.resolver = Objects.requireNonNull(resolver);
}
/**
* Validates a batch and extracts the key values, preserving order.
*
* <p>Order matters: the router matches results back to representations positionally.
*
* @throws GraphQlFederationRepresentationException when any representation is incomplete
*/
public List<Map<String, Object>> validateAndExtractKeys(
List<Map<String, Object>> representations) {
List<Map<String, Object>> keys = new ArrayList<>(representations.size());
for (Map<String, Object> representation : representations) {
resolver.validateRepresentation(representation);
Map<String, Object> keyValues = new java.util.LinkedHashMap<>();
resolver.key().fields().forEach(field -> keyValues.put(field, representation.get(field)));
keys.add(Map.copyOf(keyValues));
}
return List.copyOf(keys);
}
}
@@ -1,45 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.federation;
import java.util.List;
/**
* What this repository owns in a federated topology (design §21.1).
*
* <p>The subgraph, and nothing else. A router is a separate deployment with its own availability,
* its own scaling and its own on-call — running one is a project, not a library feature.
*/
public enum GraphQlFederationCapability {
/** This service publishes a subgraph schema. */
SUBGRAPH(true),
/** Composing subgraphs into a supergraph, owned by a separate project. */
ROUTER(false),
/** Schema stitching, not supported at all. */
SCHEMA_STITCHING(false);
private final boolean ownedHere;
GraphQlFederationCapability(boolean ownedHere) {
this.ownedHere = ownedHere;
}
/** Whether this repository implements the capability. */
public boolean ownedHere() {
return ownedHere;
}
/** The preconditions that must hold before federation is worth adopting. */
public static List<String> activationGate() {
return List.of(
"independently deployed services",
"schema ownership actually split across teams",
"composition CI",
"a router operations owner",
"distributed tracing",
"a cross-subgraph latency budget",
"an entity key lifecycle policy",
"a partial-failure policy");
}
}
@@ -1,31 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.federation;
import java.util.List;
/**
* An entity's {@code @key} fields.
*
* <p>A versioned public contract, not an implementation detail. Every other subgraph and the router
* send these fields to identify the entity, so changing one is a breaking change across services
* that deploy independently.
*
* @param typeName the entity type
* @param fields the key fields, in declaration order
*/
public record GraphQlFederationEntityKey(String typeName, List<String> fields) {
public GraphQlFederationEntityKey {
if (typeName == null || typeName.isBlank()) {
throw new IllegalArgumentException("federation entity type name is required");
}
fields = List.copyOf(fields);
if (fields.isEmpty()) {
throw new IllegalArgumentException("federation entity key cannot be empty");
}
}
/** The {@code @key(fields: "...")} directive argument this key corresponds to. */
public String directiveFields() {
return String.join(" ", fields);
}
}
@@ -1,49 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.federation;
import java.util.Map;
import java.util.Objects;
/**
* Validates entity representations before resolving them (Advanced plan Task 12).
*
* <p>Resolution itself goes through an Application query service, never a repository: an entity
* reference arriving from a router is still a request from outside, and it needs the same
* authorization and tenant scoping as one arriving over HTTP.
*/
public final class GraphQlFederationEntityResolver {
private final GraphQlFederationEntityKey key;
/**
* Creates the resolver.
*
* @param key the entity's declared key
*/
public GraphQlFederationEntityResolver(GraphQlFederationEntityKey key) {
this.key = Objects.requireNonNull(key);
}
/** The entity key this resolver serves. */
public GraphQlFederationEntityKey key() {
return key;
}
/**
* Validates one representation.
*
* @throws GraphQlFederationRepresentationException when a declared key field is missing or the
* {@code __typename} does not match
*/
public void validateRepresentation(Map<String, Object> representation) {
Object typeName = representation.get("__typename");
if (typeName != null && !key.typeName().equals(typeName)) {
throw new GraphQlFederationRepresentationException(
"representation is for a different entity type");
}
for (String field : key.fields()) {
if (!representation.containsKey(field)) {
throw new GraphQlFederationRepresentationException("missing federation entity key field");
}
}
}
}
@@ -1,34 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.federation;
import java.util.List;
/**
* Federation configuration for this subgraph.
*
* <p>Off by default, and a single executable schema remains the Stable topology: federation buys
* independent deployment at the cost of cross-subgraph N+1, network amplification, deployment
* ordering and duplicated authorization.
*
* @param enabled whether federation wiring is registered
* @param subgraphName this subgraph's name in the supergraph
* @param entityKeys the entity keys this subgraph publishes
*/
public record GraphQlFederationProperties(
boolean enabled, String subgraphName, List<GraphQlFederationEntityKey> entityKeys) {
public GraphQlFederationProperties {
entityKeys = entityKeys == null ? List.of() : List.copyOf(entityKeys);
if (enabled && (subgraphName == null || subgraphName.isBlank())) {
throw new IllegalArgumentException("an enabled subgraph requires a name");
}
if (enabled && entityKeys.isEmpty()) {
throw new IllegalArgumentException(
"an enabled subgraph must publish at least one entity key");
}
}
/** Federation disabled: the single executable schema default. */
public static GraphQlFederationProperties disabled() {
return new GraphQlFederationProperties(false, null, List.of());
}
}
@@ -1,21 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.federation;
/**
* Raised when a router sends an entity representation missing a declared key field.
*
* <p>Rejected rather than resolved partially: without the full key the subgraph would have to guess
* which entity was meant, and a guess here returns another tenant's or another user's object.
*/
public class GraphQlFederationRepresentationException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates the failure.
*
* @param reason bounded description; never the representation itself
*/
public GraphQlFederationRepresentationException(String reason) {
super(reason);
}
}
@@ -1,54 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.federation;
import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability;
import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedModuleGuard;
import java.util.List;
import java.util.Objects;
/**
* Registers federation wiring, only when federation is actually enabled.
*
* <p>Without the flag nothing is registered at all: a schema that advertises {@code _entities} and
* {@code _service} tells a router it may send entity references, and the router will.
*/
public final class GraphQlFederationSchemaFactory {
private final GraphQlAdvancedModuleGuard guard;
private final GraphQlFederationProperties properties;
/**
* Creates the factory.
*
* @param guard the Advanced capability guard
* @param properties federation configuration
*/
public GraphQlFederationSchemaFactory(
GraphQlAdvancedModuleGuard guard, GraphQlFederationProperties properties) {
this.guard = Objects.requireNonNull(guard);
this.properties = Objects.requireNonNull(properties);
}
/** Whether federation wiring should be registered. */
public boolean federationEnabled() {
return properties.enabled() && guard.enabled(GraphQlAdvancedCapability.FEDERATION_SUBGRAPH);
}
/**
* The entity resolvers this subgraph publishes.
*
* @throws dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap
* .GraphQlAdvancedCapabilityDisabledException when federation is configured but not enabled
*/
public List<GraphQlFederationEntityResolver> entityResolvers() {
if (!properties.enabled()) {
return List.of();
}
guard.requireEnabled(GraphQlAdvancedCapability.FEDERATION_SUBGRAPH);
return properties.entityKeys().stream().map(GraphQlFederationEntityResolver::new).toList();
}
/** What this repository owns; a router is not part of it. */
public GraphQlFederationCapability capability() {
return GraphQlFederationCapability.SUBGRAPH;
}
}
@@ -1,45 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.get;
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpProfile;
import java.util.List;
import java.util.Map;
/**
* What this deployment implements of the moving GraphQL over HTTP draft.
*
* <p>The point of tracking it separately: the draft can change without the Stable POST contract
* changing. This report is where draft drift is observed, so adopting a change stays a decision
* rather than a consequence of upgrading a library.
*
* @param draftStage the draft stage this was checked against
* @param supportedFeatures draft features implemented
* @param deliberatelyUnsupported draft features deliberately not implemented
*/
public record GraphQlHttpDraftCompatibilityReport(
String draftStage, List<String> supportedFeatures, List<String> deliberatelyUnsupported) {
public GraphQlHttpDraftCompatibilityReport {
supportedFeatures = List.copyOf(supportedFeatures);
deliberatelyUnsupported = List.copyOf(deliberatelyUnsupported);
}
/** The current position: POST is Stable, GET is experimental, and 294 is not adopted. */
public static GraphQlHttpDraftCompatibilityReport current() {
return new GraphQlHttpDraftCompatibilityReport(
"Stage 2 Draft",
List.of(
"POST", "application/graphql-response+json", "4xx request errors", "200 field errors"),
List.of(
"GET (experimental only)",
"status " + GraphQlHttpProfile.DRAFT_PARTIAL_RESPONSE_STATUS + " for partial responses",
"HTTP array batching"));
}
/** The report as a flat map, for the release evidence. */
public Map<String, Object> asMap() {
return Map.of(
"draftStage", draftStage,
"supported", supportedFeatures,
"deliberatelyUnsupported", deliberatelyUnsupported);
}
}
@@ -1,47 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.get;
/**
* Whether a GET response may be cached, and by whom.
*
* <p>The reason GET is attractive is caching, and the reason it is dangerous is the same. A GraphQL
* response depends on the actor, so a shared cache keyed by URL will serve one user's data to
* another.
*/
public enum GraphQlHttpGetCachePolicy {
/** No caching. */
NO_STORE("no-store"),
/** The requesting client may cache; no shared cache may. */
PRIVATE("private, max-age=0"),
/**
* A shared cache may store the response; only sound for responses with no actor-specific data.
*/
SHARED("public, max-age=60");
private final String cacheControl;
GraphQlHttpGetCachePolicy(String cacheControl) {
this.cacheControl = cacheControl;
}
/** The {@code Cache-Control} header this policy sets. */
public String cacheControl() {
return cacheControl;
}
/**
* The policy for a request.
*
* @param actorSpecificResponse whether the response depends on who asked
* @param profile the GET profile in force
*/
public static GraphQlHttpGetCachePolicy forRequest(
boolean actorSpecificResponse, GraphQlHttpGetProfile profile) {
if (actorSpecificResponse) {
return NO_STORE;
}
return profile.sharedCacheAllowed() ? SHARED : PRIVATE;
}
}
@@ -1,42 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.get;
/**
* CSRF protection for GET requests carrying ambient credentials.
*
* <p>Required whenever cookies are the credential. A GET with cookies is triggerable by any page
* that can make the browser fetch a URL, and the read it performs is a read of the victim's data.
*/
public final class GraphQlHttpGetCsrfPolicy {
private final boolean cookieCredentials;
private final GraphQlHttpGetProfile profile;
/**
* Creates the policy.
*
* @param cookieCredentials whether the deployment authenticates with cookies
* @param profile the GET profile in force
*/
public GraphQlHttpGetCsrfPolicy(boolean cookieCredentials, GraphQlHttpGetProfile profile) {
this.cookieCredentials = cookieCredentials;
this.profile = profile;
}
/** Whether a CSRF token must accompany the request. */
public boolean csrfTokenRequired() {
return cookieCredentials || profile.csrfRequired();
}
/**
* Verifies a request.
*
* @param csrfTokenPresent whether a valid CSRF token accompanied it
* @throws GraphQlHttpGetRejectedException when protection is required and missing
*/
public void verify(boolean csrfTokenPresent) {
if (csrfTokenRequired() && !csrfTokenPresent) {
throw new GraphQlHttpGetRejectedException(
"a CSRF token is required for cookie-authenticated GET requests");
}
}
}
@@ -1,28 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.get;
/**
* Which operations GET may carry (Advanced plan Task 17).
*
* <p>Queries only. A mutation over GET is a side effect behind a URL: prefetchers follow it, caches
* store it, and a link is enough to trigger it.
*/
public final class GraphQlHttpGetOperationPolicy {
private GraphQlHttpGetOperationPolicy() {}
/** The query-only policy. */
public static GraphQlHttpGetOperationPolicy queryOnly() {
return new GraphQlHttpGetOperationPolicy();
}
/**
* Verifies the operation type.
*
* @throws GraphQlHttpGetRejectedException for a mutation or subscription
*/
public void verify(String operationType) {
if (!"query".equals(operationType)) {
throw new GraphQlHttpGetRejectedException("GET supports query operations only");
}
}
}
@@ -1,41 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.get;
/**
* The GET draft profile's limits.
*
* <p>A URI budget, because query strings are truncated by proxies at lengths nobody controls, and a
* CSRF requirement whenever cookies are involved: a GET with ambient credentials is triggerable
* from any page.
*
* @param maximumUriBytes largest accepted request URI
* @param sharedCacheAllowed whether a shared cache may store responses
* @param csrfRequired whether CSRF protection is required
*/
public record GraphQlHttpGetProfile(
int maximumUriBytes, boolean sharedCacheAllowed, boolean csrfRequired) {
/** A conservative URI budget, below common proxy limits. */
public static final int CONSERVATIVE_URI_BYTES = 2_048;
public GraphQlHttpGetProfile {
if (maximumUriBytes < 1) {
throw new IllegalArgumentException("maximum URI size must be positive");
}
}
/** The default: conservative URI budget, no shared caching, CSRF required. */
public static GraphQlHttpGetProfile conservative() {
return new GraphQlHttpGetProfile(CONSERVATIVE_URI_BYTES, false, true);
}
/**
* Verifies a request URI fits the budget.
*
* @throws GraphQlHttpGetRejectedException when it does not
*/
public void verifyUriSize(int uriBytes) {
if (uriBytes > maximumUriBytes) {
throw new GraphQlHttpGetRejectedException("request URI exceeds the configured maximum");
}
}
}
@@ -1,21 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.get;
/**
* Raised when a GET request is outside the query-only draft profile.
*
* <p>Carries no query text: a rejected GET's document is in the URL, which is the reason GET is
* risky in the first place.
*/
public class GraphQlHttpGetRejectedException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates the failure.
*
* @param reason bounded description
*/
public GraphQlHttpGetRejectedException(String reason) {
super(reason);
}
}
@@ -1,53 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.get;
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpRequestEnvelope;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;
/**
* Parses a GET query string into the standard request envelope.
*
* <p>{@code variables} and {@code extensions} arrive as URL-encoded JSON text, which is one more
* place a malformed value can appear — the parser rejects rather than coerces, and the resulting
* envelope is the same one the POST profile validates.
*/
public final class GraphQlHttpGetRequestParser {
private final GraphQlHttpGetProfile profile;
/**
* Creates the parser.
*
* @param profile the GET profile's limits
*/
public GraphQlHttpGetRequestParser(GraphQlHttpGetProfile profile) {
this.profile = Objects.requireNonNull(profile);
}
/**
* Parses query parameters into an envelope.
*
* @param parameters decoded query parameters
* @param uriBytes the raw request URI size
* @throws GraphQlHttpGetRejectedException when the URI is too large or the document is missing
*/
public GraphQlHttpRequestEnvelope parse(Map<String, String> parameters, int uriBytes) {
profile.verifyUriSize(uriBytes);
String query = parameters.get("query");
if (query == null || query.isBlank()) {
throw new GraphQlHttpGetRejectedException("query parameter is required");
}
verifyEncodable(query);
return new GraphQlHttpRequestEnvelope(
query, parameters.get("operationName"), Map.of(), Map.of());
}
private static void verifyEncodable(String value) {
if (value.getBytes(StandardCharsets.UTF_8).length != value.length()
&& value.chars().anyMatch(Character::isISOControl)) {
throw new GraphQlHttpGetRejectedException("query parameter contains invalid characters");
}
}
}
@@ -1,45 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.incremental;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlCancellation;
import java.util.Objects;
/**
* Stops outstanding patches when the client goes away.
*
* <p>A client that disconnects after the initial result leaves deferred work in flight. Without
* cancellation those fragments keep resolving — doing database and downstream work for a response
* that can no longer be delivered.
*/
public final class GraphQlIncrementalCancellation {
private final GraphQlCancellation cancellation;
/**
* Creates the cancellation bridge.
*
* @param cancellation the request's cancellation signal
*/
public GraphQlIncrementalCancellation(GraphQlCancellation cancellation) {
this.cancellation = Objects.requireNonNull(cancellation);
}
/** Registers work producing a deferred patch. */
public void onCancel(Runnable stopPatch) {
cancellation.onCancel(stopPatch);
}
/** Cancels every outstanding patch. */
public void cancel() {
cancellation.cancel();
}
/**
* Whether a further patch may still be produced.
*
* <p>Checked before each patch, so a disconnect stops the work at the next boundary rather than
* at the end.
*/
public boolean mayContinue() {
return !cancellation.cancelled();
}
}
@@ -1,35 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.incremental;
/**
* Refuses incremental delivery on a runtime that cannot serve it (Advanced plan Task 18).
*
* <p>Never falls back to a complete response. A silent fallback means the feature appears to work
* in every environment where it is not actually enabled, and fails only where someone relied on it.
*/
public final class GraphQlIncrementalCompatibilityGate {
/**
* Verifies the runtime can serve incremental delivery.
*
* @throws GraphQlIncrementalDeliveryRejectedException when either half is missing
*/
public void verify(GraphQlIncrementalDeliveryCapability capability) {
if (!capability.engineSupported() || !capability.transportSupported()) {
throw new GraphQlIncrementalDeliveryRejectedException(
"incremental delivery runtime unsupported");
}
}
/**
* Verifies the client negotiated incremental delivery.
*
* @param clientNegotiated whether the client asked for it
* @throws GraphQlIncrementalDeliveryRejectedException when it did not
*/
public void verifyClientNegotiation(boolean clientNegotiated) {
if (!clientNegotiated) {
throw new GraphQlIncrementalDeliveryRejectedException(
"incremental responses require explicit client capability negotiation");
}
}
}
@@ -1,19 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.incremental;
/**
* Whether the engine and the transport can both do incremental delivery.
*
* <p>Both are required and they move independently: an engine that supports {@code @defer} over a
* transport that cannot stream produces a response the client cannot consume.
*
* @param engineSupported whether the GraphQL engine supports it
* @param transportSupported whether the transport can stream the patches
*/
public record GraphQlIncrementalDeliveryCapability(
boolean engineSupported, boolean transportSupported) {
/** Whether both halves are present. */
public boolean available() {
return engineSupported && transportSupported;
}
}
@@ -1,32 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.incremental;
/**
* The version-gated incremental delivery profile.
*
* <p>Version-gated because {@code @defer} and {@code @stream} are not in the September 2025 Stable
* contract and their engine and transport support are still settling. Pinning the profile is what
* keeps a library upgrade from silently changing what clients receive.
*
* @param profileVersion the profile this deployment implements
* @param deferSupported whether {@code @defer} is served
* @param streamSupported whether {@code @stream} is served
*/
public record GraphQlIncrementalDeliveryProfile(
String profileVersion, boolean deferSupported, boolean streamSupported) {
public GraphQlIncrementalDeliveryProfile {
if (profileVersion == null || profileVersion.isBlank()) {
throw new IllegalArgumentException("incremental delivery profile version is required");
}
}
/** Disabled, which is the Stable position. */
public static GraphQlIncrementalDeliveryProfile disabled() {
return new GraphQlIncrementalDeliveryProfile("experimental-v0", false, false);
}
/** Whether anything incremental is served at all. */
public boolean enabled() {
return deferSupported || streamSupported;
}
}
@@ -1,22 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.incremental;
/**
* Raised when incremental delivery cannot be served.
*
* <p>A configuration error rather than a silent fallback: a client that asked for {@code @defer}
* and received a complete response has been served correctly by accident, and will not notice until
* the response it depends on being incremental is not.
*/
public class GraphQlIncrementalDeliveryRejectedException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates the failure.
*
* @param reason bounded description
*/
public GraphQlIncrementalDeliveryRejectedException(String reason) {
super(reason);
}
}
@@ -1,32 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.incremental;
import java.util.List;
import java.util.Map;
/**
* One patch following an initial incremental result.
*
* <p>Carries its own path and errors. A deferred fragment can fail on its own, and its error
* belongs to the patch's path — attributing it to the initial result would tell the client the
* wrong field failed.
*
* @param path where in the response this patch applies
* @param data the patch's data, possibly partial
* @param errors errors raised while producing it
* @param hasNext whether more patches follow
*/
public record GraphQlIncrementalPatch(
List<Object> path,
Map<String, Object> data,
List<Map<String, Object>> errors,
boolean hasNext) {
public GraphQlIncrementalPatch {
path = path == null ? List.of() : List.copyOf(path);
data =
data == null
? Map.of()
: java.util.Collections.unmodifiableMap(new java.util.LinkedHashMap<>(data));
errors = errors == null ? List.of() : List.copyOf(errors);
}
}
@@ -1,42 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.incremental;
import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlRuntimeBudgetTracker;
import java.util.Objects;
/**
* Keeps incremental responses inside the Stable budgets.
*
* <p>Patches are part of the same response, so they consume the same node and byte budget. Counting
* only the initial result would make a deferred fragment a way to send an unbounded response one
* patch at a time.
*/
public final class GraphQlIncrementalTransportPolicy {
private final GraphQlRuntimeBudgetTracker budgetTracker;
/**
* Creates the policy.
*
* @param budgetTracker the request's runtime budget
*/
public GraphQlIncrementalTransportPolicy(GraphQlRuntimeBudgetTracker budgetTracker) {
this.budgetTracker = Objects.requireNonNull(budgetTracker);
}
/**
* Records a patch against the request's budget.
*
* @throws dev.caskeleton.adapter.inbound.graphql.cost.GraphQlRuntimeBudgetExceededException when
* the response budget is exhausted
*/
public void recordPatch(GraphQlIncrementalPatch patch) {
budgetTracker.recordNode();
budgetTracker.recordBytes(
patch.data().toString().getBytes(java.nio.charset.StandardCharsets.UTF_8).length);
}
/** Marks the response committed; from here an overrun terminates the connection. */
public void markInitialResultSent() {
budgetTracker.markResponseCommitted();
}
}
@@ -1,100 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.persisted;
import java.util.Set;
/**
* One approved operation (design §19).
*
* <p>Carries the schema hash it was approved against, so an operation cannot survive a schema
* change that invalidated it, and its own complexity and variable limits, so an
* approved-but-expensive operation stays bounded even for a client whose general profile is
* generous.
*
* <p>Deliberately holds no variables: variables are per-request data, and the registry is
* long-lived storage.
*
* @param id operation identity
* @param operationName the operation's name, which the request must match
* @param documentHash SHA-256 of the canonical document
* @param canonicalDocument the approved document text
* @param schemaContractHash schema the operation was approved against
* @param allowedClientProfiles client profiles that may run it
* @param maximumComplexity complexity ceiling for this operation
* @param maximumVariablesBytes variable size ceiling for this operation
* @param status lifecycle state
*/
public record GraphQlPersistedOperation(
GraphQlPersistedOperationId id,
String operationName,
String documentHash,
String canonicalDocument,
String schemaContractHash,
Set<String> allowedClientProfiles,
long maximumComplexity,
int maximumVariablesBytes,
GraphQlPersistedOperationStatus status) {
public GraphQlPersistedOperation {
if (id == null || status == null) {
throw new IllegalArgumentException("persisted operation id and status are required");
}
if (operationName == null || operationName.isBlank()) {
throw new IllegalArgumentException("persisted operation name is required");
}
if (documentHash == null || documentHash.isBlank()) {
throw new IllegalArgumentException("persisted operation document hash is required");
}
if (canonicalDocument == null || canonicalDocument.isBlank()) {
throw new IllegalArgumentException("persisted operation document is required");
}
if (schemaContractHash == null || schemaContractHash.isBlank()) {
throw new IllegalArgumentException("persisted operation schema hash is required");
}
allowedClientProfiles = Set.copyOf(allowedClientProfiles);
if (allowedClientProfiles.isEmpty()) {
throw new IllegalArgumentException(
"a persisted operation must allow at least one client profile");
}
if (maximumComplexity < 1 || maximumVariablesBytes < 1) {
throw new IllegalArgumentException("persisted operation limits must be positive");
}
}
/** Registers an active operation with first-party defaults. */
public static GraphQlPersistedOperation active(
String id,
String operationName,
String documentHash,
String canonicalDocument,
String schemaHash) {
return new GraphQlPersistedOperation(
new GraphQlPersistedOperationId(id),
operationName,
documentHash,
canonicalDocument,
schemaHash,
Set.of("FIRST_PARTY"),
10_000,
65_536,
GraphQlPersistedOperationStatus.ACTIVE);
}
/** Returns a copy in a different lifecycle state. */
public GraphQlPersistedOperation withStatus(GraphQlPersistedOperationStatus newStatus) {
return new GraphQlPersistedOperation(
id,
operationName,
documentHash,
canonicalDocument,
schemaContractHash,
allowedClientProfiles,
maximumComplexity,
maximumVariablesBytes,
newStatus);
}
/** Whether a client profile may run this operation. */
public boolean allows(String clientProfileName) {
return allowedClientProfiles.contains(clientProfileName);
}
}
@@ -1,23 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.persisted;
/**
* Raised when one operation id is registered with a different document.
*
* <p>Rejected rather than overwritten: clients already deployed are sending that id expecting the
* document that was approved with it, and replacing it would change what their requests execute
* without any client changing.
*/
public class GraphQlPersistedOperationConflictException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates the failure.
*
* @param operationId the id that was registered twice
*/
public GraphQlPersistedOperationConflictException(String operationId) {
super(
"persisted operation " + operationId + " is already registered with a different document");
}
}
@@ -1,23 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.persisted;
import java.util.regex.Pattern;
/**
* The identity a client sends instead of a document.
*
* <p>Bounded, because it becomes a registry key and a metric label. Versioned by convention —
* {@code get-order-v2} rather than mutating {@code get-order} — so a client on the old build keeps
* running while a new one ships.
*
* @param value operation id matching {@code [a-z][a-z0-9.-]{2,127}}
*/
public record GraphQlPersistedOperationId(String value) {
private static final Pattern PATTERN = Pattern.compile("[a-z][a-z0-9.-]{2,127}");
public GraphQlPersistedOperationId {
if (value == null || !PATTERN.matcher(value).matches()) {
throw new IllegalArgumentException("invalid persisted operation id");
}
}
}
@@ -1,66 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.persisted;
import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability;
import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedModuleGuard;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
import java.util.Objects;
/**
* Runs the persisted-operation stage, before parsing (Advanced plan Task 3).
*
* <p>Before parsing because with an operation id the registry <em>is</em> the document source.
* Every check happens here in one place, and none of them is authorization: resolving an approved
* operation says the document is allowed to exist, not that this actor may run it.
*/
public final class GraphQlPersistedOperationInterceptor {
private final GraphQlAdvancedModuleGuard guard;
private final GraphQlPersistedOperationLookup lookup;
/**
* Creates the interceptor.
*
* @param guard the Advanced capability guard
* @param lookup the registry lookup
*/
public GraphQlPersistedOperationInterceptor(
GraphQlAdvancedModuleGuard guard, GraphQlPersistedOperationLookup lookup) {
this.guard = Objects.requireNonNull(guard);
this.lookup = Objects.requireNonNull(lookup);
}
/**
* Resolves and validates a persisted operation request.
*
* @param request what the client sent
* @param clientProfileName the caller's client profile
* @param deployedSchemaHash the deployed schema hash
* @param clientPolicy the caller's client policy
* @return the approved operation, ready to execute
* @throws GraphQlPersistedOperationRejectedException on any failed check
*/
public GraphQlPersistedOperation resolve(
GraphQlPersistedOperationRequest request,
String clientProfileName,
String deployedSchemaHash,
GraphQlClientPolicy clientPolicy) {
guard.requireEnabled(GraphQlAdvancedCapability.PERSISTED_OPERATION);
GraphQlPersistedOperation operation = lookup.require(request.operationId());
GraphQlPersistedOperationPolicy.requireActive(operation);
GraphQlPersistedOperationPolicy.requireClientAllowed(operation, clientProfileName);
GraphQlPersistedOperationPolicy.requireSchemaMatch(operation, deployedSchemaHash);
GraphQlPersistedOperationPolicy.requireDocumentMatch(operation, request.suppliedDocumentHash());
GraphQlPersistedOperationPolicy.requireVariablesWithinLimit(
operation, request, clientPolicy.maxVariablesBytes());
return operation;
}
/** The complexity ceiling for an operation: the stricter of its own and the client's. */
public long effectiveComplexityLimit(
GraphQlPersistedOperation operation, GraphQlClientPolicy clientPolicy) {
return GraphQlPersistedOperationPolicy.effectiveLimit(
operation.maximumComplexity(), clientPolicy.maxComplexity());
}
}
@@ -1,37 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.persisted;
import java.util.Objects;
/**
* Resolves an operation id to its approved document.
*
* <p>An unknown id is rejected with the same message as a blocked one, so the response does not
* tell a caller which ids exist.
*/
public final class GraphQlPersistedOperationLookup {
private final GraphQlPersistedOperationRegistry registry;
/**
* Creates the lookup.
*
* @param registry the approved operation store
*/
public GraphQlPersistedOperationLookup(GraphQlPersistedOperationRegistry registry) {
this.registry = Objects.requireNonNull(registry);
}
/**
* Resolves an operation.
*
* @throws GraphQlPersistedOperationRejectedException when it is unknown
*/
public GraphQlPersistedOperation require(GraphQlPersistedOperationId id) {
return registry
.find(id)
.orElseThrow(
() ->
new GraphQlPersistedOperationRejectedException(
"persisted operation is not available"));
}
}
@@ -1,25 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.persisted;
/**
* Raised when an admin command names an operation the registry does not hold.
*
* <p>A distinct failure from a conflict: "there is nothing here" and "you cannot do that from here"
* lead an operator to different next steps, and the admin plane used to report neither — an unknown
* id produced a successful-looking audit entry.
*/
public class GraphQlPersistedOperationNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
/** Stable error code. */
public static final String CODE = "GRAPHQL_PERSISTED_OPERATION_NOT_FOUND";
/**
* Creates the failure.
*
* @param operationId the operation that does not exist
*/
public GraphQlPersistedOperationNotFoundException(String operationId) {
super(CODE + ": " + operationId);
}
}
@@ -1,90 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.persisted;
/**
* The checks an approved operation must still pass at request time (Advanced plan Task 3).
*
* <p>Being in the registry is not permission to run. The operation must still be active, belong to
* this client, match the deployed schema, and stay inside the stricter of its own and the client's
* limits — and none of that is authorization, which happens afterwards against the actor.
*/
public final class GraphQlPersistedOperationPolicy {
private GraphQlPersistedOperationPolicy() {}
/**
* Requires the operation to be executable.
*
* @throws GraphQlPersistedOperationRejectedException when it is blocked
*/
public static GraphQlPersistedOperation requireActive(GraphQlPersistedOperation operation) {
if (operation.status() != GraphQlPersistedOperationStatus.ACTIVE) {
throw new GraphQlPersistedOperationRejectedException("persisted operation is not active");
}
return operation;
}
/**
* Requires the client profile to be allowlisted for this operation.
*
* @throws GraphQlPersistedOperationRejectedException when it is not
*/
public static void requireClientAllowed(
GraphQlPersistedOperation operation, String clientProfileName) {
if (!operation.allows(clientProfileName)) {
throw new GraphQlPersistedOperationRejectedException(
"persisted operation is not allowed for this client profile");
}
}
/**
* Requires the operation to match the deployed schema.
*
* @throws GraphQlPersistedOperationRejectedException when the schema has moved on
*/
public static void requireSchemaMatch(
GraphQlPersistedOperation operation, String deployedSchemaHash) {
if (!operation.schemaContractHash().equals(deployedSchemaHash)) {
throw new GraphQlPersistedOperationRejectedException(
"persisted operation was approved against a different schema");
}
}
/**
* Requires a supplied document to match the approved one.
*
* @throws GraphQlPersistedOperationRejectedException when the hashes differ
*/
public static void requireDocumentMatch(
GraphQlPersistedOperation operation, String suppliedDocumentHash) {
if (suppliedDocumentHash != null && !operation.documentHash().equals(suppliedDocumentHash)) {
throw new GraphQlPersistedOperationRejectedException(
"the supplied document does not match the persisted operation");
}
}
/**
* The effective limit: the stricter of the operation's and the client's.
*
* @param operationLimit the operation's own ceiling
* @param clientLimit the client policy's ceiling
*/
public static long effectiveLimit(long operationLimit, long clientLimit) {
return Math.min(operationLimit, clientLimit);
}
/**
* Requires the request's variables to fit inside the effective limit.
*
* @throws GraphQlPersistedOperationRejectedException when they do not
*/
public static void requireVariablesWithinLimit(
GraphQlPersistedOperation operation,
GraphQlPersistedOperationRequest request,
int clientMaximumVariablesBytes) {
long limit = effectiveLimit(operation.maximumVariablesBytes(), clientMaximumVariablesBytes);
if (request.variablesBytes() > limit) {
throw new GraphQlPersistedOperationRejectedException(
"persisted operation variables too large");
}
}
}
@@ -1,123 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.persisted;
import dev.caskeleton.shared.opstore.OperationalRecord;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/**
* Translates a persisted operation to and from a neutral operational record.
*
* <p>The whole point of the split. Durable storage for persisted operations has to live in
* infrastructure, and infrastructure must not implement a type that belongs to an inbound transport
* — a Postgres adapter implementing {@code GraphQlPersistedOperationRegistry} would point the
* dependency from the database back at the GraphQL boundary. So the store speaks {@link
* OperationalRecord} and knows nothing about GraphQL, and this class is the only place that knows
* both vocabularies.
*
* <p>The encoding is length-framed rather than delimited. A canonical document contains newlines,
* an operation name is client-influenced, and a client profile is a free-form string; any delimiter
* chosen from those alphabets is a delimiter a value can contain, and the field after it is then
* read as something else. Framing each field by its length removes the question.
*/
public final class GraphQlPersistedOperationRecordMapping {
/** The key space this capability owns in the operational store. */
public static final String NAMESPACE = "graphql.persisted-operation";
private static final int FIELDS = 9;
private GraphQlPersistedOperationRecordMapping() {}
/**
* The store key for an operation id.
*
* @param id the operation id
*/
public static String keyFor(GraphQlPersistedOperationId id) {
Objects.requireNonNull(id, "persisted operation id is required");
return id.value();
}
/**
* Encodes an operation as a neutral record.
*
* @param operation the operation to store
* @param version the version the caller read, for the store's compare-and-set
*/
public static OperationalRecord toRecord(GraphQlPersistedOperation operation, long version) {
Objects.requireNonNull(operation, "persisted operation is required");
StringBuilder encoded = new StringBuilder();
write(encoded, operation.id().value());
write(encoded, operation.operationName());
write(encoded, operation.documentHash());
write(encoded, operation.canonicalDocument());
write(encoded, operation.schemaContractHash());
write(encoded, String.join(",", operation.allowedClientProfiles()));
write(encoded, Long.toString(operation.maximumComplexity()));
write(encoded, Integer.toString(operation.maximumVariablesBytes()));
write(encoded, operation.status().name());
return new OperationalRecord(NAMESPACE, keyFor(operation.id()), encoded.toString(), version);
}
/**
* Decodes an operation from a neutral record.
*
* @param record the stored record
* @throws IllegalArgumentException when the record is not a persisted operation of this shape
*/
public static GraphQlPersistedOperation fromRecord(OperationalRecord record) {
Objects.requireNonNull(record, "operational record is required");
if (!NAMESPACE.equals(record.namespace())) {
throw new IllegalArgumentException("operational record belongs to another namespace");
}
List<String> fields = readAll(record.value());
if (fields.size() != FIELDS) {
throw new IllegalArgumentException("stored persisted operation has an unexpected shape");
}
Set<String> profiles = new LinkedHashSet<>();
if (!fields.get(5).isEmpty()) {
profiles.addAll(List.of(fields.get(5).split(",", -1)));
}
return new GraphQlPersistedOperation(
new GraphQlPersistedOperationId(fields.get(0)),
fields.get(1),
fields.get(2),
fields.get(3),
fields.get(4),
profiles,
Long.parseLong(fields.get(6)),
Integer.parseInt(fields.get(7)),
GraphQlPersistedOperationStatus.valueOf(fields.get(8)));
}
private static void write(StringBuilder out, String value) {
out.append(value.length()).append(':').append(value);
}
private static List<String> readAll(String encoded) {
List<String> fields = new java.util.ArrayList<>();
int cursor = 0;
while (cursor < encoded.length()) {
int separator = encoded.indexOf(':', cursor);
if (separator < 0) {
throw new IllegalArgumentException("stored persisted operation is not length-framed");
}
int length;
try {
length = Integer.parseInt(encoded.substring(cursor, separator));
} catch (NumberFormatException malformed) {
throw new IllegalArgumentException("stored persisted operation has an invalid frame");
}
int start = separator + 1;
int end = start + length;
if (length < 0 || end > encoded.length()) {
throw new IllegalArgumentException("stored persisted operation frame runs past its value");
}
fields.add(encoded.substring(start, end));
cursor = end;
}
return List.copyOf(fields);
}
}
@@ -1,39 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.persisted;
import java.util.Optional;
/**
* Storage for approved operations.
*
* <p>An SPI rather than a fixed implementation: a registry needs to survive restarts and stay
* consistent across instances, and which store provides that is a deployment decision the platform
* should not make.
*/
public interface GraphQlPersistedOperationRegistry {
/**
* Registers an operation.
*
* @throws GraphQlPersistedOperationConflictException when the id already holds a different
* document
*/
void register(GraphQlPersistedOperation operation);
/** Looks up an operation. */
Optional<GraphQlPersistedOperation> find(GraphQlPersistedOperationId id);
/**
* Applies a lifecycle transition and returns the operation as it now stands.
*
* <p>Returning the record, and failing when there is nothing to change, is what makes an audit
* entry trustworthy. The previous {@code updateStatus} was a no-op for an unknown id, so the
* admin plane recorded {@code ABSENT -> BLOCKED} as a successful incident response for an
* operation that had never existed — the one entry an operator would rely on afterwards.
*
* @throws GraphQlPersistedOperationNotFoundException when the operation does not exist
* @throws GraphQlPersistedOperationConflictException when the transition is not permitted from
* the operation's current state
*/
GraphQlPersistedOperation apply(
GraphQlPersistedOperationId id, GraphQlPersistedOperationTransition transition);
}
@@ -1,30 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.persisted;
/**
* Raised when a persisted operation may not execute.
*
* <p>One exception for every reason — blocked, unknown, wrong client, stale schema, oversized
* variables — with a bounded message, so a caller cannot use the rejection reason to probe the
* registry.
*/
public class GraphQlPersistedOperationRejectedException extends RuntimeException {
private static final long serialVersionUID = 1L;
/** Stable request-error code. */
public static final String CODE = "PERSISTED_OPERATION_REJECTED";
/**
* Creates the failure.
*
* @param reason bounded reason, never containing the document or variables
*/
public GraphQlPersistedOperationRejectedException(String reason) {
super(reason);
}
/** The stable request-error code. */
public String code() {
return CODE;
}
}
@@ -1,25 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.persisted;
/**
* What a client sent when invoking a persisted operation.
*
* <p>{@code suppliedDocumentHash} exists because some clients send the id <em>and</em> the
* document. When they do, the two must agree — otherwise a caller could quote an approved id while
* executing a document of their own.
*
* @param operationId the operation identity
* @param suppliedDocumentHash hash of the document the client also sent, or {@code null}
* @param variablesBytes serialized variables size
*/
public record GraphQlPersistedOperationRequest(
GraphQlPersistedOperationId operationId, String suppliedDocumentHash, int variablesBytes) {
public GraphQlPersistedOperationRequest {
if (operationId == null) {
throw new IllegalArgumentException("persisted operation id is required");
}
if (variablesBytes < 0) {
throw new IllegalArgumentException("variables size cannot be negative");
}
}
}
@@ -1,31 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.persisted;
/**
* An approved operation's lifecycle state.
*
* <p>{@link #BLOCKED} is the reason this is a state rather than a boolean: during an incident, one
* expensive operation has to be stoppable immediately, without a redeploy and without disabling the
* endpoint for everyone else.
*/
public enum GraphQlPersistedOperationStatus {
/** Executable. */
ACTIVE(true),
/** Still executable, but scheduled for removal. */
DEPRECATED(true),
/** Refused, effective immediately. */
BLOCKED(false);
private final boolean executable;
GraphQlPersistedOperationStatus(boolean executable) {
this.executable = executable;
}
/** Whether an operation in this state may run. */
public boolean executable() {
return executable;
}
}
@@ -1,80 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.persisted;
import java.util.Map;
import java.util.Set;
/**
* Which lifecycle changes the registry will accept.
*
* <p>Without a table, {@code updateStatus} accepted anything, and the sequence that mattered was
* {@code BLOCKED → DEPRECATED}: an operation stopped during an incident could be made executable
* again by a status change that read like a documentation update. Blocking is the emergency
* control, so leaving it is the transition that has to be deliberate.
*
* <p>{@code BLOCKED} is therefore terminal except through {@link #UNBLOCK}, which exists precisely
* so that reversing an incident block is its own audited command rather than a side effect of
* something else.
*/
public enum GraphQlPersistedOperationTransition {
/** First registration of an operation. */
REGISTER,
/** Marks an operation deprecated while clients migrate. It stays executable. */
DEPRECATE,
/** Stops an operation immediately. */
BLOCK,
/** Reverses a block, deliberately and with its own audit entry. */
UNBLOCK,
/** Retires an operation: it is blocked and no longer offered. */
RETIRE;
private static final Map<
GraphQlPersistedOperationTransition, Set<GraphQlPersistedOperationStatus>>
ALLOWED_FROM =
Map.of(
DEPRECATE,
Set.of(
GraphQlPersistedOperationStatus.ACTIVE,
GraphQlPersistedOperationStatus.DEPRECATED),
BLOCK,
Set.of(
GraphQlPersistedOperationStatus.ACTIVE,
GraphQlPersistedOperationStatus.DEPRECATED),
UNBLOCK,
Set.of(GraphQlPersistedOperationStatus.BLOCKED),
RETIRE,
Set.of(
GraphQlPersistedOperationStatus.ACTIVE,
GraphQlPersistedOperationStatus.DEPRECATED,
GraphQlPersistedOperationStatus.BLOCKED));
/** The state this transition leaves the operation in. */
public GraphQlPersistedOperationStatus target() {
return switch (this) {
case REGISTER, UNBLOCK -> GraphQlPersistedOperationStatus.ACTIVE;
case DEPRECATE -> GraphQlPersistedOperationStatus.DEPRECATED;
case BLOCK, RETIRE -> GraphQlPersistedOperationStatus.BLOCKED;
};
}
/** Whether this transition may be applied to an operation currently in the given state. */
public boolean allowedFrom(GraphQlPersistedOperationStatus current) {
return this != REGISTER && ALLOWED_FROM.getOrDefault(this, Set.of()).contains(current);
}
/**
* Verifies the transition.
*
* @throws GraphQlPersistedOperationConflictException when the change is not permitted from here
*/
public void verify(GraphQlPersistedOperationId id, GraphQlPersistedOperationStatus current) {
if (!allowedFrom(current)) {
throw new GraphQlPersistedOperationConflictException(
id.value() + " cannot go " + current + " -> " + name());
}
}
}
@@ -1,44 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.persisted;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCacheKey;
/**
* Bridges an approved operation onto the preparsed document cache.
*
* <p>The two are different things and must not be merged. The registry decides <em>whether</em> a
* document may run; the cache only avoids re-parsing one that already may. Blocking an operation
* therefore has to take effect immediately, even though its parsed form is still cached — which is
* why the block is checked on every request rather than at cache-fill time.
*/
public final class GraphQlPersistedPreparsedBridge {
private GraphQlPersistedPreparsedBridge() {}
/**
* The cache key for an approved operation.
*
* @param operation the approved operation
* @param validationPolicyVersion version of the validation rules in force
* @param clientSchemaProfile client profile whose schema view applies
*/
public static GraphQlPreparsedCacheKey cacheKey(
GraphQlPersistedOperation operation,
String validationPolicyVersion,
String clientSchemaProfile) {
return new GraphQlPreparsedCacheKey(
operation.documentHash(),
operation.schemaContractHash(),
validationPolicyVersion,
clientSchemaProfile);
}
/**
* Whether a cached parse may be reused for this operation.
*
* <p>A blocked operation may never run, even though its parsed document is still cached — the
* cache is a parsing optimisation, never an execution permission.
*/
public static boolean executable(GraphQlPersistedOperation operation) {
return operation.status().executable();
}
}
@@ -1,96 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.persisted;
import dev.caskeleton.shared.opstore.OperationalRecord;
import dev.caskeleton.shared.opstore.OperationalRecordConflictException;
import dev.caskeleton.shared.opstore.OperationalRecordStorePort;
import java.util.Objects;
import java.util.Optional;
/**
* The persisted-operation registry, backed by whatever durable store the deployment provides.
*
* <p>This is the registry an adopter runs. The dependency points from here to a neutral contract in
* {@code shared-contract}, and the durable implementation of that contract points at the same
* contract from the other side — so a Postgres or Redis adapter never names a GraphQL type, and
* this leaf never names a datastore. The composition root connects the two and owns no policy.
*
* <p>Registration and transitions are compare-and-set against the version this registry read. Two
* admin planes blocking and approving the same operation a second apart used to resolve by arrival
* order, and the loser left no trace; now the loser is told.
*/
public final class OperationalStoreGraphQlPersistedOperationRegistry
implements GraphQlPersistedOperationRegistry {
private final OperationalRecordStorePort store;
/**
* Creates the registry.
*
* @param store the deployment's durable operational store
*/
public OperationalStoreGraphQlPersistedOperationRegistry(OperationalRecordStorePort store) {
this.store = Objects.requireNonNull(store, "operational record store is required");
}
@Override
public void register(GraphQlPersistedOperation operation) {
Objects.requireNonNull(operation, "persisted operation is required");
String key = GraphQlPersistedOperationRecordMapping.keyFor(operation.id());
Optional<OperationalRecord> stored =
store.find(GraphQlPersistedOperationRecordMapping.NAMESPACE, key);
if (stored.isPresent()) {
GraphQlPersistedOperation existing =
GraphQlPersistedOperationRecordMapping.fromRecord(stored.get());
if (!existing.canonicalDocument().equals(operation.canonicalDocument())) {
throw new GraphQlPersistedOperationConflictException(operation.id().value());
}
return;
}
try {
store.compareAndSet(
GraphQlPersistedOperationRecordMapping.toRecord(
operation, OperationalRecord.ABSENT_VERSION),
OperationalRecord.ABSENT_VERSION);
} catch (OperationalRecordConflictException lost) {
// Another instance registered the same id between the read and the write. That is a conflict
// in exactly the sense this capability already has a name for.
throw new GraphQlPersistedOperationConflictException(operation.id().value());
}
}
@Override
public Optional<GraphQlPersistedOperation> find(GraphQlPersistedOperationId id) {
Objects.requireNonNull(id, "persisted operation id is required");
return store
.find(
GraphQlPersistedOperationRecordMapping.NAMESPACE,
GraphQlPersistedOperationRecordMapping.keyFor(id))
.map(GraphQlPersistedOperationRecordMapping::fromRecord);
}
@Override
public GraphQlPersistedOperation apply(
GraphQlPersistedOperationId id, GraphQlPersistedOperationTransition transition) {
Objects.requireNonNull(id, "persisted operation id is required");
Objects.requireNonNull(transition, "transition is required");
OperationalRecord stored =
store
.find(
GraphQlPersistedOperationRecordMapping.NAMESPACE,
GraphQlPersistedOperationRecordMapping.keyFor(id))
.orElseThrow(() -> new GraphQlPersistedOperationNotFoundException(id.value()));
GraphQlPersistedOperation current = GraphQlPersistedOperationRecordMapping.fromRecord(stored);
transition.verify(id, current.status());
GraphQlPersistedOperation next = current.withStatus(transition.target());
try {
store.compareAndSet(
GraphQlPersistedOperationRecordMapping.toRecord(next, stored.version() + 1),
stored.version());
} catch (OperationalRecordConflictException lost) {
throw new GraphQlPersistedOperationConflictException(id.value());
}
return next;
}
}
@@ -1,45 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.release;
import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability;
import dev.caskeleton.adapter.inbound.graphql.release.GraphQlCompatibilityMatrix;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* The protocol and library versions one Advanced capability was verified against.
*
* <p>Extends the Stable matrix rather than replacing it, and adds the protocol versions that only
* Advanced capabilities have: a WebSocket sub-protocol, a federation specification version, a
* codegen engine.
*
* @param capability the capability
* @param stableMatrix the Stable framework combination underneath it
* @param protocolVersions protocol versions verified, keyed by protocol name
*/
public record GraphQlAdvancedCompatibilityMatrix(
GraphQlAdvancedCapability capability,
GraphQlCompatibilityMatrix stableMatrix,
Map<String, String> protocolVersions) {
public GraphQlAdvancedCompatibilityMatrix {
if (capability == null || stableMatrix == null) {
throw new IllegalArgumentException("capability and stable matrix are required");
}
protocolVersions = Map.copyOf(protocolVersions);
}
/** Whether the whole combination is supported. */
public boolean supported() {
return problems().isEmpty();
}
/** Why the combination is unsupported, in a deterministic order. */
public List<String> problems() {
List<String> problems = new ArrayList<>(stableMatrix.problems());
if (protocolVersions.isEmpty()) {
problems.add(capability.name() + " declares no verified protocol version");
}
return List.copyOf(problems);
}
}
@@ -1,64 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.release;
import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability;
import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapabilityGrade;
import java.time.Instant;
import java.util.List;
/**
* A decision to promote, hold or withdraw one capability.
*
* <p>Promotion out of Experimental needs a recorded decision with an owner. Without one a
* capability drifts into production by habit — enabled in one environment, then another, until
* nobody remembers it was never approved.
*
* @param capability the capability decided on
* @param fromGrade its grade before
* @param toGrade its grade after
* @param decisionRecord reference to the ADR or decision log entry
* @param owner who owns the capability
* @param decidedAt when the decision was made
* @param missingEvidence evidence still outstanding, empty when promotion is clean
*/
public record GraphQlAdvancedPromotionDecision(
GraphQlAdvancedCapability capability,
GraphQlAdvancedCapabilityGrade fromGrade,
GraphQlAdvancedCapabilityGrade toGrade,
String decisionRecord,
String owner,
Instant decidedAt,
List<String> missingEvidence) {
public GraphQlAdvancedPromotionDecision {
if (capability == null || fromGrade == null || toGrade == null) {
throw new IllegalArgumentException("capability and both grades are required");
}
if (decisionRecord == null || decisionRecord.isBlank()) {
throw new IllegalArgumentException("a promotion requires a recorded decision reference");
}
if (owner == null || owner.isBlank()) {
throw new IllegalArgumentException("a promotion requires an owner");
}
if (decidedAt == null) {
throw new IllegalArgumentException("a promotion requires a decision instant");
}
missingEvidence = List.copyOf(missingEvidence);
}
/** Whether the decision actually promotes the capability. */
public boolean promotes() {
return toGrade != fromGrade && toGrade != GraphQlAdvancedCapabilityGrade.EXPERIMENTAL;
}
/**
* Verifies a promotion is supported by evidence.
*
* @throws GraphQlAdvancedReleaseException when evidence is still outstanding
*/
public void verify() {
if (promotes() && !missingEvidence.isEmpty()) {
throw new GraphQlAdvancedReleaseException(
capability.name() + " cannot be promoted with outstanding evidence: " + missingEvidence);
}
}
}
@@ -1,31 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.release;
/**
* The evidence an Advanced capability release requires (Advanced plan Task 19).
*
* <p>The Stable baseline comes first and is not negotiable: an Advanced capability sits on top of
* the Stable platform's transport, error, security and cost guarantees, so releasing one on an
* unproven base means its own evidence was gathered against something that might not hold.
*
* @param stableBaselinePassed the Stable release gate passed
* @param capabilityContractsPassed the capability's own contract suites passed
* @param securityPassed authentication, authorization and isolation evidence
* @param soakPassed long-running behaviour under sustained load
* @param compatibilityPassed framework and protocol compatibility
*/
public record GraphQlAdvancedReleaseEvidence(
boolean stableBaselinePassed,
boolean capabilityContractsPassed,
boolean securityPassed,
boolean soakPassed,
boolean compatibilityPassed) {
/** Whether every kind of evidence is present. */
public boolean complete() {
return stableBaselinePassed
&& capabilityContractsPassed
&& securityPassed
&& soakPassed
&& compatibilityPassed;
}
}
@@ -1,20 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.release;
/**
* Raised when an Advanced capability may not be released.
*
* <p>Names what is missing, so the gate is a checklist rather than a wall.
*/
public class GraphQlAdvancedReleaseException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates the failure.
*
* @param reason which evidence is missing
*/
public GraphQlAdvancedReleaseException(String reason) {
super(reason);
}
}
@@ -1,50 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.release;
import java.util.ArrayList;
import java.util.List;
/**
* Blocks an Advanced capability release without complete evidence.
*
* <p>The Stable baseline is checked first and reported on its own, because everything else is
* measured against it: if the Stable platform's guarantees have not been demonstrated, the
* capability's soak numbers describe a system nobody has verified.
*/
public final class GraphQlAdvancedReleaseGate {
/**
* Verifies an Advanced release.
*
* @throws GraphQlAdvancedReleaseException naming the missing evidence
*/
public void verify(GraphQlAdvancedReleaseEvidence evidence) {
if (!evidence.stableBaselinePassed()) {
throw new GraphQlAdvancedReleaseException("stable graphql baseline must pass first");
}
List<String> missing = missing(evidence);
if (!missing.isEmpty()) {
throw new GraphQlAdvancedReleaseException("advanced graphql evidence incomplete: " + missing);
}
}
/** Which evidence is missing, in a deterministic order. */
public List<String> missing(GraphQlAdvancedReleaseEvidence evidence) {
List<String> missing = new ArrayList<>();
if (!evidence.stableBaselinePassed()) {
missing.add("stableBaseline");
}
if (!evidence.capabilityContractsPassed()) {
missing.add("capabilityContracts");
}
if (!evidence.securityPassed()) {
missing.add("security");
}
if (!evidence.soakPassed()) {
missing.add("soak");
}
if (!evidence.compatibilityPassed()) {
missing.add("compatibility");
}
return List.copyOf(missing);
}
}
@@ -1,52 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.release;
import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability;
import java.util.EnumMap;
import java.util.Map;
/**
* The operational runbook each capability must have before release.
*
* <p>Every Advanced capability introduces a failure mode the Stable platform does not have — a
* connection storm, a blocked operation to reverse, a subgraph to roll back. Requiring the runbook
* up front is what stops that being written for the first time during the incident.
*/
public final class GraphQlAdvancedRunbookIndex {
private final Map<GraphQlAdvancedCapability, String> runbooks =
new EnumMap<>(GraphQlAdvancedCapability.class);
/**
* Registers a capability's runbook.
*
* @param capability the capability
* @param runbookReference where the runbook lives
*/
public GraphQlAdvancedRunbookIndex register(
GraphQlAdvancedCapability capability, String runbookReference) {
if (runbookReference == null || runbookReference.isBlank()) {
throw new IllegalArgumentException("a runbook reference is required");
}
runbooks.put(capability, runbookReference);
return this;
}
/**
* Requires a capability to have a runbook.
*
* @throws GraphQlAdvancedReleaseException when it does not
*/
public String require(GraphQlAdvancedCapability capability) {
String reference = runbooks.get(capability);
if (reference == null) {
throw new GraphQlAdvancedReleaseException(
capability.name() + " cannot be released without an operational runbook");
}
return reference;
}
/** Registered runbooks. */
public Map<GraphQlAdvancedCapability, String> runbooks() {
return Map.copyOf(runbooks);
}
}
@@ -1,51 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.release;
import java.util.List;
/**
* The soak scenarios a long-lived transport must survive (design §24.4).
*
* <p>All of these are duration problems, invisible to a short test. A buffer leak, a connection
* that never re-authenticates and a source that reconnects badly all look fine for the first
* minute.
*/
public enum GraphQlAdvancedSoakScenario {
/** A thousand persistent connections held open. */
BASELINE_1K_CONNECTIONS,
/** The deployment's target connection count. */
TARGET_CONNECTION_COUNT,
/** Several subscriptions multiplexed on one connection. */
MULTIPLE_SUBSCRIPTIONS_PER_CONNECTION,
/** A burst of events far above steady state. */
EVENT_BURST,
/** A client that reads more slowly than the source produces. */
SLOW_CONSUMER,
/** Many simultaneous cancellations. */
CANCEL_STORM,
/** Credentials expiring mid-stream. */
AUTH_EXPIRY,
/** The server restarting under load. */
SERVER_RESTART,
/** A rolling deployment across instances. */
ROLLING_DEPLOYMENT,
/** Graceful shutdown with subscriptions in flight. */
GRACEFUL_DRAIN,
/** The event source restarting underneath the subscriptions. */
SOURCE_RESTART;
/** Every scenario a realtime capability must pass before promotion. */
public static List<GraphQlAdvancedSoakScenario> requiredForRealtime() {
return List.of(values());
}
}
@@ -1,49 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.replay;
import dev.caskeleton.adapter.inbound.graphql.advanced.security.GraphQlWebSocketPrincipal;
/**
* Authorizes a replay before any history is delivered.
*
* <p>Replay reads the past, so the check is stricter than for a live subscription: the tenant and
* actor resuming must be the ones the cursor was issued to, and must still be authorized now —
* access granted when the events were produced may since have been withdrawn.
*
* <p>Tenant is checked alongside actor rather than assumed to follow from it. Checking only the
* actor is correct exactly while one actor identity never spans two tenants, and nothing here
* enforces that; when it stops holding, the replay succeeds and hands over history the caller was
* never entitled to.
*/
public final class GraphQlReplayAuthorization {
private GraphQlReplayAuthorization() {}
/**
* Verifies a replay request.
*
* @param cursorActorFingerprint the actor the cursor was issued to
* @param cursorTenantFingerprint the tenant the cursor was issued to
* @param principal the actor presenting it
* @param stillAuthorized whether the Application still authorizes this actor for the subscription
* @throws GraphQlReplayAuthorizationException when tenant or actor differs, or authorization has
* since been withdrawn
*/
public static void verify(
String cursorActorFingerprint,
String cursorTenantFingerprint,
GraphQlWebSocketPrincipal principal,
boolean stillAuthorized) {
if (cursorActorFingerprint == null
|| !cursorActorFingerprint.equals(principal.actorFingerprint())) {
throw new GraphQlReplayAuthorizationException();
}
if (cursorTenantFingerprint == null
|| !cursorTenantFingerprint.equals(principal.tenantFingerprint())) {
throw new GraphQlReplayAuthorizationException();
}
if (!stillAuthorized) {
throw new GraphQlReplayAuthorizationException();
}
}
}
@@ -1,17 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.replay;
/**
* Raised when a caller may not replay a subscription's history.
*
* <p>Carries no actor identity or position: a denial must not reveal whose cursor it was or how far
* it reached.
*/
public class GraphQlReplayAuthorizationException extends RuntimeException {
private static final long serialVersionUID = 1L;
/** Creates the failure. */
public GraphQlReplayAuthorizationException() {
super("subscription replay is not authorized");
}
}
@@ -1,22 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.replay;
/**
* Raised when a snapshot and the live stream do not join up.
*
* <p>A gap means events happened between the snapshot and the first live event, and the client will
* never see them. Failing loudly is the only honest option: silently continuing would present an
* incomplete stream as a complete one.
*/
public class GraphQlReplayGapException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates the failure.
*
* @param reason bounded description of the gap
*/
public GraphQlReplayGapException(String reason) {
super(reason);
}
}
@@ -1,25 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.replay;
/**
* Raised when a resume position has fallen outside the retention window.
*
* <p>A distinct outcome from a rejected cursor: the cursor is genuine, the history is simply gone,
* and the client's correct response is to re-read a snapshot rather than to re-authenticate.
*/
public class GraphQlReplayHistoryLostException extends RuntimeException {
private static final long serialVersionUID = 1L;
/** Stable error code. */
public static final String CODE = "SUBSCRIPTION_HISTORY_LOST";
/** Creates the failure. */
public GraphQlReplayHistoryLostException() {
super(CODE);
}
/** The stable error code. */
public String code() {
return CODE;
}
}
@@ -1,23 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.replay;
/**
* A position in the source event sequence.
*
* <p>The sequence is the messaging platform's, not GraphQL's: GraphQL has no resume token, and
* inventing one here would promise a durability guarantee the transport cannot keep.
*
* @param sequence monotonic source position
*/
public record GraphQlReplayPosition(long sequence) {
public GraphQlReplayPosition {
if (sequence < 0) {
throw new IllegalArgumentException("sequence cannot be negative");
}
}
/** The position immediately after this one. */
public GraphQlReplayPosition next() {
return new GraphQlReplayPosition(sequence + 1);
}
}
@@ -1,41 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.replay;
import dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionEvent;
import org.reactivestreams.Publisher;
/**
* A source that can replay from a position.
*
* <p>The durability is the messaging platform's, and so is the retention window. This interface
* only asks whether a position is still available — a cursor older than the window has to fail
* rather than silently resume from wherever history now begins.
*/
public interface GraphQlReplaySource {
/** The earliest position still retained. */
GraphQlReplayPosition earliestAvailable();
/** Whether a position can still be replayed. */
default boolean available(GraphQlReplayPosition position) {
return position.sequence() >= earliestAvailable().sequence();
}
/**
* Replays from a position.
*
* @throws GraphQlReplayHistoryLostException when the position has fallen outside the retention
* window
*/
Publisher<GraphQlSubscriptionEvent> replayFrom(GraphQlReplayPosition position);
/**
* Verifies a position is still replayable.
*
* @throws GraphQlReplayHistoryLostException when it is not
*/
default void requireAvailable(GraphQlReplayPosition position) {
if (!available(position)) {
throw new GraphQlReplayHistoryLostException();
}
}
}
@@ -1,38 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.replay;
/**
* The join between a snapshot and the live stream (Advanced plan Task 10).
*
* <p>Resuming means reading a snapshot and then continuing live, and the two have to meet exactly.
* A live stream starting later than the snapshot ends loses events; one starting earlier repeats
* them. Both are checked, because "roughly continuous" is not something a client can compensate
* for.
*
* @param snapshotPosition last position included in the snapshot
* @param liveStartPosition first position the live stream will deliver
*/
public record GraphQlSnapshotLiveHandoff(
GraphQlReplayPosition snapshotPosition, GraphQlReplayPosition liveStartPosition) {
public GraphQlSnapshotLiveHandoff {
if (snapshotPosition == null || liveStartPosition == null) {
throw new IllegalArgumentException("both handoff positions are required");
}
}
/**
* Verifies the two streams join without a gap.
*
* @throws GraphQlReplayGapException when events would be missed
*/
public void verifyContiguous() {
if (liveStartPosition.sequence() > snapshotPosition.sequence() + 1) {
throw new GraphQlReplayGapException("snapshot and live stream contain a gap");
}
}
/** Whether the join would repeat events the snapshot already contained. */
public boolean duplicates() {
return liveStartPosition.sequence() <= snapshotPosition.sequence();
}
}
@@ -1,95 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.replay;
import dev.caskeleton.adapter.inbound.graphql.advanced.security.GraphQlWebSocketPrincipal;
import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorCodec;
import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorFraming;
import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorPayload;
import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorScope;
import java.util.Map;
import java.util.Objects;
/**
* A signed resume position for a subscription.
*
* <p>Signed and bound to the tenant, the actor and the subscription profile for the same reason
* connection cursors are: an unsigned resume token is a "start reading from here" parameter, and
* replay reads history.
*
* <p>The tenant is part of the binding, not left to the actor fingerprint to imply. An actor
* identifier that happens to be unique per tenant today stops being a tenant check the moment one
* identity can act in two tenants, and the failure is silent — the cursor verifies, the actor
* matches, and the replay delivers another tenant's history. Taking the principal rather than a
* bare fingerprint makes issuing a cursor without a tenant impossible to express.
*
* <p>GraphQL itself defines no resume mechanism — this is an extension, and the durability behind
* it belongs to the messaging platform.
*/
public final class GraphQlSubscriptionCursor {
/** Query profile cursors of this kind are bound to. */
public static final String QUERY_PROFILE = "subscription-replay";
private GraphQlSubscriptionCursor() {}
/**
* Issues a resume cursor.
*
* @param codec the signing codec
* @param subscriptionProfile the subscription this cursor belongs to
* @param principal the tenant and actor it was issued to
* @param position the resume position
*/
public static String issue(
GraphQlCursorCodec codec,
String subscriptionProfile,
GraphQlWebSocketPrincipal principal,
GraphQlReplayPosition position) {
return codec.encode(
GraphQlCursorPayload.issue(
QUERY_PROFILE,
GraphQlCursorPayload.FORWARD,
Map.of("id", subscriptionProfile, "sequence", Long.toString(position.sequence())),
subscriptionProfile,
scopeOf(principal)));
}
/**
* Verifies and decodes a resume cursor.
*
* @param codec the signing codec
* @param cursor the cursor the client presented
* @param subscriptionProfile the subscription being resumed
* @param principal the tenant and actor presenting it
* @throws dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorException when the
* cursor was issued for another tenant, actor or subscription
*/
public static GraphQlReplayPosition resume(
GraphQlCursorCodec codec,
String cursor,
String subscriptionProfile,
GraphQlWebSocketPrincipal principal) {
GraphQlCursorPayload payload =
codec.decode(
cursor,
new GraphQlCursorScope(
QUERY_PROFILE,
subscriptionProfile,
GraphQlCursorPayload.FORWARD,
scopeOf(principal)));
return new GraphQlReplayPosition(Long.parseLong(payload.keyset().get("sequence")));
}
/**
* The scope fingerprint a cursor is bound to.
*
* <p>Length-framed rather than concatenated, so a tenant ending in the prefix of an actor cannot
* produce the same scope string as a different pair.
*/
private static String scopeOf(GraphQlWebSocketPrincipal principal) {
Objects.requireNonNull(principal, "principal is required");
StringBuilder scope = new StringBuilder();
GraphQlCursorFraming.write(scope, principal.tenantFingerprint());
GraphQlCursorFraming.write(scope, principal.actorFingerprint());
return scope.toString();
}
}
@@ -1,55 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.rsocket;
import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability;
import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedModuleGuard;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationType;
import java.util.Objects;
/**
* Decides whether an RSocket route may be served, and which interaction model it gets.
*
* <p>Admission, not a handler and not a registration: nothing here touches an {@code RSocket}
* acceptor. It answers "is this route allowed, and is this request/stream or request/response",
* which is what the runtime needs before it binds anything.
*
* <p>Experimental, so in production the guard additionally requires an approval profile. The
* interaction model comes from the operation type rather than the caller's request.
*/
public final class GraphQlRSocketAdmission {
private final GraphQlAdvancedModuleGuard guard;
private final GraphQlRSocketProperties properties;
private final GraphQlRSocketRoutePolicy routePolicy;
/**
* Creates the factory.
*
* @param guard the Advanced capability guard
* @param properties transport configuration
*/
public GraphQlRSocketAdmission(
GraphQlAdvancedModuleGuard guard, GraphQlRSocketProperties properties) {
this.guard = Objects.requireNonNull(guard);
this.properties = Objects.requireNonNull(properties);
this.routePolicy = new GraphQlRSocketRoutePolicy(properties.allowedRoutes());
}
/**
* Accepts a request on a route.
*
* @param route the requested route
* @param operationType the operation type
* @return the interaction model to use
* @throws GraphQlRSocketRouteRejectedException when the route is not allowlisted
*/
public GraphQlRSocketCapability accept(String route, GraphQlOperationType operationType) {
guard.requireEnabled(GraphQlAdvancedCapability.RSOCKET);
routePolicy.requireAllowed(route);
return GraphQlRSocketCapability.forOperation(operationType);
}
/** Whether the transport is registered at all. */
public boolean enabled() {
return properties.enabled() && guard.enabled(GraphQlAdvancedCapability.RSOCKET);
}
}
@@ -1,49 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.rsocket;
import java.util.Objects;
import java.util.Set;
/**
* Authentication metadata accepted on an RSocket connection.
*
* <p>MIME types are allowlisted for the same reason routes are: metadata drives how a credential is
* parsed, and an unexpected encoding is an unexpected parser.
*/
public final class GraphQlRSocketAuthentication {
private final Set<String> allowedMetadataMimeTypes;
/**
* Creates the authentication policy.
*
* @param allowedMetadataMimeTypes metadata MIME types accepted
*/
public GraphQlRSocketAuthentication(Set<String> allowedMetadataMimeTypes) {
this.allowedMetadataMimeTypes = Set.copyOf(Objects.requireNonNull(allowedMetadataMimeTypes));
}
/**
* Requires a metadata MIME type to be allowlisted.
*
* @throws GraphQlRSocketRouteRejectedException when it is not
*/
public void requireAllowedMetadata(String mimeType) {
if (mimeType == null || !allowedMetadataMimeTypes.contains(mimeType)) {
throw new GraphQlRSocketRouteRejectedException("metadata MIME type " + mimeType);
}
}
/**
* Requires an authenticated actor.
*
* <p>The same actor and tenant rules as HTTP: a different transport does not mean different
* security.
*
* @throws GraphQlRSocketRouteRejectedException when the connection is unauthenticated
*/
public void requireAuthenticated(boolean authenticated) {
if (!authenticated) {
throw new GraphQlRSocketRouteRejectedException("unauthenticated RSocket connection");
}
}
}
@@ -1,28 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.advanced.rsocket;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationType;
/**
* How GraphQL operations map onto RSocket interaction models.
*
* <p>A fixed mapping, not a choice: a query as request-stream would leave the client waiting for a
* stream that emits once and never completes in the way it expects.
*/
public enum GraphQlRSocketCapability {
/** Query and mutation: one request, one response. */
REQUEST_RESPONSE,
/** Subscription: one request, a stream of responses. */
REQUEST_STREAM;
/** The interaction model for an operation type. */
public static GraphQlRSocketCapability forOperation(GraphQlOperationType operationType) {
return operationType == GraphQlOperationType.SUBSCRIPTION ? REQUEST_STREAM : REQUEST_RESPONSE;
}
/** Whether RSocket is a public-facing transport. It is not. */
public static boolean publicTransport() {
return false;
}
}

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