review-followup Wave 3 라운드 1(P16): 빌드 게이트 정리 — JPA evidence manifest 폐기, build-tools 제거, API surface를 leaf check로

- 결정 4: JPA evidence·qualification manifest 폐기 → persistence-jpa 테스트, build-tools included build 비움(verifyEnvKeys는
  app-bootstrap 태스크, 구현은 build-logic `ca.config-contract`), gRPC release gate 삭제
- 결정 20: API surface 검사를 leaf `check`로, JPA adopter 검사를 `ca.api-surface`로 합침(구현 하나)
- 레인 단계 정리(문서 대조 레인은 `mainStage()`), integrationCheck가 입력 없는 레인을 이름과 함께 제외 → 로컬 통과(NEW-16)
- release workflow 통합, releaseCheck는 tag 전용, build-logic 비핵심 플러그인 정리, sample을 ArchUnit 대상에
- 보류 4행(B3 변경 모듈만 실행, C 이미지 서명, messaging 카드 검증 이동 2행 — 결정 필요), 남음 2행(O3-5 나머지)
- 통합: P17이 옮긴 gRPC release gate 사본 삭제, `grpc-proto-buf`를 release-gate needs에(P17-new-3)

검증: ./gradlew ci verifyDependencyLocks --warning-mode=fail 통과(685 task), mainCheck 통과(268 task),
-p optional-platforms ci 통과, -p build-logic test 78건 통과(손상된 TestKit 캐시 삭제 후)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
donghyeon-ka
2026-09-28 16:44:17 +09:00
co-authored by Claude Opus 5.5
parent 4fb7943b85
commit 0ed7bc8df7
166 changed files with 1666 additions and 6571 deletions
-1
View File
@@ -51,7 +51,6 @@ COPY --parents settings.gradle build.gradle **/build.gradle **/gradle.lockfile .
# so settings.gradle's `includeBuild('build-logic')` resolved against a build that declared no
# plugins and every leaf failed on an unknown plugin id, in the dependency-resolution stage below.
COPY build-logic/ ./build-logic/
COPY build-tools/ ./build-tools/
# Resolve every module configuration in STRICT mode (no --write-locks in a release build). This
# custom task fails on drift; Gradle's diagnostic `dependencies` report can print FAILED entries
+18 -15
View File
@@ -26,10 +26,10 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇
| `qualityCheck` | 모든 leaf의 SpotBugs + FindSecBugs를 실행 |
| `configContractCheck` | `:app-bootstrap:verifyEnvKeys`로 환경 설정 계약을 검사 |
| `qualificationCheck` | 전체 기동(system) 레인과 보조 source set Checkstyle을 실행 |
| `integrationCheck` | 명시적으로 선언된 strict integration lane을 실행. 일부 lane은 container runtime이 필요 |
| `ci` | PR 게이트: 모든 leaf `check` + `architectureCheck` + `qualityCheck` |
| `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + sample web 계약 + `verifyPublicPathSnapshot` + API surface + 전송·메시징 qualification 레인 + JPA readiness registry |
| `releaseCheck` | `ci`에 release provenance/archive 관련 검증을 추가 |
| `integrationCheck` | 선언된 strict integration lane(sample 포함)을 실행. 대부분 container runtime이 필요. 입력이 필요한 lane(Redis topology: `-Predis.topology.mode`, AWS: 보호 자격 증명 env)은 입력이 없으면 빠지고 집계가 그 이유를 출력 |
| `ci` | PR 게이트: 모든 leaf `check`(API surface 검사 포함, 소유자 결정 20) + `architectureCheck` + `qualityCheck` |
| `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + sample web 계약 + `verifyPublicPathSnapshot` + 전송·메시징 qualification 레인 + 각 leaf의 `mainCheck`(문서 대조 레인 `*DocumentContractTest`, objectstorage MinIO 레인) |
| `releaseCheck` | tag 전용 검사: `verifyReleaseProvenance` + `verifyPublicPathSnapshot`(`ci`를 다시 돌리지 않음) |
따라서 로컬에서 한 모듈만 수정했다면 `./gradlew :domain-core:check`처럼 focused task를
먼저 사용합니다. 전체 기동 qualification은 일반 leaf `check`나 `:app-bootstrap:build`에
@@ -44,8 +44,9 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇
### Local bootstrap
`./gradlew bootstrap`은 `bootstrapCompile` → `bootstrapDependencies` →
`bootstrapMigrateAndStart` → `bootstrapSmoke`를 순서대로 실행합니다.
`scripts/bootstrap-local.sh [profile]`(저장소 루트)은 compile → Docker 확인 → DB 기동 대기 →
app 기동(Flyway 포함) → health smoke를 순서대로 실행합니다(예전 `./gradlew bootstrap`, 리뷰
BUILD-O3-5로 build-logic 플러그인에서 스크립트로 옮김).
DB와 app lifecycle은 저장소 루트의 base/local Compose 조합이 소유하며, app startup Flyway가
끝나 public health endpoint가 준비되어야 다음 단계로 넘어갑니다. `src/.env.example`은 커밋된
env 계약이고 `src/.env`는 로컬 실행 입력입니다. `verifyEnvKeys`는 example/registry/shipped YAML을
@@ -53,13 +54,14 @@ env 계약이고 `src/.env`는 로컬 실행 입력입니다. `verifyEnvKeys`는
### Traceable version + dependency locking
- 추적 가능한 checkout에서는 project version이 `<MAJOR>.<MINOR>.<PATCH>+<12자리 git sha>`가 됩니다.
base version은 `-PreleaseVersion`/`RELEASE_VERSION`, revision은 `-PgitRevision`/`GIT_SHA`/
`GITHUB_SHA` 순으로 주입하고, 로컬에서는 현재 Git commit을 읽습니다.
- Git metadata와 revision property가 모두 없는 일반 source archive build는 configuration 단계에서
실패하지 않고 `<MAJOR>.<MINOR>.<PATCH>-SNAPSHOT`으로 동작합니다. 다만 `releaseCheck`가 실행하는
`verifyReleaseProvenance`는 source revision이 없으면 실패하므로 추적 불가능한 산출물을 release로
취급할 수 없습니다.
- leaf version은 release version뿐입니다(`-PreleaseVersion`/`RELEASE_VERSION`, 기본 `0.0.1`).
revision(`-PgitRevision`/`GIT_SHA`/`GITHUB_SHA`)을 모르면 `-SNAPSHOT`이 붙습니다. revision은 jar
이름에 넣지 않고 각 jar manifest의 `Build-Revision`과 app-bootstrap의
`META-INF/build-info.properties`(`build.revision`)에 남깁니다. 예전에는 version이
`<MAJOR>.<MINOR>.<PATCH>+<sha>`라 커밋마다 새 jar 이름이 생겼고 그 잔여물을 `ca.archive-hygiene`이
치웠는데, 둘 다 없앴습니다(리뷰 BUILD-O3-5).
- `releaseCheck`가 실행하는 `verifyReleaseProvenance`는 source revision이 없으면 실패하므로 추적
불가능한 산출물을 release로 취급할 수 없습니다.
- 모든 subproject가 `lockAllConfigurations()` + `LockMode.STRICT`를 사용하고, lock state는 Gradle
기본 `<module>/gradle.lockfile`에 둡니다. 이 경로는 Renovate Gradle manager 기본 인식 경로와
같습니다.
@@ -121,7 +123,8 @@ Checkstyle은 파싱된 파일에 같은 질문을 하고, leaf 단위로 돕니
- **소유.** app-bootstrap. 이 질문("이 애플리케이션의 배포에 무엇을 줘야 하는가")은 composition
root의 것이고, `./gradlew :domain-core:check`가 알아야 할 사항이 아닙니다. 루트 집계 이름은
`configContractCheck`이고 구현은 `build-tools`의 `ca.config-contract` plugin입니다.
`configContractCheck`이고 구현은 `build-logic`의 `ca.config-contract` plugin입니다(소유자 결정 4:
태스크는 app-bootstrap에 유지, `build-tools` included build는 비워서 삭제).
- **하는 일.** `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 가 생기면 빌드를
@@ -532,7 +535,7 @@ migration/vendor 계약의 증거로 사용하지 않습니다. 멱등성 provid
docker compose -f docker-compose.yml -f docker-compose.local.yml up -d --wait db
```
컨테이너로 띄우는 `./gradlew bootstrap` 경로는 이 호스트 포트를 쓰지 않습니다. compose 가 app
컨테이너로 띄우는 `scripts/bootstrap-local.sh` 경로는 이 호스트 포트를 쓰지 않습니다. compose 가 app
컨테이너의 `APP_DATASOURCE_URL` 을 내부 네트워크 주소 `jdbc:postgresql://db:5432/...` 로 덮어씁니다.
`ca-skeleton.persistence.vendor`(`postgresql` | `h2`)가 어느 vendor 구성을 조립할지 고르는 단일
@@ -11,8 +11,11 @@ import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles;
import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways;
import dev.caskeleton.adapter.outbound.httpclient.testkit.ToxiproxyFixture;
import eu.rekawek.toxiproxy.Proxy;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.URI;
import java.util.Map;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
@@ -37,27 +40,32 @@ class FailureInjectionContractTest {
System.getProperty("httpclient.fault.httpbin.image", "kennethreitz/httpbin:latest"))
.asCompatibleSubstituteFor("kennethreitz/httpbin");
/**
* A refused connect is the one fault that must be classified before anything is written.
*
* <p>This used to disable a Toxiproxy listener and call its published port. With Docker's
* userland proxy ({@code docker-proxy}, the default) the host port stays open and accepts the
* connect before closing it, so the client really did write the request and the evidence was
* {@code SENT_NO_RESPONSE}: the test measured the Docker network mode, not the adapter (review
* P11-new-3, NEW-16). A loopback port nobody listens on refuses the connect on every Docker
* configuration and without Docker at all.
*/
@Test
@SuppressWarnings("resource")
void disabledProxyFailsBeforeARequestCanBeSent() throws Exception {
ToxiproxyFixture.requireAvailable();
try (Network network = Network.newNetwork();
GenericContainer<?> upstream =
new GenericContainer<>(UPSTREAM_IMAGE)
.withNetwork(network)
.withNetworkAliases("upstream")
.withExposedPorts(80)) {
upstream.start();
try (ToxiproxyFixture toxiproxy = ToxiproxyFixture.start(network)) {
Proxy proxy = toxiproxy.proxyTo("connect-refused", "upstream", 80);
proxy.disable();
HttpClientException failure = callThrough(toxiproxy, "/get", ResponseType.of(byte[].class));
assertThat(failure.metadata().evidence()).isEqualTo(ExecutionEvidence.NOT_SENT);
assertThat(failure.getMessage()).doesNotContain("http://");
}
@DisplayName("연결이 거부되면 요청을 쓰기 전에 NOT_SENT 증거로 실패한다")
void refusedConnectionFailsBeforeARequestCanBeSent() throws Exception {
// given
int closedPort;
try (ServerSocket reserved = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
closedPort = reserved.getLocalPort();
}
URI refusing = URI.create("http://127.0.0.1:" + closedPort + "/");
// when
HttpClientException failure = call(refusing, "/get", ResponseType.of(byte[].class));
// then
assertThat(failure.metadata().evidence()).isEqualTo(ExecutionEvidence.NOT_SENT);
assertThat(failure.getMessage()).doesNotContain("http://");
}
@Test
@@ -87,8 +95,14 @@ class FailureInjectionContractTest {
private static <T> HttpClientException callThrough(
ToxiproxyFixture toxiproxy, String path, ResponseType<T> responseType) throws Exception {
URI baseUrl =
URI.create("http://" + toxiproxy.proxiedHost() + ":" + toxiproxy.proxiedPort() + "/");
return call(
URI.create("http://" + toxiproxy.proxiedHost() + ":" + toxiproxy.proxiedPort() + "/"),
path,
responseType);
}
private static <T> HttpClientException call(
URI baseUrl, String path, ResponseType<T> responseType) throws Exception {
try (TestGateways.Harness harness =
TestGateways.forProfile(ClientProfiles.builder("faulty").baseUrl(baseUrl).build())) {
return org.assertj.core.api.Assertions.catchThrowableOfType(
+12 -15
View File
@@ -75,19 +75,16 @@ apiSurface {
]
}
// NotificationEvidenceVerifierTest holds docs/notification/evidence-manifest.json, the support
// matrix it grades and the evidence files it names to each other. Those files are inputs of `test`,
// or Gradle would call it up to date after an edit to any of them.
def repositoryRoot = rootProject.projectDir.parentFile
tasks.named('test') {
inputs.files(
new File(repositoryRoot, 'docs/notification/evidence-manifest.json'),
new File(repositoryRoot, 'docs/notification/support-matrix.md'),
rootProject.file('adapter/outbound/persistence-jpa/build.gradle'))
.withPathSensitivity(PathSensitivity.RELATIVE)
inputs.files(fileTree(rootProject.projectDir) {
include 'adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/**'
include 'adapter/outbound/notification/src/test/java/**'
include 'application-notification/src/test/java/**'
}).withPathSensitivity(PathSensitivity.RELATIVE)
// NotificationEvidenceVerifierTest's repository case holds docs/notification/evidence-manifest.json,
// the support matrix it grades and the evidence files it names to each other. A comparison with
// repository documents, so it runs in this leaf's `mainCheck`, not in the pull-request `test`
// (review 2026-09-24 BUILD-계획-B4-27). The verifier's fixture cases stay in `test`. A lane never
// reports up to date, so it needs no inputs declared for the files it reads.
strictTestLanes {
lane('notificationDocumentContractTest') {
tag = 'document-contract'
description = 'Holds the notification support matrix to the evidence manifest and the evidence it names.'
rejectSkipped = true
mainStage()
}
}
@@ -8,12 +8,16 @@ import dev.caskeleton.adapter.outbound.notification.evidence.NotificationEvidenc
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class NotificationEvidenceVerifierTest {
// The repository's own documents, not a fixture: a main-stage lane
// (notificationDocumentContractTest).
@Test
@Tag("document-contract")
void repositorySupportMatrixClaimsNoMoreThanTheManifestProves() throws Exception {
// given
File repository = new File("../../../..").getCanonicalFile();
@@ -89,9 +89,18 @@ strictTestLanes {
requires 'dev.caskeleton.adapter.outbound.objectstorage.qualification.AwsS3QualificationPreconditionsTest'
rejectSkipped = true
jvmArgs '-Duser.timezone=UTC'
// The protected environment of object-storage-qualification.yml is the only caller that has
// the authority. Without it the lane can only fail, so integrationCheck leaves it out and
// says so (review NEW-16); naming the task still runs it and still fails closed.
if (providers.environmentVariable('OBJECT_STORAGE_AWS_QUALIFICATION_ENABLED').getOrElse('') != 'true') {
explicitOnly 'it needs OBJECT_STORAGE_AWS_QUALIFICATION_ENABLED=true and the protected AWS sandbox inputs'
}
}
}
tasks.named('check') {
// The MinIO lanes start a container, so they are the main-branch stage of this leaf, not its
// pull-request `check` (review BUILD-계획-B3); object-storage-qualification.yml runs them on pull
// requests that touch object storage, and integrationCheck runs them with every integration lane.
tasks.named('mainCheck') {
dependsOn 'objectStorageMinioContractTest', 'objectStorageMinioFaultTest'
}
+16 -45
View File
@@ -383,57 +383,28 @@ base task 외에 다음 candidate task가 Docker 부재 시 skip이 아니라
postgresqlIdempotencyIntegrationTest
```
### evidence manifest와 R2 gate
### readiness card 검사 (evidence manifest 폐기)
`readiness-cards.yaml`의 `evidence.scenarios`와 `evidence.task-claims`가 required evidence를 실제
JUnit selector/Gradle task에 연결한다. `verifyJpaReadinessRegistryContract`는 unknown claim,
duplicate selector와 다른 card task 차용을 mutation test로 거절한다.
테스트와 task에 연결한다. build-tools의 JPA evidence manifest(`ca.jpa-evidence`,
`ca.jpa-qualification`, `verifyJpaCandidateEvidence`, `verifyJpaPrimaryFoundationEvidence`,
`jpa-r2-evidence.yml`)는 소유자 결정 4(2026-09-25)로 폐기했다. 그 manifest가 증명하던 사실은
이제 두 곳에서 확인한다.
- `JpaReadinessRegistryTest`(이 leaf의 `test`): 카드 상태·선행 관계(순환 없음), 구현된 카드가
가리키는 이 leaf의 task가 `build.gradle`에 선언된 lane인지, 인용한 scenario 메서드가
`src/postgresqlIntegrationTest`에 있는지, required evidence가 모두 덮이는지, 소유 schema
stream의 location·history table이 고유하고 존재하는지.
- readiness lane 자체: 카드가 인용한 scenario마다 lane의 required test가 되고(`requires`),
lane은 skip을 거절한다(`rejectSkipped`). 실제 PostgreSQL이 없으면 skip이 아니라 실패한다.
```bash
./gradlew :adapter:outbound:persistence-jpa:verifyJpaCandidateEvidence --console=plain
./gradlew :adapter:outbound:persistence-jpa:test --tests '*JpaReadinessRegistryTest' --console=plain
./gradlew :adapter:outbound:persistence-jpa:integrationTestLaneCheck --console=plain # 모든 readiness·platform lane
```
위 task는 active card의 producer를 실행하고 JUnit XML에서 exact selector와
executed/skipped/failure/error 수를 읽는다. 각 manifest는 source revision/dirty digest,
prerequisite manifest ID, PostgreSQL image digest, pgjdbc/Hibernate/Flyway version, topology와
migration/dispatch metadata를 담고 다음 위치에 canonical JSON SHA-256 이름으로 생성된다.
```text
build/jpa-evidence/manifests/<card-id>/<sha256>.json
```
후보 검증은 zero-skip, schema, content hash와 prerequisite link가 맞으면 성공하지만
`attainedReadiness=R1`을 유지한다. 로컬 후보 lane은 다음 E2/E3 동작을 실제 PostgreSQL에서
검증한다.
- bounded pool saturation과 shutdown 뒤 connection 거부
- runtime/migration role 분리, trusted namespace, TLS `verify-full`의 정상·hostname mismatch·
untrusted CA·expired certificate 경로
- persistence failure의 HTTP/log/span redaction
- fresh/legacy adoption, interrupted migration forward recovery, N/N-1 additive rolling shape
- deadlock, action 실패 rollback, `inNew` 독립 commit, commit transport 단절(재시도 없음)
- idempotency 등 독립 stream의 disabled/first-enable/disable/re-enable/interrupted
lifecycle
각 manifest는 그래도 candidate profile, dirty source와 아직 R2가 아닌 prerequisite를
`readinessBlockers`에 보존하므로 후보 통과를 R2로 오인할 수 없다.
실제 aggregation gate는 별도 명령이다.
```bash
./gradlew \
:adapter:outbound:persistence-jpa:verifyJpaPrimaryFoundationEvidence \
-PjpaEvidenceProfile=r2 \
--console=plain
```
이 task는 clean revision, `JPA_EVIDENCE_CI_JOB`,
`JPA_EVIDENCE_ARTIFACT_LOCATION`, immutable PostgreSQL image digest, 모든 required evidence와
R2 prerequisite DAG가 있어야만 성공한다. `.github/workflows/ci-quality-gates.yml`의 candidate
job은 PR에서 zero-skip manifest를 보존하고, `.github/workflows/jpa-r2-evidence.yml`은 명시적으로
실행하는 production-profile lane이다. 로컬 dirty worktree 또는 unpublished 실행은
`worktree-is-dirty`/CI provenance blocker를 보고 실패하는 것이 정식 동작이다. R2 승격은 clean
revision에서 workflow를 실행하고 보존된 manifest artifact를 검토한 뒤에만 가능하다.
R2(운영 evidence) 승격은 더 이상 build가 판정하지 않는다. clean revision에서 위 lane을 돌린
CI 결과(`jpa-release` job의 JUnit XML artifact)를 검토해 결정한다.
stream migration이 중단되면 history/registry/object 상태를 먼저 확인하고 기존 migration을
임의 수정하거나 history를 바로 `repair`하지 않는다. 장애를 수정한 forward migration으로
@@ -2,7 +2,6 @@ plugins {
id 'ca.spring-library'
id 'ca.spring-config'
id 'java-test-fixtures'
id 'ca.jpa-evidence'
id 'ca.auxiliary-source-set'
id 'ca.api-surface'
}
@@ -140,7 +139,7 @@ dependencies {
// Real-PostgreSQL lanes. A readiness lane runs one named class (the security lane also names the
// runtime-role namespace-denial method), a platform lane selects a tag, and the pool lane has a
// source set of its own. jpa-release.yml and config/jpa/*.{json,yaml} name these tasks.
// source set of its own. release.yml (jpa-release-gate) and config/jpa/*.{json,yaml} name these tasks.
def jpaEvidenceImage = providers.gradleProperty('jpaPostgreSqlEvidenceImage').orElse('postgres:16-alpine').get()
def jpaMatrixVersions = providers.gradleProperty('jpa.matrix.versions').orElse('16').get()
def readinessLanes = [
@@ -169,6 +168,15 @@ def platformLanes = [
jpaPlatformQueryPlanTest: ['jpa-queryplan', 'Asserts query plan structure and planner estimate error (design §33).'],
jpaPlatformSecurityTest : ['jpa-security', 'Verifies runtime role privileges and search_path safety (design §36).'],
]
// Every scenario a readiness card cites (config/jpa/readiness-cards.yaml `evidence.scenarios`) is a
// required test of the lane that runs its class, and a readiness lane rejects skips. That is what the
// deleted JPA evidence manifest used to establish from JUnit XML after the fact; JpaReadinessRegistryTest
// checks the cards themselves.
def readinessScenarios = new groovy.json.JsonSlurper()
.parse(rootProject.file('config/jpa/readiness-cards.yaml'))
.cards.values()
.findAll { it.state != 'not-implemented' }
.collectMany { card -> (card.evidence?.scenarios ?: []).collect { it.selector } }
strictTestLanes {
readinessLanes.each { taskName, selection ->
String testClass = 'dev.caskeleton.adapter.outbound.persistence.readiness.' + selection[0]
@@ -178,6 +186,13 @@ strictTestLanes {
description = 'Runs the no-skip real PostgreSQL readiness scenario ' + testClass + '.'
requires testClass
selection.drop(1).each { method -> requires testClass + '.' + method }
readinessScenarios.findAll { it.startsWith(testClass + '#') }.each { selector ->
String method = testClass + '.' + selector.substring(selector.indexOf('#') + 1)
if (!selection.drop(1).contains(selector.substring(selector.indexOf('#') + 1))) {
requires method
}
}
rejectSkipped = true
jvmArgs '-Duser.timezone=UTC', '-Djpa.evidence.postgresql.image=' + jpaEvidenceImage
}
}
@@ -205,7 +220,7 @@ tasks.named('postgresqlSecurityBaselineIntegrationTest') {
dependsOn ':adapter:inbound:web:jpaPersistenceRedactionContractTest'
}
// Which JPA lanes block a release is declared by .github/workflows/jpa-release.yml.
// Which JPA lanes block a release is declared by config/jpa/release-registry.json (jpaReleaseQualification below).
// This leaf declares the lanes and how each runs; it does not own release orchestration.
// The unit lane reads three files that are not Java sources: the release registry and its two
@@ -217,6 +232,9 @@ tasks.named('postgresqlSecurityBaselineIntegrationTest') {
// exactly those edits never run on them.
tasks.named('test') {
inputs.file(rootProject.file('config/jpa/release-registry.json'))
// JpaReadinessRegistryTest: the readiness cards, the lanes they name and the scenarios they cite.
inputs.file(rootProject.file('config/jpa/readiness-cards.yaml'))
inputs.dir(file('src/postgresqlIntegrationTest/java')).withPropertyName('readinessScenarioSources')
inputs.file(new File(rootProject.projectDir.parentFile, 'docs/jpa/support-matrix.md'))
inputs.file(new File(rootProject.projectDir.parentFile, 'docs/jpa/repository-adaptation.md'))
// The whole directory, not the two named workflows: the Experimental-major check asks whether
@@ -225,12 +243,6 @@ tasks.named('test') {
inputs.dir(new File(rootProject.projectDir.parentFile, '.github/workflows'))
inputs.file(file('build.gradle'))
inputs.dir(file('src/jpaPlatformPerformanceTest/java'))
// JpaAdopterApiSurfaceTest: every other leaf's production sources and the adopter baseline.
inputs.file(new File(rootProject.projectDir.parentFile, 'docs/architecture/jpa-adopter-api-surface.txt'))
inputs.files(fileTree(rootProject.projectDir) {
include '**/src/main/java/**/*.java'
exclude '**/build/**', 'adapter/outbound/persistence-jpa/**', 'adapter/outbound/persistence-fileserver/**'
}).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('adopterSources')
}
// verifyJpaApiSurface — every public type this leaf exposes is a committed decision.
@@ -255,13 +267,28 @@ apiSurface {
'surface; the rest is implementation that has not been moved under an internal',
'root yet.',
]
// The reviewed subset other leaves' production code may import. The two leaves that implement
// JPA persistence (this one and persistence-fileserver) are the implementation, not adopters.
// This used to be JpaAdopterApiSurfaceTest, a regular-expression import scan beside the
// convention (review 2026-09-24 BUILD-중복-3); the convention parses imports with javac now.
adopterBaseline = rootProject.file('../docs/architecture/jpa-adopter-api-surface.txt')
adopterSources = fileTree(rootProject.projectDir) {
include '*/**/src/main/java/**/*.java'
exclude '**/build/**', 'adapter/outbound/persistence-jpa/**', 'adapter/outbound/persistence-fileserver/**',
'build-logic/**', 'optional-platforms/**'
}
}
// The JPA readiness registry describes this platform's lanes and resolves their task paths. It runs
// in the main-branch stage (`mainCheck`), not in `check`. The task itself is registered by the
// ca.jpa-qualification plugin from build-tools, which the root applies.
tasks.named('mainCheck') {
dependsOn rootProject.tasks.named('verifyJpaReadinessRegistry')
// The release registry (config/jpa/release-registry.json) names the blocking release gates; this
// aggregate runs exactly those. It replaced the build-tools `ca.jpa-qualification` plugin (review
// 2026-09-24 BUILD-O3-2): a gate that names a task that does not exist fails when the task graph is
// built, which is the whole of what `verifyJpaReleaseGateTasks` used to check.
tasks.register('jpaReleaseQualification') {
group = 'verification'
description = 'Runs exactly the blocking JPA release gates declared by config/jpa/release-registry.json.'
dependsOn(new groovy.json.JsonSlurper()
.parse(rootProject.file('config/jpa/release-registry.json'))
.gates.findAll { it.blocking }.collect { it.task })
}
@@ -1,92 +0,0 @@
package dev.caskeleton.adapter.outbound.persistence;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
/**
* Production code outside this leaf imports only the persistence types the adopter baseline lists.
*
* <p>A language-level public type is not a compatibility promise; the baseline is. The leaves that
* own JPA persistence implementations (this one and persistence-fileserver) are the implementation
* rather than adopters of it. The build declares every production source and the baseline as inputs
* of {@code test}.
*/
class JpaAdopterApiSurfaceTest {
private static final Path SOURCE_ROOT = Path.of("../../..").toAbsolutePath().normalize();
private static final Path BASELINE =
SOURCE_ROOT.resolve("../docs/architecture/jpa-adopter-api-surface.txt");
private static final Pattern IMPORT =
Pattern.compile(
"^\\s*import\\s+(dev\\.caskeleton\\.adapter\\.outbound\\.persistence\\.[A-Za-z0-9_$.]+)\\s*;\\s*$");
private static final List<String> OWNERS =
List.of("adapter/outbound/persistence-jpa/", "adapter/outbound/persistence-fileserver/");
@Test
void productionCodeElsewhereImportsOnlyTheReviewedAdopterSurface() throws IOException {
// given
Set<String> allowed = new TreeSet<>();
for (String line : Files.readAllLines(BASELINE)) {
if (!line.isBlank() && !line.startsWith("#")) {
allowed.add(line.trim());
}
}
// when
Set<String> unreviewed = new TreeSet<>();
for (Path source : adopterSources()) {
for (String line : Files.readAllLines(source)) {
Matcher matcher = IMPORT.matcher(line);
if (matcher.matches() && !allowed.contains(matcher.group(1))) {
unreviewed.add(SOURCE_ROOT.relativize(source) + ": " + matcher.group(1));
}
}
}
// then
assertThat(unreviewed).isEmpty();
}
private static List<Path> adopterSources() throws IOException {
List<Path> sources = new ArrayList<>();
Files.walkFileTree(
SOURCE_ROOT,
new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attributes) {
String name = directory.getFileName() == null ? "" : directory.getFileName().toString();
String path = SOURCE_ROOT.relativize(directory).toString().replace('\\', '/') + "/";
boolean skipped =
name.equals("build")
|| name.startsWith(".")
|| OWNERS.stream().anyMatch(path::startsWith);
return skipped && !directory.equals(SOURCE_ROOT)
? FileVisitResult.SKIP_SUBTREE
: FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
String path = file.toString().replace('\\', '/');
if (path.endsWith(".java") && path.contains("/src/main/java/")) {
sources.add(file);
}
return FileVisitResult.CONTINUE;
}
});
return sources;
}
}
@@ -0,0 +1,262 @@
package dev.caskeleton.adapter.outbound.persistence.testkit;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
/**
* The JPA readiness cards ({@code src/config/jpa/readiness-cards.yaml}) against the lanes and tests
* they name.
*
* <p>This replaced the build-tools {@code ca.jpa-qualification}/{@code ca.jpa-evidence} plugins
* (review 2026-09-24 BUILD-O3-2, owner decision 4). The evidence manifest they generated is gone;
* what it proved is split between this test (the registry is well formed and every lane, scenario
* and migration stream it names exists) and the readiness lanes themselves, which require every
* scenario selector a card cites and reject skipped tests. The build declares the registry and the
* readiness sources as inputs of {@code test}.
*/
class JpaReadinessRegistryTest {
private static final Path SOURCE_ROOT = Path.of("../../..").toAbsolutePath().normalize();
private static final Path REGISTRY = SOURCE_ROOT.resolve("config/jpa/readiness-cards.yaml");
private static final Path LEAF = SOURCE_ROOT.resolve("adapter/outbound/persistence-jpa");
private static final String LEAF_PATH = ":adapter:outbound:persistence-jpa:";
private static final Set<String> STATES =
Set.of("selected", "implemented-candidate", "not-implemented");
private static final Set<String> LEAF_AGGREGATES = Set.of("test", "integrationTestLaneCheck");
private static final Pattern LANE_NAME =
Pattern.compile("^\\s*(?:lane\\('(\\w+)'\\)|(\\w+)\\s*:\\s*\\[)", Pattern.MULTILINE);
private final JsonNode registry = JsonMapper.builder().build().readTree(REGISTRY.toFile());
@Test
@DisplayName("모든 카드의 상태와 선행 카드가 유효하고 선행 관계에 순환이 없다")
void everyCardHasALegalStateAndAnAcyclicSetOfKnownPrerequisites() {
// given
Map<String, JsonNode> cards = cards();
// when
List<String> violations = new ArrayList<>();
cards.forEach(
(id, card) -> {
String state = card.path("state").asString();
if (!STATES.contains(state)) {
violations.add(id + ": unknown state " + state);
}
for (JsonNode prerequisite : card.path("prerequisites")) {
JsonNode target = cards.get(prerequisite.asString());
if (target == null) {
violations.add(id + ": unknown prerequisite " + prerequisite.asString());
} else if (state.equals("selected")
&& !target.path("state").asString().equals("selected")) {
violations.add(id + ": selected card requires non-selected " + prerequisite);
}
}
if (hasCycle(id, cards, new HashSet<>())) {
violations.add(id + ": prerequisite cycle");
}
});
// then
assertThat(violations).isEmpty();
}
@Test
@DisplayName("구현된 카드가 가리키는 이 leaf의 task는 build.gradle에 선언된 lane이다")
void everyImplementedCardNamesTasksThisLeafDeclares() throws IOException {
// given
Set<String> declared = declaredLaneNames();
// when
List<String> unknown = new ArrayList<>();
activeCards()
.forEach(
(id, card) -> {
List<String> tasks = new ArrayList<>();
tasks.add(card.path("readiness-task").asString());
card.path("support-tasks").forEach(task -> tasks.add(task.asString()));
for (String task : tasks) {
if (task.startsWith(LEAF_PATH)) {
String name = task.substring(LEAF_PATH.length());
if (!declared.contains(name) && !LEAF_AGGREGATES.contains(name)) {
unknown.add(id + ": " + task);
}
} else if (!task.startsWith(":")) {
unknown.add(id + ": not an absolute task path " + task);
}
}
});
// then
assertThat(unknown).isEmpty();
}
@Test
@DisplayName("구현된 카드의 evidence는 존재하는 테스트 메서드와 카드가 요구한 항목만 가리킨다")
void everyEvidenceScenarioNamesAnExistingTestMethodAndARequiredClaim() {
// given
Map<String, JsonNode> active = activeCards();
// when
List<String> violations = new ArrayList<>();
Set<String> selectors = new HashSet<>();
active.forEach(
(id, card) -> {
Set<String> allowed = new HashSet<>();
card.path("required-evidence").forEach(claim -> allowed.add(claim.asString()));
if (!allowed.remove("no-skip")) {
violations.add(id + ": required-evidence must include no-skip");
}
card.path("migration")
.path("lifecycle-evidence")
.forEach(stage -> allowed.add("migration-lifecycle:" + stage.asString()));
Set<String> covered = new HashSet<>();
for (JsonNode scenario : card.path("evidence").path("scenarios")) {
String selector = scenario.path("selector").asString();
if (!selectors.add(selector)) {
violations.add(id + ": duplicate selector " + selector);
}
if (!testMethodExists(selector)) {
violations.add(id + ": no such readiness test method " + selector);
}
scenario.path("covers").forEach(claim -> covered.add(claim.asString()));
}
for (JsonNode claim : card.path("evidence").path("task-claims")) {
claim.path("covers").forEach(cover -> covered.add(cover.asString()));
}
Set<String> unknownClaims = new HashSet<>(covered);
unknownClaims.removeAll(allowed);
if (!unknownClaims.isEmpty()) {
violations.add(id + ": covers requirements it does not declare " + unknownClaims);
}
Set<String> uncovered = new HashSet<>(allowed);
uncovered.removeAll(covered);
uncovered.removeIf(claim -> claim.startsWith("migration-lifecycle:"));
if (!uncovered.isEmpty()) {
violations.add(id + ": required evidence nothing covers " + uncovered);
}
});
// then
assertThat(violations).isEmpty();
}
@Test
@DisplayName("소유 schema stream마다 고유한 migration 위치와 history table이 있고 구현된 stream의 위치는 존재한다")
void everyOwnedSchemaStreamHasAUniqueExistingLocationAndHistoryTable() {
// given
Map<String, JsonNode> cards = cards();
// when
List<String> violations = new ArrayList<>();
Map<String, String> locations = new HashMap<>();
Map<String, String> historyTables = new HashMap<>();
cards.forEach(
(id, card) -> {
boolean owned = card.path("schema-stream").asString().equals("owned");
JsonNode migration = card.path("migration");
if (owned != !migration.isMissingNode()) {
violations.add(id + ": an owned schema stream and a migration go together");
return;
}
if (!owned) {
return;
}
String location = migration.path("location").asString();
String history = migration.path("history-table").asString();
if (locations.put(location, id) != null) {
violations.add(id + ": duplicate migration location " + location);
}
if (historyTables.put(history, id) != null) {
violations.add(id + ": duplicate history table " + history);
}
if (!card.path("state").asString().equals("not-implemented")
&& !migrationLocationExists(location)) {
violations.add(id + ": no persistence leaf ships " + location);
}
});
// then
assertThat(violations).isEmpty();
}
private Map<String, JsonNode> cards() {
Map<String, JsonNode> cards = new HashMap<>();
registry
.path("cards")
.properties()
.forEach(entry -> cards.put(entry.getKey(), entry.getValue()));
return cards;
}
private Map<String, JsonNode> activeCards() {
Map<String, JsonNode> active = new HashMap<>(cards());
active.values().removeIf(card -> card.path("state").asString().equals("not-implemented"));
return active;
}
private static boolean hasCycle(String id, Map<String, JsonNode> cards, Set<String> path) {
if (!path.add(id)) {
return true;
}
JsonNode card = cards.get(id);
if (card != null) {
for (JsonNode prerequisite : card.path("prerequisites")) {
if (hasCycle(prerequisite.asString(), cards, path)) {
return true;
}
}
}
path.remove(id);
return false;
}
private static Set<String> declaredLaneNames() throws IOException {
Set<String> names = new HashSet<>();
Matcher matcher = LANE_NAME.matcher(Files.readString(LEAF.resolve("build.gradle")));
while (matcher.find()) {
names.add(matcher.group(1) != null ? matcher.group(1) : matcher.group(2));
}
return names;
}
private static boolean testMethodExists(String selector) {
int hash = selector.indexOf('#');
if (hash < 0) {
return false;
}
Path source =
LEAF.resolve("src/postgresqlIntegrationTest/java")
.resolve(selector.substring(0, hash).replace('.', '/') + ".java");
try {
return Files.isRegularFile(source)
&& Files.readString(source).contains("void " + selector.substring(hash + 1) + "(");
} catch (IOException unreadable) {
return false;
}
}
private static boolean migrationLocationExists(String location) {
try (Stream<Path> leaves = Files.list(SOURCE_ROOT.resolve("adapter/outbound"))) {
return leaves.anyMatch(
leaf -> Files.isDirectory(leaf.resolve("src/main/resources").resolve(location)));
} catch (IOException unreadable) {
return false;
}
}
}
@@ -31,7 +31,7 @@ class JpaReleaseRenderingTest {
private final JpaReleaseManifest manifest = JpaReleaseManifest.loadFromRepository();
private final String supportMatrix = read("docs/jpa/support-matrix.md");
private final String releaseWorkflow = read(".github/workflows/jpa-release.yml");
private final String releaseWorkflow = read(".github/workflows/release.yml");
private final String nightlyWorkflow = read(".github/workflows/jpa-nightly.yml");
@Test
@@ -226,12 +226,17 @@ tasks.named('check') {
dependsOn 'mongoStableContractTest'
}
// MongoTestLaneContractTest reads the integration sources' lane tags and the release-contract
// manifest; both are inputs here, or Gradle would call `test` up to date after editing either.
tasks.named('test') {
inputs.dir('src/mongoIntegrationTest/java').withPathSensitivity(PathSensitivity.RELATIVE)
inputs.file(rootProject.file('config/mongodb/release-contracts.json'))
.withPathSensitivity(PathSensitivity.RELATIVE)
// MongoTestLaneContractTest compares the integration sources' lane tags with the release-contract
// manifest. A comparison with a repository document, so it runs in this leaf's `mainCheck`, not in
// the pull-request `test` (review 2026-09-24 BUILD-계획-B4-30). A lane never reports up to date, so
// it needs no inputs declared for the files it reads.
strictTestLanes {
lane('mongoDocumentContractTest') {
tag = 'document-contract'
description = 'Holds the Mongo lane tags to config/mongodb/release-contracts.json.'
rejectSkipped = true
mainStage()
}
}
@@ -23,9 +23,10 @@ import tools.jackson.databind.json.JsonMapper;
/**
* The Mongo lanes are defined by tags, so a tag mistake moves a test between lanes without any
* build failure. These two rules read the files the lanes are built from; the build declares both
* as inputs of this leaf's {@code test} task.
* build failure. These two rules read the files the lanes are built from. They run in the
* main-stage lane {@code mongoDocumentContractTest}, which always executes, not in {@code test}.
*/
@Tag("document-contract")
class MongoTestLaneContractTest {
private static final Path INTEGRATION_SOURCES = Path.of("src/mongoIntegrationTest/java");
+37 -1
View File
@@ -110,7 +110,8 @@ sourceSets {
// Every capability a service can select — the commented runtimeOnly lines below — listed once.
// Two consumers read it: the whole-repository ArchUnit import (spec §7: the architecture suite sees
// every module, the shipped runtime only the selected ones) and the qualification artifact the
// every module of this build and the sample, the shipped runtime only the selected ones; the
// optional-platforms build is held by its own Gradle direction gate instead) and the qualification artifact the
// Compose lanes boot (qualificationBootJar, below). Neither reaches `bootJar`, `test` or
// `systemTest`, because a capability on a classpath is switched on there by its mere presence.
// A new capability leaf is added here and as a commented line below; nowhere else.
@@ -154,6 +155,14 @@ dependencies {
// runtimeOnly project(':composition:notification-platform') // 알림 (persistence-jpa 줄도 함께 푼다)
capabilityProjects.each { architectureTestRuntimeOnly project(it) }
// The sample is the reference adopters copy, so the whole-repository rules read it too (review
// BUILD-중복-8). Architecture-test runtime only: no production configuration reaches it.
//
// What this import does NOT see: the optional-platforms build (`grpc:*`, `grpc-advanced:*`).
// It is a separate Gradle build, so its classes cannot be on this classpath; its registered
// leaves are held by the Gradle direction gate (`-p optional-platforms ci` runs
// verifyCleanArchitectureDependencies), which is the whole of what the owner decided it needs.
architectureTestRuntimeOnly project(':sample-portfolio')
// The capability integration lane selects Fileserver and object storage together, as a service
// would, and turns off whichever one a test is not about.
@@ -311,6 +320,33 @@ bootJar {
mainClass = 'dev.caskeleton.bootstrap.CaSkeletonApplication'
}
// The deployable artifact names the release and the commit it was built from in
// META-INF/build-info.properties (review BUILD-O3-5: provenance through Spring Boot's build info
// rather than a revision in every leaf's jar name). `time` is excluded so an unchanged commit still
// produces an unchanged resource and cached tasks stay cached.
springBoot {
buildInfo {
excludes = ['time']
properties {
additional = ['revision': rootProject.releaseProvenance.sourceRevision]
}
}
}
// The deny-by-default public path baseline (docs/security/public-paths-snapshot.txt) is an approval
// test beside the security configuration it pins, not a build-logic plugin (review BUILD-O3-5). The
// root `verifyPublicPathSnapshot` names this lane; `-PapprovePublicPathChange` rewrites the baseline
// after review instead of comparing it.
strictTestLanes {
lane('publicPathSnapshotTest') {
tag = 'public-path-snapshot'
description = 'Compares the shipped public path default with the reviewed baseline.'
rejectSkipped = true
mainStage()
systemProperty 'publicpath.snapshot.write', project.hasProperty('approvePublicPathChange') ? 'true' : 'false'
}
}
tasks.register('stageDockerJar', Sync) {
dependsOn tasks.named('bootJar')
from(tasks.named('bootJar').flatMap { it.archiveFile })
+1
View File
@@ -20,6 +20,7 @@ com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,architectureTes
com.github.docker-java:docker-java-api:3.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath
com.github.docker-java:docker-java-transport-zerodep:3.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath
com.github.docker-java:docker-java-transport:3.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath
com.github.f4b6a3:uuid-creator:6.1.1=architectureTestRuntimeClasspath
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor
com.github.luben:zstd-jni:1.5.6-10=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs
@@ -159,7 +159,7 @@ ca-skeleton:
presentation:
# Pinned even though application.yml has an inline default, because the default is /v1 and
# src/.env says /api. Everything that names a URL in this repository — SECURITY_PUBLIC_PATHS,
# the compose healthchecks, bootstrapSmoke, the README curl — assumes /api, so a launcher that
# the compose healthchecks, scripts/bootstrap-local.sh, the README curl — assumes /api, so a launcher that
# missed src/.env served /v1/healthcheck and answered 401 on the address the docs give.
api-base-path: /api
privacy:
@@ -11,6 +11,7 @@ import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
@@ -33,21 +34,26 @@ class DeveloperExperienceContractTest {
}
@Test
void bootstrapEntrypointIsOwnedByDeveloperBootstrapPlugin() throws IOException {
String build = read("src/build.gradle");
@DisplayName("로컬 기동 진입점은 네 단계를 순서대로 밟는 scripts/bootstrap-local.sh 하나다")
void theLocalBootstrapEntrypointIsOneScriptWithFourOrderedStages() throws IOException {
// given
Path script = REPOSITORY_ROOT.resolve("scripts/bootstrap-local.sh");
// Registration and ordering are executable behavior and are covered by
// DeveloperBootstrapPluginFunctionalTest. The repository contract only fixes ownership: the
// root applies one Java convention and must not duplicate the bootstrap implementation in
// Groovy.
assertThat(build)
.contains("id 'ca.developer-bootstrap'")
.doesNotContain("tasks.register('bootstrapCompile')")
.doesNotContain("tasks.register('bootstrapDockerPreflight')")
.doesNotContain("tasks.register('bootstrapDependencies')")
.doesNotContain("tasks.register('bootstrapMigrateAndStart')")
.doesNotContain("tasks.register('bootstrapSmoke')")
.doesNotContain("tasks.register('bootstrap')");
// when
String body = Files.readString(script);
// then
// It replaced the build-logic ca.developer-bootstrap plugin (review BUILD-O3-5); starting
// containers and probing a port is not a build rule. `set -e` is what makes the order a
// contract: a stage runs only when the one before it succeeded.
assertThat(Files.isExecutable(script)).isTrue();
assertThat(body).contains("set -euo pipefail");
assertThat(body.indexOf("bootstrap 1/4"))
.isPositive()
.isLessThan(body.indexOf("bootstrap 2/4"));
assertThat(body.indexOf("bootstrap 2/4")).isLessThan(body.indexOf("bootstrap 3/4"));
assertThat(body.indexOf("bootstrap 3/4")).isLessThan(body.indexOf("bootstrap 4/4"));
assertThat(read("src/build.gradle")).doesNotContain("ca.developer-bootstrap");
}
@Test
@@ -110,7 +116,7 @@ class DeveloperExperienceContractTest {
String readme = read("README.md");
assertThat(readme)
.contains("./gradlew bootstrap")
.contains("scripts/bootstrap-local.sh")
.contains("GET /api/healthcheck")
.contains("## 퀵스타트")
.contains("첫 실행 진입점은 하나입니다.");
@@ -255,15 +261,19 @@ class DeveloperExperienceContractTest {
void architectureWorkflowSelectorsUseTheArchitectureSourceSetTask() throws IOException {
String staleSelector = ":app-bootstrap:test --tests 'dev.caskeleton.bootstrap.architecture.*'";
// The whole-repository architecture suite runs once per pull request, in ci-quality-gates.yml's
// `:ci` (architectureCheck). The fileserver workflow's filtered second run was removed (review
// BUILD-중복-6), and the release workflow runs only the tag-only releaseCheck.
assertThat(read(".github/workflows/ci-quality-gates.yml"))
.as("the pull-request gate is the one place the architecture suite runs")
.contains("./gradlew :ci");
assertThat(read(".github/workflows/fileserver-pr.yml"))
.as(
"the fileserver PR workflow must execute architecture tests through their source-set"
+ " task")
.contains(":app-bootstrap:architectureTest")
.as("the fileserver PR workflow must not repeat the architecture suite")
.doesNotContain(":app-bootstrap:architectureTest")
.doesNotContain(staleSelector);
assertThat(read(".github/workflows/release.yml"))
.as("the release workflow delegates repository architecture policy to releaseCheck")
.as("the release workflow runs the tag-only checks through releaseCheck")
.contains("./gradlew :releaseCheck")
.doesNotContain(staleSelector);
@@ -0,0 +1,153 @@
package dev.caskeleton.bootstrap.security;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
/**
* The deny-by-default public path surface against its committed, reviewed baseline.
*
* <p>An approval test rather than the build-logic {@code ca.public-path-snapshot} plugin it
* replaced (review 2026-09-24 BUILD-O3-5): the rule is about this composition root's shipped
* security configuration, so it lives beside it. The repository comparison runs in the main-stage
* lane {@code publicPathSnapshotTest} (root alias {@code verifyPublicPathSnapshot}); approving a
* reviewed change is {@code ./gradlew verifyPublicPathSnapshot -PapprovePublicPathChange}, which
* rewrites the baseline instead of comparing. The rendering cases run in {@code test}.
*/
class PublicPathSnapshotTest {
private static final Path SECURITY_CONFIGURATION =
Path.of("src/main/resources/config/security.yml");
private static final Path SNAPSHOT = Path.of("../../docs/security/public-paths-snapshot.txt");
private static final Pattern BINDING = Pattern.compile("^\\s*public-paths:\\s*(\\S.*?)\\s*$");
private static final Pattern DEFAULTED_PLACEHOLDER =
Pattern.compile("\\$\\{[A-Za-z0-9_.]+:([^{}]*)}");
private static final String HEADER =
"""
# feature-security-operational-baseline D5 — deny-by-default public path snapshot.
# SSOT: ca-skeleton.security.public-paths default in app-bootstrap/src/main/resources/config/security.yml
# -> SecurityConfig permitAll(); anyRequest authenticated. An operator's own SECURITY_PUBLIC_PATHS
# overrides it at run time and is outside this snapshot.
# Update only after review with: ./gradlew verifyPublicPathSnapshot -PapprovePublicPathChange
""";
@Test
@Tag("public-path-snapshot")
@DisplayName("배포되는 public path 기본값이 검토된 기준선과 같다")
void theShippedPublicPathDefaultMatchesTheReviewedBaseline() throws IOException {
// given
String rendered = render(Files.readAllLines(SECURITY_CONFIGURATION, StandardCharsets.UTF_8));
if (Boolean.getBoolean("publicpath.snapshot.write")) {
Files.writeString(SNAPSHOT, rendered, StandardCharsets.UTF_8);
}
// when
String committed =
Files.isRegularFile(SNAPSHOT) ? Files.readString(SNAPSHOT, StandardCharsets.UTF_8) : "";
// then
assertThat(committed)
.as(
"the deny-by-default public path surface changed, so a protected endpoint may now be"
+ " public. Review it, then run ./gradlew verifyPublicPathSnapshot"
+ " -PapprovePublicPathChange")
.isEqualTo(rendered);
}
@Test
@DisplayName("중첩된 기본값 placeholder를 풀어 정렬된 경로 목록으로 만든다")
void nestedDefaultedPlaceholdersUnwindToASortedPathList() {
// given
List<String> configuration =
List.of(
"ca-skeleton:",
" security:",
" public-paths: ${SECURITY_PUBLIC_PATHS:${API_BASE:/v1}/z,${API_BASE:/v1}/a}");
// when
String rendered = render(configuration);
// then
assertThat(rendered).isEqualTo(HEADER + "/v1/a\n/v1/z\n");
}
@Test
@DisplayName("기본값 없는 placeholder가 남으면 기준선을 만들지 않고 실패한다")
void aPlaceholderWithoutADefaultCannotBeSnapshotted() {
// given
List<String> configuration = List.of(" public-paths: ${SECURITY_PUBLIC_PATHS}");
// when
Throwable failure = catchThrowable(() -> render(configuration));
// then
assertThat(failure)
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("still holds a placeholder with no default");
}
@Test
@DisplayName("public-paths 바인딩이 정확히 하나가 아니면 실패한다")
void aConfigurationWithoutExactlyOneBindingIsRefused() {
// given
List<String> configuration = List.of("ca-skeleton:", " security: {}");
// when
Throwable failure = catchThrowable(() -> render(configuration));
// then
assertThat(failure)
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("expected exactly one 'public-paths:' binding, found 0");
}
private static String render(List<String> configuration) {
List<String> bindings = new ArrayList<>();
for (String line : configuration) {
Matcher matcher = BINDING.matcher(line);
if (matcher.matches()) {
bindings.add(matcher.group(1));
}
}
if (bindings.size() != 1) {
throw new IllegalStateException(
"expected exactly one 'public-paths:' binding, found "
+ bindings.size()
+ " — the snapshot cannot say which surface it pins");
}
String raw = bindings.getFirst();
for (int depth = 0; depth < 16; depth++) {
Matcher matcher = DEFAULTED_PLACEHOLDER.matcher(raw);
if (!matcher.find()) {
break;
}
raw = raw.substring(0, matcher.start()) + matcher.group(1) + raw.substring(matcher.end());
}
if (raw.contains("${")) {
throw new IllegalStateException(
"'public-paths' resolves to '"
+ raw
+ "', which still holds a placeholder with no default — the deployed surface is not"
+ " determined by the repository");
}
List<String> paths =
Pattern.compile(",")
.splitAsStream(raw)
.map(String::trim)
.filter(value -> !value.isEmpty())
.sorted()
.toList();
return HEADER + (paths.isEmpty() ? "" : String.join("\n", paths) + "\n");
}
}
+3
View File
@@ -7,6 +7,9 @@ plugins {
// composition and diagnostic rendering belong to adapters/bootstrap.
dependencies {
// The direction the registry, AGENTS.md and the layer workflow all state: a use case orchestrates
// the domain (review S1-#16). modules.json has allowed this edge all along; the build had lost it.
implementation project(':domain-core')
implementation project(':shared-contract')
// Port contracts (`*Contract`) are abstract JUnit classes that fakes and adapters both extend.
+11 -4
View File
@@ -15,12 +15,13 @@ capability, and the files it reads are declared as that test task's inputs.
| `ca.quality-conventions` | Spotless, Checkstyle, Error Prone, SpotBugs/FindSecBugs wiring shared by Java leaves |
| `ca.java-library` / `ca.spring-library` / `ca.spring-config` | leaf-level composition of the Java/quality conventions for plain and Spring libraries |
| `ca.platform-module` / `ca.grpc-platform-module` | what a vendored platform leaf (`messaging:*`, `grpc:*`, `grpc-advanced:*`) is: `java-library`, plus the gRPC BOM for the leaves that had it |
| `ca.strict-test-lane` | the one "named tests ran, none skipped" mechanism: tagged / named / own-source-set `Test` lanes that fail when they execute nothing, miss a `requires` class, or (with `rejectSkipped`) skip anything |
| `ca.strict-test-lane` | the one "named tests ran, none skipped" mechanism: tagged / named / own-source-set `Test` lanes that fail when they execute nothing, miss a `requires` class, or (with `rejectSkipped`) skip anything. `mainStage()` moves a tagged lane out of `test` into the leaf's `mainCheck`; `explicitOnly(reason)` keeps a lane that needs an outside input out of every aggregate, and the aggregate prints the reason |
| `ca.redis-topology-lane` | the Redis topology lane (mode selection, `-P` property validation, per-mode required classes) the redis-sdk-topology workflow drives |
| `ca.auxiliary-source-set` | extra test source sets |
| `ca.api-surface` | read-only public API surface verification with a separate update task, wired into `mainCheck` |
| `ca.public-path-snapshot`, `ca.archive-hygiene`, `ca.release-provenance` | the permitAll baseline, stale traceable jars, release version and revision |
| `ca.developer-bootstrap`, `ca.bootrun-dotenv` | the ordered local start-up and `bootRun`'s `.env` |
| `ca.api-surface` | read-only public API surface verification with a separate update task, wired into the leaf's `check` (owner decision 20); optionally holds other leaves' imports to a reviewed adopter subset (`adopterBaseline`) |
| `ca.release-provenance` | release version and revision (`verifyReleaseProvenance`); leaf versions carry the release version only |
| `ca.config-contract` | app-bootstrap's `verifyEnvKeys` (moved from the deleted build-tools included build; owner decision 4 keeps the task in app-bootstrap) |
| `ca.bootrun-dotenv` | `bootRun`'s `.env` |
Plain classes rather than plugins, because settings and projects load plugins through different
mechanisms and more than one caller needs each:
@@ -45,6 +46,12 @@ Error Prone, `-Werror`, SpotBugs and Checkstyle off for benchmark and generated
| `ca.jpa-test-lanes` | the lanes declared in `adapter/outbound/persistence-jpa/build.gradle` |
| `ca.test-jvm-agents`, `quarantineTest` | `ca.java-conventions`; the quarantine bucket had no tests |
| `ca.jmh-benchmarks` | `me.champeau.jmh` |
| build-tools `ca.jpa-evidence`, `ca.jpa-qualification` (+ `junit` evidence reader) | owner decision 4: persistence-jpa `JpaReadinessRegistryTest`, readiness lanes that require every cited scenario and reject skips, the leaf's `jpaReleaseQualification` aggregate over `config/jpa/release-registry.json` |
| build-tools `ca.config-contract` | moved here unchanged |
| `ca.public-path-snapshot` | app-bootstrap `PublicPathSnapshotTest` (lane `publicPathSnapshotTest`, root alias `verifyPublicPathSnapshot`) |
| `ca.archive-hygiene` | nothing to clean: leaf versions no longer carry the revision, so no stale traceable jar is produced |
| `ca.developer-bootstrap` | `scripts/bootstrap-local.sh` |
| `JpaAdopterApiSurfaceTest` (a regex import scan in persistence-jpa) | `ca.api-surface` `adopterBaseline` |
## Testing a convention
+4 -12
View File
@@ -35,14 +35,6 @@ dependencies {
gradlePlugin {
plugins {
publicPathSnapshot {
id = 'ca.public-path-snapshot'
implementationClass = 'dev.caskeleton.buildlogic.publicpath.PublicPathSnapshotPlugin'
}
archiveHygiene {
id = 'ca.archive-hygiene'
implementationClass = 'dev.caskeleton.buildlogic.archive.ArchiveHygienePlugin'
}
auxiliarySourceSet {
id = 'ca.auxiliary-source-set'
implementationClass = 'dev.caskeleton.buildlogic.auxiliary.AuxiliarySourceSetPlugin'
@@ -63,10 +55,6 @@ gradlePlugin {
id = 'ca.java-conventions'
implementationClass = 'dev.caskeleton.buildlogic.java.JavaConventionsPlugin'
}
developerBootstrap {
id = 'ca.developer-bootstrap'
implementationClass = 'dev.caskeleton.buildlogic.bootstrap.DeveloperBootstrapPlugin'
}
bootRunDotenv {
id = 'ca.bootrun-dotenv'
implementationClass = 'dev.caskeleton.buildlogic.bootstrap.BootRunDotenvPlugin'
@@ -107,6 +95,10 @@ gradlePlugin {
id = 'ca.platform-module'
implementationClass = 'dev.caskeleton.buildlogic.convention.PlatformModuleConventionPlugin'
}
configContract {
id = 'ca.config-contract'
implementationClass = 'dev.caskeleton.buildlogic.config.ConfigContractPlugin'
}
grpcPlatformModuleConvention {
id = 'ca.grpc-platform-module'
implementationClass = 'dev.caskeleton.buildlogic.convention.GrpcPlatformModuleConventionPlugin'
@@ -12,6 +12,8 @@ public class ApiSurfaceExtension {
private List<String> rationale = new ArrayList<>();
private String sourceRoot = "src/main/java";
private List<String> additionalSourceRoots = new ArrayList<>();
private File adopterBaseline;
private Object adopterSources;
public String getLabel() { return label; }
public void setLabel(String label) { this.label = label; }
@@ -30,4 +32,14 @@ public class ApiSurfaceExtension {
this.additionalSourceRoots =
additionalSourceRoots == null ? new ArrayList<>() : new ArrayList<>(additionalSourceRoots);
}
/**
* The reviewed subset of the surface other leaves' production code may import. Optional: without
* it, every public type is fair game to an adopter, which is what the surface alone says.
*/
public File getAdopterBaseline() { return adopterBaseline; }
public void setAdopterBaseline(File adopterBaseline) { this.adopterBaseline = adopterBaseline; }
/** The adopter sources whose imports are held to {@link #getAdopterBaseline()}; any {@code files()} notation. */
public Object getAdopterSources() { return adopterSources; }
public void setAdopterSources(Object adopterSources) { this.adopterSources = adopterSources; }
}
@@ -87,6 +87,55 @@ public final class ApiSurfacePolicy {
+ approvalProperty);
}
/**
* Holds other leaves' imports of this surface to the reviewed adopter subset.
*
* <p>The surface says what is public; the adopter baseline says which of those public types other
* leaves' production code may depend on. An import of a surface type the adopter baseline does not
* list fails, and so does an adopter entry the surface no longer has.
*/
public static void verifyAdopters(
String verifyTaskName, String rendered, File adopterBaseline, List<String> adopterImports) {
if (!adopterBaseline.isFile()) {
throw new IllegalStateException(
verifyTaskName + ": missing committed adopter baseline " + adopterBaseline);
}
java.util.Set<String> surface = new java.util.HashSet<>(surfaceLines(rendered));
java.util.Set<String> allowed = new java.util.TreeSet<>();
for (String line : read(adopterBaseline).lines().toList()) {
if (!line.isBlank() && !line.startsWith("#")) {
allowed.add(line.trim());
}
}
List<String> stale = allowed.stream().filter(type -> !surface.contains(type)).toList();
List<String> unreviewed =
adopterImports.stream()
.filter(entry -> {
String type = entry.substring(entry.indexOf(": ") + 2);
return surface.contains(type) && !allowed.contains(type);
})
.toList();
if (stale.isEmpty() && unreviewed.isEmpty()) {
return;
}
throw new IllegalStateException(
verifyTaskName
+ ": the adopter surface ("
+ adopterBaseline.getName()
+ ") does not match what other leaves import.\n"
+ (unreviewed.isEmpty()
? ""
: " imported but not in the adopter baseline:\n "
+ String.join("\n ", unreviewed)
+ "\n")
+ (stale.isEmpty()
? ""
: " in the adopter baseline but not in the public surface:\n "
+ String.join("\n ", stale)
+ "\n")
+ "Add a reviewed type to the adopter baseline, or stop importing it.");
}
public static void requireNoUnapprovedGrowth(
String updateTaskName,
String owningProjectPath,
@@ -2,6 +2,7 @@ package dev.caskeleton.buildlogic;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.JavacTask;
import java.io.File;
@@ -44,6 +45,47 @@ public final class JavaPublicTypes {
}
}
}
Set<String> types = new TreeSet<>();
for (CompilationUnitTree unit : parse(sources, "The public API surface")) {
if (unit.getPackageName() == null) {
continue;
}
String packageName = unit.getPackageName().toString();
for (Tree declaration : unit.getTypeDecls()) {
if (declaration instanceof ClassTree type
&& type.getModifiers().getFlags().contains(Modifier.PUBLIC)) {
types.add(packageName + "." + type.getSimpleName());
}
}
}
return List.copyOf(types);
}
/**
* Every single-type, non-static import in {@code sources}, as {@code "<file name>: <import>"}.
* Wildcard and static imports are not listed; a leaf whose adopters need them is declaring a
* surface this check does not model.
*/
public static List<String> imports(Collection<File> sources) {
List<File> files =
sources == null
? List.of()
: sources.stream().filter(file -> file.getName().endsWith(".java")).toList();
Set<String> imports = new TreeSet<>();
for (CompilationUnitTree unit : parse(files, "The adopter sources")) {
String file = new File(unit.getSourceFile().toUri()).getName();
for (ImportTree declaration : unit.getImports()) {
String name = declaration.getQualifiedIdentifier().toString();
if (!declaration.isStatic() && !name.endsWith(".*")) {
imports.add(file + ": " + name);
}
}
}
return List.copyOf(imports);
}
private static List<CompilationUnitTree> parse(Collection<File> files, String subject) {
List<File> sources = new ArrayList<>(files);
if (sources.isEmpty()) {
return List.of();
}
@@ -58,7 +100,6 @@ public final class JavaPublicTypes {
}
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
Set<String> types = new TreeSet<>();
try (StandardJavaFileManager fileManager =
compiler.getStandardFileManager(diagnostics, null, StandardCharsets.UTF_8)) {
JavacTask task =
@@ -70,7 +111,8 @@ public final class JavaPublicTypes {
List.of("-proc:none"),
null,
fileManager.getJavaFileObjectsFromFiles(sources));
Iterable<? extends CompilationUnitTree> units = task.parse();
List<CompilationUnitTree> units = new ArrayList<>();
task.parse().forEach(units::add);
List<Diagnostic<? extends JavaFileObject>> errors =
diagnostics.getDiagnostics().stream()
.filter(diagnostic -> diagnostic.getKind() == Diagnostic.Kind.ERROR)
@@ -79,27 +121,11 @@ public final class JavaPublicTypes {
String first =
errors.stream().limit(5).map(Object::toString).reduce((a, b) -> a + "\n " + b).orElse("");
String more = errors.size() > 5 ? "\n (" + (errors.size() - 5) + " more)" : "";
throw new IllegalStateException(
"The public API surface could not be parsed:\n " + first + more);
}
for (CompilationUnitTree unit : units) {
if (unit.getPackageName() == null) {
continue;
}
String packageName = unit.getPackageName().toString();
for (Tree declaration : unit.getTypeDecls()) {
if (!(declaration instanceof ClassTree type)) {
continue;
}
if (type.getModifiers().getFlags().contains(Modifier.PUBLIC)) {
types.add(packageName + "." + type.getSimpleName());
}
}
throw new IllegalStateException(subject + " could not be parsed:\n " + first + more);
}
return units;
} catch (IOException exception) {
throw new IllegalStateException("Could not parse Java source files", exception);
}
return List.copyOf(types);
}
}
@@ -67,6 +67,12 @@ public final class ApiSurfacePlugin implements Plugin<Project> {
task.getUpdateTaskName().set(updateTaskName);
task.getApprovalProperty().set(approvalProperty);
task.getUpdateApproved().set(approved);
if (extension.getAdopterBaseline() != null) {
task.getAdopterBaseline().fileValue(extension.getAdopterBaseline());
if (extension.getAdopterSources() != null) {
task.getAdopterSources().from(extension.getAdopterSources());
}
}
});
project
@@ -93,11 +99,12 @@ public final class ApiSurfacePlugin implements Plugin<Project> {
task.getCeilingRaiseApproved().set(ceilingApproved);
});
// Main-branch stage (mainCheck), not the pull-request `check`; the verify task runs on its own
// for anyone changing a public type.
// The leaf's `check`, so a pull request that changes a public type fails there (owner
// decision 20, 2026-09-25). It used to run only in `mainCheck`, which reported the change
// after it had merged.
project
.getTasks()
.matching(task -> task.getName().equals("mainCheck"))
.matching(task -> task.getName().equals("check"))
.configureEach(task -> task.dependsOn(verify));
});
}
@@ -1,6 +1,7 @@
package dev.caskeleton.buildlogic.apisurface;
import dev.caskeleton.buildlogic.ApiSurfacePolicy;
import dev.caskeleton.buildlogic.JavaPublicTypes;
import java.io.File;
import java.util.List;
import org.gradle.api.DefaultTask;
@@ -10,8 +11,12 @@ import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.ListProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.Optional;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.TaskAction;
import org.gradle.work.DisableCachingByDefault;
@@ -36,6 +41,15 @@ public abstract class VerifyApiSurfaceTask extends DefaultTask {
@Input public abstract Property<String> getApprovalProperty();
@Input public abstract Property<Boolean> getUpdateApproved();
/** Other leaves' production sources, held to the adopter baseline when one is declared. */
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
public abstract ConfigurableFileCollection getAdopterSources();
@Optional
@InputFile
public abstract RegularFileProperty getAdopterBaseline();
@TaskAction
public void verifySurface() {
if (getUpdateApproved().get()) {
@@ -63,6 +77,13 @@ public abstract class VerifyApiSurfaceTask extends DefaultTask {
getApprovalProperty().get(),
getBaseline().get().getAsFile(),
rendered);
if (getAdopterBaseline().isPresent()) {
ApiSurfacePolicy.verifyAdopters(
getName(),
rendered,
getAdopterBaseline().get().getAsFile(),
JavaPublicTypes.imports(getAdopterSources().getFiles()));
}
} catch (IllegalStateException invalidSurface) {
throw new GradleException(invalidSurface.getMessage(), invalidSurface);
}
@@ -1,65 +0,0 @@
package dev.caskeleton.buildlogic.archive;
import java.util.ArrayList;
import java.util.List;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.tasks.TaskProvider;
import org.gradle.api.tasks.bundling.Jar;
public final class ArchiveHygienePlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
TaskProvider<CleanStaleTraceableJarsTask> cleanTask =
project
.getTasks()
.register(
"cleanStaleTraceableJars",
CleanStaleTraceableJarsTask.class,
task -> {
task.setGroup("build");
task.setDescription(
"Explicitly deletes older git-revision JARs from leaf build/libs directories.");
});
TaskProvider<VerifyNoStaleTraceableJarsTask> verifyTask =
project
.getTasks()
.register(
"verifyNoStaleTraceableJars",
VerifyNoStaleTraceableJarsTask.class,
task -> {
task.setGroup("verification");
task.setDescription(
"Fails without mutation when leaf build/libs directories retain old traceable JARs.");
});
project
.getGradle()
.projectsEvaluated(
ignored -> {
List<ArchiveTarget> targets = collectTargets(project);
cleanTask.configure(task -> task.setTargets(targets));
verifyTask.configure(task -> task.setTargets(targets));
});
}
private static List<ArchiveTarget> collectTargets(Project rootProject) {
List<ArchiveTarget> targets = new ArrayList<>();
for (Project subproject : rootProject.getSubprojects()) {
subproject
.getTasks()
.withType(Jar.class)
.forEach(
jar ->
targets.add(
new ArchiveTarget(
jar.getPath(),
jar.getDestinationDirectory().get().getAsFile(),
jar.getArchiveBaseName().get(),
jar.getArchiveClassifier().getOrElse(""),
jar.getArchiveFileName().get())));
}
return List.copyOf(targets);
}
}
@@ -1,39 +0,0 @@
package dev.caskeleton.buildlogic.archive;
import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
public final class ArchiveHygienePolicy {
private ArchiveHygienePolicy() {}
public static List<File> staleArchives(ArchiveTarget target) {
File outputDirectory = target.outputDirectory();
if (!outputDirectory.isDirectory()) {
return List.of();
}
String classifierPart =
target.classifier().isBlank() ? "" : "-" + Pattern.quote(target.classifier());
Pattern traceableArchive =
Pattern.compile(
"^"
+ Pattern.quote(target.baseName())
+ "-\\d+\\.\\d+\\.\\d+\\+[0-9a-f]{7,40}"
+ classifierPart
+ "\\.jar$");
File[] matches =
outputDirectory.listFiles(
file ->
file.isFile()
&& traceableArchive.matcher(file.getName()).matches()
&& !file.getName().equals(target.currentArchiveName()));
if (matches == null || matches.length == 0) {
return List.of();
}
return Arrays.stream(matches).sorted(Comparator.comparing(File::getName)).toList();
}
}
@@ -1,22 +0,0 @@
package dev.caskeleton.buildlogic.archive;
import java.io.File;
import java.io.Serializable;
import java.util.Objects;
public record ArchiveTarget(
String taskPath,
File outputDirectory,
String baseName,
String classifier,
String currentArchiveName)
implements Serializable {
public ArchiveTarget {
Objects.requireNonNull(taskPath, "taskPath");
Objects.requireNonNull(outputDirectory, "outputDirectory");
Objects.requireNonNull(baseName, "baseName");
classifier = classifier == null ? "" : classifier;
Objects.requireNonNull(currentArchiveName, "currentArchiveName");
}
}
@@ -1,38 +0,0 @@
package dev.caskeleton.buildlogic.archive;
import java.io.File;
import java.util.List;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.work.DisableCachingByDefault;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.TaskAction;
@DisableCachingByDefault(because = "Explicit cleanup task mutates existing archives")
public abstract class CleanStaleTraceableJarsTask extends DefaultTask {
private List<ArchiveTarget> targets = List.of();
@Internal
public final List<ArchiveTarget> getTargets() {
return targets;
}
public final void setTargets(List<ArchiveTarget> targets) {
this.targets = List.copyOf(targets);
}
@TaskAction
public void cleanArchives() {
int deleted = 0;
for (ArchiveTarget target : targets) {
for (File stale : ArchiveHygienePolicy.staleArchives(target)) {
if (!stale.delete()) {
throw new GradleException("cleanStaleTraceableJars: failed to delete " + stale);
}
deleted++;
getLogger().lifecycle("cleanStaleTraceableJars: deleted {}", stale);
}
}
getLogger().lifecycle("cleanStaleTraceableJars: deleted {} stale archive(s).", deleted);
}
}
@@ -1,52 +0,0 @@
package dev.caskeleton.buildlogic.archive;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.work.DisableCachingByDefault;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.TaskAction;
@DisableCachingByDefault(because = "Verification task has no outputs")
public abstract class VerifyNoStaleTraceableJarsTask extends DefaultTask {
private List<ArchiveTarget> targets = List.of();
@Internal
public final List<ArchiveTarget> getTargets() {
return targets;
}
public final void setTargets(List<ArchiveTarget> targets) {
this.targets = List.copyOf(targets);
}
@TaskAction
public void verifyArchives() {
List<String> violations = new ArrayList<>();
for (ArchiveTarget target : targets) {
List<String> staleJars =
ArchiveHygienePolicy.staleArchives(target).stream().map(File::getName).toList();
if (!staleJars.isEmpty()) {
violations.add(
target.taskPath()
+ ": stale JAR(s) "
+ staleJars
+ "; current archive is "
+ target.currentArchiveName());
}
}
if (!violations.isEmpty()) {
throw new GradleException(
"verifyNoStaleTraceableJars: "
+ violations.size()
+ " archive task(s) retain old traceable JARs. Run cleanStaleTraceableJars explicitly "
+ "if removal is intended.\n "
+ String.join("\n ", violations));
}
getLogger()
.lifecycle("verifyNoStaleTraceableJars: OK — no stale traceable JARs in build/libs.");
}
}
@@ -1,75 +0,0 @@
package dev.caskeleton.buildlogic.bootstrap;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.TaskAction;
import org.gradle.work.DisableCachingByDefault;
@DisableCachingByDefault(because = "Probes a live local application endpoint")
public abstract class BootstrapSmokeTask extends DefaultTask {
@Input
public abstract Property<String> getEndpoint();
@Input
public abstract Property<Integer> getTimeoutSeconds();
@TaskAction
public void verifyHealth() {
URI endpoint = URI.create(getEndpoint().get());
long deadline =
System.nanoTime() + TimeUnit.SECONDS.toNanos(getTimeoutSeconds().get().longValue());
String lastFailure = "no response";
while (System.nanoTime() < deadline) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) endpoint.toURL().openConnection();
connection.setConnectTimeout(2_000);
connection.setReadTimeout(2_000);
connection.setRequestMethod("GET");
int status = connection.getResponseCode();
byte[] bodyBytes =
status >= 200 && status < 400
? connection.getInputStream().readAllBytes()
: connection.getErrorStream() == null
? new byte[0]
: connection.getErrorStream().readAllBytes();
String body = new String(bodyBytes, StandardCharsets.UTF_8);
if (status == 200 && body.contains("\"status\":\"UP\"")) {
getLogger()
.lifecycle(
"bootstrapSmoke: OK — GET /api/healthcheck returned HTTP 200 and status=UP.");
return;
}
lastFailure = "HTTP " + status + ": " + body;
} catch (IOException exception) {
lastFailure = exception.getMessage();
} finally {
if (connection != null) {
connection.disconnect();
}
}
try {
Thread.sleep(1_000L);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new GradleException("bootstrapSmoke: interrupted while waiting for healthcheck", interrupted);
}
}
throw new GradleException(
"bootstrapSmoke: /api/healthcheck did not become healthy within "
+ getTimeoutSeconds().get()
+ "s; last result: "
+ lastFailure);
}
}
@@ -1,199 +0,0 @@
package dev.caskeleton.buildlogic.bootstrap;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.tasks.Exec;
import org.gradle.api.tasks.TaskProvider;
public final class DeveloperBootstrapPlugin implements Plugin<Project> {
private static final String GROUP = "developer experience";
/** Selects the compose overlay merged onto docker-compose.yml. */
public static final String PROFILE_PROPERTY = "bootstrapProfile";
private static final String DEFAULT_PROFILE = "local";
@Override
public void apply(Project project) {
if (project != project.getRootProject()) {
throw new GradleException("ca.developer-bootstrap must be applied to the root project.");
}
File repositoryDirectory = project.getProjectDir().getParentFile();
// Which environment this bootstrap brings up. `local` stays the default, so the four-stage
// contract a developer already knows is unchanged when nothing is passed.
//
// A property rather than a `scripts/run <env>` wrapper: the ordered lifecycle — compile, Docker
// preflight, dependency wait, migrate-and-start, health smoke — already lives here, and a shell
// script would either duplicate it or become a second entry point that drifts from it. The only
// thing the environment decides is which overlay merges onto the base compose file.
String profile = String.valueOf(project.findProperty(PROFILE_PROPERTY));
if ("null".equals(profile)) {
profile = DEFAULT_PROFILE;
}
// The overlay is checked when a bootstrap task runs, not here: the Docker image build copies only
// src/ into its context, where no compose file exists, and a check at configuration time would
// stop every task in that build — not only the bootstrap ones.
File overlay = new File(repositoryDirectory, "docker-compose." + profile + ".yml");
File baseComposeFile = new File(repositoryDirectory, "docker-compose.yml");
List<String> composeCommand =
List.of(
"docker",
"compose",
"-f",
baseComposeFile.getAbsolutePath(),
"-f",
overlay.getAbsolutePath());
String bootstrapProfile = profile;
TaskProvider<?> compile =
project
.getTasks()
.register(
"bootstrapCompile",
task -> {
task.setGroup(GROUP);
task.setDescription(
"Stage 1/4: compiles the default application composition and its required upstream projects.");
task.dependsOn(":app-bootstrap:compileTestJava");
});
ByteArrayOutputStream dockerInfoOutput = new ByteArrayOutputStream();
ByteArrayOutputStream dockerInfoError = new ByteArrayOutputStream();
TaskProvider<Exec> dockerPreflight =
project
.getTasks()
.register(
"bootstrapDockerPreflight",
Exec.class,
task -> {
task.setGroup(GROUP);
task.setDescription("Checks that the Docker CLI can reach a running Docker daemon.");
task.dependsOn(compile);
task.doFirst(
ignored -> requireOverlay(overlay, bootstrapProfile, repositoryDirectory));
task.commandLine("docker", "info");
task.setIgnoreExitValue(true);
task.setStandardOutput(dockerInfoOutput);
task.setErrorOutput(dockerInfoError);
task.doLast(
ignored -> {
if (task.getExecutionResult().get().getExitValue() != 0) {
throw new GradleException(
"bootstrap: Docker가 필요합니다. Docker Desktop/daemon을 시작한 뒤 "
+ "`docker info`가 성공하는지 확인하세요.\n"
+ dockerInfoError);
}
});
});
TaskProvider<Exec> dependencies =
project
.getTasks()
.register(
"bootstrapDependencies",
Exec.class,
task -> {
task.setGroup(GROUP);
task.setDescription(
"Stage 2/4: starts the "
+ bootstrapProfile
+ " PostgreSQL dependency and waits for readiness.");
task.dependsOn(dockerPreflight);
task.commandLine(command(composeCommand, "up", "-d", "--wait", "db"));
});
TaskProvider<Exec> migrateAndStart =
project
.getTasks()
.register(
"bootstrapMigrateAndStart",
Exec.class,
task -> {
task.setGroup(GROUP);
task.setDescription(
"Stage 3/4: builds/starts the app; startup Flyway must finish before health is ready.");
task.dependsOn(dependencies);
task.commandLine(
command(composeCommand, "up", "-d", "--build", "--wait", "app"));
});
TaskProvider<BootstrapSmokeTask> smoke =
project
.getTasks()
.register(
"bootstrapSmoke",
BootstrapSmokeTask.class,
task -> {
task.setGroup(GROUP);
task.setDescription(
"Stage 4/4: requires HTTP 200 and status=UP from GET /api/healthcheck.");
task.dependsOn(migrateAndStart);
task.getEndpoint().set("http://localhost:8080/api/healthcheck");
task.getTimeoutSeconds().set(60);
});
project
.getTasks()
.register(
"bootstrap",
task -> {
task.setGroup(GROUP);
task.setDescription(
"Runs the complete four-stage bootstrap contract for the "
+ bootstrapProfile
+ " environment. Select another with -P"
+ PROFILE_PROPERTY
+ "=<name>.");
task.dependsOn(smoke);
});
}
private static void requireOverlay(File overlay, String profile, File repositoryDirectory) {
if (!overlay.isFile()) {
throw new GradleException(
"bootstrap: -P"
+ PROFILE_PROPERTY
+ "="
+ profile
+ " names no overlay; expected "
+ overlay.getName()
+ " beside docker-compose.yml. Available: "
+ availableProfiles(repositoryDirectory));
}
}
/** The overlay names that exist beside the base compose file, for the failure message. */
private static List<String> availableProfiles(File repositoryDirectory) {
File[] files = repositoryDirectory.listFiles();
if (files == null) {
return List.of();
}
List<String> profiles = new ArrayList<>();
for (File file : files) {
String name = file.getName();
// The base file is `docker-compose.yml`, which matches both affixes and names no profile.
int start = "docker-compose.".length();
int end = name.length() - ".yml".length();
if (file.isFile() && name.startsWith("docker-compose.") && name.endsWith(".yml")
&& end > start) {
profiles.add(name.substring(start, end));
}
}
profiles.sort(String::compareTo);
return List.copyOf(profiles);
}
private static List<String> command(List<String> prefix, String... arguments) {
List<String> command = new ArrayList<>(prefix.size() + arguments.length);
command.addAll(prefix);
command.addAll(List.of(arguments));
return List.copyOf(command);
}
}
@@ -1,4 +1,4 @@
package dev.caskeleton.buildtools.config;
package dev.caskeleton.buildlogic.config;
import java.io.File;
import org.gradle.api.Plugin;
@@ -1,4 +1,4 @@
package dev.caskeleton.buildtools.config;
package dev.caskeleton.buildlogic.config;
import java.util.List;
@@ -1,4 +1,4 @@
package dev.caskeleton.buildtools.config;
package dev.caskeleton.buildlogic.config;
import java.io.File;
import java.io.IOException;
@@ -1,4 +1,4 @@
package dev.caskeleton.buildtools.config;
package dev.caskeleton.buildlogic.config;
import java.util.Objects;
import java.util.Optional;
@@ -1,4 +1,4 @@
package dev.caskeleton.buildtools.config;
package dev.caskeleton.buildlogic.config;
import java.io.File;
import java.util.Objects;
@@ -1,4 +1,4 @@
package dev.caskeleton.buildtools.config;
package dev.caskeleton.buildlogic.config;
import java.util.List;
import org.gradle.api.DefaultTask;
@@ -35,7 +35,14 @@ public final class JavaConventionsPlugin implements Plugin<Project> {
project.setGroup("dev.caskeleton");
ReleaseProvenanceExtension provenance =
project.getRootProject().getExtensions().findByType(ReleaseProvenanceExtension.class);
project.setVersion(provenance == null ? "0.0.1-SNAPSHOT" : provenance.getTraceableVersion());
// The release version alone, never the revision: a revision in the version put a new jar name in
// every leaf's build/libs on every commit, which is what the deleted archive-hygiene plugin
// existed to clean up (review BUILD-O3-5). The revision stays in each jar's manifest
// (Build-Revision) and in app-bootstrap's build-info.properties.
project.setVersion(
provenance == null
? "0.0.1-SNAPSHOT"
: provenance.getReleaseVersion() + (provenance.isComplete() ? "" : "-SNAPSHOT"));
String buildRevision = provenance == null ? "unknown" : provenance.getSourceRevision();
JavaPluginExtension javaExtension = project.getExtensions().getByType(JavaPluginExtension.class);
@@ -65,6 +72,18 @@ public final class JavaConventionsPlugin implements Plugin<Project> {
"Implementation-Version", project.getVersion().toString(),
"Build-Revision", buildRevision)));
// Both attributes change on every commit, and every test and SpotBugs task has this jar on its
// runtime classpath: without the normalization a CI build never reuses a cached test result
// (review O-4c). They describe the build, not the classes, so a runtime classpath ignores them.
project
.getNormalization()
.getRuntimeClasspath()
.metaInf(
metaInf -> {
metaInf.ignoreAttribute("Implementation-Version");
metaInf.ignoreAttribute("Build-Revision");
});
project
.getTasks()
.withType(JavaCompile.class)
@@ -1,9 +0,0 @@
package dev.caskeleton.buildlogic.publicpath;
import java.util.List;
public record PublicPathSnapshot(List<String> publicPaths, String canonicalText) {
public PublicPathSnapshot {
publicPaths = List.copyOf(publicPaths);
}
}
@@ -1,56 +0,0 @@
package dev.caskeleton.buildlogic.publicpath;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.provider.Provider;
public final class PublicPathSnapshotPlugin implements Plugin<Project> {
static final String APPROVAL_PROPERTY = "approvePublicPathChange";
@Override
public void apply(Project project) {
var source =
project
.getLayout()
.getProjectDirectory()
.file("app-bootstrap/src/main/resources/config/security.yml");
var snapshot =
project
.getLayout()
.getProjectDirectory()
.file("../docs/security/public-paths-snapshot.txt");
Provider<Boolean> approvalRequested =
project.getProviders().gradleProperty(APPROVAL_PROPERTY).map(ignored -> true).orElse(false);
project
.getTasks()
.register(
"verifyPublicPathSnapshot",
VerifyPublicPathSnapshotTask.class,
task -> {
task.setGroup("verification");
task.setDescription(
"Fails without mutation when the committed deny-by-default public path baseline drifts.");
task.getSecurityConfigFile().set(source);
task.getSnapshotFile().set(snapshot);
task.getApprovalRequested().convention(approvalRequested);
task.getTrackedFiles().from(source, snapshot);
});
project
.getTasks()
.register(
"updatePublicPathSnapshot",
UpdatePublicPathSnapshotTask.class,
task -> {
task.setGroup("build setup");
task.setDescription(
"Explicitly updates the committed public path baseline after security review.");
task.getSecurityConfigFile().set(source);
task.getSnapshotFile().set(snapshot);
task.getApproved().convention(approvalRequested);
task.getTrackedFiles().from(source);
task.getOutputs().upToDateWhen(ignored -> false);
});
}
}
@@ -1,89 +0,0 @@
package dev.caskeleton.buildlogic.publicpath;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class PublicPathSnapshotRenderer {
private static final Pattern BINDING_PATTERN =
Pattern.compile("^\\s*public-paths:\\s*(\\S.*?)\\s*$");
private static final Pattern DEFAULTED_PLACEHOLDER =
Pattern.compile("\\$\\{[A-Za-z0-9_.]+:([^{}]*)}");
private static final int MAX_PLACEHOLDER_DEPTH = 16;
private static final String HEADER =
"# feature-security-operational-baseline D5 — deny-by-default public path snapshot.\n"
+ "# SSOT: ca-skeleton.security.public-paths default in "
+ "app-bootstrap/src/main/resources/config/security.yml\n"
+ "# -> SecurityConfig permitAll(); anyRequest authenticated. An operator's own "
+ "SECURITY_PUBLIC_PATHS\n"
+ "# overrides it at run time and is outside this snapshot.\n"
+ "# Update only after review with: ./gradlew updatePublicPathSnapshot "
+ "-PapprovePublicPathChange\n";
private PublicPathSnapshotRenderer() {}
public static PublicPathSnapshot render(File securityConfigFile) {
if (!securityConfigFile.isFile()) {
throw new IllegalStateException(
"missing public-path security configuration " + securityConfigFile);
}
List<String> bindings = new ArrayList<>();
for (String line : readLines(securityConfigFile)) {
Matcher matcher = BINDING_PATTERN.matcher(line);
if (matcher.matches()) {
bindings.add(matcher.group(1));
}
}
if (bindings.size() != 1) {
throw new IllegalStateException(
"expected exactly one 'public-paths:' binding in "
+ securityConfigFile
+ ", found "
+ bindings.size()
+ " — the snapshot cannot say which surface it pins");
}
String raw = bindings.getFirst();
for (int guard = 0; guard < MAX_PLACEHOLDER_DEPTH; guard++) {
Matcher matcher = DEFAULTED_PLACEHOLDER.matcher(raw);
if (!matcher.find()) {
break;
}
raw = raw.substring(0, matcher.start()) + matcher.group(1) + raw.substring(matcher.end());
}
if (raw.contains("${")) {
throw new IllegalStateException(
"'public-paths' in "
+ securityConfigFile
+ " resolves to '"
+ raw
+ "', which still holds a placeholder with no default — the deployed public path "
+ "surface is not determined by the repository and cannot be snapshotted");
}
List<String> publicPaths =
Pattern.compile(",")
.splitAsStream(raw)
.map(String::trim)
.filter(value -> !value.isEmpty())
.sorted()
.toList();
String canonical = HEADER + (publicPaths.isEmpty() ? "" : String.join("\n", publicPaths) + "\n");
return new PublicPathSnapshot(publicPaths, canonical);
}
private static List<String> readLines(File file) {
try {
return Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
} catch (IOException exception) {
throw new UncheckedIOException("failed to read " + file, exception);
}
}
}
@@ -1,60 +0,0 @@
package dev.caskeleton.buildlogic.publicpath;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
public abstract class UpdatePublicPathSnapshotTask extends DefaultTask {
@Internal
public abstract RegularFileProperty getSecurityConfigFile();
@OutputFile
public abstract RegularFileProperty getSnapshotFile();
@Input
public abstract Property<Boolean> getApproved();
@InputFiles
public abstract ConfigurableFileCollection getTrackedFiles();
@TaskAction
public void updateSnapshot() {
if (!getApproved().get()) {
throw new GradleException(
"updatePublicPathSnapshot requires -PapprovePublicPathChange");
}
File source = getSecurityConfigFile().get().getAsFile();
PublicPathSnapshot rendered;
try {
rendered = PublicPathSnapshotRenderer.render(source);
} catch (IllegalStateException invalidSource) {
throw new GradleException("updatePublicPathSnapshot: " + invalidSource.getMessage(), invalidSource);
}
File snapshot = getSnapshotFile().get().getAsFile();
File parent = snapshot.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new GradleException(
"updatePublicPathSnapshot: failed to create " + parent);
}
try {
Files.writeString(snapshot.toPath(), rendered.canonicalText(), StandardCharsets.UTF_8);
} catch (IOException exception) {
throw new UncheckedIOException("failed to write " + snapshot, exception);
}
getLogger().lifecycle("updatePublicPathSnapshot: wrote reviewed baseline {}", snapshot);
}
}
@@ -1,74 +0,0 @@
package dev.caskeleton.buildlogic.publicpath;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.TaskAction;
public abstract class VerifyPublicPathSnapshotTask extends DefaultTask {
@Internal
public abstract RegularFileProperty getSecurityConfigFile();
@Internal
public abstract RegularFileProperty getSnapshotFile();
@Input
public abstract Property<Boolean> getApprovalRequested();
@InputFiles
public abstract ConfigurableFileCollection getTrackedFiles();
@TaskAction
public void verifySnapshot() {
if (getApprovalRequested().get()) {
throw new GradleException(
"verifyPublicPathSnapshot is read-only; use updatePublicPathSnapshot "
+ "-PapprovePublicPathChange for an intentional update.");
}
File source = getSecurityConfigFile().get().getAsFile();
File snapshot = getSnapshotFile().get().getAsFile();
PublicPathSnapshot rendered;
try {
rendered = PublicPathSnapshotRenderer.render(source);
} catch (IllegalStateException invalidSource) {
throw new GradleException("verifyPublicPathSnapshot: " + invalidSource.getMessage(), invalidSource);
}
if (!snapshot.isFile()) {
throw new GradleException(
"verifyPublicPathSnapshot: missing committed baseline " + snapshot);
}
String existing = read(snapshot);
if (!existing.equals(rendered.canonicalText())) {
throw new GradleException(
"verifyPublicPathSnapshot: the deny-by-default public path surface changed.\n"
+ " expected (snapshot):\n"
+ existing
+ "\n"
+ " actual (security.yml public-paths default):\n"
+ rendered.canonicalText()
+ "\nA protected endpoint may now be public. Review the change, then run:\n"
+ " ./gradlew updatePublicPathSnapshot -PapprovePublicPathChange");
}
getLogger().lifecycle("verifyPublicPathSnapshot: OK — committed public paths are unchanged.");
}
private static String read(File file) {
try {
return Files.readString(file.toPath(), StandardCharsets.UTF_8);
} catch (IOException exception) {
throw new UncheckedIOException("failed to read " + file, exception);
}
}
}
@@ -59,6 +59,14 @@ public final class RedisTopologyLanePlugin implements Plugin<Project> {
"redisTopologyTest",
lane -> {
lane.integration();
if ("unset".equals(declaredMode)) {
// The lane needs a running topology from infra/redis-sdk and its coordinates; without
// them it can only fail, so the repository's integrationCheck leaves it out and says
// so rather than failing on an input it was never given (review NEW-16).
lane.explicitOnly(
"it needs -Predis.topology.mode=<standalone|sentinel|cluster|tls> and the topology"
+ " coordinates from infra/redis-sdk (redis-sdk-topology.yml passes them)");
}
lane.setTag("redis-topology & lane-" + declaredMode);
lane.setDescription(
"Runs this leaf's Redis contracts against a real topology declared in infra/redis-sdk.");
@@ -67,6 +67,32 @@ public final class StrictTestLanePlugin implements Plugin<Project> {
project.afterEvaluate(
ignored -> lanes.forEach(lane -> validateLane(project, lane)));
lanes.all(
lane ->
project.afterEvaluate(
ignored -> {
if (!lane.isMainStage()) {
return;
}
String tag = lane.getTag();
if (tag == null || tag.isBlank()) {
throw new GradleException(
"strict test lane '"
+ lane.getName()
+ "' in "
+ ownerPath
+ " is a main-stage lane without a tag; the tag is what keeps its tests out of `test`.");
}
project
.getTasks()
.named("test", Test.class)
.configure(test -> test.useJUnitPlatform(options -> options.excludeTags(tag)));
project
.getTasks()
.matching(task -> task.getName().equals("mainCheck"))
.configureEach(task -> task.dependsOn(lane.getName()));
}));
registerAggregate(
project,
extension,
@@ -122,9 +148,30 @@ public final class StrictTestLanePlugin implements Plugin<Project> {
project.provider(
() ->
extension.getLanes().stream()
.filter(lane -> lane.getExplicitOnlyReason() == null)
.filter(selection)
.map(lane -> project.getTasks().named(lane.getName()))
.toList()));
// An explicit-only lane is left out, and the aggregate says so when it runs, so a
// green aggregate is never read as covering it.
var leftOut =
project.provider(
() ->
extension.getLanes().stream()
.filter(lane -> lane.getExplicitOnlyReason() != null)
.filter(selection)
.map(
lane ->
"strict test lane '"
+ lane.getName()
+ "' in "
+ project.getPath()
+ " runs only when named: "
+ lane.getExplicitOnlyReason()
+ ".")
.toList());
task.doLast(
running -> leftOut.get().forEach(note -> running.getLogger().lifecycle(note)));
});
}
@@ -18,6 +18,8 @@ public class StrictTestLaneSpec implements Named {
private String sourceSet = "test";
private String maxHeapSize;
private boolean rejectSkipped;
private boolean mainStage;
private String explicitOnlyReason;
private TestLaneCategory category = TestLaneCategory.TEST;
private final List<String> requiredTests = new ArrayList<>();
private final List<String> jvmArgs = new ArrayList<>();
@@ -84,6 +86,33 @@ public class StrictTestLaneSpec implements Named {
this.rejectSkipped = rejectSkipped;
}
public boolean isMainStage() {
return mainStage;
}
/**
* Runs this lane in the leaf's {@code mainCheck} instead of its {@code test}: the lane's tag is
* excluded from {@code test}. For checks that compare a leaf with documents or registries, which
* are not worth a pull request's wait (review 2026-09-24 BUILD-계획-B4-27).
*/
public void mainStage() {
mainStage = true;
}
public String getExplicitOnlyReason() {
return explicitOnlyReason;
}
/**
* Keeps this lane out of every aggregate ({@code strictTestLaneCheck}, {@code
* integrationTestLaneCheck}, ...): it runs only when named. For a lane that cannot pass without
* an input the aggregate's caller does not have — protected credentials, an external topology —
* so that the aggregate states the gap instead of failing on it (review NEW-16).
*/
public void explicitOnly(String reason) {
explicitOnlyReason = Objects.requireNonNull(reason, "reason");
}
public TestLaneCategory getCategory() {
return category;
}
@@ -1,265 +0,0 @@
package dev.caskeleton.bootstrap.contract;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
final class BuildVerificationPurityContractTest {
/**
* What the renderer produces for the fixture's {@code security.yml}.
*
* <p>These five tests were red on main. The snapshot's input moved from {@code src/.env} to the
* committed {@code app-bootstrap/src/main/resources/config/security.yml} — because {@code
* src/.env*} is gitignored, so the old gate took its expected value from a file no CI checkout
* has — but the fixture below kept writing a {@code .env}, and this constant kept the header and
* the paths that file used to produce. The script was right and its test was describing the
* previous contract.
*/
private static final String CANONICAL_PUBLIC_PATH_SNAPSHOT =
"""
# feature-security-operational-baseline D5 — deny-by-default public path snapshot.
# SSOT: ca-skeleton.security.public-paths default in app-bootstrap/src/main/resources/config/security.yml
# -> SecurityConfig permitAll(); anyRequest authenticated. An operator's own SECURITY_PUBLIC_PATHS
# overrides it at run time and is outside this snapshot.
# Update only after review with: ./gradlew updatePublicPathSnapshot -PapprovePublicPathChange
/v1/healthcheck
""";
@Test
void jarTaskLeavesStaleTraceableArchivesUntouched(@TempDir Path temporaryDirectory)
throws IOException {
ArchiveFixture fixture = archiveFixture(temporaryDirectory);
run(fixture.projectDirectory(), ":family:module:jar");
assertThat(fixture.staleArchive()).exists().hasContent("stale");
assertThat(fixture.currentArchive()).exists();
assertThat(fixture.nonmatchingArchive()).exists().hasContent("local");
}
@Test
void staleArchiveVerificationFailsWithoutDeleting(@TempDir Path temporaryDirectory)
throws IOException {
ArchiveFixture fixture = archiveFixture(temporaryDirectory);
BuildResult result =
runAndFail(fixture.projectDirectory(), ":family:module:jar", "verifyNoStaleTraceableJars");
assertThat(result.getOutput())
.contains("verifyNoStaleTraceableJars")
.contains(":family:module:jar")
.contains(fixture.staleArchive().getFileName().toString());
assertThat(fixture.staleArchive()).exists().hasContent("stale");
assertThat(fixture.currentArchive()).exists();
assertThat(fixture.nonmatchingArchive()).exists().hasContent("local");
}
@Test
void explicitStaleArchiveCleanupDeletesOnlyStaleArchive(@TempDir Path temporaryDirectory)
throws IOException {
ArchiveFixture fixture = archiveFixture(temporaryDirectory);
BuildResult result =
run(fixture.projectDirectory(), ":family:module:jar", "cleanStaleTraceableJars");
assertThat(result.getOutput()).contains("deleted 1 stale archive(s)");
assertThat(fixture.staleArchive()).doesNotExist();
assertThat(fixture.currentArchive()).exists();
assertThat(fixture.nonmatchingArchive()).exists().hasContent("local");
}
@Test
void missingPublicPathConfigurationFailsWithoutCreatingSnapshot(@TempDir Path temporaryDirectory)
throws IOException {
PublicPathFixture fixture = publicPathFixture(temporaryDirectory);
Files.delete(fixture.securityConfiguration());
BuildResult result = runAndFail(fixture.projectDirectory(), "verifyPublicPathSnapshot");
assertThat(result.getOutput()).contains("missing public-path security configuration");
assertThat(fixture.snapshot()).doesNotExist();
}
@Test
void missingPublicPathSnapshotFailsWithoutCreatingIt(@TempDir Path temporaryDirectory)
throws IOException {
PublicPathFixture fixture = publicPathFixture(temporaryDirectory);
BuildResult result = runAndFail(fixture.projectDirectory(), "verifyPublicPathSnapshot");
assertThat(result.getOutput()).contains("missing committed baseline");
assertThat(fixture.snapshot()).doesNotExist();
}
@Test
void driftedPublicPathSnapshotFailsWithoutChangingBytes(@TempDir Path temporaryDirectory)
throws IOException {
PublicPathFixture fixture = publicPathFixture(temporaryDirectory);
Files.createDirectories(fixture.snapshot().getParent());
Files.writeString(fixture.snapshot(), "reviewed-old-baseline\n", UTF_8);
byte[] before = Files.readAllBytes(fixture.snapshot());
BuildResult result = runAndFail(fixture.projectDirectory(), "verifyPublicPathSnapshot");
assertThat(result.getOutput()).contains("public path surface changed");
assertThat(Files.readAllBytes(fixture.snapshot())).containsExactly(before);
}
@Test
void verifierRejectsUpdateApprovalWithoutChangingSnapshot(@TempDir Path temporaryDirectory)
throws IOException {
PublicPathFixture fixture = publicPathFixture(temporaryDirectory);
Files.createDirectories(fixture.snapshot().getParent());
Files.writeString(fixture.snapshot(), "reviewed-old-baseline\n", UTF_8);
byte[] before = Files.readAllBytes(fixture.snapshot());
BuildResult result =
runAndFail(
fixture.projectDirectory(), "verifyPublicPathSnapshot", "-PapprovePublicPathChange");
assertThat(result.getOutput()).contains("updatePublicPathSnapshot");
assertThat(Files.readAllBytes(fixture.snapshot())).containsExactly(before);
}
@Test
void updaterRequiresExplicitApproval(@TempDir Path temporaryDirectory) throws IOException {
PublicPathFixture fixture = publicPathFixture(temporaryDirectory);
BuildResult result = runAndFail(fixture.projectDirectory(), "updatePublicPathSnapshot");
assertThat(result.getOutput()).contains("requires -PapprovePublicPathChange");
assertThat(fixture.snapshot()).doesNotExist();
}
@Test
void approvedUpdaterWritesCanonicalSnapshot(@TempDir Path temporaryDirectory) throws IOException {
PublicPathFixture fixture = publicPathFixture(temporaryDirectory);
run(fixture.projectDirectory(), "updatePublicPathSnapshot", "-PapprovePublicPathChange");
assertThat(fixture.snapshot()).hasContent(CANONICAL_PUBLIC_PATH_SNAPSHOT);
run(fixture.projectDirectory(), "verifyPublicPathSnapshot");
assertThat(fixture.snapshot()).hasContent(CANONICAL_PUBLIC_PATH_SNAPSHOT);
}
@Test
void unapprovedUpdaterPreservesExistingSnapshot(@TempDir Path temporaryDirectory)
throws IOException {
PublicPathFixture fixture = publicPathFixture(temporaryDirectory);
Files.createDirectories(fixture.snapshot().getParent());
Files.writeString(fixture.snapshot(), "reviewed-old-baseline\n", UTF_8);
byte[] before = Files.readAllBytes(fixture.snapshot());
BuildResult result = runAndFail(fixture.projectDirectory(), "updatePublicPathSnapshot");
assertThat(result.getOutput()).contains("requires -PapprovePublicPathChange");
assertThat(Files.readAllBytes(fixture.snapshot())).containsExactly(before);
}
@Test
void approvedUpdaterReplacesDriftedSnapshot(@TempDir Path temporaryDirectory) throws IOException {
PublicPathFixture fixture = publicPathFixture(temporaryDirectory);
Files.createDirectories(fixture.snapshot().getParent());
Files.writeString(fixture.snapshot(), "reviewed-old-baseline\n", UTF_8);
run(fixture.projectDirectory(), "updatePublicPathSnapshot", "-PapprovePublicPathChange");
assertThat(fixture.snapshot()).hasContent(CANONICAL_PUBLIC_PATH_SNAPSHOT);
}
private static ArchiveFixture archiveFixture(Path temporaryDirectory) throws IOException {
Path projectDirectory = temporaryDirectory.resolve("archive-fixture");
Path moduleDirectory = projectDirectory.resolve("family/module");
Files.createDirectories(moduleDirectory.resolve("src/main/java/example"));
Files.writeString(
projectDirectory.resolve("settings.gradle"), "include 'family:module'\n", UTF_8);
Files.writeString(
projectDirectory.resolve("build.gradle"),
"""
plugins {
id 'base'
id 'ca.archive-hygiene'
}
allprojects { version = '1.0.0+abcdef1' }
project(':family:module') { apply plugin: 'java' }
""",
UTF_8);
Files.writeString(
moduleDirectory.resolve("src/main/java/example/Sample.java"),
"package example; public final class Sample {}\n",
UTF_8);
Path archiveDirectory = moduleDirectory.resolve("build/libs");
Files.createDirectories(archiveDirectory);
Path staleArchive = archiveDirectory.resolve("module-1.0.0+1234567.jar");
Files.writeString(staleArchive, "stale", UTF_8);
Path currentArchive = archiveDirectory.resolve("module-1.0.0+abcdef1.jar");
Path nonmatchingArchive = archiveDirectory.resolve("module-local.jar");
Files.writeString(nonmatchingArchive, "local", UTF_8);
return new ArchiveFixture(projectDirectory, staleArchive, currentArchive, nonmatchingArchive);
}
private static PublicPathFixture publicPathFixture(Path temporaryDirectory) throws IOException {
Path repositoryDirectory = temporaryDirectory.resolve("public-path-fixture");
Path projectDirectory = repositoryDirectory.resolve("src");
Files.createDirectories(projectDirectory);
Files.writeString(
projectDirectory.resolve("settings.gradle"), "rootProject.name='fixture'\n", UTF_8);
Files.writeString(
projectDirectory.resolve("build.gradle"),
"plugins { id 'ca.public-path-snapshot' }\n",
UTF_8);
// The committed binding default, spelled exactly as the real file spells it — nested Spring
// placeholders and all, because unwinding them to `/v1/healthcheck` is what the renderer does
// and therefore what these tests are about.
Path securityConfig =
projectDirectory.resolve("app-bootstrap/src/main/resources/config/security.yml");
Files.createDirectories(securityConfig.getParent());
Files.writeString(
securityConfig,
"""
ca-skeleton:
security:
public-paths: ${SECURITY_PUBLIC_PATHS:${PRESENTATION_API_BASE_PATH:/v1}/healthcheck}
""",
UTF_8);
return new PublicPathFixture(
projectDirectory,
securityConfig,
repositoryDirectory.resolve("docs/security/public-paths-snapshot.txt"));
}
private static BuildResult run(Path projectDirectory, String... arguments) {
return runner(projectDirectory, arguments).build();
}
private static BuildResult runAndFail(Path projectDirectory, String... arguments) {
return runner(projectDirectory, arguments).buildAndFail();
}
private static GradleRunner runner(Path projectDirectory, String... arguments) {
String[] fullArguments = new String[arguments.length + 2];
fullArguments[0] = "--console=plain";
fullArguments[1] = "--stacktrace";
System.arraycopy(arguments, 0, fullArguments, 2, arguments.length);
return GradleRunner.create()
.withProjectDir(projectDirectory.toFile())
.withPluginClasspath()
.withArguments(fullArguments);
}
private record ArchiveFixture(
Path projectDirectory, Path staleArchive, Path currentArchive, Path nonmatchingArchive) {}
private record PublicPathFixture(
Path projectDirectory, Path securityConfiguration, Path snapshot) {}
}
@@ -98,6 +98,81 @@ class ApiSurfaceConventionTest {
assertFalse(result.getOutput().contains("ApiSurface"), result.getOutput());
}
@Test
void theLeafCheckRunsTheSurfaceVerification() throws Exception {
// given
runner("updateFixtureApiSurface", "-PapproveFixtureApiSurfaceChange").build();
// when
BuildResult result = runner("check", "--dry-run").build();
// then
assertTrue(result.getOutput().contains(":verifyFixtureApiSurface"), result.getOutput());
}
@Test
void anAdopterImportOutsideTheAdopterBaselineFailsTheVerification() throws Exception {
// given
runner("updateFixtureApiSurface", "-PapproveFixtureApiSurfaceChange").build();
writeAdopter("package consumer;\nimport app.Visible;\npublic final class Consumer {}\n");
Files.writeString(projectDir.resolve("adopters.txt"), "# reviewed adopter surface\n");
// when
BuildResult result = runner("verifyFixtureApiSurface").buildAndFail();
// then
assertTrue(result.getOutput().contains("Consumer.java: app.Visible"), result.getOutput());
}
@Test
void anAdopterImportTheAdopterBaselineListsPasses() throws Exception {
// given
runner("updateFixtureApiSurface", "-PapproveFixtureApiSurfaceChange").build();
writeAdopter("package consumer;\nimport app.Visible;\npublic final class Consumer {}\n");
Files.writeString(projectDir.resolve("adopters.txt"), "app.Visible\n");
// when
BuildResult result = runner("verifyFixtureApiSurface").build();
// then
assertTrue(result.getOutput().contains("OK"), result.getOutput());
}
@Test
void anAdopterBaselineEntryTheSurfaceNoLongerHasFailsTheVerification() throws Exception {
// given
runner("updateFixtureApiSurface", "-PapproveFixtureApiSurfaceChange").build();
writeAdopter("package consumer;\npublic final class Consumer {}\n");
Files.writeString(projectDir.resolve("adopters.txt"), "app.Gone\n");
// when
BuildResult result = runner("verifyFixtureApiSurface").buildAndFail();
// then
assertTrue(result.getOutput().contains("app.Gone"), result.getOutput());
}
private void writeAdopter(String source) throws Exception {
Path adopter = projectDir.resolve("adopter/src/consumer");
Files.createDirectories(adopter);
Files.writeString(adopter.resolve("Consumer.java"), source);
Files.writeString(
projectDir.resolve("build.gradle"),
"""
plugins {
id 'java'
id 'ca.api-surface'
}
apiSurface {
label = 'Fixture'
baseline = file('surface.txt')
description = 'The fixture leaf public surface.'
adopterBaseline = file('adopters.txt')
adopterSources = fileTree('adopter/src') { include '**/*.java' }
}
""");
}
private void writeConfiguredBuild(String sourceRoot) throws Exception {
Files.writeString(
projectDir.resolve("build.gradle"),
@@ -1,46 +0,0 @@
package dev.caskeleton.buildlogic.archive;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class ArchiveHygienePolicyTest {
@Test
void findsOnlyOldTraceableArchivesForTheSameJar(@TempDir Path temp) throws Exception {
Files.writeString(temp.resolve("module-1.0.0+1234567.jar"), "stale");
Files.writeString(temp.resolve("module-1.0.0+abcdef1.jar"), "current");
Files.writeString(temp.resolve("module-local.jar"), "local");
Files.writeString(temp.resolve("other-1.0.0+1234567.jar"), "other");
ArchiveTarget target =
new ArchiveTarget(
":module:jar", temp.toFile(), "module", "", "module-1.0.0+abcdef1.jar");
assertThat(ArchiveHygienePolicy.staleArchives(target))
.extracting(file -> file.getName())
.containsExactly("module-1.0.0+1234567.jar");
}
@Test
void classifierIsPartOfTraceableArchiveIdentity(@TempDir Path temp) throws Exception {
Files.writeString(temp.resolve("module-1.0.0+1234567-sources.jar"), "stale");
Files.writeString(temp.resolve("module-1.0.0+abcdef1-sources.jar"), "current");
Files.writeString(temp.resolve("module-1.0.0+1234567.jar"), "main");
ArchiveTarget target =
new ArchiveTarget(
":module:sourcesJar",
temp.toFile(),
"module",
"sources",
"module-1.0.0+abcdef1-sources.jar");
assertThat(ArchiveHygienePolicy.staleArchives(target))
.extracting(file -> file.getName())
.containsExactly("module-1.0.0+1234567-sources.jar");
}
}
@@ -1,143 +0,0 @@
package dev.caskeleton.buildlogic.bootstrap;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
final class DeveloperBootstrapPluginFunctionalTest {
@Test
void registersTheFourStageBootstrapLifecycle(@TempDir Path temporaryDirectory) throws IOException {
Path projectDirectory = fixture(temporaryDirectory);
BuildResult result = run(projectDirectory, "tasks", "--group=developer experience");
assertThat(result.getOutput())
.contains("bootstrapCompile")
.contains("bootstrapDockerPreflight")
.contains("bootstrapDependencies")
.contains("bootstrapMigrateAndStart")
.contains("bootstrapSmoke")
.contains("bootstrap - Runs the complete four-stage bootstrap contract for the local")
.contains("-PbootstrapProfile=<name>");
}
@Test
void theEnvironmentIsSelectableAndTheDefaultIsLocal(@TempDir Path temporaryDirectory)
throws IOException {
Path projectDirectory = fixture(temporaryDirectory);
BuildResult devRun =
run(projectDirectory, "tasks", "--group=developer experience", "-PbootstrapProfile=dev");
assertThat(devRun.getOutput())
.contains("bootstrap contract for the dev")
.contains("starts the dev PostgreSQL dependency");
}
@Test
void aProfileWithNoOverlayIsRefusedAndTheMessageListsTheRealOnes(
@TempDir Path temporaryDirectory) throws IOException {
// The failure a developer is most likely to hit is a typo, and the answer they need is which
// names exist — read off the directory rather than from a list somebody has to maintain.
Path projectDirectory = fixture(temporaryDirectory);
BuildResult failure =
runAndFail(projectDirectory, "bootstrapDockerPreflight", "-PbootstrapProfile=staging");
assertThat(failure.getOutput())
.contains("names no overlay")
.contains("docker-compose.staging.yml")
.contains("[dev, local]");
}
@Test
void configurationDoesNotRequireComposeFiles(@TempDir Path temporaryDirectory)
throws IOException {
// The Docker image build copies only src/ into its context, so the repository root and its
// compose files do not exist there. Configuring the root project must still succeed; only the
// bootstrap tasks themselves need an overlay.
Path projectDirectory = fixtureWithoutComposeFiles(temporaryDirectory);
BuildResult result = run(projectDirectory, "help");
assertThat(result.getOutput()).contains("BUILD SUCCESSFUL");
}
@Test
void bootstrapTaskKeepsTheRequiredStageOrder(@TempDir Path temporaryDirectory) throws IOException {
Path projectDirectory = fixture(temporaryDirectory);
BuildResult result = run(projectDirectory, "bootstrap", "--dry-run");
String output = result.getOutput();
assertThat(output.indexOf(":bootstrapCompile SKIPPED")).isLessThan(output.indexOf(":bootstrapDockerPreflight SKIPPED"));
assertThat(output.indexOf(":bootstrapDockerPreflight SKIPPED")).isLessThan(output.indexOf(":bootstrapDependencies SKIPPED"));
assertThat(output.indexOf(":bootstrapDependencies SKIPPED")).isLessThan(output.indexOf(":bootstrapMigrateAndStart SKIPPED"));
assertThat(output.indexOf(":bootstrapMigrateAndStart SKIPPED")).isLessThan(output.indexOf(":bootstrapSmoke SKIPPED"));
assertThat(output.indexOf(":bootstrapSmoke SKIPPED")).isLessThan(output.indexOf(":bootstrap SKIPPED"));
}
private static Path fixture(Path temporaryDirectory) throws IOException {
Path projectDirectory = fixtureWithoutComposeFiles(temporaryDirectory);
Path repositoryRoot = projectDirectory.getParent();
// The bootstrap merges an overlay onto the base compose file and refuses a profile that names
// none, so the fixture has to carry the two the repository carries.
Files.writeString(repositoryRoot.resolve("docker-compose.yml"), "services: {}\n", UTF_8);
Files.writeString(repositoryRoot.resolve("docker-compose.local.yml"), "services: {}\n", UTF_8);
Files.writeString(repositoryRoot.resolve("docker-compose.dev.yml"), "services: {}\n", UTF_8);
return projectDirectory;
}
private static Path fixtureWithoutComposeFiles(Path temporaryDirectory) throws IOException {
Path repositoryRoot = temporaryDirectory.resolve("repository");
Path projectDirectory = repositoryRoot.resolve("src");
Files.createDirectories(projectDirectory.resolve("app-bootstrap"));
Files.writeString(
projectDirectory.resolve("settings.gradle"),
"rootProject.name='fixture'\ninclude 'app-bootstrap'\n",
UTF_8);
Files.writeString(
projectDirectory.resolve("build.gradle"),
"plugins { id 'ca.developer-bootstrap' }\n",
UTF_8);
Files.writeString(
projectDirectory.resolve("app-bootstrap/build.gradle"),
"plugins { id 'java' }\n",
UTF_8);
return projectDirectory;
}
private static BuildResult runAndFail(Path projectDirectory, String... arguments) {
return GradleRunner.create()
.withProjectDir(projectDirectory.toFile())
.withPluginClasspath()
.withArguments(withConsole(arguments))
.buildAndFail();
}
private static String[] withConsole(String... arguments) {
String[] fullArguments = new String[arguments.length + 1];
fullArguments[0] = "--console=plain";
System.arraycopy(arguments, 0, fullArguments, 1, arguments.length);
return fullArguments;
}
private static BuildResult run(Path projectDirectory, String... arguments) {
String[] fullArguments = new String[arguments.length + 1];
fullArguments[0] = "--console=plain";
System.arraycopy(arguments, 0, fullArguments, 1, arguments.length);
return GradleRunner.create()
.withProjectDir(projectDirectory.toFile())
.withPluginClasspath()
.withArguments(fullArguments)
.build();
}
}
@@ -1,4 +1,4 @@
package dev.caskeleton.buildtools.config;
package dev.caskeleton.buildlogic.config;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -1,4 +1,4 @@
package dev.caskeleton.buildtools.config;
package dev.caskeleton.buildlogic.config;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -1,37 +0,0 @@
package dev.caskeleton.buildlogic.publicpath;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class PublicPathSnapshotRendererTest {
@Test
void resolvesNestedSpringDefaultsAndSortsPaths(@TempDir Path temp) throws Exception {
Path security = temp.resolve("security.yml");
Files.writeString(
security,
"ca-skeleton:\n security:\n public-paths: ${SECURITY_PUBLIC_PATHS:${PRESENTATION_API_BASE_PATH:/v1}/healthcheck,/actuator/info}\n");
PublicPathSnapshot rendered = PublicPathSnapshotRenderer.render(security.toFile());
assertThat(rendered.publicPaths()).containsExactly("/actuator/info", "/v1/healthcheck");
assertThat(rendered.canonicalText())
.contains("# feature-security-operational-baseline D5")
.endsWith("/actuator/info\n/v1/healthcheck\n");
}
@Test
void unresolvedPlaceholderFailsClosed(@TempDir Path temp) throws Exception {
Path security = temp.resolve("security.yml");
Files.writeString(security, "public-paths: ${SECURITY_PUBLIC_PATHS}\n");
assertThatThrownBy(() -> PublicPathSnapshotRenderer.render(security.toFile()))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("still holds a placeholder with no default");
}
}
@@ -56,6 +56,38 @@ class RedisTopologyLanePluginFunctionalTest {
}
@Test
void withoutADeclaredModeTheLaneStaysOutOfTheIntegrationAggregate() {
// given
String[] arguments = {"integrationTestLaneCheck", "--console=plain"};
// when
BuildResult result = runner(arguments).build();
// then
assertTrue(!result.getOutput().contains("> Task :redisTopologyTest"), result.getOutput());
assertTrue(
result.getOutput().contains("'redisTopologyTest' in : runs only when named"),
result.getOutput());
}
@Test
void aDeclaredModePutsTheLaneInTheIntegrationAggregate() throws Exception {
// given
Path testSource = projectDir.resolve("src/test/java");
Files.createDirectories(testSource);
Files.writeString(testSource.resolve("FixtureTest.java"), "class FixtureTest {}\n");
String[] arguments = {
"integrationTestLaneCheck", "-Predis.topology.mode=standalone", "--dry-run", "--console=plain"
};
// when
BuildResult result = runner(arguments).build();
// then
assertTrue(result.getOutput().contains(":redisTopologyTest"), result.getOutput());
}
private GradleRunner runner(String... arguments) {
return GradleRunner.create()
.withProjectDir(projectDir.toFile())
@@ -385,6 +385,79 @@ class StrictTestLaneConventionTest {
assertTrue(result.getOutput().contains("performanceLane"), result.getOutput());
}
@Test
void aMainStageLaneLeavesTheLeafTestTaskAndJoinsMainCheck() throws Exception {
// given
buildFile(
junitDependencies()
+ """
tasks.register('mainCheck')
strictTestLanes {
lane('documentContractTest') {
tag = 'document-contract'
description = 'Compares the leaf with its documents.'
rejectSkipped = true
mainStage()
}
}
""");
writeTest(
"DocumentTest.java",
"""
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
class DocumentTest {
@Test @Tag("document-contract") void comparesDocuments() {
throw new AssertionError("document lane test ran in the pull-request test task");
}
@Test void ordinary() {}
}
""");
// when
BuildResult test = runner("test").build();
BuildResult mainCheck = runner("mainCheck", "--dry-run").build();
// then
assertTrue(test.getOutput().contains("BUILD SUCCESSFUL"), test.getOutput());
assertTrue(mainCheck.getOutput().contains(":documentContractTest"), mainCheck.getOutput());
}
@Test
void anExplicitOnlyLaneStaysOutOfEveryAggregate() throws Exception {
// given
buildFile(
"""
sourceSets { integration }
strictTestLanes {
lane('credentialLane') {
sourceSet = 'integration'
description = 'Needs protected credentials.'
integration()
explicitOnly 'the protected credentials are not set'
}
}
tasks.register('reportAggregates') {
doLast {
['strictTestLaneCheck', 'integrationTestLaneCheck'].each { name ->
def aggregate = tasks.named(name).get()
logger.lifecycle(name + '=' + aggregate.taskDependencies.getDependencies(aggregate)*.name.sort())
}
}
}
""");
// when
BuildResult result =
runner("reportAggregates", "integrationTestLaneCheck", "--console=plain").build();
// then
assertTrue(result.getOutput().contains("strictTestLaneCheck=[]"), result.getOutput());
assertTrue(result.getOutput().contains("integrationTestLaneCheck=[]"), result.getOutput());
assertTrue(
result.getOutput().contains("the protected credentials are not set"), result.getOutput());
}
private void buildFile(String laneBlock) throws Exception {
Files.writeString(
projectDir.resolve("build.gradle"),
-39
View File
@@ -1,39 +0,0 @@
plugins {
id 'java-gradle-plugin'
}
// Repository verification tooling lives here, physically separate from compilation conventions.
// Precompiled plugins in this build should stay thin: task wiring here, verification algorithms in normal classes.
// Locked like build-logic and every leaf (gradle.lockfile beside this file). Regenerate with
// `./gradlew -p build-tools dependencies --write-locks` after a catalog version change.
dependencyLocking {
lockAllConfigurations()
lockMode = LockMode.STRICT
}
dependencies {
implementation libs.jackson3.databind
testImplementation libs.junit.jupiter
testRuntimeOnly libs.junit.platform.launcher
}
gradlePlugin {
plugins {
jpaEvidence {
id = 'ca.jpa-evidence'
implementationClass = 'dev.caskeleton.buildtools.jpa.JpaEvidencePlugin'
}
configContract {
id = 'ca.config-contract'
implementationClass = 'dev.caskeleton.buildtools.config.ConfigContractPlugin'
}
jpaQualification {
id = 'ca.jpa-qualification'
implementationClass = 'dev.caskeleton.buildtools.jpa.JpaQualificationPlugin'
}
}
}
tasks.named('test') { useJUnitPlatform() }
-18
View File
@@ -1,18 +0,0 @@
# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
com.fasterxml.jackson.core:jackson-annotations:2.20=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
org.junit.jupiter:junit-jupiter-api:5.11.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:5.11.3=testRuntimeClasspath
org.junit.jupiter:junit-jupiter-params:5.11.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter:5.11.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:1.11.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-engine:1.11.3=testRuntimeClasspath
org.junit.platform:junit-platform-launcher:1.11.3=testRuntimeClasspath
org.junit:junit-bom:5.11.3=testCompileClasspath,testRuntimeClasspath
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-core:3.0.2=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-databind:3.0.2=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
tools.jackson:jackson-bom:3.0.2=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
empty=annotationProcessor,testAnnotationProcessor
-4
View File
@@ -1,4 +0,0 @@
# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
empty=incomingCatalogForLibs0
-14
View File
@@ -1,14 +0,0 @@
dependencyResolutionManagement {
versionCatalogs {
libs {
from(files('../gradle/libs.versions.toml'))
}
}
repositories {
mavenCentral()
gradlePluginPortal()
}
}
rootProject.name = 'build-tools'
@@ -1,372 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.inject.Inject;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.file.FileSystemOperations;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.MapProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.OutputDirectory;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.services.ServiceReference;
import org.gradle.process.ExecOperations;
import org.gradle.process.ExecResult;
import org.gradle.work.DisableCachingByDefault;
@DisableCachingByDefault(because = "Evidence contains execution state and a generation timestamp")
public abstract class GenerateJpaEvidenceManifestsTask extends DefaultTask {
private final ExecOperations execOperations;
private final FileSystemOperations fileSystemOperations;
@Inject
public GenerateJpaEvidenceManifestsTask(
ExecOperations execOperations, FileSystemOperations fileSystemOperations) {
this.execOperations = execOperations;
this.fileSystemOperations = fileSystemOperations;
}
@InputFile
public abstract RegularFileProperty getRegistryFile();
@OutputDirectory
public abstract DirectoryProperty getEvidenceOutputDirectory();
@Input
public abstract Property<String> getPostgreSqlImage();
@Input
public abstract Property<String> getEvidenceProfile();
@Input
public abstract Property<String> getCiJob();
@Input
public abstract Property<String> getArtifactLocation();
@Input
public abstract Property<String> getTopology();
@Input
public abstract Property<String> getSourceRevision();
@Input
public abstract Property<String> getTraceableVersion();
@Input
public abstract Property<String> getPgjdbcVersion();
@Input
public abstract Property<String> getHibernateVersion();
@Input
public abstract Property<String> getFlywayVersion();
@Input
public abstract Property<String> getRepositoryRootPath();
@Input
public abstract MapProperty<String, String> getJUnitResultDirectories();
@ServiceReference("jpaEvidenceExecution")
public abstract Property<JpaEvidenceExecutionService> getExecutionService();
@TaskAction
public void generate() {
JpaReadinessRegistry registry =
JpaEvidenceTaskSupport.loadRegistry(getRegistryFile().get().getAsFile());
List<JpaReadinessCard> activeCards = registry.activeCards();
String profile = getEvidenceProfile().get();
if (!profile.equals("candidate") && !profile.equals("r2")) {
throw new GradleException(
"jpaEvidenceProfile must be candidate or r2; got '" + profile + "'");
}
String ciJob = getCiJob().get();
String configuredArtifactLocation = getArtifactLocation().get();
String topology = getTopology().get();
String worktreeStatus =
runCommand(
List.of("git", "status", "--porcelain=v1", "--untracked-files=all"), true);
boolean worktreeDirty = !worktreeStatus.isBlank();
String worktreeStatusDigest = JpaEvidenceVerifier.sha256(worktreeStatus);
String image = getPostgreSqlImage().get();
String imageDigest =
runCommand(
List.of(
"docker", "image", "inspect", "--format={{index .RepoDigests 0}}", image),
false);
JpaDependencyVersions dependencyVersions =
new JpaDependencyVersions(
getPgjdbcVersion().get(), getHibernateVersion().get(), getFlywayVersion().get());
JpaEvidenceTestResultLocator testResultsByTask =
new JpaEvidenceTestResultLocator(
java.nio.file.Path.of(getRepositoryRootPath().get()), getJUnitResultDirectories().get());
JpaEvidenceExecutionService executionService = getExecutionService().get();
List<String> productionMetadataBlockers = new ArrayList<>();
if (profile.equals("r2")) {
if (worktreeDirty) {
productionMetadataBlockers.add("worktree-is-dirty");
}
if (ciJob.isBlank()) {
productionMetadataBlockers.add("missing-JPA_EVIDENCE_CI_JOB");
}
if (configuredArtifactLocation.isBlank()) {
productionMetadataBlockers.add("missing-JPA_EVIDENCE_ARTIFACT_LOCATION");
} else if (!configuredArtifactLocation.matches("(?i)(https|s3|gs)://\\S+")) {
productionMetadataBlockers.add("artifact-location-is-not-externally-retained");
}
}
if (!imageDigest.matches(".+@sha256:[0-9a-f]{64}")) {
productionMetadataBlockers.add("missing-immutable-postgresql-image-digest");
}
if (dependencyVersions.pgjdbc().isBlank()) {
productionMetadataBlockers.add("missing-pgjdbc-version");
}
if (dependencyVersions.hibernate().isBlank()) {
productionMetadataBlockers.add("missing-hibernate-version");
}
if (dependencyVersions.flyway().isBlank()) {
productionMetadataBlockers.add("missing-flyway-version");
}
File outputDirectory = getEvidenceOutputDirectory().get().getAsFile();
fileSystemOperations.delete(spec -> spec.delete(outputDirectory));
if (!outputDirectory.mkdirs() && !outputDirectory.isDirectory()) {
throw new GradleException("Could not create JPA evidence directory " + outputDirectory);
}
Map<String, JpaGeneratedEvidenceManifest> manifests = new HashMap<>();
Map<String, String> manifestIds = new HashMap<>();
for (JpaReadinessCard card : activeCards) {
String cardId = card.id();
List<JpaGeneratedTestResult> testResults = new ArrayList<>();
if (cardId.equals("jpa-primary-foundation")) {
for (String prerequisite : card.prerequisites()) {
JpaGeneratedEvidenceManifest prerequisiteManifest = manifests.get(prerequisite);
if (prerequisiteManifest != null) {
testResults.add(prerequisiteManifest.testResult());
}
}
} else {
testResults.add(testResultsByTask.read(card.readinessTask()));
for (String supportPath : card.supportTasks()) {
if (getJUnitResultDirectories().get().containsKey(supportPath)) {
testResults.add(testResultsByTask.read(supportPath));
}
}
}
Set<String> executedSelectors = new TreeSet<>();
testResults.forEach(result -> executedSelectors.addAll(result.executedSelectors()));
Set<String> covered = new TreeSet<>();
JpaCardEvidence cardEvidence =
card.evidence()
.orElseThrow(
() -> new GradleException(cardId + ": active card has no typed evidence declaration"));
for (JpaEvidenceScenario scenario : cardEvidence.scenarios()) {
if (executedSelectors.contains(scenario.selector())) {
covered.addAll(scenario.covers());
}
}
for (JpaEvidenceTaskClaim taskClaim : cardEvidence.taskClaims()) {
if (executionService.completedSuccessfully(taskClaim.task())) {
covered.addAll(taskClaim.covers());
}
}
int executedTestCount = JpaEvidenceTaskSupport.sumExecuted(testResults);
int skippedOrAbortedCount = JpaEvidenceTaskSupport.sumSkipped(testResults);
int failureCount = JpaEvidenceTaskSupport.sumFailures(testResults);
int errorCount = JpaEvidenceTaskSupport.sumErrors(testResults);
boolean noSkipResult =
executedTestCount > 0
&& skippedOrAbortedCount == 0
&& failureCount == 0
&& errorCount == 0;
if (noSkipResult) {
covered.add("no-skip");
}
if (cardId.equals("jpa-primary-foundation")
&& card.prerequisites().stream().allMatch(manifestIds::containsKey)) {
covered.add("base-card-manifests");
}
List<String> required = JpaEvidenceVerifier.requiredEvidence(card);
List<String> coveredList =
covered.stream().filter(required::contains).sorted().toList();
List<String> missing = new ArrayList<>(required);
missing.removeAll(coveredList);
missing.sort(String::compareTo);
List<JpaPrerequisiteEvidence> prerequisites = new ArrayList<>();
for (String prerequisiteId : card.prerequisites()) {
JpaGeneratedEvidenceManifest prerequisiteManifest = manifests.get(prerequisiteId);
String prerequisiteManifestId = manifestIds.get(prerequisiteId);
if (prerequisiteManifest == null || prerequisiteManifestId == null) {
throw new GradleException(
cardId
+ ": prerequisite manifest '"
+ prerequisiteId
+ "' was not produced first");
}
prerequisites.add(
new JpaPrerequisiteEvidence(
prerequisiteId,
prerequisiteManifest.cardVersion(),
prerequisiteManifestId,
prerequisiteManifest.attainedReadiness()));
}
List<String> readinessBlockers = new ArrayList<>();
if (profile.equals("candidate")) {
readinessBlockers.add("candidate-profile-is-not-release-evidence");
}
readinessBlockers.addAll(productionMetadataBlockers);
for (String requirement : missing) {
readinessBlockers.add("missing-evidence:" + requirement);
}
for (JpaPrerequisiteEvidence prerequisite : prerequisites) {
if (!prerequisite.attainedReadiness().equals("R2")) {
readinessBlockers.add("prerequisite-not-R2:" + prerequisite.cardId());
}
}
List<String> sortedReadinessBlockers =
JpaEvidenceTaskSupport.sortedDistinct(readinessBlockers);
boolean attainedR2 =
profile.equals("r2") && sortedReadinessBlockers.isEmpty() && missing.isEmpty();
String generatedAt = Instant.now().toString();
String cardVersion =
card.migration()
.map(migration -> Integer.toString(migration.featureRevision()))
.orElse(getTraceableVersion().get());
String evidenceGrade =
cardId.equals("jpa-primary-foundation")
? "E1"
: covered.stream()
.anyMatch(
claim ->
Set.of(
"concurrency",
"fault",
"publish-fault",
"migration",
"query-plan",
"optimistic-conflict")
.contains(claim))
? "E3"
: "E2";
JpaGeneratedMigrationEvidence migration =
card.migration()
.map(
spec ->
new JpaGeneratedMigrationEvidence(
spec.location(),
spec.historyTable(),
spec.requiredCoreEpoch(),
spec.featureRevision(),
spec.lifecycleEvidence()))
.orElse(null);
JpaGeneratedTestResult combinedTestResult =
new JpaGeneratedTestResult(
JpaEvidenceTaskSupport.allTasks(testResults),
JpaEvidenceTaskSupport.allResultDirectories(testResults),
executedTestCount,
skippedOrAbortedCount,
failureCount,
errorCount,
noSkipResult,
List.copyOf(executedSelectors));
JpaGeneratedEvidenceManifest manifest =
new JpaGeneratedEvidenceManifest(
1,
cardId,
cardVersion,
card.state().externalValue(),
attainedR2 ? "R2" : "R1",
evidenceGrade,
profile,
prerequisites,
new JpaGeneratedSourceEvidence(
getSourceRevision().get(), worktreeDirty, worktreeStatusDigest),
new JpaGeneratedProducerEvidence(card.readinessTask(), ciJob),
combinedTestResult,
required,
coveredList,
missing,
sortedReadinessBlockers,
new JpaGeneratedPostgresqlEvidence(image, imageDigest, "16"),
dependencyVersions,
generatedAt,
generatedAt.substring(0, 10),
topology,
configuredArtifactLocation,
migration,
card.dispatchModes());
String contentHash =
JpaEvidenceVerifier.sha256(JpaEvidenceVerifier.canonicalJson(manifest));
File cardDirectory = new File(outputDirectory, cardId);
if (!cardDirectory.mkdirs() && !cardDirectory.isDirectory()) {
throw new GradleException("Could not create JPA evidence card directory " + cardDirectory);
}
File manifestFile = new File(cardDirectory, contentHash + ".json");
try {
Files.writeString(
manifestFile.toPath(), JpaEvidenceVerifier.prettyJson(manifest), StandardCharsets.UTF_8);
} catch (IOException exception) {
throw new UncheckedIOException("failed to write " + manifestFile, exception);
}
manifests.put(cardId, manifest);
manifestIds.put(cardId, "sha256:" + contentHash);
}
getLogger()
.lifecycle(
"generateJpaEvidenceManifests: wrote {} {} content-addressed card manifests to {}",
manifests.size(),
profile,
outputDirectory);
}
private String runCommand(List<String> command, boolean requireSuccess) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecResult result =
execOperations.exec(
spec -> {
spec.setCommandLine(command);
spec.setIgnoreExitValue(true);
spec.setStandardOutput(output);
});
String text = output.toString(StandardCharsets.UTF_8).trim();
if (requireSuccess && result.getExitValue() != 0) {
throw new GradleException(
"JPA evidence: `"
+ String.join(" ", command)
+ "` exited "
+ result.getExitValue()
+ ". Its result is a precondition of the evidence, not an optional detail — an unavailable command must not be read as a satisfied condition.");
}
return text;
}
}
@@ -1,11 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.List;
public record JpaCardEvidence(
List<JpaEvidenceScenario> scenarios, List<JpaEvidenceTaskClaim> taskClaims) {
public JpaCardEvidence {
scenarios = List.copyOf(scenarios);
taskClaims = List.copyOf(taskClaims);
}
}
@@ -1,26 +0,0 @@
package dev.caskeleton.buildtools.jpa;
public enum JpaCardState {
SELECTED("selected"),
IMPLEMENTED_CANDIDATE("implemented-candidate"),
NOT_IMPLEMENTED("not-implemented");
private final String externalValue;
JpaCardState(String externalValue) {
this.externalValue = externalValue;
}
public String externalValue() {
return externalValue;
}
public static JpaCardState parse(String value) {
for (JpaCardState state : values()) {
if (state.externalValue.equals(value)) {
return state;
}
}
throw new IllegalStateException("invalid JPA card state '" + value + "'");
}
}
@@ -1,11 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.Objects;
public record JpaDependencyVersions(String pgjdbc, String hibernate, String flyway) {
public JpaDependencyVersions {
Objects.requireNonNull(pgjdbc, "pgjdbc");
Objects.requireNonNull(hibernate, "hibernate");
Objects.requireNonNull(flyway, "flyway");
}
}
@@ -1,45 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.gradle.api.services.BuildService;
import org.gradle.api.services.BuildServiceParameters;
import org.gradle.tooling.events.FinishEvent;
import org.gradle.tooling.events.OperationCompletionListener;
import org.gradle.tooling.events.task.TaskFailureResult;
import org.gradle.tooling.events.task.TaskFinishEvent;
import org.gradle.tooling.events.task.TaskSkippedResult;
import org.gradle.tooling.events.task.TaskSuccessResult;
public abstract class JpaEvidenceExecutionService
implements BuildService<BuildServiceParameters.None>, OperationCompletionListener {
private final Map<String, JpaEvidenceTaskOutcome> outcomes = new ConcurrentHashMap<>();
@Override
public void onFinish(FinishEvent event) {
if (!(event instanceof TaskFinishEvent taskEvent)) {
return;
}
String taskPath = taskEvent.getDescriptor().getTaskPath();
if (taskEvent.getResult() instanceof TaskSuccessResult) {
record(taskPath, JpaEvidenceTaskOutcome.SUCCESS);
} else if (taskEvent.getResult() instanceof TaskFailureResult) {
record(taskPath, JpaEvidenceTaskOutcome.FAILED);
} else if (taskEvent.getResult() instanceof TaskSkippedResult) {
record(taskPath, JpaEvidenceTaskOutcome.SKIPPED);
}
}
void record(String taskPath, JpaEvidenceTaskOutcome outcome) {
outcomes.put(taskPath, outcome);
}
Optional<JpaEvidenceTaskOutcome> outcome(String taskPath) {
return Optional.ofNullable(outcomes.get(taskPath));
}
public boolean completedSuccessfully(String taskPath) {
return outcomes.get(taskPath) == JpaEvidenceTaskOutcome.SUCCESS;
}
}
@@ -1,33 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.List;
import java.util.Objects;
public record JpaEvidenceManifest(
String cardId,
String attainedReadiness,
String profile,
String evidenceGrade,
List<String> missingEvidence,
List<String> readinessBlockers,
JpaTestResult testResult,
JpaPostgresqlEvidence postgresql,
JpaDependencyVersions dependencies,
JpaSourceEvidence source,
JpaProducerEvidence producer,
String artifactLocation) {
public JpaEvidenceManifest {
Objects.requireNonNull(cardId, "cardId");
Objects.requireNonNull(attainedReadiness, "attainedReadiness");
Objects.requireNonNull(profile, "profile");
Objects.requireNonNull(evidenceGrade, "evidenceGrade");
missingEvidence = List.copyOf(missingEvidence);
readinessBlockers = List.copyOf(readinessBlockers);
Objects.requireNonNull(testResult, "testResult");
Objects.requireNonNull(postgresql, "postgresql");
Objects.requireNonNull(dependencies, "dependencies");
Objects.requireNonNull(source, "source");
Objects.requireNonNull(producer, "producer");
Objects.requireNonNull(artifactLocation, "artifactLocation");
}
}
@@ -1,216 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.inject.Inject;
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.provider.Provider;
import org.gradle.api.tasks.TaskProvider;
import org.gradle.api.tasks.testing.Test;
import org.gradle.build.event.BuildEventsListenerRegistry;
public final class JpaEvidencePlugin implements Plugin<Project> {
private final BuildEventsListenerRegistry buildEventsListenerRegistry;
@Inject
public JpaEvidencePlugin(BuildEventsListenerRegistry buildEventsListenerRegistry) {
this.buildEventsListenerRegistry = buildEventsListenerRegistry;
}
@Override
public void apply(Project project) {
Project root = project.getRootProject();
File registryFile = root.file("config/jpa/readiness-cards.yaml");
var outputDirectory = project.getLayout().getBuildDirectory().dir("jpa-evidence/manifests");
Provider<JpaEvidenceExecutionService> executionService =
project
.getGradle()
.getSharedServices()
.registerIfAbsent(
"jpaEvidenceExecution", JpaEvidenceExecutionService.class, ignored -> {});
buildEventsListenerRegistry.onTaskCompletion(executionService);
TaskProvider<GenerateJpaEvidenceManifestsTask> generate =
project
.getTasks()
.register(
"generateJpaEvidenceManifests",
GenerateJpaEvidenceManifestsTask.class,
task -> {
task.setGroup("verification");
task.setDescription(
"Runs active JPA card producers and writes content-addressed candidate/R2 manifests.");
task.dependsOn(root.getTasks().named("verifyJpaReadinessRegistry"));
task.getRegistryFile().fileValue(registryFile);
task.getEvidenceOutputDirectory().set(outputDirectory);
task.getPostgreSqlImage()
.convention(
project
.getProviders()
.gradleProperty("jpaPostgreSqlEvidenceImage")
.orElse("postgres:16-alpine"));
var profile =
project
.getProviders()
.gradleProperty("jpaEvidenceProfile")
.orElse(project.getProviders().environmentVariable("JPA_EVIDENCE_PROFILE"))
.orElse("candidate");
task.getEvidenceProfile().convention(profile);
task.getCiJob()
.convention(
project
.getProviders()
.environmentVariable("JPA_EVIDENCE_CI_JOB")
.orElse(
profile.map(
value ->
value.equals("candidate")
? "local-unpublished"
: "")));
String candidateArtifactLocation =
root.relativePath(outputDirectory.get().getAsFile());
task.getArtifactLocation()
.convention(
project
.getProviders()
.environmentVariable("JPA_EVIDENCE_ARTIFACT_LOCATION")
.orElse(
profile.map(
value ->
value.equals("candidate")
? candidateArtifactLocation
: "")));
task.getTopology()
.convention(
project
.getProviders()
.environmentVariable("JPA_EVIDENCE_TOPOLOGY")
.orElse("single-postgresql-testcontainer"));
task.getSourceRevision().set(configurationString(root, "sourceRevision"));
task.getTraceableVersion().set(configurationString(root, "traceableVersion"));
task.getRepositoryRootPath().set(root.getProjectDir().getAbsolutePath());
task.getExecutionService().set(executionService);
task.usesService(executionService);
var runtimeClasspath =
project
.getConfigurations()
.getByName("postgresqlIntegrationTestRuntimeClasspath");
Provider<JpaDependencyVersions> dependencyVersions =
project
.getProviders()
.provider(
() -> JpaEvidenceTaskSupport.resolvedVersions(runtimeClasspath));
task.getPgjdbcVersion().set(dependencyVersions.map(JpaDependencyVersions::pgjdbc));
task.getHibernateVersion()
.set(dependencyVersions.map(JpaDependencyVersions::hibernate));
task.getFlywayVersion().set(dependencyVersions.map(JpaDependencyVersions::flyway));
Map<String, String> junitResultDirectories = new LinkedHashMap<>();
JpaReadinessRegistry registry =
JpaEvidenceTaskSupport.loadRegistry(registryFile);
for (JpaReadinessCard card : registry.activeCards()) {
if (!card.id().equals("jpa-primary-foundation")) {
Task readinessTask =
JpaEvidenceTaskSupport.taskAtPath(root, card.readinessTask());
task.dependsOn(readinessTask);
if (!(readinessTask instanceof Test readinessTest)) {
throw new GradleException(
card.id()
+ ": readiness task "
+ readinessTask.getPath()
+ " must be a Test task");
}
junitResultDirectories.put(
readinessTask.getPath(), junitResultDirectory(readinessTest));
}
for (String supportPath : card.supportTasks()) {
Task supportTask = JpaEvidenceTaskSupport.taskAtPath(root, supportPath);
task.dependsOn(supportTask);
if (supportTask instanceof Test supportTest) {
junitResultDirectories.put(
supportTask.getPath(), junitResultDirectory(supportTest));
}
}
}
task.getJUnitResultDirectories().set(junitResultDirectories);
task.getOutputs().upToDateWhen(ignored -> false);
});
project
.getGradle()
.getTaskGraph()
.whenReady(
graph -> {
if (!graph.hasTask(generate.get())) {
return;
}
project
.getTasks()
.named("test", Test.class)
.get()
.getOutputs()
.upToDateWhen(ignored -> false);
Project appBootstrap = root.findProject(":app-bootstrap");
if (appBootstrap != null) {
appBootstrap
.getTasks()
.named("test", Test.class)
.get()
.getOutputs()
.upToDateWhen(ignored -> false);
}
});
project
.getTasks()
.register(
"verifyJpaCandidateEvidence",
VerifyJpaCandidateEvidenceTask.class,
task -> {
task.setGroup("verification");
task.setDescription(
"Validates hashes, schema, exact JUnit selectors, no-skip, and prerequisite links without claiming R2.");
task.dependsOn(generate);
task.getRegistryFile().fileValue(registryFile);
task.getEvidenceOutputDirectory().set(outputDirectory);
task.getOutputs().upToDateWhen(ignored -> false);
});
project
.getTasks()
.register(
"verifyJpaPrimaryFoundationEvidence",
VerifyJpaPrimaryFoundationEvidenceTask.class,
task -> {
task.setGroup("verification");
task.setDescription(
"Requires complete immutable base-card manifests from a clean, retained CI R2 evidence lane.");
task.dependsOn(generate);
task.getRegistryFile().fileValue(registryFile);
task.getEvidenceOutputDirectory().set(outputDirectory);
task.getOutputs().upToDateWhen(ignored -> false);
});
}
private static String configurationString(Project project, String name) {
var extra = project.getExtensions().getExtraProperties();
return extra.has(name) ? String.valueOf(extra.get(name)) : "";
}
private static String junitResultDirectory(Test test) {
return test
.getReports()
.getJunitXml()
.getOutputLocation()
.get()
.getAsFile()
.getAbsolutePath();
}
}
@@ -1,11 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.List;
import java.util.Objects;
public record JpaEvidenceScenario(String selector, List<String> covers) {
public JpaEvidenceScenario {
Objects.requireNonNull(selector, "selector");
covers = List.copyOf(covers);
}
}
@@ -1,11 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.List;
import java.util.Objects;
public record JpaEvidenceTaskClaim(String task, List<String> covers) {
public JpaEvidenceTaskClaim {
Objects.requireNonNull(task, "task");
covers = List.copyOf(covers);
}
}
@@ -1,7 +0,0 @@
package dev.caskeleton.buildtools.jpa;
enum JpaEvidenceTaskOutcome {
SUCCESS,
FAILED,
SKIPPED
}
@@ -1,100 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import org.gradle.api.GradleException;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.component.ModuleComponentIdentifier;
import org.gradle.api.artifacts.result.ResolvedComponentResult;
final class JpaEvidenceTaskSupport {
private JpaEvidenceTaskSupport() {}
static JpaReadinessRegistry loadRegistry(File registryFile) {
try {
return JpaReadinessRegistryParser.parse(
Files.readString(registryFile.toPath(), StandardCharsets.UTF_8));
} catch (IOException exception) {
throw new UncheckedIOException("failed to read " + registryFile, exception);
}
}
static Task taskAtPath(Project rootProject, String absoluteTaskPath) {
int separator = absoluteTaskPath.lastIndexOf(':');
if (separator < 0 || separator == absoluteTaskPath.length() - 1) {
throw new GradleException("Invalid absolute Gradle task path '" + absoluteTaskPath + "'");
}
String projectPath = separator == 0 ? ":" : absoluteTaskPath.substring(0, separator);
String taskName = absoluteTaskPath.substring(separator + 1);
Project owner = rootProject.findProject(projectPath);
if (owner == null) {
throw new GradleException("Unknown project for JPA evidence task '" + absoluteTaskPath + "'");
}
Task task = owner.getTasks().findByName(taskName);
if (task == null) {
throw new GradleException("Missing JPA evidence task '" + absoluteTaskPath + "'");
}
return task;
}
static JpaDependencyVersions resolvedVersions(Configuration configuration) {
String pgjdbc = "";
String hibernate = "";
String flyway = "";
for (ResolvedComponentResult component :
configuration.getIncoming().getResolutionResult().getAllComponents()) {
if (!(component.getId() instanceof ModuleComponentIdentifier id)) {
continue;
}
String coordinate = id.getGroup() + ":" + id.getModule();
if (coordinate.equals("org.postgresql:postgresql")) {
pgjdbc = id.getVersion();
} else if (coordinate.equals("org.hibernate.orm:hibernate-core")) {
hibernate = id.getVersion();
} else if (coordinate.equals("org.flywaydb:flyway-core")) {
flyway = id.getVersion();
}
}
return new JpaDependencyVersions(pgjdbc, hibernate, flyway);
}
static List<String> sortedDistinct(List<String> values) {
return new TreeSet<>(values).stream().toList();
}
static int sumExecuted(List<JpaGeneratedTestResult> values) {
return values.stream().mapToInt(JpaGeneratedTestResult::executedTestCount).sum();
}
static int sumSkipped(List<JpaGeneratedTestResult> values) {
return values.stream().mapToInt(JpaGeneratedTestResult::skippedOrAbortedCount).sum();
}
static int sumFailures(List<JpaGeneratedTestResult> values) {
return values.stream().mapToInt(JpaGeneratedTestResult::failureCount).sum();
}
static int sumErrors(List<JpaGeneratedTestResult> values) {
return values.stream().mapToInt(JpaGeneratedTestResult::errorCount).sum();
}
static List<String> allTasks(List<JpaGeneratedTestResult> results) {
List<String> values = new ArrayList<>();
results.forEach(result -> values.addAll(result.tasks()));
return sortedDistinct(values);
}
static List<String> allResultDirectories(List<JpaGeneratedTestResult> results) {
List<String> values = new ArrayList<>();
results.forEach(result -> values.addAll(result.resultDirectories()));
return sortedDistinct(values);
}
}
@@ -1,48 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import dev.caskeleton.buildtools.junit.JUnitEvidenceReader;
import dev.caskeleton.buildtools.junit.JUnitEvidenceResult;
import java.io.File;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
final class JpaEvidenceTestResultLocator {
private final Path repositoryRoot;
private final Map<String, String> resultDirectories;
JpaEvidenceTestResultLocator(Path repositoryRoot, Map<String, String> resultDirectories) {
this.repositoryRoot = repositoryRoot.toAbsolutePath().normalize();
this.resultDirectories = Map.copyOf(resultDirectories);
}
JpaGeneratedTestResult read(String taskPath) {
String configuredDirectory = resultDirectories.get(taskPath);
if (configuredDirectory == null || configuredDirectory.isBlank()) {
throw new IllegalStateException(
taskPath + ": no configured JUnit result directory for JPA evidence");
}
Path resultDirectory = Path.of(configuredDirectory).toAbsolutePath().normalize();
JUnitEvidenceResult result = JUnitEvidenceReader.read(taskPath, resultDirectory.toFile());
String renderedDirectory = renderDirectory(resultDirectory);
return new JpaGeneratedTestResult(
List.of(taskPath),
List.of(renderedDirectory),
result.tests(),
result.skipped(),
result.failures(),
result.errors(),
result.isClean(),
new TreeSet<>(result.executedSelectors()).stream().toList());
}
private String renderDirectory(Path resultDirectory) {
if (resultDirectory.startsWith(repositoryRoot)) {
return repositoryRoot.relativize(resultDirectory).toString().replace(File.separatorChar, '/');
}
return resultDirectory.toString();
}
}
@@ -1,18 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.List;
public record JpaEvidenceVerificationResult(
List<String> violations, List<JpaEvidenceManifest> manifests) {
public JpaEvidenceVerificationResult {
violations = List.copyOf(violations);
manifests = List.copyOf(manifests);
}
public JpaEvidenceManifest manifest(String cardId) {
return manifests.stream()
.filter(manifest -> manifest.cardId().equals(cardId))
.findFirst()
.orElse(null);
}
}
@@ -1,251 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HexFormat;
import java.util.List;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
/** Pure evidence semantics for JPA readiness manifests. No Gradle API. */
public final class JpaEvidenceVerifier {
private static final ObjectMapper JSON = JsonMapper.builder().build();
private JpaEvidenceVerifier() {}
public static String canonicalJson(String json) {
return canonicalJson(JSON.readTree(json));
}
public static String canonicalJson(JsonNode node) {
StringBuilder result = new StringBuilder();
appendCanonical(node, result);
return result.toString();
}
public static String prettyJson(JpaEvidenceManifest manifest) {
return JSON.writerWithDefaultPrettyPrinter().writeValueAsString(manifest) + System.lineSeparator();
}
public static String canonicalJson(JpaGeneratedEvidenceManifest manifest) {
return canonicalJson(JSON.writeValueAsString(manifest));
}
public static String prettyJson(JpaGeneratedEvidenceManifest manifest) {
return JSON.writerWithDefaultPrettyPrinter().writeValueAsString(manifest) + System.lineSeparator();
}
public static String sha256(String value) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return HexFormat.of().formatHex(digest.digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 is unavailable", exception);
}
}
public static List<String> requiredEvidence(JpaReadinessCard card) {
return card.allRequiredEvidence();
}
public static List<String> validateManifest(JpaEvidenceManifest manifest) {
List<String> violations = new ArrayList<>();
String cardId = manifest.cardId();
JpaTestResult testResult = manifest.testResult();
if (testResult.executedTestCount() <= 0) {
violations.add(cardId + ": executed test count must be positive");
}
if (testResult.skippedOrAbortedCount() != 0) {
violations.add(cardId + ": skippedOrAbortedCount must be zero");
}
if (testResult.failureCount() != 0) {
violations.add(cardId + ": failureCount must be zero");
}
if (testResult.errorCount() != 0) {
violations.add(cardId + ": errorCount must be zero");
}
if (!testResult.noSkipResult()) {
violations.add(cardId + ": no-skip sentinel must be true");
}
if (!manifest.postgresql().imageDigest().matches(".+@sha256:[0-9a-f]{64}")) {
violations.add(cardId + ": PostgreSQL image digest must be immutable");
}
if (manifest.dependencies().pgjdbc().isBlank()) {
violations.add(cardId + ": pgjdbc version must be present");
}
if (manifest.dependencies().hibernate().isBlank()) {
violations.add(cardId + ": hibernate version must be present");
}
if (manifest.dependencies().flyway().isBlank()) {
violations.add(cardId + ": flyway version must be present");
}
if (manifest.attainedReadiness().equals("R2")) {
if (!manifest.profile().equals("r2")) {
violations.add(cardId + ": R2 requires the r2 profile");
}
if (manifest.source().worktreeDirty()) {
violations.add(cardId + ": R2 requires a clean worktree");
}
if (!manifest.missingEvidence().isEmpty()) {
violations.add(cardId + ": R2 has missing evidence " + manifest.missingEvidence());
}
if (manifest.producer().ciJob().isBlank()
|| manifest.producer().ciJob().equals("local-unpublished")) {
violations.add(cardId + ": R2 requires a real CI job identity");
}
if (!manifest.artifactLocation().matches("(?i)(https|s3|gs)://\\S+")) {
violations.add(cardId + ": R2 requires an externally retained artifact location");
}
}
return List.copyOf(violations);
}
public static JpaEvidenceVerificationResult verifyDirectory(
File outputDirectory, JpaReadinessRegistry registry) {
List<String> violations = new ArrayList<>();
List<JpaEvidenceManifest> manifests = new ArrayList<>();
for (JpaReadinessCard card : registry.activeCards()) {
File cardDirectory = new File(outputDirectory, card.id());
File[] jsonFiles =
cardDirectory.isDirectory()
? cardDirectory.listFiles(file -> file.isFile() && file.getName().endsWith(".json"))
: null;
List<File> files =
jsonFiles == null
? List.of()
: java.util.Arrays.stream(jsonFiles)
.sorted(Comparator.comparing(File::getName))
.toList();
if (files.size() != 1) {
violations.add(
card.id()
+ ": expected exactly one content-addressed manifest; got "
+ files.size());
continue;
}
JpaEvidenceManifest manifest = parseManifest(files.getFirst());
violations.addAll(validateManifest(manifest));
manifests.add(manifest);
}
return new JpaEvidenceVerificationResult(violations, manifests);
}
public static JpaEvidenceManifest parseManifest(File manifestFile) {
JsonNode root = JSON.readTree(read(manifestFile));
return new JpaEvidenceManifest(
text(root, "cardId", ""),
text(root, "attainedReadiness", ""),
text(root, "profile", ""),
text(root, "evidenceGrade", ""),
strings(root.get("missingEvidence")),
strings(root.get("readinessBlockers")),
parseTestResult(root.get("testResult")),
new JpaPostgresqlEvidence(text(root.get("postgresql"), "imageDigest", "")),
parseDependencies(root.get("dependencies")),
new JpaSourceEvidence(booleanValue(root.get("source"), "worktreeDirty", true)),
new JpaProducerEvidence(text(root.get("producer"), "ciJob", "")),
text(root, "artifactLocation", ""));
}
private static JpaTestResult parseTestResult(JsonNode node) {
return new JpaTestResult(
integer(node, "executedTestCount", 0),
integer(node, "skippedOrAbortedCount", 0),
integer(node, "failureCount", 0),
integer(node, "errorCount", 0),
booleanValue(node, "noSkipResult", false));
}
private static JpaDependencyVersions parseDependencies(JsonNode node) {
return new JpaDependencyVersions(
text(node, "pgjdbc", ""), text(node, "hibernate", ""), text(node, "flyway", ""));
}
private static void appendCanonical(JsonNode node, StringBuilder into) {
if (node == null || node.isNull()) {
into.append("null");
return;
}
if (node.isObject()) {
List<String> names = new ArrayList<>();
node.properties().forEach(entry -> names.add(entry.getKey()));
names.sort(String::compareTo);
into.append('{');
for (int index = 0; index < names.size(); index++) {
if (index > 0) {
into.append(',');
}
String name = names.get(index);
into.append(JSON.writeValueAsString(name)).append(':');
appendCanonical(node.get(name), into);
}
into.append('}');
return;
}
if (node.isArray()) {
into.append('[');
for (int index = 0; index < node.size(); index++) {
if (index > 0) {
into.append(',');
}
appendCanonical(node.get(index), into);
}
into.append(']');
return;
}
into.append(node.toString());
}
private static List<String> strings(JsonNode node) {
if (node == null || !node.isArray()) {
return List.of();
}
List<String> values = new ArrayList<>();
for (JsonNode value : node) {
values.add(value.asText());
}
return List.copyOf(values);
}
private static String text(JsonNode node, String field, String fallback) {
if (node == null || !node.isObject()) {
return fallback;
}
JsonNode value = node.get(field);
return value == null || value.isNull() ? fallback : value.asText();
}
private static int integer(JsonNode node, String field, int fallback) {
if (node == null || !node.isObject()) {
return fallback;
}
JsonNode value = node.get(field);
return value == null || !value.isIntegralNumber() ? fallback : value.asInt();
}
private static boolean booleanValue(JsonNode node, String field, boolean fallback) {
if (node == null || !node.isObject()) {
return fallback;
}
JsonNode value = node.get(field);
return value == null || !value.isBoolean() ? fallback : value.asBoolean();
}
private static String read(File file) {
try {
return Files.readString(file.toPath(), StandardCharsets.UTF_8);
} catch (IOException exception) {
throw new UncheckedIOException("failed to read " + file, exception);
}
}
}
@@ -1,12 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.Objects;
public record JpaExternalPrerequisite(
String registry, String cardId, String minimumReadiness) {
public JpaExternalPrerequisite {
Objects.requireNonNull(registry, "registry");
Objects.requireNonNull(cardId, "cardId");
Objects.requireNonNull(minimumReadiness, "minimumReadiness");
}
}
@@ -1,69 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.List;
import java.util.Objects;
public record JpaGeneratedEvidenceManifest(
int schemaVersion,
String cardId,
String cardVersion,
String declaredState,
String attainedReadiness,
String evidenceGrade,
String profile,
List<JpaPrerequisiteEvidence> prerequisites,
JpaGeneratedSourceEvidence source,
JpaGeneratedProducerEvidence producer,
JpaGeneratedTestResult testResult,
List<String> requiredEvidence,
List<String> coveredEvidence,
List<String> missingEvidence,
List<String> readinessBlockers,
JpaGeneratedPostgresqlEvidence postgresql,
JpaDependencyVersions dependencies,
String generatedAt,
String date,
String topology,
String artifactLocation,
JpaGeneratedMigrationEvidence migration,
List<String> dispatchModes) {
public JpaGeneratedEvidenceManifest {
Objects.requireNonNull(cardId, "cardId");
Objects.requireNonNull(cardVersion, "cardVersion");
Objects.requireNonNull(declaredState, "declaredState");
Objects.requireNonNull(attainedReadiness, "attainedReadiness");
Objects.requireNonNull(evidenceGrade, "evidenceGrade");
Objects.requireNonNull(profile, "profile");
prerequisites = List.copyOf(prerequisites);
Objects.requireNonNull(source, "source");
Objects.requireNonNull(producer, "producer");
Objects.requireNonNull(testResult, "testResult");
requiredEvidence = List.copyOf(requiredEvidence);
coveredEvidence = List.copyOf(coveredEvidence);
missingEvidence = List.copyOf(missingEvidence);
readinessBlockers = List.copyOf(readinessBlockers);
Objects.requireNonNull(postgresql, "postgresql");
Objects.requireNonNull(dependencies, "dependencies");
Objects.requireNonNull(generatedAt, "generatedAt");
Objects.requireNonNull(date, "date");
Objects.requireNonNull(topology, "topology");
Objects.requireNonNull(artifactLocation, "artifactLocation");
dispatchModes = List.copyOf(dispatchModes);
}
public JpaEvidenceManifest verificationView() {
return new JpaEvidenceManifest(
cardId,
attainedReadiness,
profile,
evidenceGrade,
missingEvidence,
readinessBlockers,
testResult.verificationView(),
new JpaPostgresqlEvidence(postgresql.imageDigest()),
dependencies,
new JpaSourceEvidence(source.worktreeDirty()),
new JpaProducerEvidence(producer.ciJob()),
artifactLocation);
}
}
@@ -1,17 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.List;
import java.util.Objects;
public record JpaGeneratedMigrationEvidence(
String location,
String historyTable,
int requiredCoreEpoch,
int featureRevision,
List<String> streamLifecycleEvidenceIds) {
public JpaGeneratedMigrationEvidence {
Objects.requireNonNull(location, "location");
Objects.requireNonNull(historyTable, "historyTable");
streamLifecycleEvidenceIds = List.copyOf(streamLifecycleEvidenceIds);
}
}
@@ -1,12 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.Objects;
public record JpaGeneratedPostgresqlEvidence(
String image, String imageDigest, String managedEngineVersion) {
public JpaGeneratedPostgresqlEvidence {
Objects.requireNonNull(image, "image");
Objects.requireNonNull(imageDigest, "imageDigest");
Objects.requireNonNull(managedEngineVersion, "managedEngineVersion");
}
}
@@ -1,10 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.Objects;
public record JpaGeneratedProducerEvidence(String gradleTask, String ciJob) {
public JpaGeneratedProducerEvidence {
Objects.requireNonNull(gradleTask, "gradleTask");
Objects.requireNonNull(ciJob, "ciJob");
}
}
@@ -1,11 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.Objects;
public record JpaGeneratedSourceEvidence(
String revision, boolean worktreeDirty, String worktreeStatusDigest) {
public JpaGeneratedSourceEvidence {
Objects.requireNonNull(revision, "revision");
Objects.requireNonNull(worktreeStatusDigest, "worktreeStatusDigest");
}
}
@@ -1,24 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.List;
public record JpaGeneratedTestResult(
List<String> tasks,
List<String> resultDirectories,
int executedTestCount,
int skippedOrAbortedCount,
int failureCount,
int errorCount,
boolean noSkipResult,
List<String> executedSelectors) {
public JpaGeneratedTestResult {
tasks = List.copyOf(tasks);
resultDirectories = List.copyOf(resultDirectories);
executedSelectors = List.copyOf(executedSelectors);
}
public JpaTestResult verificationView() {
return new JpaTestResult(
executedTestCount, skippedOrAbortedCount, failureCount, errorCount, noSkipResult);
}
}
@@ -1,31 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import org.gradle.api.Project;
import org.gradle.api.Task;
final class JpaGradleTaskPath {
private JpaGradleTaskPath() {}
static Task find(Project rootProject, String absoluteTaskPath) {
if (absoluteTaskPath == null || !absoluteTaskPath.startsWith(":")) {
return null;
}
int separator = absoluteTaskPath.lastIndexOf(':');
if (separator < 0 || separator == absoluteTaskPath.length() - 1) {
return null;
}
String projectPath = separator == 0 ? ":" : absoluteTaskPath.substring(0, separator);
String taskName = absoluteTaskPath.substring(separator + 1);
Project owner = rootProject.findProject(projectPath);
return owner == null ? null : owner.getTasks().findByName(taskName);
}
static String projectPath(String absoluteTaskPath) {
int separator = absoluteTaskPath.lastIndexOf(':');
return separator == 0 ? ":" : absoluteTaskPath.substring(0, separator);
}
static String taskName(String absoluteTaskPath) {
return absoluteTaskPath.substring(absoluteTaskPath.lastIndexOf(':') + 1);
}
}
@@ -1,37 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.Set;
import java.util.TreeSet;
import org.gradle.api.Project;
import org.gradle.api.tasks.testing.Test;
record JpaGradleTaskSnapshot(
Set<String> projectPaths, Set<String> taskPaths, Set<String> testTaskPaths) {
JpaGradleTaskSnapshot {
projectPaths = Set.copyOf(projectPaths);
taskPaths = Set.copyOf(taskPaths);
testTaskPaths = Set.copyOf(testTaskPaths);
}
static JpaGradleTaskSnapshot capture(Project rootProject) {
Set<String> projects = new TreeSet<>();
Set<String> tasks = new TreeSet<>();
Set<String> tests = new TreeSet<>();
for (Project project : rootProject.getAllprojects()) {
String projectPath = project.getPath();
projects.add(projectPath);
for (String taskName : project.getTasks().getNames()) {
tasks.add(taskPath(projectPath, taskName));
}
for (String taskName : project.getTasks().withType(Test.class).getNames()) {
tests.add(taskPath(projectPath, taskName));
}
}
return new JpaGradleTaskSnapshot(projects, tasks, tests);
}
private static String taskPath(String projectPath, String taskName) {
return projectPath.equals(":") ? ":" + taskName : projectPath + ":" + taskName;
}
}
@@ -1,19 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.List;
import java.util.Objects;
public record JpaLegacyAdoption(
String state,
String location,
String historyTable,
List<Integer> immutableAppliedVersions,
String allowedOrigin) {
public JpaLegacyAdoption {
Objects.requireNonNull(state, "state");
Objects.requireNonNull(location, "location");
Objects.requireNonNull(historyTable, "historyTable");
immutableAppliedVersions = List.copyOf(immutableAppliedVersions);
Objects.requireNonNull(allowedOrigin, "allowedOrigin");
}
}
@@ -1,17 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.List;
import java.util.Objects;
public record JpaMigrationSpec(
String location,
String historyTable,
int requiredCoreEpoch,
int featureRevision,
List<String> lifecycleEvidence) {
public JpaMigrationSpec {
Objects.requireNonNull(location, "location");
Objects.requireNonNull(historyTable, "historyTable");
lifecycleEvidence = List.copyOf(lifecycleEvidence);
}
}
@@ -1,9 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.Objects;
public record JpaPostgresqlEvidence(String imageDigest) {
public JpaPostgresqlEvidence {
Objects.requireNonNull(imageDigest, "imageDigest");
}
}
@@ -1,13 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.Objects;
public record JpaPrerequisiteEvidence(
String cardId, String cardVersion, String manifestId, String attainedReadiness) {
public JpaPrerequisiteEvidence {
Objects.requireNonNull(cardId, "cardId");
Objects.requireNonNull(cardVersion, "cardVersion");
Objects.requireNonNull(manifestId, "manifestId");
Objects.requireNonNull(attainedReadiness, "attainedReadiness");
}
}
@@ -1,9 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.Objects;
public record JpaProducerEvidence(String ciJob) {
public JpaProducerEvidence {
Objects.requireNonNull(ciJob, "ciJob");
}
}
@@ -1,91 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.tasks.TaskProvider;
public final class JpaQualificationPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
Project root = project.getRootProject();
TaskProvider<VerifyJpaReleaseGateTasksTask> releaseGateTasks =
project
.getTasks()
.register(
"verifyJpaReleaseGateTasks",
VerifyJpaReleaseGateTasksTask.class,
task -> {
task.setGroup("verification");
task.setDescription(
"Resolves every release-registry gate task against the real Gradle task"
+ " graph.");
task.getRegistryFile().fileValue(root.file("config/jpa/release-registry.json"));
});
TaskProvider<Task> releaseQualification =
project
.getTasks()
.register(
"jpaReleaseQualification",
task -> {
task.setGroup("verification");
task.setDescription(
"Runs exactly the blocking JPA release gates declared by"
+ " config/jpa/release-registry.json.");
task.dependsOn(releaseGateTasks);
});
TaskProvider<VerifyJpaReadinessRegistryTask> readinessRegistry =
project
.getTasks()
.register(
"verifyJpaReadinessRegistry",
VerifyJpaReadinessRegistryTask.class,
task -> {
task.setGroup("verification");
task.setDescription(
"Validates the JPA readiness card, prerequisite, task, and migration"
+ " registry.");
task.getRegistryFile().fileValue(root.file("config/jpa/readiness-cards.yaml"));
});
project
.getGradle()
.projectsEvaluated(
ignored -> {
JpaGradleTaskSnapshot snapshot = JpaGradleTaskSnapshot.capture(root);
releaseGateTasks.configure(
task -> {
task.getAvailableProjectPaths().set(snapshot.projectPaths());
task.getAvailableTaskPaths().set(snapshot.taskPaths());
task.getTestTaskPaths().set(snapshot.testTaskPaths());
});
readinessRegistry.configure(
task -> task.getAvailableTaskPaths().set(snapshot.taskPaths()));
JpaReleaseRegistry registry = readReleaseRegistry(root);
releaseQualification.configure(
task ->
task.dependsOn(
registry.gates().stream()
.filter(JpaReleaseGate::blocking)
.map(JpaReleaseGate::task)
.toList()));
});
}
private static JpaReleaseRegistry readReleaseRegistry(Project root) {
try {
return JpaReleaseRegistryParser.parse(
Files.readString(
root.file("config/jpa/release-registry.json").toPath(), StandardCharsets.UTF_8));
} catch (IOException exception) {
throw new UncheckedIOException("failed to read JPA release registry", exception);
}
}
}
@@ -1,49 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.TreeSet;
public record JpaReadinessCard(
String id,
JpaCardState state,
JpaSchemaStream schemaStream,
List<String> prerequisites,
List<JpaExternalPrerequisite> externalPrerequisites,
String readinessTask,
List<String> supportTasks,
List<String> requiredEvidence,
Optional<JpaCardEvidence> evidence,
List<String> dispatchModes,
Optional<JpaMigrationSpec> migration) {
public JpaReadinessCard {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(state, "state");
Objects.requireNonNull(schemaStream, "schemaStream");
prerequisites = List.copyOf(prerequisites);
externalPrerequisites = List.copyOf(externalPrerequisites);
Objects.requireNonNull(readinessTask, "readinessTask");
supportTasks = List.copyOf(supportTasks);
requiredEvidence = List.copyOf(requiredEvidence);
evidence = evidence == null ? Optional.empty() : evidence;
dispatchModes = List.copyOf(dispatchModes);
migration = migration == null ? Optional.empty() : migration;
}
public List<String> allOwnedTasks() {
TreeSet<String> tasks = new TreeSet<>();
tasks.add(readinessTask);
tasks.addAll(supportTasks);
return List.copyOf(tasks);
}
public List<String> allRequiredEvidence() {
TreeSet<String> required = new TreeSet<>(requiredEvidence);
migration.ifPresent(
spec ->
spec.lifecycleEvidence()
.forEach(lifecycle -> required.add("migration-lifecycle:" + lifecycle)));
return List.copyOf(required);
}
}
@@ -1,26 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
public record JpaReadinessRegistry(
int schemaVersion, JpaLegacyAdoption legacyAdoption, List<JpaReadinessCard> cards) {
public JpaReadinessRegistry {
Objects.requireNonNull(legacyAdoption, "legacyAdoption");
cards = List.copyOf(cards);
}
public Optional<JpaReadinessCard> findCard(String id) {
return cards.stream().filter(card -> card.id().equals(id)).findFirst();
}
public JpaReadinessCard card(String id) {
return findCard(id)
.orElseThrow(() -> new IllegalArgumentException("unknown JPA readiness card '" + id + "'"));
}
public List<JpaReadinessCard> activeCards() {
return cards.stream().filter(card -> card.state() != JpaCardState.NOT_IMPLEMENTED).toList();
}
}
@@ -1,285 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
public final class JpaReadinessRegistryParser {
private static final ObjectMapper JSON = JsonMapper.builder().build();
private static final Set<String> ROOT_KEYS = Set.of("schema-version", "legacy-adoption", "cards");
private static final Set<String> LEGACY_KEYS =
Set.of("state", "location", "history-table", "immutable-applied-versions", "allowed-origin");
private static final Set<String> CARD_KEYS =
Set.of(
"state",
"schema-stream",
"prerequisites",
"external-prerequisites",
"readiness-task",
"support-tasks",
"required-evidence",
"evidence",
"dispatch-modes",
"migration");
private static final Set<String> EVIDENCE_KEYS = Set.of("scenarios", "task-claims");
private static final Set<String> SCENARIO_KEYS = Set.of("selector", "covers");
private static final Set<String> TASK_CLAIM_KEYS = Set.of("task", "covers");
private static final Set<String> MIGRATION_KEYS =
Set.of(
"location",
"history-table",
"required-core-epoch",
"feature-revision",
"lifecycle-evidence");
private static final Set<String> EXTERNAL_KEYS =
Set.of("registry", "card-id", "minimum-readiness");
private JpaReadinessRegistryParser() {}
public static JpaReadinessRegistry parse(String raw) {
detectDuplicateRawCardKeys(raw);
JsonNode root = JSON.readTree(raw);
requireObject(root, "root");
requireExactKeys(root, ROOT_KEYS, "root");
int schemaVersion = requiredInt(root, "schema-version");
JsonNode legacyNode = requiredObject(root, "legacy-adoption");
requireExactKeys(legacyNode, LEGACY_KEYS, "legacy-adoption");
JpaLegacyAdoption legacy =
new JpaLegacyAdoption(
requiredText(legacyNode, "state"),
requiredText(legacyNode, "location"),
requiredText(legacyNode, "history-table"),
integerArray(legacyNode.get("immutable-applied-versions"), "immutable-applied-versions"),
requiredText(legacyNode, "allowed-origin"));
JsonNode cardsNode = requiredObject(root, "cards");
List<JpaReadinessCard> cards = new ArrayList<>();
cardsNode.properties().forEach(entry -> cards.add(parseCard(entry.getKey(), entry.getValue())));
return new JpaReadinessRegistry(schemaVersion, legacy, cards);
}
private static JpaReadinessCard parseCard(String id, JsonNode node) {
requireObject(node, id);
Set<String> actualKeys = keys(node);
Set<String> unknown = new HashSet<>(actualKeys);
unknown.removeAll(CARD_KEYS);
if (!unknown.isEmpty()) {
throw new IllegalStateException(id + ": unknown card keys " + new java.util.TreeSet<>(unknown));
}
OptionalNode<JpaCardEvidence> evidence = optionalEvidence(id, node.get("evidence"));
OptionalNode<JpaMigrationSpec> migration = optionalMigration(id, node.get("migration"));
return new JpaReadinessCard(
id,
JpaCardState.parse(requiredText(node, "state")),
JpaSchemaStream.parse(requiredText(node, "schema-stream")),
stringArray(requiredNode(node, "prerequisites"), id + ".prerequisites"),
externalPrerequisites(id, node.get("external-prerequisites")),
requiredText(node, "readiness-task"),
optionalStringArray(node.get("support-tasks"), id + ".support-tasks"),
stringArray(requiredNode(node, "required-evidence"), id + ".required-evidence"),
evidence.value(),
optionalStringArray(node.get("dispatch-modes"), id + ".dispatch-modes"),
migration.value());
}
private static OptionalNode<JpaCardEvidence> optionalEvidence(String cardId, JsonNode node) {
if (node == null || node.isNull()) {
return OptionalNode.empty();
}
requireObject(node, cardId + ".evidence");
requireExactKeys(node, EVIDENCE_KEYS, cardId + ".evidence");
List<JpaEvidenceScenario> scenarios = new ArrayList<>();
JsonNode scenariosNode = requiredNode(node, "scenarios");
requireArray(scenariosNode, cardId + ".evidence.scenarios");
int scenarioIndex = 0;
for (JsonNode scenario : scenariosNode) {
requireObject(scenario, cardId + ".evidence.scenarios[" + scenarioIndex + "]");
requireExactKeys(
scenario, SCENARIO_KEYS, cardId + ".evidence.scenarios[" + scenarioIndex + "]");
scenarios.add(
new JpaEvidenceScenario(
requiredText(scenario, "selector"),
stringArray(
requiredNode(scenario, "covers"),
cardId + ".evidence.scenarios[" + scenarioIndex + "].covers")));
scenarioIndex++;
}
List<JpaEvidenceTaskClaim> taskClaims = new ArrayList<>();
JsonNode taskClaimsNode = requiredNode(node, "task-claims");
requireArray(taskClaimsNode, cardId + ".evidence.task-claims");
int claimIndex = 0;
for (JsonNode claim : taskClaimsNode) {
requireObject(claim, cardId + ".evidence.task-claims[" + claimIndex + "]");
requireExactKeys(
claim, TASK_CLAIM_KEYS, cardId + ".evidence.task-claims[" + claimIndex + "]");
taskClaims.add(
new JpaEvidenceTaskClaim(
requiredText(claim, "task"),
stringArray(
requiredNode(claim, "covers"),
cardId + ".evidence.task-claims[" + claimIndex + "].covers")));
claimIndex++;
}
return OptionalNode.of(new JpaCardEvidence(scenarios, taskClaims));
}
private static OptionalNode<JpaMigrationSpec> optionalMigration(String cardId, JsonNode node) {
if (node == null || node.isNull()) {
return OptionalNode.empty();
}
requireObject(node, cardId + ".migration");
requireExactKeys(node, MIGRATION_KEYS, cardId + ".migration");
return OptionalNode.of(
new JpaMigrationSpec(
requiredText(node, "location"),
requiredText(node, "history-table"),
requiredInt(node, "required-core-epoch"),
requiredInt(node, "feature-revision"),
stringArray(
requiredNode(node, "lifecycle-evidence"),
cardId + ".migration.lifecycle-evidence")));
}
private static List<JpaExternalPrerequisite> externalPrerequisites(String cardId, JsonNode node) {
if (node == null || node.isNull()) {
return List.of();
}
requireArray(node, cardId + ".external-prerequisites");
List<JpaExternalPrerequisite> result = new ArrayList<>();
int index = 0;
for (JsonNode external : node) {
requireObject(external, cardId + ".external-prerequisites[" + index + "]");
requireExactKeys(
external, EXTERNAL_KEYS, cardId + ".external-prerequisites[" + index + "]");
result.add(
new JpaExternalPrerequisite(
requiredText(external, "registry"),
requiredText(external, "card-id"),
requiredText(external, "minimum-readiness")));
index++;
}
return List.copyOf(result);
}
private static void detectDuplicateRawCardKeys(String raw) {
java.util.regex.Matcher matcher =
java.util.regex.Pattern.compile("\\\"(?<card>jpa-[a-z0-9.-]+)\\\"\\s*:").matcher(raw);
Set<String> seen = new HashSet<>();
Set<String> duplicates = new java.util.TreeSet<>();
while (matcher.find()) {
String id = matcher.group("card");
if (!seen.add(id)) {
duplicates.add(id);
}
}
if (!duplicates.isEmpty()) {
throw new IllegalStateException("duplicate raw card keys " + duplicates);
}
}
private static JsonNode requiredObject(JsonNode parent, String field) {
JsonNode node = requiredNode(parent, field);
requireObject(node, field);
return node;
}
private static JsonNode requiredNode(JsonNode parent, String field) {
JsonNode node = parent == null ? null : parent.get(field);
if (node == null || node.isNull()) {
throw new IllegalStateException("missing required field '" + field + "'");
}
return node;
}
private static String requiredText(JsonNode parent, String field) {
JsonNode node = requiredNode(parent, field);
if (!node.isString()) {
throw new IllegalStateException("field '" + field + "' must be a string");
}
return node.asText();
}
private static int requiredInt(JsonNode parent, String field) {
JsonNode node = requiredNode(parent, field);
if (!node.isIntegralNumber()) {
throw new IllegalStateException("field '" + field + "' must be an integer");
}
return node.asInt();
}
private static List<String> optionalStringArray(JsonNode node, String field) {
return node == null || node.isNull() ? List.of() : stringArray(node, field);
}
private static List<String> stringArray(JsonNode node, String field) {
requireArray(node, field);
List<String> values = new ArrayList<>();
for (JsonNode value : node) {
if (!value.isString()) {
throw new IllegalStateException(field + " values must be strings");
}
values.add(value.asText());
}
return List.copyOf(values);
}
private static List<Integer> integerArray(JsonNode node, String field) {
requireArray(node, field);
List<Integer> values = new ArrayList<>();
for (JsonNode value : node) {
if (!value.isIntegralNumber()) {
throw new IllegalStateException(field + " values must be integers");
}
values.add(value.asInt());
}
return List.copyOf(values);
}
private static void requireObject(JsonNode node, String name) {
if (node == null || !node.isObject()) {
throw new IllegalStateException(name + " must be an object");
}
}
private static void requireArray(JsonNode node, String name) {
if (node == null || !node.isArray()) {
throw new IllegalStateException(name + " must be a list");
}
}
private static void requireExactKeys(JsonNode node, Set<String> expected, String name) {
Set<String> actual = keys(node);
if (!actual.equals(expected)) {
Set<String> unknown = new java.util.TreeSet<>(actual);
unknown.removeAll(expected);
Set<String> missing = new java.util.TreeSet<>(expected);
missing.removeAll(actual);
String detail = !unknown.isEmpty() ? "unknown " + name + " keys " + unknown : name + " missing keys " + missing;
throw new IllegalStateException(detail);
}
}
private static Set<String> keys(JsonNode node) {
Set<String> result = new HashSet<>();
node.properties().forEach(entry -> result.add(entry.getKey()));
return result;
}
private record OptionalNode<T>(java.util.Optional<T> value) {
private static <T> OptionalNode<T> empty() {
return new OptionalNode<>(java.util.Optional.empty());
}
private static <T> OptionalNode<T> of(T value) {
return new OptionalNode<>(java.util.Optional.of(value));
}
}
}
@@ -1,310 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Predicate;
/** Repository-policy validator for the typed JPA readiness registry. */
public final class JpaReadinessRegistryValidator {
private JpaReadinessRegistryValidator() {}
public static List<String> validate(
JpaReadinessRegistry registry, Predicate<String> taskExists) {
List<String> violations = new ArrayList<>();
if (registry.schemaVersion() != 1) {
violations.add("schema-version must be integer 1; got " + registry.schemaVersion());
}
validateLegacy(registry.legacyAdoption(), violations);
Map<String, JpaReadinessCard> cardsById = new HashMap<>();
for (JpaReadinessCard card : registry.cards()) {
cardsById.putIfAbsent(card.id(), card);
}
Map<String, String> taskOwners = new HashMap<>();
Map<String, String> migrationLocationOwners = new HashMap<>();
Map<String, String> migrationHistoryOwners = new HashMap<>();
Map<String, String> evidenceSelectorOwners = new HashMap<>();
for (JpaReadinessCard card : registry.cards()) {
validateCard(
card,
cardsById,
taskExists,
taskOwners,
migrationLocationOwners,
migrationHistoryOwners,
evidenceSelectorOwners,
violations);
}
detectCycles(cardsById, violations);
return List.copyOf(violations);
}
private static void validateLegacy(JpaLegacyAdoption legacy, List<String> violations) {
if (!legacy.state().equals("transition-only")) {
violations.add("legacy-adoption.state must be transition-only");
}
if (!legacy.location().equals("db/migration/postgresql")) {
violations.add("legacy-adoption.location must be db/migration/postgresql");
}
if (!legacy.historyTable().equals("flyway_schema_history")) {
violations.add("legacy-adoption.history-table must be flyway_schema_history");
}
if (!legacy.immutableAppliedVersions().equals(List.of(1, 3, 4, 5))) {
violations.add("legacy-adoption immutable versions must be exactly [1, 3, 4, 5]");
}
if (!legacy.allowedOrigin().equals("LEGACY_ADOPTED")) {
violations.add("legacy-adoption.allowed-origin must be LEGACY_ADOPTED");
}
}
private static void validateCard(
JpaReadinessCard card,
Map<String, JpaReadinessCard> cardsById,
Predicate<String> taskExists,
Map<String, String> taskOwners,
Map<String, String> migrationLocationOwners,
Map<String, String> migrationHistoryOwners,
Map<String, String> evidenceSelectorOwners,
List<String> violations) {
if (hasDuplicates(card.prerequisites())) {
violations.add(card.id() + ": duplicate prerequisites " + card.prerequisites());
}
for (String prerequisite : card.prerequisites()) {
JpaReadinessCard target = cardsById.get(prerequisite);
if (target == null) {
violations.add(card.id() + ": unknown prerequisite '" + prerequisite + "'");
} else if (card.state() == JpaCardState.SELECTED
&& target.state() != JpaCardState.SELECTED) {
violations.add(card.id() + ": selected card requires non-selected '" + prerequisite + "'");
}
}
if (!card.readinessTask().startsWith(":")) {
violations.add(card.id() + ": readiness-task must be an absolute Gradle task path");
}
if (hasDuplicates(card.supportTasks())) {
violations.add(card.id() + ": duplicate support-tasks " + card.supportTasks());
}
for (String task : card.allOwnedTasks()) {
if (!task.startsWith(":")) {
violations.add(card.id() + ": task '" + task + "' must be an absolute Gradle task path");
continue;
}
String previousOwner = taskOwners.putIfAbsent(task, card.id());
if (previousOwner != null && !previousOwner.equals(card.id())) {
violations.add("duplicate task '" + task + "' owned by " + previousOwner + " and " + card.id());
}
if (card.state() == JpaCardState.SELECTED && !taskExists.test(task)) {
violations.add(card.id() + ": selected task does not exist '" + task + "'");
}
}
if (card.requiredEvidence().isEmpty()) {
violations.add(card.id() + ": required-evidence must be a non-empty list");
} else {
if (hasDuplicates(card.requiredEvidence())) {
violations.add(card.id() + ": duplicate required-evidence " + card.requiredEvidence());
}
if (!card.requiredEvidence().contains("no-skip")) {
violations.add(card.id() + ": required-evidence must include no-skip");
}
}
Set<String> allowedEvidenceClaims = new HashSet<>(card.requiredEvidence());
allowedEvidenceClaims.remove("no-skip");
card.migration()
.ifPresent(
migration ->
migration.lifecycleEvidence().forEach(
lifecycle -> allowedEvidenceClaims.add("migration-lifecycle:" + lifecycle)));
if (card.state() == JpaCardState.NOT_IMPLEMENTED) {
if (card.evidence().isPresent()) {
violations.add(card.id() + ": not-implemented card forbids evidence");
}
} else if (card.evidence().isEmpty()) {
violations.add(card.id() + ": active card requires evidence");
} else {
validateEvidence(
card,
card.evidence().orElseThrow(),
allowedEvidenceClaims,
evidenceSelectorOwners,
violations);
}
if (card.schemaStream() == JpaSchemaStream.OWNED) {
if (card.migration().isEmpty()) {
violations.add(card.id() + ": owned schema-stream requires migration");
}
} else if (card.migration().isPresent()) {
violations.add(
card.id() + ": schema-stream " + card.schemaStream().externalValue() + " forbids migration");
}
card.migration()
.ifPresent(
migration ->
validateMigration(
card.id(),
migration,
migrationLocationOwners,
migrationHistoryOwners,
violations));
for (int index = 0; index < card.externalPrerequisites().size(); index++) {
JpaExternalPrerequisite external = card.externalPrerequisites().get(index);
if (!external.registry().startsWith("src/config/")) {
violations.add(card.id() + ": external prerequisite " + index + " has invalid registry");
}
if (!external.cardId().matches("[a-z0-9.-]+")) {
violations.add(card.id() + ": external prerequisite " + index + " has invalid card-id");
}
if (!external.minimumReadiness().matches("R[0-3]")) {
violations.add(card.id() + ": external prerequisite " + index + " has invalid minimum-readiness");
}
}
}
private static void validateEvidence(
JpaReadinessCard card,
JpaCardEvidence evidence,
Set<String> allowedEvidenceClaims,
Map<String, String> evidenceSelectorOwners,
List<String> violations) {
if (evidence.scenarios().isEmpty() && evidence.taskClaims().isEmpty()) {
violations.add(card.id() + ": evidence must contain a scenario or task claim");
}
for (int index = 0; index < evidence.scenarios().size(); index++) {
JpaEvidenceScenario scenario = evidence.scenarios().get(index);
if (!scenario.selector().matches("dev\\.caskeleton\\.[A-Za-z0-9_.]+#[A-Za-z][A-Za-z0-9_]*")) {
violations.add(card.id() + ": invalid evidence selector '" + scenario.selector() + "'");
} else {
String previousOwner = evidenceSelectorOwners.putIfAbsent(scenario.selector(), card.id());
if (previousOwner != null) {
violations.add(
"duplicate evidence selector '"
+ scenario.selector()
+ "' owned by "
+ previousOwner
+ " and "
+ card.id());
}
}
validateCovers(card.id(), "evidence scenario " + index, scenario.covers(), allowedEvidenceClaims, violations);
}
Set<String> ownedTasks = new HashSet<>(card.allOwnedTasks());
for (int index = 0; index < evidence.taskClaims().size(); index++) {
JpaEvidenceTaskClaim claim = evidence.taskClaims().get(index);
if (!ownedTasks.contains(claim.task())) {
violations.add(card.id() + ": evidence task claim is not owned by card '" + claim.task() + "'");
}
validateCovers(card.id(), "evidence task claim " + index, claim.covers(), allowedEvidenceClaims, violations);
}
}
private static void validateCovers(
String cardId,
String label,
List<String> covers,
Set<String> allowedEvidenceClaims,
List<String> violations) {
if (covers.isEmpty()) {
violations.add(cardId + ": " + label + " covers must be non-empty");
}
if (hasDuplicates(covers)) {
violations.add(cardId + ": " + label + " has duplicate covers " + covers);
}
for (String claim : covers) {
if (!allowedEvidenceClaims.contains(claim)) {
violations.add(cardId + ": evidence covers unknown requirement '" + claim + "'");
}
}
}
private static void validateMigration(
String cardId,
JpaMigrationSpec migration,
Map<String, String> migrationLocationOwners,
Map<String, String> migrationHistoryOwners,
List<String> violations) {
if (!migration.location().matches("db/migration/jpa/[a-z0-9-]+")) {
violations.add(cardId + ": invalid migration location '" + migration.location() + "'");
} else {
String previousOwner = migrationLocationOwners.putIfAbsent(migration.location(), cardId);
if (previousOwner != null) {
violations.add(
"duplicate migration location '"
+ migration.location()
+ "' for "
+ previousOwner
+ " and "
+ cardId);
}
}
if (!migration.historyTable().matches("flyway_jpa_[a-z0-9_]+_history")) {
violations.add(cardId + ": invalid migration history-table '" + migration.historyTable() + "'");
} else {
String previousOwner = migrationHistoryOwners.putIfAbsent(migration.historyTable(), cardId);
if (previousOwner != null) {
violations.add(
"duplicate migration history-table '"
+ migration.historyTable()
+ "' for "
+ previousOwner
+ " and "
+ cardId);
}
}
if (migration.requiredCoreEpoch() < 0) {
violations.add(cardId + ": required-core-epoch must be a non-negative integer");
}
if (migration.featureRevision() <= 0) {
violations.add(cardId + ": feature-revision must be a positive integer");
}
if (migration.lifecycleEvidence().isEmpty()) {
violations.add(cardId + ": lifecycle-evidence must be a non-empty list");
} else if (hasDuplicates(migration.lifecycleEvidence())) {
violations.add(cardId + ": duplicate lifecycle-evidence " + migration.lifecycleEvidence());
}
}
private static void detectCycles(
Map<String, JpaReadinessCard> cardsById, List<String> violations) {
Map<String, Integer> visitState = new HashMap<>();
for (String cardId : cardsById.keySet()) {
visit(cardId, cardsById, visitState, violations);
}
}
private static void visit(
String cardId,
Map<String, JpaReadinessCard> cardsById,
Map<String, Integer> visitState,
List<String> violations) {
int state = visitState.getOrDefault(cardId, 0);
if (state == 1) {
violations.add("readiness prerequisite cycle includes '" + cardId + "'");
return;
}
if (state == 2 || !cardsById.containsKey(cardId)) {
return;
}
visitState.put(cardId, 1);
for (String prerequisite : cardsById.get(cardId).prerequisites()) {
visit(prerequisite, cardsById, visitState, violations);
}
visitState.put(cardId, 2);
}
private static boolean hasDuplicates(List<String> values) {
return new HashSet<>(values).size() != values.size();
}
}
@@ -1,10 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.Objects;
public record JpaReleaseDatabase(int major, String supportLevel, String image) {
public JpaReleaseDatabase {
Objects.requireNonNull(supportLevel, "supportLevel");
Objects.requireNonNull(image, "image");
}
}
@@ -1,10 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.Objects;
public record JpaReleaseGate(String name, String task, boolean blocking) {
public JpaReleaseGate {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(task, "task");
}
}
@@ -1,12 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.Objects;
public record JpaReleaseProvider(
String name, String stableTestedBaseline, String compatibilityTarget) {
public JpaReleaseProvider {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(stableTestedBaseline, "stableTestedBaseline");
Objects.requireNonNull(compatibilityTarget, "compatibilityTarget");
}
}
@@ -1,16 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.List;
import java.util.Objects;
public record JpaReleaseRegistry(
int schemaVersion,
List<JpaReleaseDatabase> databases,
JpaReleaseProvider provider,
List<JpaReleaseGate> gates) {
public JpaReleaseRegistry {
databases = List.copyOf(databases);
Objects.requireNonNull(provider, "provider");
gates = List.copyOf(gates);
}
}
@@ -1,133 +0,0 @@
package dev.caskeleton.buildtools.jpa;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
public final class JpaReleaseRegistryParser {
private static final ObjectMapper JSON = JsonMapper.builder().build();
private static final Set<String> ROOT_KEYS =
Set.of("schema-version", "_comment", "databases", "provider", "gates");
private static final Set<String> DATABASE_KEYS =
Set.of("major", "support-level", "image");
private static final Set<String> PROVIDER_KEYS =
Set.of("_comment", "name", "stable-tested-baseline", "compatibility-target");
private static final Set<String> GATE_KEYS = Set.of("name", "task", "blocking");
private JpaReleaseRegistryParser() {}
public static JpaReleaseRegistry parse(String raw) {
JsonNode root = JSON.readTree(raw);
requireObject(root, "root");
requireExactKeys(root, ROOT_KEYS, "root");
List<JpaReleaseDatabase> databases = new ArrayList<>();
JsonNode databasesNode = requiredArray(root, "databases");
int databaseIndex = 0;
for (JsonNode database : databasesNode) {
String name = "databases[" + databaseIndex + "]";
requireObject(database, name);
requireExactKeys(database, DATABASE_KEYS, name);
databases.add(
new JpaReleaseDatabase(
requiredInt(database, "major"),
requiredText(database, "support-level"),
requiredText(database, "image")));
databaseIndex++;
}
JsonNode providerNode = requiredObject(root, "provider");
requireExactKeys(providerNode, PROVIDER_KEYS, "provider");
JpaReleaseProvider provider =
new JpaReleaseProvider(
requiredText(providerNode, "name"),
requiredText(providerNode, "stable-tested-baseline"),
requiredText(providerNode, "compatibility-target"));
List<JpaReleaseGate> gates = new ArrayList<>();
JsonNode gatesNode = requiredArray(root, "gates");
int gateIndex = 0;
for (JsonNode gate : gatesNode) {
String name = "gates[" + gateIndex + "]";
requireObject(gate, name);
requireExactKeys(gate, GATE_KEYS, name);
gates.add(
new JpaReleaseGate(
requiredText(gate, "name"),
requiredText(gate, "task"),
requiredBoolean(gate, "blocking")));
gateIndex++;
}
return new JpaReleaseRegistry(requiredInt(root, "schema-version"), databases, provider, gates);
}
private static JsonNode requiredObject(JsonNode parent, String field) {
JsonNode node = requiredNode(parent, field);
requireObject(node, field);
return node;
}
private static JsonNode requiredArray(JsonNode parent, String field) {
JsonNode node = requiredNode(parent, field);
if (!node.isArray()) {
throw new IllegalStateException(field + " must be a list");
}
return node;
}
private static JsonNode requiredNode(JsonNode parent, String field) {
JsonNode node = parent == null ? null : parent.get(field);
if (node == null || node.isNull()) {
throw new IllegalStateException("missing required field '" + field + "'");
}
return node;
}
private static String requiredText(JsonNode parent, String field) {
JsonNode node = requiredNode(parent, field);
if (!node.isString() || node.asText().isBlank()) {
throw new IllegalStateException("field '" + field + "' must be non-blank text");
}
return node.asText();
}
private static int requiredInt(JsonNode parent, String field) {
JsonNode node = requiredNode(parent, field);
if (!node.isIntegralNumber()) {
throw new IllegalStateException("field '" + field + "' must be an integer");
}
return node.asInt();
}
private static boolean requiredBoolean(JsonNode parent, String field) {
JsonNode node = requiredNode(parent, field);
if (!node.isBoolean()) {
throw new IllegalStateException("field '" + field + "' must be boolean");
}
return node.asBoolean();
}
private static void requireObject(JsonNode node, String name) {
if (node == null || !node.isObject()) {
throw new IllegalStateException(name + " must be an object");
}
}
private static void requireExactKeys(JsonNode node, Set<String> expected, String name) {
Set<String> actual = new HashSet<>();
node.properties().forEach(entry -> actual.add(entry.getKey()));
if (!actual.equals(expected)) {
Set<String> unknown = new java.util.TreeSet<>(actual);
unknown.removeAll(expected);
Set<String> missing = new java.util.TreeSet<>(expected);
missing.removeAll(actual);
throw new IllegalStateException(
name + " keys mismatch; unknown=" + unknown + ", missing=" + missing);
}
}
}
@@ -1,26 +0,0 @@
package dev.caskeleton.buildtools.jpa;
public enum JpaSchemaStream {
NONE("none"),
OWNED("owned"),
CONTRIBUTES_TO_CORE("contributes-to-core");
private final String externalValue;
JpaSchemaStream(String externalValue) {
this.externalValue = externalValue;
}
public String externalValue() {
return externalValue;
}
public static JpaSchemaStream parse(String value) {
for (JpaSchemaStream stream : values()) {
if (stream.externalValue.equals(value)) {
return stream;
}
}
throw new IllegalStateException("invalid JPA schema-stream '" + value + "'");
}
}

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