refactor(worker): Outbox 轮询可被信号打断
StartOutboxPoller 接受 ctx 并改为阻塞函数,调用方负责放进自己的 goroutine。 轮询等待由 waitOrDone 实现。ctx 取消后立即返回 false,不再 sleep 满一秒。单条发布的超时派生自该 ctx,停机时不会挂在一条消息上。 StartConsumer 同样去掉内部 go,改为阻塞到 ctx 取消。 测试覆盖 waitOrDone 的两条路径:取消后立即返回,未取消时等满间隔。
This commit is contained in:
@@ -21,47 +21,75 @@ import (
|
||||
// 的既有语义,而不是把整个轮询器挂在一条消息上。
|
||||
const outboxPublishTimeout = 5 * time.Second
|
||||
|
||||
// 轮询器,轮询数据库中的 outbox 表,获取待投递的消息,投递到 MQ 中
|
||||
func StartOutboxPoller(db *gorm.DB, tmq *rabbitmq.TimelineMQ) {
|
||||
const (
|
||||
// outboxPollInterval 是空批次后的等待时间。
|
||||
outboxPollInterval = time.Second
|
||||
// outboxBatchSize 是单轮最多投递的行数。
|
||||
outboxBatchSize = 100
|
||||
)
|
||||
|
||||
// StartOutboxPoller 轮询 outbox 表并把待投递消息发布到 timeline exchange,
|
||||
// 阻塞到 ctx 取消;调用方负责把它放进自己的 goroutine。
|
||||
//
|
||||
// 它跑在 Worker 进程而不是 API 进程:随 API 实例数复制会让同一行被投递多次,
|
||||
// 而 API 的退出路径也不该等待一个数据库轮询器。
|
||||
func StartOutboxPoller(ctx context.Context, db *gorm.DB, tmq *rabbitmq.TimelineMQ) {
|
||||
if db == nil || tmq == nil {
|
||||
log.Printf("Outbox poller disabled: timeline mq is not initialized")
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
var messages []video.OutboxMsg
|
||||
for ctx.Err() == nil {
|
||||
var messages []video.OutboxMsg
|
||||
|
||||
err := db.Where("status = ?", "pending").Order("create_time ASC").Limit(100).Find(&messages).Error
|
||||
|
||||
if err != nil {
|
||||
log.Printf("outbox 轮询失败: %v", err)
|
||||
time.Sleep(1 * time.Second)
|
||||
continue
|
||||
err := db.Where("status = ?", "pending").Order("create_time ASC").Limit(outboxBatchSize).Find(&messages).Error
|
||||
if err != nil {
|
||||
log.Printf("outbox 轮询失败: %v", err)
|
||||
if !waitOrDone(ctx, outboxPollInterval) {
|
||||
return
|
||||
}
|
||||
if len(messages) == 0 {
|
||||
time.Sleep(1 * time.Second)
|
||||
continue
|
||||
continue
|
||||
}
|
||||
if len(messages) == 0 {
|
||||
if !waitOrDone(ctx, outboxPollInterval) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
for _, msg := range messages {
|
||||
pubCtx, cancel := context.WithTimeout(context.Background(), outboxPublishTimeout)
|
||||
err := tmq.PublishVideo(pubCtx, msg.VideoID, msg.CreateTime)
|
||||
cancel()
|
||||
for _, msg := range messages {
|
||||
// 超时派生自 poller 的 ctx:进程退出时不再为一条消息多等 5 秒。
|
||||
pubCtx, cancel := context.WithTimeout(ctx, outboxPublishTimeout)
|
||||
err := tmq.PublishVideo(pubCtx, msg.VideoID, msg.CreateTime)
|
||||
cancel()
|
||||
|
||||
if err == nil {
|
||||
if err := db.Delete(&msg).Error; err != nil {
|
||||
log.Printf("删除 outbox 消息失败: id=%d, err=%v", msg.ID, err)
|
||||
}
|
||||
} else {
|
||||
log.Printf("投递MQ失败: VideoID: %d, err: %v", msg.VideoID, err)
|
||||
if err == nil {
|
||||
if err := db.Delete(&msg).Error; err != nil {
|
||||
log.Printf("删除 outbox 消息失败: id=%d, err=%v", msg.ID, err)
|
||||
}
|
||||
} else {
|
||||
log.Printf("投递MQ失败: VideoID: %d, err: %v", msg.VideoID, err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// StartConsumer 消费 timeline 事件并写入 Redis ZSet。
|
||||
// waitOrDone 等待 d 或 ctx 取消;返回 true 表示等满间隔,false 表示被取消。
|
||||
//
|
||||
// 抽成独立函数是为了让"轮询间隔可被退出信号打断"能被单测直接验证——它不碰数据库。
|
||||
func waitOrDone(ctx context.Context, d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-t.C:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// StartConsumer 消费 timeline 事件并写入 Redis ZSet,阻塞到 ctx 取消;
|
||||
// 调用方负责把它放进自己的 goroutine。
|
||||
//
|
||||
// 连接级重连、拓扑重放、channel 重建全部交给连接管理器(rabbitmq.RunConsumer),
|
||||
// 这里只关心"一条消息应该怎么被处理"。
|
||||
@@ -75,7 +103,7 @@ func StartConsumer(ctx context.Context, rmq *rabbitmq.RabbitMQ, queueName string
|
||||
return
|
||||
}
|
||||
|
||||
go rabbitmq.RunConsumer(ctx, rmq, "TimelineConsumer", 10, func(ch *amqp.Channel) error {
|
||||
rabbitmq.RunConsumer(ctx, rmq, "TimelineConsumer", 10, func(ch *amqp.Channel) error {
|
||||
msgs, err := ch.Consume(queueName, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
33
backend/internal/worker/outboxworker_test.go
Normal file
33
backend/internal/worker/outboxworker_test.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 轮询间隔必须可被 ctx 打断:否则 Worker 收到 SIGTERM 后还要把最后一轮空等走完。
|
||||
func TestWaitOrDone(t *testing.T) {
|
||||
t.Run("ctx 已取消时立即返回 false", func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
start := time.Now()
|
||||
if waitOrDone(ctx, time.Minute) {
|
||||
t.Fatal("ctx 已取消时不应报告等待完成")
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > time.Second {
|
||||
t.Fatalf("ctx 已取消仍等待了 %v", elapsed)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ctx 未取消时等满间隔返回 true", func(t *testing.T) {
|
||||
start := time.Now()
|
||||
if !waitOrDone(context.Background(), 20*time.Millisecond) {
|
||||
t.Fatal("ctx 未取消时应报告等待完成")
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed < 20*time.Millisecond {
|
||||
t.Fatalf("提前返回:%v", elapsed)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user