重构:完成架构一致性整改与生命周期收口
This commit is contained in:
1 parent
55904cc409
commit
9eb6be2875
344 files changed
+15961
-13926
No files matched your search
@@ -7,7 +7,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// init 负责init相关处理。
|
||||
// init 封装init业务协调。
|
||||
func init() {
|
||||
// 通知单测使用 httptest 的 loopback 服务;生产构造器仍使用 netguard。
|
||||
newOutboundHTTPClient = func() *http.Client { return &http.Client{Timeout: 10 * time.Second} }
|
||||
|
||||
+158
-154
@@ -33,7 +33,7 @@ import (
|
||||
"xianyu-go/internal/netguard"
|
||||
)
|
||||
|
||||
// EventAccountOffline 保存Event账号Offline,供当前处理流程使用
|
||||
// EventAccountOffline 用于本次流程后续判断的Event账号Offline
|
||||
const (
|
||||
EventAccountOffline = "account_offline"
|
||||
EventAccountRecovered = "account_recovered"
|
||||
@@ -66,10 +66,10 @@ type Notifier struct {
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
// newOutboundHTTPClient 保存newOutboundHTTPClient,供当前处理流程使用
|
||||
// newOutboundHTTPClient 用于本次流程后续判断的newOutboundHTTPClient
|
||||
var newOutboundHTTPClient = func() *http.Client { return netguard.PublicHTTPClient(10 * time.Second) }
|
||||
|
||||
// dialPublicSMTP 保存dialPublicSMTP,供当前处理流程使用
|
||||
// dialPublicSMTP 用于本次流程后续判断的dialPublicSMTP
|
||||
var dialPublicSMTP = netguard.DialPublicContext
|
||||
|
||||
// New 构造。
|
||||
@@ -95,6 +95,10 @@ func NewWithRepository(cookieID string, repository Repository, logger *slog.Logg
|
||||
// 通知只写数据库,不在订单/账号处理调用栈中等待外部网络。
|
||||
// Start 启动当前值。
|
||||
func (n *Notifier) Start(ctx context.Context) {
|
||||
// nil Context 无法提供取消边界,拒绝启动以免创建无法回收的后台 worker。
|
||||
if ctx == nil {
|
||||
return
|
||||
}
|
||||
if n == nil || n.repository == nil || !n.started.CompareAndSwap(false, true) {
|
||||
return
|
||||
}
|
||||
@@ -132,7 +136,7 @@ func (n *Notifier) WaitContext(ctx context.Context) error {
|
||||
|
||||
// NotifyDelivery 发送发货结果通知。
|
||||
// accountID 为 cookie_id。向该账号所有已启用渠道发送发货通知。
|
||||
// NotifyDelivery 负责Notify发货相关处理。
|
||||
// NotifyDelivery 封装Notify发货业务协调。
|
||||
func (n *Notifier) NotifyDelivery(accountID, buyerName, buyerID, itemID, message, chatID string) {
|
||||
n.NotifyEvent(context.Background(), NotificationEvent{
|
||||
AccountID: accountID,
|
||||
@@ -175,7 +179,7 @@ func (n *Notifier) NotifyAutomationRun(ctx context.Context, runID int64, account
|
||||
|
||||
// NotifyAccountAlert 发送账号告警通知(token 失效/自动恢复失败/风控验证等)。
|
||||
// level 取 AlertLevel* 常量。向该账号所有已启用渠道发送。
|
||||
// NotifyAccountAlert 负责Notify账号Alert相关处理。
|
||||
// NotifyAccountAlert 封装Notify账号Alert业务协调。
|
||||
func (n *Notifier) NotifyAccountAlert(accountID, level, title, body string) {
|
||||
n.NotifyAccountEvent(accountID, classifyAccountAlertEvent(title, body), level, title, body)
|
||||
}
|
||||
@@ -204,18 +208,18 @@ func (n *Notifier) notifyEvent(ctx context.Context, ev NotificationEvent, idempo
|
||||
if ev.Time.IsZero() {
|
||||
ev.Time = time.Now()
|
||||
}
|
||||
// channels、err 保存channels、err,供当前处理流程使用
|
||||
// channels、err 用于本次流程后续判断的channels、err
|
||||
channels, err := n.repository.AccountChannels(ctx, ev.AccountID)
|
||||
if err != nil || len(channels) == 0 {
|
||||
return
|
||||
}
|
||||
// full 保存full,供当前处理流程使用
|
||||
// full 用于本次流程后续判断的full
|
||||
full := formatEvent(ev)
|
||||
// eligible 保存eligible,供当前处理流程使用
|
||||
// eligible 用于本次流程后续判断的eligible
|
||||
eligible := make([]db.NotificationChannel, 0, len(channels))
|
||||
// ch 表示当前遍历过程中的ch
|
||||
for _, ch := range channels {
|
||||
// allowed、err 保存allowed、err,供当前处理流程使用
|
||||
// allowed、err 用于本次流程后续判断的allowed、err
|
||||
allowed, err := eventAllowed(ch.EventTypes, ev.Type)
|
||||
if err != nil {
|
||||
n.logger.Warn("通知事件订阅配置无效,跳过渠道", "channel", ch.ID, "event_types", ch.EventTypes, "err", err)
|
||||
@@ -235,7 +239,7 @@ func (n *Notifier) notifyEvent(ctx context.Context, ev NotificationEvent, idempo
|
||||
for _, ch := range eligible {
|
||||
messages = append(messages, db.NotificationOutboxInput{ChannelID: ch.ID, EventType: ev.Type, Body: full, IdempotencyKey: idempotencyKey})
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := n.repository.EnqueueOutbox(ctx, messages); err != nil {
|
||||
n.logger.Error("持久化通知失败", "event_type", ev.Type, "err", err)
|
||||
}
|
||||
@@ -243,17 +247,17 @@ func (n *Notifier) notifyEvent(ctx context.Context, ev NotificationEvent, idempo
|
||||
}
|
||||
// 未启动 worker 的独立使用场景保持同步行为,便于 CLI 和单元测试显式使用。
|
||||
for _, ch := range eligible {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := n.send(ch, full); err != nil {
|
||||
n.logger.Error("发送通知失败", "channel", ch.Type, "event_type", ev.Type, "err", logsafe.Error(err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// runOutbox 负责运行Outbox相关处理。
|
||||
// runOutbox 封装运行Outbox业务协调。
|
||||
func (n *Notifier) runOutbox(ctx context.Context) {
|
||||
n.drainOutbox(ctx)
|
||||
// ticker 保存ticker,供当前处理流程使用
|
||||
// ticker 用于本次流程后续判断的ticker
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
@@ -266,15 +270,15 @@ func (n *Notifier) runOutbox(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// drainOutbox 负责drainOutbox相关处理。
|
||||
// drainOutbox 封装drainOutbox业务协调。
|
||||
func (n *Notifier) drainOutbox(ctx context.Context) {
|
||||
// workerToken、err 保存工作器Token、err,供当前处理流程使用
|
||||
// workerToken、err 用于本次流程后续判断的工作器Token、err
|
||||
workerToken, err := notificationWorkerToken()
|
||||
if err != nil {
|
||||
n.logger.Error("生成通知 worker token 失败", "err", err)
|
||||
return
|
||||
}
|
||||
// messages、err 保存messages、err,供当前处理流程使用
|
||||
// messages、err 用于本次流程后续判断的messages、err
|
||||
messages, err := n.repository.ClaimOutbox(ctx, workerToken, time.Now(), 20)
|
||||
if err != nil {
|
||||
if ctx.Err() == nil {
|
||||
@@ -284,7 +288,7 @@ func (n *Notifier) drainOutbox(ctx context.Context) {
|
||||
}
|
||||
// message 表示当前遍历过程中的消息
|
||||
for _, message := range messages {
|
||||
// channel、getErr 保存channel、getErr,供当前处理流程使用
|
||||
// channel、getErr 用于本次流程后续判断的channel、getErr
|
||||
channel, getErr := n.repository.GetChannel(ctx, message.ChannelID)
|
||||
if getErr != nil {
|
||||
n.retryOutbox(ctx, message, workerToken, getErr)
|
||||
@@ -300,13 +304,13 @@ func (n *Notifier) drainOutbox(ctx context.Context) {
|
||||
}
|
||||
continue
|
||||
}
|
||||
if // sendErr 保存sendErr,供当前处理流程使用
|
||||
if // sendErr 用于本次流程后续判断的sendErr
|
||||
sendErr := n.send(*channel, message.Body); sendErr != nil {
|
||||
n.logger.Error("发送通知失败", "channel", channel.Type, "event_type", message.EventType, "attempt", message.AttemptCount, "err", logsafe.Error(sendErr))
|
||||
n.retryOutbox(ctx, message, workerToken, sendErr)
|
||||
continue
|
||||
}
|
||||
if // completed、completeErr 保存completed、completeErr,供当前处理流程使用
|
||||
if // completed、completeErr 用于本次流程后续判断的completed、completeErr
|
||||
completed, completeErr := n.repository.CompleteOutbox(ctx, message.ID, workerToken); completeErr != nil {
|
||||
// uncertain、uncertainErr 保存发送成功后的隔离结果和隔离失败错误。
|
||||
uncertain, uncertainErr := n.repository.MarkOutboxUncertain(ctx, message.ID, workerToken, completeErr.Error())
|
||||
@@ -323,15 +327,15 @@ func (n *Notifier) drainOutbox(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// retryOutbox 负责重试Outbox相关处理。
|
||||
// retryOutbox 封装重试Outbox业务协调。
|
||||
func (n *Notifier) retryOutbox(ctx context.Context, message db.NotificationOutboxMessage, workerToken string, cause error) {
|
||||
// permanent 保存permanent,供当前处理流程使用
|
||||
// permanent 用于本次流程后续判断的permanent
|
||||
permanent := message.AttemptCount >= 10
|
||||
// shift 保存shift,供当前处理流程使用
|
||||
// shift 用于本次流程后续判断的shift
|
||||
shift := min(max(message.AttemptCount-1, 0), 7)
|
||||
// delay 保存延迟,供当前处理流程使用
|
||||
// delay 用于本次流程后续判断的延迟
|
||||
delay := 5 * time.Second * time.Duration(1<<shift)
|
||||
// updated、err 保存updated、err,供当前处理流程使用
|
||||
// updated、err 用于本次流程后续判断的updated、err
|
||||
updated, err := n.repository.RetryOutbox(ctx, message.ID, workerToken, cause.Error(), time.Now().Add(delay).Unix(), permanent)
|
||||
if err != nil {
|
||||
n.logger.Warn("更新通知重试状态失败", "outbox_id", message.ID, "err", err)
|
||||
@@ -340,11 +344,11 @@ func (n *Notifier) retryOutbox(ctx context.Context, message db.NotificationOutbo
|
||||
}
|
||||
}
|
||||
|
||||
// notificationWorkerToken 负责通知工作器令牌相关处理。
|
||||
// notificationWorkerToken 封装通知工作器令牌业务协调。
|
||||
func notificationWorkerToken() (string, error) {
|
||||
// raw 保存原始,供当前处理流程使用
|
||||
// raw 用于本次流程后续判断的原始
|
||||
raw := make([]byte, 16)
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := rand.Read(raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -356,7 +360,7 @@ func (n *Notifier) SendToChannel(channelID int64, body string) error {
|
||||
if n == nil || n.repository == nil {
|
||||
return fmt.Errorf("通知器未初始化")
|
||||
}
|
||||
// ch、err 保存ch、err,供当前处理流程使用
|
||||
// ch、err 用于本次流程后续判断的ch、err
|
||||
ch, err := n.repository.GetChannel(context.Background(), channelID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("查询渠道失败: %w", err)
|
||||
@@ -367,7 +371,7 @@ func (n *Notifier) SendToChannel(channelID int64, body string) error {
|
||||
return n.send(*ch, body)
|
||||
}
|
||||
|
||||
// levelLabel 负责levelLabel相关处理。
|
||||
// levelLabel 封装levelLabel业务协调。
|
||||
func levelLabel(level string) string {
|
||||
switch level {
|
||||
case "critical":
|
||||
@@ -381,7 +385,7 @@ func levelLabel(level string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// eventLabel 负责eventLabel相关处理。
|
||||
// eventLabel 封装eventLabel业务协调。
|
||||
func eventLabel(eventType string) string {
|
||||
switch eventType {
|
||||
case EventAccountOffline:
|
||||
@@ -406,9 +410,9 @@ func eventLabel(eventType string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// classifyAccountAlertEvent 负责classify账号AlertEvent相关处理。
|
||||
// classifyAccountAlertEvent 封装classify账号AlertEvent业务协调。
|
||||
func classifyAccountAlertEvent(title, body string) string {
|
||||
// msg 保存msg,供当前处理流程使用
|
||||
// msg 用于本次流程后续判断的msg
|
||||
msg := strings.ToLower(title + " " + body)
|
||||
switch {
|
||||
case strings.Contains(msg, "风控"), strings.Contains(msg, "验证"),
|
||||
@@ -428,18 +432,18 @@ func classifyAccountAlertEvent(title, body string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// formatEvent 负责formatEvent相关处理。
|
||||
// formatEvent 封装formatEvent业务协调。
|
||||
func formatEvent(ev NotificationEvent) string {
|
||||
// b 保存b,供当前处理流程使用
|
||||
// b 用于本次流程后续判断的b
|
||||
var b strings.Builder
|
||||
// label 保存label,供当前处理流程使用
|
||||
// label 用于本次流程后续判断的label
|
||||
label := eventLabel(ev.Type)
|
||||
// level 保存level,供当前处理流程使用
|
||||
// level 用于本次流程后续判断的level
|
||||
level := levelLabel(ev.Level)
|
||||
if level == "" {
|
||||
level = "提示"
|
||||
}
|
||||
// title 保存标题,供当前处理流程使用
|
||||
// title 用于本次流程后续判断的标题
|
||||
title := strings.TrimSpace(ev.Title)
|
||||
if title == "" {
|
||||
title = label
|
||||
@@ -457,7 +461,7 @@ func formatEvent(ev NotificationEvent) string {
|
||||
b.WriteString("\n时间: ")
|
||||
b.WriteString(ev.Time.Format("2006-01-02 15:04:05"))
|
||||
if len(ev.Fields) > 0 {
|
||||
// keys 保存keys,供当前处理流程使用
|
||||
// keys 用于本次流程后续判断的keys
|
||||
keys := make([]string, 0, len(ev.Fields))
|
||||
// k 表示当前遍历过程中的k
|
||||
for k := range ev.Fields {
|
||||
@@ -466,7 +470,7 @@ func formatEvent(ev NotificationEvent) string {
|
||||
sortStrings(keys)
|
||||
// k 表示当前遍历过程中的k
|
||||
for _, k := range keys {
|
||||
// v 保存v,供当前处理流程使用
|
||||
// v 用于本次流程后续判断的v
|
||||
v := strings.TrimSpace(ev.Fields[k])
|
||||
if v == "" {
|
||||
continue
|
||||
@@ -477,7 +481,7 @@ func formatEvent(ev NotificationEvent) string {
|
||||
b.WriteString(v)
|
||||
}
|
||||
}
|
||||
// body 保存请求体,供当前处理流程使用
|
||||
// body 用于本次流程后续判断的请求体
|
||||
body := strings.TrimSpace(ev.Body)
|
||||
if body != "" {
|
||||
b.WriteString("\n\n")
|
||||
@@ -486,13 +490,13 @@ func formatEvent(ev NotificationEvent) string {
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// eventAllowed 负责eventAllowed相关处理。
|
||||
// eventAllowed 封装eventAllowed业务协调。
|
||||
func eventAllowed(raw, eventType string) (bool, error) {
|
||||
eventType = strings.TrimSpace(eventType)
|
||||
if eventType == "" {
|
||||
return true, nil
|
||||
}
|
||||
// events、err 保存events、err,供当前处理流程使用
|
||||
// events、err 用于本次流程后续判断的events、err
|
||||
events, err := parseEventTypes(raw)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -503,16 +507,16 @@ func eventAllowed(raw, eventType string) (bool, error) {
|
||||
return events[eventType], nil
|
||||
}
|
||||
|
||||
// parseEventTypes 负责parseEventTypes相关处理。
|
||||
// parseEventTypes 封装parseEventTypes业务协调。
|
||||
func parseEventTypes(raw string) (map[string]bool, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return nil, nil
|
||||
}
|
||||
// arr 保存arr,供当前处理流程使用
|
||||
// arr 用于本次流程后续判断的arr
|
||||
var arr []string
|
||||
if strings.HasPrefix(raw, "[") {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := json.Unmarshal([]byte(raw), &arr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -524,7 +528,7 @@ func parseEventTypes(raw string) (map[string]bool, error) {
|
||||
if len(arr) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
// out 保存out,供当前处理流程使用
|
||||
// out 用于本次流程后续判断的out
|
||||
out := make(map[string]bool, len(arr))
|
||||
// v 表示当前遍历过程中的v
|
||||
for _, v := range arr {
|
||||
@@ -536,20 +540,20 @@ func parseEventTypes(raw string) (map[string]bool, error) {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// sortStrings 负责sortStrings相关处理。
|
||||
// sortStrings 封装sortStrings业务协调。
|
||||
func sortStrings(values []string) {
|
||||
for // i 保存i,供当前处理流程使用
|
||||
for // i 用于本次流程后续判断的i
|
||||
i := 1; i < len(values); i++ {
|
||||
for // j 保存j,供当前处理流程使用
|
||||
for // j 用于本次流程后续判断的j
|
||||
j := i; j > 0 && values[j-1] > values[j]; j-- {
|
||||
values[j-1], values[j] = values[j], values[j-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// send 负责send相关处理。
|
||||
// send 封装send业务协调。
|
||||
func (n *Notifier) send(ch db.NotificationChannel, message string) error {
|
||||
// cfg 保存cfg,供当前处理流程使用
|
||||
// cfg 用于本次流程后续判断的cfg
|
||||
cfg := parseConfig(ch.Config)
|
||||
switch ch.Type {
|
||||
case "ding_talk", "dingtalk":
|
||||
@@ -579,9 +583,9 @@ func parseConfig(config string) map[string]any {
|
||||
if config == "" {
|
||||
return map[string]any{}
|
||||
}
|
||||
// m 保存m,供当前处理流程使用
|
||||
// m 用于本次流程后续判断的m
|
||||
var m map[string]any
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := json.Unmarshal([]byte(config), &m); err != nil {
|
||||
return map[string]any{"config": config}
|
||||
}
|
||||
@@ -590,36 +594,36 @@ func parseConfig(config string) map[string]any {
|
||||
|
||||
// ---- 钉钉 ----
|
||||
func (n *Notifier) sendDingTalk(cfg map[string]any, message string) error {
|
||||
// webhook 保存webhook,供当前处理流程使用
|
||||
// webhook 用于本次流程后续判断的webhook
|
||||
webhook := strOr(cfg, "webhook_url", strOr(cfg, "config", ""))
|
||||
// secret 保存secret,供当前处理流程使用
|
||||
// secret 用于本次流程后续判断的secret
|
||||
secret := strOr(cfg, "secret", "")
|
||||
if webhook == "" {
|
||||
return fmt.Errorf("钉钉 webhook_url 为空")
|
||||
}
|
||||
if secret != "" {
|
||||
// ts 保存ts,供当前处理流程使用
|
||||
// ts 用于本次流程后续判断的ts
|
||||
ts := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
||||
// stringToSign 保存stringToSign,供当前处理流程使用
|
||||
// stringToSign 用于本次流程后续判断的stringToSign
|
||||
stringToSign := ts + "\n" + secret
|
||||
// h 保存h,供当前处理流程使用
|
||||
// h 用于本次流程后续判断的h
|
||||
h := hmac.New(sha256.New, []byte(secret))
|
||||
h.Write([]byte(stringToSign))
|
||||
// sign 保存sign,供当前处理流程使用
|
||||
// sign 用于本次流程后续判断的sign
|
||||
sign := base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||
// parsed、err 保存parsed、err,供当前处理流程使用
|
||||
// parsed、err 用于本次流程后续判断的parsed、err
|
||||
parsed, err := url.Parse(webhook)
|
||||
if err != nil {
|
||||
return fmt.Errorf("钉钉 webhook 地址无效: %w", err)
|
||||
}
|
||||
// query 保存查询,供当前处理流程使用
|
||||
// query 用于本次流程后续判断的查询
|
||||
query := parsed.Query()
|
||||
query.Set("timestamp", ts)
|
||||
query.Set("sign", sign)
|
||||
parsed.RawQuery = query.Encode()
|
||||
webhook = parsed.String()
|
||||
}
|
||||
// payload 保存请求载荷,供当前处理流程使用
|
||||
// payload 用于本次流程后续判断的请求载荷
|
||||
payload := map[string]any{
|
||||
"msgtype": "markdown",
|
||||
"markdown": map[string]any{
|
||||
@@ -632,25 +636,25 @@ func (n *Notifier) sendDingTalk(cfg map[string]any, message string) error {
|
||||
|
||||
// ---- 飞书 ----
|
||||
func (n *Notifier) sendFeishu(cfg map[string]any, message string) error {
|
||||
// webhook 保存webhook,供当前处理流程使用
|
||||
// webhook 用于本次流程后续判断的webhook
|
||||
webhook := strOr(cfg, "webhook_url", "")
|
||||
// secret 保存secret,供当前处理流程使用
|
||||
// secret 用于本次流程后续判断的secret
|
||||
secret := strOr(cfg, "secret", "")
|
||||
if webhook == "" {
|
||||
return fmt.Errorf("飞书 webhook_url 为空")
|
||||
}
|
||||
// ts 保存ts,供当前处理流程使用
|
||||
// ts 用于本次流程后续判断的ts
|
||||
ts := strconv.FormatInt(time.Now().Unix(), 10)
|
||||
// data 保存数据,供当前处理流程使用
|
||||
// data 用于本次流程后续判断的数据
|
||||
data := map[string]any{
|
||||
"msg_type": "text",
|
||||
"content": map[string]any{"text": message},
|
||||
"timestamp": ts,
|
||||
}
|
||||
if secret != "" {
|
||||
// stringToSign 保存stringToSign,供当前处理流程使用
|
||||
// stringToSign 用于本次流程后续判断的stringToSign
|
||||
stringToSign := ts + "\n" + secret
|
||||
// h 保存h,供当前处理流程使用
|
||||
// h 用于本次流程后续判断的h
|
||||
h := hmac.New(sha256.New, []byte(stringToSign))
|
||||
h.Write([]byte(""))
|
||||
data["sign"] = base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||
@@ -659,16 +663,16 @@ func (n *Notifier) sendFeishu(cfg map[string]any, message string) error {
|
||||
}
|
||||
|
||||
// ---- Bark ----
|
||||
// sendBark 负责sendBark相关处理。
|
||||
// sendBark 封装sendBark业务协调。
|
||||
func (n *Notifier) sendBark(cfg map[string]any, message string) error {
|
||||
// server 保存server,供当前处理流程使用
|
||||
// server 用于本次流程后续判断的server
|
||||
server := strings.TrimRight(strOr(cfg, "server_url", "https://api.day.app"), "/")
|
||||
// deviceKey 保存deviceKey,供当前处理流程使用
|
||||
// deviceKey 用于本次流程后续判断的deviceKey
|
||||
deviceKey := strOr(cfg, "device_key", "")
|
||||
if deviceKey == "" {
|
||||
return fmt.Errorf("bark device_key 为空")
|
||||
}
|
||||
// data 保存数据,供当前处理流程使用
|
||||
// data 用于本次流程后续判断的数据
|
||||
data := map[string]any{
|
||||
"device_key": deviceKey,
|
||||
"title": strOr(cfg, "title", "闲鱼自动回复通知"),
|
||||
@@ -676,11 +680,11 @@ func (n *Notifier) sendBark(cfg map[string]any, message string) error {
|
||||
"sound": strOr(cfg, "sound", "default"),
|
||||
"group": strOr(cfg, "group", "xianyu"),
|
||||
}
|
||||
if // icon 保存icon,供当前处理流程使用
|
||||
if // icon 用于本次流程后续判断的icon
|
||||
icon := strOr(cfg, "icon", ""); icon != "" {
|
||||
data["icon"] = icon
|
||||
}
|
||||
if // u 保存u,供当前处理流程使用
|
||||
if // u 用于本次流程后续判断的u
|
||||
u := strOr(cfg, "url", ""); u != "" {
|
||||
data["url"] = u
|
||||
}
|
||||
@@ -688,30 +692,30 @@ func (n *Notifier) sendBark(cfg map[string]any, message string) error {
|
||||
}
|
||||
|
||||
// ---- Webhook ----
|
||||
// sendWebhook 负责sendWebhook相关处理。
|
||||
// sendWebhook 封装sendWebhook业务协调。
|
||||
func (n *Notifier) sendWebhook(cfg map[string]any, message string) error {
|
||||
// webhook 保存webhook,供当前处理流程使用
|
||||
// webhook 用于本次流程后续判断的webhook
|
||||
webhook := strOr(cfg, "webhook_url", "")
|
||||
if webhook == "" {
|
||||
return fmt.Errorf("webhook_url 为空")
|
||||
}
|
||||
// method 保存方法,供当前处理流程使用
|
||||
// method 用于本次流程后续判断的方法
|
||||
method := strings.ToUpper(strOr(cfg, "http_method", "POST"))
|
||||
// headers 保存headers,供当前处理流程使用
|
||||
// headers 用于本次流程后续判断的headers
|
||||
headers := map[string]any{}
|
||||
if // h 保存h,供当前处理流程使用
|
||||
if // h 用于本次流程后续判断的h
|
||||
h := strOr(cfg, "headers", ""); h != "" {
|
||||
_ = json.Unmarshal([]byte(h), &headers)
|
||||
}
|
||||
// data 保存数据,供当前处理流程使用
|
||||
// data 用于本次流程后续判断的数据
|
||||
data := map[string]any{
|
||||
"message": message,
|
||||
"timestamp": time.Now().Format("2006-01-02 15:04:05"),
|
||||
"source": "xianyu-auto-reply",
|
||||
}
|
||||
// body 保存请求体,供当前处理流程使用
|
||||
// body 用于本次流程后续判断的请求体
|
||||
body, _ := json.Marshal(data)
|
||||
// req、err 保存req、err,供当前处理流程使用
|
||||
// req、err 用于本次流程后续判断的req、err
|
||||
req, err := http.NewRequest(method, webhook, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -721,13 +725,13 @@ func (n *Notifier) sendWebhook(cfg map[string]any, message string) error {
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, fmt.Sprintf("%v", v))
|
||||
}
|
||||
// resp、err 保存resp、err,供当前处理流程使用
|
||||
// resp、err 用于本次流程后续判断的resp、err
|
||||
resp, err := n.httpc.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -739,7 +743,7 @@ func (n *Notifier) sendWebhook(cfg map[string]any, message string) error {
|
||||
|
||||
// ---- 企业微信 ----
|
||||
func (n *Notifier) sendWeChat(cfg map[string]any, message string) error {
|
||||
// webhook 保存webhook,供当前处理流程使用
|
||||
// webhook 用于本次流程后续判断的webhook
|
||||
webhook := strOr(cfg, "webhook_url", "")
|
||||
if webhook == "" {
|
||||
return fmt.Errorf("微信 webhook_url 为空")
|
||||
@@ -751,16 +755,16 @@ func (n *Notifier) sendWeChat(cfg map[string]any, message string) error {
|
||||
}
|
||||
|
||||
// ---- Telegram ----
|
||||
// sendTelegram 负责sendTelegram相关处理。
|
||||
// sendTelegram 封装sendTelegram业务协调。
|
||||
func (n *Notifier) sendTelegram(cfg map[string]any, message string) error {
|
||||
// botToken 保存bot令牌,供当前处理流程使用
|
||||
// botToken 用于本次流程后续判断的bot令牌
|
||||
botToken := strOr(cfg, "bot_token", "")
|
||||
// chatID 保存聊天ID,供当前处理流程使用
|
||||
// chatID 用于本次流程后续判断的聊天ID
|
||||
chatID := strOr(cfg, "chat_id", "")
|
||||
if botToken == "" || chatID == "" {
|
||||
return fmt.Errorf("telegram bot_token/chat_id 不完整")
|
||||
}
|
||||
// endpoint 保存endpoint,供当前处理流程使用
|
||||
// endpoint 用于本次流程后续判断的endpoint
|
||||
endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken)
|
||||
return n.postJSON(endpoint, map[string]any{
|
||||
"chat_id": chatID,
|
||||
@@ -770,34 +774,34 @@ func (n *Notifier) sendTelegram(cfg map[string]any, message string) error {
|
||||
|
||||
// ---- 邮件 ----
|
||||
func (n *Notifier) sendEmail(cfg map[string]any, message string) error {
|
||||
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
|
||||
// ctx、cancel 用于本次流程后续判断的ctx、cancel
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
// server 保存server,供当前处理流程使用
|
||||
// server 用于本次流程后续判断的server
|
||||
server := n.smtpConfigValue(ctx, cfg, "smtp_server", "")
|
||||
// port 保存port,供当前处理流程使用
|
||||
// port 用于本次流程后续判断的port
|
||||
port := n.smtpConfigValue(ctx, cfg, "smtp_port", "587")
|
||||
// user 保存用户,供当前处理流程使用
|
||||
// user 用于本次流程后续判断的用户
|
||||
user := n.smtpConfigValue(ctx, cfg, "smtp_user", "")
|
||||
// pass 保存pass,供当前处理流程使用
|
||||
// pass 用于本次流程后续判断的pass
|
||||
pass := n.smtpConfigValue(ctx, cfg, "smtp_password", "")
|
||||
// useTLS 保存useTLS,供当前处理流程使用
|
||||
// useTLS 用于本次流程后续判断的useTLS
|
||||
useTLS := parseConfigBool(n.smtpConfigValue(ctx, cfg, "smtp_use_tls", "true"), true)
|
||||
// useSSL 保存useSSL,供当前处理流程使用
|
||||
// useSSL 用于本次流程后续判断的useSSL
|
||||
useSSL := parseConfigBool(n.smtpConfigValue(ctx, cfg, "smtp_use_ssl", "false"), false)
|
||||
// fromAddress 保存fromAddress,供当前处理流程使用
|
||||
// fromAddress 用于本次流程后续判断的fromAddress
|
||||
fromAddress := n.smtpConfigValue(ctx, cfg, "smtp_from_address", "")
|
||||
// fromName 保存from名称,供当前处理流程使用
|
||||
// fromName 用于本次流程后续判断的from名称
|
||||
fromName := n.smtpConfigValue(ctx, cfg, "smtp_from_name", "")
|
||||
// legacyFrom 保存legacyFrom,供当前处理流程使用
|
||||
// legacyFrom 用于本次流程后续判断的legacyFrom
|
||||
legacyFrom := n.smtpConfigValue(ctx, cfg, "smtp_from", "")
|
||||
// to 保存to,供当前处理流程使用
|
||||
// to 用于本次流程后续判断的to
|
||||
to := strOr(cfg, "to_email", strOr(cfg, "email", ""))
|
||||
if server == "" || user == "" || to == "" {
|
||||
return fmt.Errorf("邮件配置不完整:请配置系统 SMTP 或在邮件渠道中覆盖 SMTP,并填写收件邮箱")
|
||||
}
|
||||
if legacyFrom != "" {
|
||||
if // parsed、err 保存parsed、err,供当前处理流程使用
|
||||
if // parsed、err 用于本次流程后续判断的parsed、err
|
||||
parsed, err := mail.ParseAddress(legacyFrom); err == nil && strings.Contains(parsed.Address, "@") {
|
||||
if fromAddress == "" {
|
||||
fromAddress = parsed.Address
|
||||
@@ -812,32 +816,32 @@ func (n *Notifier) sendEmail(cfg map[string]any, message string) error {
|
||||
if fromAddress == "" {
|
||||
fromAddress = user
|
||||
}
|
||||
// from、err 保存from、err,供当前处理流程使用
|
||||
// from、err 用于本次流程后续判断的from、err
|
||||
from, err := mail.ParseAddress(fromAddress)
|
||||
if err != nil || !strings.Contains(from.Address, "@") {
|
||||
return fmt.Errorf("发件邮箱地址无效")
|
||||
}
|
||||
// recipient、err 保存recipient、err,供当前处理流程使用
|
||||
// recipient、err 用于本次流程后续判断的recipient、err
|
||||
recipient, err := mail.ParseAddress(to)
|
||||
if err != nil || !strings.Contains(recipient.Address, "@") {
|
||||
return fmt.Errorf("收件邮箱地址无效")
|
||||
}
|
||||
from.Name = fromName
|
||||
// fromHeader 保存fromHeader,供当前处理流程使用
|
||||
// fromHeader 用于本次流程后续判断的fromHeader
|
||||
fromHeader := from.Address
|
||||
if from.Name != "" {
|
||||
fromHeader = from.String()
|
||||
}
|
||||
// toHeader 保存toHeader,供当前处理流程使用
|
||||
// toHeader 用于本次流程后续判断的toHeader
|
||||
toHeader := recipient.Address
|
||||
if recipient.Name != "" {
|
||||
toHeader = recipient.String()
|
||||
}
|
||||
// addr 保存addr,供当前处理流程使用
|
||||
// addr 用于本次流程后续判断的addr
|
||||
addr := server + ":" + port
|
||||
// auth 保存auth,供当前处理流程使用
|
||||
// auth 用于本次流程后续判断的auth
|
||||
auth := smtp.PlainAuth("", user, pass, server)
|
||||
// msg 保存msg,供当前处理流程使用
|
||||
// msg 用于本次流程后续判断的msg
|
||||
msg := strings.Join([]string{
|
||||
"From: " + fromHeader,
|
||||
"To: " + toHeader,
|
||||
@@ -853,93 +857,93 @@ func (n *Notifier) sendEmail(cfg map[string]any, message string) error {
|
||||
})
|
||||
}
|
||||
|
||||
// smtpTransportOptions 保存smtpTransportOptions,供当前处理流程使用
|
||||
// smtpTransportOptions 用于本次流程后续判断的smtpTransportOptions
|
||||
type smtpTransportOptions struct {
|
||||
UseSTARTTLS bool
|
||||
UseImplicitTLS bool
|
||||
}
|
||||
|
||||
// sendPublicSMTP 负责sendPublicSMTP相关处理。
|
||||
// sendPublicSMTP 封装sendPublicSMTP业务协调。
|
||||
func sendPublicSMTP(ctx context.Context, addr, server string, auth smtp.Auth, from, to string, message []byte, options ...smtpTransportOptions) error {
|
||||
// rawPort、err 保存原始Port、err,供当前处理流程使用
|
||||
// rawPort、err 用于本次流程后续判断的原始Port、err
|
||||
_, rawPort, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("SMTP 地址无效")
|
||||
}
|
||||
// port、err 保存port、err,供当前处理流程使用
|
||||
// port、err 用于本次流程后续判断的port、err
|
||||
port, err := strconv.Atoi(strings.TrimSpace(rawPort))
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
return fmt.Errorf("SMTP 端口无效")
|
||||
}
|
||||
// conn、err 保存conn、err,供当前处理流程使用
|
||||
// conn、err 用于本次流程后续判断的conn、err
|
||||
conn, err := dialPublicSMTP(ctx, "tcp", addr, 10*time.Second)
|
||||
if err != nil {
|
||||
return fmt.Errorf("连接 SMTP 服务器失败: %w", err)
|
||||
}
|
||||
defer func() { _ = conn.Close() }()
|
||||
_ = conn.SetDeadline(time.Now().Add(20 * time.Second))
|
||||
// transport 保存transport,供当前处理流程使用
|
||||
// transport 用于本次流程后续判断的transport
|
||||
transport := smtpTransportOptions{UseSTARTTLS: true}
|
||||
if len(options) > 0 {
|
||||
transport = options[0]
|
||||
}
|
||||
if transport.UseImplicitTLS {
|
||||
// tlsConn 保存tlsConn,供当前处理流程使用
|
||||
// tlsConn 用于本次流程后续判断的tlsConn
|
||||
tlsConn := tls.Client(conn, &tls.Config{MinVersion: tls.VersionTLS12, ServerName: server})
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := tlsConn.HandshakeContext(ctx); err != nil {
|
||||
return fmt.Errorf("SMTP SSL 握手失败: %w", err)
|
||||
}
|
||||
conn = tlsConn
|
||||
}
|
||||
// client、err 保存client、err,供当前处理流程使用
|
||||
// client、err 用于本次流程后续判断的client、err
|
||||
client, err := smtp.NewClient(conn, server)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = client.Close() }()
|
||||
if transport.UseSTARTTLS {
|
||||
if // ok 保存ok,供当前处理流程使用
|
||||
if // ok 用于本次流程后续判断的ok
|
||||
ok, _ := client.Extension("STARTTLS"); !ok {
|
||||
return fmt.Errorf("SMTP 服务器不支持要求的 STARTTLS")
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := client.StartTLS(&tls.Config{MinVersion: tls.VersionTLS12, ServerName: server}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if auth != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := client.Auth(auth); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := client.Mail(from); err != nil {
|
||||
return err
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := client.Rcpt(to); err != nil {
|
||||
return err
|
||||
}
|
||||
// w、err 保存w、err,供当前处理流程使用
|
||||
// w、err 用于本次流程后续判断的w、err
|
||||
w, err := client.Data()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := w.Write(message); err != nil {
|
||||
_ = w.Close()
|
||||
return err
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := w.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Quit()
|
||||
}
|
||||
|
||||
// parseConfigBool 负责parse配置Bool相关处理。
|
||||
// parseConfigBool 封装parse配置Bool业务协调。
|
||||
func parseConfigBool(raw string, fallback bool) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(raw)) {
|
||||
case "1", "true", "yes", "on":
|
||||
@@ -951,14 +955,14 @@ func parseConfigBool(raw string, fallback bool) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// configOrSetting 负责配置Or设置相关处理。
|
||||
// configOrSetting 封装配置Or设置业务协调。
|
||||
func (n *Notifier) configOrSetting(ctx context.Context, cfg map[string]any, key, fallbackValue string) string {
|
||||
if // v 保存v,供当前处理流程使用
|
||||
if // v 用于本次流程后续判断的v
|
||||
v := strings.TrimSpace(strOr(cfg, key, "")); v != "" {
|
||||
return v
|
||||
}
|
||||
if n.repository != nil {
|
||||
if // v、err 保存v、err,供当前处理流程使用
|
||||
if // v、err 用于本次流程后续判断的v、err
|
||||
v, err := n.repository.GetSetting(ctx, key); err == nil && strings.TrimSpace(v) != "" {
|
||||
return strings.TrimSpace(v)
|
||||
}
|
||||
@@ -968,22 +972,22 @@ func (n *Notifier) configOrSetting(ctx context.Context, cfg map[string]any, key,
|
||||
|
||||
// smtpConfigValue keeps legacy per-field fallback behavior for existing rows,
|
||||
// while new rows use an explicit all-system or all-channel SMTP mode.
|
||||
// smtpConfigValue 负责smtp配置值相关处理。
|
||||
// smtpConfigValue 封装smtp配置值业务协调。
|
||||
func (n *Notifier) smtpConfigValue(ctx context.Context, cfg map[string]any, key, fallbackValue string) string {
|
||||
// modeValue、hasExplicitMode 保存模式Value、hasExplicit模式,供当前处理流程使用
|
||||
// modeValue、hasExplicitMode 用于本次流程后续判断的模式Value、hasExplicit模式
|
||||
modeValue, hasExplicitMode := cfg["use_custom_smtp"]
|
||||
if !hasExplicitMode {
|
||||
return n.configOrSetting(ctx, cfg, key, fallbackValue)
|
||||
}
|
||||
if parseConfigBool(fmt.Sprintf("%v", modeValue), false) {
|
||||
if // value 保存值,供当前处理流程使用
|
||||
if // value 用于本次流程后续判断的值
|
||||
value := strings.TrimSpace(strOr(cfg, key, "")); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallbackValue
|
||||
}
|
||||
if n.repository != nil {
|
||||
if // value、err 保存value、err,供当前处理流程使用
|
||||
if // value、err 用于本次流程后续判断的value、err
|
||||
value, err := n.repository.GetSetting(ctx, key); err == nil && strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
@@ -993,24 +997,24 @@ func (n *Notifier) smtpConfigValue(ctx context.Context, cfg map[string]any, key,
|
||||
|
||||
// postJSON 通用 JSON POST。
|
||||
func (n *Notifier) postJSON(url string, payload any) error {
|
||||
// body、err 保存body、err,供当前处理流程使用
|
||||
// body、err 用于本次流程后续判断的body、err
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// req、err 保存req、err,供当前处理流程使用
|
||||
// req、err 用于本次流程后续判断的req、err
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
// resp、err 保存resp、err,供当前处理流程使用
|
||||
// resp、err 用于本次流程后续判断的resp、err
|
||||
resp, err := n.httpc.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// responseBody、err 保存响应Body、err,供当前处理流程使用
|
||||
// responseBody、err 用于本次流程后续判断的响应Body、err
|
||||
responseBody, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -1018,57 +1022,57 @@ func (n *Notifier) postJSON(url string, payload any) error {
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("状态码 %d", resp.StatusCode)
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := notificationBusinessError(responseBody); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// notificationBusinessError 负责通知Business错误相关处理。
|
||||
// notificationBusinessError 封装通知Business错误业务协调。
|
||||
func notificationBusinessError(body []byte) error {
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return nil
|
||||
}
|
||||
// payload 保存请求载荷,供当前处理流程使用
|
||||
// payload 用于本次流程后续判断的请求载荷
|
||||
var payload map[string]any
|
||||
if json.Unmarshal(body, &payload) != nil {
|
||||
return nil
|
||||
}
|
||||
// message 保存消息,供当前处理流程使用
|
||||
// message 用于本次流程后续判断的消息
|
||||
message := strings.TrimSpace(firstMapString(payload, "errmsg", "msg", "message", "description"))
|
||||
if // code、ok 保存code、ok,供当前处理流程使用
|
||||
if // code、ok 用于本次流程后续判断的code、ok
|
||||
code, ok := mapNumber(payload, "errcode"); ok && code != 0 {
|
||||
return fmt.Errorf("通知渠道返回错误 %.0f: %s", code, message)
|
||||
}
|
||||
if // code、ok 保存code、ok,供当前处理流程使用
|
||||
if // code、ok 用于本次流程后续判断的code、ok
|
||||
code, ok := mapNumber(payload, "StatusCode"); ok && code != 0 {
|
||||
return fmt.Errorf("通知渠道返回错误 %.0f: %s", code, message)
|
||||
}
|
||||
if // code、ok 保存code、ok,供当前处理流程使用
|
||||
if // code、ok 用于本次流程后续判断的code、ok
|
||||
code, ok := mapNumber(payload, "code"); ok && code != 0 && code != 200 {
|
||||
return fmt.Errorf("通知渠道返回错误 %.0f: %s", code, message)
|
||||
}
|
||||
if // okValue、exists 保存okValue、exists,供当前处理流程使用
|
||||
if // okValue、exists 用于本次流程后续判断的okValue、exists
|
||||
okValue, exists := payload["ok"].(bool); exists && !okValue {
|
||||
return fmt.Errorf("通知渠道返回失败: %s", message)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mapNumber 负责mapNumber相关处理。
|
||||
// mapNumber 封装mapNumber业务协调。
|
||||
func mapNumber(payload map[string]any, key string) (float64, bool) {
|
||||
// value、ok 保存value、ok,供当前处理流程使用
|
||||
// value、ok 用于本次流程后续判断的value、ok
|
||||
value, ok := payload[key]
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
switch // typed 保存typed,供当前处理流程使用
|
||||
switch // typed 用于本次流程后续判断的typed
|
||||
typed := value.(type) {
|
||||
case float64:
|
||||
return typed, true
|
||||
case string:
|
||||
// number、err 保存number、err,供当前处理流程使用
|
||||
// number、err 用于本次流程后续判断的number、err
|
||||
number, err := strconv.ParseFloat(typed, 64)
|
||||
return number, err == nil
|
||||
default:
|
||||
@@ -1076,11 +1080,11 @@ func mapNumber(payload map[string]any, key string) (float64, bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// firstMapString 负责firstMapString相关处理。
|
||||
// firstMapString 封装firstMapString业务协调。
|
||||
func firstMapString(payload map[string]any, keys ...string) string {
|
||||
// key 表示当前遍历过程中的key
|
||||
for _, key := range keys {
|
||||
if // value、ok 保存value、ok,供当前处理流程使用
|
||||
if // value、ok 用于本次流程后续判断的value、ok
|
||||
value, ok := payload[key].(string); ok && value != "" {
|
||||
return value
|
||||
}
|
||||
@@ -1090,9 +1094,9 @@ func firstMapString(payload map[string]any, keys ...string) string {
|
||||
|
||||
// strOr 从 map 取字符串,缺失返回 fallback。
|
||||
func strOr(m map[string]any, key, fallback string) string {
|
||||
if // v、ok 保存v、ok,供当前处理流程使用
|
||||
if // v、ok 用于本次流程后续判断的v、ok
|
||||
v, ok := m[key]; ok {
|
||||
switch // x 保存x,供当前处理流程使用
|
||||
switch // x 用于本次流程后续判断的x
|
||||
x := v.(type) {
|
||||
case string:
|
||||
return x
|
||||
@@ -1103,7 +1107,7 @@ func strOr(m map[string]any, key, fallback string) string {
|
||||
return fallback
|
||||
}
|
||||
|
||||
// fallback 负责fallback相关处理。
|
||||
// fallback 封装fallback业务协调。
|
||||
func fallback(s, def string) string {
|
||||
if s == "" {
|
||||
return def
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -86,18 +86,18 @@ func nilLogger() *slog.Logger {
|
||||
|
||||
// newNotifyStoreBare 提供一个独立 store,方便各测试用例自由构造数据。
|
||||
// 预置一个 admin 用户和一个 cookie_id="cid" 的 cookie 记录以满足外键约束。
|
||||
// newNotifyStoreBare 负责newNotifyStoreBare相关处理。
|
||||
// newNotifyStoreBare 封装newNotifyStoreBare业务协调。
|
||||
func newNotifyStoreBare(t *testing.T) (*db.Store, func()) {
|
||||
t.Helper()
|
||||
// d、err 保存d、err,供当前处理流程使用
|
||||
// d、err 用于本次流程后续判断的d、err
|
||||
d, _, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "test.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
// s 保存s,供当前处理流程使用
|
||||
// s 用于本次流程后续判断的s
|
||||
s := db.NewStore(d, db.DialectSQLite)
|
||||
s.Users.Create(context.Background(), "admin", "[email protected]", "pw")
|
||||
// admin 保存admin,供当前处理流程使用
|
||||
// admin 用于本次流程后续判断的admin
|
||||
admin, _ := s.Users.GetByUsername(context.Background(), "admin")
|
||||
s.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID)
|
||||
return s, func() { _ = d.Close() }
|
||||
@@ -106,16 +106,16 @@ func newNotifyStoreBare(t *testing.T) (*db.Store, func()) {
|
||||
// addWebhookChannel 插入一个 webhook 渠道并绑定到 cookieID,返回渠道 ID。
|
||||
func addWebhookChannel(t *testing.T, s *db.Store, cookieID, name, webhookURL string) int64 {
|
||||
t.Helper()
|
||||
// res、err 保存res、err,供当前处理流程使用
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := s.DB.ExecContext(context.Background(),
|
||||
`INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES (?,?,?,1,1)`,
|
||||
name, "webhook", `{"webhook_url":"`+webhookURL+`"}`)
|
||||
if err != nil {
|
||||
t.Fatalf("insert channel: %v", err)
|
||||
}
|
||||
// id 保存标识,供当前处理流程使用
|
||||
// id 用于本次流程后续判断的标识
|
||||
id, _ := res.LastInsertId()
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := s.DB.ExecContext(context.Background(),
|
||||
`INSERT INTO message_notifications (cookie_id,channel_id,enabled) VALUES (?,?,1)`,
|
||||
cookieID, id); err != nil {
|
||||
@@ -126,7 +126,7 @@ func addWebhookChannel(t *testing.T, s *db.Store, cookieID, name, webhookURL str
|
||||
|
||||
// TestNotifyAccountAlert_NoStore store 为 nil 时安全返回。
|
||||
func TestNotifyAccountAlert_NoStore(t *testing.T) {
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := &Notifier{logger: nilLogger()}
|
||||
// 不应 panic。
|
||||
n.NotifyAccountAlert("cid", "warn", "标题", "正文")
|
||||
@@ -134,25 +134,25 @@ func TestNotifyAccountAlert_NoStore(t *testing.T) {
|
||||
|
||||
// TestNotifyAccountAlert_NoChannels 无绑定渠道时不报错。
|
||||
func TestNotifyAccountAlert_NoChannels(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStoreBare(t)
|
||||
defer cleanup()
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
n.NotifyAccountAlert("cid", "warn", "标题", "正文")
|
||||
}
|
||||
|
||||
// TestNotifyAccountAlert_WithChannel 告警通知发送并包含标题与正文。
|
||||
func TestNotifyAccountAlert_WithChannel(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStoreBare(t)
|
||||
defer cleanup()
|
||||
|
||||
// gotBody 保存got请求体,供当前处理流程使用
|
||||
// gotBody 用于本次流程后续判断的got请求体
|
||||
var gotBody string
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
// srv 用于本次流程后续判断的srv
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// b 保存b,供当前处理流程使用
|
||||
// b 用于本次流程后续判断的b
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
gotBody = string(b)
|
||||
w.WriteHeader(200)
|
||||
@@ -160,7 +160,7 @@ func TestNotifyAccountAlert_WithChannel(t *testing.T) {
|
||||
defer srv.Close()
|
||||
|
||||
addWebhookChannel(t, s, "cid", "告警渠道", srv.URL)
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
n.NotifyAccountAlert("cid", "critical", "Token失效", "请重新登录")
|
||||
|
||||
@@ -172,41 +172,41 @@ func TestNotifyAccountAlert_WithChannel(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotifyEventUsesPersistentOutboxWhenStarted 负责TestNotifyEventUsesPersistentOutboxWhenStarted相关处理。
|
||||
// TestNotifyEventUsesPersistentOutboxWhenStarted 封装TestNotifyEventUsesPersistentOutboxWhenStarted业务协调。
|
||||
func TestNotifyEventUsesPersistentOutboxWhenStarted(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStoreBare(t)
|
||||
defer cleanup()
|
||||
// calls 保存calls,供当前处理流程使用
|
||||
// calls 用于本次流程后续判断的calls
|
||||
var calls int32
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
// srv 用于本次流程后续判断的srv
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
atomic.AddInt32(&calls, 1)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
addWebhookChannel(t, s, "cid", "outbox", srv.URL)
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nilLogger())
|
||||
// 标记异步模式但不启动循环,精确验证调用返回时尚未发生外部网络请求。
|
||||
n.started.Store(true)
|
||||
n.NotifyAccountAlert("cid", "warn", "持久化通知", "正文")
|
||||
if // got 保存got,供当前处理流程使用
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := atomic.LoadInt32(&calls); got != 0 {
|
||||
t.Fatalf("business call performed synchronous network I/O: %d", got)
|
||||
}
|
||||
// queued 保存queued,供当前处理流程使用
|
||||
// queued 用于本次流程后续判断的queued
|
||||
var queued int
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := s.DB.QueryRow(`SELECT COUNT(*) FROM notification_outbox WHERE status='pending'`).Scan(&queued); err != nil || queued != 1 {
|
||||
t.Fatalf("queued=%d err=%v", queued, err)
|
||||
}
|
||||
n.drainOutbox(context.Background())
|
||||
if // got 保存got,供当前处理流程使用
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := atomic.LoadInt32(&calls); got != 1 {
|
||||
t.Fatalf("outbox delivery calls=%d", got)
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := s.DB.QueryRow(`SELECT COUNT(*) FROM notification_outbox`).Scan(&queued); err != nil || queued != 0 {
|
||||
t.Fatalf("remaining=%d err=%v", queued, err)
|
||||
}
|
||||
@@ -248,7 +248,7 @@ func TestDrainOutbox_SendSuccessCompletionFailureQuarantines(t *testing.T) {
|
||||
|
||||
// TestNotifyAccountAlert_LevelLabels 覆盖 levelLabel 各分支。
|
||||
func TestNotifyAccountAlert_LevelLabels(t *testing.T) {
|
||||
// cases 保存cases,供当前处理流程使用
|
||||
// cases 用于本次流程后续判断的cases
|
||||
cases := map[string]string{
|
||||
"critical": "严重",
|
||||
"warn": "警告",
|
||||
@@ -257,7 +257,7 @@ func TestNotifyAccountAlert_LevelLabels(t *testing.T) {
|
||||
}
|
||||
// level、want 表示当前遍历过程中的level、want
|
||||
for level, want := range cases {
|
||||
if // got 保存got,供当前处理流程使用
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := levelLabel(level); got != want {
|
||||
t.Errorf("levelLabel(%q)=%q want %q", level, got, want)
|
||||
}
|
||||
@@ -266,26 +266,26 @@ func TestNotifyAccountAlert_LevelLabels(t *testing.T) {
|
||||
|
||||
// TestSendToChannel 直接发送到指定渠道。
|
||||
func TestSendToChannel(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStoreBare(t)
|
||||
defer cleanup()
|
||||
|
||||
// gotBody 保存got请求体,供当前处理流程使用
|
||||
// gotBody 用于本次流程后续判断的got请求体
|
||||
var gotBody string
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
// srv 用于本次流程后续判断的srv
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// b 保存b,供当前处理流程使用
|
||||
// b 用于本次流程后续判断的b
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
gotBody = string(b)
|
||||
w.WriteHeader(200)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
// chID 保存chID,供当前处理流程使用
|
||||
// chID 用于本次流程后续判断的chID
|
||||
chID := addWebhookChannel(t, s, "cid", "直发渠道", srv.URL)
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := n.SendToChannel(chID, "直发测试"); err != nil {
|
||||
t.Fatalf("SendToChannel: %v", err)
|
||||
}
|
||||
@@ -298,15 +298,15 @@ func TestSendToChannel(t *testing.T) {
|
||||
func TestSendToChannel_Errors(t *testing.T) {
|
||||
// store 为 nil。
|
||||
n := &Notifier{logger: nilLogger()}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := n.SendToChannel(1, "x"); err == nil {
|
||||
t.Fatal("store 为 nil 应报错")
|
||||
}
|
||||
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStoreBare(t)
|
||||
defer cleanup()
|
||||
// n2 保存n2,供当前处理流程使用
|
||||
// n2 用于本次流程后续判断的n2
|
||||
n2 := New("cid", s, nil)
|
||||
// 不存在的渠道 ID。
|
||||
if err := n2.SendToChannel(99999, "x"); err == nil {
|
||||
@@ -316,11 +316,11 @@ func TestSendToChannel_Errors(t *testing.T) {
|
||||
|
||||
// TestNotifyDelivery_MultiChannel 某渠道失败不影响其他渠道。
|
||||
func TestNotifyDelivery_MultiChannel(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStoreBare(t)
|
||||
defer cleanup()
|
||||
|
||||
// okCount 保存ok数量,供当前处理流程使用
|
||||
// okCount 用于本次流程后续判断的ok数量
|
||||
var okCount int32
|
||||
// 成功渠道。
|
||||
okSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -339,10 +339,10 @@ func TestNotifyDelivery_MultiChannel(t *testing.T) {
|
||||
addWebhookChannel(t, s, "cid", "成功渠道", okSrv.URL)
|
||||
addWebhookChannel(t, s, "cid", "失败渠道", failSrv.URL)
|
||||
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
n.NotifyDelivery("cid", "买家", "b1", "item1", "成功", "chat1")
|
||||
if // got 保存got,供当前处理流程使用
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := atomic.LoadInt32(&okCount); got != 1 {
|
||||
t.Errorf("成功渠道应收到 1 次,实际 %d", got)
|
||||
}
|
||||
@@ -350,15 +350,15 @@ func TestNotifyDelivery_MultiChannel(t *testing.T) {
|
||||
|
||||
// TestNotifyDelivery_TemplateVars 通知正文应包含买家名、商品ID、结果等变量。
|
||||
func TestNotifyDelivery_TemplateVars(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStoreBare(t)
|
||||
defer cleanup()
|
||||
|
||||
// gotBody 保存got请求体,供当前处理流程使用
|
||||
// gotBody 用于本次流程后续判断的got请求体
|
||||
var gotBody string
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
// srv 用于本次流程后续判断的srv
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// b 保存b,供当前处理流程使用
|
||||
// b 用于本次流程后续判断的b
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
gotBody = string(b)
|
||||
w.WriteHeader(200)
|
||||
@@ -366,7 +366,7 @@ func TestNotifyDelivery_TemplateVars(t *testing.T) {
|
||||
defer srv.Close()
|
||||
|
||||
addWebhookChannel(t, s, "cid", "模板渠道", srv.URL)
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
n.NotifyDelivery("cid", "张三", "BID123", "ITEM456", "发货成功", "CHAT789")
|
||||
|
||||
@@ -380,15 +380,15 @@ func TestNotifyDelivery_TemplateVars(t *testing.T) {
|
||||
|
||||
// TestNotifyDelivery_EmptyChatID chatID 为空时回退为“未知”。
|
||||
func TestNotifyDelivery_EmptyChatID(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStoreBare(t)
|
||||
defer cleanup()
|
||||
|
||||
// gotBody 保存got请求体,供当前处理流程使用
|
||||
// gotBody 用于本次流程后续判断的got请求体
|
||||
var gotBody string
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
// srv 用于本次流程后续判断的srv
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// b 保存b,供当前处理流程使用
|
||||
// b 用于本次流程后续判断的b
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
gotBody = string(b)
|
||||
w.WriteHeader(200)
|
||||
@@ -396,7 +396,7 @@ func TestNotifyDelivery_EmptyChatID(t *testing.T) {
|
||||
defer srv.Close()
|
||||
|
||||
addWebhookChannel(t, s, "cid", "渠道", srv.URL)
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
n.NotifyDelivery("cid", "买家", "b1", "item1", "结果", "")
|
||||
if !strings.Contains(gotBody, "未知") {
|
||||
@@ -447,7 +447,7 @@ func TestNotifyAutomationRunQueuesEachTerminalStateOnce(t *testing.T) {
|
||||
|
||||
// TestParseConfig_InvalidJSON 非法 JSON 走旧格式兼容分支。
|
||||
func TestParseConfig_InvalidJSON(t *testing.T) {
|
||||
// m 保存m,供当前处理流程使用
|
||||
// m 用于本次流程后续判断的m
|
||||
m := parseConfig("{not json")
|
||||
if m["config"] != "{not json" {
|
||||
t.Errorf("非法 JSON 应放入 config: %v", m)
|
||||
@@ -456,25 +456,25 @@ func TestParseConfig_InvalidJSON(t *testing.T) {
|
||||
|
||||
// TestStrOr 覆盖 string / 非 string / 缺失三个分支。
|
||||
func TestStrOr(t *testing.T) {
|
||||
// m 保存m,供当前处理流程使用
|
||||
// m 用于本次流程后续判断的m
|
||||
m := map[string]any{
|
||||
"s": "abc",
|
||||
"n": 42,
|
||||
"b": true,
|
||||
}
|
||||
if // got 保存got,供当前处理流程使用
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := strOr(m, "s", "x"); got != "abc" {
|
||||
t.Errorf("strOr(s)=%q", got)
|
||||
}
|
||||
if // got 保存got,供当前处理流程使用
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := strOr(m, "n", "x"); got != "42" {
|
||||
t.Errorf("strOr(n)=%q", got)
|
||||
}
|
||||
if // got 保存got,供当前处理流程使用
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := strOr(m, "b", "x"); got != "true" {
|
||||
t.Errorf("strOr(b)=%q", got)
|
||||
}
|
||||
if // got 保存got,供当前处理流程使用
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := strOr(m, "missing", "def"); got != "def" {
|
||||
t.Errorf("strOr(missing)=%q", got)
|
||||
}
|
||||
@@ -482,11 +482,11 @@ func TestStrOr(t *testing.T) {
|
||||
|
||||
// TestFallback fallback 空串与非空串。
|
||||
func TestFallback(t *testing.T) {
|
||||
if // got 保存got,供当前处理流程使用
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := fallback("", "默认"); got != "默认" {
|
||||
t.Errorf("fallback('')=%q", got)
|
||||
}
|
||||
if // got 保存got,供当前处理流程使用
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := fallback("值", "默认"); got != "值" {
|
||||
t.Errorf("fallback('值')=%q", got)
|
||||
}
|
||||
@@ -494,13 +494,13 @@ func TestFallback(t *testing.T) {
|
||||
|
||||
// TestNotifyAccountAlert_DBError 查询出错时不 panic(err != nil 分支)。
|
||||
func TestNotifyAccountAlert_DBError(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStoreBare(t)
|
||||
// d 保存d,供当前处理流程使用
|
||||
// d 用于本次流程后续判断的d
|
||||
d := s.DB
|
||||
cleanup() // 提前关闭 DB,使查询返回错误
|
||||
_ = d
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
// store 非 nil 但 DB 已关闭,查询会报错;不应 panic。
|
||||
n.NotifyAccountAlert("cid", "warn", "标题", "正文")
|
||||
@@ -508,7 +508,7 @@ func TestNotifyAccountAlert_DBError(t *testing.T) {
|
||||
|
||||
// TestNotifyDelivery_DBError 查询出错时不 panic(err != nil 分支)。
|
||||
func TestNotifyDelivery_DBError(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStoreBare(t)
|
||||
cleanup() // 提前关闭 DB
|
||||
n := New("cid", s, nil)
|
||||
@@ -517,11 +517,11 @@ func TestNotifyDelivery_DBError(t *testing.T) {
|
||||
|
||||
// TestSendToChannel_DBError 查询渠道出错时返回包装错误。
|
||||
func TestSendToChannel_DBError(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStoreBare(t)
|
||||
cleanup() // 提前关闭 DB
|
||||
n := New("cid", s, nil)
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := n.SendToChannel(1, "x"); err == nil {
|
||||
t.Fatal("DB 查询出错应返回 error")
|
||||
}
|
||||
@@ -529,18 +529,18 @@ func TestSendToChannel_DBError(t *testing.T) {
|
||||
|
||||
// TestNotifyAccountAlert_SendError 某渠道发送失败时记录错误但不中断。
|
||||
func TestNotifyAccountAlert_SendError(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStoreBare(t)
|
||||
defer cleanup()
|
||||
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
// srv 用于本次流程后续判断的srv
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
addWebhookChannel(t, s, "cid", "失败渠道", srv.URL)
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
// 渠道返回 5xx,send 报错 → 走 logger.Error 分支,但不应 panic。
|
||||
n.NotifyAccountAlert("cid", "warn", "标题", "正文")
|
||||
@@ -548,10 +548,10 @@ func TestNotifyAccountAlert_SendError(t *testing.T) {
|
||||
|
||||
// TestNew_DefaultLogger logger 为 nil 时使用默认 logger。
|
||||
func TestNew_DefaultLogger(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStoreBare(t)
|
||||
defer cleanup()
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
if n == nil || n.logger == nil || n.httpc == nil {
|
||||
t.Fatal("New 未正确初始化字段")
|
||||
|
||||
@@ -33,18 +33,28 @@ func TestNotifierWaitContextHonorsDeadline(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// newNotifyStore 负责newNotifyStore相关处理。
|
||||
// TestNotifierStartRejectsNilContext 验证 nil Context 不会启动无法取消的通知 worker。
|
||||
func TestNotifierStartRejectsNilContext(t *testing.T) {
|
||||
// notifier 保存具备启动标记的最小通知器测试替身。
|
||||
notifier := &Notifier{done: make(chan struct{})}
|
||||
notifier.Start(nil)
|
||||
if notifier.started.Load() {
|
||||
t.Fatal("nil Context 不应标记通知 worker 已启动")
|
||||
}
|
||||
}
|
||||
|
||||
// newNotifyStore 封装newNotifyStore业务协调。
|
||||
func newNotifyStore(t *testing.T) (*db.Store, func()) {
|
||||
t.Helper()
|
||||
// d、err 保存d、err,供当前处理流程使用
|
||||
// d、err 用于本次流程后续判断的d、err
|
||||
d, _, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "test.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
// s 保存s,供当前处理流程使用
|
||||
// s 用于本次流程后续判断的s
|
||||
s := db.NewStore(d, db.DialectSQLite)
|
||||
s.Users.Create(context.Background(), "admin", "[email protected]", "pw")
|
||||
// admin 保存admin,供当前处理流程使用
|
||||
// admin 用于本次流程后续判断的admin
|
||||
admin, _ := s.Users.GetByUsername(context.Background(), "admin")
|
||||
s.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID)
|
||||
return s, func() { d.Close() }
|
||||
@@ -52,35 +62,35 @@ func newNotifyStore(t *testing.T) (*db.Store, func()) {
|
||||
|
||||
// TestSendDingTalk 钉钉渠道 POST 正确 payload。
|
||||
func TestSendDingTalk(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStore(t)
|
||||
defer cleanup()
|
||||
|
||||
// got 保存got,供当前处理流程使用
|
||||
// got 用于本次流程后续判断的got
|
||||
var got map[string]any
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
// srv 用于本次流程后续判断的srv
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// b 保存b,供当前处理流程使用
|
||||
// b 用于本次流程后续判断的b
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
_ = json.Unmarshal(b, &got)
|
||||
w.WriteHeader(200)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
// cfg 保存cfg,供当前处理流程使用
|
||||
// cfg 用于本次流程后续判断的cfg
|
||||
cfg := `{"webhook_url":"` + srv.URL + `"}`
|
||||
// ch 保存ch,供当前处理流程使用
|
||||
// ch 用于本次流程后续判断的ch
|
||||
ch := db.NotificationChannel{ID: 1, Name: "钉钉", Type: "ding_talk", Config: cfg}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := n.send(ch, "测试消息"); err != nil {
|
||||
t.Fatalf("send dingtalk: %v", err)
|
||||
}
|
||||
if got["msgtype"] != "markdown" {
|
||||
t.Errorf("msgtype=%v want markdown", got["msgtype"])
|
||||
}
|
||||
// md 保存md,供当前处理流程使用
|
||||
// md 用于本次流程后续判断的md
|
||||
md, _ := got["markdown"].(map[string]any)
|
||||
if md["text"] != "测试消息" {
|
||||
t.Errorf("text=%v", md["text"])
|
||||
@@ -89,22 +99,22 @@ func TestSendDingTalk(t *testing.T) {
|
||||
|
||||
// TestSendTelegram Telegram 渠道。
|
||||
func TestSendTelegram(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStore(t)
|
||||
defer cleanup()
|
||||
|
||||
// got 保存got,供当前处理流程使用
|
||||
// got 用于本次流程后续判断的got
|
||||
var got map[string]any
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
// srv 用于本次流程后续判断的srv
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// b 保存b,供当前处理流程使用
|
||||
// b 用于本次流程后续判断的b
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
_ = json.Unmarshal(b, &got)
|
||||
w.WriteHeader(200)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
// 用 config 覆盖 API URL 不可行(硬编码),故直接调内部 sendTelegram。
|
||||
cfg := map[string]any{"bot_token": "TOKEN", "chat_id": "123"}
|
||||
@@ -121,10 +131,10 @@ func TestSendTelegram(t *testing.T) {
|
||||
|
||||
// TestRouteByChannelType 渠道类型路由。
|
||||
func TestRouteByChannelType(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStore(t)
|
||||
defer cleanup()
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
|
||||
// 不支持的类型应返回 error。
|
||||
@@ -140,10 +150,10 @@ func TestRouteByChannelType(t *testing.T) {
|
||||
|
||||
// TestNotifyDelivery_NoChannels 无通知配置时不报错。
|
||||
func TestNotifyDelivery_NoChannels(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStore(t)
|
||||
defer cleanup()
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
// 不应 panic。
|
||||
n.NotifyDelivery("cid", "买家", "b1", "item1", "发货成功", "chat1")
|
||||
@@ -151,20 +161,20 @@ func TestNotifyDelivery_NoChannels(t *testing.T) {
|
||||
|
||||
// TestNotifyDelivery_WithChannel 有渠道时发送。
|
||||
func TestNotifyDelivery_WithChannel(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
// ctx 用于本次流程后续判断的ctx
|
||||
ctx := context.Background()
|
||||
// admin 保存admin,供当前处理流程使用
|
||||
// admin 用于本次流程后续判断的admin
|
||||
admin, _ := s.Users.GetByUsername(ctx, "admin")
|
||||
_ = admin
|
||||
|
||||
// gotBody 保存got请求体,供当前处理流程使用
|
||||
// gotBody 用于本次流程后续判断的got请求体
|
||||
var gotBody string
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
// srv 用于本次流程后续判断的srv
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// b 保存b,供当前处理流程使用
|
||||
// b 用于本次流程后续判断的b
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
gotBody = string(b)
|
||||
w.WriteHeader(200)
|
||||
@@ -175,12 +185,12 @@ func TestNotifyDelivery_WithChannel(t *testing.T) {
|
||||
res, _ := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES ('测试','webhook',?,1,1)`,
|
||||
`{"webhook_url":"`+srv.URL+`"}`)
|
||||
// chID 保存chID,供当前处理流程使用
|
||||
// chID 用于本次流程后续判断的chID
|
||||
chID, _ := res.LastInsertId()
|
||||
s.DB.ExecContext(ctx,
|
||||
`INSERT INTO message_notifications (cookie_id,channel_id,enabled) VALUES ('cid',?,1)`, chID)
|
||||
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
n.NotifyDelivery("cid", "买家甲", "b1", "item1", "发货成功", "chat1")
|
||||
if gotBody == "" {
|
||||
@@ -191,51 +201,51 @@ func TestNotifyDelivery_WithChannel(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotifyEvent_FiltersByChannelEventTypes 负责TestNotifyEventFiltersBy渠道EventTypes相关处理。
|
||||
// TestNotifyEvent_FiltersByChannelEventTypes 封装TestNotifyEventFiltersBy渠道EventTypes业务协调。
|
||||
func TestNotifyEvent_FiltersByChannelEventTypes(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
// ctx 用于本次流程后续判断的ctx
|
||||
ctx := context.Background()
|
||||
|
||||
// hits 保存hits,供当前处理流程使用
|
||||
// hits 用于本次流程后续判断的hits
|
||||
hits := map[string]int{}
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
// srv 用于本次流程后续判断的srv
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits[r.URL.Path]++
|
||||
w.WriteHeader(200)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
// resOffline、err 保存响应Offline、err,供当前处理流程使用
|
||||
// resOffline、err 用于本次流程后续判断的响应Offline、err
|
||||
resOffline, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO notification_channels (name,type,config,event_types,enabled,user_id) VALUES ('掉线','webhook',?,?,1,1)`,
|
||||
`{"webhook_url":"`+srv.URL+`/offline"}`, `["`+EventAccountOffline+`"]`)
|
||||
if err != nil {
|
||||
t.Fatalf("insert offline channel: %v", err)
|
||||
}
|
||||
// offlineID 保存offlineID,供当前处理流程使用
|
||||
// offlineID 用于本次流程后续判断的offlineID
|
||||
offlineID, _ := resOffline.LastInsertId()
|
||||
// resDisabled、err 保存响应Disabled、err,供当前处理流程使用
|
||||
// resDisabled、err 用于本次流程后续判断的响应Disabled、err
|
||||
resDisabled, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO notification_channels (name,type,config,event_types,enabled,user_id) VALUES ('禁用','webhook',?,?,1,1)`,
|
||||
`{"webhook_url":"`+srv.URL+`/disabled"}`, `["`+EventAccountDisabled+`"]`)
|
||||
if err != nil {
|
||||
t.Fatalf("insert disabled channel: %v", err)
|
||||
}
|
||||
// disabledID 保存disabledID,供当前处理流程使用
|
||||
// disabledID 用于本次流程后续判断的disabledID
|
||||
disabledID, _ := resDisabled.LastInsertId()
|
||||
// id 表示当前遍历过程中的标识
|
||||
for _, id := range []int64{offlineID, disabledID} {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO message_notifications (cookie_id,channel_id,enabled) VALUES ('cid',?,1)`, id); err != nil {
|
||||
t.Fatalf("insert binding: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
n.NotifyAccountEvent("cid", EventAccountOffline, "warn", "掉线", "正在恢复")
|
||||
if hits["/offline"] != 1 {
|
||||
@@ -246,51 +256,51 @@ func TestNotifyEvent_FiltersByChannelEventTypes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotifyAccountAlertClassifiesLegacyAlerts 负责TestNotify账号AlertClassifiesLegacyAlerts相关处理。
|
||||
// TestNotifyAccountAlertClassifiesLegacyAlerts 封装TestNotify账号AlertClassifiesLegacyAlerts业务协调。
|
||||
func TestNotifyAccountAlertClassifiesLegacyAlerts(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
// ctx 用于本次流程后续判断的ctx
|
||||
ctx := context.Background()
|
||||
|
||||
// hits 保存hits,供当前处理流程使用
|
||||
// hits 用于本次流程后续判断的hits
|
||||
hits := map[string]int{}
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
// srv 用于本次流程后续判断的srv
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits[r.URL.Path]++
|
||||
w.WriteHeader(200)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
// resSecurity、err 保存响应Security、err,供当前处理流程使用
|
||||
// resSecurity、err 用于本次流程后续判断的响应Security、err
|
||||
resSecurity, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO notification_channels (name,type,config,event_types,enabled,user_id) VALUES ('风控','webhook',?,?,1,1)`,
|
||||
`{"webhook_url":"`+srv.URL+`/security"}`, `["`+EventSecurityVerification+`"]`)
|
||||
if err != nil {
|
||||
t.Fatalf("insert security channel: %v", err)
|
||||
}
|
||||
// securityID 保存securityID,供当前处理流程使用
|
||||
// securityID 用于本次流程后续判断的securityID
|
||||
securityID, _ := resSecurity.LastInsertId()
|
||||
// resToken、err 保存响应Token、err,供当前处理流程使用
|
||||
// resToken、err 用于本次流程后续判断的响应Token、err
|
||||
resToken, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO notification_channels (name,type,config,event_types,enabled,user_id) VALUES ('续期','webhook',?,?,1,1)`,
|
||||
`{"webhook_url":"`+srv.URL+`/token"}`, `["`+EventTokenRenewal+`"]`)
|
||||
if err != nil {
|
||||
t.Fatalf("insert token channel: %v", err)
|
||||
}
|
||||
// tokenID 保存令牌ID,供当前处理流程使用
|
||||
// tokenID 用于本次流程后续判断的令牌ID
|
||||
tokenID, _ := resToken.LastInsertId()
|
||||
// id 表示当前遍历过程中的标识
|
||||
for _, id := range []int64{securityID, tokenID} {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO message_notifications (cookie_id,channel_id,enabled) VALUES ('cid',?,1)`, id); err != nil {
|
||||
t.Fatalf("insert binding: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
n.NotifyAccountAlert("cid", "warn", "闲鱼要求滑块验证", "请完成 captcha")
|
||||
if hits["/security"] != 1 {
|
||||
@@ -301,39 +311,39 @@ func TestNotifyAccountAlertClassifiesLegacyAlerts(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotifyEventRejectsMalformedEventTypes 负责TestNotifyEventRejectsMalformedEventTypes相关处理。
|
||||
// TestNotifyEventRejectsMalformedEventTypes 封装TestNotifyEventRejectsMalformedEventTypes业务协调。
|
||||
func TestNotifyEventRejectsMalformedEventTypes(t *testing.T) {
|
||||
// s、cleanup 保存s、cleanup,供当前处理流程使用
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
s, cleanup := newNotifyStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
// ctx 用于本次流程后续判断的ctx
|
||||
ctx := context.Background()
|
||||
|
||||
// hits 保存hits,供当前处理流程使用
|
||||
// hits 用于本次流程后续判断的hits
|
||||
hits := 0
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
// srv 用于本次流程后续判断的srv
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits++
|
||||
w.WriteHeader(200)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
// res、err 保存res、err,供当前处理流程使用
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO notification_channels (name,type,config,event_types,enabled,user_id) VALUES ('坏配置','webhook',?,?,1,1)`,
|
||||
`{"webhook_url":"`+srv.URL+`"}`, `["`+EventAccountOffline+`"`)
|
||||
if err != nil {
|
||||
t.Fatalf("insert malformed channel: %v", err)
|
||||
}
|
||||
// channelID 保存渠道ID,供当前处理流程使用
|
||||
// channelID 用于本次流程后续判断的渠道ID
|
||||
channelID, _ := res.LastInsertId()
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO message_notifications (cookie_id,channel_id,enabled) VALUES ('cid',?,1)`, channelID); err != nil {
|
||||
t.Fatalf("insert binding: %v", err)
|
||||
}
|
||||
|
||||
// n 保存n,供当前处理流程使用
|
||||
// n 用于本次流程后续判断的n
|
||||
n := New("cid", s, nil)
|
||||
n.NotifyAccountEvent("cid", EventAccountOffline, "warn", "掉线", "正在恢复")
|
||||
if hits != 0 {
|
||||
@@ -360,9 +370,9 @@ func TestParseConfig(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// contains 负责contains相关处理。
|
||||
// contains 封装contains业务协调。
|
||||
func contains(s, sub string) bool {
|
||||
for // i 保存i,供当前处理流程使用
|
||||
for // i 用于本次流程后续判断的i
|
||||
i := 0; i+len(sub) <= len(s); i++ {
|
||||
if s[i:i+len(sub)] == sub {
|
||||
return true
|
||||
|
||||
@@ -11,32 +11,32 @@ import (
|
||||
"xianyu-go/internal/netguard"
|
||||
)
|
||||
|
||||
// TestSendPublicSMTPRejectsInvalidPortAndLoopback 负责TestSendPublicSMTPRejectsInvalidPortAndLoopback相关处理。
|
||||
// TestSendPublicSMTPRejectsInvalidPortAndLoopback 封装TestSendPublicSMTPRejectsInvalidPortAndLoopback业务协调。
|
||||
func TestSendPublicSMTPRejectsInvalidPortAndLoopback(t *testing.T) {
|
||||
// testDialer 保存testDialer,供当前处理流程使用
|
||||
// testDialer 用于本次流程后续判断的testDialer
|
||||
testDialer := dialPublicSMTP
|
||||
dialPublicSMTP = netguard.DialPublicContext
|
||||
t.Cleanup(func() { dialPublicSMTP = testDialer })
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := sendPublicSMTP(context.Background(), "smtp.example.com:not-a-port", "smtp.example.com", nil, "[email protected]", "[email protected]", nil); err == nil || !strings.Contains(err.Error(), "端口无效") {
|
||||
t.Fatalf("invalid port must be rejected, got %v", err)
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := sendPublicSMTP(context.Background(), "127.0.0.1:25", "127.0.0.1", nil, "[email protected]", "[email protected]", nil); err == nil || !strings.Contains(err.Error(), "非公网") {
|
||||
t.Fatalf("loopback SMTP must be rejected, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendPublicSMTPRequiresAdvertisedSTARTTLS 负责TestSendPublicSMTPRequiresAdvertisedSTARTTLS相关处理。
|
||||
// TestSendPublicSMTPRequiresAdvertisedSTARTTLS 封装TestSendPublicSMTPRequiresAdvertisedSTARTTLS业务协调。
|
||||
func TestSendPublicSMTPRequiresAdvertisedSTARTTLS(t *testing.T) {
|
||||
// original 保存original,供当前处理流程使用
|
||||
// original 用于本次流程后续判断的original
|
||||
original := dialPublicSMTP
|
||||
dialPublicSMTP = func(context.Context, string, string, time.Duration) (net.Conn, error) {
|
||||
// client、server 保存client、server,供当前处理流程使用
|
||||
// client、server 用于本次流程后续判断的client、server
|
||||
client, server := net.Pipe()
|
||||
go func() {
|
||||
defer server.Close()
|
||||
// reader 保存reader,供当前处理流程使用
|
||||
// reader 用于本次流程后续判断的reader
|
||||
reader := bufio.NewReader(server)
|
||||
_, _ = server.Write([]byte("220 smtp.example.test ESMTP\r\n"))
|
||||
_, _ = reader.ReadString('\n')
|
||||
@@ -45,7 +45,7 @@ func TestSendPublicSMTPRequiresAdvertisedSTARTTLS(t *testing.T) {
|
||||
return client, nil
|
||||
}
|
||||
t.Cleanup(func() { dialPublicSMTP = original })
|
||||
// err 保存err,供当前处理流程使用
|
||||
// err 用于本次流程后续判断的err
|
||||
err := sendPublicSMTP(context.Background(), "smtp.example.test:587", "smtp.example.test", nil,
|
||||
"[email protected]", "[email protected]", nil, smtpTransportOptions{UseSTARTTLS: true})
|
||||
if err == nil || !strings.Contains(err.Error(), "STARTTLS") {
|
||||
|
||||
Reference in new issue
Block a user