# 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](README.md) 가 모아둔다 (이 문서는 모듈 규칙 SSOT). ## Responsibility - Use case inbound ports (`CommandUseCase`, `QueryUseCase`) and their command / query contracts. - Outbound ports (`*Port` interfaces) the use cases depend on. - Application exceptions and policy types. - Coordinate domain models through ports. - Own application transaction boundaries through the `TransactionPort` abstraction. - 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` (use `TransactionPort` instead — 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#getBeansOfType` remain ArchUnit's static-analysis blind spot per D12 — guard via code review checklist. - Lombok (`lombok..`) — also forbidden in `domain-core`. Within `application-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` | Base type for inbound ports. Concrete inbound ports MUST extend `CommandUseCase` or `QueryUseCase`. | | `usecase.CommandUseCase` | Inbound port for write use cases. Implementations MUST be annotated `@UseCaseCapability`. | | `usecase.QueryUseCase` | 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

` | Closed exact-record payload type, canonical component order, local schema identity/hash and provider-neutral descriptor contribution. | | `messaging.event.IntegrationEventDraft

` | 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 - Inbound port implementations end with `UseCase` (e.g. `RegisterUserUseCase`). Enforced by ArchUnit. - Outbound port interfaces end with `Port` (e.g. `NotificationPort`). - Command records end with `Command`; query records end with `Query`. ## Canonical use case shape ```java @UseCaseCapability( transactionMode = TransactionMode.WRITE, idempotency = Idempotency.KEYED, repositoryAccess = RepositoryAccess.WRITE_REPOSITORY) public final class RegisterUserUseCase implements CommandUseCase { 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. ## 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` / `Runnable` and cannot throw checked exceptions. This matches Spring's `TransactionCallback` 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 raw `Idempotency-Key` never reaches this layer or the store. - **Store**: `IdempotencyStorePort`, contributed by exactly one provider selected with `app.capabilities.idempotency.provider` (`redis` → `cache-redis`, `postgresql` → `persistence-jpa`; default `disabled`). In-memory prod storage is forbidden. - **Executor**: built once by `composition:idempotency` `IdempotencyAutoConfiguration` from `IdempotencySettings` (processing lease 30s, replay TTL `APP_IDEMPOTENCY_TTL` 24h ≤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 → 409 `IDEMPOTENT_IN_FLIGHT`, fingerprint mismatch (SHA-256) → 422 `IDEMPOTENT_REQUEST_MISMATCH`; `IdempotencyUnavailableException` and `IdempotencyRecoveryRequiredException` mean 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 `QueryPort` MUST return application-layer projection DTOs only — never a domain aggregate, JPA entity, or web type, **including through generic type arguments** (`List`). Enforced by ArchUnit `query_ports_do_not_leak_domain_jpa_or_web_types`. Projection usage itself is **opt-in**, not a forced default; the demo lives in `sample-portfolio` (`WorkLogSummaryQueryPort` / `WorkLogSummary`). - **D3 — Strict ceremony:** every read goes through a `QueryUseCase` bean. There is no thin web→read-port path — that would bypass the mandatory `@UseCaseCapability` fitness function. - **D4 — transaction:** reads default to `TransactionPort.inRead`. A no-tx (autocommit) read is an opt-in only when `spring.jpa.open-in-view=false` is confirmed **and** the read is projection-only (no lazy access) **and** a single statement; otherwise keep `inRead`. - **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) stay `RepositoryAccess.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_transport` - `application_does_not_use_spring_transactional_annotation` - `application_does_not_depend_on_application_context` (D11) - `APPLICATION_HAS_NO_DIAGNOSTIC_FRAMEWORK` - `inbound_port_implementations_end_with_use_case` - `inbound_port_implementations_declare_capability` - `query_ports_do_not_leak_domain_jpa_or_web_types` (query-bypass D1 — `*QueryPort` return purity) ## Test ```bash 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.