114 lines
2.4 KiB
Go
114 lines
2.4 KiB
Go
package warningnotify
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strings"
|
|
"sync"
|
|
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
)
|
|
|
|
type Sender interface {
|
|
Send(ctx context.Context, batch Batch) error
|
|
}
|
|
|
|
var (
|
|
currentSender Sender = LogSender{}
|
|
senderMu sync.RWMutex
|
|
)
|
|
|
|
func SetSender(sender Sender) func() {
|
|
senderMu.Lock()
|
|
old := currentSender
|
|
if sender == nil {
|
|
currentSender = LogSender{}
|
|
} else {
|
|
currentSender = sender
|
|
}
|
|
senderMu.Unlock()
|
|
return func() {
|
|
senderMu.Lock()
|
|
currentSender = old
|
|
senderMu.Unlock()
|
|
}
|
|
}
|
|
|
|
func Dispatch(ctx context.Context, events []Event) error {
|
|
batches := BuildBatches(events)
|
|
if len(batches) == 0 {
|
|
return nil
|
|
}
|
|
senderMu.RLock()
|
|
sender := currentSender
|
|
senderMu.RUnlock()
|
|
if sender == nil {
|
|
sender = LogSender{}
|
|
}
|
|
var sendErrors []error
|
|
for _, batch := range batches {
|
|
if err := sender.Send(ctx, batch); err != nil {
|
|
sendErrors = append(sendErrors, err)
|
|
}
|
|
}
|
|
return errors.Join(sendErrors...)
|
|
}
|
|
|
|
type LogSender struct{}
|
|
|
|
func (LogSender) Send(ctx context.Context, batch Batch) error {
|
|
switch batch.Method {
|
|
case MethodSMS:
|
|
g.Log().Infof(
|
|
ctx,
|
|
"WarningNotify SMS payload prepared, business:%s, tenantId:%s, deptId:%d, category:%s, stage:%d, recipients:%s, count:%d, content:%s",
|
|
batch.Business,
|
|
batch.TenantID,
|
|
batch.DeptID,
|
|
batch.Category,
|
|
batch.WarnStage,
|
|
strings.Join(batch.Recipients, ","),
|
|
len(batch.Items),
|
|
batch.SMSContent,
|
|
)
|
|
case MethodEmail:
|
|
g.Log().Infof(
|
|
ctx,
|
|
"WarningNotify email payload prepared, business:%s, tenantId:%s, deptId:%d, category:%s, stage:%d, recipients:%s, count:%d, subject:%s, body:%s",
|
|
batch.Business,
|
|
batch.TenantID,
|
|
batch.DeptID,
|
|
batch.Category,
|
|
batch.WarnStage,
|
|
strings.Join(batch.Recipients, ","),
|
|
len(batch.Items),
|
|
batch.EmailSubject,
|
|
batch.EmailBody,
|
|
)
|
|
case MethodPlatform:
|
|
g.Log().Infof(
|
|
ctx,
|
|
"WarningNotify platform payload prepared, business:%s, tenantId:%s, deptId:%d, category:%s, stage:%d, count:%d, title:%s, content:%s",
|
|
batch.Business,
|
|
batch.TenantID,
|
|
batch.DeptID,
|
|
batch.Category,
|
|
batch.WarnStage,
|
|
len(batch.Items),
|
|
batch.PlatformTitle,
|
|
batch.PlatformContent,
|
|
)
|
|
default:
|
|
g.Log().Infof(
|
|
ctx,
|
|
"WarningNotify payload skipped by unsupported method, business:%s, method:%s, tenantId:%s, deptId:%d, count:%d",
|
|
batch.Business,
|
|
batch.Method,
|
|
batch.TenantID,
|
|
batch.DeptID,
|
|
len(batch.Items),
|
|
)
|
|
}
|
|
return nil
|
|
}
|