阶段七:完成 React Feature 化与前置重构收口
This commit is contained in:
1 parent
375e84d663
commit
1a228dc35c
305 files changed
+14179
-5431
No files matched your search
@@ -0,0 +1,10 @@
|
||||
-- +goose Up
|
||||
-- idempotency_key 让同一自动化运行终态对同一渠道只保留一条 outbox 记录。
|
||||
-- NULL 保持历史普通通知可重复投递;uncertain 记录保留原键,从而禁止恢复时自动重新入队。
|
||||
ALTER TABLE notification_outbox ADD COLUMN idempotency_key VARCHAR(255) NULL;
|
||||
CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency
|
||||
ON notification_outbox(channel_id, idempotency_key);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX idx_notification_outbox_channel_idempotency ON notification_outbox;
|
||||
ALTER TABLE notification_outbox DROP COLUMN idempotency_key;
|
||||
@@ -0,0 +1,10 @@
|
||||
-- +goose Up
|
||||
-- idempotency_key 让同一自动化运行终态对同一渠道只保留一条 outbox 记录。
|
||||
-- NULL 保持历史普通通知可重复投递;uncertain 记录保留原键,从而禁止恢复时自动重新入队。
|
||||
ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL;
|
||||
CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency
|
||||
ON notification_outbox(channel_id, idempotency_key);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency;
|
||||
ALTER TABLE notification_outbox DROP COLUMN idempotency_key;
|
||||
@@ -0,0 +1,10 @@
|
||||
-- +goose Up
|
||||
-- idempotency_key 让同一自动化运行终态对同一渠道只保留一条 outbox 记录。
|
||||
-- NULL 保持历史普通通知可重复投递;uncertain 记录保留原键,从而禁止恢复时自动重新入队。
|
||||
ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL;
|
||||
CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency
|
||||
ON notification_outbox(channel_id, idempotency_key);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency;
|
||||
ALTER TABLE notification_outbox DROP COLUMN idempotency_key;
|
||||
@@ -105,6 +105,83 @@ func TestNotificationOutboxLeaseFencesStaleWorker(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotificationOutboxIdempotencyKeepsUncertainMessage 验证同一业务投递键不会重复入队,
|
||||
// 且外部发送成功后本地确认失败形成 uncertain 时,恢复扫描也不能把它重新变为可发送状态。
|
||||
func TestNotificationOutboxIdempotencyKeepsUncertainMessage(t *testing.T) {
|
||||
// store、cleanup 保存带完整迁移的 SQLite 存储与关闭责任。
|
||||
store, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
// ctx 限制本测试所有数据库操作的生命周期。
|
||||
ctx := context.Background()
|
||||
// created、createErr 保存测试用户创建结果和数据库错误。
|
||||
created, createErr := store.Users.Create(ctx, "notify-idempotency", "[email protected]", "pw")
|
||||
if createErr != nil || !created {
|
||||
t.Fatalf("create owner: created=%v err=%v", created, createErr)
|
||||
}
|
||||
// owner、ownerErr 保存通知渠道所属用户和读取错误。
|
||||
owner, ownerErr := store.Users.GetByUsername(ctx, "notify-idempotency")
|
||||
if ownerErr != nil {
|
||||
t.Fatal(ownerErr)
|
||||
}
|
||||
// channelResult、channelErr 保存测试通知渠道插入结果和数据库错误。
|
||||
channelResult, channelErr := store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES (?,?,?,1,?)`, "idempotency", "webhook", `{}`, owner.ID)
|
||||
if channelErr != nil {
|
||||
t.Fatal(channelErr)
|
||||
}
|
||||
// channelID、channelIDErr 保存测试渠道主键和读取错误。
|
||||
channelID, channelIDErr := channelResult.LastInsertId()
|
||||
if channelIDErr != nil {
|
||||
t.Fatal(channelIDErr)
|
||||
}
|
||||
// input 表示同一自动化运行成功终态对该渠道的稳定投递事实。
|
||||
input := NotificationOutboxInput{ChannelID: channelID, EventType: "delivery_result", Body: "自动化结果", IdempotencyKey: "automation-run:42:success"}
|
||||
// enqueueErr 保存首次持久化业务投递键时的数据库错误。
|
||||
if enqueueErr := store.Notifications.EnqueueOutbox(ctx, []NotificationOutboxInput{input}); enqueueErr != nil {
|
||||
t.Fatal(enqueueErr)
|
||||
}
|
||||
// enqueueErr 保存同一业务投递键重复入队时的数据库错误;冲突应被仓储忽略而非作为错误返回。
|
||||
if enqueueErr := store.Notifications.EnqueueOutbox(ctx, []NotificationOutboxInput{input}); enqueueErr != nil {
|
||||
t.Fatal(enqueueErr)
|
||||
}
|
||||
// queued 保存第一次重复入队后的记录数;同一渠道只能保留一条该业务键。
|
||||
var queued int
|
||||
// queryErr 保存读取去重后记录数时的数据库错误。
|
||||
if queryErr := store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM notification_outbox WHERE channel_id=? AND idempotency_key=?`, channelID, input.IdempotencyKey).Scan(&queued); queryErr != nil {
|
||||
t.Fatal(queryErr)
|
||||
}
|
||||
if queued != 1 {
|
||||
t.Fatalf("duplicate queue count=%d want 1", queued)
|
||||
}
|
||||
// claimed、claimErr 保存本次投递领取的记录和数据库错误。
|
||||
claimed, claimErr := store.Notifications.ClaimOutbox(ctx, "idempotency-worker", time.Now(), 1)
|
||||
if claimErr != nil || len(claimed) != 1 {
|
||||
t.Fatalf("claim: messages=%+v err=%v", claimed, claimErr)
|
||||
}
|
||||
// isolated、isolateErr 保存外部投递成功但本地确认失败后的隔离结果和数据库错误。
|
||||
isolated, isolateErr := store.Notifications.MarkOutboxUncertain(ctx, claimed[0].ID, "idempotency-worker", "local completion failed")
|
||||
if isolateErr != nil || !isolated {
|
||||
t.Fatalf("mark uncertain: isolated=%v err=%v", isolated, isolateErr)
|
||||
}
|
||||
// enqueueErr 保存 uncertain 运行被恢复流程再次报告时的数据库错误;同一键必须继续被忽略。
|
||||
if enqueueErr := store.Notifications.EnqueueOutbox(ctx, []NotificationOutboxInput{input}); enqueueErr != nil {
|
||||
t.Fatal(enqueueErr)
|
||||
}
|
||||
// status 保存恢复后仍应保留的 uncertain 状态,禁止重新变为 pending。
|
||||
var status string
|
||||
// queryErr 保存读取 uncertain 状态时的数据库错误。
|
||||
if queryErr := store.DB.QueryRowContext(ctx, `SELECT status FROM notification_outbox WHERE channel_id=? AND idempotency_key=?`, channelID, input.IdempotencyKey).Scan(&status); queryErr != nil {
|
||||
t.Fatal(queryErr)
|
||||
}
|
||||
if status != "uncertain" {
|
||||
t.Fatalf("status=%q want uncertain", status)
|
||||
}
|
||||
// recoveredClaim、recoveredErr 保存重复恢复后可领取消息和数据库错误;uncertain 消息必须不可领取。
|
||||
recoveredClaim, recoveredErr := store.Notifications.ClaimOutbox(ctx, "recovery-worker", time.Now().Add(time.Hour), 10)
|
||||
if recoveredErr != nil || len(recoveredClaim) != 0 {
|
||||
t.Fatalf("uncertain message became claimable: messages=%+v err=%v", recoveredClaim, recoveredErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotificationOutboxPermanentRetry 将达到重试上限的发送失败消息标记为 dead 隔离。
|
||||
func TestNotificationOutboxPermanentRetry(t *testing.T) {
|
||||
// store、cleanup 保存测试数据库及其关闭责任。
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -36,9 +37,14 @@ func (n *Notifications) OwnsChannel(ctx context.Context, channelID, userID int64
|
||||
|
||||
// NotificationOutboxInput 保存通知OutboxInput,供当前处理流程使用
|
||||
type NotificationOutboxInput struct {
|
||||
// ChannelID 是接收本次通知的渠道主键;幂等约束以渠道为粒度,避免一个渠道的重复入队影响其他渠道。
|
||||
ChannelID int64
|
||||
// EventType 是通知类别,仅用于渠道订阅过滤和运维分类,不携带业务正文。
|
||||
EventType string
|
||||
Body string
|
||||
// Body 是 worker 投递给外部渠道的格式化正文,只能留在 outbox 内部处理流程。
|
||||
Body string
|
||||
// IdempotencyKey 是可选的业务投递键;非空时同一渠道只保留一条该键对应的记录,包括 uncertain 隔离记录。
|
||||
IdempotencyKey string
|
||||
}
|
||||
|
||||
// NotificationOutboxMessage 保存通知Outbox消息,供当前处理流程使用
|
||||
@@ -271,6 +277,8 @@ func (n *Notifications) AccountChannels(ctx context.Context, cookieID string) ([
|
||||
}
|
||||
|
||||
// EnqueueOutbox 在一个事务中持久化同一事件的各渠道投递,避免进程退出造成部分丢失。
|
||||
// IdempotencyKey 非空时,(channel_id,idempotency_key) 唯一约束会忽略重复入队;这样 uncertain
|
||||
// 消息不会因业务运行恢复而重新变为 pending,外部投递成功但本地确认失败时不会自动重发。
|
||||
func (n *Notifications) EnqueueOutbox(ctx context.Context, messages []NotificationOutboxInput) error {
|
||||
if len(messages) == 0 {
|
||||
return nil
|
||||
@@ -281,19 +289,33 @@ func (n *Notifications) EnqueueOutbox(ctx context.Context, messages []Notificati
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
// message 表示当前遍历过程中的消息
|
||||
// insertSQL 使用方言一致的冲突忽略语义,只把同一渠道的相同业务投递键视为重复。
|
||||
insertSQL := dialectInsertIgnorePrefix(n.Dialect) + ` INTO notification_outbox
|
||||
(channel_id,event_type,body,idempotency_key,status,attempt_count,next_attempt_at,lease_expires_at,worker_token,last_error)
|
||||
VALUES (?,?,?,?, 'pending',0,0,0,'','')` + dialectInsertIgnore(n.Dialect, []string{"channel_id", "idempotency_key"})
|
||||
// message 表示当前事务中待写入的单渠道通知。
|
||||
for _, message := range messages {
|
||||
// idempotencyKey 将空字符串转换为 NULL,使未指定业务幂等键的历史通知保持可重复发送语义。
|
||||
idempotencyKey := nullableOutboxIdempotencyKey(message.IdempotencyKey)
|
||||
if // err 保存err,供当前处理流程使用
|
||||
_, err := tx.ExecContext(ctx, `INSERT INTO notification_outbox
|
||||
(channel_id,event_type,body,status,attempt_count,next_attempt_at,lease_expires_at,worker_token,last_error)
|
||||
VALUES (?,?,?,'pending',0,0,0,'','')`,
|
||||
message.ChannelID, message.EventType, message.Body); err != nil {
|
||||
_, err := tx.ExecContext(ctx, insertSQL, message.ChannelID, message.EventType, message.Body, idempotencyKey); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// nullableOutboxIdempotencyKey 将未声明幂等语义的空键写为 SQL NULL。
|
||||
// SQL 唯一索引允许多个 NULL,因此普通账号告警和手动通知不会被错误去重。
|
||||
func nullableOutboxIdempotencyKey(key string) any {
|
||||
// trimmedKey 是移除无意义空白后的业务投递键;调用方只能用稳定键触发持久化去重。
|
||||
trimmedKey := strings.TrimSpace(key)
|
||||
if trimmedKey == "" {
|
||||
return nil
|
||||
}
|
||||
return trimmedKey
|
||||
}
|
||||
|
||||
// ClaimOutbox 原子领取到期投递。过期 running 任务可以被重新接管,worker token
|
||||
// 用于隔离迟到的旧 worker。
|
||||
// ClaimOutbox 负责ClaimOutbox相关处理。
|
||||
|
||||
Reference in new issue
Block a user