Files
clean-architecture-backend-…/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java
T
DongHyeonka 6a792b8144 refactor(layout)!: 옮긴 경로를 부르는 곳을 모두 새 배치에 맞춘다
문제: 앞 커밋이 Gradle 루트를 저장소 루트로 옮기고 계층 폴더를 묶었다.
빌드 스크립트·build-logic·시험·workflow·스크립트·문서가 아직 옛 배치
(Gradle 루트 = src/)를 가정해 빌드가 되지 않는다.

고른 방법:
- Gradle 경로와 registry id는 그대로 둔다(:app-bootstrap, :application-core,
  :composition:*). registry의 source_path만 새 폴더를 가리킨다. 폴더에 맞춘
  이름(:domain:core, :application:core)은 프로젝트 이름 core가 둘이 되어
  boot jar의 BOOT-INF/lib와 기본 capability가 겹치고, 파생 서비스의 모든
  project(':…') 줄을 바꾸게 한다.
- registry는 gradle/modules.json, 시험 이미지 목록은
  gradle/container-images.properties: 버전 카탈로그 옆, 빌드가 고정하는 것.
  config/는 코드 검사 도구 설정만 둔다.
- build-logic: settings·architecture 플러그인의 저장소 루트를 Gradle 루트로
  (getParentFile 제거). config contract의 파일 트리는 src/만 훑는다(루트를
  훑으면 docs·.claude/worktrees까지 줍는다).
- 빌드 스크립트: rootProject.projectDir.parentFile → rootProject.projectDir,
  rootProject.file('../…') → rootProject.file('…'), 옛 src 기준 include에
  src/를 붙인다. notification API surface의 application-notification 소스
  루트를 새 폴더로(놓치면 272개 타입이 surface에서 말없이 빠진다).
- 시험: 옛 src 기준 모듈 목록과 ../ 개수를 고친다. 없는 폴더를 말없이
  건너뛰던 목록(MessagingAuthority, NotificationPayloadAtRest 등)을 새
  폴더로, FileserverDocumentationCoverageTest는 Gradle 경로 → 폴더를
  registry로 찾는다. Docker 계약은 WORKDIR /build, 새 jar 경로.
- Docker: 빌드 context를 저장소 루트로, .dockerignore는 허용 목록으로 다시
  써서 전에 context였던 것만 들어가게 한다. compose의 build.context는 .,
  env_file은 ./.env.
