mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-03 20:21:51 +08:00
feat(chat,proxy): add @schedule mentions and localize proxy/schedule errors
- Support @schedule mentions in DB search, server mention resolution, and frontend mention parsing/i18n. - Return structured product error codes for proxy route validation and localize them in proxy/schedule UI. - Preserve unchanged proxy routes when rescheduling an existing schedule whose pool has no active nodes.
This commit is contained in:
1 parent
8568c41528
commit
e6241dda09
15 files changed
+312
-49
No files matched your search
+30
-3
@@ -1,6 +1,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -8,6 +9,7 @@ import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
@@ -17,11 +19,11 @@ const maxChatMentions = 10
|
||||
|
||||
// The visible token survives drafts, uploads, retries and conversation history.
|
||||
// Labels are only for display: the server trusts only the type and numeric ID.
|
||||
var chatMentionPattern = regexp.MustCompile(`@\[(task|finding|asset|company|endpoint|ip|app|root_domain|subdomain|service|任务|漏洞|资产|企业|接口|IP|应用|域名|子域名|服务)#([0-9]+)(?: [^\]\r\n]*)?\]`)
|
||||
var chatMentionPattern = regexp.MustCompile(`@\[(schedule|task|finding|asset|company|endpoint|ip|app|root_domain|subdomain|service|计划任务|计划|任务|漏洞|资产|企业|接口|IP|应用|域名|子域名|服务)#([0-9]+)(?: [^\]\r\n]*)?\]`)
|
||||
var chatMentionKinds = map[string]string{
|
||||
"任务": "task", "漏洞": "finding", "资产": "asset", "企业": "company", "接口": "endpoint",
|
||||
"任务": "task", "计划任务": "schedule", "计划": "schedule", "漏洞": "finding", "资产": "asset", "企业": "company", "接口": "endpoint",
|
||||
"IP": "ip", "应用": "app", "域名": "root_domain", "子域名": "subdomain", "服务": "service",
|
||||
"task": "task", "finding": "finding", "asset": "asset", "company": "company", "endpoint": "endpoint",
|
||||
"task": "task", "schedule": "schedule", "finding": "finding", "asset": "asset", "company": "company", "endpoint": "endpoint",
|
||||
"ip": "ip", "app": "app", "root_domain": "root_domain", "subdomain": "subdomain", "service": "service",
|
||||
}
|
||||
|
||||
@@ -164,6 +166,31 @@ func loadChatMention(pg *db.DB, ref chatMentionRef) (any, error) {
|
||||
}
|
||||
}
|
||||
return map[string]any{"task": t, "proxy_route": route}, nil
|
||||
case "schedule":
|
||||
item, err := pg.GetTaskSchedule(ref.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if item == nil {
|
||||
return nil, nil
|
||||
}
|
||||
safe := *item
|
||||
safe.ProxyURL = maskSecrets(safe.ProxyURL)
|
||||
out := map[string]any{
|
||||
"schedule": safe,
|
||||
"timezone": scheduleLocation(item.TimezoneMode).String(),
|
||||
"server_time": time.Now().Format(time.RFC3339),
|
||||
}
|
||||
if stats, err := pg.ScheduleRunStats(item.ID); err == nil {
|
||||
out["run_count"] = stats.RunCount
|
||||
if stats.LastRunAt != nil {
|
||||
out["last_run_at"] = stats.LastRunAt
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
case "finding":
|
||||
f, err := pg.GetFinding(ref.ID)
|
||||
if err != nil || f == nil {
|
||||
|
||||
+36
-8
@@ -184,17 +184,31 @@ func (s *Server) resolveContainerUpstream(src traffic.SourceIdentity) (*url.URL,
|
||||
}
|
||||
}
|
||||
|
||||
type proxyRouteValidationError struct{ msg string }
|
||||
type proxyRouteValidationError struct {
|
||||
code string
|
||||
msg string
|
||||
params map[string]any
|
||||
}
|
||||
|
||||
func (e *proxyRouteValidationError) Error() string { return e.msg }
|
||||
|
||||
func writeProxyRouteErr(w http.ResponseWriter, status int, err error) {
|
||||
if verr, ok := err.(*proxyRouteValidationError); ok && verr.code != "" {
|
||||
writeProductError(w, status, verr.code, verr.msg, verr.params)
|
||||
return
|
||||
}
|
||||
writeErr(w, status, err.Error())
|
||||
}
|
||||
func (s *Server) validateAndNormalizeProxyRoute(req ProxyRouteInput, prev *ContainerProxyRoute) (ContainerProxyRoute, error) {
|
||||
mode := strings.ToLower(strings.TrimSpace(req.Mode))
|
||||
if mode == "" {
|
||||
mode = "inherit"
|
||||
}
|
||||
if mode != "inherit" && mode != "direct" && mode != "pool" && mode != "proxy" {
|
||||
return ContainerProxyRoute{}, &proxyRouteValidationError{"mode must be inherit, direct, pool, or proxy"}
|
||||
return ContainerProxyRoute{}, &proxyRouteValidationError{
|
||||
code: "proxy_route_invalid_mode",
|
||||
msg: "mode must be inherit, direct, pool, or proxy",
|
||||
}
|
||||
}
|
||||
route := ContainerProxyRoute{
|
||||
Mode: mode,
|
||||
@@ -209,7 +223,10 @@ func (s *Server) validateAndNormalizeProxyRoute(req ProxyRouteInput, prev *Conta
|
||||
route.ProxyURL = ""
|
||||
case "pool":
|
||||
if _, raw := s.m.ActivePoolRawURL(); raw == "" {
|
||||
return ContainerProxyRoute{}, &proxyRouteValidationError{"代理池暂无可用节点,请先在代理设置中添加并启用节点"}
|
||||
return ContainerProxyRoute{}, &proxyRouteValidationError{
|
||||
code: "proxy_pool_no_available_nodes",
|
||||
msg: "代理池暂无可用节点,请先在代理设置中添加并启用节点",
|
||||
}
|
||||
}
|
||||
route.ProxyPoolID = ""
|
||||
route.ProxyURL = ""
|
||||
@@ -217,7 +234,11 @@ func (s *Server) validateAndNormalizeProxyRoute(req ProxyRouteInput, prev *Conta
|
||||
if route.ProxyPoolID != "" {
|
||||
id, raw := s.resolvePoolEntryByIDOrName(route.ProxyPoolID)
|
||||
if raw == "" {
|
||||
return ContainerProxyRoute{}, &proxyRouteValidationError{fmt.Sprintf("proxy_pool_id %q not found", route.ProxyPoolID)}
|
||||
return ContainerProxyRoute{}, &proxyRouteValidationError{
|
||||
code: "proxy_pool_node_not_found",
|
||||
msg: fmt.Sprintf("proxy_pool_id %q not found", route.ProxyPoolID),
|
||||
params: map[string]any{"id": route.ProxyPoolID},
|
||||
}
|
||||
}
|
||||
route.ProxyPoolID = id
|
||||
route.ProxyURL = ""
|
||||
@@ -227,7 +248,11 @@ func (s *Server) validateAndNormalizeProxyRoute(req ProxyRouteInput, prev *Conta
|
||||
route.ProxyURL = prev.ProxyURL
|
||||
}
|
||||
if _, err := traffic.ValidateProxyURL(route.ProxyURL); err != nil {
|
||||
return ContainerProxyRoute{}, &proxyRouteValidationError{err.Error()}
|
||||
return ContainerProxyRoute{}, &proxyRouteValidationError{
|
||||
code: "proxy_route_invalid_url",
|
||||
msg: err.Error(),
|
||||
params: map[string]any{"detail": err.Error()},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -238,7 +263,10 @@ func (s *Server) setContainerProxyRoute(scope, ownerID string, req ProxyRouteInp
|
||||
scope = strings.ToLower(strings.TrimSpace(scope))
|
||||
ownerID = strings.TrimSpace(ownerID)
|
||||
if (scope != "task" && scope != "session") || ownerID == "" {
|
||||
return ContainerProxyRoute{}, &proxyRouteValidationError{"invalid scope or owner_id (scope must be task or session)"}
|
||||
return ContainerProxyRoute{}, &proxyRouteValidationError{
|
||||
code: "proxy_route_invalid_target",
|
||||
msg: "invalid scope or owner_id (scope must be task or session)",
|
||||
}
|
||||
}
|
||||
rt := s.ensureRouteRuntime()
|
||||
key := scope + ":" + ownerID
|
||||
@@ -510,7 +538,7 @@ func (s *Server) getProxyRoute(w http.ResponseWriter, r *http.Request) {
|
||||
scope := strings.ToLower(strings.TrimSpace(r.PathValue("scope")))
|
||||
ownerID := strings.TrimSpace(r.PathValue("owner_id"))
|
||||
if (scope != "task" && scope != "session") || ownerID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "invalid scope or owner_id (scope must be task or session)")
|
||||
writeProductError(w, http.StatusBadRequest, "proxy_route_invalid_target", "invalid scope or owner_id (scope must be task or session)", nil)
|
||||
return
|
||||
}
|
||||
item, globalDisplay := s.containerProxyRouteView(scope, ownerID)
|
||||
@@ -539,7 +567,7 @@ func (s *Server) putProxyRoute(w http.ResponseWriter, r *http.Request) {
|
||||
route, err := s.setContainerProxyRoute(scope, ownerID, req)
|
||||
if err != nil {
|
||||
if _, ok := err.(*proxyRouteValidationError); ok {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
writeProxyRouteErr(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
|
||||
@@ -436,3 +436,61 @@ func TestProxyScheduleAndTaskMentionWithPostgres(t *testing.T) {
|
||||
t.Fatalf("expected task snapshot with proxy_route in mention message, got: %s", injected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateScheduleProxyUnchangedAndErrorCodes(t *testing.T) {
|
||||
m := &Manager{
|
||||
tasks: map[string]*Task{},
|
||||
proxyPool: &proxyPoolState{entries: nil},
|
||||
}
|
||||
s := &Server{m: m}
|
||||
s.initProxyRoutesAndGateway()
|
||||
|
||||
// 1. Existing schedule with proxy_mode=pool can still be rescheduled/updated when pool has no active nodes.
|
||||
existingPool := &db.TaskSchedule{ID: 9, Name: "nightly", ProxyMode: "pool"}
|
||||
inUnchanged := db.TaskScheduleInput{Name: "nightly", ProxyMode: "pool"}
|
||||
if err := s.validateScheduleProxy(&inUnchanged, existingPool); err != nil {
|
||||
t.Fatalf("expected unchanged pool schedule update to succeed with empty pool, got: %v", err)
|
||||
}
|
||||
if inUnchanged.ProxyMode != "pool" || inUnchanged.ProxyPoolID != "" || inUnchanged.ProxyURL != "" {
|
||||
t.Fatalf("unexpected normalized unchanged pool input: %+v", inUnchanged)
|
||||
}
|
||||
|
||||
// 2. Existing schedule with masked custom proxy URL keeps raw secret when unchanged.
|
||||
existingURL := &db.TaskSchedule{ID: 10, Name: "custom", ProxyMode: "proxy", ProxyURL: "http://alice:[email protected]:8080"}
|
||||
inMasked := db.TaskScheduleInput{Name: "custom", ProxyMode: "proxy", ProxyURL: "http://alice:***@127.0.0.1:8080"}
|
||||
if err := s.validateScheduleProxy(&inMasked, existingURL); err != nil {
|
||||
t.Fatalf("expected unchanged masked proxy URL update to succeed, got: %v", err)
|
||||
}
|
||||
if inMasked.ProxyURL != existingURL.ProxyURL {
|
||||
t.Fatalf("expected raw proxy URL preserved, got %q", inMasked.ProxyURL)
|
||||
}
|
||||
|
||||
// 3. Newly selecting mode=pool with empty pool fails with structured error code.
|
||||
existingInherit := &db.TaskSchedule{ID: 11, Name: "inherit", ProxyMode: "inherit"}
|
||||
inSwitchToPool := db.TaskScheduleInput{Name: "inherit", ProxyMode: "pool"}
|
||||
err := s.validateScheduleProxy(&inSwitchToPool, existingInherit)
|
||||
verr, ok := err.(*proxyRouteValidationError)
|
||||
if !ok || verr.code != "proxy_pool_no_available_nodes" {
|
||||
t.Fatalf("expected proxy_pool_no_available_nodes error, got %T %v", err, err)
|
||||
}
|
||||
|
||||
// 4. HTTP PUT /api/proxy/routes/task/5 returns structured code for i18n clients.
|
||||
req := httptest.NewRequest(http.MethodPut, "/api/proxy/routes/task/5", bytes.NewBufferString(`{"mode":"pool"}`))
|
||||
req.SetPathValue("scope", "task")
|
||||
req.SetPathValue("owner_id", "5")
|
||||
rec := httptest.NewRecorder()
|
||||
s.putProxyRoute(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var payload struct {
|
||||
Error string `json:"error"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("decode error payload: %v", err)
|
||||
}
|
||||
if payload.Code != "proxy_pool_no_available_nodes" || payload.Error == "" {
|
||||
t.Fatalf("unexpected error payload: %+v", payload)
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,21 @@ import (
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
func TestChatMentionScheduleParsing(t *testing.T) {
|
||||
refs, err := parseChatMentions("请修改 @[计划任务#3 夜间扫描] 和 @[schedule#3 重复] 以及 @[schedule#9 应急复测] 和 @[计划#12 周末巡检]")
|
||||
if err != nil {
|
||||
t.Fatalf("parseChatMentions error: %v", err)
|
||||
}
|
||||
if len(refs) != 3 {
|
||||
t.Fatalf("expected 3 deduplicated schedule refs, got %+v", refs)
|
||||
}
|
||||
for i, wantID := range []int64{3, 9, 12} {
|
||||
if refs[i].Kind != "schedule" || refs[i].ID != wantID {
|
||||
t.Fatalf("ref[%d] = %+v, want schedule #%d", i, refs[i], wantID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func TestChatScheduleToolsAndServerClock(t *testing.T) {
|
||||
dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN"))
|
||||
@@ -95,6 +110,31 @@ func TestChatScheduleToolsAndServerClock(t *testing.T) {
|
||||
t.Fatalf("update_task_schedule failed: err=%v res=%+v", err, updRes)
|
||||
}
|
||||
updText := ""
|
||||
// 2b. Search schedule mentions via DB and compose @[schedule#ID] snapshot.
|
||||
page, err := pg.SearchChatMentionsPage(context.Background(), "schedule", "工作日", "")
|
||||
if err != nil {
|
||||
t.Fatalf("SearchChatMentionsPage(schedule): %v", err)
|
||||
}
|
||||
foundMention := false
|
||||
for _, item := range page.Items {
|
||||
if item.Kind == "schedule" && item.ID == schedID {
|
||||
foundMention = true
|
||||
if !strings.Contains(item.Description, "18:00-23:45") {
|
||||
t.Fatalf("expected schedule time window in mention description, got %+v", item)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !foundMention {
|
||||
t.Fatalf("expected schedule #%d in SearchChatMentionsPage results, got %+v", schedID, page.Items)
|
||||
}
|
||||
injected, err := composeChatMentionMessage(pg, fmt.Sprintf("把 @[schedule#%d 工作日夜间扫描] 改成 23:45 结束", schedID))
|
||||
if err != nil {
|
||||
t.Fatalf("composeChatMentionMessage(schedule): %v", err)
|
||||
}
|
||||
if !strings.Contains(injected, "工作日夜间扫描") || !strings.Contains(injected, `"proxy_mode":"pool"`) || !strings.Contains(injected, `"server_time"`) {
|
||||
t.Fatalf("unexpected injected schedule snapshot: %s", injected)
|
||||
}
|
||||
|
||||
for _, b := range updRes.Content {
|
||||
updText += b.Text
|
||||
}
|
||||
@@ -122,4 +162,8 @@ func TestChatScheduleToolsAndServerClock(t *testing.T) {
|
||||
if err != nil || delRes.IsError {
|
||||
t.Fatalf("delete_task_schedule failed: err=%v res=%+v", err, delRes)
|
||||
}
|
||||
// Verify deleted schedule mention returns a clean input error.
|
||||
if _, err := composeChatMentionMessage(pg, fmt.Sprintf("查看 @[schedule#%d 已删]", schedID)); err == nil {
|
||||
t.Fatalf("expected error for deleted schedule mention")
|
||||
}
|
||||
}
|
||||
+46
-9
@@ -56,18 +56,55 @@ func (s *Server) scheduleInput(req scheduleRequest, existing *db.TaskSchedule) d
|
||||
}
|
||||
|
||||
func (s *Server) validateScheduleProxy(in *db.TaskScheduleInput, existing *db.TaskSchedule) error {
|
||||
inMode := strings.ToLower(strings.TrimSpace(in.ProxyMode))
|
||||
if inMode == "" {
|
||||
inMode = "inherit"
|
||||
}
|
||||
inPoolID := strings.TrimSpace(in.ProxyPoolID)
|
||||
inURL := strings.TrimSpace(in.ProxyURL)
|
||||
|
||||
var prev *ContainerProxyRoute
|
||||
if existing != nil && existing.ProxyURL != "" {
|
||||
if existing != nil {
|
||||
oldMode := strings.ToLower(strings.TrimSpace(existing.ProxyMode))
|
||||
if oldMode == "" {
|
||||
oldMode = "inherit"
|
||||
}
|
||||
oldPoolID := strings.TrimSpace(existing.ProxyPoolID)
|
||||
oldURL := strings.TrimSpace(existing.ProxyURL)
|
||||
prev = &ContainerProxyRoute{
|
||||
Mode: existing.ProxyMode,
|
||||
ProxyPoolID: existing.ProxyPoolID,
|
||||
ProxyURL: existing.ProxyURL,
|
||||
Mode: oldMode,
|
||||
ProxyPoolID: oldPoolID,
|
||||
ProxyURL: oldURL,
|
||||
}
|
||||
// Allow editing/rescheduling an existing plan without re-validating unchanged proxy routes
|
||||
// (e.g. dragging a schedule whose proxy_mode is already "pool" when the live pool is temporarily empty).
|
||||
if inMode == oldMode {
|
||||
switch oldMode {
|
||||
case "inherit", "direct", "pool":
|
||||
in.ProxyMode = oldMode
|
||||
in.ProxyPoolID = ""
|
||||
in.ProxyURL = ""
|
||||
return nil
|
||||
case "proxy":
|
||||
if oldPoolID != "" && inPoolID == oldPoolID && inURL == "" {
|
||||
in.ProxyMode = "proxy"
|
||||
in.ProxyPoolID = oldPoolID
|
||||
in.ProxyURL = ""
|
||||
return nil
|
||||
}
|
||||
if oldPoolID == "" && inPoolID == "" && oldURL != "" && (inURL == oldURL || strings.Contains(inURL, "***")) {
|
||||
in.ProxyMode = "proxy"
|
||||
in.ProxyPoolID = ""
|
||||
in.ProxyURL = oldURL
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
norm, err := s.validateAndNormalizeProxyRoute(ProxyRouteInput{
|
||||
Mode: in.ProxyMode,
|
||||
ProxyPoolID: in.ProxyPoolID,
|
||||
ProxyURL: in.ProxyURL,
|
||||
Mode: inMode,
|
||||
ProxyPoolID: inPoolID,
|
||||
ProxyURL: inURL,
|
||||
}, prev)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -197,7 +234,7 @@ func (s *Server) createSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
input := s.scheduleInput(req, nil)
|
||||
if err := s.validateScheduleProxy(&input, nil); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
writeProxyRouteErr(w, 400, err)
|
||||
return
|
||||
}
|
||||
item, err := s.m.pg.CreateTaskSchedule(input)
|
||||
@@ -230,7 +267,7 @@ func (s *Server) updateSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
input := s.scheduleInput(req, old)
|
||||
if err := s.validateScheduleProxy(&input, old); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
writeProxyRouteErr(w, 400, err)
|
||||
return
|
||||
}
|
||||
item, err := s.m.pg.UpdateTaskSchedule(id, input)
|
||||
|
||||
+29
-17
@@ -1833,6 +1833,8 @@ type createTaskReq struct {
|
||||
type taskCreateError struct {
|
||||
Status int
|
||||
Msg string
|
||||
Code string
|
||||
Params map[string]any
|
||||
}
|
||||
|
||||
func (s *Server) createTask(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -1843,7 +1845,11 @@ func (s *Server) createTask(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
t, cerr := s.createTaskFromRequest(req)
|
||||
if cerr != nil {
|
||||
writeErr(w, cerr.Status, cerr.Msg)
|
||||
if cerr.Code != "" {
|
||||
writeProductError(w, cerr.Status, cerr.Code, cerr.Msg, cerr.Params)
|
||||
} else {
|
||||
writeErr(w, cerr.Status, cerr.Msg)
|
||||
}
|
||||
return
|
||||
}
|
||||
dto := taskDTO(t, s.resolvedTaskStatus(t))
|
||||
@@ -1862,48 +1868,51 @@ func (s *Server) createTaskFromRequest(req createTaskReq) (*Task, *taskCreateErr
|
||||
req.LLMProfileIDs = []int64{*req.LLMProfileID}
|
||||
}
|
||||
if err := s.validateTaskProfileIDs(req.LLMProfileIDs); err != nil {
|
||||
return nil, &taskCreateError{400, err.Error()}
|
||||
return nil, &taskCreateError{Status: 400, Msg: err.Error()}
|
||||
}
|
||||
if err := db.NormalizeNoResultOptions(&db.TaskCreateOptions{NoResultSeconds: req.NoResultSeconds, NoResultMinFindings: req.NoResultMinFindings, NoResultMinSeverity: req.NoResultMinSeverity}); err != nil {
|
||||
return nil, &taskCreateError{400, err.Error()}
|
||||
return nil, &taskCreateError{Status: 400, Msg: err.Error()}
|
||||
}
|
||||
if req.TimeoutSeconds < 0 {
|
||||
req.TimeoutSeconds = 0
|
||||
}
|
||||
if len(req.SourceTaskIDs) > db.MaxTaskSourceCount {
|
||||
return nil, &taskCreateError{400, fmt.Sprintf("关联任务最多选择 %d 个", db.MaxTaskSourceCount)}
|
||||
return nil, &taskCreateError{Status: 400, Msg: fmt.Sprintf("关联任务最多选择 %d 个", db.MaxTaskSourceCount)}
|
||||
}
|
||||
sourceIDs := make([]int64, 0, len(req.SourceTaskIDs))
|
||||
seenSources := map[int64]bool{}
|
||||
for _, raw := range req.SourceTaskIDs {
|
||||
id, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
|
||||
if err != nil || id <= 0 || seenSources[id] {
|
||||
return nil, &taskCreateError{400, "关联任务 id 无效或重复"}
|
||||
return nil, &taskCreateError{Status: 400, Msg: "关联任务 id 无效或重复"}
|
||||
}
|
||||
if _, ok := s.m.Task(strconv.FormatInt(id, 10)); !ok {
|
||||
return nil, &taskCreateError{400, fmt.Sprintf("关联任务 #%d 不存在", id)}
|
||||
return nil, &taskCreateError{Status: 400, Msg: fmt.Sprintf("关联任务 #%d 不存在", id)}
|
||||
}
|
||||
seenSources[id] = true
|
||||
sourceIDs = append(sourceIDs, id)
|
||||
}
|
||||
companyIDs, err := db.NormalizeTaskCompanyIDs(req.CompanyIDs)
|
||||
if err != nil {
|
||||
return nil, &taskCreateError{400, fmt.Sprintf("关联企业无效:最多选择 %d 个有效企业", db.MaxTaskCompanyCount)}
|
||||
return nil, &taskCreateError{Status: 400, Msg: fmt.Sprintf("关联企业无效:最多选择 %d 个有效企业", db.MaxTaskCompanyCount)}
|
||||
}
|
||||
req.CompanyIDs = companyIDs
|
||||
interceptRules, err := buildTaskInterceptRules(req.InterceptRules)
|
||||
if err != nil {
|
||||
return nil, &taskCreateError{400, "任务级拦截规则无效:" + err.Error()}
|
||||
return nil, &taskCreateError{Status: 400, Msg: "任务级拦截规则无效:" + err.Error()}
|
||||
}
|
||||
var schedule *db.TaskScheduleInput
|
||||
if req.Schedule != nil {
|
||||
input := s.scheduleInput(*req.Schedule, nil)
|
||||
input.TaskIDs = nil
|
||||
if err := db.ValidateTaskScheduleInput(input); err != nil {
|
||||
return nil, &taskCreateError{400, err.Error()}
|
||||
return nil, &taskCreateError{Status: 400, Msg: err.Error()}
|
||||
}
|
||||
if err := s.validateScheduleProxy(&input, nil); err != nil {
|
||||
return nil, &taskCreateError{400, err.Error()}
|
||||
if verr, ok := err.(*proxyRouteValidationError); ok {
|
||||
return nil, &taskCreateError{Status: 400, Msg: verr.msg, Code: verr.code, Params: verr.params}
|
||||
}
|
||||
return nil, &taskCreateError{Status: 400, Msg: err.Error()}
|
||||
}
|
||||
schedule = &input
|
||||
}
|
||||
@@ -1911,7 +1920,10 @@ func (s *Server) createTaskFromRequest(req createTaskReq) (*Task, *taskCreateErr
|
||||
if req.ProxyRoute != nil {
|
||||
norm, err := s.validateAndNormalizeProxyRoute(*req.ProxyRoute, nil)
|
||||
if err != nil {
|
||||
return nil, &taskCreateError{400, "任务代理配置无效:" + err.Error()}
|
||||
if verr, ok := err.(*proxyRouteValidationError); ok {
|
||||
return nil, &taskCreateError{Status: 400, Msg: verr.msg, Code: verr.code, Params: verr.params}
|
||||
}
|
||||
return nil, &taskCreateError{Status: 400, Msg: "任务代理配置无效:" + err.Error()}
|
||||
}
|
||||
if norm.Mode != "inherit" {
|
||||
validatedProxy = &ProxyRouteInput{
|
||||
@@ -1935,13 +1947,13 @@ func (s *Server) createTaskFromRequest(req createTaskReq) (*Task, *taskCreateErr
|
||||
}
|
||||
remark, err := normalizeRemark(req.Remark)
|
||||
if err != nil {
|
||||
return nil, &taskCreateError{400, err.Error()}
|
||||
return nil, &taskCreateError{Status: 400, Msg: err.Error()}
|
||||
}
|
||||
if req.WorkerCount < 0 {
|
||||
return nil, &taskCreateError{400, "Worker 运行数量不能为负数"}
|
||||
return nil, &taskCreateError{Status: 400, Msg: "Worker 运行数量不能为负数"}
|
||||
}
|
||||
if req.WorkerCount > db.MaxTaskWorkerCount {
|
||||
return nil, &taskCreateError{400, fmt.Sprintf("Worker 运行数量最多 %d", db.MaxTaskWorkerCount)}
|
||||
return nil, &taskCreateError{Status: 400, Msg: fmt.Sprintf("Worker 运行数量最多 %d", db.MaxTaskWorkerCount)}
|
||||
}
|
||||
t, err := s.m.CreateTaskWithOptions(req.Description, req.Goal, db.TaskCreateOptions{
|
||||
Schedule: schedule,
|
||||
@@ -1957,12 +1969,12 @@ func (s *Server) createTaskFromRequest(req createTaskReq) (*Task, *taskCreateErr
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrTaskCategoryInvalid) || errors.Is(err, db.ErrTaskCategoryNotFound) {
|
||||
return nil, &taskCreateError{400, "任务分类不存在或无效"}
|
||||
return nil, &taskCreateError{Status: 400, Msg: "任务分类不存在或无效"}
|
||||
}
|
||||
if errors.Is(err, db.ErrTaskCompanyIDsInvalid) || errors.Is(err, db.ErrTaskCompanyNotFound) {
|
||||
return nil, &taskCreateError{400, "关联企业不存在或无效"}
|
||||
return nil, &taskCreateError{Status: 400, Msg: "关联企业不存在或无效"}
|
||||
}
|
||||
return nil, &taskCreateError{500, err.Error()}
|
||||
return nil, &taskCreateError{Status: 500, Msg: err.Error()}
|
||||
}
|
||||
if newDesc, newGoal, copied := transferDraftUploadsToTask(s.m.dir, t.ID, req.Description, req.Goal); copied > 0 {
|
||||
req.Description, req.Goal = newDesc, newGoal
|
||||
|
||||
Reference in new issue
Block a user