Version: 0.9.60.dev.260430

后端:
1.接入主动调度 worker 与飞书通知链路
- 新增 due job scanner 与 active_schedule.triggered workflow
- 接入 notification.feishu.requested handler、飞书 webhook provider 和用户通知配置接口
- 支持 notification_records 去重、重试、skipped/dead 状态流转
- 完成 api / worker / all 启动模式装配与主动调度验收记录
2.后续要做的就是补全从异常发生到给用户推送消息之间的逻辑缺口
This commit is contained in:
Losita
2026-04-30 23:45:27 +08:00
parent e945578fbf
commit 0a014f7472
26 changed files with 3636 additions and 55 deletions

View File

@@ -2,6 +2,8 @@ package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
@@ -12,6 +14,7 @@ import (
"github.com/LoveLosita/smartflow/backend/active_scheduler/trigger"
"github.com/LoveLosita/smartflow/backend/respond"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// ActiveScheduleAPI 承载主动调度开发期和验收期 API。
@@ -23,12 +26,14 @@ import (
type ActiveScheduleAPI struct {
dryRunService *activesvc.DryRunService
previewConfirmService *activesvc.PreviewConfirmService
triggerService *activesvc.TriggerService
}
func NewActiveScheduleAPI(dryRunService *activesvc.DryRunService, previewConfirmService *activesvc.PreviewConfirmService) *ActiveScheduleAPI {
func NewActiveScheduleAPI(dryRunService *activesvc.DryRunService, previewConfirmService *activesvc.PreviewConfirmService, triggerService *activesvc.TriggerService) *ActiveScheduleAPI {
return &ActiveScheduleAPI{
dryRunService: dryRunService,
previewConfirmService: previewConfirmService,
triggerService: triggerService,
}
}
@@ -39,6 +44,7 @@ type ActiveScheduleDryRunRequest struct {
FeedbackID string `json:"feedback_id"`
IdempotencyKey string `json:"idempotency_key"`
MockNow *time.Time `json:"mock_now"`
Payload any `json:"payload"`
}
// DryRun 同步执行主动调度诊断,不写 preview、不发通知、不修改正式日程。
@@ -81,6 +87,51 @@ func (api *ActiveScheduleAPI) DryRun(c *gin.Context) {
c.JSON(http.StatusOK, respond.RespWithData(respond.Ok, result))
}
// Trigger 写入正式主动调度 trigger 并发布 active_schedule.triggered。
func (api *ActiveScheduleAPI) Trigger(c *gin.Context) {
if api == nil || api.triggerService == nil {
c.JSON(http.StatusInternalServerError, respond.InternalError(nilServiceError("主动调度 trigger service 未初始化")))
return
}
var req ActiveScheduleDryRunRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, respond.WrongParamType)
return
}
rawPayload, err := json.Marshal(req.Payload)
if err != nil {
c.JSON(http.StatusBadRequest, respond.WrongParamType)
return
}
if string(rawPayload) == "null" {
rawPayload = []byte("{}")
}
now := time.Now()
ctx, cancel := context.WithTimeout(c.Request.Context(), 3*time.Second)
defer cancel()
result, err := api.triggerService.CreateAndPublish(ctx, activesvc.TriggerRequest{
UserID: c.GetInt("user_id"),
TriggerType: trigger.TriggerType(req.TriggerType),
Source: trigger.SourceAPITrigger,
TargetType: trigger.TargetType(req.TargetType),
TargetID: req.TargetID,
FeedbackID: req.FeedbackID,
IdempotencyKey: req.IdempotencyKey,
MockNow: req.MockNow,
IsMockTime: req.MockNow != nil,
RequestedAt: now,
Payload: rawPayload,
TraceID: fmt.Sprintf("trace_api_trigger_%d_%d", c.GetInt("user_id"), now.UnixNano()),
})
if err != nil {
respond.DealWithError(c, err)
return
}
c.JSON(http.StatusOK, respond.RespWithData(respond.Ok, result))
}
// CreatePreview 先同步 dry-run再把 top1 候选固化为待确认预览。
func (api *ActiveScheduleAPI) CreatePreview(c *gin.Context) {
if api == nil || api.dryRunService == nil || api.previewConfirmService == nil {
@@ -168,12 +219,85 @@ func (api *ActiveScheduleAPI) ConfirmPreview(c *gin.Context) {
defer cancel()
result, err := api.previewConfirmService.ConfirmPreview(ctx, req)
if err != nil {
respond.DealWithError(c, err)
writeActiveScheduleConfirmError(c, err)
return
}
c.JSON(http.StatusOK, respond.RespWithData(respond.Ok, result))
}
// writeActiveScheduleConfirmError 将 confirm/apply 的可预期业务拒绝映射为 4xx。
//
// 职责边界:
// 1. 只处理主动调度 confirm/apply 链路已经分类的 ApplyError
// 2. 不吞掉数据库、超时、panic recover 等系统错误,未知错误继续交给通用 respond 走 500
// 3. 响应体保留 error_code / error_message便于前端按过期、冲突、越权等场景给出明确交互。
func writeActiveScheduleConfirmError(c *gin.Context, err error) {
if applyErr, ok := activeapply.AsApplyError(err); ok {
status := activeScheduleApplyHTTPStatus(applyErr.Code)
message := applyErr.Message
if message == "" {
message = applyErr.Error()
}
applyStatus := activeapply.ApplyStatusRejected
if applyErr.Code == activeapply.ErrorCodeExpired {
applyStatus = activeapply.ApplyStatusExpired
}
if applyErr.Code == activeapply.ErrorCodeDBError {
applyStatus = activeapply.ApplyStatusFailed
}
c.JSON(status, respond.RespWithData(respond.Response{
Status: fmt.Sprintf("%d", status),
Info: message,
}, activeapply.ConfirmResult{
ApplyStatus: applyStatus,
ErrorCode: applyErr.Code,
ErrorMessage: message,
}))
return
}
if errors.Is(err, gorm.ErrRecordNotFound) {
c.JSON(http.StatusNotFound, respond.RespWithData(respond.Response{
Status: fmt.Sprintf("%d", http.StatusNotFound),
Info: "预览不存在或已被删除",
}, activeapply.ConfirmResult{
ApplyStatus: activeapply.ApplyStatusRejected,
ErrorCode: activeapply.ErrorCodeTargetNotFound,
ErrorMessage: "预览不存在或已被删除",
}))
return
}
respond.DealWithError(c, err)
}
// activeScheduleApplyHTTPStatus 只负责错误码到 HTTP 语义的稳定映射。
//
// 说明:
// 1. 请求体/编辑范围问题返回 400
// 2. 越权返回 403目标缺失返回 404
// 3. 过期、幂等冲突、节次冲突、目标状态变化统一返回 409提示前端刷新预览或重新生成。
func activeScheduleApplyHTTPStatus(code activeapply.ErrorCode) int {
switch code {
case activeapply.ErrorCodeInvalidRequest,
activeapply.ErrorCodeInvalidEditedChanges,
activeapply.ErrorCodeUnsupportedChangeType:
return http.StatusBadRequest
case activeapply.ErrorCodeForbidden:
return http.StatusForbidden
case activeapply.ErrorCodeTargetNotFound:
return http.StatusNotFound
case activeapply.ErrorCodeExpired,
activeapply.ErrorCodeIdempotencyConflict,
activeapply.ErrorCodeBaseVersionChanged,
activeapply.ErrorCodeTargetCompleted,
activeapply.ErrorCodeTargetAlreadySchedule,
activeapply.ErrorCodeSlotConflict,
activeapply.ErrorCodeAlreadyApplied:
return http.StatusConflict
default:
return http.StatusInternalServerError
}
}
type nilServiceError string
func (e nilServiceError) Error() string {

View File

@@ -9,4 +9,5 @@ type ApiHandlers struct {
AgentHandler *AgentHandler
MemoryHandler *MemoryHandler
ActiveSchedule *ActiveScheduleAPI
Notification *NotificationAPI
}

129
backend/api/notification.go Normal file
View File

@@ -0,0 +1,129 @@
package api
import (
"context"
"errors"
"net/http"
"time"
"github.com/LoveLosita/smartflow/backend/notification"
"github.com/LoveLosita/smartflow/backend/respond"
"github.com/gin-gonic/gin"
)
const notificationAPITimeout = 8 * time.Second
// NotificationAPI 承载当前用户的外部通知通道配置接口。
//
// 职责边界:
// 1. 只负责从 JWT 上下文取得当前 user_id、绑定请求体并调用 notification.ChannelService
// 2. 不直接读写 user_notification_channels避免 API 层绕过 webhook 校验和脱敏规则;
// 3. 不参与主动调度、notification_records 状态机和 outbox 消费。
type NotificationAPI struct {
channelService *notification.ChannelService
}
func NewNotificationAPI(channelService *notification.ChannelService) *NotificationAPI {
return &NotificationAPI{channelService: channelService}
}
type saveFeishuWebhookRequest struct {
Enabled *bool `json:"enabled"`
WebhookURL string `json:"webhook_url" binding:"required"`
AuthType string `json:"auth_type"`
BearerToken string `json:"bearer_token"`
}
// GetFeishuWebhook 查询当前用户的飞书 Webhook 触发器配置。
func (api *NotificationAPI) GetFeishuWebhook(c *gin.Context) {
if api == nil || api.channelService == nil {
c.JSON(http.StatusInternalServerError, respond.InternalError(nilServiceError("通知通道 service 未初始化")))
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), notificationAPITimeout)
defer cancel()
channel, err := api.channelService.GetFeishuWebhook(ctx, c.GetInt("user_id"))
if err != nil {
writeNotificationError(c, err)
return
}
c.JSON(http.StatusOK, respond.RespWithData(respond.Ok, channel))
}
// SaveFeishuWebhook 幂等保存当前用户的飞书 Webhook 触发器配置。
func (api *NotificationAPI) SaveFeishuWebhook(c *gin.Context) {
if api == nil || api.channelService == nil {
c.JSON(http.StatusInternalServerError, respond.InternalError(nilServiceError("通知通道 service 未初始化")))
return
}
var req saveFeishuWebhookRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, respond.WrongParamType)
return
}
enabled := true
if req.Enabled != nil {
enabled = *req.Enabled
}
ctx, cancel := context.WithTimeout(c.Request.Context(), notificationAPITimeout)
defer cancel()
channel, err := api.channelService.SaveFeishuWebhook(ctx, c.GetInt("user_id"), notification.SaveFeishuWebhookRequest{
Enabled: enabled,
WebhookURL: req.WebhookURL,
AuthType: req.AuthType,
BearerToken: req.BearerToken,
})
if err != nil {
writeNotificationError(c, err)
return
}
c.JSON(http.StatusOK, respond.RespWithData(respond.Ok, channel))
}
// DeleteFeishuWebhook 删除当前用户的飞书 Webhook 触发器配置。
func (api *NotificationAPI) DeleteFeishuWebhook(c *gin.Context) {
if api == nil || api.channelService == nil {
c.JSON(http.StatusInternalServerError, respond.InternalError(nilServiceError("通知通道 service 未初始化")))
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), notificationAPITimeout)
defer cancel()
if err := api.channelService.DeleteFeishuWebhook(ctx, c.GetInt("user_id")); err != nil {
writeNotificationError(c, err)
return
}
c.JSON(http.StatusOK, respond.RespWithData(respond.Ok, gin.H{"deleted": true}))
}
// TestFeishuWebhook 发送一条最小业务 JSON 到当前用户配置的飞书 Webhook。
func (api *NotificationAPI) TestFeishuWebhook(c *gin.Context) {
if api == nil || api.channelService == nil {
c.JSON(http.StatusInternalServerError, respond.InternalError(nilServiceError("通知通道 service 未初始化")))
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), notificationAPITimeout)
defer cancel()
result, err := api.channelService.TestFeishuWebhook(ctx, c.GetInt("user_id"))
if err != nil {
writeNotificationError(c, err)
return
}
c.JSON(http.StatusOK, respond.RespWithData(respond.Ok, result))
}
func writeNotificationError(c *gin.Context, err error) {
if errors.Is(err, notification.ErrInvalidChannelConfig) {
c.JSON(http.StatusBadRequest, respond.WrongParamType)
return
}
respond.DealWithError(c, err)
}