-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.gradle
More file actions
690 lines (577 loc) · 20.1 KB
/
Copy pathbuild.gradle
File metadata and controls
690 lines (577 loc) · 20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
plugins {
id 'java'
id 'org.springframework.boot' version '3.3.3'
id 'io.spring.dependency-management' version '1.1.7'
id 'jacoco'
}
group = 'com.carecode'
version = '0.0.1-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
maven { url 'https://repo1.maven.org/maven2/' }
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.flywaydb:flyway-core'
implementation 'org.flywaydb:flyway-mysql'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-aop'
// Swagger/OpenAPI 3
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
implementation 'io.micrometer:micrometer-registry-prometheus'
implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5'
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
annotationProcessor 'org.projectlombok:lombok'
// MapStruct for DTO mappings
implementation 'org.mapstruct:mapstruct:1.5.5.Final'
annotationProcessor 'org.mapstruct:mapstruct-processor:1.5.5.Final'
annotationProcessor 'org.projectlombok:lombok-mapstruct-binding:0.2.0'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'org.testcontainers:junit-jupiter:1.21.3'
testImplementation 'org.testcontainers:mariadb:1.21.3'
runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
// 소셜 로그인(OAuth2)
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
// 이메일 인증
implementation 'org.springframework.boot:spring-boot-starter-mail'
// Redis
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
// FCM 푸시 알림 (서비스 계정 자격증명이 없으면 런타임에 비활성화됨)
implementation 'com.google.firebase:firebase-admin:9.4.1'
// Claude API (챗봇). API 키가 없으면 룰 기반 응답으로 폴백한다.
implementation 'com.anthropic:anthropic-java:2.34.0'
// Logging - JSON 형식 로깅 지원
implementation 'net.logstash.logback:logstash-logback-encoder:7.4'
// API 문서는 springdoc-openapi 가 런타임에 생성한다(운영 프로파일에서는 비공개).
// asciidoctor 로 정적 산출물을 만들던 시절의 의존성이 남아 있었는데, .adoc 도 사용처도 없이
// 실행 jar 에 7.5MB 를 차지하고 취약점 스캔 표면만 늘리고 있었다.
}
// 소스에 한글 문자열 리터럴이 있다. 인코딩을 지정하지 않으면 Windows(CP949)에서 깨져 컴파일된다.
// 공공데이터 응답의 한글 필드명("서비스ID" 등) 조회가 전부 실패하는 원인이었다.
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
}
tasks.withType(Test).configureEach {
systemProperty 'file.encoding', 'UTF-8'
jvmArgs '-Dfile.encoding=UTF-8'
// Testcontainers 가 쓰는 docker-java 는 API 버전을 따로 주지 않으면 1.32 로 고정한다.
// Docker Engine 29 는 최소 API 가 1.40 이라 이 요청을 400 으로 거부하고, Testcontainers 는
// "Docker 를 찾지 못함" 으로 판단해 통합 테스트를 조용히 건너뛴다(disabledWithoutDocker).
// 로컬(Docker Desktop, Engine 29)에서 스키마 정합성 검증이 한 번도 돌지 않던 이유다.
// CI 가 통과하는 건 러너가 아직 이전 Engine 이기 때문이라, 러너가 올라가면 CI 도 같은 상태가 된다.
// 1.44 는 Engine 25 이상이 지원하므로 로컬·CI 모두 안전하다. 필요하면 -Papi.version= 으로 덮어쓴다.
systemProperty 'api.version', project.findProperty('api.version') ?: '1.44'
// 통합 테스트가 늘면서 Spring 컨텍스트가 14개까지 떠, 기본 힙으로는 OutOfMemory 로 워커가 죽었다.
// 컨텍스트마다 JPA·커넥션풀·캐시를 들고 있어 개수가 곧 메모리다.
maxHeapSize = '2g'
// 동시에 살아 있는 컨텍스트 수를 제한한다. 기본값(32)이면 한 번 뜬 컨텍스트가 끝까지 캐시에 남아
// 테스트 클래스를 추가할 때마다 메모리가 계단식으로 늘어난다. 넘치면 오래된 컨텍스트를 닫는다.
systemProperty 'spring.test.context.cache.maxSize', '6'
// API 스펙 파일 갱신 스위치. Gradle 속성으로 받아 테스트 JVM 까지 넘긴다
// (-D 로 주면 Gradle JVM 에만 붙고 테스트 워커에는 전달되지 않는다).
systemProperty 'openapi.lock.update', project.findProperty('openapi.lock.update') ?: 'false'
}
tasks.named('test') {
useJUnitPlatform {
// 외부 API 를 호출하는 테스트는 기본 빌드에서 제외한다. 네트워크 상태로 빌드가 깨지면 안 된다.
// 실행: ./gradlew liveSyncCheck
excludeTags 'live'
}
finalizedBy(tasks.named('jacocoTestReport'))
// 스키마 정합성 검증이 skip 되면 로컬에서도 크게 알린다.
// CI 는 같은 경우 빌드를 실패시키지만(ci-cd.yml "Assert schema validation actually ran"),
// 로컬은 초록불이 뜬 채 지나가서 Docker 가 없거나 연결이 안 되는 걸 아무도 몰랐다.
// 로컬에서 실패시키지는 않는다 — Docker 없이도 나머지 테스트는 돌려야 한다.
doLast {
def report = file("${buildDir}/test-results/test/TEST-com.carecode.integration.FlywaySchemaValidationTest.xml")
if (report.exists() && !(report.text =~ /skipped="0"/)) {
logger.warn("""
|
|[경고] 스키마 정합성 검증(FlywaySchemaValidationTest)이 skip 됐습니다.
| Docker 가 없거나 연결되지 않았습니다. 마이그레이션과 엔티티가 어긋나도 이 빌드는 잡지 못합니다.
| Docker Desktop 을 켜고 다시 실행하세요. (CI 에서는 이 상태가 빌드 실패입니다)
|""".stripMargin())
}
}
}
/** 공공데이터 실연동 점검. 키를 환경변수로 넘겨 수동 실행한다. */
tasks.register('liveSyncCheck', Test) {
group = 'verification'
description = '실제 공공데이터 API 를 호출해 적재까지 확인한다'
testClassesDirs = sourceSets.test.output.classesDirs
classpath = sourceSets.test.runtimeClasspath
useJUnitPlatform {
includeTags 'live'
}
testLogging {
showStandardStreams = true
}
}
jacoco {
toolVersion = "0.8.12"
}
tasks.named('jacocoTestReport') {
dependsOn tasks.named('test')
reports {
xml.required = true
html.required = true
}
}
tasks.named('check') {
dependsOn tasks.named('jacocoTestCoverageVerification')
}
tasks.named('jacocoTestCoverageVerification') {
dependsOn tasks.named('test')
violationRules {
// 1) 전체 커버리지: 후퇴 방지선(ratchet).
// 현재 라인 커버리지는 약 38% 다. 테스트를 늘릴 때마다 이 값을 함께 올린다.
// (기존 0.01 은 사실상 게이트가 없는 것과 같아 통과해도 의미가 없었다.)
rule {
element = 'BUNDLE'
limit {
counter = 'LINE'
value = 'COVEREDRATIO'
minimum = 0.37
}
}
// 2) 보안·인증 핵심 클래스는 별도의 높은 기준을 적용한다.
// 이 경로들이 테스트 없이 수정되면 빌드가 실패해야 한다.
//
// 목록을 고를 때의 기준은 "여기가 조용히 망가지면 사고가 되는가" 다.
// - CurrentUserFacade: 본인 확인(소유권). 뚫리면 남의 계정을 조작할 수 있다.
// - JwtAuthenticationFilter: 누구로 인증되는지를 정한다.
// - RateLimitInterceptor: fail-open 이 깨지면 Redis 장애가 전면 장애가 된다.
// - EmailVerificationService: 인증번호 난수·시도 제한.
// - UserService: 가입·역할·계정 상태. 0.7% 였던 동안 여기서 P0 가 세 번 나왔다.
// - AuthServiceImpl: 카카오 계정 연결. 1% 였고, 검증 안 된 이메일로 남의 계정을 가져갈 수 있었다.
rule {
element = 'CLASS'
includes = [
'com.carecode.domain.user.service.JwtService',
'com.carecode.core.util.ClientIpResolver',
'com.carecode.core.util.PageRequestUtil',
'com.carecode.core.security.CurrentUserFacade',
'com.carecode.core.security.JwtAuthenticationFilter',
'com.carecode.core.RateLimitInterceptor',
'com.carecode.domain.user.service.EmailVerificationService',
'com.carecode.domain.user.service.UserService',
'com.carecode.domain.user.service.impl.AuthServiceImpl'
]
limit {
counter = 'LINE'
value = 'COVEREDRATIO'
minimum = 0.60
}
}
}
}
// JAR 빌드 최적화
jar {
enabled = false
archiveClassifier = ''
}
// Spring Boot JAR 설정
springBoot {
buildInfo()
}
// 프로덕션 빌드 최적화
tasks.named('bootJar') {
archiveFileName = 'carecode-app.jar'
// 중복 파일 처리 전략 설정
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
// 메타데이터 추가
manifest {
attributes(
'Implementation-Title': 'CareCode Application',
'Implementation-Version': version,
'Built-By': System.getProperty('user.name'),
'Built-Date': new Date(),
'Built-JDK': System.getProperty('java.version')
)
}
// 리소스 최적화
from('src/main/resources') {
include '**/*'
into 'BOOT-INF/classes'
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
}
// 프로파일별 빌드 태스크
task buildRelease {
dependsOn bootJar
doLast {
println "✅ 프로덕션 JAR 빌드 완료: ${bootJar.archiveFile.get()}"
println "📦 파일 크기: ${bootJar.archiveFile.get().asFile.length() / 1024 / 1024} MB"
}
}
// Docker 빌드용 태스크
task buildDocker {
dependsOn bootJar
doLast {
copy {
from bootJar
into 'build/docker'
rename { String fileName ->
'app.jar'
}
}
println "✅ Docker 빌드용 JAR 준비 완료"
}
}
// API 문서 생성 태스크
task generateApiDocs {
doLast {
def outputDir = file('src/docs/asciidoc')
outputDir.mkdirs()
// Swagger JSON 다운로드 (환경 변수 또는 gradle -P 로 주입 가능)
def serverUrl = System.getenv('SWAGGER_SERVER_URL') ?: (project.hasProperty('swaggerServerUrl') ? project.getProperty('swaggerServerUrl') : 'http://localhost:8081')
def swaggerUrl = serverUrl + '/v3/api-docs'
def swaggerFile = file('swagger.json')
new URL(swaggerUrl).withInputStream { input ->
swaggerFile.withOutputStream { output ->
output << input
}
}
println "✅ Swagger JSON 다운로드 완료"
println "📁 출력 디렉토리: ${outputDir.absolutePath}"
println "📄 Swagger JSON: ${swaggerFile.absolutePath}"
}
}
// 상세 API 문서 생성
task generateDetailedApiDocs {
doLast {
def outputDir = file('src/docs/asciidoc')
outputDir.mkdirs()
println "🚀 상세 API 문서 생성을 시작합니다..."
println "📁 출력 디렉토리: ${outputDir.absolutePath}"
// API 문서 생성기 실행
def detailedDocFile = file('src/docs/asciidoc/api-docs-detailed.adoc')
javaexec {
classpath = sourceSets.main.runtimeClasspath
mainClass = 'com.carecode.docs.ApiDocumentationGenerator'
def serverUrl = System.getenv('SWAGGER_SERVER_URL') ?: (project.hasProperty('swaggerServerUrl') ? project.getProperty('swaggerServerUrl') : 'http://localhost:8081')
args = [serverUrl + '/api-docs', detailedDocFile.absolutePath]
}
println "✅ 상세 API 문서 생성 완료: ${detailedDocFile.absolutePath}"
}
}
// 간단한 API 목록 생성
task generateApiList {
doLast {
def outputDir = file('src/docs/asciidoc')
outputDir.mkdirs()
println "🚀 API 목록 생성을 시작합니다..."
println "📁 출력 디렉토리: ${outputDir.absolutePath}"
// 간단한 API 목록 생성
def apiListFile = file('src/docs/asciidoc/api-list.adoc')
def apiListContent = generateApiListContent()
apiListFile.text = apiListContent
println "✅ API 목록 생성 완료: ${apiListFile.absolutePath}"
}
}
// API 목록 생성 함수
def generateApiListContent() {
def asciiDoc = new StringBuilder()
// 기본 헤더
asciiDoc.append("= CareCode API 목록\n")
asciiDoc.append(":toc: left\n")
asciiDoc.append(":toclevels: 2\n")
asciiDoc.append(":sectnums:\n")
asciiDoc.append(":icons: font\n\n")
asciiDoc.append("== 개요\n\n")
asciiDoc.append("CareCode API의 주요 엔드포인트 목록입니다.\n\n")
// API 그룹별 목록
def apiGroups = [
"인증": [
["POST /auth/login", "로그인"],
["POST /auth/register", "회원가입"],
["POST /auth/logout", "로그아웃"],
["GET /auth/me", "현재 사용자 정보 조회"]
],
"육아시설": [
["GET /facilities", "시설 목록 조회"],
["GET /facilities/{id}", "시설 상세 조회"],
["POST /facilities/search", "시설 검색"],
["POST /facilities/{id}/bookings", "예약 생성"]
],
"커뮤니티": [
["GET /community/posts", "게시글 목록 조회"],
["POST /community/posts", "게시글 작성"],
["GET /community/posts/{id}", "게시글 상세 조회"]
],
"건강관리": [
["GET /health/records", "건강기록 조회"],
["POST /health/records", "건강기록 등록"],
["GET /health/statistics", "건강 통계 조회"]
],
"정책정보": [
["GET /policies", "정책 목록 조회"],
["GET /policies/{id}", "정책 상세 조회"],
["POST /policies/search", "정책 검색"]
],
"챗봇": [
["POST /chatbot/chat", "챗봇 대화"],
["GET /chatbot/sessions", "세션 목록 조회"]
],
"알림": [
["GET /notifications", "알림 목록 조회"],
["POST /notifications", "알림 생성"]
]
]
apiGroups.each { tag, apis ->
asciiDoc.append("== ${tag}\n\n")
apis.each { api ->
asciiDoc.append("* `${api[0]}` - ${api[1]}\n")
}
asciiDoc.append("\n")
}
return asciiDoc.toString()
}
// AsciiDoc 템플릿 생성
task createAsciiDocTemplate {
doLast {
def templateDir = file('src/docs/templates')
templateDir.mkdirs()
def template = file('src/docs/templates/api-docs.adoc')
template.text = '''= CareCode API 문서
:toc: left
:toclevels: 3
:sectnums:
:source-highlighter: highlightjs
:icons: font
== 개요
CareCode API는 육아 정보 플랫폼을 위한 RESTful API입니다.
=== 기본 정보
* **Base URL**: `http://13.209.36.209:8081`
* **API 버전**: v1
* **인증**: JWT Bearer Token
== 인증
=== JWT 토큰
API 요청 시 Authorization 헤더에 JWT 토큰을 포함해야 합니다:
[source,http]
----
Authorization: Bearer <your-jwt-token>
----
== API 엔드포인트
=== 사용자 관리
==== 로그인
[source,http]
----
POST /auth/login
Content-Type: application/json
{
"email": "user@example.com",
"password": "password"
}
----
==== 회원가입
[source,http]
----
POST /auth/register
Content-Type: application/json
{
"email": "user@example.com",
"password": "password",
"name": "사용자명"
}
----
=== 육아시설
==== 시설 목록 조회
[source,http]
----
GET /api/facilities?page=0&size=10
Authorization: Bearer <token>
----
==== 시설 상세 조회
[source,http]
----
GET /api/facilities/{id}
Authorization: Bearer <token>
----
=== 커뮤니티
==== 게시글 목록
[source,http]
----
GET /api/community/posts?page=0&size=10
Authorization: Bearer <token>
----
==== 게시글 작성
[source,http]
----
POST /api/community/posts
Authorization: Bearer <token>
Content-Type: application/json
{
"title": "제목",
"content": "내용",
"category": "GENERAL"
}
----
=== 건강관리
==== 건강기록 조회
[source,http]
----
GET /api/health/records?childId={childId}
Authorization: Bearer <token>
----
==== 건강기록 등록
[source,http]
----
POST /api/health/records
Authorization: Bearer <token>
Content-Type: multipart/form-data
{
"childId": 1,
"recordType": "VACCINATION",
"title": "예방접종",
"description": "접종 내용",
"recordDate": "2024-01-15"
}
----
=== 정책정보
==== 정책 목록
[source,http]
----
GET /api/policies?category=EDUCATION&page=0&size=10
Authorization: Bearer <token>
----
==== 정책 상세
[source,http]
----
GET /api/policies/{id}
Authorization: Bearer <token>
----
=== 챗봇
==== 채팅 시작
[source,http]
----
POST /api/chatbot/sessions
Authorization: Bearer <token>
Content-Type: application/json
{
"message": "안녕하세요"
}
----
==== 메시지 전송
[source,http]
----
POST /api/chatbot/sessions/{sessionId}/messages
Authorization: Bearer <token>
Content-Type: application/json
{
"message": "육아 시설 추천해주세요"
}
----
== 응답 코드
|코드|설명|
|---|---|
|200|성공|
|201|생성됨|
|400|잘못된 요청|
|401|인증 실패|
|403|권한 없음|
|404|찾을 수 없음|
|500|서버 오류|
== 에러 응답
[source,json]
----
{
"timestamp": "2024-01-15T10:30:00",
"status": 400,
"error": "Bad Request",
"message": "잘못된 요청입니다",
"path": "/api/facilities"
}
----
== 데이터 모델
=== 사용자 (User)
[source,json]
----
{
"id": 1,
"email": "user@example.com",
"name": "사용자명",
"role": "USER",
"createdAt": "2024-01-15T10:30:00",
"updatedAt": "2024-01-15T10:30:00"
}
----
=== 육아시설 (CareFacility)
[source,json]
----
{
"id": 1,
"name": "행복한 어린이집",
"address": "서울시 강남구",
"phone": "02-1234-5678",
"capacity": 50,
"currentCount": 30,
"rating": 4.5,
"facilityType": "KINDERGARTEN"
}
----
=== 게시글 (Post)
[source,json]
----
{
"id": 1,
"title": "육아 팁 공유",
"content": "육아에 도움이 되는 팁입니다",
"author": {
"id": 1,
"name": "사용자명"
},
"category": "GENERAL",
"createdAt": "2024-01-15T10:30:00",
"viewCount": 10,
"likeCount": 5
}
----
== 개발 환경 설정
=== 로컬 개발
1. 애플리케이션 실행:
```bash
./gradlew bootRun
```
2. Swagger UI 접속:
```
http://13.209.36.209:8081/swagger-ui.html
```
3. API 문서 생성:
```bash
./gradlew generateApiDocs
```
=== 테스트
API 테스트는 Postman이나 curl을 사용할 수 있습니다:
[source,bash]
----
# 로그인
curl -X POST http://13.209.36.209:8081/auth/login \\
-H "Content-Type: application/json" \\
-d '{"email":"user@example.com","password":"password"}'
# 토큰으로 API 호출
curl -X GET http://13.209.36.209:8081/api/facilities \\
-H "Authorization: Bearer <your-token>"
----
'''
println "✅ AsciiDoc 템플릿 생성 완료: ${template.absolutePath}"
}
}