- workflow: working-directory: src 기본값과 그것을 되돌리던 줄을 지운다.
- scripts: verify.sh, ci/*, bootstrap-local, new-feature,
  verify-feature-scaffold, mongo 검증, hooks, check-repo-layout 허용 목록.
  check-docs의 경로 검사는 build-logic/·gradle/로 시작하는 경로도 본다.
- 문서: AGENTS.md 지도, README 구조 표, leaf AGENTS.md의 cd src, gates·
  operate·결정 색인, src/bootstrap/AGENTS.md를 조립 계층 family 규칙으로
  다시 쓴다. 기록 문서(docs/design·history·reviews, 지난 upgrade 안내,
  capability-status 제거 표)는 머리 블록만 고친다. 파생 서비스용 안내
  docs/upgrade/2026-11-relayout.md를 더한다.

위험: bootRun working dir가 저장소 루트가 되어 .env와 상대 경로 설정이
루트 기준이다. 루트 .env는 compose 보간에도 읽힌다(upgrade 안내 5절).
파생 서비스는 태그 pre-relayout-2026-11까지 받은 뒤 이 묶음을 받는다.

검증: desktop에서 캐시 없이 scripts/verify.sh docs·pr·main·release,
compose smoke 18 lane, 빠른 시작(scripts/verify.sh app). 결과는 PR 본문.
구조 리뷰(arch-reviewer) 지적 5건을 반영했다.

BREAKING CHANGE: Gradle은 저장소 루트에서 돈다(cd src 없음). registry는
gradle/modules.json, 이미지 빌드 context는 저장소 루트다. 옛 경로 → 새 경로
표는 docs/upgrade/2026-11-relayout.md.
Refs: design-docs repo-structure/01-backend-layout.md 6.1절 가-2·가-3
2026-11-11 22:15:42 +09:00

430 lines
18 KiB
Java

package dev.caskeleton.buildlogic.config;
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.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Repository policy for the operator-facing environment contract. No Gradle API. */
public final class EnvContractVerifier {
private static final Pattern ENV_LINE = Pattern.compile("^([A-Z][A-Z0-9_]*)=.*");
private static final Pattern PLACEHOLDER =
Pattern.compile("\\$\\{([A-Z][A-Z0-9_]*)(:[^}]*)?}");
private static final Pattern SECRET_REFERENCE =
Pattern.compile("secret://environment/(APP_[A-Z][A-Z0-9_]*)");
private static final Pattern REGISTRY_NAME =
Pattern.compile("^\\s*- name: (APP_[A-Z0-9_]+)");
private static final Pattern REGISTRY_FIELD =
Pattern.compile("^\\s*([a-z_]+):\\s*(\\S.*)?$");
private static final Pattern APP_KEY = Pattern.compile("APP_[A-Z][A-Z0-9_]*");
/** A variable a Compose service sets: an {@code APP_*} key of an {@code environment:} map. */
private static final Pattern COMPOSE_ENVIRONMENT_KEY =
Pattern.compile("(?m)^\\s+(APP_[A-Z][A-Z0-9_]*):");
/** A variable Logback reads directly: {@code <springProperty source="APP_*">}. */
private static final Pattern LOGBACK_SOURCE =
Pattern.compile("source=\"(APP_[A-Z][A-Z0-9_]*)\"");
/**
* A variable a JSON object sets: the {@code activationEnv} maps of the Compose lane contract, and
* the smoke wrapper's {@code CAPABILITIES_OFF} literal. An {@code "APP_X=value"} string (an
* argument the wrapper passes on) is not a key and is not matched.
*/
private static final Pattern JSON_KEY = Pattern.compile("\"(APP_[A-Z][A-Z0-9_]*)\"\\s*:");
/** Every variable a JSON object sets, {@code APP_} or not. */
private static final Pattern JSON_VARIABLE_KEY = Pattern.compile("\"([A-Z][A-Z0-9_]*)\"\\s*:");
/** The variable a credential reference names: the last segment of {@code secret://…/<VAR>}. */
private static final Pattern REFERENCED_VARIABLE =
Pattern.compile("secret://[^\\s\"']*/([A-Z][A-Z0-9_]*)");
/**
* Spring Boot's own namespaces: a variable under one is bound to its {@code spring.*}, {@code
* management.*} or {@code server.*} property by relaxed binding, so the framework reads it.
*/
private static final List<String> FRAMEWORK_VARIABLE_PREFIXES =
List.of("SPRING_", "MANAGEMENT_", "SERVER_");
/**
* A list element ({@code APP_HTTPCLIENT_CLIENTS_0_NAME}). Its field template is registered by the
* owning module's field registry ({@code docs/httpclient/env-fields.yaml}, held by that module's
* manifest test and strict binder), not as a row here.
*/
private static final Pattern INDEXED_KEY = Pattern.compile(".*_[0-9]+(_.*)?");
private EnvContractVerifier() {}
/**
* Verifies the contract, and also every {@code APP_*} name the operator-facing files set.
*
* <p>Operator files are what an operator edits or runs to supply values — the root Compose files
* that run the application, {@code logback-spring.xml}, the Compose lane contract and the smoke
* wrapper that drives it. A Compose file contributes the keys of its {@code environment:} maps,
* Logback its {@code springProperty} sources, a JSON file or a shell script the keys of its JSON
* objects (review 2026-11-03 RR-06-07). A name there must be registered, and something must read it:
* a shipped-configuration placeholder, a production source, or a typed property. A variable set
* in a Compose file that nothing reads is a setting the operator believes is in force and is not
* ({@code APP_LOG_JSON_ENABLED} in the prod-smoke file, 07-10).
*
* <p>An operator-file key whose registry row names a {@code property:} counts as read only when
* that property is declared — a registry row alone is what the operator file was already trusted
* for (review 2026-11-04 RR2-04-05). A non-{@code APP_} key of a JSON object counts as read only
* under a Spring Boot namespace or as the variable a {@code secret://…/<VAR>} reference names:
* the {@code CASKELETON_GRPC_ENABLED} switch that started RR-06-07 was neither, and nothing read
* it.
*
* <p>The typed properties under {@code typedPrefixes} and the declared properties an operator key
* may name are read once, from the same classpath, by {@link ConfigurationMetadataClasspath}. They
* used to be two computations — the task read the classpath, the tests a scope file — so the unit
* tests did not see the path the build runs (review 2026-11-04 RR3-04-04).
*
* @param metadataClasspath the composition's classpath with every capability a service can
* select, whose configuration metadata declares the properties
* @param typedPrefixes the property trees whose every typed property needs a registry row
* @param enforcedPrefixes the {@code APP_*} prefixes whose every registered key must be read
* @param operatorFiles the operator-facing files whose {@code APP_*} names are checked
*/
public static EnvContractResult verify(
File envFile,
Collection<File> configurationFiles,
File registryFile,
Collection<File> productionSources,
Collection<File> metadataClasspath,
Collection<String> typedPrefixes,
Collection<String> enforcedPrefixes,
Collection<File> operatorFiles) {
requireFile(
envFile,
"missing "
+ envFile
+ ". The tracked example is the contract an adopter copies; a real .env is operator "
+ "input and is never read here.");
if (configurationFiles.isEmpty()) {
throw new IllegalStateException(
"verifyEnvKeys: no shipped configuration files were supplied for verification");
}
for (File configurationFile : configurationFiles) {
requireFile(configurationFile, "missing shipped configuration " + configurationFile);
}
requireFile(registryFile, "missing " + registryFile);
Set<String> envKeys = new TreeSet<>();
for (String line : readLines(envFile)) {
Matcher matcher = ENV_LINE.matcher(line);
if (matcher.matches()) {
envKeys.add(matcher.group(1));
}
}
Set<String> requiredPlaceholders = new TreeSet<>();
Set<String> allPlaceholders = new TreeSet<>();
Set<String> environmentSecretReferences = new TreeSet<>();
for (File configurationFile : configurationFiles) {
String configuration = read(configurationFile);
Matcher placeholderMatcher = PLACEHOLDER.matcher(configuration);
while (placeholderMatcher.find()) {
allPlaceholders.add(placeholderMatcher.group(1));
if (placeholderMatcher.group(2) == null) {
requiredPlaceholders.add(placeholderMatcher.group(1));
}
}
Matcher secretMatcher = SECRET_REFERENCE.matcher(configuration);
while (secretMatcher.find()) {
environmentSecretReferences.add(secretMatcher.group(1));
}
}
Set<String> applicationAppReferences = new TreeSet<>();
allPlaceholders.stream()
.filter(name -> name.startsWith("APP_"))
.forEach(applicationAppReferences::add);
applicationAppReferences.addAll(environmentSecretReferences);
failUnlessEmpty(
difference(requiredPlaceholders, envKeys),
"shipped configuration references required env absent from .env.example: ");
List<EnvRegistryRow> registryRows = parseRegistryRows(registryFile);
Set<String> registryAppKeys = new TreeSet<>();
Set<String> registryProperties = new TreeSet<>();
for (EnvRegistryRow row : registryRows) {
registryAppKeys.add(row.name());
row.property().ifPresent(registryProperties::add);
}
failUnlessEmpty(
difference(registryAppKeys, envKeys),
"docs/registries/env-keys.yaml registers APP_ keys absent from .env.example, so an "
+ "adopter copying the example never sees them: ");
Set<String> envAppKeys = new TreeSet<>();
envKeys.stream().filter(name -> name.startsWith("APP_")).forEach(envAppKeys::add);
failUnlessEmpty(
difference(envAppKeys, registryAppKeys),
".env.example declares APP_ keys absent from docs/registries/env-keys.yaml "
+ "(registry is the SSOT for APP_ keys): ");
failUnlessEmpty(
difference(applicationAppReferences, registryAppKeys),
"shipped configuration references APP_ keys absent from docs/registries/env-keys.yaml "
+ "(optional defaults and environment secret references are included): ");
Set<String> declared = ConfigurationMetadataClasspath.propertiesUnder(metadataClasspath, "");
Set<String> typedProperties = new TreeSet<>();
Set<String> undeclaredPrefixes = new TreeSet<>();
for (String prefix : typedPrefixes) {
List<String> underPrefix = declared.stream().filter(name -> name.startsWith(prefix)).toList();
if (underPrefix.isEmpty()) {
undeclaredPrefixes.add(prefix);
}
typedProperties.addAll(underPrefix);
}
if (!undeclaredPrefixes.isEmpty()) {
throw new IllegalStateException(
"verifyEnvKeys: no configuration metadata on the classpath declares a property under "
+ undeclaredPrefixes
+ " — put the owning module on the metadata classpath and run its compileJava (the"
+ " annotation processor writes the metadata), or the typed-property check silently"
+ " covers nothing.");
}
failUnlessEmpty(
difference(typedProperties, registryProperties),
"typed configuration properties absent from docs/registries/env-keys.yaml: ",
" — every bindable property needs a registry row carrying its official env name, type, "
+ "default, secret classification and required_when.");
Set<String> scopedRegistryProperties = new TreeSet<>();
for (String property : registryProperties) {
if (typedPrefixes.stream().anyMatch(property::startsWith)) {
scopedRegistryProperties.add(property);
}
}
failUnlessEmpty(
difference(scopedRegistryProperties, typedProperties),
"docs/registries/env-keys.yaml declares properties that no typed settings class binds any more: ",
" — remove the row or restore the property.");
Set<String> consumed = new TreeSet<>(applicationAppReferences);
consumed.addAll(scanProductionSourceConsumers(productionSources));
Set<String> operatorReferences = new TreeSet<>();
Set<String> unreadOperatorVariables = new TreeSet<>();
for (File operatorFile : operatorFiles) {
requireFile(operatorFile, "missing operator file " + operatorFile);
String content = read(operatorFile);
Matcher matcher = operatorKeyPattern(operatorFile.getName()).matcher(content);
while (matcher.find()) {
if (!INDEXED_KEY.matcher(matcher.group(1)).matches()) {
operatorReferences.add(matcher.group(1));
}
}
if (operatorKeyPattern(operatorFile.getName()) == JSON_KEY) {
unreadOperatorVariables.addAll(unreadNonApplicationVariables(content));
}
}
failUnlessEmpty(
difference(operatorReferences, registryAppKeys),
"operator files (Compose, logback-spring.xml, the Compose lane contract, the smoke wrapper)"
+ " set APP_ keys absent from docs/registries/env-keys.yaml: ");
Set<String> typedRows = new TreeSet<>();
registryRows.stream()
.filter(row -> row.property().filter(declared::contains).isPresent())
.forEach(row -> typedRows.add(row.name()));
Set<String> unreadOperatorReferences = new TreeSet<>();
for (String name : operatorReferences) {
if (!consumed.contains(name) && !typedRows.contains(name)) {
unreadOperatorReferences.add(name);
}
}
failUnlessEmpty(
unreadOperatorReferences,
"operator files (Compose, logback-spring.xml, the Compose lane contract, the smoke"
+ " wrapper) set APP_ keys nothing reads — no shipped configuration placeholder,"
+ " production source or typed property: ");
failUnlessEmpty(
unreadOperatorVariables,
"the Compose lane contract or the smoke wrapper sets variables outside APP_ that nothing"
+ " reads — not a Spring Boot namespace (SPRING_, MANAGEMENT_, SERVER_) and not named"
+ " by a secret://…/<VAR> reference: ",
" — a switch spelled this way changes nothing, and the lane can pass for another reason.");
Set<String> unconsumed = new TreeSet<>();
for (EnvRegistryRow row : registryRows) {
if (!consumed.contains(row.name()) && row.property().isEmpty() && !row.deprecatedOrphaned()) {
unconsumed.add(row.name());
}
}
Set<String> unconsumedOwned = new TreeSet<>();
for (String name : unconsumed) {
if (enforcedPrefixes.stream().anyMatch(name::startsWith)) {
unconsumedOwned.add(name);
}
}
if (!unconsumedOwned.isEmpty()) {
throw new IllegalStateException(
"verifyEnvKeys: registered Redis keys that nothing reads — no typed property, no "
+ "shipped-configuration reference, no production consumer, and not marked "
+ "deprecated_orphaned: "
+ unconsumedOwned
+ ". Wire the key to a consumer, or mark the row deprecated_orphaned with a "
+ "removal_deadline so a deployment still setting it is told rather than silently ignored.");
}
Set<String> unconsumedElsewhere = difference(unconsumed, unconsumedOwned);
List<String> warnings = new ArrayList<>();
if (!unconsumedElsewhere.isEmpty()) {
warnings.add(
"registered keys outside the Redis surface that nothing reads yet: "
+ unconsumedElsewhere
+ " — owned by the branch that registered them.");
}
return new EnvContractResult(
envKeys.size(),
requiredPlaceholders.size(),
applicationAppReferences.size(),
typedProperties.size(),
registryRows.size() - unconsumed.size(),
warnings);
}
/**
* The non-{@code APP_} variables a JSON object in {@code content} sets that nothing reads: outside
* Spring Boot's namespaces and named by no {@code secret://} reference in the same file.
*/
private static Set<String> unreadNonApplicationVariables(String content) {
Set<String> referenced = new TreeSet<>();
Matcher reference = REFERENCED_VARIABLE.matcher(content);
while (reference.find()) {
referenced.add(reference.group(1));
}
Set<String> unread = new TreeSet<>();
Matcher variable = JSON_VARIABLE_KEY.matcher(content);
while (variable.find()) {
String name = variable.group(1);
if (!name.startsWith("APP_")
&& FRAMEWORK_VARIABLE_PREFIXES.stream().noneMatch(name::startsWith)
&& !referenced.contains(name)) {
unread.add(name);
}
}
return unread;
}
private static Pattern operatorKeyPattern(String fileName) {
if (fileName.endsWith(".xml")) {
return LOGBACK_SOURCE;
}
if (fileName.endsWith(".json") || fileName.endsWith(".sh")) {
return JSON_KEY;
}
return COMPOSE_ENVIRONMENT_KEY;
}
private static List<EnvRegistryRow> parseRegistryRows(File registryFile) {
List<EnvRegistryRow> rows = new ArrayList<>();
RowBuilder current = null;
for (String line : readLines(registryFile)) {
Matcher nameMatcher = REGISTRY_NAME.matcher(line);
if (nameMatcher.find()) {
if (current != null) {
rows.add(current.build());
}
current = new RowBuilder(nameMatcher.group(1));
continue;
}
if (current == null) {
continue;
}
Matcher fieldMatcher = REGISTRY_FIELD.matcher(line);
if (!fieldMatcher.find()) {
continue;
}
String key = fieldMatcher.group(1);
String value = fieldMatcher.group(2) == null ? "" : fieldMatcher.group(2).trim();
if (key.equals("property")) {
current.property = value;
} else if (key.equals("deprecated_orphaned")) {
current.deprecatedOrphaned = Boolean.parseBoolean(value);
}
}
if (current != null) {
rows.add(current.build());
}
return List.copyOf(rows);
}
private static Set<String> scanProductionSourceConsumers(Collection<File> productionSources) {
Set<String> consumed = new TreeSet<>();
for (File source : productionSources) {
if (!source.isFile()) {
continue;
}
Matcher matcher = APP_KEY.matcher(read(source));
while (matcher.find()) {
consumed.add(matcher.group());
}
}
return consumed;
}
private static void requireFile(File file, String message) {
if (!file.exists()) {
throw new IllegalStateException("verifyEnvKeys: " + message);
}
}
private static void failUnlessEmpty(
Collection<String> values, String prefix) {
failUnlessEmpty(values, prefix, "");
}
private static void failUnlessEmpty(
Collection<String> values, String prefix, String suffix) {
if (!values.isEmpty()) {
throw new IllegalStateException("verifyEnvKeys: " + prefix + values + suffix);
}
}
private static Set<String> difference(Collection<String> left, Collection<String> right) {
Set<String> result = new TreeSet<>(left);
result.removeAll(new HashSet<>(right));
return result;
}
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);
}
}
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);
}
}
private static final class RowBuilder {
private final String name;
private String property;
private boolean deprecatedOrphaned;
private RowBuilder(String name) {
this.name = name;
}
private EnvRegistryRow build() {
return new EnvRegistryRow(name, Optional.ofNullable(property), deprecatedOrphaned);
}
}
}