feat!: 남은 리뷰 발견을 고치고 개발 매뉴얼과 기능 생성 명령을 더한다

문제: High·P1을 고친 뒤에도 P2·P3 약 90건이 남았다. 연결·구독·메시지
크기 상한이 없는 전송(WebSocket·gRPC·GraphQL deadline), 낙관적 충돌의
500, upsert 경쟁, Mongo 무제한 timeout, 샘플 목록 N+1, 갈라진 복사본
(TenantId 3벌, 이벤트 ID 문법 5곳, SQLState 표 2벌), 문서를 읽는 PR
테스트와 캐시를 막는 lane 설정 등이다. 새 기능을 어디에 어떤 순서로
만드는지 알려 주는 문서와 도구가 없었다. MinIO 공식 이미지가 사라져
객체 저장소 lane이 돌지 않았다.

방법: 영역별 묶음으로 실패 테스트를 먼저 쓰고 고쳤다. 고치는 중에 찾은
결함도 함께 고쳤다(durable operation id가 UUIDv4라 이벤트가 전부 DEAD,
S3 어댑터 생성·작은 chunk 읽기 실패, Redis 조건부 기록의 EVALSHA 권한).
MinIO는 pgsty/minio를 digest로 고정했다(Chainguard는 태그·실행 사용자·
mc 이미지 문제로 버림). docs/manual/에 작업 순서와 판단 지점을 쓰고,
scripts/new-feature.sh가 5개 leaf에 뼈대를 만든다. 생성→빌드→통과
왕복을 verifyFeatureScaffold가 mainCheck에서 본다. 묶음별 결과와
결정은 리뷰 README 14절에 있다.

위험·한계: 파생 서비스 동작이 바뀐다. JDBC batch 50 기본, 운영 jar에서
H2 제거, 트랜잭션 30초 제한, 격리 수준을 Hikari에서 고정, gRPC·
WebSocket·GraphQL 새 한도, correlation ID 규칙 밖이면 서버가 교체,
샘플 키 오류 코드 IDEMPOTENCY_KEY_INVALID. 새 leaf 두 개
(composition:durable-operation, adapter:inbound:messaging)와 새
마이그레이션(postgresql V20·V21, notification V11·V12, sample V8_1,
grpc-ledger V002)이 생긴다. V21 유일 인덱스는 기존 중복이 있으면
실패한다(runbook에 확인 쿼리).

검증: ci, mainCheck(생성 명령 왕복 포함), integrationCheck(MinIO 포함
전 컨테이너 lane), -p optional-platforms ci integrationCheck 통과.

Refs: docs/reviews/2026-11-01-maturity-review/README.md 14절
BREAKING CHANGE: JDBC batch 기본 켜짐, H2 운영 의존 제거, 트랜잭션
기본 제한 30초, gRPC·WebSocket·GraphQL 서버 한도 기본값 추가,
샘플 Idempotency-Key 오류 코드 변경.
This commit is contained in:
DongHyeonka
2026-11-03 19:52:06 +09:00
parent 34565130e0
commit 1400dc1506
768 changed files with 26982 additions and 3348 deletions
@@ -0,0 +1,12 @@
package dev.caskeleton.adapter.inbound.web.__feature__;
/**
* The body of {@code POST /__featurePath__}.
*
* <p>No bean-validation constraint on {@code name}: the aggregate owns the rule (blank, length) and
* answers {@code __FEATURE___INVALID}. A constraint here would be a second copy of that rule that can
* drift from the first. Put a constraint here only for what the domain cannot see — the wire shape.
*
* @param name the requested name
*/
public record Create__Feature__HttpRequest(String name) {}
@@ -0,0 +1,69 @@
package dev.caskeleton.adapter.inbound.web.__feature__;
import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory;
import dev.caskeleton.application.__feature__.Create__Feature__Command;
import dev.caskeleton.application.__feature__.Create__Feature__UseCase;
import dev.caskeleton.application.__feature__.Get__Feature__Query;
import dev.caskeleton.application.__feature__.Get__Feature__UseCase;
import dev.caskeleton.application.__feature__.__Feature__View;
import dev.caskeleton.domain.__feature__.__Feature__Id;
import dev.caskeleton.shared.response.Envelope;
import java.net.URI;
import java.util.Objects;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
/**
* __Feature__ over HTTP. A transport only: it turns the request into a command or query, calls the
* use case and wraps the view in an {@link Envelope}. Who may create is the use case's {@code
* @RequiresPermission}; failures are {@code ApiErrorCarrier}s the global handler maps.
*
* <p>Registered by {@code __Feature__Config} in app-bootstrap, which exists only when a {@code
* __Feature__Repository} adapter is on the classpath; not found by a component scan.
*/
@RestController
@RequestMapping("/__featurePath__")
public class __Feature__Controller {
private final Create__Feature__UseCase create;
private final Get__Feature__UseCase get;
/**
* A controller over the two use cases.
*
* @param create creates a __Feature__
* @param get reads one
*/
public __Feature__Controller(Create__Feature__UseCase create, Get__Feature__UseCase get) {
this.create = Objects.requireNonNull(create, "create");
this.get = Objects.requireNonNull(get, "get");
}
/** Creates one; {@code 201} with its {@code Location}. */
@PostMapping
public ResponseEntity<Envelope<__Feature__HttpResponse>> create(
@RequestBody Create__Feature__HttpRequest request) {
__Feature__View created = create.handle(new Create__Feature__Command(request.name()));
URI location =
ServletUriComponentsBuilder.fromCurrentRequestUri()
.path("/{id}")
.buildAndExpand(created.id())
.toUri();
return ResponseEntity.created(location)
.body(Envelope.ok(__Feature__HttpResponse.from(created), ResponseMetaFactory.fromMdc()));
}
/** Reads one; {@code 404 __FEATURE___NOT_FOUND} when none has the id. */
@GetMapping("/{id}")
public ResponseEntity<Envelope<__Feature__HttpResponse>> get(@PathVariable String id) {
__Feature__View found = get.handle(new Get__Feature__Query(__Feature__Id.of(id)));
return ResponseEntity.ok(
Envelope.ok(__Feature__HttpResponse.from(found), ResponseMetaFactory.fromMdc()));
}
}
@@ -0,0 +1,17 @@
package dev.caskeleton.adapter.inbound.web.__feature__;
import dev.caskeleton.application.__feature__.__Feature__View;
/**
* One __Feature__ on the wire. Its own type, so a change to the application view is a decision here
* rather than a silent change of the HTTP contract.
*
* @param id the identifier
* @param name the name
*/
public record __Feature__HttpResponse(String id, String name) {
static __Feature__HttpResponse from(__Feature__View view) {
return new __Feature__HttpResponse(view.id(), view.name());
}
}
@@ -0,0 +1,98 @@
package dev.caskeleton.adapter.inbound.web.__feature__;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice;
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
import dev.caskeleton.application.__feature__.Create__Feature__UseCase;
import dev.caskeleton.application.__feature__.Get__Feature__UseCase;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
import dev.caskeleton.domain.__feature__.__Feature__;
import dev.caskeleton.domain.__feature__.__Feature__Id;
import dev.caskeleton.domain.__feature__.testkit.InMemory__Feature__Repository;
import dev.caskeleton.domain.__feature__.testkit.Sequential__Feature__IdFactory;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
/**
* The HTTP contract of {@code /__featurePath__} over the real use cases and the port owners' fakes.
*
* <p>Standalone MockMvc: no security filter chain and no method-security proxy, so the permission
* on create is not exercised here. The composition test in app-bootstrap builds the beans the proxy
* wraps.
*/
class __Feature__ControllerTest {
private static final __Feature__Id STORED = Sequential__Feature__IdFactory.idAt(1);
private final InMemory__Feature__Repository repository = new InMemory__Feature__Repository();
private final DirectTransactionPort tx = new DirectTransactionPort();
private final MockMvc mvc =
MockMvcBuilders.standaloneSetup(
new __Feature__Controller(
new Create__Feature__UseCase(
repository, new Sequential__Feature__IdFactory(), tx),
new Get__Feature__UseCase(repository, tx)))
.setControllerAdvice(
new GlobalExceptionHandler(SpanErrorRecorder.NOOP), new EnvelopeBodyAdvice())
.build();
@Test
void aCreateAnswers201WithTheNewResourcesLocation() throws Exception {
// when
ResultActions response = create("{\"name\":\"first\"}");
// then
response
.andExpect(status().isCreated())
.andExpect(header().string("Location", "http://localhost/__featurePath__/" + STORED.value()))
.andExpect(jsonPath("$.data.name").value("first"));
}
@Test
void aBlankNameAnswers400WithTheFeaturesOwnCode() throws Exception {
// when
ResultActions response = create("{\"name\":\" \"}");
// then
response
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.error.code").value("__FEATURE___INVALID"));
}
@Test
void aStored__Feature__IsReadWith200() throws Exception {
// given
repository.save(__Feature__.create(STORED, "first"));
// when
ResultActions response = mvc.perform(get("/__featurePath__/" + STORED.value()));
// then
response.andExpect(status().isOk()).andExpect(jsonPath("$.data.name").value("first"));
}
@Test
void anUnknownIdAnswers404WithTheFeaturesOwnCode() throws Exception {
// when
ResultActions response = mvc.perform(get("/__featurePath__/" + STORED.value()));
// then
response
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.error.code").value("__FEATURE___NOT_FOUND"));
}
private ResultActions create(String body) throws Exception {
return mvc.perform(
post("/__featurePath__").contentType(MediaType.APPLICATION_JSON).content(body));
}
}
@@ -0,0 +1,20 @@
package dev.caskeleton.adapter.outbound.identifier.__feature__;
import dev.caskeleton.domain.__feature__.__Feature__Id;
import dev.caskeleton.domain.__feature__.__Feature__IdFactory;
import java.util.UUID;
/**
* Mints {@link __Feature__Id}s as random (version 4) UUIDs from the JDK's secure generator.
*
* <p>Random UUIDs scatter inserts across a B-tree primary key. When __Feature__ rows are written
* often, switch to a time-ordered UUIDv7 as the sample's {@code UuidWorkLogIdFactory} does; the
* domain contract (canonical UUID text) does not change.
*/
public final class Uuid__Feature__IdFactory implements __Feature__IdFactory {
@Override
public __Feature__Id newId() {
return __Feature__Id.of(UUID.randomUUID().toString());
}
}
@@ -0,0 +1,24 @@
package dev.caskeleton.adapter.outbound.identifier.__feature__;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.domain.__feature__.__Feature__Id;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
class Uuid__Feature__IdFactoryTest {
private final Uuid__Feature__IdFactory factory = new Uuid__Feature__IdFactory();
@Test
void aThousandMintedIdsAreAllDifferent() {
// when
Set<__Feature__Id> ids =
IntStream.range(0, 1000).mapToObj(i -> factory.newId()).collect(Collectors.toSet());
// then
assertThat(ids).hasSize(1000);
}
}
@@ -0,0 +1,56 @@
package dev.caskeleton.bootstrap.autoconfigure.__feature__;
import dev.caskeleton.adapter.inbound.web.__feature__.__Feature__Controller;
import dev.caskeleton.adapter.outbound.identifier.__feature__.Uuid__Feature__IdFactory;
import dev.caskeleton.application.__feature__.Create__Feature__UseCase;
import dev.caskeleton.application.__feature__.Get__Feature__UseCase;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.domain.__feature__.__Feature__IdFactory;
import dev.caskeleton.domain.__feature__.__Feature__Repository;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
/**
* __Feature__: its use cases and its HTTP endpoints.
*
* <p>Turns itself on from what is on the classpath: a {@link __Feature__Repository} adapter and a
* {@link TransactionPort}. Until a repository adapter exists the feature is absent rather than half
* present (docs/manual/02-new-feature.md step 5). When the adapter comes from another
* auto-configuration, name it in {@code afterName} so this condition sees its bean.
*
* <p>The use cases are beans, not objects the controller builds, because the method security
* advisor proxies beans: {@code @RequiresPermission} on create is enforced by that proxy. Grant
* {@code __feature_kebab__:create} to a role under {@code app.authz.role-permissions}; until then
* every create is refused (docs/manual/07-authorization.md).
*/
@AutoConfiguration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnBean({__Feature__Repository.class, TransactionPort.class})
@Import(__Feature__Controller.class)
public class __Feature__Config {
/** Server-assigned ids, unless the application supplies its own factory. */
@Bean
@ConditionalOnMissingBean(__Feature__IdFactory.class)
public __Feature__IdFactory __featureCamel__IdFactory() {
return new Uuid__Feature__IdFactory();
}
/** Creates a __Feature__. */
@Bean
public Create__Feature__UseCase create__Feature__UseCase(
__Feature__Repository repository, __Feature__IdFactory ids, TransactionPort transactions) {
return new Create__Feature__UseCase(repository, ids, transactions);
}
/** Reads one __Feature__. */
@Bean
public Get__Feature__UseCase get__Feature__UseCase(
__Feature__Repository repository, TransactionPort transactions) {
return new Get__Feature__UseCase(repository, transactions);
}
}
@@ -0,0 +1,52 @@
package dev.caskeleton.bootstrap.autoconfigure.__feature__;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.web.__feature__.__Feature__Controller;
import dev.caskeleton.application.__feature__.Create__Feature__UseCase;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
import dev.caskeleton.domain.__feature__.__Feature__Repository;
import dev.caskeleton.domain.__feature__.testkit.InMemory__Feature__Repository;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.context.annotation.ImportCandidates;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
class __Feature__ConfigTest {
private final WebApplicationContextRunner runner =
new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(__Feature__Config.class));
@Test
void bootDiscoversTheConfigurationThroughItsAutoConfigurationImports() {
// when
List<String> candidates =
ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader()).getCandidates();
// then
assertThat(candidates).contains(__Feature__Config.class.getName());
}
@Test
void withoutARepositoryAdapterTheFeatureIsAbsent() {
runner
.withBean(TransactionPort.class, DirectTransactionPort::new)
.run(context -> assertThat(context).doesNotHaveBean(__Feature__Controller.class));
}
@Test
void withARepositoryAdapterTheUseCasesAndTheControllerAreBeans() {
runner
.withBean(TransactionPort.class, DirectTransactionPort::new)
.withBean(__Feature__Repository.class, InMemory__Feature__Repository::new)
.run(
context ->
assertThat(context)
.hasSingleBean(Create__Feature__UseCase.class)
.hasSingleBean(__Feature__Controller.class));
}
}
@@ -0,0 +1,10 @@
package dev.caskeleton.application.__feature__;
import dev.caskeleton.application.command.Command;
/**
* The intent to create a __Feature__. Carries plain values; the aggregate checks them.
*
* @param name the requested name
*/
public record Create__Feature__Command(String name) implements Command {}
@@ -0,0 +1,63 @@
package dev.caskeleton.application.__feature__;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.CommandUseCase;
import dev.caskeleton.domain.__feature__.__Feature__;
import dev.caskeleton.domain.__feature__.__Feature__IdFactory;
import dev.caskeleton.domain.__feature__.__Feature__InvariantException;
import dev.caskeleton.domain.__feature__.__Feature__Repository;
/**
* Creates a __Feature__ under a server-minted id.
*
* <p>Not {@code final} and built as a bean: {@code @RequiresPermission} is enforced by the method
* security proxy around the bean, and a class that cannot be proxied fails the boot
* ({@code RequiresPermissionProxyabilityTest}). {@code NOT_IDEMPOTENT}: a retried request creates a
* second __Feature__. Make it {@code KEYED} with {@code IdempotencyExecutor} when a client may
* resend (docs/manual/05-idempotency.md).
*/
@RequiresPermission("__feature_kebab__:create")
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
idempotency = Idempotency.NOT_IDEMPOTENT,
repositoryAccess = RepositoryAccess.WRITE_REPOSITORY)
public class Create__Feature__UseCase
implements CommandUseCase<Create__Feature__Command, __Feature__View> {
private final __Feature__Repository repository;
private final __Feature__IdFactory ids;
private final TransactionPort tx;
/**
* A use case over its ports.
*
* @param repository where the aggregate is stored
* @param ids mints the new id
* @param tx the transaction boundary
*/
public Create__Feature__UseCase(
__Feature__Repository repository, __Feature__IdFactory ids, TransactionPort tx) {
this.repository = repository;
this.ids = ids;
this.tx = tx;
}
@Override
public __Feature__View handle(Create__Feature__Command command) {
__Feature__ created = build(command);
return tx.inWrite(() -> __Feature__View.from(repository.save(created)));
}
private __Feature__ build(Create__Feature__Command command) {
try {
return __Feature__.create(ids.newId(), command.name());
} catch (__Feature__InvariantException invalid) {
throw new __Feature__RejectedException(invalid);
}
}
}
@@ -0,0 +1,17 @@
package dev.caskeleton.application.__feature__;
import dev.caskeleton.application.query.Query;
import dev.caskeleton.domain.__feature__.__Feature__Id;
import java.util.Objects;
/**
* The intent to read one __Feature__.
*
* @param id the identifier to read
*/
public record Get__Feature__Query(__Feature__Id id) implements Query {
public Get__Feature__Query {
Objects.requireNonNull(id, "id");
}
}
@@ -0,0 +1,45 @@
package dev.caskeleton.application.__feature__;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.QueryUseCase;
import dev.caskeleton.domain.__feature__.__Feature__Repository;
/**
* Reads one __Feature__. A read needs no {@code @RequiresPermission}; add one, or an object access
* check, when not every authenticated caller may see every __Feature__
* (docs/manual/07-authorization.md).
*/
@UseCaseCapability(
transactionMode = TransactionMode.READ_ONLY,
idempotency = Idempotency.IDEMPOTENT,
repositoryAccess = RepositoryAccess.READ_REPOSITORY)
public class Get__Feature__UseCase implements QueryUseCase<Get__Feature__Query, __Feature__View> {
private final __Feature__Repository repository;
private final TransactionPort tx;
/**
* A use case over its ports.
*
* @param repository where the aggregate is read from
* @param tx the transaction boundary
*/
public Get__Feature__UseCase(__Feature__Repository repository, TransactionPort tx) {
this.repository = repository;
this.tx = tx;
}
@Override
public __Feature__View handle(Get__Feature__Query query) {
return tx.inRead(
() ->
repository
.findById(query.id())
.map(__Feature__View::from)
.orElseThrow(() -> new __Feature__NotFoundException(query.id())));
}
}
@@ -0,0 +1,42 @@
package dev.caskeleton.application.__feature__;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.Category;
/**
* The client-facing failures of the __Feature__ use cases. Every transport maps them through {@code
* ApiErrorCarrier}; no handler names this feature. A service records its own codes in its own
* registry, not in docs/registries/error-codes.yaml (docs/manual/06-errors.md).
*/
public enum __Feature__ErrorCode implements ApiErrorCode {
__FEATURE___NOT_FOUND(Category.NOT_FOUND, 404),
__FEATURE___INVALID(Category.VALIDATION, 400);
private final Category category;
private final int httpStatus;
__Feature__ErrorCode(Category category, int httpStatus) {
this.category = category;
this.httpStatus = httpStatus;
}
@Override
public String code() {
return name();
}
@Override
public Category category() {
return category;
}
@Override
public int httpStatus() {
return httpStatus;
}
@Override
public boolean retryable() {
return false;
}
}
@@ -0,0 +1,25 @@
package dev.caskeleton.application.__feature__;
import dev.caskeleton.domain.__feature__.__Feature__Id;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
/** No __Feature__ has the requested id. A client error: {@code __FEATURE___NOT_FOUND}, 404. */
public class __Feature__NotFoundException extends RuntimeException implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
/**
* The failure for one id.
*
* @param id the id that was not found
*/
public __Feature__NotFoundException(__Feature__Id id) {
super("__Feature__ not found: " + id.value());
}
@Override
public ApiErrorCode errorCode() {
return __Feature__ErrorCode.__FEATURE___NOT_FOUND;
}
}
@@ -0,0 +1,29 @@
package dev.caskeleton.application.__feature__;
import dev.caskeleton.domain.__feature__.__Feature__InvariantException;
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
/**
* The request asked for a __Feature__ that breaks an invariant. A client error: {@code
* __FEATURE___INVALID}, 400. The domain exception stays the cause, so its {@code reason()} reaches
* the logs; only the code reaches the client.
*/
public class __Feature__RejectedException extends RuntimeException implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
/**
* Wraps the broken invariant.
*
* @param cause the domain failure
*/
public __Feature__RejectedException(__Feature__InvariantException cause) {
super("__Feature__ rejected: " + cause.reason(), cause);
}
@Override
public ApiErrorCode errorCode() {
return __Feature__ErrorCode.__FEATURE___INVALID;
}
}
@@ -0,0 +1,17 @@
package dev.caskeleton.application.__feature__;
import dev.caskeleton.domain.__feature__.__Feature__;
/**
* What a use case hands back about one __Feature__. An application type, so a transport never
* receives the aggregate itself.
*
* @param id the identifier text
* @param name the name
*/
public record __Feature__View(String id, String name) {
static __Feature__View from(__Feature__ aggregate) {
return new __Feature__View(aggregate.id().value(), aggregate.name());
}
}
@@ -0,0 +1,47 @@
package dev.caskeleton.application.__feature__;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
import dev.caskeleton.domain.__feature__.testkit.InMemory__Feature__Repository;
import dev.caskeleton.domain.__feature__.testkit.Sequential__Feature__IdFactory;
import org.junit.jupiter.api.Test;
class Create__Feature__UseCaseTest {
private final InMemory__Feature__Repository repository = new InMemory__Feature__Repository();
private final DirectTransactionPort tx = new DirectTransactionPort();
private final Create__Feature__UseCase useCase =
new Create__Feature__UseCase(repository, new Sequential__Feature__IdFactory(), tx);
@Test
void aCreated__Feature__IsStoredUnderTheMintedId() {
// when
useCase.handle(new Create__Feature__Command("first"));
// then
assertThat(repository.findById(Sequential__Feature__IdFactory.idAt(1)).map(found -> found.name()))
.contains("first");
}
@Test
void theCreateCommitsOneWriteTransaction() {
// when
useCase.handle(new Create__Feature__Command("first"));
// then
assertThat(tx.committed()).containsExactly(DirectTransactionPort.Boundary.WRITE);
}
@Test
void aBlankNameIsRejectedWithTheFeaturesInvalidCode() {
// when
Throwable thrown = catchThrowable(() -> useCase.handle(new Create__Feature__Command(" ")));
// then
assertThat(thrown)
.isInstanceOfSatisfying(
__Feature__RejectedException.class, failure -> assertThat(failure.errorCode()).isEqualTo(__Feature__ErrorCode.__FEATURE___INVALID));
}
}
@@ -0,0 +1,43 @@
package dev.caskeleton.application.__feature__;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
import dev.caskeleton.domain.__feature__.__Feature__;
import dev.caskeleton.domain.__feature__.__Feature__Id;
import dev.caskeleton.domain.__feature__.testkit.InMemory__Feature__Repository;
import dev.caskeleton.domain.__feature__.testkit.Sequential__Feature__IdFactory;
import org.junit.jupiter.api.Test;
class Get__Feature__UseCaseTest {
private static final __Feature__Id STORED = Sequential__Feature__IdFactory.idAt(1);
private final InMemory__Feature__Repository repository = new InMemory__Feature__Repository();
private final Get__Feature__UseCase useCase =
new Get__Feature__UseCase(repository, new DirectTransactionPort());
@Test
void aStored__Feature__IsReadAsItsView() {
// given
repository.save(__Feature__.create(STORED, "first"));
// when
__Feature__View view = useCase.handle(new Get__Feature__Query(STORED));
// then
assertThat(view).isEqualTo(new __Feature__View(STORED.value(), "first"));
}
@Test
void anIdNothingIsStoredUnderIsNotFound() {
// when
Throwable thrown = catchThrowable(() -> useCase.handle(new Get__Feature__Query(STORED)));
// then
assertThat(thrown)
.isInstanceOfSatisfying(
__Feature__NotFoundException.class, failure -> assertThat(failure.errorCode()).isEqualTo(__Feature__ErrorCode.__FEATURE___NOT_FOUND));
}
}
@@ -0,0 +1,68 @@
package dev.caskeleton.domain.__feature__;
import dev.caskeleton.domain.stereotype.AggregateRoot;
import java.util.Objects;
/**
* The __Feature__ aggregate root: the only way its state changes.
*
* <p>Generated by {@code scripts/new-feature.sh} with one placeholder field, {@code name}. Replace it
* with the feature's real state and keep each invariant in this class: a rule that must always hold
* for one __Feature__ belongs here, not in a use case or a mapper (docs/manual/02-new-feature.md).
*/
@AggregateRoot
public final class __Feature__ {
/** The longest name a __Feature__ accepts; the database column is sized to it. */
public static final int NAME_MAX_LENGTH = 100;
private final __Feature__Id id;
private final String name;
private __Feature__(__Feature__Id id, String name) {
this.id = Objects.requireNonNull(id, "id");
this.name = requireValidName(name);
}
/**
* A new __Feature__.
*
* @param id the server-assigned identifier
* @param name the name; not blank, at most {@link #NAME_MAX_LENGTH} characters
* @return the new aggregate
* @throws __Feature__InvariantException when the name breaks an invariant
*/
public static __Feature__ create(__Feature__Id id, String name) {
return new __Feature__(id, name);
}
/**
* A __Feature__ read back from storage. The same invariants hold: stored state that breaks them
* is a defect, and it fails here rather than later.
*
* @param id the stored identifier
* @param name the stored name
* @return the aggregate
*/
public static __Feature__ restore(__Feature__Id id, String name) {
return new __Feature__(id, name);
}
public __Feature__Id id() {
return id;
}
public String name() {
return name;
}
private static String requireValidName(String name) {
if (name == null || name.isBlank()) {
throw new __Feature__InvariantException(__Feature__InvariantException.Reason.NAME_BLANK);
}
if (name.length() > NAME_MAX_LENGTH) {
throw new __Feature__InvariantException(__Feature__InvariantException.Reason.NAME_TOO_LONG);
}
return name;
}
}
@@ -0,0 +1,38 @@
package dev.caskeleton.domain.__feature__;
import dev.caskeleton.domain.identifier.ResourceId;
import dev.caskeleton.domain.stereotype.ValueObject;
import java.util.regex.Pattern;
/**
* Identifier of a {@link __Feature__}: the canonical 36-character UUID text. The grammar is checked
* here, at construction, so every layer that holds a __Feature__Id holds a valid one.
*/
@ValueObject
public record __Feature__Id(String value) implements ResourceId<__Feature__Id> {
private static final Pattern CANONICAL_UUID =
Pattern.compile(
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
/**
* Checks the grammar.
*
* @throws IllegalArgumentException when {@code value} is not canonical UUID text
*/
public __Feature__Id {
if (value == null || !CANONICAL_UUID.matcher(value).matches()) {
throw new IllegalArgumentException("invalid __Feature__Id: " + value);
}
}
/**
* Parses identifier text.
*
* @param value canonical UUID text
* @return the identifier
*/
public static __Feature__Id of(String value) {
return new __Feature__Id(value);
}
}
@@ -0,0 +1,9 @@
package dev.caskeleton.domain.__feature__;
import dev.caskeleton.domain.identifier.IdFactory;
/**
* Mints new {@link __Feature__Id}s. The domain owns the contract; an outbound adapter ({@code
* adapter:outbound:identifier}) generates the value, and the create use case calls it.
*/
public interface __Feature__IdFactory extends IdFactory<__Feature__Id> {}
@@ -0,0 +1,33 @@
package dev.caskeleton.domain.__feature__;
/**
* A {@link __Feature__} invariant was broken. Carries a {@link Reason} and nothing about error
* codes or HTTP: the application turns it into a client error ({@code
* Create__Feature__UseCase}), because domain-core cannot see shared-contract.
*/
public final class __Feature__InvariantException extends RuntimeException {
private static final long serialVersionUID = 1L;
/** Which invariant was broken. Safe to show a client. */
public enum Reason {
NAME_BLANK,
NAME_TOO_LONG
}
private final Reason reason;
/**
* An invariant failure.
*
* @param reason which invariant was broken
*/
public __Feature__InvariantException(Reason reason) {
super("__Feature__ invariant violated: " + reason);
this.reason = reason;
}
public Reason reason() {
return reason;
}
}
@@ -0,0 +1,30 @@
package dev.caskeleton.domain.__feature__;
import java.util.Optional;
/**
* Stores and loads {@link __Feature__} aggregates, one whole aggregate at a time.
*
* <p>Domain-owned because it speaks only in aggregates. A read whose shape differs from the
* aggregate is a separate application {@code *QueryPort} returning a projection
* (docs/manual/02-new-feature.md, decision "저장 포트 소유자"). Every implementation passes {@code
* __Feature__RepositoryContract} in this module's test fixtures.
*/
public interface __Feature__Repository {
/**
* Saves the aggregate, inserting it or replacing the stored state with the same id.
*
* @param aggregate the aggregate to store
* @return the stored aggregate as the store now holds it
*/
__Feature__ save(__Feature__ aggregate);
/**
* Loads one aggregate.
*
* @param id the identifier
* @return the aggregate, or empty when none has that id
*/
Optional<__Feature__> findById(__Feature__Id id);
}
@@ -0,0 +1,31 @@
package dev.caskeleton.domain.__feature__;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
class __Feature__IdTest {
@Test
void canonicalUuidTextIsAccepted() {
assertThat(__Feature__Id.of("0190a3c4-7b2e-7d4f-9a1b-2c3d4e5f6a7b").value())
.isEqualTo("0190a3c4-7b2e-7d4f-9a1b-2c3d4e5f6a7b");
}
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {"not-a-uuid", "0190a3c47b2e7d4f9a1b2c3d4e5f6a7b", "1"})
void textThatIsNotCanonicalUuidIsRejected(String value) {
// when
Throwable thrown = catchThrowable(() -> __Feature__Id.of(value));
// then
assertThat(thrown)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageStartingWith("invalid __Feature__Id");
}
}
@@ -0,0 +1,53 @@
package dev.caskeleton.domain.__feature__;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
class __Feature__Test {
private static final __Feature__Id ID =
__Feature__Id.of("00000000-0000-7000-8000-000000000001");
@Test
void aCreated__Feature__KeepsItsIdAndName() {
// when
__Feature__ created = __Feature__.create(ID, "first");
// then
assertThat(created).extracting(__Feature__::id, __Feature__::name).containsExactly(ID, "first");
}
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {" ", "\t"})
void aBlankNameIsRejected(String name) {
// when
Throwable thrown = catchThrowable(() -> __Feature__.create(ID, name));
// then
assertThat(thrown)
.isInstanceOf(__Feature__InvariantException.class)
.hasFieldOrPropertyWithValue("reason", __Feature__InvariantException.Reason.NAME_BLANK);
}
@Test
@DisplayName("이름이 NAME_MAX_LENGTH + 1자이면 거절한다")
void aNameLongerThanTheLimitIsRejected() {
// given
String name = "x".repeat(__Feature__.NAME_MAX_LENGTH + 1);
// when
Throwable thrown = catchThrowable(() -> __Feature__.create(ID, name));
// then
assertThat(thrown)
.isInstanceOf(__Feature__InvariantException.class)
.hasFieldOrPropertyWithValue("reason", __Feature__InvariantException.Reason.NAME_TOO_LONG);
}
}
@@ -0,0 +1,13 @@
package dev.caskeleton.domain.__feature__.testkit;
import dev.caskeleton.domain.__feature__.__Feature__Repository;
class InMemory__Feature__RepositoryContractTest extends __Feature__RepositoryContract {
private final InMemory__Feature__Repository repository = new InMemory__Feature__Repository();
@Override
protected __Feature__Repository repository() {
return repository;
}
}
@@ -0,0 +1,29 @@
package dev.caskeleton.domain.__feature__.testkit;
import dev.caskeleton.domain.__feature__.__Feature__;
import dev.caskeleton.domain.__feature__.__Feature__Id;
import dev.caskeleton.domain.__feature__.__Feature__Repository;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
/**
* The one fake of {@link __Feature__Repository}, held to the same promises as every real adapter by
* {@link __Feature__RepositoryContract}. Not thread-safe: a use case test is single-threaded.
*/
public final class InMemory__Feature__Repository implements __Feature__Repository {
private final Map<__Feature__Id, __Feature__> rows = new LinkedHashMap<>();
@Override
public __Feature__ save(__Feature__ aggregate) {
__Feature__ stored = __Feature__.restore(aggregate.id(), aggregate.name());
rows.put(stored.id(), stored);
return __Feature__.restore(stored.id(), stored.name());
}
@Override
public Optional<__Feature__> findById(__Feature__Id id) {
return Optional.ofNullable(rows.get(id)).map(row -> __Feature__.restore(row.id(), row.name()));
}
}
@@ -0,0 +1,29 @@
package dev.caskeleton.domain.__feature__.testkit;
import dev.caskeleton.domain.__feature__.__Feature__Id;
import dev.caskeleton.domain.__feature__.__Feature__IdFactory;
import java.util.concurrent.atomic.AtomicLong;
/**
* The one fake of {@link __Feature__IdFactory}: predictable ids, so a test can name the id a create
* will mint ({@link #idAt(long)}).
*/
public final class Sequential__Feature__IdFactory implements __Feature__IdFactory {
private final AtomicLong next = new AtomicLong(1);
/**
* The id this factory mints on its {@code n}th call, counting from 1.
*
* @param n the call number
* @return that id
*/
public static __Feature__Id idAt(long n) {
return __Feature__Id.of(String.format("00000000-0000-7000-8000-%012d", n));
}
@Override
public __Feature__Id newId() {
return idAt(next.getAndIncrement());
}
}
@@ -0,0 +1,56 @@
package dev.caskeleton.domain.__feature__.testkit;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.domain.__feature__.__Feature__;
import dev.caskeleton.domain.__feature__.__Feature__Id;
import dev.caskeleton.domain.__feature__.__Feature__Repository;
import java.util.Optional;
import org.junit.jupiter.api.Test;
/**
* What every {@link __Feature__Repository} promises. {@link InMemory__Feature__Repository} extends
* it in domain-core's tests; a real adapter extends it in a lane that runs against its real store
* (docs/manual/04-persistence.md). Add a test here before adding a repository method.
*/
public abstract class __Feature__RepositoryContract {
private static final __Feature__Id FIRST = Sequential__Feature__IdFactory.idAt(1);
private static final __Feature__Id UNKNOWN = Sequential__Feature__IdFactory.idAt(99);
/**
* The repository under test, empty at the start of each test.
*
* @return the repository
*/
protected abstract __Feature__Repository repository();
@Test
void aSaved__Feature__IsFoundByItsId() {
// given
repository().save(__Feature__.create(FIRST, "first"));
// when
Optional<__Feature__> found = repository().findById(FIRST);
// then
assertThat(found.map(__Feature__::name)).contains("first");
}
@Test
void anIdNothingWasSavedUnderIsNotFound() {
assertThat(repository().findById(UNKNOWN)).isEmpty();
}
@Test
void savingTheSameIdAgainReplacesTheStoredState() {
// given
repository().save(__Feature__.create(FIRST, "first"));
// when
repository().save(__Feature__.restore(FIRST, "renamed"));
// then
assertThat(repository().findById(FIRST).map(__Feature__::name)).contains("renamed");
}
}
+157
View File
@@ -0,0 +1,157 @@
#!/usr/bin/env bash
# 새 업무 기능의 뼈대를 계층 leaf에 만든다.
#
# scripts/new-feature.sh <FeatureName> [--path <segment>] [--no-format]
#
# 예: scripts/new-feature.sh Invoice -> /invoices
# scripts/new-feature.sh PurchaseOrder -> /purchaseOrders
# scripts/new-feature.sh Person --path people -> /people
#
# 만드는 것(배치·이름 근거는 docs/manual/03-placement.md, 단계는 02-new-feature.md):
# domain-core dev.caskeleton.domain.<f> aggregate·id·IdFactory·Repository·불변식 예외
# testFixtures .../<f>/testkit 포트당 fake 하나 + 공유 계약(XxxRepositoryContract)
# application-core dev.caskeleton.application.<f> Create/Get 유스케이스·command·query·view·오류 코드
# outbound:identifier dev.caskeleton.adapter.outbound.identifier.<f> Uuid<F>IdFactory
# inbound:web dev.caskeleton.adapter.inbound.web.<f> 컨트롤러·요청/응답 DTO
# app-bootstrap dev.caskeleton.bootstrap.autoconfigure.<f> <F>Config + AutoConfiguration.imports 한 줄
# 그리고 각 leaf의 테스트.
#
# 만들지 않는 것: 저장 adapter(JPA 엔티티·마이그레이션). 고를 저장소와 번호대가 서비스마다 달라
# 사람이 정한다(docs/manual/04-persistence.md). 그 adapter가 생기기 전까지 <F>Config는 꺼져 있다.
#
# 생성 뒤 그대로 통과해야 하는 검사(scripts/verify-feature-scaffold.sh가 왕복으로 고정한다):
# ./gradlew :domain-core:check :application-core:check :adapter:outbound:identifier:check \
# :adapter:inbound:web:check :app-bootstrap:check architectureCheck
set -euo pipefail
usage() {
sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//'
exit 2
}
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
templates="$repo_root/scripts/feature-scaffold/templates"
name=""
path_segment=""
format=1
while [ $# -gt 0 ]; do
case "$1" in
--path) path_segment="${2:-}"; shift 2 ;;
--no-format) format=0; shift ;;
-h|--help) usage ;;
-*) echo "알 수 없는 옵션: $1" >&2; usage ;;
*) [ -z "$name" ] || usage; name="$1"; shift ;;
esac
done
[ -n "$name" ] || usage
# --- 이름 검사 -----------------------------------------------------------------------------
if ! [[ "$name" =~ ^[A-Z][a-z0-9]+([A-Z][a-z0-9]+)*$ ]]; then
echo "기능 이름은 PascalCase여야 한다(예: Invoice, PurchaseOrder): $name" >&2
exit 2
fi
package_name="$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')"
camel="$(printf '%s' "${name:0:1}" | tr '[:upper:]' '[:lower:]')${name:1}"
upper_snake="$(printf '%s' "$name" | sed -E 's/([a-z0-9])([A-Z])/\1_\2/g' | tr '[:lower:]' '[:upper:]')"
kebab="$(printf '%s' "$name" | sed -E 's/([a-z0-9])([A-Z])/\1-\2/g' | tr '[:upper:]' '[:lower:]')"
if [ -z "$path_segment" ]; then
case "$camel" in
*s|*x|*ch|*sh) path_segment="${camel}es" ;;
*[!aeiou]y) path_segment="${camel%y}ies" ;;
*) path_segment="${camel}s" ;;
esac
fi
# AIP-122: 경로 조각은 소문자로 시작하는 영숫자(ForbiddenApiArchitectureTest.CONTROLLER_REQUEST_MAPPINGS_FOLLOW_AIP122).
if ! [[ "$path_segment" =~ ^[a-z][a-zA-Z0-9]*$ ]]; then
echo "--path는 AIP-122 모양([a-z][a-zA-Z0-9]*)이어야 한다: $path_segment" >&2
exit 2
fi
# Java 예약어와 플랫폼 패키지 이름은 패키지로 쓸 수 없거나 템플릿 코드와 섞인다.
reserved=" abstract assert boolean break byte case catch char class const continue default do
double else enum extends final finally float for goto if implements import instanceof int
interface long native new package private protected public return short static strictfp super
switch synchronized this throw throws transient try void volatile while record sealed permits
var yield
capability command query usecase transaction security tenant operation outbox idempotency lease
lock cache messaging observability outbound realtime identifier stereotype notification
fileserver objectstorage auth authz error envelope mvc "
reserved=" $(printf '%s' "$reserved" | tr -s ' \n' ' ') "
if [[ "$reserved" == *" $package_name "* ]]; then
echo "'$package_name'는 Java 예약어이거나 템플릿 플랫폼 패키지 이름이다. 다른 이름을 고른다." >&2
exit 2
fi
# --- 대상 경로 -----------------------------------------------------------------------------
substitute() {
sed -e "s/__Feature__/$name/g" \
-e "s/__featureCamel__/$camel/g" \
-e "s/__feature_kebab__/$kebab/g" \
-e "s/__featurePath__/$path_segment/g" \
-e "s/__FEATURE__/$upper_snake/g" \
-e "s/__feature__/$package_name/g"
}
mapfile -t sources < <(cd "$templates" && find . -type f -name '*.tmpl' | sort)
[ "${#sources[@]}" -gt 0 ] || { echo "템플릿이 없다: $templates" >&2; exit 1; }
targets=()
for source in "${sources[@]}"; do
relative="${source#./}"
target="$(printf '%s' "${relative%.tmpl}" | substitute)"
if [ -e "$repo_root/$target" ]; then
echo "이미 있다(덮어쓰지 않는다): $target" >&2
exit 1
fi
targets+=("$target")
done
for package_dir in \
"src/domain-core/src/main/java/dev/caskeleton/domain/$package_name" \
"src/application-core/src/main/java/dev/caskeleton/application/$package_name" \
"src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/$package_name"; do
if [ -d "$repo_root/$package_dir" ]; then
echo "패키지가 이미 있다: $package_dir" >&2
exit 1
fi
done
imports="$repo_root/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports"
config_class="dev.caskeleton.bootstrap.autoconfigure.$package_name.${name}Config"
[ -f "$imports" ] || { echo "없다: $imports" >&2; exit 1; }
# --- 생성 ----------------------------------------------------------------------------------
for i in "${!sources[@]}"; do
mkdir -p "$(dirname "$repo_root/${targets[$i]}")"
substitute < "$templates/${sources[$i]#./}" > "$repo_root/${targets[$i]}"
echo "생성 ${targets[$i]}"
done
# 파일 끝 줄바꿈이 없으면 붙이고 한 줄을 더한다.
[ -z "$(tail -c1 "$imports")" ] || printf '\n' >> "$imports"
printf '%s\n' "$config_class" >> "$imports"
echo "추가 ${imports#"$repo_root/"}: $config_class"
leaves=(:domain-core :application-core :adapter:outbound:identifier :adapter:inbound:web :app-bootstrap)
# google-java-format은 Javadoc 줄바꿈을 이름 길이에 따라 다시 맞춘다. 템플릿만으로는 모든 이름에서
# spotlessCheck를 통과시킬 수 없어 생성 직후 한 번 적용한다.
if [ "$format" -eq 1 ]; then
spotless=()
for leaf in "${leaves[@]}"; do spotless+=("$leaf:spotlessApply"); done
(cd "$repo_root/src" && ./gradlew -q --console=plain "${spotless[@]}")
echo "포맷 spotlessApply (${leaves[*]})"
fi
checks=()
for leaf in "${leaves[@]}"; do checks+=("$leaf:check"); done
cat <<EOF
$name 뼈대를 만들었다. 다음 순서로 진행한다(docs/manual/02-new-feature.md).
1. 검사: cd src && ./gradlew ${checks[*]} architectureCheck --console=plain
2. 권한: app.authz.role-permissions에 역할 -> $kebab:create 를 준다(07-authorization.md).
주기 전까지 POST /$path_segment 는 모두 403이다.
3. 저장 adapter: ${name}Repository를 구현하고 ${name}RepositoryContract를 실제 저장소로 상속한다
(04-persistence.md). 그 전까지 ${name}Config는 꺼져 있어 /$path_segment 가 없다.
4. placeholder 필드 name을 실제 상태로 바꾸고 불변식을 ${name} 안에 둔다.
EOF
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env bash
# 생성 명령 왕복 검사: 새 기능을 만들면 그 결과가 손대지 않고 PR 게이트를 통과하는가.
#
# scripts/verify-feature-scaffold.sh [FeatureName ...]
#
# 작업 트리(추적 파일 + 무시되지 않은 새 파일)를 임시 디렉터리로 복사하고, 거기서
# scripts/new-feature.sh를 이름마다 실행한 뒤, 생성물이 닿는 leaf의 check와 architectureCheck를
# 돌린다. 작업 트리는 건드리지 않고, 임시 디렉터리는 끝나면 지운다(KEEP_SCAFFOLD_COPY=1이면 남긴다).
#
# 기본 이름 두 개: 한 단어(Invoice)와 여러 단어(PurchaseOrder). 여러 단어 이름은 패키지·경로·
# 오류 코드·권한 이름이 서로 다른 모양으로 갈리고 Javadoc 줄바꿈이 달라지는 경우다.
#
# 루트 Gradle 태스크 `verifyFeatureScaffold`가 이 스크립트를 부르고 mainCheck에 들어 있다.
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
names=("$@")
[ "${#names[@]}" -gt 0 ] || names=(Invoice PurchaseOrder)
parent="${TMPDIR:-/tmp}"
copy="$(mktemp -d "$parent/feature-scaffold.XXXXXX")"
cleanup() {
if [ "${KEEP_SCAFFOLD_COPY:-0}" = "1" ]; then
echo "복사본을 남겼다: $copy"
else
rm -rf "$copy"
fi
}
trap cleanup EXIT
# 작업 트리 그대로(커밋하지 않은 변경 포함). build 산출물은 .gitignore라 빠진다.
# 지웠지만 아직 커밋하지 않은 추적 파일은 목록에서 뺀다(`-d`로 받은 경로를 거른다). 그대로 두면
# tar가 없는 파일을 만나 실패한다.
(cd "$repo_root" && git ls-files -co --exclude-standard -z \
| grep -zvxF -f <(git ls-files -d -z | tr '\0' '\n' | sed '/^$/d'; echo '/dev/null/none')) \
| (cd "$repo_root" && tar --null -T - -cf -) \
| tar -xf - -C "$copy"
# architectureCheck의 Git-carryable 검사와 sourceRevision은 Git 저장소를 읽는다.
(
cd "$copy"
git init -q
git add -A
GIT_AUTHOR_NAME=scaffold GIT_AUTHOR_EMAIL=scaffold@invalid \
GIT_COMMITTER_NAME=scaffold GIT_COMMITTER_EMAIL=scaffold@invalid \
git commit -q -m "feature scaffold round trip baseline"
)
for name in "${names[@]}"; do
"$copy/scripts/new-feature.sh" "$name" > "$copy/new-feature-$name.log"
echo "생성: $name"
done
# 생성 명령이 정말로 무언가를 만들었는지(빈 왕복이 녹색이 되지 않게).
for name in "${names[@]}"; do
package_name="$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')"
for required in \
"src/domain-core/src/main/java/dev/caskeleton/domain/$package_name/${name}.java" \
"src/application-core/src/main/java/dev/caskeleton/application/$package_name/Create${name}UseCase.java" \
"src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/$package_name/${name}Controller.java" \
"src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/$package_name/${name}Config.java"; do
[ -f "$copy/$required" ] || { echo "생성되지 않았다: $required" >&2; exit 1; }
done
done
cd "$copy/src"
./gradlew --console=plain --continue \
:domain-core:check \
:application-core:check \
:adapter:outbound:identifier:check \
:adapter:inbound:web:check \
:app-bootstrap:check \
architectureCheck
# 생성된 테스트가 실제로 실행되었는지: 각 leaf의 테스트 결과에 기능 테스트 클래스가 있어야 한다.
for name in "${names[@]}"; do
for result in \
"domain-core/build/test-results/test/TEST-dev.caskeleton.domain.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').${name}Test.xml" \
"application-core/build/test-results/test/TEST-dev.caskeleton.application.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').Create${name}UseCaseTest.xml" \
"adapter/inbound/web/build/test-results/test/TEST-dev.caskeleton.adapter.inbound.web.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').${name}ControllerTest.xml" \
"app-bootstrap/build/test-results/test/TEST-dev.caskeleton.bootstrap.autoconfigure.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').${name}ConfigTest.xml"; do
[ -f "$result" ] || { echo "생성된 테스트가 실행되지 않았다: $result" >&2; exit 1; }
if grep -q '<failure\|<error' "$result"; then
echo "생성된 테스트가 실패했다: $result" >&2
exit 1
fi
done
done
echo "feature scaffold 왕복 통과: ${names[*]}"
+3 -2
View File
@@ -19,7 +19,6 @@ from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
PLATFORM = REPO_ROOT / "src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient"
BOOTSTRAP = REPO_ROOT / "src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/httpclient"
DOCS_DIR = REPO_ROOT / "docs/httpclient"
ENV_FIELD_MANIFEST = REPO_ROOT / "docs/httpclient/env-fields.yaml"
@@ -61,7 +60,9 @@ def violation_codes() -> list[str]:
for source_file in [
PLATFORM / "profile/ClientProfileValidator.java",
PLATFORM / "security/TlsPolicyValidator.java",
BOOTSTRAP / "HttpClientStartupValidator.java",
# The startup validator moved from app-bootstrap into the leaf; the old path made this
# script fail on a missing file before it checked anything.
PLATFORM / "autoconfigure/HttpClientStartupValidator.java",
]:
source = source_file.read_text(encoding="utf-8")
codes.update(re.findall(r'"([A-Z][A-Z0-9_]{4,})"', source))