Chuyển tới nội dung chính

Campaign Service: overview

TL;DR
  • 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ận now làm tham số) ⇒ unit test không cần Spring.
  • Concurrency: optimistic lock (@Version) cho lệnh admin, FOR UPDATE SKIP LOCKED cho 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àmKhông làm
CRUD campaign, candidate, rule set có versionNhận vote, đếm quota
State machine DRAFT → … → FINALIZEDTí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-serviceBá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ầnGiá trị
HTTP:8081; /actuator/prometheus, /actuator/health (không đi qua gateway)
Trang công khaiGET /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 relayplatform-common, poll 200 ms
Kafka consumergroup votee-campaign-service trên votee.voting.tally-events.v1
DBschema campaign, role campaign_service, Flyway khi khởi động

4. Config chính (application.yml)​

KeyMặc địnhÝ nghĩa
votee.campaign.finalization-grace10sChờ sau ends_at trước khi FINALIZING (phải > 5 s)
votee.campaign.campaign-events-topicvotee.campaign.campaign-events.v1
votee.campaign.tally-events-topicvotee.voting.tally-events.v1
votee.outbox.routesevent type → topicRelay fail nếu thiếu route
spring.jackson.property-naming-strategySNAKE_CASEJSON khớp contract
spring.kafka.producer.acks / enable.idempotenceall / 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​

ModuleCâu hỏi nó trả lờiCase
Lifecycle & RulesTrạng thái nào được chuyển sang trạng thái nào, ai kiểm tra?C9
Scheduler & snapshot publishingChuyể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 handshakeFINALIZING → 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
aggregateCụm đối tượng được sửa cùng nhau và bảo vệ bất biến của chúngLifecycle & Rules
state machineMô hình các trạng thái và chuyển trạng thái hợp lệLifecycle & Rules
optimistic lockingPhát hiện ghi chồng bằng cột phiên bảnCredit Service
SKIP LOCKEDBỏ qua dòng đang bị khoá để nhiều instance chia việcOutbox
layered architectureTách domain, application, infrastructure theo hướng phụ thuộc một chiềuVoting Service

Đọc tiếp: Lifecycle & Rules để xem state machine và luật của từng lệnh.