문제: High·P1을 고친 뒤에도 P2·P3 약 90건이 남았다. 연결·구독·메시지 크기 상한이 없는 전송(WebSocket·gRPC·GraphQL deadline), 낙관적 충돌의 500, upsert 경쟁, Mongo 무제한 timeout, 샘플 목록 N+1, 갈라진 복사본 (TenantId 3벌, 이벤트 ID 문법 5곳, SQLState 표 2벌), 문서를 읽는 PR 테스트와 캐시를 막는 lane 설정 등이다. 새 기능을 어디에 어떤 순서로 만드는지 알려 주는 문서와 도구가 없었다. MinIO 공식 이미지가 사라져 객체 저장소 lane이 돌지 않았다. 방법: 영역별 묶음으로 실패 테스트를 먼저 쓰고 고쳤다. 고치는 중에 찾은 결함도 함께 고쳤다(durable operation id가 UUIDv4라 이벤트가 전부 DEAD, S3 어댑터 생성·작은 chunk 읽기 실패, Redis 조건부 기록의 EVALSHA 권한). MinIO는 pgsty/minio를 digest로 고정했다(Chainguard는 태그·실행 사용자· mc 이미지 문제로 버림). docs/manual/에 작업 순서와 판단 지점을 쓰고, scripts/new-feature.sh가 5개 leaf에 뼈대를 만든다. 생성→빌드→통과 왕복을 verifyFeatureScaffold가 mainCheck에서 본다. 묶음별 결과와 결정은 리뷰 README 14절에 있다. 위험·한계: 파생 서비스 동작이 바뀐다. JDBC batch 50 기본, 운영 jar에서 H2 제거, 트랜잭션 30초 제한, 격리 수준을 Hikari에서 고정, gRPC· WebSocket·GraphQL 새 한도, correlation ID 규칙 밖이면 서버가 교체, 샘플 키 오류 코드 IDEMPOTENCY_KEY_INVALID. 새 leaf 두 개 (composition:durable-operation, adapter:inbound:messaging)와 새 마이그레이션(postgresql V20·V21, notification V11·V12, sample V8_1, grpc-ledger V002)이 생긴다. V21 유일 인덱스는 기존 중복이 있으면 실패한다(runbook에 확인 쿼리). 검증: ci, mainCheck(생성 명령 왕복 포함), integrationCheck(MinIO 포함 전 컨테이너 lane), -p optional-platforms ci integrationCheck 통과. Refs: docs/reviews/2026-11-01-maturity-review/README.md 14절 BREAKING CHANGE: JDBC batch 기본 켜짐, H2 운영 의존 제거, 트랜잭션 기본 제한 30초, gRPC·WebSocket·GraphQL 서버 한도 기본값 추가, 샘플 Idempotency-Key 오류 코드 변경.
16 KiB
application-core — application use cases
Registered identity
- Module ID:
application-core - Gradle path:
:application-core - Focused test (derived from Gradle path):
./gradlew :application-core:test --console=plain - Runtime baseline: Java 21; repository framework baseline: the Spring Boot 4.x version pinned by the shared version catalog.
- Registry SSOT:
src/config/architecture/modules.json.
Package root: dev.caskeleton.application.
코드 주석에서 덜어낸 설계 결정의 근거는 README.md 가 모아둔다 (이 문서는 모듈 규칙 SSOT).
Responsibility
- Use case inbound ports (
CommandUseCase,QueryUseCase) and their command / query contracts. - Outbound ports (
*Portinterfaces) the use cases depend on. - Application exceptions and policy types.
- Coordinate domain models through ports.
- Own application transaction boundaries through the
TransactionPortabstraction. - Expose framework-free invocation context through ports such as
CorrelationIdPort; adapters own MDC or other concrete storage. - Own the framework-free semantic integration-event draft, validated-event value contract and exact typed payload contribution SPI. This is the messaging semantic contract R1 boundary only.
Allowed
:domain-core:shared-contract- Java standard library types.
Forbidden
adapter-*implementation classes.app-bootstrap.- Controller request/response DTOs.
- JPA entities and Spring Data repositories.
- HTTP status, transport types (
org.springframework.web..). org.springframework.transaction.annotation.Transactional(useTransactionPortinstead — D3).org.springframework.context.ApplicationContext— direct dependency forbidden (getBean(Class)reflection-style bypass blocked by ArchUnit D11). String-key bean lookup /Class.forName(String)/BeanFactory#getBeansOfTyperemain ArchUnit's static-analysis blind spot per D12 — guard via code review checklist.- Lombok (
lombok..) — also forbidden indomain-core. Withinapplication-core, Lombok is currently not in scope for the contract; if you intend to use it, weigh the bytecode opacity cost first. - Persistence-layer transaction annotations of any kind inside this module.
- Diagnostic frameworks (
org.slf4j,java.util.logging, Logback, Log4j, Micrometer). Express diagnostic intent through a specific outbound*Port; adapters own rendering. - Messaging provider/runtime types: physical topic, Kafka record or metadata, JSON tree/raw JSON payload, serializer/schema-validator implementation, security topology and publication epoch.
Contract types
| Type | Purpose |
|---|---|
usecase.UseCase<I, O> |
Base type for inbound ports. Concrete inbound ports MUST extend CommandUseCase or QueryUseCase. |
usecase.CommandUseCase<C extends Command, R> |
Inbound port for write use cases. Implementations MUST be annotated @UseCaseCapability. |
usecase.QueryUseCase<Q extends Query, R> |
Inbound port for read-only use cases. Implementations MUST declare transactionMode = READ_ONLY and repositoryAccess = READ_REPOSITORY. |
command.Command |
Marker for write intents. Plain immutable types built from domain values. |
query.Query |
Marker for read intents. Plain immutable types built from domain values. |
transaction.TransactionPort |
Outbound port for join-capable write/read, physical root-only write, and independent write boundaries. Implemented by adapter-persistence. |
outbound.SecretSourcePort |
Framework-free outbound secret-resolution seam. Deployment selects a backend in app-bootstrap; concrete environment/cloud/vault readers belong to outbound adapter leaves. |
transaction.NestedRootTransactionRejectedException |
Fail-fast signal raised before action/provider side effects when inRootWrite detects an actual ambient transaction. |
transaction.TransactionMode |
WRITE / READ_ONLY / REQUIRES_NEW. NESTED and NEVER are intentionally absent. |
transaction.Isolation |
READ_COMMITTED (pinned default) / REPEATABLE_READ / SERIALIZABLE. READ_UNCOMMITTED is forbidden (not declared); the vendor default is never used (engine defaults differ — PostgreSQL READ COMMITTED vs MySQL InnoDB REPEATABLE READ). Routing the stricter levels through TransactionPort is a planned joint change with feature-application-port-usecase-contract; the shipped call path pins READ_COMMITTED. |
capability.UseCaseCapability |
Mandatory annotation on every concrete use case: declares transactionMode, idempotency, repositoryAccess, externalOutboundAllowed. |
capability.Idempotency |
IDEMPOTENT / KEYED / NOT_IDEMPOTENT. |
capability.RepositoryAccess |
NONE / READ_REPOSITORY / WRITE_REPOSITORY. |
messaging.contract.IntegrationEventContractContribution<P> |
Closed exact-record payload type, canonical component order, local schema identity/hash and provider-neutral descriptor contribution. |
messaging.event.IntegrationEventDraft<P> |
Typed semantic event before local encoding; never JSON, Kafka or persistence state. |
messaging.event.ValidatedIntegrationEvent |
Stable semantic identities plus immutable exact encoded bytes and hashes, ready for a later durable append boundary. |
messaging.event.IntegrationEventEncoderPort |
Framework-free local draft-to-validated-event boundary implemented by an outbound adapter (the template's: adapter:outbound:support JsonIntegrationEventEncoder). |
outbox.OutboxAppendPort |
The one outbox append: a ValidatedIntegrationEvent, in the caller's write transaction. |
tenant.TenantId |
The tenant identifier and its one grammar ([A-Za-z0-9][A-Za-z0-9_.-]{0,63}); the web and GraphQL transport contexts both carry it. Built by a transport from verified authentication data only. |
Notification (NOTIF-ADR-005)
..notification.platform.. (leaf application-notification) is canonical. The R1 types directly
under dev.caskeleton.application.notification were removed on 2026-09-25; only the simple
NotificationPort, Notification and NotificationChannel remain there.
Naming convention
This section is the repository's naming rule book. NamingConventionTest (app-bootstrap
architectureTest) enforces the machine-checkable rows; the rest are review rules, and a review checks
them against this table. A new feature follows the "new code" column; the "existing exceptions" are
named so nobody copies them by accident.
| Role | Name | Where | Existing exceptions (do not copy) |
|---|---|---|---|
| Use case (inbound port implementation) | <Verb><Noun>UseCase, enforced by ArchUnit |
application package of the feature |
*ApplicationUseCase (application-fileserver, application-notification), *Service (notification, fileserver) |
| Command / query record | *Command / *Query |
next to its use case | — |
| Aggregate persistence (stores and returns whole aggregates) | <Aggregate>Repository |
domain package of the aggregate, owned by the domain | — |
| Technical store the application owns (outbox, idempotency, operation rows) | <Thing>StorePort |
application package | *WritePort (old onboarding fixture, removed) |
| Read model that returns projections, not aggregates | <Thing>QueryPort |
application package; returns projections only (ArchUnit) | — |
| Any other outbound port | <Capability>Port |
application package | — |
| Server-assigned id generation | <Aggregate>IdFactory extends IdFactory<<Aggregate>Id> |
domain package; the id record implements ResourceId<Self> |
OutboxEventIdFactory (sample; event ids are not resource ids) |
| Configuration binding | *Settings (operational) or *Policy (authorization / domain policy), enforced by ArchUnit |
the leaf that binds it | — |
| Throwable | *Exception, enforced by ArchUnit |
— | — |
| Contract test kit for a port | abstract <Port>Contract in the port owner's testFixtures; the fake's and each adapter's test extend it |
testFixtures | value-type tests were once named *ContractTest; they are *ValueTypesTest now |
The one-line rule for stores: if the domain would recognise the thing it stores, it is a
Repository in the domain; if it is plumbing the application needs, it is a StorePort in the
application.
Canonical use case shape
@RequiresPermission("user:register")
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
idempotency = Idempotency.KEYED,
repositoryAccess = RepositoryAccess.WRITE_REPOSITORY)
public class RegisterUserUseCase implements CommandUseCase<RegisterUserCommand, User> {
private final UserRepository users;
private final TransactionPort tx;
public RegisterUserUseCase(UserRepository users, TransactionPort tx) {
this.users = users;
this.tx = tx;
}
@Override
public User handle(RegisterUserCommand cmd) {
return tx.inWrite(() -> {
// ... domain coordination
});
}
}
The class is plain Java. A composition root constructs it with its ports and configuration values;
application-core never self-registers with a DI framework. It is not final: a mutating use case
declares @RequiresPermission, the web adapter enforces it through a CGLIB proxy, and CGLIB cannot
subclass a final class (RequiresPermissionProxyabilityTest). It is registered as a bean for the
same reason — a use case built with new is never checked. A use case only the system calls (a
scheduler, a relay) carries @SystemInvoked(reason = ...) instead of a permission and is not a bean.
A composition with @RequiresPermission beans but no enforcing advisor fails startup
(composition:service-runtime PermissionEnforcementGuard).
Allowed transactional shapes
| Use case shape | transactionMode |
TransactionPort call | When |
|---|---|---|---|
| Write command | WRITE |
tx.inWrite(...) |
Default for CommandUseCase. |
| Physical-root write command | WRITE |
tx.inRootWrite(...) |
Only when orchestration must prove there is no ambient transaction and expose a result after commit. |
| Read-only query | READ_ONLY |
tx.inRead(...) |
Default for QueryUseCase. |
| Outbox / audit / compensation | REQUIRES_NEW |
tx.inNew(...) |
Only when the use case MUST commit independently of the caller. |
NESTED and NEVER propagation are forbidden.
inRootWrite MUST reject an actual ambient transaction before invoking its action or
PlatformTransactionManager; it MUST NOT emulate root-only behavior with REQUIRES_NEW.
Both inWrite and inRootWrite satisfy the direct boundary fitness rule for a
WRITE_REPOSITORY + WRITE use case. READ and REQUIRES_NEW mappings remain exclusive.
Callback signature contract (D11)
TransactionPort callbacks are Supplier<T> / Runnable and cannot throw checked
exceptions. This matches Spring's TransactionCallback<T> constraint. Wrap domain
checked exceptions into RuntimeException subclasses
(DomainException extends RuntimeException); IOException → UncheckedIOException;
SQLException is auto-translated by Spring's DataAccessException hierarchy.
inNew pool-sizing constraint (D12)
inNew acquires a new physical JDBC connection. Pool size MUST satisfy:
hikari.maximumPoolSize >= (concurrent_threads × (1 + max_inNew_depth)) + 1
Forbidden: calling tx.inNew(...) inside a loop over many records — pool
exhaustion + deadlock risk. Batch records inside ONE inNew call, or move the
loop outside the transaction boundary.
Idempotency (KEYED) — feature-rate-limit-idempotency-contract
@UseCaseCapability(idempotency = Idempotency.KEYED) is supported. A KEYED use case wraps
its work with dev.caskeleton.application.idempotency.IdempotencyExecutor — the one owner-safe
generation; the V1 IdempotencyScope/tryBegin API is gone.
- Scope: the caller passes an
IdempotencyScopeDigest— a versioned HMAC of principal + client key + operation code, computed before the executor sees it. The rawIdempotency-Keynever reaches this layer or the store. - Store:
IdempotencyStorePort, contributed by exactly one provider selected withapp.capabilities.idempotency.provider(redis→cache-redis,postgresql→persistence-jpa; defaultdisabled). In-memory prod storage is forbidden. - Executor: built once by
composition:idempotencyIdempotencyAutoConfigurationfromIdempotencySettings(processing lease 30s, replay TTLAPP_IDEMPOTENCY_TTL24h ≤72h, failure retention 24h). Do not construct it in a use case or a sample config. - The action returns
IdempotentAction.Outcome(Success/RetryableNoEffect/EffectUnknown); a thrown exception counts as effect-unknown. In progress → 409IDEMPOTENT_IN_FLIGHT, fingerprint mismatch (SHA-256) → 422IDEMPOTENT_REQUEST_MISMATCH;IdempotencyUnavailableExceptionandIdempotencyRecoveryRequiredExceptionmean the store could not prove the outcome, so do not blindly retry.
The former ArchUnit freeze rule inbound_port_implementations_do_not_declare_keyed_idempotency
and its fixture were removed when this branch merged.
Read / query path (feature-application-query-bypass-contract)
The read side has two equally-valid shapes; pick per read, do not force one:
| Shape | Returns | When | How |
|---|---|---|---|
| Through-aggregate (default for simple reads) | domain aggregate via a *Repository port |
read shape == write aggregate and the aggregate is the minimal invariant boundary (no lazy collections needed) | QueryUseCase → repository port → WorkLog |
| Projection (CQRS-lite) | application-layer projection DTO via a *QueryPort |
read shape ≠ write, or to skip aggregate hydration / lazy-collection joins | QueryUseCase → *QueryPort → WorkLogSummary (record); query via JPQL SELECT new / JdbcTemplate |
- D1 — purity guardrail (core, machine-enforced): a read port whose simple name ends
with
QueryPortMUST return application-layer projection DTOs only — never a domain aggregate, JPA entity, or web type, including through generic type arguments (List<DomainType>). Enforced by ArchUnitquery_ports_do_not_leak_domain_jpa_or_web_types. Projection usage itself is opt-in, not a forced default; the demo lives insample-portfolio(WorkLogSummaryQueryPort/WorkLogSummary). - D3 — Strict ceremony: every read goes through a
QueryUseCasebean. There is no thin web→read-port path — that would bypass the mandatory@UseCaseCapabilityfitness function. - D4 — transaction: reads default to
TransactionPort.inRead. A no-tx (autocommit) read is an opt-in only whenspring.jpa.open-in-view=falseis confirmed and the read is projection-only (no lazy access) and a single statement; otherwise keepinRead. - D5 — capability: a repository-backed projection read is still
repositoryAccess = READ_REPOSITORY. "Projection vs aggregate" is the return shape axis, orthogonal to the repository-access level axis — no new enum. Outbound-HTTP reads (no repository) stayRepositoryAccess.NONE. - Full CQRS with a separate physical read store (D2) is out of scope — escalation only.
ArchUnit guardrails (enforced)
application_does_not_depend_on_adapters_or_transportapplication_does_not_use_spring_transactional_annotationapplication_does_not_depend_on_application_context(D11)APPLICATION_HAS_NO_DIAGNOSTIC_FRAMEWORKinbound_port_implementations_end_with_use_caseinbound_port_implementations_declare_capabilityquery_ports_do_not_leak_domain_jpa_or_web_types(query-bypass D1 —*QueryPortreturn purity)
Test
cd src
./gradlew :application-core:test
./gradlew :app-bootstrap:architectureTest
The messaging types above establish semantic contract R1 only. They do not claim JSON Schema qualification, Kafka publication, durable outbox persistence or any messaging R2 capability.