收口调度器与通知工作器关闭边界

This commit is contained in:
Christ committed 2026-08-15 16:46:16 +08:00
1 parent c1c065e023
commit e609f7b39a
8 files changed
+129 -10

No files matched your search

+26 -2
View File
@@ -61,6 +61,7 @@ type Notifier struct {
httpc *http.Client
started atomic.Bool
workers sync.WaitGroup
done chan struct{}
}
// newOutboundHTTPClient 保存newOutboundHTTPClient,供当前处理流程使用
@@ -84,6 +85,7 @@ func NewWithRepository(cookieID string, repository Repository, logger *slog.Logg
repository: repository,
logger: logger.With("account", cookieID, "subsys", "notify"),
httpc: newOutboundHTTPClient(),
done: make(chan struct{}),
}
}
@@ -97,12 +99,34 @@ func (n *Notifier) Start(ctx context.Context) {
n.workers.Add(1)
go func() {
defer n.workers.Done()
defer close(n.done)
n.runOutbox(ctx)
}()
}
// Wait 等待 outbox worker 随生命周期 context 退出。
func (n *Notifier) Wait() { n.workers.Wait() }
// Wait 等待 outbox worker 随生命周期 context 退出,并兼容旧调用方。
func (n *Notifier) Wait() {
_ = n.WaitContext(context.Background())
}
// WaitContext 在 ctx 约束内等待 outbox worker 退出。
func (n *Notifier) WaitContext(ctx context.Context) error {
if n == nil {
return nil
}
if !n.started.Load() || n.done == nil {
return nil
}
if ctx == nil {
ctx = context.Background()
}
select {
case <-n.done:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// NotifyDelivery 发送发货结果通知。
// accountID 为 cookie_id。向该账号所有已启用渠道发送发货通知。
+21
View File
@@ -3,15 +3,36 @@ package notify
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
"xianyu-go/internal/db"
)
// TestNotifierWaitContextHonorsDeadline 验证通知 worker 等待受关闭上下文限制。
func TestNotifierWaitContextHonorsDeadline(t *testing.T) {
// notifier 保存已启动但尚未完成的通知器,以验证等待超时不会永久阻塞。
notifier := &Notifier{done: make(chan struct{})}
notifier.started.Store(true)
// ctx、cancel 保存短时关闭上下文及其释放函数。
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Millisecond)
defer cancel()
// err 表示尚未完成 worker 在超时上下文下的等待结果。
if err := notifier.WaitContext(ctx); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("WaitContext error=%v, want deadline exceeded", err)
}
close(notifier.done)
// err 表示已完成 worker 的等待结果。
if err := notifier.WaitContext(context.Background()); err != nil {
t.Fatalf("completed WaitContext error=%v", err)
}
}
// newNotifyStore 负责newNotifyStore相关处理。
func newNotifyStore(t *testing.T) (*db.Store, func()) {
t.Helper()