2026-03-19 15:45:30 +08:00
|
|
|
package lifecycle
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"log/slog"
|
|
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
|
|
|
|
|
|
|
|
|
"github.com/chaitin/MonkeyCode/backend/consts"
|
|
|
|
|
"github.com/chaitin/MonkeyCode/backend/domain"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// TaskNotifyHook 任务状态变更时发送通知
|
|
|
|
|
type TaskNotifyHook struct {
|
|
|
|
|
notify NotifyPublisher
|
|
|
|
|
logger *slog.Logger
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// NewTaskNotifyHook 创建任务通知 Hook
|
|
|
|
|
func NewTaskNotifyHook(notify NotifyPublisher, logger *slog.Logger) *TaskNotifyHook {
|
|
|
|
|
return &TaskNotifyHook{
|
|
|
|
|
notify: notify,
|
|
|
|
|
logger: logger.With("hook", "task-notify-hook"),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-19 15:46:51 +08:00
|
|
|
func (h *TaskNotifyHook) Name() string { return "task-notify-hook" }
|
|
|
|
|
func (h *TaskNotifyHook) Priority() int { return 50 }
|
|
|
|
|
func (h *TaskNotifyHook) Async() bool { return true } // 异步执行,不阻塞状态转换
|
2026-03-19 15:45:30 +08:00
|
|
|
|
2026-03-19 15:46:51 +08:00
|
|
|
func (h *TaskNotifyHook) OnStateChange(ctx context.Context, taskID uuid.UUID, from, to consts.TaskStatus, metadata TaskMetadata) error {
|
2026-03-19 15:45:30 +08:00
|
|
|
var eventType consts.NotifyEventType
|
|
|
|
|
switch to {
|
2026-03-19 15:46:51 +08:00
|
|
|
case consts.TaskStatusPending:
|
2026-03-19 15:45:30 +08:00
|
|
|
eventType = consts.NotifyEventTaskCreated
|
|
|
|
|
default:
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
event := &domain.NotifyEvent{
|
|
|
|
|
EventType: eventType,
|
2026-03-19 15:46:51 +08:00
|
|
|
SubjectUserID: metadata.UserID,
|
2026-03-19 15:45:30 +08:00
|
|
|
RefID: taskID.String(),
|
|
|
|
|
Payload: domain.NotifyEventPayload{
|
|
|
|
|
TaskID: taskID.String(),
|
|
|
|
|
TaskStatus: string(to),
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
h.logger.InfoContext(ctx, "publishing notify event", "event", eventType, "task_id", taskID)
|
|
|
|
|
return h.notify.Publish(ctx, event)
|
|
|
|
|
}
|