功能:新增消息中心统一入口

This commit is contained in:
xiaowang
2026-05-15 09:33:41 +08:00
parent 2074addc40
commit 479b3e30af
38 changed files with 1572 additions and 193 deletions
@@ -17,8 +17,7 @@ import java.nio.file.Paths;
@SpringBootApplication
public class MessageHubApplication {
private static final String APP_RUNTIME_DIR = "YumiNail";
private static final String MODULE_RUNTIME_DIR = "MessageHub";
private static final String APP_RUNTIME_DIR = "MessageHub";
public static void main(String[] args) {
configureNacosRuntimePaths();
@@ -46,9 +45,9 @@ public class MessageHubApplication {
private static Path resolveBaseRuntimePath() {
String localAppData = System.getenv("LOCALAPPDATA");
if (hasText(localAppData)) {
return Paths.get(localAppData, APP_RUNTIME_DIR, MODULE_RUNTIME_DIR);
return Paths.get(localAppData, APP_RUNTIME_DIR);
}
return Paths.get(System.getProperty("user.home"), ".yuminail", MODULE_RUNTIME_DIR.toLowerCase());
return Paths.get(System.getProperty("user.home"), ".messagehub");
}
private static void configurePathIfAbsent(String key, String child, boolean includeNacosDir) {
@@ -1,53 +1,50 @@
package com.xiaowang.messagehub.config;
import org.springframework.amqp.core.*;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* RabbitMQ配置类
* 用于配置RabbitMQ的队列、交换机和绑定
*/
@Configuration
public class RabbitMQConfig {
// 定义短信队列名称常量
public static final String SMS_QUEUE = "smsQueue";
// 定义邮件队列名称常量
public static final String EMAIL_QUEUE = "emailQueue";
public static final String QQ_QUEUE = "qqQueue";
// 定义统一消息交换机名称常量
public static final String INGRESS_QUEUE = "messagehub.ingress.queue";
public static final String MESSAGE_EXCHANGE = "messageExchange";
public static final String INGRESS_EXCHANGE = "messagehub.ingress.exchange";
public static final String DEAD_LETTER_EXCHANGE = "messageDeadLetterExchange";
public static final String SMS_DEAD_LETTER_QUEUE = "smsDeadLetterQueue";
public static final String EMAIL_DEAD_LETTER_QUEUE = "emailDeadLetterQueue";
public static final String QQ_DEAD_LETTER_QUEUE = "qqDeadLetterQueue";
public static final String INGRESS_DEAD_LETTER_QUEUE = "messagehubIngressDeadLetterQueue";
public static final String SMS_ROUTING_KEY = "sms.#";
public static final String EMAIL_ROUTING_KEY = "email.#";
public static final String QQ_ROUTING_KEY = "qq.#";
public static final String INGRESS_ROUTING_KEY = "message.send";
public static final String SMS_DEAD_LETTER_ROUTING_KEY = "dead.sms";
public static final String EMAIL_DEAD_LETTER_ROUTING_KEY = "dead.email";
public static final String QQ_DEAD_LETTER_ROUTING_KEY = "dead.qq";
// 定义短信路由键常量
public static final String SMS_ROUTING_KEY = "sms.#";
// 定义邮件路由键常量
public static final String EMAIL_ROUTING_KEY = "email.#";
public static final String QQ_ROUTING_KEY = "qq.#";
public static final String INGRESS_DEAD_LETTER_ROUTING_KEY = "dead.ingress";
/**
* 配置短信队列
* @return 持久化的短信队列
*/
@Bean
public Queue smsQueue() {
return QueueBuilder.durable(SMS_QUEUE).build();
}
/**
* 配置邮件队列
* @return 持久化的邮件队列
*/
@Bean
public Queue emailQueue() {
return QueueBuilder.durable(EMAIL_QUEUE).build();
@@ -58,15 +55,21 @@ public class RabbitMQConfig {
return QueueBuilder.durable(QQ_QUEUE).build();
}
/**
* 配置统一消息交换机
* @return 持久化的、自动删除的、不自动声明的主题交换机
*/
@Bean
public Queue ingressQueue() {
return QueueBuilder.durable(INGRESS_QUEUE).build();
}
@Bean
public TopicExchange messageExchange() {
return new TopicExchange(MESSAGE_EXCHANGE, true, false);
}
@Bean
public TopicExchange ingressExchange() {
return new TopicExchange(INGRESS_EXCHANGE, true, false);
}
@Bean
public DirectExchange deadLetterExchange() {
return new DirectExchange(DEAD_LETTER_EXCHANGE, true, false);
@@ -87,19 +90,16 @@ public class RabbitMQConfig {
return QueueBuilder.durable(QQ_DEAD_LETTER_QUEUE).build();
}
/**
* 配置短信队列与交换机的绑定关系
* @return 绑定对象,将短信队列绑定到统一消息交换机,并设置路由键
*/
@Bean
public Queue ingressDeadLetterQueue() {
return QueueBuilder.durable(INGRESS_DEAD_LETTER_QUEUE).build();
}
@Bean
public Binding smsBinding() {
return BindingBuilder.bind(smsQueue()).to(messageExchange()).with(SMS_ROUTING_KEY);
}
/**
* 配置邮件队列与交换机的绑定关系
* @return 绑定对象,将邮件队列绑定到统一消息交换机,并设置路由键
*/
@Bean
public Binding emailBinding() {
return BindingBuilder.bind(emailQueue()).to(messageExchange()).with(EMAIL_ROUTING_KEY);
@@ -110,6 +110,11 @@ public class RabbitMQConfig {
return BindingBuilder.bind(qqQueue()).to(messageExchange()).with(QQ_ROUTING_KEY);
}
@Bean
public Binding ingressBinding() {
return BindingBuilder.bind(ingressQueue()).to(ingressExchange()).with(INGRESS_ROUTING_KEY);
}
@Bean
public Binding smsDeadLetterBinding() {
return BindingBuilder.bind(smsDeadLetterQueue()).to(deadLetterExchange()).with(SMS_DEAD_LETTER_ROUTING_KEY);
@@ -125,6 +130,11 @@ public class RabbitMQConfig {
return BindingBuilder.bind(qqDeadLetterQueue()).to(deadLetterExchange()).with(QQ_DEAD_LETTER_ROUTING_KEY);
}
@Bean
public Binding ingressDeadLetterBinding() {
return BindingBuilder.bind(ingressDeadLetterQueue()).to(deadLetterExchange()).with(INGRESS_DEAD_LETTER_ROUTING_KEY);
}
@Bean
public SimpleRabbitListenerContainerFactory manualAckRabbitListenerContainerFactory(
SimpleRabbitListenerContainerFactoryConfigurer configurer,
@@ -0,0 +1,55 @@
package com.xiaowang.messagehub.controller;
import com.xiaowang.messagehub.dto.api.MessageIdReserveRequest;
import com.xiaowang.messagehub.dto.api.MessageIdReserveResponse;
import com.xiaowang.messagehub.dto.api.MessageStatusResponse;
import com.xiaowang.messagehub.dto.api.PlatformCapabilityView;
import com.xiaowang.messagehub.dto.common.ApiResponse;
import com.xiaowang.messagehub.service.api.MessageHubPublicService;
import com.xiaowang.messagehub.service.source.MessageSourceSystemService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.List;
@Validated
@RestController
@RequestMapping("/api/v1")
public class MessageHubPublicController {
private final MessageHubPublicService publicService;
public MessageHubPublicController(MessageHubPublicService publicService) {
this.publicService = publicService;
}
@PostMapping("/messages/ids")
public ApiResponse<MessageIdReserveResponse> reserveMessageId(
@RequestHeader(MessageSourceSystemService.ACCESS_TOKEN_HEADER) String accessToken,
@Valid @RequestBody MessageIdReserveRequest request) {
return ApiResponse.success(publicService.reserveMessageId(request.getSourceSystem(), accessToken));
}
@GetMapping("/platforms")
public ApiResponse<List<PlatformCapabilityView>> listPlatforms(
@RequestHeader(MessageSourceSystemService.ACCESS_TOKEN_HEADER) String accessToken,
@RequestParam String sourceSystem) {
return ApiResponse.success(publicService.listPlatforms(sourceSystem, accessToken));
}
@GetMapping("/messages/{messageId}/status")
public ApiResponse<MessageStatusResponse> getMessageStatus(
@RequestHeader(MessageSourceSystemService.ACCESS_TOKEN_HEADER) String accessToken,
@PathVariable String messageId,
@RequestParam String sourceSystem) {
return ApiResponse.success(publicService.getStatus(messageId, sourceSystem, accessToken));
}
}
@@ -49,4 +49,9 @@ public class MessageSourceSystemAdminController {
return ApiResponse.success("来源系统状态更新成功",
sourceSystemService.updateSourceSystemStatus(id, request.getEnabled()));
}
@PostMapping("/{id}/access-token/rotate")
public ApiResponse<SourceSystemView> rotateAccessToken(@PathVariable Long id) {
return ApiResponse.success("access token rotated", sourceSystemService.rotateAccessToken(id));
}
}
@@ -29,6 +29,8 @@ public class PushLogView {
private Integer status;
private String dispatchStatus;
private Integer retryCount;
private LocalDateTime nextRetryTime;
@@ -4,6 +4,7 @@ import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Set;
@Data
public class SourceSystemSaveRequest {
@@ -26,4 +27,6 @@ public class SourceSystemSaveRequest {
private Long defaultEmailChannelId;
private Long defaultQqChannelId;
private Set<String> allowedPlatforms;
}
@@ -3,6 +3,7 @@ package com.xiaowang.messagehub.dto.admin;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.Set;
@Data
public class SourceSystemView {
@@ -17,6 +18,14 @@ public class SourceSystemView {
private String remark;
private Set<String> allowedPlatforms;
private String accessToken;
private String accessTokenHint;
private LocalDateTime tokenUpdateTime;
private Long defaultSmsChannelId;
private String defaultSmsChannelName;
@@ -0,0 +1,14 @@
package com.xiaowang.messagehub.dto.api;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
@Data
public class MessageIdReserveRequest {
@NotBlank(message = "sourceSystem is required")
@Size(max = 64, message = "sourceSystem length must not exceed 64")
private String sourceSystem;
}
@@ -0,0 +1,11 @@
package com.xiaowang.messagehub.dto.api;
import lombok.Data;
@Data
public class MessageIdReserveResponse {
private String messageId;
private String dispatchStatus;
}
@@ -0,0 +1,30 @@
package com.xiaowang.messagehub.dto.api;
import lombok.Data;
import java.util.LinkedHashMap;
import java.util.Map;
@Data
public class MessageIngressEnvelope {
private String messageId;
private String sourceSystem;
private String platform;
private String receiver;
private String msgType;
private String templateCode;
private Map<String, Object> templateParams = new LinkedHashMap<>();
private Long channelId;
private String uniqueId;
private Map<String, Object> platformParams = new LinkedHashMap<>();
}
@@ -0,0 +1,41 @@
package com.xiaowang.messagehub.dto.api;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class MessageStatusResponse {
private String messageId;
private String sourceSystem;
private String uniqueId;
private String platform;
private String receiver;
private String msgType;
private String dispatchStatus;
private Integer legacyStatus;
private Long channelId;
private String providerCode;
private Integer retryCount;
private String failReason;
private String providerResponse;
private LocalDateTime sendTime;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,20 @@
package com.xiaowang.messagehub.dto.api;
import lombok.Data;
import java.util.LinkedHashMap;
import java.util.Map;
@Data
public class PlatformCapabilityView {
private String platform;
private String name;
private boolean available;
private int enabledChannelCount;
private Map<String, String> platformParams = new LinkedHashMap<>();
}
@@ -29,6 +29,15 @@ public class MessageSourceSystemDO {
@TableField("remark")
private String remark;
@TableField("access_token_hash")
private String accessTokenHash;
@TableField("access_token_hint")
private String accessTokenHint;
@TableField("token_update_time")
private LocalDateTime tokenUpdateTime;
@TableLogic
@TableField("deleted")
private Integer deleted;
@@ -0,0 +1,33 @@
package com.xiaowang.messagehub.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("message_source_system_permission")
public class MessageSourceSystemPermissionDO {
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
@TableField("system_id")
private Long systemId;
@TableField("platform")
private String platform;
@TableField("enabled")
private Integer enabled;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}
@@ -50,6 +50,9 @@ public class PushLogDO {
@TableField("status")
private Integer status; // 推送状态,如0-待发送,1-发送成功,2-发送失败等
@TableField("dispatch_status")
private String dispatchStatus;
@TableField("retry_count")
private Integer retryCount; // 重试次数
@@ -0,0 +1,54 @@
package com.xiaowang.messagehub.enums;
import java.util.Locale;
public enum DispatchStatusEnum {
ACCEPTED(0),
PENDING(0),
SUCCESS(1),
FAILED(2);
private final int legacyStatus;
DispatchStatusEnum(int legacyStatus) {
this.legacyStatus = legacyStatus;
}
public int getLegacyStatus() {
return legacyStatus;
}
public static DispatchStatusEnum fromCode(String code) {
if (code == null || code.trim().isEmpty()) {
return null;
}
String normalized = code.trim().toUpperCase(Locale.ROOT);
for (DispatchStatusEnum item : values()) {
if (item.name().equals(normalized)) {
return item;
}
}
throw new IllegalArgumentException("Unsupported dispatch status: " + code);
}
public static DispatchStatusEnum fromLegacyStatus(Integer status) {
if (status == null) {
return ACCEPTED;
}
if (status == 1) {
return SUCCESS;
}
if (status == 2) {
return FAILED;
}
return PENDING;
}
public static String normalize(String code, Integer legacyStatus) {
DispatchStatusEnum status = fromCode(code);
if (status != null) {
return status.name();
}
return fromLegacyStatus(legacyStatus).name();
}
}
@@ -1,14 +1,12 @@
package com.xiaowang.messagehub.listener;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.xiaowang.messagehub.config.RabbitMQConfig;
import com.xiaowang.messagehub.dto.EmailMessageDTO;
import com.xiaowang.messagehub.model.EmailDispatchRequest;
import com.xiaowang.messagehub.model.ManagedChannelConfig;
import com.xiaowang.messagehub.service.EmailSendService;
import com.xiaowang.messagehub.service.impl.MessageHandleService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.xiaowang.messagehub.service.ingress.MessageDispatchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
@@ -22,17 +20,17 @@ import java.time.LocalDateTime;
@Component
public class EmailQueueListener {
private final EmailSendService emailSendService;
private final MessageHandleService messageHandleService;
private final MessageDispatchService messageDispatchService;
private final ObjectMapper objectMapper;
private final RabbitTemplate rabbitTemplate;
public EmailQueueListener(EmailSendService emailSendService,
MessageHandleService messageHandleService,
public EmailQueueListener(MessageHandleService messageHandleService,
MessageDispatchService messageDispatchService,
ObjectMapper objectMapper,
RabbitTemplate rabbitTemplate) {
this.emailSendService = emailSendService;
this.messageHandleService = messageHandleService;
this.messageDispatchService = messageDispatchService;
this.objectMapper = objectMapper;
this.rabbitTemplate = rabbitTemplate;
}
@@ -45,36 +43,18 @@ public class EmailQueueListener {
try {
String messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
log.info("========================================");
log.info("收到邮件消息");
log.info("消息ID: {}", messageId);
log.info("消息内容: {}", messageBody);
log.info("========================================");
log.info("收到邮件消息, messageId: {}, body: {}", messageId, messageBody);
EmailMessageDTO messageDTO = objectMapper.readValue(messageBody, EmailMessageDTO.class);
MessageHandleService.MessageLogDecision decision =
messageHandleService.validateAndPrepareLog(messageDTO, messageId, sendTime, messageBody);
if (!decision.shouldProcess()) {
log.warn("邮件消息无需继续处理,消息ID: {}, reason: {}", messageId, decision.reason());
MessageDispatchService.DispatchOutcome outcome =
messageDispatchService.dispatch(messageDTO, messageId, messageBody);
if (!outcome.processed()) {
log.warn("Legacy email message skipped, messageId: {}, reason: {}", messageId, outcome.reason());
acknowledge(channel, deliveryTag);
return;
}
EmailDispatchRequest request = buildDispatchRequest(messageDTO);
ManagedChannelConfig dispatchChannel = emailSendService.sendEmail(request);
messageHandleService.markDispatchChannel(
messageId,
dispatchChannel.entity().getId(),
dispatchChannel.entity().getProviderCode()
);
messageHandleService.markSendSuccess(messageId, request.getContent());
log.info("========================================");
log.info("邮件消息处理完成");
log.info("消息ID: {}", messageId);
log.info("收件人: {}", messageDTO.getReceiver());
log.info("主题: {}", request.getSubject());
log.info("========================================");
log.info("邮件消息处理完成, messageId: {}, receiver: {}", messageId, messageDTO.getReceiver());
acknowledge(channel, deliveryTag);
} catch (JsonProcessingException exception) {
log.error("邮件消息解析失败,消息ID: {}", messageId, exception);
@@ -85,7 +65,7 @@ public class EmailQueueListener {
MessageHandleService.MessageRetryDecision retryDecision =
messageHandleService.recordSendFailure(messageId, "EMAIL", sendTime, exception);
if (retryDecision.shouldRetry()) {
log.warn("邮件消息准备重试,消息ID: {}, retryCount: {}, reason: {}",
log.warn("邮件消息准备重试,messageId: {}, retryCount: {}, reason: {}",
messageId, retryDecision.retryCount(), retryDecision.failReason());
requeue(channel, deliveryTag);
return;
@@ -97,21 +77,6 @@ public class EmailQueueListener {
}
}
private EmailDispatchRequest buildDispatchRequest(EmailMessageDTO messageDTO) {
EmailDispatchRequest request = new EmailDispatchRequest();
request.setReceiver(messageDTO.getReceiver());
request.setSubject(messageDTO.getSubject());
request.setContent(messageDTO.getContent());
request.setBodyType(messageDTO.getBodyType());
request.setEmailTemplateCode(messageDTO.getEmailTemplateCode());
request.setLegacyTemplateCode(messageDTO.getTemplateCode());
request.setTemplateParams(messageDTO.getTemplateParams());
request.setChannelId(messageDTO.getChannelId());
request.setSourceSystem(messageDTO.getSourceSystem());
request.setAttachmentIds(messageDTO.getAttachmentIds());
return request;
}
private void acknowledge(Channel channel, long deliveryTag) {
try {
channel.basicAck(deliveryTag, false);
@@ -0,0 +1,158 @@
package com.xiaowang.messagehub.listener;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.xiaowang.messagehub.config.RabbitMQConfig;
import com.xiaowang.messagehub.dto.MessageDTO;
import com.xiaowang.messagehub.dto.api.MessageIngressEnvelope;
import com.xiaowang.messagehub.service.impl.MessageHandleService;
import com.xiaowang.messagehub.service.ingress.MessageDispatchService;
import com.xiaowang.messagehub.service.ingress.MessageIngressEnvelopeMapper;
import com.xiaowang.messagehub.service.source.MessageSourceSystemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
@Slf4j
@Component
public class MessageIngressQueueListener {
private final ObjectMapper objectMapper;
private final MessageIngressEnvelopeMapper envelopeMapper;
private final MessageSourceSystemService sourceSystemService;
private final MessageDispatchService messageDispatchService;
private final MessageHandleService messageHandleService;
private final RabbitTemplate rabbitTemplate;
public MessageIngressQueueListener(ObjectMapper objectMapper,
MessageIngressEnvelopeMapper envelopeMapper,
MessageSourceSystemService sourceSystemService,
MessageDispatchService messageDispatchService,
MessageHandleService messageHandleService,
RabbitTemplate rabbitTemplate) {
this.objectMapper = objectMapper;
this.envelopeMapper = envelopeMapper;
this.sourceSystemService = sourceSystemService;
this.messageDispatchService = messageDispatchService;
this.messageHandleService = messageHandleService;
this.rabbitTemplate = rabbitTemplate;
}
@RabbitListener(queues = RabbitMQConfig.INGRESS_QUEUE, containerFactory = "manualAckRabbitListenerContainerFactory")
public void handleIngressMessage(Message message, Channel channel) {
String headerMessageId = message.getMessageProperties().getMessageId();
LocalDateTime sendTime = LocalDateTime.now();
long deliveryTag = message.getMessageProperties().getDeliveryTag();
MessageIngressEnvelope envelope = null;
boolean reservationValidated = false;
try {
String messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
envelope = objectMapper.readValue(messageBody, MessageIngressEnvelope.class);
String accessToken = readAccessToken(message);
sourceSystemService.authenticateSourceSystem(envelope.getSourceSystem(), accessToken);
messageHandleService.requireIngressReservation(envelope.getMessageId(), envelope.getSourceSystem());
reservationValidated = true;
sourceSystemService.requirePlatformPermission(envelope.getSourceSystem(), envelope.getPlatform());
MessageDTO messageDTO = envelopeMapper.toMessageDTO(envelope);
MessageDispatchService.DispatchOutcome outcome =
messageDispatchService.dispatch(messageDTO, envelope.getMessageId(), messageBody);
if (!outcome.processed()) {
log.warn("Ingress message skipped, messageId: {}, reason: {}", envelope.getMessageId(), outcome.reason());
}
acknowledge(channel, deliveryTag);
} catch (JsonProcessingException exception) {
String reason = "Ingress message body parse failed: " + exception.getOriginalMessage();
log.error(reason, exception);
publishDeadLetter(message, reason);
acknowledge(channel, deliveryTag);
} catch (IllegalArgumentException exception) {
String messageId = resolveMessageId(envelope, headerMessageId);
String platform = resolvePlatform(envelope);
log.error("Ingress message rejected, messageId: {}, reason: {}", messageId, exception.getMessage());
if (reservationValidated) {
markRejectedIfPossible(messageId, platform, sendTime, exception.getMessage());
}
publishDeadLetter(message, exception.getMessage());
acknowledge(channel, deliveryTag);
} catch (Exception exception) {
String messageId = resolveMessageId(envelope, headerMessageId);
String platform = resolvePlatform(envelope);
log.error("Ingress message handling failed, messageId: {}", messageId, exception);
MessageHandleService.MessageRetryDecision retryDecision =
messageHandleService.recordSendFailure(messageId, platform, sendTime, exception);
if (retryDecision.shouldRetry()) {
log.warn("Ingress message will retry, messageId: {}, retryCount: {}, reason: {}",
messageId, retryDecision.retryCount(), retryDecision.failReason());
requeue(channel, deliveryTag);
return;
}
messageHandleService.markMessageRejected(messageId, platform, sendTime, retryDecision.failReason());
publishDeadLetter(message, retryDecision.failReason());
acknowledge(channel, deliveryTag);
}
}
private String readAccessToken(Message message) {
Object value = message.getMessageProperties().getHeaders().get(MessageSourceSystemService.ACCESS_TOKEN_HEADER);
if (value == null) {
return null;
}
return String.valueOf(value);
}
private String resolveMessageId(MessageIngressEnvelope envelope, String headerMessageId) {
if (envelope != null && StringUtils.hasText(envelope.getMessageId())) {
return envelope.getMessageId();
}
return headerMessageId;
}
private String resolvePlatform(MessageIngressEnvelope envelope) {
if (envelope != null && StringUtils.hasText(envelope.getPlatform())) {
return envelope.getPlatform();
}
return "UNKNOWN";
}
private void markRejectedIfPossible(String messageId, String platform, LocalDateTime sendTime, String reason) {
if (!StringUtils.hasText(messageId)) {
return;
}
messageHandleService.markMessageRejected(messageId, platform, sendTime, reason);
}
private void acknowledge(Channel channel, long deliveryTag) {
try {
channel.basicAck(deliveryTag, false);
} catch (Exception ackException) {
log.error("Ingress message ack failed", ackException);
}
}
private void requeue(Channel channel, long deliveryTag) {
try {
channel.basicNack(deliveryTag, false, true);
} catch (Exception nackException) {
log.error("Ingress message requeue failed", nackException);
}
}
private void publishDeadLetter(Message message, String reason) {
try {
message.getMessageProperties().setHeader("x-messagehub-dead-letter-reason", reason);
rabbitTemplate.send(RabbitMQConfig.DEAD_LETTER_EXCHANGE, RabbitMQConfig.INGRESS_DEAD_LETTER_ROUTING_KEY, message);
} catch (Exception exception) {
log.error("Ingress message dead-letter publish failed", exception);
}
}
}
@@ -5,9 +5,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.xiaowang.messagehub.config.RabbitMQConfig;
import com.xiaowang.messagehub.dto.QqMessageDTO;
import com.xiaowang.messagehub.model.QqDispatchRequest;
import com.xiaowang.messagehub.service.QqSendService;
import com.xiaowang.messagehub.service.impl.MessageHandleService;
import com.xiaowang.messagehub.service.ingress.MessageDispatchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
@@ -16,23 +15,22 @@ import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
@Slf4j
@Component
public class QqQueueListener {
private final QqSendService qqSendService;
private final MessageHandleService messageHandleService;
private final MessageDispatchService messageDispatchService;
private final ObjectMapper objectMapper;
private final RabbitTemplate rabbitTemplate;
public QqQueueListener(QqSendService qqSendService,
MessageHandleService messageHandleService,
public QqQueueListener(MessageHandleService messageHandleService,
MessageDispatchService messageDispatchService,
ObjectMapper objectMapper,
RabbitTemplate rabbitTemplate) {
this.qqSendService = qqSendService;
this.messageHandleService = messageHandleService;
this.messageDispatchService = messageDispatchService;
this.objectMapper = objectMapper;
this.rabbitTemplate = rabbitTemplate;
}
@@ -48,24 +46,15 @@ public class QqQueueListener {
log.info("Received QQ message, messageId: {}, body: {}", messageId, messageBody);
QqMessageDTO messageDTO = objectMapper.readValue(messageBody, QqMessageDTO.class);
MessageHandleService.MessageLogDecision decision =
messageHandleService.validateAndPrepareLog(messageDTO, messageId, sendTime, messageBody);
if (!decision.shouldProcess()) {
log.warn("QQ message skipped, messageId: {}, reason: {}", messageId, decision.reason());
MessageDispatchService.DispatchOutcome outcome =
messageDispatchService.dispatch(messageDTO, messageId, messageBody);
if (!outcome.processed()) {
log.warn("Legacy QQ message skipped, messageId: {}, reason: {}", messageId, outcome.reason());
acknowledge(channel, deliveryTag);
return;
}
QqSendService.QqDispatchResult dispatchResult = qqSendService.sendQq(buildDispatchRequest(messageDTO));
messageHandleService.markDispatchChannel(
messageId,
dispatchResult.channelConfig().entity().getId(),
dispatchResult.channelConfig().entity().getProviderCode()
);
if (dispatchResult.sendResult() != null) {
messageHandleService.markProviderResponse(messageId, dispatchResult.sendResult().getRawResponse());
}
messageHandleService.markSendSuccess(messageId, dispatchResult.finalContent());
log.info("QQ message handled, messageId: {}, receiver: {}", messageId, messageDTO.getReceiver());
acknowledge(channel, deliveryTag);
} catch (JsonProcessingException exception) {
log.error("QQ message JSON parse failed, messageId: {}", messageId, exception);
@@ -88,19 +77,6 @@ public class QqQueueListener {
}
}
private QqDispatchRequest buildDispatchRequest(QqMessageDTO messageDTO) {
QqDispatchRequest request = new QqDispatchRequest();
request.setReceiver(messageDTO.getReceiver());
request.setTargetType(messageDTO.getTargetType());
request.setContent(messageDTO.getContent());
request.setContentMode(messageDTO.getContentMode());
request.setTemplateCode(messageDTO.getTemplateCode());
request.setTemplateParams(messageDTO.getTemplateParams() == null ? new LinkedHashMap<>() : new LinkedHashMap<>(messageDTO.getTemplateParams()));
request.setChannelId(messageDTO.getChannelId());
request.setSourceSystem(messageDTO.getSourceSystem());
return request;
}
private void acknowledge(Channel channel, long deliveryTag) {
try {
channel.basicAck(deliveryTag, false);
@@ -1,12 +1,13 @@
package com.xiaowang.messagehub.listener;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.xiaowang.messagehub.config.RabbitMQConfig;
import com.xiaowang.messagehub.dto.SmsMessageDTO;
import com.xiaowang.messagehub.service.SmsSendService;
import com.xiaowang.messagehub.service.impl.MessageHandleService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.xiaowang.messagehub.service.ingress.MessageDispatchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
@@ -25,15 +26,18 @@ public class SmsQueueListener {
private final ObjectMapper objectMapper;
private final SmsSendService smsSendService;
private final MessageHandleService messageHandleService;
private final MessageDispatchService messageDispatchService;
private final RabbitTemplate rabbitTemplate;
public SmsQueueListener(ObjectMapper objectMapper,
SmsSendService smsSendService,
MessageHandleService messageHandleService,
MessageDispatchService messageDispatchService,
RabbitTemplate rabbitTemplate) {
this.objectMapper = objectMapper;
this.smsSendService = smsSendService;
this.messageHandleService = messageHandleService;
this.messageDispatchService = messageDispatchService;
this.rabbitTemplate = rabbitTemplate;
}
@@ -52,25 +56,18 @@ public class SmsQueueListener {
logger.info("========================================");
SmsMessageDTO smsMessageDTO = objectMapper.readValue(messageBody, SmsMessageDTO.class);
MessageHandleService.MessageLogDecision decision =
messageHandleService.validateAndPrepareLog(smsMessageDTO, messageId, sendTime);
if (!decision.shouldProcess()) {
logger.warn("短信消息无需继续处理,messageId: {}, reason: {}", messageId, decision.reason());
MessageDispatchService.DispatchOutcome outcome =
messageDispatchService.dispatch(smsMessageDTO, messageId, messageBody);
if (!outcome.processed()) {
logger.warn("Legacy SMS message skipped, messageId: {}, reason: {}", messageId, outcome.reason());
acknowledge(channel, deliveryTag);
return;
}
smsSendService.sendSms(smsMessageDTO);
String finalContent = messageHandleService.buildFinalContent(
smsMessageDTO.getTemplateCode(),
smsMessageDTO.getTemplateParams()
);
messageHandleService.markSendSuccess(messageId, finalContent);
logger.info("========================================");
logger.info("短信消息处理完成");
logger.info("消息ID: {}", messageId);
logger.info("手机号: {}", smsMessageDTO.getReceiver());
logger.info("手机号码: {}", smsMessageDTO.getReceiver());
logger.info("发送方式: {}", smsMessageDTO.getSendMethod());
logger.info("========================================");
acknowledge(channel, deliveryTag);
@@ -0,0 +1,9 @@
package com.xiaowang.messagehub.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.messagehub.entity.MessageSourceSystemPermissionDO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface MessageSourceSystemPermissionMapper extends BaseMapper<MessageSourceSystemPermissionDO> {
}
@@ -85,9 +85,10 @@ public interface PushLogMapper extends BaseMapper<PushLogDO> {
* @param failReason 失败原因
* @return 更新的记录数
*/
@Update("UPDATE push_log SET status = #{status}, retry_count = retry_count + 1, fail_reason = #{failReason}, next_retry_time = #{nextRetryTime}, dead_letter_reason = #{deadLetterReason} WHERE id = #{id}")
@Update("UPDATE push_log SET status = #{status}, dispatch_status = #{dispatchStatus}, retry_count = retry_count + 1, fail_reason = #{failReason}, next_retry_time = #{nextRetryTime}, dead_letter_reason = #{deadLetterReason} WHERE id = #{id}")
int updateRetryStatus(@Param("id") String id,
@Param("status") Integer status,
@Param("dispatchStatus") String dispatchStatus,
@Param("failReason") String failReason,
@Param("nextRetryTime") LocalDateTime nextRetryTime,
@Param("deadLetterReason") String deadLetterReason);
@@ -0,0 +1,4 @@
package com.xiaowang.messagehub.model;
public record SmsDispatchResult(ManagedChannelConfig channelConfig, SmsSendResult sendResult, String finalContent) {
}
@@ -3,6 +3,7 @@ package com.xiaowang.messagehub.service.admin;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.messagehub.dto.admin.PushLogView;
import com.xiaowang.messagehub.entity.PushLogDO;
import com.xiaowang.messagehub.enums.DispatchStatusEnum;
import com.xiaowang.messagehub.mapper.PushLogMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@@ -66,6 +67,7 @@ public class PushLogAdminService {
view.setTemplateCode(entity.getTemplateCode());
view.setFinalContent(entity.getFinalContent());
view.setStatus(entity.getStatus());
view.setDispatchStatus(DispatchStatusEnum.normalize(entity.getDispatchStatus(), entity.getStatus()));
view.setRetryCount(entity.getRetryCount());
view.setNextRetryTime(entity.getNextRetryTime());
view.setFailReason(entity.getFailReason());
@@ -0,0 +1,148 @@
package com.xiaowang.messagehub.service.api;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.messagehub.dto.api.MessageIdReserveResponse;
import com.xiaowang.messagehub.dto.api.MessageStatusResponse;
import com.xiaowang.messagehub.dto.api.PlatformCapabilityView;
import com.xiaowang.messagehub.entity.MessageChannelConfigDO;
import com.xiaowang.messagehub.entity.PushLogDO;
import com.xiaowang.messagehub.enums.ChannelHealthStatusEnum;
import com.xiaowang.messagehub.enums.ChannelTypeEnum;
import com.xiaowang.messagehub.enums.DispatchStatusEnum;
import com.xiaowang.messagehub.mapper.MessageChannelConfigMapper;
import com.xiaowang.messagehub.service.impl.MessageHandleService;
import com.xiaowang.messagehub.service.source.MessageSourceSystemService;
import com.xiaowang.messagehub.support.id.TimeOrderedSnowflakeIdGenerator;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Service
public class MessageHubPublicService {
private static final int PROVIDER_RESPONSE_LIMIT = 4000;
private final MessageSourceSystemService sourceSystemService;
private final MessageHandleService messageHandleService;
private final MessageChannelConfigMapper channelConfigMapper;
private final TimeOrderedSnowflakeIdGenerator idGenerator;
public MessageHubPublicService(MessageSourceSystemService sourceSystemService,
MessageHandleService messageHandleService,
MessageChannelConfigMapper channelConfigMapper,
TimeOrderedSnowflakeIdGenerator idGenerator) {
this.sourceSystemService = sourceSystemService;
this.messageHandleService = messageHandleService;
this.channelConfigMapper = channelConfigMapper;
this.idGenerator = idGenerator;
}
public MessageIdReserveResponse reserveMessageId(String sourceSystem, String accessToken) {
sourceSystemService.authenticateSourceSystem(sourceSystem, accessToken);
String messageId = idGenerator.nextIdString();
messageHandleService.reserveAcceptedLog(messageId, sourceSystem);
MessageIdReserveResponse response = new MessageIdReserveResponse();
response.setMessageId(messageId);
response.setDispatchStatus(DispatchStatusEnum.ACCEPTED.name());
return response;
}
public List<PlatformCapabilityView> listPlatforms(String sourceSystem, String accessToken) {
sourceSystemService.authenticateSourceSystem(sourceSystem, accessToken);
Set<String> allowedPlatforms = sourceSystemService.listAllowedPlatforms(sourceSystem);
return allowedPlatforms.stream()
.map(this::toPlatformView)
.filter(PlatformCapabilityView::isAvailable)
.toList();
}
public MessageStatusResponse getStatus(String messageId, String sourceSystem, String accessToken) {
sourceSystemService.authenticateSourceSystem(sourceSystem, accessToken);
PushLogDO pushLog = messageHandleService.getPushLog(messageId);
if (pushLog == null) {
throw new IllegalArgumentException("messageId not found: " + messageId);
}
if (!StringUtils.hasText(pushLog.getSourceSystem())
|| !pushLog.getSourceSystem().equalsIgnoreCase(sourceSystem.trim())) {
throw new IllegalArgumentException("messageId does not belong to sourceSystem: " + sourceSystem);
}
return toStatusResponse(pushLog);
}
private PlatformCapabilityView toPlatformView(String platform) {
ChannelTypeEnum channelType = ChannelTypeEnum.fromCode(platform);
List<MessageChannelConfigDO> enabledChannels = listEnabledChannels(channelType.getCode());
PlatformCapabilityView view = new PlatformCapabilityView();
view.setPlatform(channelType.getCode());
view.setName(channelType.getLabel());
view.setEnabledChannelCount(enabledChannels.size());
view.setAvailable(!enabledChannels.isEmpty());
view.setPlatformParams(platformParams(channelType));
return view;
}
private List<MessageChannelConfigDO> listEnabledChannels(String platform) {
LambdaQueryWrapper<MessageChannelConfigDO> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(MessageChannelConfigDO::getChannelType, platform)
.eq(MessageChannelConfigDO::getEnabled, 1)
.orderByDesc(MessageChannelConfigDO::getIsDefault)
.orderByDesc(MessageChannelConfigDO::getUpdateTime);
return channelConfigMapper.selectList(queryWrapper).stream()
.filter(item -> !ChannelHealthStatusEnum.UNHEALTHY.getCode().equalsIgnoreCase(item.getHealthStatus()))
.toList();
}
private Map<String, String> platformParams(ChannelTypeEnum channelType) {
Map<String, String> params = new LinkedHashMap<>();
switch (channelType) {
case SMS -> params.put("sendMethod", "SPUG or OTHER; optional, defaults to OTHER");
case EMAIL -> {
params.put("subject", "Email subject; optional when emailTemplateCode/templateCode is provided");
params.put("content", "Email body; optional when emailTemplateCode/templateCode is provided");
params.put("bodyType", "TEXT or HTML");
params.put("emailTemplateCode", "Email template code");
params.put("attachmentIds", "Array of uploaded attachment ids");
}
case QQ -> {
params.put("targetType", "FRIEND or GROUP");
params.put("content", "Text or OneBot JSON content");
params.put("contentMode", "TEXT or ONEBOT_JSON");
}
}
return params;
}
private MessageStatusResponse toStatusResponse(PushLogDO entity) {
MessageStatusResponse response = new MessageStatusResponse();
response.setMessageId(entity.getId());
response.setSourceSystem(entity.getSourceSystem());
response.setUniqueId(entity.getUniqueId());
response.setPlatform(entity.getChannelType());
response.setReceiver(entity.getReceiver());
response.setMsgType(entity.getMsgType());
response.setDispatchStatus(DispatchStatusEnum.normalize(entity.getDispatchStatus(), entity.getStatus()));
response.setLegacyStatus(entity.getStatus());
response.setChannelId(entity.getChannelId());
response.setProviderCode(entity.getProviderCode());
response.setRetryCount(entity.getRetryCount());
response.setFailReason(entity.getFailReason());
response.setProviderResponse(truncate(entity.getProviderResponse(), PROVIDER_RESPONSE_LIMIT));
response.setSendTime(entity.getSendTime());
response.setCreateTime(entity.getCreateTime());
response.setUpdateTime(entity.getUpdateTime());
return response;
}
private String truncate(String value, int limit) {
if (value == null || value.length() <= limit) {
return value;
}
return value.substring(0, limit) + "...";
}
}
@@ -25,6 +25,7 @@ import com.xiaowang.messagehub.model.ManagedChannelConfig;
import com.xiaowang.messagehub.model.QqDispatchRequest;
import com.xiaowang.messagehub.model.QqSendResult;
import com.xiaowang.messagehub.model.SmsDispatchRequest;
import com.xiaowang.messagehub.model.SmsDispatchResult;
import com.xiaowang.messagehub.model.SmsSendResult;
import com.xiaowang.messagehub.service.QqSendService;
import com.xiaowang.messagehub.service.channel.email.EmailChannelProvider;
@@ -358,6 +359,10 @@ public class MessageChannelService {
}
public void sendSms(SmsDispatchRequest request) {
dispatchSms(request);
}
public SmsDispatchResult dispatchSms(SmsDispatchRequest request) {
ManagedChannelConfig channelConfig = resolveDispatchChannel(ChannelTypeEnum.SMS, request.getChannelId(), request.getSourceSystem());
PushTemplateDO template = requireEnabledTemplate(request.getTemplateCode());
validateTemplateChannelBinding(template, channelConfig.entity().getId());
@@ -376,7 +381,8 @@ public class MessageChannelService {
} else if (StringUtils.hasText(template.getExternalId())) {
request.setTemplateExternalId(template.getExternalId());
}
resolveSmsProvider(channelConfig.entity().getProviderCode()).send(channelConfig, request);
SmsSendResult sendResult = resolveSmsProvider(channelConfig.entity().getProviderCode()).send(channelConfig, request);
return new SmsDispatchResult(channelConfig, sendResult, request.getContent());
}
public QqSendService.QqDispatchResult sendQq(QqDispatchRequest request) {
@@ -185,8 +185,8 @@ public class AttachmentStorageService {
private Path resolveStorageRoot() {
String localAppData = System.getenv("LOCALAPPDATA");
Path base = StringUtils.hasText(localAppData)
? Paths.get(localAppData, "YumiNail", "MessageHub")
: Paths.get(System.getProperty("user.home"), ".yuminail", "messagehub");
? Paths.get(localAppData, "MessageHub")
: Paths.get(System.getProperty("user.home"), ".messagehub");
return base.resolve("uploads").resolve("email-attachments").toAbsolutePath().normalize();
}
@@ -6,6 +6,7 @@ import com.xiaowang.messagehub.config.MessageChannelProperties;
import com.xiaowang.messagehub.dto.MessageDTO;
import com.xiaowang.messagehub.entity.PushLogDO;
import com.xiaowang.messagehub.entity.PushTemplateDO;
import com.xiaowang.messagehub.enums.DispatchStatusEnum;
import com.xiaowang.messagehub.mapper.PushLogMapper;
import com.xiaowang.messagehub.mapper.PushTemplateMapper;
import com.xiaowang.messagehub.service.source.MessageSourceSystemService;
@@ -54,11 +55,58 @@ public class MessageHandleService {
return validateAndPrepareLog(messageDTO, messageId, sendTime, null);
}
public void reserveAcceptedLog(String messageId, String sourceSystem) {
if (!StringUtils.hasText(messageId)) {
throw new IllegalArgumentException("messageId is required");
}
if (!StringUtils.hasText(sourceSystem)) {
throw new IllegalArgumentException("sourceSystem is required");
}
PushLogDO existingLog = pushLogMapper.selectById(messageId);
if (existingLog != null) {
throw new IllegalArgumentException("messageId already exists: " + messageId);
}
PushLogDO pushLog = new PushLogDO();
pushLog.setId(messageId.trim());
pushLog.setSourceSystem(sourceSystem.trim().toLowerCase());
pushLog.setStatus(DispatchStatusEnum.ACCEPTED.getLegacyStatus());
pushLog.setDispatchStatus(DispatchStatusEnum.ACCEPTED.name());
pushLog.setRetryCount(0);
insertPendingLog(pushLog);
}
public PushLogDO getPushLog(String messageId) {
if (!StringUtils.hasText(messageId)) {
return null;
}
return pushLogMapper.selectById(messageId.trim());
}
public PushLogDO requireIngressReservation(String messageId, String sourceSystem) {
if (!StringUtils.hasText(messageId)) {
throw new IllegalArgumentException("messageId is required");
}
if (!StringUtils.hasText(sourceSystem)) {
throw new IllegalArgumentException("sourceSystem is required");
}
PushLogDO pushLog = pushLogMapper.selectById(messageId.trim());
if (pushLog == null) {
throw new IllegalArgumentException("messageId must be reserved before MQ ingress: " + messageId);
}
if (!StringUtils.hasText(pushLog.getSourceSystem())
|| !pushLog.getSourceSystem().equalsIgnoreCase(sourceSystem.trim())) {
throw new IllegalArgumentException("messageId does not belong to sourceSystem: " + sourceSystem);
}
return pushLog;
}
public MessageLogDecision validateAndPrepareLog(MessageDTO messageDTO, String messageId, LocalDateTime sendTime, String requestPayload) {
String failReason = validateMessage(messageDTO);
if (failReason != null) {
PushLogDO rejectedLog = buildPushLog(messageDTO, messageId, sendTime);
rejectedLog.setDispatchStatus(DispatchStatusEnum.FAILED.name());
rejectedLog.setRequestPayload(requestPayload);
saveOrUpdateRejectedLog(rejectedLog, failReason);
logger.warn("消息校验失败,messageId: {}, reason: {}", messageId, failReason);
@@ -92,6 +140,7 @@ public class MessageHandleService {
PushLogDO pushLog = buildPushLog(messageDTO, messageId, sendTime);
pushLog.setRequestPayload(requestPayload);
pushLog.setStatus(0);
pushLog.setDispatchStatus(DispatchStatusEnum.PENDING.name());
pushLog.setFailReason(null);
insertPendingLog(pushLog);
logger.info("消息校验通过,messageId: {}, sourceSystem: {}, channelType: {}",
@@ -129,6 +178,7 @@ public class MessageHandleService {
PushLogDO pushLog = new PushLogDO();
pushLog.setId(messageId);
pushLog.setStatus(1);
pushLog.setDispatchStatus(DispatchStatusEnum.SUCCESS.name());
pushLog.setFailReason(null);
pushLog.setDeadLetterReason(null);
pushLog.setNextRetryTime(null);
@@ -164,6 +214,7 @@ public class MessageHandleService {
PushLogDO pushLog = new PushLogDO();
pushLog.setId(messageId);
pushLog.setStatus(status);
pushLog.setDispatchStatus(DispatchStatusEnum.fromLegacyStatus(status).name());
pushLog.setFailReason(failReason);
pushLogMapper.updateById(pushLog);
}
@@ -186,6 +237,7 @@ public class MessageHandleService {
fallbackLog.setSendTime(sendTime);
fallbackLog.setRetryCount(0);
fallbackLog.setStatus(0);
fallbackLog.setDispatchStatus(DispatchStatusEnum.PENDING.name());
fallbackLog.setFailReason(null);
insertPendingLog(fallbackLog);
existingLog = pushLogMapper.selectById(messageId);
@@ -195,7 +247,14 @@ public class MessageHandleService {
int maxAttempts = Math.max(1, channelProperties.getRetry().getMaxAttempts());
boolean shouldRetry = nextRetryCount < maxAttempts;
LocalDateTime nextRetryTime = shouldRetry ? LocalDateTime.now().plusNanos(resolveRetryDelayMillis(nextRetryCount) * 1_000_000L) : null;
pushLogMapper.updateRetryStatus(messageId, shouldRetry ? 0 : 2, failReason, nextRetryTime, shouldRetry ? null : failReason);
pushLogMapper.updateRetryStatus(
messageId,
shouldRetry ? 0 : 2,
shouldRetry ? DispatchStatusEnum.PENDING.name() : DispatchStatusEnum.FAILED.name(),
failReason,
nextRetryTime,
shouldRetry ? null : failReason
);
return shouldRetry
? MessageRetryDecision.retry(failReason, nextRetryCount)
: MessageRetryDecision.reject(failReason, nextRetryCount);
@@ -210,6 +269,7 @@ public class MessageHandleService {
pushLog.setChannelType(channelType);
pushLog.setSendTime(sendTime);
pushLog.setStatus(2);
pushLog.setDispatchStatus(DispatchStatusEnum.FAILED.name());
pushLog.setRetryCount(0);
pushLog.setFailReason(failReason);
pushLog.setDeadLetterReason(failReason);
@@ -284,6 +344,7 @@ public class MessageHandleService {
}
pushLog.setStatus(2);
pushLog.setDispatchStatus(DispatchStatusEnum.FAILED.name());
pushLog.setFailReason(failReason);
pushLog.setDeadLetterReason(failReason);
PushLogDO existingLog = pushLogMapper.selectById(pushLog.getId());
@@ -292,12 +353,14 @@ public class MessageHandleService {
PushLogDO rejectedLog = new PushLogDO();
rejectedLog.setId(pushLog.getId());
rejectedLog.setStatus(2);
rejectedLog.setDispatchStatus(DispatchStatusEnum.FAILED.name());
rejectedLog.setFailReason(failReason);
pushLogMapper.updateById(rejectedLog);
return;
}
existingLog.setStatus(2);
existingLog.setDispatchStatus(DispatchStatusEnum.FAILED.name());
existingLog.setFailReason(failReason);
existingLog.setDeadLetterReason(failReason);
existingLog.setSendTime(pushLog.getSendTime());
@@ -339,6 +402,7 @@ public class MessageHandleService {
existingLog.setTemplateParams(toJson(messageDTO.getTemplateParams()));
existingLog.setSendTime(sendTime);
existingLog.setStatus(0);
existingLog.setDispatchStatus(DispatchStatusEnum.PENDING.name());
existingLog.setFailReason(null);
existingLog.setDeadLetterReason(null);
existingLog.setRequestPayload(requestPayload);
@@ -0,0 +1,163 @@
package com.xiaowang.messagehub.service.ingress;
import com.xiaowang.messagehub.dto.EmailMessageDTO;
import com.xiaowang.messagehub.dto.MessageDTO;
import com.xiaowang.messagehub.dto.QqMessageDTO;
import com.xiaowang.messagehub.dto.SmsMessageDTO;
import com.xiaowang.messagehub.enums.ChannelTypeEnum;
import com.xiaowang.messagehub.model.EmailDispatchRequest;
import com.xiaowang.messagehub.model.ManagedChannelConfig;
import com.xiaowang.messagehub.model.QqDispatchRequest;
import com.xiaowang.messagehub.model.QqSendResult;
import com.xiaowang.messagehub.model.SmsDispatchRequest;
import com.xiaowang.messagehub.model.SmsDispatchResult;
import com.xiaowang.messagehub.model.SmsSendResult;
import com.xiaowang.messagehub.service.EmailSendService;
import com.xiaowang.messagehub.service.QqSendService;
import com.xiaowang.messagehub.service.channel.MessageChannelService;
import com.xiaowang.messagehub.service.impl.MessageHandleService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
@Service
public class MessageDispatchService {
private final MessageHandleService messageHandleService;
private final MessageChannelService messageChannelService;
private final EmailSendService emailSendService;
private final QqSendService qqSendService;
public MessageDispatchService(MessageHandleService messageHandleService,
MessageChannelService messageChannelService,
EmailSendService emailSendService,
QqSendService qqSendService) {
this.messageHandleService = messageHandleService;
this.messageChannelService = messageChannelService;
this.emailSendService = emailSendService;
this.qqSendService = qqSendService;
}
public DispatchOutcome dispatch(MessageDTO messageDTO, String messageId, String requestPayload) {
LocalDateTime sendTime = LocalDateTime.now();
MessageHandleService.MessageLogDecision decision =
messageHandleService.validateAndPrepareLog(messageDTO, messageId, sendTime, requestPayload);
if (!decision.shouldProcess()) {
return DispatchOutcome.skipped(decision.reason());
}
ChannelTypeEnum channelType = ChannelTypeEnum.fromCode(messageDTO.getChannelType());
switch (channelType) {
case SMS -> dispatchSms((messageDTO instanceof SmsMessageDTO smsMessageDTO) ? smsMessageDTO : toSmsMessage(messageDTO), messageId);
case EMAIL -> dispatchEmail((messageDTO instanceof EmailMessageDTO emailMessageDTO) ? emailMessageDTO : toEmailMessage(messageDTO), messageId);
case QQ -> dispatchQq((messageDTO instanceof QqMessageDTO qqMessageDTO) ? qqMessageDTO : toQqMessage(messageDTO), messageId);
}
return DispatchOutcome.success();
}
private void dispatchSms(SmsMessageDTO messageDTO, String messageId) {
SmsDispatchRequest request = new SmsDispatchRequest();
request.setReceiver(messageDTO.getReceiver());
request.setTemplateCode(messageDTO.getTemplateCode());
request.setChannelId(messageDTO.getChannelId());
request.setSourceSystem(messageDTO.getSourceSystem());
request.setTemplateParams(messageDTO.getTemplateParams() == null
? new LinkedHashMap<>()
: new LinkedHashMap<>(messageDTO.getTemplateParams()));
SmsDispatchResult result = messageChannelService.dispatchSms(request);
ManagedChannelConfig channelConfig = result.channelConfig();
messageHandleService.markDispatchChannel(messageId, channelConfig.entity().getId(), channelConfig.entity().getProviderCode());
SmsSendResult sendResult = result.sendResult();
if (sendResult != null && StringUtils.hasText(sendResult.getRawResponse())) {
messageHandleService.markProviderResponse(messageId, sendResult.getRawResponse());
}
messageHandleService.markSendSuccess(messageId, result.finalContent());
}
private void dispatchEmail(EmailMessageDTO messageDTO, String messageId) {
EmailDispatchRequest request = new EmailDispatchRequest();
request.setReceiver(messageDTO.getReceiver());
request.setSubject(messageDTO.getSubject());
request.setContent(messageDTO.getContent());
request.setBodyType(messageDTO.getBodyType());
request.setEmailTemplateCode(messageDTO.getEmailTemplateCode());
request.setLegacyTemplateCode(messageDTO.getTemplateCode());
request.setTemplateParams(messageDTO.getTemplateParams() == null
? new LinkedHashMap<>()
: new LinkedHashMap<>(messageDTO.getTemplateParams()));
request.setChannelId(messageDTO.getChannelId());
request.setSourceSystem(messageDTO.getSourceSystem());
request.setAttachmentIds(messageDTO.getAttachmentIds() == null ? new ArrayList<>() : new ArrayList<>(messageDTO.getAttachmentIds()));
ManagedChannelConfig channelConfig = emailSendService.sendEmail(request);
messageHandleService.markDispatchChannel(messageId, channelConfig.entity().getId(), channelConfig.entity().getProviderCode());
messageHandleService.markSendSuccess(messageId, request.getContent());
}
private void dispatchQq(QqMessageDTO messageDTO, String messageId) {
QqDispatchRequest request = new QqDispatchRequest();
request.setReceiver(messageDTO.getReceiver());
request.setTargetType(messageDTO.getTargetType());
request.setContent(messageDTO.getContent());
request.setContentMode(messageDTO.getContentMode());
request.setTemplateCode(messageDTO.getTemplateCode());
request.setTemplateParams(messageDTO.getTemplateParams() == null
? new LinkedHashMap<>()
: new LinkedHashMap<>(messageDTO.getTemplateParams()));
request.setChannelId(messageDTO.getChannelId());
request.setSourceSystem(messageDTO.getSourceSystem());
QqSendService.QqDispatchResult result = qqSendService.sendQq(request);
ManagedChannelConfig channelConfig = result.channelConfig();
messageHandleService.markDispatchChannel(messageId, channelConfig.entity().getId(), channelConfig.entity().getProviderCode());
QqSendResult sendResult = result.sendResult();
if (sendResult != null && StringUtils.hasText(sendResult.getRawResponse())) {
messageHandleService.markProviderResponse(messageId, sendResult.getRawResponse());
}
messageHandleService.markSendSuccess(messageId, result.finalContent());
}
private SmsMessageDTO toSmsMessage(MessageDTO source) {
SmsMessageDTO target = new SmsMessageDTO();
copyBase(source, target);
target.setSendMethod("OTHER");
return target;
}
private EmailMessageDTO toEmailMessage(MessageDTO source) {
EmailMessageDTO target = new EmailMessageDTO();
copyBase(source, target);
return target;
}
private QqMessageDTO toQqMessage(MessageDTO source) {
QqMessageDTO target = new QqMessageDTO();
copyBase(source, target);
return target;
}
private void copyBase(MessageDTO source, MessageDTO target) {
target.setReceiver(source.getReceiver());
target.setChannelType(source.getChannelType());
target.setMsgType(source.getMsgType());
target.setTemplateCode(source.getTemplateCode());
target.setTemplateParams(source.getTemplateParams());
target.setChannelId(source.getChannelId());
target.setSourceSystem(source.getSourceSystem());
target.setUniqueId(source.getUniqueId());
}
public record DispatchOutcome(boolean processed, String reason) {
public static DispatchOutcome success() {
return new DispatchOutcome(true, null);
}
public static DispatchOutcome skipped(String reason) {
return new DispatchOutcome(false, reason);
}
}
}
@@ -0,0 +1,121 @@
package com.xiaowang.messagehub.service.ingress;
import com.xiaowang.messagehub.dto.EmailMessageDTO;
import com.xiaowang.messagehub.dto.MessageDTO;
import com.xiaowang.messagehub.dto.QqMessageDTO;
import com.xiaowang.messagehub.dto.SmsMessageDTO;
import com.xiaowang.messagehub.dto.api.MessageIngressEnvelope;
import com.xiaowang.messagehub.enums.ChannelTypeEnum;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@Component
public class MessageIngressEnvelopeMapper {
public MessageDTO toMessageDTO(MessageIngressEnvelope envelope) {
requireText(envelope.getMessageId(), "messageId is required");
requireText(envelope.getSourceSystem(), "sourceSystem is required");
requireText(envelope.getPlatform(), "platform is required");
requireText(envelope.getReceiver(), "receiver is required");
requireText(envelope.getMsgType(), "msgType is required");
ChannelTypeEnum platform = ChannelTypeEnum.fromCode(envelope.getPlatform());
MessageDTO messageDTO = switch (platform) {
case SMS -> buildSms(envelope);
case EMAIL -> buildEmail(envelope);
case QQ -> buildQq(envelope);
};
applyBase(messageDTO, envelope, platform.getCode());
return messageDTO;
}
private SmsMessageDTO buildSms(MessageIngressEnvelope envelope) {
SmsMessageDTO messageDTO = new SmsMessageDTO();
messageDTO.setSendMethod(stringParam(envelope, "sendMethod", "OTHER").toUpperCase(Locale.ROOT));
return messageDTO;
}
private EmailMessageDTO buildEmail(MessageIngressEnvelope envelope) {
EmailMessageDTO messageDTO = new EmailMessageDTO();
messageDTO.setSubject(stringParam(envelope, "subject", null));
messageDTO.setContent(stringParam(envelope, "content", null));
messageDTO.setBodyType(stringParam(envelope, "bodyType", null));
messageDTO.setEmailTemplateCode(stringParam(envelope, "emailTemplateCode", null));
messageDTO.setAttachmentIds(longListParam(envelope.getPlatformParams(), "attachmentIds"));
return messageDTO;
}
private QqMessageDTO buildQq(MessageIngressEnvelope envelope) {
QqMessageDTO messageDTO = new QqMessageDTO();
messageDTO.setTargetType(stringParam(envelope, "targetType", null));
messageDTO.setContent(stringParam(envelope, "content", null));
messageDTO.setContentMode(stringParam(envelope, "contentMode", null));
return messageDTO;
}
private void applyBase(MessageDTO target, MessageIngressEnvelope envelope, String platform) {
target.setReceiver(envelope.getReceiver().trim());
target.setChannelType(platform);
target.setMsgType(envelope.getMsgType().trim().toUpperCase(Locale.ROOT));
target.setTemplateCode(trimToNull(envelope.getTemplateCode()));
target.setTemplateParams(envelope.getTemplateParams() == null
? new LinkedHashMap<>()
: new LinkedHashMap<>(envelope.getTemplateParams()));
target.setChannelId(envelope.getChannelId());
target.setSourceSystem(envelope.getSourceSystem().trim().toLowerCase(Locale.ROOT));
target.setUniqueId(StringUtils.hasText(envelope.getUniqueId())
? envelope.getUniqueId().trim()
: envelope.getMessageId().trim());
}
private String stringParam(MessageIngressEnvelope envelope, String key, String fallback) {
Map<String, Object> params = envelope.getPlatformParams();
if (params == null || !params.containsKey(key) || params.get(key) == null) {
return fallback;
}
String value = String.valueOf(params.get(key)).trim();
return StringUtils.hasText(value) ? value : fallback;
}
private List<Long> longListParam(Map<String, Object> params, String key) {
if (params == null || params.get(key) == null) {
return new ArrayList<>();
}
Object raw = params.get(key);
if (!(raw instanceof Iterable<?> iterable)) {
throw new IllegalArgumentException(key + " must be an array");
}
List<Long> result = new ArrayList<>();
for (Object item : iterable) {
if (item == null) {
continue;
}
if (item instanceof Number number) {
result.add(number.longValue());
continue;
}
try {
result.add(Long.parseLong(String.valueOf(item).trim()));
} catch (NumberFormatException exception) {
throw new IllegalArgumentException(key + " contains non-numeric value: " + item);
}
}
return result;
}
private String trimToNull(String value) {
return StringUtils.hasText(value) ? value.trim() : null;
}
private void requireText(String value, String message) {
if (!StringUtils.hasText(value)) {
throw new IllegalArgumentException(message);
}
}
}
@@ -6,36 +6,54 @@ import com.xiaowang.messagehub.dto.admin.SourceSystemView;
import com.xiaowang.messagehub.entity.MessageChannelConfigDO;
import com.xiaowang.messagehub.entity.MessageSourceSystemChannelDO;
import com.xiaowang.messagehub.entity.MessageSourceSystemDO;
import com.xiaowang.messagehub.entity.MessageSourceSystemPermissionDO;
import com.xiaowang.messagehub.enums.ChannelTypeEnum;
import com.xiaowang.messagehub.mapper.MessageChannelConfigMapper;
import com.xiaowang.messagehub.mapper.MessageSourceSystemChannelMapper;
import com.xiaowang.messagehub.mapper.MessageSourceSystemMapper;
import com.xiaowang.messagehub.mapper.MessageSourceSystemPermissionMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.time.LocalDateTime;
@Service
public class MessageSourceSystemService {
public static final String ACCESS_TOKEN_HEADER = "X-MessageHub-Access-Token";
private static final long CACHE_TTL_MILLIS = 30_000L;
private static final SecureRandom TOKEN_RANDOM = new SecureRandom();
private final MessageSourceSystemMapper sourceSystemMapper;
private final MessageSourceSystemChannelMapper sourceSystemChannelMapper;
private final MessageChannelConfigMapper channelConfigMapper;
private final MessageSourceSystemPermissionMapper permissionMapper;
private final Map<String, CachedSourceAuth> sourceAuthCache = new ConcurrentHashMap<>();
private final Map<String, CachedPermissions> permissionCache = new ConcurrentHashMap<>();
public MessageSourceSystemService(MessageSourceSystemMapper sourceSystemMapper,
MessageSourceSystemChannelMapper sourceSystemChannelMapper,
MessageChannelConfigMapper channelConfigMapper) {
MessageChannelConfigMapper channelConfigMapper,
MessageSourceSystemPermissionMapper permissionMapper) {
this.sourceSystemMapper = sourceSystemMapper;
this.sourceSystemChannelMapper = sourceSystemChannelMapper;
this.channelConfigMapper = channelConfigMapper;
this.permissionMapper = permissionMapper;
}
public List<SourceSystemView> listSourceSystems() {
@@ -55,22 +73,32 @@ public class MessageSourceSystemService {
ensureUniqueSystemCode(request.getSystemCode(), null);
MessageSourceSystemDO entity = new MessageSourceSystemDO();
applySourceSystem(entity, request);
String accessToken = generateAccessToken();
applyAccessToken(entity, accessToken);
sourceSystemMapper.insert(entity);
persistDefaultChannel(entity.getId(), ChannelTypeEnum.SMS.getCode(), request.getDefaultSmsChannelId());
persistDefaultChannel(entity.getId(), ChannelTypeEnum.EMAIL.getCode(), request.getDefaultEmailChannelId());
persistDefaultChannel(entity.getId(), ChannelTypeEnum.QQ.getCode(), request.getDefaultQqChannelId());
return getSourceSystem(entity.getId());
persistPermissions(entity.getId(), resolveRequestedPlatforms(request));
clearCaches(entity.getSystemCode());
SourceSystemView view = getSourceSystem(entity.getId());
view.setAccessToken(accessToken);
return view;
}
@Transactional
public SourceSystemView updateSourceSystem(Long id, SourceSystemSaveRequest request) {
MessageSourceSystemDO entity = requireSourceSystem(id);
String previousSystemCode = entity.getSystemCode();
ensureUniqueSystemCode(request.getSystemCode(), id);
applySourceSystem(entity, request);
sourceSystemMapper.updateById(entity);
persistDefaultChannel(id, ChannelTypeEnum.SMS.getCode(), request.getDefaultSmsChannelId());
persistDefaultChannel(id, ChannelTypeEnum.EMAIL.getCode(), request.getDefaultEmailChannelId());
persistDefaultChannel(id, ChannelTypeEnum.QQ.getCode(), request.getDefaultQqChannelId());
persistPermissions(id, resolveRequestedPlatforms(request));
clearCaches(previousSystemCode);
clearCaches(entity.getSystemCode());
return getSourceSystem(id);
}
@@ -79,13 +107,64 @@ public class MessageSourceSystemService {
MessageSourceSystemDO entity = requireSourceSystem(id);
entity.setEnabled(enabled ? 1 : 0);
sourceSystemMapper.updateById(entity);
clearCaches(entity.getSystemCode());
return getSourceSystem(id);
}
@Transactional
public SourceSystemView rotateAccessToken(Long id) {
MessageSourceSystemDO entity = requireSourceSystem(id);
String accessToken = generateAccessToken();
applyAccessToken(entity, accessToken);
sourceSystemMapper.updateById(entity);
clearCaches(entity.getSystemCode());
SourceSystemView view = getSourceSystem(id);
view.setAccessToken(accessToken);
return view;
}
public void requireEnabledSourceSystem(String systemCode) {
requireEnabledSourceSystemEntity(systemCode);
}
public void authenticateSourceSystem(String systemCode, String accessToken) {
String normalizedCode = normalizeSystemCode(systemCode);
if (!StringUtils.hasText(accessToken)) {
throw new IllegalArgumentException("Missing " + ACCESS_TOKEN_HEADER);
}
CachedSourceAuth auth = loadSourceAuth(normalizedCode);
if (auth.accessTokenHash() == null || auth.accessTokenHash().isBlank()) {
throw new IllegalArgumentException("Source system access token is not configured: " + normalizedCode);
}
String tokenHash = hashAccessToken(accessToken.trim());
if (!constantTimeEquals(auth.accessTokenHash(), tokenHash)) {
throw new IllegalArgumentException("Invalid source system access token");
}
}
public void requirePlatformPermission(String systemCode, String platform) {
String normalizedCode = normalizeSystemCode(systemCode);
String normalizedPlatform = ChannelTypeEnum.fromCode(platform).getCode();
Set<String> allowedPlatforms = listAllowedPlatforms(normalizedCode);
if (!allowedPlatforms.contains(normalizedPlatform)) {
throw new IllegalArgumentException("Source system is not allowed to call platform: " + normalizedPlatform);
}
}
public Set<String> listAllowedPlatforms(String systemCode) {
String normalizedCode = normalizeSystemCode(systemCode);
CachedPermissions cached = permissionCache.get(normalizedCode);
long now = System.currentTimeMillis();
if (cached != null && cached.expiresAtMillis() > now) {
return cached.platforms();
}
MessageSourceSystemDO entity = requireEnabledSourceSystemEntity(normalizedCode);
Set<String> platforms = loadPermissionPlatforms(entity.getId());
permissionCache.put(normalizedCode, new CachedPermissions(platforms, now + CACHE_TTL_MILLIS));
return platforms;
}
public Long resolveSystemDefaultChannelId(String systemCode, String channelType) {
MessageSourceSystemDO entity = requireEnabledSourceSystemEntity(systemCode);
LambdaQueryWrapper<MessageSourceSystemChannelDO> queryWrapper = new LambdaQueryWrapper<>();
@@ -118,8 +197,10 @@ public class MessageSourceSystemService {
.put(mapping.getChannelType(), mapping);
}
Map<Long, Set<String>> permissionMap = fetchPermissionMap(systemMap.keySet());
return systems.stream()
.map(system -> toView(system, mappingMap.get(system.getId()), channelMap))
.map(system -> toView(system, mappingMap.get(system.getId()), channelMap, permissionMap.get(system.getId())))
.toList();
}
@@ -129,13 +210,17 @@ public class MessageSourceSystemService {
private SourceSystemView toView(MessageSourceSystemDO entity,
Map<String, MessageSourceSystemChannelDO> mappingByType,
Map<Long, MessageChannelConfigDO> channelMap) {
Map<Long, MessageChannelConfigDO> channelMap,
Set<String> allowedPlatforms) {
SourceSystemView view = new SourceSystemView();
view.setId(entity.getId());
view.setSystemCode(entity.getSystemCode());
view.setSystemName(entity.getSystemName());
view.setEnabled(entity.getEnabled() != null && entity.getEnabled() == 1);
view.setRemark(entity.getRemark());
view.setAccessTokenHint(entity.getAccessTokenHint());
view.setTokenUpdateTime(entity.getTokenUpdateTime());
view.setAllowedPlatforms(allowedPlatforms == null ? Collections.emptySet() : allowedPlatforms);
view.setCreateTime(entity.getCreateTime());
view.setUpdateTime(entity.getUpdateTime());
@@ -182,6 +267,67 @@ public class MessageSourceSystemService {
.collect(Collectors.toMap(MessageChannelConfigDO::getId, Function.identity()));
}
private Map<Long, Set<String>> fetchPermissionMap(Set<Long> systemIds) {
if (systemIds.isEmpty()) {
return Collections.emptyMap();
}
LambdaQueryWrapper<MessageSourceSystemPermissionDO> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.in(MessageSourceSystemPermissionDO::getSystemId, systemIds)
.eq(MessageSourceSystemPermissionDO::getEnabled, 1)
.orderByAsc(MessageSourceSystemPermissionDO::getPlatform);
Map<Long, Set<String>> permissionMap = new LinkedHashMap<>();
for (MessageSourceSystemPermissionDO permission : permissionMapper.selectList(queryWrapper)) {
permissionMap.computeIfAbsent(permission.getSystemId(), key -> new LinkedHashSet<>())
.add(permission.getPlatform());
}
return permissionMap;
}
private Set<String> loadPermissionPlatforms(Long systemId) {
LambdaQueryWrapper<MessageSourceSystemPermissionDO> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(MessageSourceSystemPermissionDO::getSystemId, systemId)
.eq(MessageSourceSystemPermissionDO::getEnabled, 1);
return permissionMapper.selectList(queryWrapper).stream()
.map(MessageSourceSystemPermissionDO::getPlatform)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
private void persistPermissions(Long systemId, Set<String> allowedPlatforms) {
LambdaQueryWrapper<MessageSourceSystemPermissionDO> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(MessageSourceSystemPermissionDO::getSystemId, systemId);
permissionMapper.delete(queryWrapper);
for (String platform : allowedPlatforms) {
MessageSourceSystemPermissionDO permission = new MessageSourceSystemPermissionDO();
permission.setSystemId(systemId);
permission.setPlatform(ChannelTypeEnum.fromCode(platform).getCode());
permission.setEnabled(1);
permissionMapper.insert(permission);
}
}
private Set<String> resolveRequestedPlatforms(SourceSystemSaveRequest request) {
Set<String> requested = request.getAllowedPlatforms();
if (requested != null) {
return requested.stream()
.filter(StringUtils::hasText)
.map(item -> ChannelTypeEnum.fromCode(item).getCode())
.collect(Collectors.toCollection(LinkedHashSet::new));
}
Set<String> inferred = new LinkedHashSet<>();
if (request.getDefaultSmsChannelId() != null) {
inferred.add(ChannelTypeEnum.SMS.getCode());
}
if (request.getDefaultEmailChannelId() != null) {
inferred.add(ChannelTypeEnum.EMAIL.getCode());
}
if (request.getDefaultQqChannelId() != null) {
inferred.add(ChannelTypeEnum.QQ.getCode());
}
return inferred;
}
private void applySourceSystem(MessageSourceSystemDO entity, SourceSystemSaveRequest request) {
entity.setSystemCode(normalizeSystemCode(request.getSystemCode()));
entity.setSystemName(request.getSystemName().trim());
@@ -262,10 +408,86 @@ public class MessageSourceSystemService {
return entity;
}
private CachedSourceAuth loadSourceAuth(String systemCode) {
CachedSourceAuth cached = sourceAuthCache.get(systemCode);
long now = System.currentTimeMillis();
if (cached != null && cached.expiresAtMillis() > now) {
return cached;
}
MessageSourceSystemDO entity = requireEnabledSourceSystemEntity(systemCode);
CachedSourceAuth auth = new CachedSourceAuth(
entity.getId(),
entity.getSystemCode(),
entity.getAccessTokenHash(),
now + CACHE_TTL_MILLIS
);
sourceAuthCache.put(systemCode, auth);
return auth;
}
private void applyAccessToken(MessageSourceSystemDO entity, String accessToken) {
entity.setAccessTokenHash(hashAccessToken(accessToken));
entity.setAccessTokenHint(buildAccessTokenHint(accessToken));
entity.setTokenUpdateTime(LocalDateTime.now());
}
private String generateAccessToken() {
byte[] bytes = new byte[32];
TOKEN_RANDOM.nextBytes(bytes);
return "mh_" + Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
private String hashAccessToken(String accessToken) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] bytes = digest.digest(accessToken.getBytes(StandardCharsets.UTF_8));
StringBuilder builder = new StringBuilder(bytes.length * 2);
for (byte item : bytes) {
builder.append(String.format("%02x", item));
}
return builder.toString();
} catch (Exception exception) {
throw new IllegalStateException("Failed to hash access token", exception);
}
}
private String buildAccessTokenHint(String accessToken) {
if (!StringUtils.hasText(accessToken)) {
return null;
}
String trimmed = accessToken.trim();
return trimmed.length() <= 8 ? trimmed : trimmed.substring(trimmed.length() - 8);
}
private boolean constantTimeEquals(String left, String right) {
if (left == null || right == null) {
return false;
}
return MessageDigest.isEqual(left.getBytes(StandardCharsets.UTF_8), right.getBytes(StandardCharsets.UTF_8));
}
private void clearCaches(String systemCode) {
if (!StringUtils.hasText(systemCode)) {
sourceAuthCache.clear();
permissionCache.clear();
return;
}
String normalized = normalizeSystemCode(systemCode);
sourceAuthCache.remove(normalized);
permissionCache.remove(normalized);
}
private String normalizeSystemCode(String systemCode) {
if (!StringUtils.hasText(systemCode)) {
throw new IllegalArgumentException("来源系统标识不能为空");
}
return systemCode.trim().toLowerCase(Locale.ROOT);
}
private record CachedSourceAuth(Long id, String systemCode, String accessTokenHash, long expiresAtMillis) {
}
private record CachedPermissions(Set<String> platforms, long expiresAtMillis) {
}
}
@@ -2,7 +2,7 @@
## 1. 项目定位
`MessageHub` 是 `YumiNail` 体系中的独立消息中心服务,负责统一承接短信、邮件、模板消息的异步发送请求,并通过 RabbitMQ 进行消费处理。
`MessageHub` 是独立的消息中转服务,负责统一承接短信、邮件、QQ 消息的异步发送请求,并通过 RabbitMQ 进行消费处理。
当前版本已经具备以下核心能力:
@@ -10,7 +10,9 @@
- 通道敏感字段支持加密存储
- 后台支持通道新增、编辑、启停、健康检查、测试发送
- 后台支持来源系统白名单及默认通道管理
- 开发环境可自动补齐 `MOCK_SMS`、`MOCK_EMAIL` 通道
- 公共 API 支持消息 ID 预取、平台能力查询、发送状态查询
- 统一 RabbitMQ ingress 作为正式对外发送入口
- 开发环境可自动补齐 `MOCK_SMS`、`MOCK_EMAIL`、`MOCK_QQ` 通道
- 外部业务系统通过 MQ 投递消息时,必须携带 `sourceSystem`
- 短信模板支持绑定指定短信通道;未绑定时视为全局通用
@@ -66,6 +68,7 @@ java -jar .\target\MessageHub-0.0.1-SNAPSHOT.jar
- 该脚本包含当前消息发送链路所依赖的核心表结构
- 如为增量升级环境,也可以按 `src/main/resources/sql/` 目录中的补丁脚本逐步执行
- 统一 ingress 与来源系统 token/权限需要执行 `src/main/resources/sql/2026-05-14_messagehub_ingress_public_api_patch.sql`
- 若数据库中仍存在旧的明文 `secret_json`,MessageHub 兼容读取;通过后台重新保存一次后会自动转为加密存储
## 5. 资源目录说明
@@ -3,7 +3,7 @@
-- 用途:
-- 1. 一次性补齐 MessageHub 当前发送链路依赖的关键表
-- 2. 写入旧 MessageHub.yaml 中能明确提取出的短信/邮件通道
-- 3. 写入 YumiNail 当前依赖的来源系统白名单与验证码模板
-- 3. 写入示例来源系统白名单与验证码模板
--
-- 说明:
-- 1. 本文件采用“可重复执行”的思路,尽量避免重复插入
@@ -0,0 +1,109 @@
-- MessageHub unified ingress, source token, permission and dispatch status patch.
-- Apply after 2026-05-12_messagehub_email_templates_attachments_reliability_patch.sql.
USE `messagehub`;
DROP PROCEDURE IF EXISTS sp_mh_add_column_if_missing;
DROP PROCEDURE IF EXISTS sp_mh_add_index_if_missing;
DELIMITER $$
CREATE PROCEDURE sp_mh_add_column_if_missing(
IN p_table_name VARCHAR(64),
IN p_column_name VARCHAR(64),
IN p_column_definition TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND COLUMN_NAME = p_column_name
) THEN
SET @alter_sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', p_column_definition);
PREPARE stmt FROM @alter_sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE sp_mh_add_index_if_missing(
IN p_table_name VARCHAR(64),
IN p_index_name VARCHAR(64),
IN p_index_definition TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND INDEX_NAME = p_index_name
) THEN
SET @index_sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', p_index_definition);
PREPARE stmt FROM @index_sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
DELIMITER ;
CALL sp_mh_add_column_if_missing(
'message_source_system',
'access_token_hash',
'VARCHAR(128) NULL COMMENT ''SHA-256 hash of the source access token'' AFTER `remark`'
);
CALL sp_mh_add_column_if_missing(
'message_source_system',
'access_token_hint',
'VARCHAR(16) NULL COMMENT ''Last visible characters of the source access token'' AFTER `access_token_hash`'
);
CALL sp_mh_add_column_if_missing(
'message_source_system',
'token_update_time',
'DATETIME NULL COMMENT ''Last access token update time'' AFTER `access_token_hint`'
);
CALL sp_mh_add_column_if_missing(
'push_log',
'dispatch_status',
'VARCHAR(20) NOT NULL DEFAULT ''ACCEPTED'' COMMENT ''ACCEPTED / PENDING / SUCCESS / FAILED'' AFTER `status`'
);
CREATE TABLE IF NOT EXISTS `message_source_system_permission` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
`system_id` BIGINT NOT NULL COMMENT 'Source system id',
`platform` VARCHAR(20) NOT NULL COMMENT 'SMS / EMAIL / QQ',
`enabled` TINYINT NOT NULL DEFAULT 1 COMMENT '1 enabled, 0 disabled',
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Create time',
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Update time',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_message_source_system_permission` (`system_id`, `platform`),
KEY `idx_message_source_system_permission_platform` (`platform`, `enabled`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Source system platform permissions';
INSERT IGNORE INTO `message_source_system_permission` (`system_id`, `platform`, `enabled`)
SELECT DISTINCT `system_id`, `channel_type`, 1
FROM `message_source_system_channel`
WHERE `channel_type` IN ('SMS', 'EMAIL', 'QQ');
UPDATE `push_log`
SET `dispatch_status` = CASE
WHEN `status` = 1 THEN 'SUCCESS'
WHEN `status` = 2 THEN 'FAILED'
WHEN `receiver` IS NULL AND `channel_type` IS NULL AND `request_payload` IS NULL THEN 'ACCEPTED'
ELSE 'PENDING'
END
WHERE `dispatch_status` IS NULL
OR `dispatch_status` = ''
OR `dispatch_status` = 'ACCEPTED';
CALL sp_mh_add_index_if_missing('push_log', 'idx_push_log_dispatch_status', '(`dispatch_status`)');
DROP PROCEDURE IF EXISTS sp_mh_add_column_if_missing;
DROP PROCEDURE IF EXISTS sp_mh_add_index_if_missing;
-- Existing source systems will have NULL access_token_hash after this patch.
-- Rotate the access token from the admin API before using the public REST/MQ ingress:
-- POST /admin/api/source-systems/{id}/access-token/rotate
@@ -217,6 +217,9 @@ const elements = {
defaultSmsChannelId: document.getElementById("defaultSmsChannelId"),
defaultEmailChannelId: document.getElementById("defaultEmailChannelId"),
defaultQqChannelId: document.getElementById("defaultQqChannelId"),
sourceAllowedPlatformInputs: Array.from(document.querySelectorAll('input[name="sourceAllowedPlatform"]')),
sourceAccessTokenPanel: document.getElementById("sourceAccessTokenPanel"),
sourceAccessTokenValue: document.getElementById("sourceAccessTokenValue"),
sourceFormTitle: document.getElementById("sourceFormTitle"),
sourceFormSubtitle: document.getElementById("sourceFormSubtitle"),
sourceResetButton: document.getElementById("sourceResetButton"),
@@ -558,6 +561,13 @@ function fillSourceChannelOptions(sourceSystem = state.editingSourceSystem) {
elements.defaultQqChannelId.innerHTML = buildChannelOptions("QQ", sourceSystem?.defaultQqChannelId || "");
}
function fillSourceAllowedPlatformOptions(sourceSystem = state.editingSourceSystem) {
const allowed = new Set(sourceSystem?.allowedPlatforms?.length ? sourceSystem.allowedPlatforms : ["SMS", "EMAIL", "QQ"]);
elements.sourceAllowedPlatformInputs.forEach((input) => {
input.checked = allowed.has(input.value);
});
}
function fillSmsTemplateChannelOptions(selectedId = "") {
const options = ['<option value="">全局通用(不绑定)</option>'];
listSmsChannels().forEach((channel) => {
@@ -618,12 +628,25 @@ function resetSourceSystemForm(sourceSystem = null) {
elements.sourceSystemRemark.value = sourceSystem?.remark || "";
elements.sourceSystemEnabled.checked = sourceSystem?.enabled ?? true;
fillSourceChannelOptions(sourceSystem);
fillSourceAllowedPlatformOptions(sourceSystem);
renderSourceAccessToken(null);
elements.sourceFormTitle.textContent = sourceSystem ? "编辑来源系统" : "新增来源系统";
elements.sourceFormSubtitle.textContent = sourceSystem
? `当前来源系统 ID:${sourceSystem.id}。不指定默认通道时,将回退到全局默认通道。`
: "系统标识会统一转成小写保存。不指定默认通道时,会回退到全局默认通道。";
}
function renderSourceAccessToken(sourceSystem) {
if (!sourceSystem?.accessToken) {
elements.sourceAccessTokenPanel.hidden = true;
elements.sourceAccessTokenValue.textContent = "";
return;
}
elements.sourceAccessTokenPanel.hidden = false;
elements.sourceAccessTokenValue.textContent = sourceSystem.accessToken;
}
function sourceStatusBadge(sourceSystem) {
return sourceSystem.enabled
? `<span class="badge good">已启用</span>`
@@ -637,6 +660,15 @@ function defaultChannelText(channelId, channelName) {
return `<strong>${channelName || "未知通道"}</strong><div class="table-note">ID:${channelId}</div>`;
}
function renderAllowedPlatforms(platforms = []) {
if (!platforms.length) {
return '<span class="badge warn">未授权</span>';
}
return platforms
.map((platform) => `<span class="badge">${escapeHtml(platform)}</span>`)
.join(" ");
}
function renderSourceSystemTable() {
elements.sourceSystemTableBody.innerHTML = "";
elements.sourceSystemEmptyState.hidden = state.sourceSystems.length > 0;
@@ -653,10 +685,13 @@ function renderSourceSystemTable() {
<td>${defaultChannelText(sourceSystem.defaultSmsChannelId, sourceSystem.defaultSmsChannelName)}</td>
<td>${defaultChannelText(sourceSystem.defaultEmailChannelId, sourceSystem.defaultEmailChannelName)}</td>
<td>${defaultChannelText(sourceSystem.defaultQqChannelId, sourceSystem.defaultQqChannelName)}</td>
<td>${renderAllowedPlatforms(sourceSystem.allowedPlatforms)}</td>
<td>${sourceSystem.accessTokenHint ? `<code>...${escapeHtml(sourceSystem.accessTokenHint)}</code>` : '<span class="table-note">未轮换</span>'}</td>
<td>${formatDateTime(sourceSystem.updateTime)}</td>
<td>
<div class="actions">
<button class="ghost-button small" data-action="edit" data-id="${sourceSystem.id}">编辑</button>
<button class="ghost-button small" data-action="rotate-token" data-id="${sourceSystem.id}">轮换密钥</button>
<button class="ghost-button small" data-action="status" data-id="${sourceSystem.id}">
${sourceSystem.enabled ? "停用" : "启用"}
</button>
@@ -687,7 +722,10 @@ async function onSourceSystemSubmit(event) {
enabled: elements.sourceSystemEnabled.checked,
defaultSmsChannelId: elements.defaultSmsChannelId.value ? Number(elements.defaultSmsChannelId.value) : null,
defaultEmailChannelId: elements.defaultEmailChannelId.value ? Number(elements.defaultEmailChannelId.value) : null,
defaultQqChannelId: elements.defaultQqChannelId.value ? Number(elements.defaultQqChannelId.value) : null
defaultQqChannelId: elements.defaultQqChannelId.value ? Number(elements.defaultQqChannelId.value) : null,
allowedPlatforms: elements.sourceAllowedPlatformInputs
.filter((input) => input.checked)
.map((input) => input.value)
};
const sourceSystemId = elements.sourceSystemId.value;
@@ -704,6 +742,7 @@ async function onSourceSystemSubmit(event) {
showToast(`来源系统已保存:${saved.systemCode}`);
state.editingSourceSystem = saved;
await loadSourceSystems();
renderSourceAccessToken(saved);
}
async function onSourceSystemTableClick(event) {
@@ -729,6 +768,16 @@ async function onSourceSystemTableClick(event) {
});
showToast(sourceSystem.enabled ? `来源系统已停用:${sourceSystem.systemCode}` : `来源系统已启用:${sourceSystem.systemCode}`);
await loadSourceSystems();
return;
}
if (action === "rotate-token") {
const rotated = await request(`/admin/api/source-systems/${id}/access-token/rotate`, {
method: "POST"
});
showToast(`已轮换访问密钥:${rotated.systemCode}`);
await loadSourceSystems();
renderSourceAccessToken(rotated);
}
}
@@ -64,6 +64,9 @@
<th>状态</th>
<th>默认短信通道</th>
<th>默认邮件通道</th>
<th>默认 QQ 通道</th>
<th>平台权限</th>
<th>Token</th>
<th>最后更新</th>
<th>操作</th>
</tr>
@@ -85,7 +88,7 @@
<input type="hidden" id="sourceSystemId">
<label>
<span>系统标识</span>
<input id="sourceSystemCode" type="text" maxlength="64" required placeholder="例如:yuminail">
<input id="sourceSystemCode" type="text" maxlength="64" required placeholder="例如:order-system">
</label>
<label>
<span>系统名称</span>
@@ -99,10 +102,35 @@
<span>默认邮件通道</span>
<select id="defaultEmailChannelId"></select>
</label>
<label>
<span>默认 QQ 通道</span>
<select id="defaultQqChannelId"></select>
</label>
<div class="field-group full-width">
<span>允许调用平台</span>
<div class="inline-checks">
<label class="checkbox">
<input name="sourceAllowedPlatform" type="checkbox" value="SMS" checked>
<span>SMS</span>
</label>
<label class="checkbox">
<input name="sourceAllowedPlatform" type="checkbox" value="EMAIL" checked>
<span>EMAIL</span>
</label>
<label class="checkbox">
<input name="sourceAllowedPlatform" type="checkbox" value="QQ" checked>
<span>QQ</span>
</label>
</div>
</div>
<label class="full-width">
<span>备注</span>
<input id="sourceSystemRemark" type="text" maxlength="255" placeholder="可选,用于说明该来源系统的用途">
</label>
<div id="sourceAccessTokenPanel" class="token-reveal full-width" hidden>
<div>请立即保存来源系统访问密钥,页面刷新后不再展示明文。</div>
<code id="sourceAccessTokenValue"></code>
</div>
<div class="inline-checks">
<label class="checkbox">
<input id="sourceSystemEnabled" type="checkbox" checked>
@@ -335,7 +363,7 @@
</div>
<label class="full-width">
<span>模板内容</span>
<textarea id="smsTemplateContentPattern" rows="5" required placeholder="例如:【YumiNail】您的验证码是${code},${number}分钟内有效。"></textarea>
<textarea id="smsTemplateContentPattern" rows="5" required placeholder="例如:【MessageHub】您的验证码是${code},${number}分钟内有效。"></textarea>
</label>
<label class="full-width">
<span>占位符识别</span>
@@ -333,6 +333,23 @@ textarea {
flex-wrap: wrap;
}
.token-reveal {
display: grid;
gap: 8px;
padding: 12px 14px;
border: 1px solid rgba(35, 115, 76, 0.24);
border-radius: 8px;
background: rgba(35, 115, 76, 0.08);
color: var(--good);
font-size: 13px;
}
.token-reveal code {
display: block;
overflow-wrap: anywhere;
color: var(--text);
}
.checkbox {
display: inline-flex;
align-items: center;
+84 -45
View File
@@ -1,7 +1,7 @@
# MessageHub 外部系统对接接口文档
- 文档版本:v1.0
- 适用范围:基于当前仓库代码实现整理,截止 2026-04-08
- 文档版本:v2.0
- 适用范围:基于当前仓库代码实现整理,截止 2026-05-14
- 适用对象:外部业务系统、平台运维、联调人员
## 1. 文档说明
@@ -10,27 +10,33 @@
请特别注意以下边界:
- 当前版本对外业务投递的主接口是 RabbitMQ,不是业务 HTTP 接口。
- 当前代码中只有后台管理 REST 接口,没有实现 `/message/send`、`/sms/send`、`/email/send` 这类业务发送接口。
- 当前真正打通的消息通道只有 `SMS` 和 `EMAIL`。
- `PUSH`、`WECHAT` 虽然仍出现在消息体枚举中,但当前版本没有对应队列绑定和消费实现,不能作为正式对接能力使用。
- 当前版本对外业务投递的正式主入口是统一 RabbitMQ ingress,不提供正式 HTTP 发送接口。
- REST 仅提供辅助能力:预取 `messageId`、查询来源系统可用平台、查询消息发送状态。
- 当前正式平台为 `SMS`、`EMAIL`、`QQ`。
- `smsQueue`、`emailQueue`、`qqQueue` 仍保留为兼容入口,但不再作为新的公共对接契约。
- 外部系统必须使用来源系统独立访问密钥,通过 `X-MessageHub-Access-Token` 认证。
## 2. 对接总览
| 场景 | 接入方式 | 是否对外开放 | 说明 |
| --- | --- | --- | --- |
| 业务消息投递 | RabbitMQ | 是 | 外部业务系统向交换机发布消息,MessageHub 异步消费并发送 |
| 来源系统配置 | REST 管理接口 | 仅平台/运维使用 | 创建来源系统、配置默认通道 |
| 通道配置 | REST 管理接口 | 仅平台/运维使用 | 维护短信/邮件通道、健康检查、测试发送 |
| 模板配置/查询 | REST 管理接口 | 仅平台/运维使用 | 维护短信模板,查询模板占位符 |
| 业务消息投递 | RabbitMQ | 是 | 外部系统向统一 ingress exchange 发布 envelope,MessageHub 异步消费并发送 |
| 预取消息 ID | REST 公共接口 | 是 | `POST /api/v1/messages/ids`,写入 `ACCEPTED` 日志 |
| 平台能力查询 | REST 公共接口 | 是 | `GET /api/v1/platforms?sourceSystem=xxx` |
| 发送状态查询 | REST 公共接口 | 是 | `GET /api/v1/messages/{messageId}/status?sourceSystem=xxx` |
| 来源系统配置 | REST 管理接口 | 仅平台/运维使用 | 创建来源系统、轮换访问密钥、配置默认通道和平台权限 |
| 通道配置 | REST 管理接口 | 仅平台/运维使用 | 维护短信/邮件/QQ 通道、健康检查、测试发送 |
| 模板配置/查询 | REST 管理接口 | 仅平台/运维使用 | 维护短信、邮件、QQ 模板,查询模板占位符 |
## 3. 前置条件
外部系统在正式发送消息前,需要先完成以下准备:
- 由平台管理员在 MessageHub 中创建并启用来源系统 `sourceSystem`。
- 至少配置一个可用的短信通道和/或邮件通道。
- 如需按来源系统走指定通道,需要给该来源系统配置默认短信通道或默认邮件通道。
- 创建或轮换来源系统访问密钥,外部系统只保存明文密钥,MessageHub 仅保存哈希和尾号。
- 为来源系统配置允许调用的平台权限:`SMS`、`EMAIL`、`QQ`。
- 至少配置一个可用的短信、邮件或 QQ 通道。
- 如需按来源系统走指定通道,需要给该来源系统配置默认短信、邮件或 QQ 通道。
- 发送短信前,必须先创建并启用短信模板。
- 如果短信通道提供商为 `SPUG`,则短信模板还必须配置外部模板 ID `externalId`。
@@ -38,40 +44,29 @@
### 4.1 接入方式
外部系统通过 RabbitMQ 向 MessageHub 发布业务消息。
外部系统先通过 REST 预取 `messageId`,再通过 RabbitMQ 统一 ingress 向 MessageHub 发布业务消息。
### 4.2 RabbitMQ 基础信息
| 项目 | 值 | 说明 |
| --- | --- | --- |
| Exchange | `messageExchange` | Topic 交换机 |
| Exchange | `messagehub.ingress.exchange` | Topic 交换机 |
| Exchange 类型 | `topic` | 持久化 |
| SMS 队列 | `smsQueue` | 绑定 `sms.#` |
| Email 队列 | `emailQueue` | 绑定 `email.#` |
| Queue | `messagehub.ingress.queue` | 统一业务入口队列 |
| Routing key | `message.send` | 固定路由键 |
| Header | `X-MessageHub-Access-Token` | 来源系统访问密钥 |
当前版本只消费以下两类路由:
兼容入口仍存在,但只服务旧调用方:
| 通道类型 | 路由键前缀 | 是否已实现 |
| 兼容队列 | 路由键前缀 | 说明 |
| --- | --- | --- |
| `SMS` | `sms.` | 是 |
| `EMAIL` | `email.` | 是 |
| `PUSH` | `push.` | 否 |
| `WECHAT` | `wechat.` | 否 |
| `smsQueue` | `sms.` | 旧短信入口 |
| `emailQueue` | `email.` | 旧邮件入口 |
| `qqQueue` | `qq.` | 旧 QQ 入口 |
### 4.3 路由键规则
路由键由 `channelType + "." + msgType.toLowerCase()` 组成。
| channelType | msgType | routingKey |
| --- | --- | --- |
| `SMS` | `NOTIFICATION` | `sms.notification` |
| `SMS` | `VERIFICATION` | `sms.verification` |
| `SMS` | `PROMOTION` | `sms.promotion` |
| `SMS` | `ALERT` | `sms.alert` |
| `EMAIL` | `NOTIFICATION` | `email.notification` |
| `EMAIL` | `VERIFICATION` | `email.verification` |
| `EMAIL` | `PROMOTION` | `email.promotion` |
| `EMAIL` | `ALERT` | `email.alert` |
正式 ingress 固定使用路由键 `message.send`。旧队列的 `sms.*`、`email.*`、`qq.*` 仅作为兼容路由保留。
### 4.4 AMQP 消息属性要求
@@ -80,32 +75,76 @@
| 属性 | 是否必填 | 说明 |
| --- | --- | --- |
| `contentType` | 是 | 固定为 `application/json` |
| `messageId` | 是 | 消息唯一 ID,建议不超过 100 个字符,作为 `push_log.id` 使用 |
| `messageId` | 否 | 正式入口以 body 中预取的 `messageId` 为准;可同时设置为同值便于排查 |
| `X-MessageHub-Access-Token` | 是 | 来源系统访问密钥,必须放在 AMQP header |
| `timestamp` | 否 | 建议填写发送时间,便于排查 |
| 字符编码 | 是 | 建议 UTF-8 |
说明:
- `messageId` 是 MessageHub 当前版本落库日志和重试处理的重要标识,外部系统必须传。
- `uniqueId` 是业务幂等标识,位于 JSON 消息体中,和 `messageId` 不是同一个字段。
- 建议 `messageId` 与 `uniqueId` 保持一一对应,但二者可以不同。
- `messageId` 必须先通过 `POST /api/v1/messages/ids` 预取,再放入 MQ body。
- `uniqueId` 是业务幂等标识,位于 JSON 消息体中;不传时 MessageHub 使用 `messageId`。
- 访问密钥错误、来源系统未授权平台、缺少预取日志都会被拒绝并进入 ingress 死信。
### 4.5 消息体定义
#### 4.5.1 通用字段
#### 4.5.1 统一 envelope 字段
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `receiver` | `String` | 是 | 接收目标。短信为手机号,邮件为邮箱地址 |
| `channelType` | `String` | 是 | 当前版本请只使用 `SMS` 或 `EMAIL` |
| `messageId` | `String` | 是 | 预取得到的消息 ID |
| `sourceSystem` | `String` | 是 | 来源系统编码,必须已登记、启用且 token 校验通过 |
| `platform` | `String` | 是 | `SMS`、`EMAIL`、`QQ` |
| `receiver` | `String` | 是 | 接收目标。短信为手机号,邮件为邮箱地址,QQ 为好友号或群号 |
| `msgType` | `String` | 是 | 可选值:`NOTIFICATION`、`VERIFICATION`、`PROMOTION`、`ALERT` |
| `templateCode` | `String` | 条件必填 | 短信必填;邮件选填 |
| `templateCode` | `String` | 条件必填 | 短信优先使用模板;邮件/QQ 可配合平台参数使用 |
| `templateParams` | `Object` | 否 | 模板参数,JSON 对象 |
| `channelId` | `Long` | 否 | 指定发送通道 ID;不传时按通道选择规则自动选择 |
| `sourceSystem` | `String` | 是 | 来源系统编码,必须已在 MessageHub 中登记且处于启用状态 |
| `uniqueId` | `String` | 是 | 业务唯一标识,用于幂等去重,建议不超过 100 个字符 |
| `uniqueId` | `String` | 否 | 业务唯一标识,用于幂等去重;不传时使用 `messageId` |
| `platformParams` | `Object` | 否 | 平台私有参数 |
#### 4.5.2 SMS 额外字段
正式入口示例:
```json
{
"messageId": "735000000000000001",
"sourceSystem": "order-system",
"platform": "QQ",
"receiver": "2161656029",
"msgType": "NOTIFICATION",
"templateCode": null,
"templateParams": {},
"channelId": null,
"uniqueId": "order-20260514-0001",
"platformParams": {
"targetType": "FRIEND",
"content": "[MessageHub联调] 2026-05-14T12:00:00+08:00",
"contentMode": "TEXT"
}
}
```
#### 4.5.2 平台私有参数
| platform | platformParams |
| --- | --- |
| `SMS` | `sendMethod`,兼容 `SPUG` / `OTHER`;默认 `OTHER` |
| `EMAIL` | `subject`、`content`、`bodyType`、`emailTemplateCode`、`attachmentIds` |
| `QQ` | `targetType=FRIEND|GROUP`、`content`、`contentMode=TEXT|ONEBOT_JSON` |
#### 4.5.3 REST 辅助接口
| 接口 | 说明 |
| --- | --- |
| `POST /api/v1/messages/ids` | 请求体包含 `sourceSystem`,header 携带 `X-MessageHub-Access-Token`,返回 `messageId` 和 `ACCEPTED` |
| `GET /api/v1/platforms?sourceSystem=xxx` | 返回来源系统有权限且当前有可用通道的平台 |
| `GET /api/v1/messages/{messageId}/status?sourceSystem=xxx` | 只允许来源系统查询自己的消息状态 |
### 4.6 旧队列兼容消息体
以下章节描述的是旧队列兼容入口的 DTO 字段,新接入方请优先使用统一 envelope。
#### 4.6.1 SMS 额外字段
短信消息会按 `SmsMessageDTO` 进行反序列化和校验,因此当前版本还要求携带以下字段: