Campaign Service: overview
- campaign-service sở hữu campaign, candidate, rule set và lifecycle. Mọi thay đổi đi kèm một snapshot đầy đủ vào outbox để Voting Core đồng bộ.
- Domain rules nằm trong aggregate
Campaign(Java thuần, nhậnnowlàm tham số) ⇒ unit test không cần Spring. - Concurrency: optimistic lock (
@Version) cho lệnh admin,FOR UPDATE SKIP LOCKEDcho scheduler chạy nhiều instance. - Giải case: C6, C7, C9, C17.
- Cần biết trước: Campaign, Bounded contexts.
- Từ khoá:
aggregate,state machine,optimistic locking,SKIP LOCKED,layered architecture
1. Trách nhiệm & ranh giới
Tình huống: Chi tạo campaign Giọng ca của năm, thêm Mai, Nam, Oanh và đặt rule set. Từ đó campaign tự sống theo giờ mà không ai phải bấm gì.
| Làm | Không làm |
|---|---|
| CRUD campaign, candidate, rule set có version | Nhận vote, đếm quota |
State machine DRAFT → … → FINALIZED | Tính tally (Voting Core làm) |
| Scheduler chuyển trạng thái theo thời gian (DB clock) | Gọi HTTP sang Voting Core |
| Audit transition, lịch sử rule set | |
Access policy min_identity trong rule set (campaign có paid vote không cho guest) | Xác thực token (filter dùng chung của platform-common, yêu cầu role ADMIN) |
Vote package (vote_package: giá, tiền tệ, số credit) và endpoint nội bộ cho payment-service | Bán gói, giữ order (payment-service) |
Publish CampaignSnapshotPublished, FinalizationRequested | |
Ghi nhận FinalTallyComputed (FINALIZED, correction) |
2. Cấu trúc package
campaign-service/src/main/java/io/votee/campaign/
├── CampaignApplication.java # @Import(PlatformConfiguration)
├── domain/ # Java thuần, không phụ thuộc Spring/JPA
│ ├── model/ # Campaign (aggregate root), Candidate, Rules, MinIdentity, VotePackage, CampaignStatus, QuotaPeriod
│ ├── event/ # CampaignTransitioned, RuleSetReplaced, VotingWindowChanged, Candidate*
│ ├── exception/ # LifecycleException, InvalidInputException, CampaignNotFoundException
│ └── repository/ # CampaignRepository (port)
├── application/ # CampaignCommandService, CampaignQueryService, VotePackageService
│ └── port/ # Clock, TransitionLog, RuleSetHistory, CampaignEventPublisher
└── infrastructure/
├── persistence/ # JPA entity + mapper, JpaCampaignRepository, Jdbc*, DbClock
├── messaging/ # TallyListener (in), OutboxCampaignEventPublisher + SnapshotPayloads (out)
├── web/ # CampaignController, DTO, DomainErrorAdvice
├── scheduling/ # CampaignScheduler
└── config/ # ApplicationConfig (composition root), CampaignProperties, KafkaConfig
src/main/resources/
├── application.yml
└── db/migration/V1__campaign.sql
domain là Java thuần (không Spring, không JPA): entity JPA nằm ở infrastructure/persistence và được map qua CampaignMapper ⇒ CampaignTest chạy như unit test thuần. Luật phụ thuộc được kiểm tra bằng ArchUnit (campaign-service/src/test/java/io/votee/campaign/ArchitectureTest.java).
Quyết định thiết kế chính
Quyết định: luật vòng đời nằm trong aggregate Java thuần
Vấn đề. Vòng đời campaign có nhiều luật (lệnh nào hợp lệ ở trạng thái nào, sau khi bắt đầu chỉ được kéo dài, candidate cố định…). Nếu rải trong controller và service, luật bị lặp và khó kiểm thử.
Phương án khác. Dùng entity JPA làm domain model: ít code ánh xạ hơn, nhưng luật gắn với framework và đồng hồ hệ thống.
Lựa chọn. Luật nằm trong Campaign (Java thuần, không Spring, không JPA), mỗi method nhận now làm tham số. Entity JPA nằm riêng ở infrastructure, nối với domain bằng mapper. ArchitectureTest (ArchUnit) bảo đảm chiều phụ thuộc.
Đánh đổi. Có thêm lớp ánh xạ giữa domain và entity JPA. Đổi lại unit test của aggregate chạy không cần Spring và thời gian điều khiển được.
3. Process & port
| Thành phần | Giá trị |
|---|---|
| HTTP | :8081; /actuator/prometheus, /actuator/health (không đi qua gateway) |
| Trang công khai | GET /v1/public/campaigns (keyset, lọc status) và GET /v1/public/campaigns/{id}: không cần token, ẩn DRAFT và CANCELLED, không lộ version hay checksum; index campaign_public_idx (migration V4). Controller riêng vì filter xác thực khớp theo path, không theo method |
| Scheduler | @Scheduled(fixedDelay = 1s), bật/tắt bằng votee.campaign.scheduler-enabled |
| Outbox relay | platform-common, poll 200 ms |
| Kafka consumer | group votee-campaign-service trên votee.voting.tally-events.v1 |
| DB | schema campaign, role campaign_service, Flyway khi khởi động |
4. Config chính (application.yml)
| Key | Mặc định | Ý nghĩa |
|---|---|---|
votee.campaign.finalization-grace | 10s | Chờ sau ends_at trước khi FINALIZING (phải > 5 s) |
votee.campaign.campaign-events-topic | votee.campaign.campaign-events.v1 | |
votee.campaign.tally-events-topic | votee.voting.tally-events.v1 | |
votee.outbox.routes | event type → topic | Relay fail nếu thiếu route |
spring.jackson.property-naming-strategy | SNAKE_CASE | JSON khớp contract |
spring.kafka.producer.acks / enable.idempotence | all / true |
5. Dependencies
Spring Boot 4.2 (Jackson 3 tools.jackson), Spring Data JPA (aggregate + @Version), JdbcClient (audit, scheduler query, outbox), Flyway, Spring Kafka, Micrometer Prometheus, platform-common.
6. Danh sách module
| Module | Câu hỏi nó trả lời | Case |
|---|---|---|
| Lifecycle & Rules | Trạng thái nào được chuyển sang trạng thái nào, ai kiểm tra? | C9 |
| Scheduler & snapshot publishing | Chuyển trạng thái theo thời gian thế nào khi chạy nhiều instance? Voting Core thấy thay đổi ra sao? | C6, C7 |
| Finalization handshake | FINALIZING → FINALIZED và correction được ghi nhận thế nào? | C17, C18 |
7. Rút ra & từ khoá
Điều đáng nhớ: đặt luật nghiệp vụ trong một aggregate Java thuần nhận thời gian làm tham số giúp kiểm thử không cần Spring hay cơ sở dữ liệu, và là chỗ duy nhất giữ luật vòng đời.
| Từ khoá | Nghĩa (một câu) | Nơi khác trong Votee dùng lại |
|---|---|---|
aggregate | Cụm đối tượng được sửa cùng nhau và bảo vệ bất biến của chúng | Lifecycle & Rules |
state machine | Mô hình các trạng thái và chuyển trạng thái hợp lệ | Lifecycle & Rules |
optimistic locking | Phát hiện ghi chồng bằng cột phiên bản | Credit Service |
SKIP LOCKED | Bỏ qua dòng đang bị khoá để nhiều instance chia việc | Outbox |
layered architecture | Tách domain, application, infrastructure theo hướng phụ thuộc một chiều | Voting Service |
Đọc tiếp: Lifecycle & Rules để xem state machine và luật của từng lệnh.