fix: enforce carrier-specific channel group routing

This commit is contained in:
hectorzhao
2026-07-03 12:48:16 +08:00
parent a890b03163
commit dd09d91c1e
17 changed files with 630 additions and 78 deletions
+76 -4
View File
@@ -19,6 +19,7 @@ function createPrismaMock() {
unitPrice: 3,
status: 'active',
config: { serviceId: 'SMS' },
sendRegion: '山东',
reportFields: [{ code: 'license', name: '营业执照', fieldType: 'file', required: true, description: null, sortOrder: 1, status: 'active' }],
};
return {
@@ -43,6 +44,7 @@ function createPrismaMock() {
channelHealthMetric: { findMany: jest.fn() },
smsChannelGroup: {
findMany: jest.fn(),
findUnique: jest.fn().mockResolvedValue({ id: 'group-1', code: 'G-MOBILE', name: '移动组', carrier: 'mobile', status: 'active' }),
create: jest.fn().mockImplementation(({ data }) => Promise.resolve({ id: 'group-1', ...data })),
},
smsChannelGroupItem: {
@@ -114,7 +116,7 @@ describe('ChannelsService', () => {
passwordCipher: 'secret',
srcId: '10690000',
});
await service.createGroup({ code: 'G-MOBILE', name: '移动组', retryEnabled: true, retryTimeLimitHours: 24 });
await service.createGroup({ code: 'G-MOBILE', name: '移动组', carrier: 'mobile', retryEnabled: true, retryTimeLimitHours: 24 });
await service.createRouteRule({ tenantId: 'tenant-1', applicationId: 'app-1', groupId: 'group-1', carrier: 'mobile' });
expect(prisma.smsChannel.create).toHaveBeenCalledWith({
@@ -127,7 +129,7 @@ describe('ChannelsService', () => {
}),
});
expect(prisma.smsChannelGroup.create).toHaveBeenCalledWith({
data: expect.objectContaining({ retryEnabled: true, retryTimeLimitHours: 24 }),
data: expect.objectContaining({ carrier: 'mobile', retryEnabled: true, retryTimeLimitHours: 24 }),
});
expect(prisma.channelRouteRule.create).toHaveBeenCalledWith({
data: expect.objectContaining({
@@ -146,8 +148,78 @@ describe('ChannelsService', () => {
const prisma = createPrismaMock();
const service = new ChannelsService(prisma as never);
expect(() => service.createRouteRule({ tenantId: 'tenant-1', applicationId: 'app-1', groupId: 'group-1', carrier: 'mobile', channelId: 'channel-1' }))
.toThrow('Route rules can only bind channel groups');
await expect(service.createRouteRule({ tenantId: 'tenant-1', applicationId: 'app-1', groupId: 'group-1', carrier: 'mobile', channelId: 'channel-1' }))
.rejects.toThrow('Route rules can only bind channel groups');
expect(prisma.channelRouteRule.create).not.toHaveBeenCalled();
});
it('enforces single-carrier channel groups and compatible group items', async () => {
const prisma = createPrismaMock();
const service = new ChannelsService(prisma as never);
expect(() => service.createGroup({ code: 'G-ALL', name: '三网组', carrier: 'all' })).toThrow('carrier must be mobile, unicom, or telecom');
await service.addGroupItem({ groupId: 'group-1', channelId: 'channel-1', carrier: 'mobile', province: '山东', priority: 10 });
expect(prisma.smsChannelGroupItem.create).toHaveBeenCalledWith({
data: expect.objectContaining({ groupId: 'group-1', channelId: 'channel-1', carrier: 'mobile', province: '山东' }),
});
await expect(service.addGroupItem({ groupId: 'group-1', channelId: 'channel-1', carrier: 'unicom' }))
.rejects.toThrow('Channel group items must use the same carrier');
const compatibleChannel = {
id: 'channel-1',
code: 'CMPP-A',
name: '主通道',
carrier: 'mobile',
protocol: 'CMPP',
gatewayHost: '127.0.0.1',
gatewayPort: 17890,
enterpriseCode: 'EC',
account: 'sp',
passwordCipher: 'secret',
srcId: '10690000',
cmppVersion: '3.0',
rateLimitPerSecond: 100,
unitPrice: 3,
status: 'active',
config: { serviceId: 'SMS' },
sendRegion: '山东',
};
prisma.smsChannel.findUnique.mockResolvedValueOnce({ ...compatibleChannel, carrier: 'telecom' });
await expect(service.addGroupItem({ groupId: 'group-1', channelId: 'channel-x', carrier: 'mobile' }))
.rejects.toThrow('Channel carrier is not compatible');
prisma.smsChannel.findUnique.mockResolvedValue(compatibleChannel);
prisma.smsChannelGroupItem.findFirst
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ id: 'province-item', province: '山东' });
await expect(service.addGroupItem({ groupId: 'group-1', channelId: 'channel-2', carrier: 'mobile', province: '山东' }))
.rejects.toThrow('同一通道组内同一省份只能配置一个通道');
});
it('rejects province routes with mismatched channel sendRegion and duplicate national priorities', async () => {
const prisma = createPrismaMock();
const service = new ChannelsService(prisma as never);
prisma.smsChannel.findUnique.mockResolvedValue({ id: 'channel-henan', carrier: 'all', sendRegion: '河南' });
await expect(service.addGroupItem({ groupId: 'group-1', channelId: 'channel-henan', carrier: 'mobile', province: '山东' }))
.rejects.toThrow('Province route must use a channel with the same sendRegion');
prisma.smsChannel.findUnique.mockResolvedValue({ id: 'channel-national', carrier: 'all', sendRegion: '全国' });
prisma.smsChannelGroupItem.findFirst
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ id: 'national-priority-1', province: null, priority: 1 });
await expect(service.addGroupItem({ groupId: 'group-1', channelId: 'channel-national', carrier: 'mobile', priority: 1 }))
.rejects.toThrow('同一通道组内全国通道优先级不能重复');
});
it('requires route rule carrier to match the channel group carrier', async () => {
const prisma = createPrismaMock();
const service = new ChannelsService(prisma as never);
await expect(service.createRouteRule({ tenantId: 'tenant-1', applicationId: 'app-1', groupId: 'group-1', carrier: 'unicom' }))
.rejects.toThrow('Route rule carrier must match the channel group carrier');
expect(prisma.channelRouteRule.create).not.toHaveBeenCalled();
});
+78 -3
View File
@@ -24,6 +24,7 @@ export interface CreateChannelDto {
export interface CreateChannelGroupDto {
code: string;
name: string;
carrier: string;
description?: string;
status?: string;
retryEnabled?: boolean;
@@ -391,10 +392,12 @@ export class ChannelsService {
if (!Number.isInteger(retryTimeLimitHours) || retryTimeLimitHours <= 0 || retryTimeLimitHours > 72) {
throw new BadRequestException('retryTimeLimitHours must be an integer between 1 and 72');
}
const carrier = normalizeBusinessCarrier(data.carrier);
return this.prisma.smsChannelGroup.create({
data: {
code: data.code,
name: data.name,
carrier,
description: data.description,
status: data.status ?? 'active',
retryEnabled: data.retryEnabled ?? true,
@@ -404,17 +407,51 @@ export class ChannelsService {
}
async addGroupItem(data: CreateChannelGroupItemDto) {
const group = await this.prisma.smsChannelGroup.findUnique({ where: { id: data.groupId } });
if (!group) {
throw new NotFoundException('Channel group not found');
}
const groupCarrier = normalizeBusinessCarrier(group.carrier);
const itemCarrier = data.carrier ? normalizeBusinessCarrier(data.carrier) : groupCarrier;
if (itemCarrier !== groupCarrier) {
throw new BadRequestException('Channel group items must use the same carrier as the channel group');
}
const channel = await this.prisma.smsChannel.findUnique({ where: { id: data.channelId } });
if (!channel) {
throw new NotFoundException('Channel not found');
}
if (!isChannelCarrierCompatible(channel.carrier, groupCarrier)) {
throw new BadRequestException('Channel carrier is not compatible with the channel group carrier');
}
if (data.province && !isRegionCompatible(channel.sendRegion, data.province)) {
throw new BadRequestException('Province route must use a channel with the same sendRegion');
}
const existing = await this.prisma.smsChannelGroupItem.findFirst({
where: { groupId: data.groupId, channelId: data.channelId },
});
if (existing) {
throw new BadRequestException('通道组内不能重复配置同一通道');
}
if (data.province) {
const existingProvince = await this.prisma.smsChannelGroupItem.findFirst({
where: { groupId: data.groupId, province: data.province },
});
if (existingProvince) {
throw new BadRequestException('同一通道组内同一省份只能配置一个通道');
}
} else {
const existingPriority = await this.prisma.smsChannelGroupItem.findFirst({
where: { groupId: data.groupId, province: null, priority: data.priority ?? 100 },
});
if (existingPriority) {
throw new BadRequestException('同一通道组内全国通道优先级不能重复');
}
}
return this.prisma.smsChannelGroupItem.create({
data: {
groupId: data.groupId,
channelId: data.channelId,
carrier: data.carrier,
carrier: itemCarrier,
province: data.province,
priority: data.priority ?? 100,
weight: data.weight ?? 1,
@@ -432,26 +469,34 @@ export class ChannelsService {
});
}
createRouteRule(data: CreateRouteRuleDto) {
async createRouteRule(data: CreateRouteRuleDto) {
if (!data.applicationId) {
throw new BadRequestException('applicationId is required for channel group routing');
}
if (!data.carrier) {
throw new BadRequestException('carrier is required for application channel group routing');
}
const carrier = normalizeBusinessCarrier(data.carrier);
if (data.channelId) {
throw new BadRequestException('Route rules can only bind channel groups, not single channels');
}
if (data.province) {
throw new BadRequestException('Province routing must be configured inside the channel group');
}
const group = await this.prisma.smsChannelGroup.findUnique({ where: { id: data.groupId } });
if (!group) {
throw new NotFoundException('Channel group not found');
}
if (normalizeBusinessCarrier(group.carrier) !== carrier) {
throw new BadRequestException('Route rule carrier must match the channel group carrier');
}
return this.prisma.channelRouteRule.create({
data: {
tenantId: data.tenantId,
applicationId: data.applicationId,
groupId: data.groupId,
channelId: undefined,
carrier: data.carrier,
carrier,
province: undefined,
priority: data.priority ?? 100,
status: data.status ?? 'active',
@@ -645,6 +690,36 @@ function normalizeConnectionAction(status: string) {
return 'updated';
}
function normalizeBusinessCarrier(carrier?: string | null) {
const normalized = normalizeChannelCarrier(carrier);
if (!['mobile', 'unicom', 'telecom'].includes(normalized)) {
throw new BadRequestException('carrier must be mobile, unicom, or telecom');
}
return normalized;
}
function normalizeChannelCarrier(carrier?: string | null) {
const value = String(carrier ?? '').trim().toLowerCase();
if (['mobile', 'cmcc', '移动', '中国移动'].includes(value)) return 'mobile';
if (['unicom', 'cucc', '联通', '中国联通'].includes(value)) return 'unicom';
if (['telecom', 'ctcc', '电信', '中国电信'].includes(value)) return 'telecom';
if (['all', 'tri', '三网', '全网'].includes(value)) return 'all';
return value;
}
function isChannelCarrierCompatible(channelCarrier: string | null | undefined, groupCarrier: string) {
const normalized = normalizeChannelCarrier(channelCarrier);
return normalized === 'all' || normalized === groupCarrier;
}
function normalizeRegion(region?: string | null) {
return String(region ?? '').replace(/省|市|自治区|壮族|回族|维吾尔/g, '').trim();
}
function isRegionCompatible(channelRegion: string | null | undefined, itemProvince: string) {
return normalizeRegion(channelRegion) === normalizeRegion(itemProvince);
}
function normalizeLinkEvent(action: string) {
if (action.includes('connected')) {
return '新建';