Files
clean-architecture-backend-…/scripts/new-feature.sh
T
DongHyeonka 1400dc1506 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 오류 코드 변경.
2026-11-03 19:52:06 +09:00

158 lines
7.5 KiB
Bash
Executable File

#!/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