This commit is contained in:
2026-09-29 18:47:37 +08:00
parent 2c60a29e0f
commit c2927ab9a6
291 changed files with 4008 additions and 6298 deletions
@@ -0,0 +1,56 @@
package com.baiyue.finance.controller;
import com.baiyue.common.core.api.ApiResponse;
import com.baiyue.common.core.api.ResultCode;
import com.baiyue.common.core.exception.BizException;
import com.baiyue.common.core.outbox.OutboxOperations;
import com.baiyue.common.core.outbox.EventOperationsTokenGuard;
import com.baiyue.common.event.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.web.bind.annotation.*;
import java.util.Set;
/** Internal-only operator recovery. It cannot mutate the original event or call a consumer directly. */
@RestController
@RequestMapping("/internal/finance/event-operations")
public class EventOperationsController {
private final EventOperationsTokenGuard guard;
private final OutboxOperations operations;
public EventOperationsController(JdbcTemplate jdbc, PlatformTransactionManager transactions,
ObjectMapper mapper, @Value("${baiyue.event-delivery.operations-token:}") String token) {
guard = new EventOperationsTokenGuard(token);
operations = new OutboxOperations(jdbc, transactions,
new OutboxOperations.Layout("fin_wallet_event_outbox", "event_id", "status", Set.of(EventTypes.WALLET_COMMAND_COMPLETED)),
json -> {
try {
EventEnvelope envelope = mapper.readValue(json, EventEnvelope.class).requireValid();
if (!EventPayloadHash.matches(EventPayloadCanonicalizer.canonicalize(envelope.payload()), envelope.payloadHash())) {
throw new IllegalArgumentException("Hash mismatch");
}
return new OutboxOperations.Identity(envelope.eventId(), envelope.eventType(), envelope.payloadHash());
} catch (Exception invalid) {
throw new BizException(ResultCode.CONFLICT, "原事件格式或摘要无效,禁止人工重试");
}
});
}
@GetMapping("/{entryId}")
public ApiResponse<OutboxOperations.Entry> inspect(
@RequestHeader(value = "X-Event-Operations-Token", required = false) String token,
@PathVariable String entryId) {
guard.require(token);
return ApiResponse.success(operations.inspect(entryId));
}
@PostMapping("/{entryId}/retry")
public ApiResponse<OutboxOperations.RetryResult> retry(
@RequestHeader(value = "X-Event-Operations-Token", required = false) String token,
@PathVariable String entryId, @RequestBody OutboxOperations.RetryRequest request) {
guard.require(token);
return ApiResponse.success(operations.retry(entryId, request));
}
}
@@ -6,7 +6,6 @@ import com.baiyue.common.event.DeliveryAck;
import com.baiyue.common.event.EventPayloadCanonicalizer;
import com.baiyue.common.event.EventPayloadHash;
import com.baiyue.common.event.EventTypes;
import com.baiyue.common.event.RegionCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
@@ -36,9 +35,8 @@ public class BusinessFeeSourceEventService {
throw error("FIN-EVT-001", "跨区费用事件信封无效");
}
if (!EventTypes.BUSINESS_FEE_SOURCE_CHANGED.equals(envelope.eventType())
|| envelope.eventVersion() != 1 || envelope.sourceRegion() != RegionCode.OVERSEAS
|| envelope.targetRegion() != RegionCode.CN) {
throw error("FIN-EVT-001", "跨区费用事件类型、版本或区域无效");
|| envelope.eventVersion() != 1) {
throw error("FIN-EVT-001", "跨区费用事件类型或版本无效");
}
if (!EventPayloadHash.matches(EventPayloadCanonicalizer.canonicalize(envelope.payload()), envelope.payloadHash())) {
throw new FinanceEventException("FIN-EVT-002", "事件信封摘要与实际载荷不一致");
@@ -7,7 +7,6 @@ import com.baiyue.common.event.EventIdentifiers;
import com.baiyue.common.event.EventPayloadCanonicalizer;
import com.baiyue.common.event.EventPayloadHash;
import com.baiyue.common.event.EventTypes;
import com.baiyue.common.event.RegionCode;
import com.baiyue.common.event.WalletCommandCompletedV1;
import com.baiyue.common.event.WalletCommandRequestedV1;
import com.baiyue.finance.dto.FinanceWalletDtos.WalletFreezeRequest;
@@ -108,9 +107,8 @@ public class WalletCommandEventService {
try { EventEnvelopeValidator.requireValid(envelope); }
catch (RuntimeException exception) { throw new FinanceEventException("FIN-EVT-001", "资金指令信封无效"); }
if (!EventTypes.WALLET_COMMAND_REQUESTED.equals(envelope.eventType())
|| envelope.eventVersion() != WalletCommandRequestedV1.VERSION
|| envelope.sourceRegion() != RegionCode.OVERSEAS || envelope.targetRegion() != RegionCode.CN) {
throw new FinanceEventException("FIN-EVT-001", "资金指令类型、版本或区域无效");
|| envelope.eventVersion() != WalletCommandRequestedV1.VERSION) {
throw new FinanceEventException("FIN-EVT-001", "资金指令类型或版本无效");
}
if (!EventPayloadHash.matches(EventPayloadCanonicalizer.canonicalize(envelope.payload()), envelope.payloadHash())) {
throw new FinanceEventException("FIN-EVT-002", "事件信封摘要与实际载荷不一致");
@@ -146,7 +144,7 @@ public class WalletCommandEventService {
JsonNode payload = objectMapper.valueToTree(result);
String payloadHash = EventPayloadHash.sha256(EventPayloadCanonicalizer.canonicalize(payload));
EventEnvelope completed = new EventEnvelope(EventIdentifiers.newUuid(), EventTypes.WALLET_COMMAND_COMPLETED,
WalletCommandCompletedV1.VERSION, Instant.now(), RegionCode.CN, RegionCode.OVERSEAS,
WalletCommandCompletedV1.VERSION, Instant.now(),
String.valueOf(result.customerId()), "WALLET_HOLD", result.businessNo(), 1L, null,
commandEnvelope.traceId(), commandEnvelope.correlationId(), commandEnvelope.eventId(), payload, payloadHash).requireValid();
jdbc.update("INSERT INTO fin_wallet_event_outbox(event_id,event_key,payload_json,status,next_retry_at,created_at,updated_at) VALUES(?,?,CAST(? AS JSON),'PENDING',NOW(3),NOW(3),NOW(3))",
@@ -1,6 +1,12 @@
package com.baiyue.finance.service;
import com.baiyue.common.event.EventEnvelope;
import com.baiyue.common.core.outbox.EventDeliveryJournal;
import com.baiyue.common.core.outbox.EventDeliveryProducer;
import com.baiyue.common.core.outbox.EventDeliveryJournal.Outcome;
import com.baiyue.common.web.EventDeliveryMetrics;
import com.baiyue.common.web.EventDeliveryMetrics.Stream;
import com.baiyue.common.web.EventDeliveryObservation;
import com.baiyue.common.web.EventDeliveryFailure;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.baiyue.common.core.retry.BoundedRetryPolicy;
@@ -21,8 +27,10 @@ import java.util.UUID;
@Component
@RequiredArgsConstructor
@Slf4j
public class WalletResultOutboxRelay {
public class WalletResultOutboxRelay implements EventDeliveryProducer {
private final JdbcTemplate jdbc;
private final EventDeliveryJournal journal;
private final EventDeliveryMetrics metrics;
private final ObjectMapper objectMapper;
private final WalletResultLastlegClient client;
@Value("${baiyue.security.internal-service-token}") private String internalToken;
@@ -42,16 +50,21 @@ public class WalletResultOutboxRelay {
var policy = retryPolicy();
String worker = UUID.randomUUID().toString();
LocalDateTime now = LocalDateTime.now();
int claimed = jdbc.update("UPDATE fin_wallet_event_outbox SET status='SENDING',locked_by=?,locked_at=?,updated_at=? WHERE event_id=? AND status='PENDING' AND next_retry_at<=?",
worker, now, now, eventId, now);
if (claimed != 1) return;
Map<String, Object> row = jdbc.queryForMap("SELECT payload_json,retry_count FROM fin_wallet_event_outbox WHERE event_id=?", eventId);
if (!journal.begin(worker, Stream.FINANCE.service, "WalletCommandCompleted", eventId, eventId,
Stream.FINANCE.target("WalletCommandCompleted"), now,
() -> jdbc.update("UPDATE fin_wallet_event_outbox SET status='SENDING',locked_by=?,locked_at=?,updated_at=? WHERE event_id=? AND status='PENDING' AND next_retry_at<=?",
worker, now, now, eventId, now) == 1)) return;
Map<String, Object> row = jdbc.queryForMap("SELECT payload_json,retry_count FROM fin_wallet_event_outbox WHERE event_id=? AND status='SENDING' AND locked_by=?", eventId, worker);
int failures = ((Number) row.get("retry_count")).intValue();
if (policy.exhausted(failures)) {
jdbc.update("UPDATE fin_wallet_event_outbox SET status='DEAD',locked_by=NULL,locked_at=NULL,last_error=?,updated_at=NOW(3) WHERE event_id=? AND status='SENDING' AND locked_by=?",
"自动投递次数已耗尽(含租约超时)", eventId, worker);
journal.complete(worker, Outcome.DEAD, LocalDateTime.now(), "RETRY_EXHAUSTED", null,
() -> jdbc.update("UPDATE fin_wallet_event_outbox SET status='DEAD',locked_by=NULL,locked_at=NULL,last_error=?,updated_at=NOW(3) WHERE event_id=? AND status='SENDING' AND locked_by=?",
"自动投递次数已耗尽(含租约超时)", eventId, worker));
return;
}
Outcome outcome;
String diagnostic = null;
String auditError = null;
boolean requestStarted = false;
try {
EventEnvelope envelope = objectMapper.readValue(String.valueOf(row.get("payload_json")), EventEnvelope.class).requireValid();
@@ -59,21 +72,31 @@ public class WalletResultOutboxRelay {
var response = client.receive(internalToken, envelope);
EventDeliveryFailure.requireSuccessful(response);
response.data().requireMatches(envelope);
jdbc.update("UPDATE fin_wallet_event_outbox SET status='PUBLISHED',published_at=NOW(3),locked_by=NULL,locked_at=NULL,last_error=NULL,updated_at=NOW(3) WHERE event_id=? AND status='SENDING' AND locked_by=?",
eventId, worker);
outcome = Outcome.valueOf(response.data().outcome().name());
} catch (Exception exception) {
String error = EventDeliveryFailure.diagnostic(exception, internalToken);
diagnostic = EventDeliveryFailure.diagnostic(exception, internalToken);
boolean permanent = EventDeliveryFailure.isPermanent(exception)
|| (!requestStarted && (exception instanceof JsonProcessingException || exception instanceof IllegalArgumentException));
int retries = failures + 1;
String status = permanent || policy.exhausted(retries) ? "DEAD" : "PENDING";
LocalDateTime next = permanent || policy.exhausted(retries) ? LocalDateTime.now() : LocalDateTime.now().plus(policy.delayAfterFailure(retries));
jdbc.update("UPDATE fin_wallet_event_outbox SET status=?,retry_count=?,next_retry_at=?,locked_by=NULL,locked_at=NULL,last_error=?,updated_at=NOW(3) WHERE event_id=? AND status='SENDING' AND locked_by=?",
status, retries, next, safe(error), eventId, worker);
log.warn("资金结果事件投递失败 eventId={}, reason={}", eventId, error);
auditError = EventDeliveryObservation.errorCode(exception, permanent, requestStarted);
outcome = permanent || policy.exhausted(failures + 1) ? Outcome.DEAD : Outcome.RETRY;
}
LocalDateTime finished = LocalDateTime.now();
LocalDateTime next = outcome == Outcome.RETRY ? finished.plus(policy.delayAfterFailure(failures + 1)) : null;
Outcome result = outcome;
String error = diagnostic;
journal.complete(worker, result, finished, auditError, next, () -> {
if (result == Outcome.RETRY || result == Outcome.DEAD) {
return jdbc.update("UPDATE fin_wallet_event_outbox SET status=?,retry_count=?,next_retry_at=?,locked_by=NULL,locked_at=NULL,last_error=?,updated_at=? WHERE event_id=? AND status='SENDING' AND locked_by=?",
result == Outcome.DEAD ? "DEAD" : "PENDING", failures + 1, next == null ? finished : next, safe(error), finished, eventId, worker);
}
return jdbc.update("UPDATE fin_wallet_event_outbox SET status='PUBLISHED',published_at=?,locked_by=NULL,locked_at=NULL,last_error=NULL,updated_at=? WHERE event_id=? AND status='SENDING' AND locked_by=?",
finished, finished, eventId, worker);
});
}
@Scheduled(fixedDelayString = "${baiyue.event-delivery.metrics-sample-ms:30000}")
public void sampleMetrics() { metrics.sample(Stream.FINANCE, LocalDateTime.now()); }
private List<String> candidates() {
return jdbc.queryForList("SELECT event_id FROM fin_wallet_event_outbox WHERE status='PENDING' AND next_retry_at<=NOW(3) ORDER BY created_at,event_id LIMIT 50", String.class);
}
@@ -84,10 +107,12 @@ public class WalletResultOutboxRelay {
for (Map<String, Object> row : jdbc.queryForList("SELECT event_id,locked_by,retry_count FROM fin_wallet_event_outbox WHERE status='SENDING' AND locked_at<? ORDER BY locked_at,event_id LIMIT 50", cutoff)) {
int failures = ((Number) row.get("retry_count")).intValue() + 1;
boolean dead = policy.exhausted(failures);
jdbc.update("UPDATE fin_wallet_event_outbox SET status=?,retry_count=?,next_retry_at=?,locked_by=NULL,locked_at=NULL,last_error=?,updated_at=? WHERE event_id=? AND status='SENDING' AND locked_by=? AND locked_at<?",
dead ? "DEAD" : "PENDING", failures, dead ? now : now.plus(policy.delayAfterFailure(failures)),
"投递租约超时,消费结果未知" + (dead ? ";自动次数已耗尽" : ""), now,
row.get("event_id"), row.get("locked_by"), cutoff);
LocalDateTime next = dead ? null : now.plus(policy.delayAfterFailure(failures));
journal.complete((String) row.get("locked_by"), Outcome.LEASE_EXPIRED, now, "LEASE_EXPIRED", next,
() -> jdbc.update("UPDATE fin_wallet_event_outbox SET status=?,retry_count=?,next_retry_at=?,locked_by=NULL,locked_at=NULL,last_error=?,updated_at=? WHERE event_id=? AND status='SENDING' AND locked_by=? AND locked_at<?",
dead ? "DEAD" : "PENDING", failures, dead ? now : next,
"投递租约超时,消费结果未知" + (dead ? ";自动次数已耗尽" : ""), now,
row.get("event_id"), row.get("locked_by"), cutoff));
}
}
private BoundedRetryPolicy retryPolicy() {
@@ -1,11 +0,0 @@
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: ${FINANCE_DB_URL:jdbc:mysql://127.0.0.1:3306/baiyue_finance?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true}
username: ${FINANCE_DB_USERNAME:root}
password: ${FINANCE_DB_PASSWORD:123456}
baiyue:
finance:
recharge:
qr-code-url: ${FINANCE_RECHARGE_QR_CODE_URL:/customer-recharge-qr.svg}
+10 -11
View File
@@ -3,30 +3,29 @@ server:
spring:
profiles:
active: ${SPRING_PROFILES_ACTIVE:dev}
active: ${SPRING_PROFILES_ACTIVE:test}
application:
name: finance-service
config:
import:
- optional:nacos:baiyue-common.yml?group=BAIYUE&refreshEnabled=true
- optional:nacos:${spring.application.name}.yml?group=BAIYUE&refreshEnabled=true
- nacos:baiyue-common.yml?group=${NACOS_GROUP:BAIYUE}&refreshEnabled=true
- nacos:${spring.application.name}.yml?group=${NACOS_GROUP:BAIYUE}&refreshEnabled=true
cloud:
nacos:
server-addr: ${NACOS_SERVER_ADDR:127.0.0.1:8848}
username: ${NACOS_USERNAME:nacos}
password: ${NACOS_PASSWORD:nacos}
server-addr: ${NACOS_SERVER_ADDR}
username: ${NACOS_USERNAME}
password: ${NACOS_PASSWORD}
discovery:
server-addr: ${NACOS_SERVER_ADDR:127.0.0.1:8848}
server-addr: ${NACOS_SERVER_ADDR}
enabled: ${NACOS_DISCOVERY_ENABLED:true}
register-enabled: ${NACOS_REGISTER_ENABLED:true}
group: ${NACOS_GROUP:BAIYUE}
namespace: ${NACOS_NAMESPACE:public}
namespace: ${NACOS_NAMESPACE}
config:
server-addr: ${NACOS_SERVER_ADDR:127.0.0.1:8848}
namespace: ${NACOS_NAMESPACE:public}
server-addr: ${NACOS_SERVER_ADDR}
namespace: ${NACOS_NAMESPACE}
management.endpoints.web.exposure.include: health,info,prometheus
baiyue:
wallet-event:
event-bridge-url: ${OVERSEAS_EVENT_BRIDGE_URL:http://event-bridge-overseas:9312}
+35
View File
@@ -572,3 +572,38 @@ CREATE TABLE IF NOT EXISTS fin_wallet_event_outbox (
UNIQUE KEY uk_fin_wallet_event_key (event_key),
KEY idx_fin_wallet_event_publish (status,next_retry_at,created_at)
) ENGINE=InnoDB COMMENT='国内Finance到海外资金结果可靠发送箱';
CREATE TABLE IF NOT EXISTS event_delivery_retry_audit (
request_id VARCHAR(36) NOT NULL COMMENT '人工重试请求UUID和幂等键',
producer_table VARCHAR(64) NOT NULL COMMENT '本服务发件箱表名',
entry_id VARCHAR(64) NOT NULL COMMENT '发件箱记录主键',
event_id VARCHAR(128) NOT NULL COMMENT '原事件全局标识',
event_type VARCHAR(64) NOT NULL COMMENT '原事件类型',
payload_hash VARCHAR(71) NOT NULL COMMENT '原事件不可变负载摘要',
operator_name VARCHAR(128) NOT NULL COMMENT '持有运维凭据的操作人标识',
reason VARCHAR(500) NOT NULL COMMENT '人工重试原因',
previous_failures INT NOT NULL COMMENT '重试前累计失败次数',
previous_error VARCHAR(1000) NULL COMMENT '重试前最后一次脱敏错误',
requested_at DATETIME(3) NOT NULL COMMENT '重试申请提交时间',
PRIMARY KEY (request_id),
KEY idx_event_retry_entry (producer_table,entry_id,requested_at),
KEY idx_event_retry_event (event_id,requested_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='业务事件人工重试审计,与恢复待发送状态同事务提交';
CREATE TABLE IF NOT EXISTS event_delivery_attempt (
attempt_id VARCHAR(36) NOT NULL COMMENT '本次投递租约UUID和审计主键',
service_name VARCHAR(32) NOT NULL COMMENT '本库所属生产服务',
event_type VARCHAR(96) NOT NULL COMMENT '白名单业务事件类型',
entry_id VARCHAR(128) NOT NULL COMMENT '生产者发件箱主键',
event_id VARCHAR(128) NULL COMMENT '合法原事件UUID或ULID;格式错误时为空',
target_name VARCHAR(64) NOT NULL COMMENT '固定目标业务服务',
started_at DATETIME(3) NOT NULL COMMENT '领取及审计事务提交前的开始时间',
finished_at DATETIME(3) NULL COMMENT '尝试完成或租约过期恢复时间',
duration_ms BIGINT NULL COMMENT '尝试耗时毫秒',
outcome VARCHAR(24) NOT NULL COMMENT 'STARTED/APPLIED/DUPLICATE/STALE/RETRY/DEAD/LEASE_EXPIRED',
error_code VARCHAR(64) NULL COMMENT '有限错误类别或HTTP状态;不含载荷与令牌',
next_retry_at DATETIME(3) NULL COMMENT '本次失败后下次计划投递时间',
PRIMARY KEY (attempt_id),
KEY idx_delivery_attempt_entry (service_name,entry_id,started_at),
KEY idx_delivery_attempt_outcome (outcome,started_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='本服务业务事件逐次投递审计';