From 73a471f3a8b1cdf5dfe371184dfc3579cdcbefcc Mon Sep 17 00:00:00 2001 From: CaIon Date: Thu, 17 Sep 2026 16:16:37 +0800 Subject: [PATCH] feat(policy): add request policies settings and routing decision records Group sensitive-word checks, channel selection, retries and channel health under one "Request policies" settings area with a session rules editor, per-rule session modes (inherit/off/prefer/strict) and a global default. Record routing decisions per attempt into log admin info, expose GET/PATCH /api/option/request_policy with whole-policy validation, and redirect the legacy settings URLs to the new sections. --- controller/channel.go | 19 +- controller/channel_pin_retry_test.go | 140 ++- controller/relay.go | 119 ++- controller/relay_task_plugin_test.go | 19 +- controller/request_policy.go | 27 + middleware/distributor.go | 10 + model/option.go | 33 + model/request_policy.go | 258 ++++++ model/request_policy_test.go | 122 +++ relay/mjproxy_handler.go | 32 +- relay/request_billing.go | 1 + router/api-router.go | 2 + service/channel_affinity.go | 19 +- service/channel_affinity_template_test.go | 133 +++ service/log_info_generate.go | 4 + service/midjourney.go | 34 +- service/relay_error.go | 45 +- service/relay_error_test.go | 87 ++ service/request_policy.go | 182 ++++ .../channel_affinity_setting.go | 7 +- web/.oxlintrc.json | 3 + .../layout/config/system-settings.config.ts | 11 +- web/src/features/channels/api.ts | 9 +- .../__tests__/channel-configuration.test.tsx | 36 +- .../__tests__/inference-status.test.tsx | 26 +- .../components/channel-quick-options.tsx | 3 +- web/src/features/channels/index.tsx | 4 +- web/src/features/channels/types.ts | 4 + .../components/api-keys-mutate-drawer.tsx | 2 + .../components/settings-accordion.tsx | 6 +- .../components/settings-page.tsx | 14 +- .../general/channel-affinity/index.tsx | 735 +++++----------- .../channel-affinity/rule-editor-dialog.tsx | 60 +- .../channel-affinity/session-rules-table.tsx | 298 +++++++ .../general/channel-affinity/types.ts | 4 + .../features/system-settings/models/index.tsx | 18 - .../models/section-registry.tsx | 52 +- .../__tests__/routing.test.tsx | 797 ++++++++++++++++++ .../__tests__/settings.test.tsx | 368 ++++++++ .../system-settings/request-policies/api.ts | 33 + .../channel-health-section.tsx} | 225 ++--- .../request-policies/decision-record.tsx | 54 ++ .../request-policies/defaults.ts | 72 ++ .../request-policies/index.tsx | 36 + .../request-policies/policy-label.ts | 79 ++ .../request-policies/related-policy-link.tsx | 55 ++ .../request-checks-section.tsx} | 103 ++- .../request-policies/retry-section.tsx | 86 ++ .../request-policies/routing-form.ts | 82 ++ .../request-policies/routing-section.tsx | 329 ++++++++ .../request-policies/section-registry.tsx | 63 ++ .../request-policies/use-save-policy.ts | 23 + .../security/section-registry.tsx | 15 +- web/src/features/system-settings/types.ts | 20 - .../components/dialogs/details-dialog.tsx | 9 + web/src/features/usage-logs/types.ts | 2 + web/src/i18n/locales/en.json | 95 ++- web/src/i18n/locales/fr.json | 95 ++- web/src/i18n/locales/ja.json | 95 ++- web/src/i18n/locales/ru.json | 95 ++- web/src/i18n/locales/vi.json | 95 ++- web/src/i18n/locales/zh-TW.json | 95 ++- web/src/i18n/locales/zh.json | 95 ++- web/src/routeTree.gen.ts | 46 + .../system-settings/models/$section.tsx | 14 + .../system-settings/operations/$section.tsx | 5 +- .../request-policies/$section.tsx | 37 + .../request-policies/index.tsx | 31 + .../system-settings/security/$section.tsx | 7 + 69 files changed, 4891 insertions(+), 943 deletions(-) create mode 100644 controller/request_policy.go create mode 100644 model/request_policy.go create mode 100644 model/request_policy_test.go create mode 100644 service/request_policy.go create mode 100644 web/src/features/system-settings/general/channel-affinity/session-rules-table.tsx create mode 100644 web/src/features/system-settings/request-policies/__tests__/routing.test.tsx create mode 100644 web/src/features/system-settings/request-policies/__tests__/settings.test.tsx create mode 100644 web/src/features/system-settings/request-policies/api.ts rename web/src/features/system-settings/{models/routing-reliability-section.tsx => request-policies/channel-health-section.tsx} (75%) create mode 100644 web/src/features/system-settings/request-policies/decision-record.tsx create mode 100644 web/src/features/system-settings/request-policies/defaults.ts create mode 100644 web/src/features/system-settings/request-policies/index.tsx create mode 100644 web/src/features/system-settings/request-policies/policy-label.ts create mode 100644 web/src/features/system-settings/request-policies/related-policy-link.tsx rename web/src/features/system-settings/{request-limits/sensitive-words-section.tsx => request-policies/request-checks-section.tsx} (58%) create mode 100644 web/src/features/system-settings/request-policies/retry-section.tsx create mode 100644 web/src/features/system-settings/request-policies/routing-form.ts create mode 100644 web/src/features/system-settings/request-policies/routing-section.tsx create mode 100644 web/src/features/system-settings/request-policies/section-registry.tsx create mode 100644 web/src/features/system-settings/request-policies/use-save-policy.ts create mode 100644 web/src/routes/_authenticated/system-settings/request-policies/$section.tsx create mode 100644 web/src/routes/_authenticated/system-settings/request-policies/index.tsx diff --git a/controller/channel.go b/controller/channel.go index 997c541c61..a20b9a1c20 100644 --- a/controller/channel.go +++ b/controller/channel.go @@ -156,8 +156,25 @@ func buildChannelListQuery(group string, statusFilter int, typeFilter int) *gorm } func GetChannelOps(c *gin.Context) { + snapshot := model.CurrentRequestPolicy() + automaticDisable, source := snapshot.AutoDisable, "global" + if value, present := c.GetQuery("auto_ban"); present { + autoBan, err := strconv.ParseBool(value) + if err != nil { + common.ApiError(c, err) + return + } + automaticDisable = snapshot.AutoDisable && autoBan + if snapshot.AutoDisable { + source = "global_and_channel" + if !autoBan { + source = "channel" + } + } + } common.ApiSuccess(c, gin.H{ - "retry_times": common.RetryTimes, + "retry_times": snapshot.RetryTimes, + "request_policy": gin.H{"automatic_disable": automaticDisable, "source": source}, }) } diff --git a/controller/channel_pin_retry_test.go b/controller/channel_pin_retry_test.go index f79b7b8b11..05013bd0f9 100644 --- a/controller/channel_pin_retry_test.go +++ b/controller/channel_pin_retry_test.go @@ -2,13 +2,25 @@ package controller import ( "errors" + "fmt" + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/constant" + "github.com/QuantumNous/new-api/i18n" + "github.com/QuantumNous/new-api/middleware" + "github.com/QuantumNous/new-api/model" + "github.com/QuantumNous/new-api/setting" + "github.com/QuantumNous/new-api/setting/operation_setting" + "github.com/QuantumNous/new-api/setting/ratio_setting" "net/http" "net/http/httptest" + "os" + "slices" + "strings" "testing" "github.com/QuantumNous/new-api/dto" - "github.com/QuantumNous/new-api/service" "github.com/QuantumNous/new-api/relaykit/types" + "github.com/QuantumNous/new-api/service" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -18,7 +30,7 @@ func TestShouldRetryHonorsPinRetryMode(t *testing.T) { openaiErr := types.NewOpenAIError(errors.New("upstream"), types.ErrorCodeBadResponseStatusCode, http.StatusInternalServerError) c := newPinRetryContext() - assert.True(t, shouldRetry(c, openaiErr, 1)) + assert.True(t, service.ShouldRetryRelayError(c, openaiErr, 1)) origin := newPinRetryContext() service.GetChannelConstraints(origin).AddPin(dto.ChannelPin{ @@ -27,7 +39,7 @@ func TestShouldRetryHonorsPinRetryMode(t *testing.T) { Rank: dto.PinRankOriginTask, RetryMode: dto.PinRetrySameChannel, }) - assert.True(t, shouldRetry(origin, openaiErr, 1), "origin pin retries on the same channel") + assert.True(t, service.ShouldRetryRelayError(origin, openaiErr, 1), "origin pin retries on the same channel") token := newPinRetryContext() service.GetChannelConstraints(token).AddPin(dto.ChannelPin{ @@ -36,14 +48,14 @@ func TestShouldRetryHonorsPinRetryMode(t *testing.T) { Rank: dto.PinRankToken, RetryMode: dto.PinRetrySingleAttempt, }) - assert.False(t, shouldRetry(token, openaiErr, 1), "token pin suppresses retry") + assert.Equal(t, service.PolicyDecision{Action: "stop", Reason: "pinned_channel", Source: "channel_constraint"}, service.DecideRelayRetry(token, openaiErr, 1), "token pin suppresses retry") } func TestShouldRetryTaskRelayHonorsPinRetryMode(t *testing.T) { taskErr := &dto.TaskError{StatusCode: http.StatusInternalServerError} c := newPinRetryContext() - assert.True(t, shouldRetryTaskRelay(c, 1, taskErr, 1)) + assert.Equal(t, "retry", decideTaskRetry(c, taskErr, 1).Action) origin := newPinRetryContext() service.GetChannelConstraints(origin).AddPin(dto.ChannelPin{ @@ -52,7 +64,7 @@ func TestShouldRetryTaskRelayHonorsPinRetryMode(t *testing.T) { Rank: dto.PinRankOriginTask, RetryMode: dto.PinRetrySameChannel, }) - assert.True(t, shouldRetryTaskRelay(origin, 2, taskErr, 1)) + assert.Equal(t, "retry", decideTaskRetry(origin, taskErr, 1).Action) token := newPinRetryContext() service.GetChannelConstraints(token).AddPin(dto.ChannelPin{ @@ -61,7 +73,7 @@ func TestShouldRetryTaskRelayHonorsPinRetryMode(t *testing.T) { Rank: dto.PinRankToken, RetryMode: dto.PinRetrySingleAttempt, }) - assert.False(t, shouldRetryTaskRelay(token, 1, taskErr, 1)) + assert.Equal(t, service.PolicyDecision{Action: "stop", Reason: "pinned_channel", Source: "channel_constraint"}, decideTaskRetry(token, taskErr, 1)) } func TestSameChannelPinsMergeToStricterRetryMode(t *testing.T) { @@ -84,7 +96,7 @@ func TestSameChannelPinsMergeToStricterRetryMode(t *testing.T) { assert.Equal(t, 7, pin.ChannelId) assert.Equal(t, dto.PinRetrySingleAttempt, pin.RetryMode) assert.Empty(t, overridden) - assert.False(t, shouldRetry(c, types.NewOpenAIError(errors.New("upstream"), types.ErrorCodeBadResponseStatusCode, http.StatusInternalServerError), 1)) + assert.False(t, service.ShouldRetryRelayError(c, types.NewOpenAIError(errors.New("upstream"), types.ErrorCodeBadResponseStatusCode, http.StatusInternalServerError), 1)) } func newPinRetryContext() *gin.Context { @@ -93,3 +105,115 @@ func newPinRetryContext() *gin.Context { c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) return c } + +func TestRequestPolicyConfigReturnsSettingsWithoutMigration(t *testing.T) { + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + GetRequestPolicy(ctx) + assert.Equal(t, http.StatusOK, recorder.Code) + var response struct { + Success bool `json:"success"` + Data map[string]any `json:"data"` + } + require.NoError(t, common.Unmarshal(recorder.Body.Bytes(), &response)) + assert.True(t, response.Success) + assert.Contains(t, response.Data, "options") + assert.NotContains(t, response.Data, "migration") + assert.NotContains(t, response.Data, "differences") +} + +func TestRequestPolicyRoutingDatabaseMatrix(t *testing.T) { + require.NoError(t, i18n.Init()) + for _, dialect := range []struct{ kind, env string }{{"sqlite", ""}, {"mysql", "TEST_MYSQL_DSN"}, {"postgres", "TEST_POSTGRES_DSN"}} { + t.Run(dialect.kind, func(t *testing.T) { + dsn := "" + if dialect.env != "" { + dsn = os.Getenv(dialect.env) + if dsn == "" { + t.Skipf("%s not configured", dialect.env) + } + } + db := modelManagementDB(t, dialect.kind, dsn) + previousGroups := setting.UserUsableGroups2JSONString() + previousRatios, err := common.Marshal(ratio_setting.GetGroupRatioCopy()) + require.NoError(t, err) + require.NoError(t, setting.UpdateUserUsableGroupsByJSONString(`{"default":"Default"}`)) + require.NoError(t, ratio_setting.UpdateGroupRatioByJSONString(`{"default":1}`)) + t.Cleanup(func() { + require.NoError(t, setting.UpdateUserUsableGroupsByJSONString(previousGroups)) + require.NoError(t, ratio_setting.UpdateGroupRatioByJSONString(string(previousRatios))) + }) + // Channel 1 holds the session binding but is no longer usable. + channels := []model.Channel{ + {Id: 1, Name: "A", Type: 1, Key: "test-only", Status: common.ChannelStatusAutoDisabled, Models: "policy-test", Group: "default", Priority: common.GetPointer(int64(10))}, + {Id: 2, Name: "B", Type: 1, Key: "test-only", Status: common.ChannelStatusEnabled, Models: "policy-test", Group: "default", Priority: common.GetPointer(int64(5))}, + } + for i := range channels { + require.NoError(t, db.Create(&channels[i]).Error) + require.NoError(t, channels[i].AddAbilities(db)) + } + affinity := operation_setting.GetChannelAffinitySetting() + previousAffinity := *affinity + t.Cleanup(func() { *affinity = previousAffinity }) + for _, cached := range []bool{false, true} { + for _, keep := range []bool{false, true} { + for _, tc := range []struct { + globalMode, ruleMode string + blocked bool + }{ + {"strict", "inherit", true}, + {"prefer", "strict", true}, + {"prefer", "inherit", false}, + {"strict", "prefer", false}, + } { + t.Run(fmt.Sprintf("cache=%t/keep=%t/global=%s/rule=%s", cached, keep, tc.globalMode, tc.ruleMode), func(t *testing.T) { + common.MemoryCacheEnabled = cached + model.InitChannelCache() + snapshot, err := model.BuildRequestPolicy(map[string]string{ + "channel_affinity_setting.enabled": "true", + "channel_affinity_setting.session_mode": tc.globalMode, + "channel_affinity_setting.keep_on_channel_disabled": fmt.Sprint(keep), + "channel_affinity_setting.rules": fmt.Sprintf(`[{"name":"session","model_regex":[".*"],"key_sources":[{"type":"request_header","key":"X-Session"}],"session_mode":%q}]`, tc.ruleMode), + }) + require.NoError(t, err) + *affinity = snapshot.Affinity + seed := newPinRetryContext() + seed.Request.Header.Set("X-Session", t.Name()) + _, found := service.GetPreferredChannelByAffinity(seed, "policy-test", "default") + require.False(t, found) + seed.Set("channel_id", 1) + service.RecordChannelAffinity(seed, 1) + t.Cleanup(func() { service.ClearCurrentChannelAffinityCache(seed) }) + bound, found := service.GetPreferredChannelByAffinity(seed, "policy-test", "default") + require.True(t, found) + require.Equal(t, 1, bound) + + request := newPinRetryContext() + request.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"policy-test"}`)) + request.Request.Header.Set("Content-Type", "application/json") + request.Request.Header.Set("X-Session", t.Name()) + common.SetContextKey(request, constant.ContextKeyUsingGroup, "default") + middleware.Distribute()(request) + events := service.RequestPolicy(request).Events() + assert.True(t, slices.ContainsFunc(events, func(event service.PolicyEvent) bool { return event.Decision.Reason == "session_rule_matched" }), "decision events are recorded for every request") + bound, found = service.GetPreferredChannelByAffinity(seed, "policy-test", "default") + if tc.blocked { + assert.Equal(t, http.StatusServiceUnavailable, request.Writer.Status()) + assert.True(t, request.IsAborted()) + assert.Equal(t, keep, found, "binding retention is independent of strict request handling") + if found { + assert.Equal(t, 1, bound) + } + return + } + assert.False(t, request.IsAborted()) + assert.Equal(t, 2, common.GetContextKeyInt(request, constant.ContextKeyChannelId), "prefer falls back to the next eligible channel") + require.True(t, found) + assert.Equal(t, 2, bound, "a successful fallback rebinds the session") + }) + } + } + } + }) + } +} diff --git a/controller/relay.go b/controller/relay.go index 0129934b1f..f7315361ea 100644 --- a/controller/relay.go +++ b/controller/relay.go @@ -90,6 +90,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) { defer func() { if newAPIError != nil { + service.RecordRequestPolicyTermination(c, newAPIError) logger.LogError(c, fmt.Sprintf("relay error: %s", common.LocalLogPreview(newAPIError.Error()))) newAPIError.SetMessage(common.MessageWithRequestId(newAPIError.Error(), requestId)) switch relayFormat { @@ -180,6 +181,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) { } if newAPIError == nil { + service.MarkRequestPolicySuccess(c, relayInfo.StreamStatus) relayInfo.LastError = nil return } @@ -187,9 +189,11 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) { newAPIError = service.NormalizeViolationFeeError(newAPIError) relayInfo.LastError = newAPIError + decision := service.DecideRelayRetry(c, newAPIError, common.RetryTimes-retryParam.GetRetry()) + service.RecordPolicyFailure(c, channel.Id, newAPIError, decision) processChannelError(c, *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()), newAPIError, relayInfo) - if !shouldRetry(c, newAPIError, common.RetryTimes-retryParam.GetRetry()) { + if decision.Action != "retry" { break } } @@ -258,12 +262,14 @@ func getChannel(c *gin.Context, info *relaycommon.RelayInfo, retryParam *service if !autoBan { autoBanInt = 0 } - return &model.Channel{ + channel := &model.Channel{ Id: c.GetInt("channel_id"), Type: c.GetInt("channel_type"), Name: c.GetString("channel_name"), AutoBan: &autoBanInt, - }, nil + } + service.RequestPolicy(c).BeginAttempt(channel, info.UsingGroup) + return channel, nil } channel, selectGroup, err := service.CacheGetRandomSatisfiedChannel(retryParam) if err != nil { @@ -275,6 +281,7 @@ func getChannel(c *gin.Context, info *relaycommon.RelayInfo, retryParam *service info.PriceData.GroupRatioInfo = helper.HandleGroupRatio(c, info) + service.RequestPolicy(c).BeginAttempt(channel, selectGroup) newAPIError := middleware.SetupContextForSelectedChannel(c, channel, info.OriginModelName) if newAPIError != nil { return nil, newAPIError @@ -282,15 +289,17 @@ func getChannel(c *gin.Context, info *relaycommon.RelayInfo, retryParam *service return channel, nil } -func shouldRetry(c *gin.Context, openaiErr *types.NewAPIError, retryTimes int) bool { - return service.ShouldRetryRelayError(c, openaiErr, retryTimes) -} - func processChannelError(c *gin.Context, channelError types.ChannelError, err *types.NewAPIError, relayInfo *relaycommon.RelayInfo) { service.ProcessChannelError(c, channelError, err, relayInfo) } func RelayMidjourney(c *gin.Context) { + policy := service.RequestPolicy(c) + defer func() { + if policy.Attempts > 0 && !policy.Successful { + service.RecordRequestPolicyTermination(c, types.NewErrorWithStatusCode(errors.New("Midjourney submission failed"), types.ErrorCodeBadResponseStatusCode, http.StatusBadGateway, types.ErrOptionWithSkipRetry())) + } + }() relayInfo, err := relaycommon.GenRelayInfo(c, types.RelayFormatMjProxy, nil, nil) if err != nil { @@ -318,6 +327,7 @@ func RelayMidjourney(c *gin.Context) { //err = relayMidjourneySubmit(c, relayMode) log.Println(mjErr) if mjErr != nil { + policy.Successful = false statusCode := http.StatusBadRequest if mjErr.Code == 30 { mjErr.Result = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。" @@ -457,6 +467,7 @@ func executeTaskSubmissionWith( relayInfo *relaycommon.RelayInfo, submit taskSubmitAttempt, ) (*taskSubmissionOutcome, *taskdto.TaskError) { + policy := service.RequestPolicy(c) diagnostics := newTaskPluginSubmitDiagnostics(c) diagnostics.start(relayInfo) var result *relay.TaskSubmitResult @@ -494,6 +505,7 @@ func executeTaskSubmissionWith( if lockedCh, ok := relayInfo.LockedChannel.(*model.Channel); ok && lockedCh != nil { channel = lockedCh + policy.BeginAttempt(channel, relayInfo.UsingGroup) if retryParam.GetRetry() > 0 { if setupErr := middleware.SetupContextForSelectedChannel(c, channel, relayInfo.OriginModelName); setupErr != nil { taskErr = service.TaskErrorWrapperLocal(setupErr.Err, "setup_locked_channel_failed", http.StatusInternalServerError) @@ -505,7 +517,7 @@ func executeTaskSubmissionWith( channel, channelErr = getChannel(c, relayInfo, retryParam) if channelErr != nil { logger.LogError(c, channelErr.Error()) - taskErr = service.TaskErrorWrapperLocal(channelErr.Err, "get_channel_failed", http.StatusInternalServerError) + taskErr = service.TaskErrorWrapperLocal(channelErr.Err, "get_channel_failed", channelErr.StatusCode) break } } @@ -536,15 +548,19 @@ func executeTaskSubmissionWith( break } + taskAPIError := taskSubmissionAPIError(taskErr) + relayInfo.LastError = taskAPIError + decision := decideTaskRetry(c, taskErr, common.RetryTimes-retryParam.GetRetry()) + service.RecordPolicyFailure(c, channel.Id, taskAPIError, decision) if !taskErr.LocalError { processChannelError(c, *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()), - types.NewOpenAIError(taskErr.Error, types.ErrorCodeBadResponseStatusCode, taskErr.StatusCode), + taskAPIError, relayInfo) } - willRetry := shouldRetryTaskRelay(c, channel.Id, taskErr, common.RetryTimes-retryParam.GetRetry()) + willRetry := decision.Action == "retry" diagnostics.attemptFailed(retryParam.GetRetry()+1, channel, taskErr, willRetry) if !willRetry { break @@ -646,6 +662,11 @@ func executeTaskSubmissionWith( diagnostics.failed("settle", "billing_error", taskErr, true) return nil, taskErr } + if task.Status != model.TaskStatusFailure { + service.MarkRequestPolicySuccess(c, nil) + } else { + policy.AddEvent(service.PolicyEvent{Decision: service.PolicyDecision{Action: "stop", Reason: "task_failed", Source: "upstream"}}) + } service.LogTaskConsumption(c, relayInfo, task) diagnostics.complete(task, result.Quota) @@ -706,6 +727,7 @@ func presentTaskSubmission(c *gin.Context, outcome *taskSubmissionOutcome) { } func respondTaskSubmissionError(c *gin.Context, taskErr *taskdto.TaskError) { + service.RecordRequestPolicyTermination(c, taskSubmissionAPIError(taskErr)) newTaskPluginSubmitDiagnostics(c).presentError(taskErr) if middleware.RespondTaskPluginError(c, taskErr) { return @@ -721,44 +743,53 @@ func respondTaskError(c *gin.Context, taskErr *taskdto.TaskError) { c.JSON(taskErr.StatusCode, taskErr) } -func shouldRetryTaskRelay(c *gin.Context, channelId int, taskErr *taskdto.TaskError, retryTimes int) bool { - if taskErr == nil || taskErr.NoRetry { - return false +// taskSubmissionAPIError adapts a task error for the shared relay error paths. +// TaskError.Error is nil for many local rejections, so fall back to the message. +func taskSubmissionAPIError(taskErr *taskdto.TaskError) *types.NewAPIError { + err := taskErr.Error + if err == nil { + err = errors.New(taskErr.Message) } - if service.ShouldSkipRetryAfterChannelAffinityFailure(c) { - return false - } - if retryTimes <= 0 { - return false - } - if service.GetChannelConstraints(c).SuppressesRetry() { - return false - } - if taskErr.StatusCode == http.StatusTooManyRequests { - return true - } - if taskErr.StatusCode == 307 { - return true - } - if taskErr.StatusCode/100 == 5 { + return types.NewOpenAIError(err, types.ErrorCodeBadResponseStatusCode, taskErr.StatusCode) +} + +// decideTaskRetry is the single retry decision for task submissions. The +// reason is recorded in the request policy decision events of the log details. +func decideTaskRetry(c *gin.Context, taskErr *taskdto.TaskError, retryTimes int) service.PolicyDecision { + stop := service.PolicyDecision{Action: "stop", Source: "system"} + retry := service.PolicyDecision{Action: "retry", Reason: "retry_status_matched", Source: "system"} + switch { + case taskErr == nil: + stop.Reason = "request_completed" + case taskErr.NoRetry: + stop.Reason = "task_accepted" + case service.ShouldSkipRetryAfterChannelAffinityFailure(c): + stop.Reason, stop.Source = "strict_session", "session_rule" + if source := service.RequestPolicy(c).SessionModeSource; source != "" { + stop.Source = source + } + case retryTimes <= 0: + stop.Reason, stop.Source = "attempt_budget_exhausted", "global" + case service.GetChannelConstraints(c).SuppressesRetry(): + stop.Reason, stop.Source = "pinned_channel", "channel_constraint" + case taskErr.StatusCode == http.StatusTooManyRequests, taskErr.StatusCode == 307: + return retry + case taskErr.StatusCode/100 == 5: // 超时不重试 if operation_setting.IsAlwaysSkipRetryStatusCode(taskErr.StatusCode) { - return false + stop.Reason = "system_retry_exclusion" + break } - return true - } - if taskErr.StatusCode == http.StatusBadRequest { - return false - } - if taskErr.StatusCode == 408 { + return retry + case taskErr.StatusCode == http.StatusBadRequest, taskErr.StatusCode == 408: // azure处理超时不重试 - return false + stop.Reason = "status_not_retryable" + case taskErr.LocalError: + stop.Reason = "local_rejection" + case taskErr.StatusCode/100 == 2: + stop.Reason = "system_retry_exclusion" + default: + return retry } - if taskErr.LocalError { - return false - } - if taskErr.StatusCode/100 == 2 { - return false - } - return true + return stop } diff --git a/controller/relay_task_plugin_test.go b/controller/relay_task_plugin_test.go index abef10bb4d..a9971ff18e 100644 --- a/controller/relay_task_plugin_test.go +++ b/controller/relay_task_plugin_test.go @@ -539,7 +539,24 @@ export function buildQueryRequest(){throw new Error("completed submissions must func TestAcceptedSubmitStreamNeverRetries(t *testing.T) { c := taskSubmissionTestContext() - assert.False(t, shouldRetryTaskRelay(c, 1, &dto.TaskError{StatusCode: 502, LocalError: true, NoRetry: true}, 3)) + assert.Equal(t, service.PolicyDecision{Action: "stop", Reason: "task_accepted", Source: "system"}, decideTaskRetry(c, &dto.TaskError{StatusCode: 502, LocalError: true, NoRetry: true}, 3)) +} + +// Local task rejections carry a message but no cause; the response and the +// decision record must still be produced. +func TestRespondTaskSubmissionErrorWithoutCause(t *testing.T) { + previousErrorLog := constant.ErrorLogEnabled + constant.ErrorLogEnabled = false + t.Cleanup(func() { constant.ErrorLogEnabled = previousErrorLog }) + c := taskSubmissionTestContext() + taskErr := &dto.TaskError{Code: "get_channel_failed", Message: "no channel", StatusCode: http.StatusServiceUnavailable, LocalError: true} + require.NotPanics(t, func() { respondTaskSubmissionError(c, taskErr) }) + assert.Equal(t, http.StatusServiceUnavailable, c.Writer.Status()) + events := service.RequestPolicy(c).Events() + require.Len(t, events, 1) + assert.Equal(t, service.PolicyDecision{Action: "stop", Reason: "request_failed", Source: "system"}, events[0].Decision) + assert.Equal(t, http.StatusServiceUnavailable, events[0].Status) + assert.Equal(t, service.PolicyDecision{Action: "stop", Reason: "local_rejection", Source: "system"}, decideTaskRetry(c, &dto.TaskError{StatusCode: http.StatusForbidden, LocalError: true, Message: "billing"}, 2), "local errors stop once the status rules do not force a retry") } func TestExecuteTaskSubmissionRefundsWhenFinalReserveFails(t *testing.T) { diff --git a/controller/request_policy.go b/controller/request_policy.go new file mode 100644 index 0000000000..28e40e5d18 --- /dev/null +++ b/controller/request_policy.go @@ -0,0 +1,27 @@ +package controller + +import ( + "net/http" + + "github.com/QuantumNous/new-api/model" + "github.com/gin-gonic/gin" +) + +func GetRequestPolicy(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"options": model.CurrentRequestPolicy().Options}}) +} + +func UpdateRequestPolicy(c *gin.Context) { + var request struct { + Options map[string]string `json:"options"` + } + if err := c.ShouldBindJSON(&request); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": err.Error()}) + return + } + if err := model.UpdateRequestPolicyOptions(request.Options); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": err.Error()}) + return + } + GetRequestPolicy(c) +} diff --git a/middleware/distributor.go b/middleware/distributor.go index 1998934e91..5750e70661 100644 --- a/middleware/distributor.go +++ b/middleware/distributor.go @@ -34,6 +34,12 @@ type ModelRequest struct { func Distribute() func(c *gin.Context) { return func(c *gin.Context) { var channel *model.Channel + policy := service.RequestPolicy(c) + defer func() { + if c.Writer.Status() >= 400 { + service.RecordRequestPolicyTermination(c, types.NewErrorWithStatusCode(errors.New("request rejected"), types.ErrorCodeInvalidRequest, c.Writer.Status(), types.ErrOptionWithSkipRetry())) + } + }() constraints := service.GetChannelConstraints(c) constraints.AddFilter(taskdto.ChannelFilter{ Kind: taskdto.FilterRequestPath, @@ -154,6 +160,10 @@ func Distribute() func(c *gin.Context) { if !affinityUsable && !service.ShouldKeepChannelAffinityOnChannelDisabled() { service.ClearCurrentChannelAffinityCache(c) } + if !affinityUsable && policy.SessionMode == "strict" { + abortWithOpenAiMessage(c, http.StatusServiceUnavailable, "strict_session_binding_unavailable") + return + } } if channel == nil { diff --git a/model/option.go b/model/option.go index 24f0fd6381..fe41eac63e 100644 --- a/model/option.go +++ b/model/option.go @@ -195,6 +195,13 @@ func InitOptionMap() { } func loadOptionsFromDatabase() { + requestPolicyOptionMutex.Lock() + defer requestPolicyOptionMutex.Unlock() + defer func() { + if err := refreshRequestPolicySnapshot(); err != nil { + common.SysError("invalid request policy: " + err.Error()) + } + }() passkeyOptionMutex.Lock() defer passkeyOptionMutex.Unlock() options, _ := AllOption() @@ -234,6 +241,9 @@ func validateOptionValue(key string, value string) error { } func UpdateOption(key string, value string) error { + if IsRequestPolicyOption(key) { + return UpdateRequestPolicyOptions(map[string]string{key: value}) + } if IsPasskeyDomainOption(key) { _, err := UpdatePasskeyDomainOptions(map[string]string{key: value}, false, "") return err @@ -279,6 +289,26 @@ func UpdateOptionsBulk(values map[string]string) error { return err } } + var policySnapshot *RequestPolicySnapshot + for key := range values { + if IsRequestPolicyOption(key) { + requestPolicyOptionMutex.Lock() + defer requestPolicyOptionMutex.Unlock() + options := maps.Clone(CurrentRequestPolicy().Options) + for key, value := range values { + if IsRequestPolicyOption(key) { + options[key] = value + } + } + var err error + policySnapshot, err = BuildRequestPolicy(options) + if err != nil { + return err + } + break + } + } + err := DB.Transaction(func(tx *gorm.DB) error { for k, v := range values { option := Option{Key: k} @@ -300,6 +330,9 @@ func UpdateOptionsBulk(values map[string]string) error { return err } } + if policySnapshot != nil { + requestPolicySnapshot.Store(policySnapshot) + } return nil } diff --git a/model/request_policy.go b/model/request_policy.go new file mode 100644 index 0000000000..780d72d340 --- /dev/null +++ b/model/request_policy.go @@ -0,0 +1,258 @@ +package model + +import ( + "encoding/json" + "fmt" + "maps" + "math" + "regexp" + "strconv" + "strings" + "sync" + "sync/atomic" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/setting" + "github.com/QuantumNous/new-api/setting/config" + "github.com/QuantumNous/new-api/setting/operation_setting" + "gorm.io/gorm" +) + +// RequestPolicySnapshot is the validated read model behind the request policy +// settings API. It is rebuilt from the option map on every option write, so +// the runtime globals updated by the same write never disagree with it. +type RequestPolicySnapshot struct { + Affinity operation_setting.ChannelAffinitySetting + RetryTimes int + RetryCodes []operation_setting.StatusCodeRange + DisableCodes []operation_setting.StatusCodeRange + DisableKeywords []string + CheckText bool + TextKeywords []string + AutoDisable bool + Options map[string]string +} + +var requestPolicySnapshot atomic.Pointer[RequestPolicySnapshot] +var requestPolicyOptionMutex sync.Mutex +var requestPolicyDefaults = requestPolicyDefaultOptions() + +func requestPolicyDefaultOptions() map[string]string { + defaults := make(map[string]string) + for prefix, value := range map[string]any{ + "channel_affinity_setting.": operation_setting.GetChannelAffinitySetting(), + "monitor_setting.": operation_setting.GetMonitorSetting(), + } { + fields, err := config.ConfigToMap(value) + if err != nil { + panic(err) + } + for field, value := range fields { + defaults[prefix+field] = value + } + } + defaults["RetryTimes"] = strconv.Itoa(common.RetryTimes) + defaults["AutomaticRetryStatusCodes"] = operation_setting.AutomaticRetryStatusCodesToString() + defaults["AutomaticDisableStatusCodes"] = operation_setting.AutomaticDisableStatusCodesToString() + defaults["AutomaticDisableKeywords"] = operation_setting.AutomaticDisableKeywordsToString() + defaults["AutomaticDisableChannelEnabled"] = strconv.FormatBool(common.AutomaticDisableChannelEnabled) + defaults["CheckSensitiveEnabled"] = strconv.FormatBool(setting.CheckSensitiveEnabled) + defaults["CheckSensitiveOnPromptEnabled"] = strconv.FormatBool(setting.CheckSensitiveOnPromptEnabled) + defaults["SensitiveWords"] = setting.SensitiveWordsToString() + defaults["AutomaticEnableChannelEnabled"] = strconv.FormatBool(common.AutomaticEnableChannelEnabled) + defaults["ChannelDisableThreshold"] = strconv.FormatFloat(common.ChannelDisableThreshold, 'f', -1, 64) + return defaults +} + +func IsRequestPolicyOption(key string) bool { + if strings.HasPrefix(key, "channel_affinity_setting.") { + return true + } + switch key { + case "CheckSensitiveEnabled", "CheckSensitiveOnPromptEnabled", "SensitiveWords", "AutomaticEnableChannelEnabled", "ChannelDisableThreshold", "monitor_setting.auto_test_channel_enabled", "monitor_setting.auto_test_channel_minutes", "monitor_setting.channel_test_concurrency", "monitor_setting.channel_test_mode", "RetryTimes", "AutomaticRetryStatusCodes", "AutomaticDisableChannelEnabled", "AutomaticDisableStatusCodes", "AutomaticDisableKeywords": + return true + } + return false +} + +func CurrentRequestPolicy() *RequestPolicySnapshot { + if snapshot := requestPolicySnapshot.Load(); snapshot != nil { + return snapshot + } + // Startup and test fixtures may not have loaded options yet. + snapshot, err := BuildRequestPolicy(nil) + if err != nil { + return &RequestPolicySnapshot{Options: map[string]string{}} + } + return snapshot +} + +func BuildRequestPolicy(options map[string]string) (*RequestPolicySnapshot, error) { + defaults := requestPolicyDefaults + + raw := make(map[string]string) + for key, value := range defaults { + if IsRequestPolicyOption(key) { + raw[key] = value + } + } + maps.Copy(raw, options) + snapshot := &RequestPolicySnapshot{Options: raw} + affinityFields := map[string]string{} + for key, value := range raw { + if field, ok := strings.CutPrefix(key, "channel_affinity_setting."); ok { + switch field { + case "enabled", "session_mode", "switch_on_success", "keep_on_channel_disabled", "max_entries", "default_ttl_seconds", "rules": + default: + return nil, fmt.Errorf("unknown affinity option: %s", key) + } + affinityFields[field] = value + } + } + // Decode through JSON so malformed scalar/array values cannot be silently ignored. + affinityJSON := map[string]json.RawMessage{} + for key, value := range affinityFields { + if key == "session_mode" { + encoded, _ := common.Marshal(value) + affinityJSON[key] = encoded + } else { + affinityJSON[key] = json.RawMessage(value) + } + } + encoded, err := common.Marshal(affinityJSON) + if err != nil { + return nil, err + } + if err := common.Unmarshal(encoded, &snapshot.Affinity); err != nil { + return nil, err + } + snapshot.RetryTimes, err = strconv.Atoi(raw["RetryTimes"]) + if err != nil || snapshot.RetryTimes < 0 || snapshot.RetryTimes == math.MaxInt { + return nil, fmt.Errorf("retry times must be a non-negative integer with room for the initial attempt") + } + snapshot.AutoDisable, err = strconv.ParseBool(raw["AutomaticDisableChannelEnabled"]) + if err != nil { + return nil, err + } + snapshot.RetryCodes, err = operation_setting.ParseHTTPStatusCodeRanges(raw["AutomaticRetryStatusCodes"]) + if err != nil { + return nil, err + } + snapshot.DisableCodes, err = operation_setting.ParseHTTPStatusCodeRanges(raw["AutomaticDisableStatusCodes"]) + if err != nil { + return nil, err + } + snapshot.DisableKeywords = strings.Split(raw["AutomaticDisableKeywords"], "\n") + for _, key := range []string{"CheckSensitiveEnabled", "CheckSensitiveOnPromptEnabled", "AutomaticEnableChannelEnabled", "monitor_setting.auto_test_channel_enabled"} { + if _, err := strconv.ParseBool(raw[key]); err != nil { + return nil, fmt.Errorf("invalid boolean: %s", key) + } + } + snapshot.CheckText = raw["CheckSensitiveEnabled"] == "true" && raw["CheckSensitiveOnPromptEnabled"] == "true" + for word := range strings.SplitSeq(raw["SensitiveWords"], "\n") { + if word = strings.TrimSpace(word); word != "" { + snapshot.TextKeywords = append(snapshot.TextKeywords, word) + } + } + if err := operation_setting.ValidateChannelTestConcurrency(raw["monitor_setting.channel_test_concurrency"]); err != nil { + return nil, err + } + for _, key := range []string{"ChannelDisableThreshold", "monitor_setting.auto_test_channel_minutes"} { + if raw[key] == "" && key == "ChannelDisableThreshold" { + continue + } + value, err := strconv.ParseFloat(raw[key], 64) + if err != nil || value < 0 || math.IsNaN(value) || math.IsInf(value, 0) { + return nil, fmt.Errorf("invalid numeric value: %s", key) + } + } + switch raw["monitor_setting.channel_test_mode"] { + case "scheduled_all", "auto_ban_only", "passive_recovery": + default: + return nil, fmt.Errorf("invalid channel test mode") + } + + if snapshot.Affinity.MaxEntries < 0 || snapshot.Affinity.DefaultTTLSeconds < 0 { + return nil, fmt.Errorf("invalid affinity cache limits") + } + switch snapshot.Affinity.SessionMode { + case "", "off", "prefer", "strict": + default: + return nil, fmt.Errorf("invalid global session mode") + } + for _, rule := range snapshot.Affinity.Rules { + switch rule.SessionMode { + case "", "inherit", "off", "prefer", "strict": + default: + return nil, fmt.Errorf("invalid session mode for rule %q", rule.Name) + } + patterns := append(append([]string{}, rule.ModelRegex...), rule.PathRegex...) + if rule.ValueRegex != "" { + patterns = append(patterns, rule.ValueRegex) + } + for _, pattern := range patterns { + if _, err := regexp.Compile(pattern); err != nil { + return nil, fmt.Errorf("rule %q: %w", rule.Name, err) + } + } + if rule.TTLSeconds < 0 { + return nil, fmt.Errorf("negative affinity TTL") + } + } + return snapshot, nil +} + +func refreshRequestPolicySnapshot() error { + common.OptionMapRWMutex.RLock() + options := make(map[string]string) + for key, value := range common.OptionMap { + if IsRequestPolicyOption(key) { + options[key] = value + } + } + common.OptionMapRWMutex.RUnlock() + snapshot, err := BuildRequestPolicy(options) + if err == nil { + requestPolicySnapshot.Store(snapshot) + } + return err +} + +// UpdateRequestPolicyOptions validates the entire resulting policy before any +// write. Unknown JSON rule fields stay in the original option string. +func UpdateRequestPolicyOptions(values map[string]string) error { + requestPolicyOptionMutex.Lock() + defer requestPolicyOptionMutex.Unlock() + options := maps.Clone(CurrentRequestPolicy().Options) + for key, value := range values { + if !IsRequestPolicyOption(key) { + return fmt.Errorf("not a request policy option: %s", key) + } + options[key] = value + } + snapshot, err := BuildRequestPolicy(options) + if err != nil { + return err + } + if err := DB.Transaction(func(tx *gorm.DB) error { + for key, value := range values { + option := Option{Key: key} + if err := tx.FirstOrCreate(&option, Option{Key: key}).Error; err != nil { + return err + } + if err := tx.Model(&option).Update("value", value).Error; err != nil { + return err + } + } + return nil + }); err != nil { + return err + } + for key, value := range values { + if err := updateOptionMap(key, value); err != nil { + return err + } + } + requestPolicySnapshot.Store(snapshot) + return nil +} diff --git a/model/request_policy_test.go b/model/request_policy_test.go new file mode 100644 index 0000000000..c9ed06da66 --- /dev/null +++ b/model/request_policy_test.go @@ -0,0 +1,122 @@ +package model + +import ( + "errors" + "maps" + "math" + "os" + "strconv" + "testing" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/setting/operation_setting" + "github.com/glebarez/sqlite" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/mysql" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/schema" +) + +func TestRequestPolicyDatabaseMatrix(t *testing.T) { + for _, dialect := range []string{"sqlite", "mysql", "postgres"} { + t.Run(dialect, func(t *testing.T) { + var driver gorm.Dialector + switch dialect { + case "sqlite": + driver = sqlite.Open(":memory:") + case "mysql": + dsn := os.Getenv("TEST_MYSQL_DSN") + if dsn == "" { + t.Skip("TEST_MYSQL_DSN not configured") + } + driver = mysql.Open(dsn) + case "postgres": + dsn := os.Getenv("TEST_POSTGRES_DSN") + if dsn == "" { + t.Skip("TEST_POSTGRES_DSN not configured") + } + driver = postgres.Open(dsn) + } + db, err := gorm.Open(driver, &gorm.Config{NamingStrategy: schema.NamingStrategy{TablePrefix: "policy_test_"}}) + require.NoError(t, err) + sqlDB, err := db.DB() + require.NoError(t, err) + sqlDB.SetMaxOpenConns(1) + previousDB, previousType, previousSnapshot := DB, common.MainDatabaseType(), CurrentRequestPolicy() + common.OptionMapRWMutex.Lock() + previousOptions := maps.Clone(common.OptionMap) + common.OptionMap = maps.Clone(previousSnapshot.Options) + common.OptionMapRWMutex.Unlock() + DB = db + common.SetMainDatabaseType(common.DatabaseType(dialect)) + initCol() + t.Cleanup(func() { + require.NoError(t, db.Migrator().DropTable(&Option{})) + for k, v := range previousSnapshot.Options { + require.NoError(t, updateOptionMap(k, v)) + } + requestPolicySnapshot.Store(previousSnapshot) + common.OptionMapRWMutex.Lock() + common.OptionMap = previousOptions + common.OptionMapRWMutex.Unlock() + DB = previousDB + common.SetMainDatabaseType(previousType) + initCol() + require.NoError(t, sqlDB.Close()) + }) + require.NoError(t, db.AutoMigrate(&Option{})) + var version string + query := "SELECT version()" + if dialect == "sqlite" { + query = "SELECT sqlite_version()" + } + require.NoError(t, db.Raw(query).Scan(&version).Error) + t.Logf("database version: %s", version) + rules := `[{"name":"session","model_regex":[".*"],"key_sources":[{"type":"request_header","key":"X-Session"}],"ttl_seconds":0,"skip_retry_on_failure":false,"include_using_group":false,"param_override_template":{"temperature":0},"future_field":{"enabled":false}}]` + require.NoError(t, UpdateRequestPolicyOptions(map[string]string{"RetryTimes": "2", "channel_affinity_setting.rules": rules})) + assert.Equal(t, 2, CurrentRequestPolicy().RetryTimes) + assert.Equal(t, 2, common.RetryTimes, "the runtime global follows the same write") + require.NoError(t, UpdateOption("AutomaticRetryStatusCodes", "429,500-503")) + assert.Equal(t, "429,500-503", CurrentRequestPolicy().Options["AutomaticRetryStatusCodes"]) + assert.Equal(t, "429,500-503", operation_setting.AutomaticRetryStatusCodesToString()) + assert.Error(t, UpdateRequestPolicyOptions(map[string]string{"request_policy_setting.mode": "off"}), "the removed mode switch is not a policy option") + assert.False(t, CurrentRequestPolicy().Affinity.Rules[0].SkipRetryOnFailure) + assert.Equal(t, rules, CurrentRequestPolicy().Options["channel_affinity_setting.rules"]) + loadOptionsFromDatabase() + loadOptionsFromDatabase() + assert.Equal(t, rules, CurrentRequestPolicy().Options["channel_affinity_setting.rules"], "legacy rule JSON survives reloads without dropping extension fields") + require.NoError(t, UpdateRequestPolicyOptions(map[string]string{"channel_affinity_setting.session_mode": "strict"})) + loadOptionsFromDatabase() + loadOptionsFromDatabase() + assert.Equal(t, "strict", CurrentRequestPolicy().Affinity.SessionMode) + assert.Equal(t, rules, CurrentRequestPolicy().Options["channel_affinity_setting.rules"], "a global mode never rewrites rule fields") + snapshot := CurrentRequestPolicy() + assert.Error(t, UpdateRequestPolicyOptions(map[string]string{"channel_affinity_setting.session_mode": "unknown"})) + assert.Same(t, snapshot, CurrentRequestPolicy()) + for _, value := range []string{"-1", "1.5", "bad", strconv.Itoa(math.MaxInt)} { + assert.Error(t, UpdateRequestPolicyOptions(map[string]string{"RetryTimes": value})) + assert.Same(t, snapshot, CurrentRequestPolicy()) + } + assert.Error(t, UpdateRequestPolicyOptions(map[string]string{"channel_affinity_setting.rules": "[", "RetryTimes": "8"})) + assert.Same(t, snapshot, CurrentRequestPolicy()) + var option Option + require.NoError(t, db.Where(map[string]any{"key": "RetryTimes"}).First(&option).Error) + assert.Equal(t, "2", option.Value) + require.NoError(t, db.Callback().Update().Before("gorm:update").Register("policy_fail", func(tx *gorm.DB) { + if tx.Statement.Table == "policy_test_options" { + tx.AddError(errors.New("save rejected")) + } + })) + assert.Error(t, UpdateRequestPolicyOptions(map[string]string{"RetryTimes": "8", "channel_affinity_setting.session_mode": "off"})) + assert.Same(t, snapshot, CurrentRequestPolicy()) + require.NoError(t, db.Callback().Update().Remove("policy_fail")) + option = Option{} + require.NoError(t, db.Where(map[string]any{"key": "RetryTimes"}).First(&option).Error) + assert.Equal(t, "2", option.Value) + loadOptionsFromDatabase() + assert.Equal(t, "strict", CurrentRequestPolicy().Affinity.SessionMode, "a failed save keeps the persisted global mode") + }) + } +} diff --git a/relay/mjproxy_handler.go b/relay/mjproxy_handler.go index 6525a6f141..803536f22c 100644 --- a/relay/mjproxy_handler.go +++ b/relay/mjproxy_handler.go @@ -2,7 +2,6 @@ package relay import ( "bytes" - "encoding/json" "fmt" "io" "log" @@ -125,7 +124,7 @@ func RelayMidjourneyNotify(c *gin.Context) *dto.MidjourneyResponse { midjourneyTask.FinishTime = midjRequest.FinishTime midjourneyTask.ImageUrl = midjRequest.ImageUrl midjourneyTask.VideoUrl = midjRequest.VideoUrl - videoUrlsStr, _ := json.Marshal(midjRequest.VideoUrls) + videoUrlsStr, _ := common.Marshal(midjRequest.VideoUrls) midjourneyTask.VideoUrls = string(videoUrlsStr) midjourneyTask.Status = midjRequest.Status midjourneyTask.FailReason = midjRequest.FailReason @@ -167,21 +166,21 @@ func coverMidjourneyTaskDto(c *gin.Context, originTask *model.Midjourney) (midjo midjourneyTask.Prompt = originTask.Prompt if originTask.Buttons != "" { var buttons []dto.ActionButton - err := json.Unmarshal([]byte(originTask.Buttons), &buttons) + err := common.Unmarshal([]byte(originTask.Buttons), &buttons) if err == nil { midjourneyTask.Buttons = buttons } } if originTask.VideoUrls != "" { var videoUrls []dto.ImgUrls - err := json.Unmarshal([]byte(originTask.VideoUrls), &videoUrls) + err := common.Unmarshal([]byte(originTask.VideoUrls), &videoUrls) if err == nil { midjourneyTask.VideoUrls = videoUrls } } if originTask.Properties != "" { var properties dto.Properties - err := json.Unmarshal([]byte(originTask.Properties), &properties) + err := common.Unmarshal([]byte(originTask.Properties), &properties) if err == nil { midjourneyTask.Properties = &properties } @@ -228,7 +227,9 @@ func RelaySwapFace(c *gin.Context, info *relaycommon.RelayInfo) *dto.MidjourneyR requestURL := getMjRequestPath(c.Request.URL.String()) baseURL := c.GetString("base_url") fullRequestURL := fmt.Sprintf("%s%s", baseURL, requestURL) + service.RequestPolicy(c).BeginAttempt(&model.Channel{Id: c.GetInt("channel_id")}, info.UsingGroup) mjResp, _, err := service.DoMidjourneyHttpRequest(c, time.Second*60, fullRequestURL) + accepted := service.RecordMidjourneyPolicyResponse(c, mjResp, err) if err != nil { return &mjResp.Response } @@ -268,11 +269,15 @@ func RelaySwapFace(c *gin.Context, info *relaycommon.RelayInfo) *dto.MidjourneyR if billingErr != nil { common.SysLog("error settling Midjourney quota: " + billingErr.Error()) } + if accepted { + service.MarkRequestPolicySuccess(c, nil) + } if billingApplied { billingChannelId := midjourneyTask.GetBillingChannelId() tokenName := c.GetString("token_name") logContent := fmt.Sprintf("模型固定价格 %.2f,分组倍率 %.2f,操作 %s", priceData.ModelPrice, priceData.GroupRatioInfo.GroupRatio, constant.MjActionSwapFace) other := service.GenerateMjOtherInfo(info, priceData) + service.AppendRelayLogAdminInfo(c, info, other) model.RecordConsumeLog(c, info.UserId, model.RecordConsumeLogParams{ ChannelId: billingChannelId, ModelName: modelName, @@ -287,7 +292,7 @@ func RelaySwapFace(c *gin.Context, info *relaycommon.RelayInfo) *dto.MidjourneyR model.UpdateChannelUsedQuota(billingChannelId, midjourneyTask.Quota) } c.Writer.WriteHeader(mjResp.StatusCode) - respBody, err := json.Marshal(midjResponse) + respBody, err := common.Marshal(midjResponse) if err != nil { return service.MidjourneyErrorWrapper(constant.MjRequestError, "unmarshal_response_body_failed") } @@ -323,7 +328,7 @@ func RelayMidjourneyTaskImageSeed(c *gin.Context) *dto.MidjourneyResponse { } midjResponse := &midjResponseWithStatus.Response c.Writer.WriteHeader(midjResponseWithStatus.StatusCode) - respBody, err := json.Marshal(midjResponse) + respBody, err := common.Marshal(midjResponse) if err != nil { return service.MidjourneyErrorWrapper(constant.MjRequestError, "unmarshal_response_body_failed") } @@ -346,7 +351,7 @@ func RelayMidjourneyTask(c *gin.Context, relayMode int) *dto.MidjourneyResponse } } midjourneyTask := coverMidjourneyTaskDto(c, originTask) - respBody, err = json.Marshal(midjourneyTask) + respBody, err = common.Marshal(midjourneyTask) if err != nil { return &dto.MidjourneyResponse{ Code: 4, @@ -375,7 +380,7 @@ func RelayMidjourneyTask(c *gin.Context, relayMode int) *dto.MidjourneyResponse if tasks == nil { tasks = make([]dto.MidjourneyDto, 0) } - respBody, err = json.Marshal(tasks) + respBody, err = common.Marshal(tasks) if err != nil { return &dto.MidjourneyResponse{ Code: 4, @@ -539,7 +544,9 @@ func RelayMidjourneySubmit(c *gin.Context, relayInfo *relaycommon.RelayInfo) *dt } } + service.RequestPolicy(c).BeginAttempt(&model.Channel{Id: c.GetInt("channel_id")}, relayInfo.UsingGroup) midjResponseWithStatus, responseBody, err := service.DoMidjourneyHttpRequest(c, time.Second*60, fullRequestURL) + accepted := service.RecordMidjourneyPolicyResponse(c, midjResponseWithStatus, err) if err != nil { return &midjResponseWithStatus.Response } @@ -576,9 +583,10 @@ func RelayMidjourneySubmit(c *gin.Context, relayInfo *relaycommon.RelayInfo) *dt if err != nil { common.SysLog("get_channel_null: " + err.Error()) } - if channel.GetAutoBan() && common.AutomaticDisableChannelEnabled { + if channel != nil && channel.GetAutoBan() && common.AutomaticDisableChannelEnabled { if model.UpdateChannelStatus(midjourneyTask.ChannelId, "", common.ChannelStatusManuallyDisabled, "No available account instance") { service.CloseActiveWebSocketsForChannel(midjourneyTask.ChannelId, service.ChannelDisabledCloseReason) + service.RequestPolicy(c).AddEvent(service.PolicyEvent{ChannelID: midjourneyTask.ChannelId, Decision: service.PolicyDecision{Action: "stop", Reason: "task_failed", Source: "upstream"}, Health: "channel_disable_requested"}) } } } @@ -635,11 +643,15 @@ func RelayMidjourneySubmit(c *gin.Context, relayInfo *relaycommon.RelayInfo) *dt if billingErr != nil { common.SysLog("error settling Midjourney quota: " + billingErr.Error()) } + if accepted { + service.MarkRequestPolicySuccess(c, nil) + } if billingApplied { billingChannelId := midjourneyTask.GetBillingChannelId() tokenName := c.GetString("token_name") logContent := fmt.Sprintf("模型固定价格 %.2f,分组倍率 %.2f,操作 %s,ID %s", priceData.ModelPrice, priceData.GroupRatioInfo.GroupRatio, midjRequest.Action, midjResponse.Result) other := service.GenerateMjOtherInfo(relayInfo, priceData) + service.AppendRelayLogAdminInfo(c, relayInfo, other) model.RecordConsumeLog(c, relayInfo.UserId, model.RecordConsumeLogParams{ ChannelId: billingChannelId, ModelName: modelName, diff --git a/relay/request_billing.go b/relay/request_billing.go index d3394a3f3e..4d7bd5d9ff 100644 --- a/relay/request_billing.go +++ b/relay/request_billing.go @@ -42,6 +42,7 @@ func PrepareRequestBilling(c *gin.Context, info *relaycommon.RelayInfo) *types.N if needSensitiveCheck && meta != nil { if contains, words := service.CheckSensitiveText(meta.CombineText); contains { + service.RequestPolicy(c).AddEvent(service.PolicyEvent{ErrorCode: string(types.ErrorCodeSensitiveWordsDetected), ErrorSource: "local", Decision: service.PolicyDecision{Action: "stop", Reason: "local_rejection", Source: "global"}, Health: "unchanged"}) message := fmt.Sprintf("user sensitive words detected: %s", strings.Join(words, ", ")) logger.LogWarn(c, message) return types.NewError(errors.New(message), types.ErrorCodeSensitiveWordsDetected) diff --git a/router/api-router.go b/router/api-router.go index b6b80fd3e4..b918a348cc 100644 --- a/router/api-router.go +++ b/router/api-router.go @@ -204,6 +204,8 @@ func SetApiRouter(router *gin.Engine) { optionRoute.Use(middleware.RootAuth()) { optionRoute.GET("/", controller.GetOptions) + optionRoute.GET("/request_policy", controller.GetRequestPolicy) + optionRoute.PATCH("/request_policy", controller.UpdateRequestPolicy) optionRoute.PUT("/", controller.UpdateOption) optionRoute.PUT("/passkey/domains", controller.UpdatePasskeyDomains) optionRoute.GET("/model_pricing", controller.GetModelPricingConfig) diff --git a/service/channel_affinity.go b/service/channel_affinity.go index ac61653587..eafdbcce74 100644 --- a/service/channel_affinity.go +++ b/service/channel_affinity.go @@ -549,6 +549,7 @@ func ApplyChannelAffinityOverrideTemplate(c *gin.Context, paramOverride map[stri func GetPreferredChannelByAffinity(c *gin.Context, modelName string, usingGroup string) (int, bool) { setting := operation_setting.GetChannelAffinitySetting() + state := RequestPolicy(c) if setting == nil || !setting.Enabled { return 0, false } @@ -593,11 +594,13 @@ func GetPreferredChannelByAffinity(c *gin.Context, modelName string, usingGroup } cacheKeySuffix := buildChannelAffinityCacheKeySuffix(rule, modelName, usingGroup, affinityValue) cacheKeyFull := channelAffinityCacheNamespace + ":" + cacheKeySuffix + state.SessionMode, state.SessionModeSource = EffectiveSessionMode(setting, rule) + state.RuleName = rule.Name setChannelAffinityContext(c, channelAffinityMeta{ CacheKey: cacheKeyFull, TTLSeconds: ttlSeconds, RuleName: rule.Name, - SkipRetry: rule.SkipRetryOnFailure, + SkipRetry: state.SessionMode == "strict", ParamTemplate: cloneStringAnyMap(rule.ParamOverrideTemplate), KeySourceType: strings.TrimSpace(usedSource.Type), KeySourceKey: strings.TrimSpace(usedSource.Key), @@ -609,6 +612,10 @@ func GetPreferredChannelByAffinity(c *gin.Context, modelName string, usingGroup RequestPath: path, }) + state.AddEvent(PolicyEvent{Decision: PolicyDecision{Action: "match", Reason: "session_rule_matched", Source: "session_rule"}}) + if state.SessionMode == "off" { + return 0, false + } cache := getChannelAffinityCache() channelID, found, err := cache.Get(cacheKeySuffix) if err != nil { @@ -707,6 +714,13 @@ func AppendChannelAffinityAdminInfo(c *gin.Context, other *model.LogOther) { if !ok || anyInfo == nil { return } + // The hint can be the whole session value for short keys; logs keep only + // the fingerprint. + if info, ok := anyInfo.(map[string]any); ok { + sanitized := cloneStringAnyMap(info) + delete(sanitized, "key_hint") + anyInfo = sanitized + } other.SetAdmin("channel_affinity", anyInfo) } @@ -715,6 +729,9 @@ func RecordChannelAffinity(c *gin.Context, channelID int) { return } setting := operation_setting.GetChannelAffinitySetting() + if RequestPolicy(c).SessionMode == "off" { + return + } if setting == nil || !setting.Enabled { return } diff --git a/service/channel_affinity_template_test.go b/service/channel_affinity_template_test.go index f5f61f293c..aef271f374 100644 --- a/service/channel_affinity_template_test.go +++ b/service/channel_affinity_template_test.go @@ -1,6 +1,7 @@ package service import ( + "errors" "fmt" "net/http" "net/http/httptest" @@ -8,9 +9,14 @@ import ( "testing" "time" + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/dto" + "github.com/QuantumNous/new-api/model" relaycommon "github.com/QuantumNous/new-api/relay/common" + "github.com/QuantumNous/new-api/relaykit/types" "github.com/QuantumNous/new-api/setting/operation_setting" "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -332,3 +338,130 @@ func TestChannelAffinityHitCodexTemplatePassHeadersEffective(t *testing.T) { _, exists = info.RuntimeHeadersOverride["x-codex-turn-metadata"] require.False(t, exists) } + +func TestMidjourneyPolicyAcceptance(t *testing.T) { + for _, tc := range []struct { + name string + status int + code int + properties map[string]any + requestErr error + accepted bool + reason string + }{ + {name: "submitted", status: 200, code: 1, accepted: true}, + {name: "existing task", status: 200, code: 21, accepted: true}, + {name: "queued", status: 200, code: 22, accepted: true}, + {name: "HTTP 200 with rejected prompt", status: 200, code: 24, reason: "non_retryable_error"}, + {name: "failed existing task", status: 200, code: 21, properties: map[string]any{"status": "FAILURE"}, reason: "task_accepted"}, + {name: "HTTP failure", status: 502, code: 1, reason: "non_retryable_error"}, + {name: "ambiguous transport failure", status: 502, requestErr: errors.New("connection reset"), reason: "non_retryable_error"}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ctx.Request = httptest.NewRequest(http.MethodPost, "/mj/submit/imagine", strings.NewReader(`{}`)) + ctx.Set("channel_id", 7) + state := RequestPolicy(ctx) + state.BeginAttempt(&model.Channel{Id: 7}, "default") + response := &dto.MidjourneyResponseWithStatusCode{StatusCode: tc.status, Response: dto.MidjourneyResponse{Code: tc.code, Properties: tc.properties}} + accepted := RecordMidjourneyPolicyResponse(ctx, response, tc.requestErr) + assert.Equal(t, tc.accepted, accepted) + assert.False(t, state.Successful, "acceptance alone must not bind before local processing finishes") + if accepted { + MarkRequestPolicySuccess(ctx, nil) + assert.True(t, state.Successful) + return + } + events := state.Events() + require.Len(t, events, 3) + assert.Equal(t, PolicyDecision{Action: "failure", Reason: "upstream_failure", Source: "upstream"}, events[1].Decision) + assert.Equal(t, tc.status, events[1].Status) + assert.Equal(t, PolicyDecision{Action: "stop", Reason: tc.reason, Source: "system"}, events[2].Decision, "submissions are never replayed") + }) + } +} + +func TestSessionRulesInheritOrOverrideGlobalDefault(t *testing.T) { + setting := operation_setting.GetChannelAffinitySetting() + previous := *setting + t.Cleanup(func() { *setting = previous }) + for _, globalMode := range []string{"", "off", "prefer", "strict"} { + for _, tc := range []struct { + name, mode, expected string + skipRetry bool + }{ + {name: "inherit", mode: "inherit", expected: globalMode}, + {name: "override-strict", mode: "strict", expected: "strict"}, + {name: "override-prefer", mode: "prefer", expected: "prefer", skipRetry: true}, + {name: "override-off", mode: "off", expected: "off", skipRetry: true}, + {name: "legacy-strict", expected: "strict", skipRetry: true}, + {name: "legacy-prefer", expected: "prefer"}, + } { + t.Run(globalMode+"/"+tc.name, func(t *testing.T) { + expected := tc.expected + if expected == "" { + expected = "prefer" + } + source := "session_rule" + if tc.mode == "inherit" { + source = "global" + } + rule := operation_setting.ChannelAffinityRule{ + Name: tc.name, ModelRegex: []string{"^test-model$"}, + KeySources: []operation_setting.ChannelAffinityKeySource{{Type: "request_header", Key: "X-Session"}}, + SessionMode: tc.mode, SkipRetryOnFailure: tc.skipRetry, + ParamOverrideTemplate: map[string]any{"temperature": 0}, IncludeRuleName: true, + } + encoded, err := common.Marshal([]operation_setting.ChannelAffinityRule{rule}) + require.NoError(t, err) + snapshot, err := model.BuildRequestPolicy(map[string]string{"RetryTimes": "2", "channel_affinity_setting.enabled": "true", "channel_affinity_setting.session_mode": globalMode, "channel_affinity_setting.rules": string(encoded)}) + require.NoError(t, err) + *setting = snapshot.Affinity + key := t.Name() + cacheKey := buildChannelAffinityCacheKeySuffix(rule, "test-model", "default", key) + cache := getChannelAffinityCache() + require.NoError(t, cache.SetWithTTL(cacheKey, 1, time.Minute)) + t.Cleanup(func() { _, err := cache.DeleteMany([]string{cacheKey}); assert.NoError(t, err) }) + ctx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + ctx.Request.Header.Set("X-Session", key) + state := RequestPolicy(ctx) + channelID, found := GetPreferredChannelByAffinity(ctx, "test-model", "default") + assert.Equal(t, expected != "off", found) + if found { + assert.Equal(t, 1, channelID) + } + assert.Equal(t, expected, state.SessionMode) + assert.Equal(t, source, state.SessionModeSource) + assert.Equal(t, expected == "strict", ShouldSkipRetryAfterChannelAffinityFailure(ctx)) + decision := DecideRelayRetry(ctx, types.NewOpenAIError(errors.New("upstream"), types.ErrorCodeBadResponseStatusCode, http.StatusTooManyRequests), 2) + if expected == "strict" { + assert.Equal(t, PolicyDecision{Action: "stop", Reason: "strict_session", Source: source}, decision) + } else { + assert.Equal(t, "retry", decision.Action) + } + events := state.Events() + require.Len(t, events, 1) + assert.Equal(t, PolicyDecision{Action: "match", Reason: "session_rule_matched", Source: "session_rule"}, events[0].Decision) + assert.Equal(t, tc.name, events[0].Rule) + transformed, applied := ApplyChannelAffinityOverrideTemplate(ctx, nil) + assert.True(t, applied, "session behavior does not disable request transforms") + assert.EqualValues(t, 0, transformed["temperature"]) + if expected == "off" { + ctx.Set("channel_id", 9) + RecordChannelAffinity(ctx, 9) + cached, found, err := cache.Get(cacheKey) + require.NoError(t, err) + assert.True(t, found) + assert.Equal(t, 1, cached, "off does not refresh session bindings") + _, err = cache.DeleteMany([]string{cacheKey}) + require.NoError(t, err) + RecordChannelAffinity(ctx, 9) + _, found, err = cache.Get(cacheKey) + require.NoError(t, err) + assert.False(t, found, "off does not establish session bindings") + } + }) + } + } +} diff --git a/service/log_info_generate.go b/service/log_info_generate.go index bf2e58d07d..c264390f8e 100644 --- a/service/log_info_generate.go +++ b/service/log_info_generate.go @@ -92,10 +92,14 @@ func AppendRelayLogAdminInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, } AppendChannelAffinityAdminInfo(ctx, other) + if events := RequestPolicy(ctx).Events(); len(events) > 0 { + other.SetAdmin("request_policy", events) + } } func GenerateTextOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, modelRatio, groupRatio, completionRatio float64, cacheTokens int, cacheRatio float64, modelPrice float64, userGroupRatio float64) *model.LogOther { + MarkRequestPolicySuccess(ctx, relayInfo.StreamStatus) other := model.NewLogOther() other.SetPublic("model_ratio", modelRatio) other.SetPublic("group_ratio", groupRatio) diff --git a/service/midjourney.go b/service/midjourney.go index 2276951028..c7783fdb63 100644 --- a/service/midjourney.go +++ b/service/midjourney.go @@ -2,7 +2,6 @@ package service import ( "context" - "encoding/json" "errors" "fmt" "io" @@ -273,6 +272,31 @@ func ConvertSimpleChangeParams(content string) *dto.MidjourneyRequest { return changeParams } +// RecordMidjourneyPolicyResponse distinguishes accepted tasks from errors inside +// HTTP 200 responses. Submissions are single-attempt: an ambiguous transport +// failure must never create a duplicate task on another channel. +func RecordMidjourneyPolicyResponse(c *gin.Context, response *dto.MidjourneyResponseWithStatusCode, requestErr error) bool { + if response == nil { + response = MidjourneyErrorWithStatusCodeWrapper(constant.MjErrorUnknown, "empty_response", http.StatusBadGateway) + } + accepted := requestErr == nil && response.StatusCode == http.StatusOK && (response.Response.Code == 1 || response.Response.Code == 21 || response.Response.Code == 22) + if accepted { + properties, _ := response.Response.Properties.(map[string]any) + if properties["status"] != "FAILURE" { + return true + } + } + state := RequestPolicy(c) + event := PolicyEvent{ChannelID: c.GetInt("channel_id"), Status: response.StatusCode, ErrorCode: strconv.Itoa(response.Response.Code), ErrorSource: "upstream", Decision: PolicyDecision{Action: "failure", Reason: "upstream_failure", Source: "upstream"}} + state.AddEvent(event) + event.Decision, event.Health = PolicyDecision{Action: "stop", Reason: "non_retryable_error", Source: "system"}, "unchanged" + if accepted { + event.Decision.Reason = "task_accepted" + } + state.AddEvent(event) + return false +} + func DoMidjourneyHttpRequest(c *gin.Context, timeout time.Duration, fullRequestURL string) (*dto.MidjourneyResponseWithStatusCode, []byte, error) { var nullBytes []byte //var requestBody io.Reader @@ -281,7 +305,7 @@ func DoMidjourneyHttpRequest(c *gin.Context, timeout time.Duration, fullRequestU var mapResult map[string]any // if get request, no need to read request body if c.Request.Method != "GET" { - err := json.NewDecoder(c.Request.Body).Decode(&mapResult) + err := common.DecodeJson(c.Request.Body, &mapResult) if err != nil { return MidjourneyErrorWithStatusCodeWrapper(constant.MjErrorUnknown, "read_request_body_failed", http.StatusInternalServerError), nullBytes, err } @@ -303,7 +327,7 @@ func DoMidjourneyHttpRequest(c *gin.Context, timeout time.Duration, fullRequestU mapResult["prompt"] = prompt } } - reqBody, err := json.Marshal(mapResult) + reqBody, err := common.Marshal(mapResult) if err != nil { return MidjourneyErrorWithStatusCodeWrapper(constant.MjErrorUnknown, "marshal_request_body_failed", http.StatusInternalServerError), nullBytes, err } @@ -350,9 +374,9 @@ func DoMidjourneyHttpRequest(c *gin.Context, timeout time.Duration, fullRequestU if len(responseBody) == 0 { return MidjourneyErrorWithStatusCodeWrapper(constant.MjErrorUnknown, "empty_response_body", statusCode), responseBody, nil } else { - err = json.Unmarshal(responseBody, &midjResponse) + err = common.Unmarshal(responseBody, &midjResponse) if err != nil { - err2 := json.Unmarshal(responseBody, &midjourneyUploadsResponse) + err2 := common.Unmarshal(responseBody, &midjourneyUploadsResponse) if err2 != nil { return MidjourneyErrorWithStatusCodeWrapper(constant.MjErrorUnknown, "unmarshal_response_body_failed", statusCode), responseBody, err } diff --git a/service/relay_error.go b/service/relay_error.go index 14462fbc4c..b788015682 100644 --- a/service/relay_error.go +++ b/service/relay_error.go @@ -16,36 +16,49 @@ import ( "github.com/gin-gonic/gin" ) -func ShouldRetryRelayError(c *gin.Context, openaiErr *types.NewAPIError, retryTimes int) bool { - if openaiErr == nil { - return false +// DecideRelayRetry is the single retry decision for relay attempts. The reason +// is recorded in the request policy decision events of the log details. +func DecideRelayRetry(c *gin.Context, err *types.NewAPIError, retryTimes int) PolicyDecision { + if err == nil { + return PolicyDecision{Action: "stop", Reason: "request_completed", Source: "system"} } if ShouldSkipRetryAfterChannelAffinityFailure(c) { - return false + source := RequestPolicy(c).SessionModeSource + if source == "" { + source = "session_rule" + } + return PolicyDecision{Action: "stop", Reason: "strict_session", Source: source} } if GetChannelConstraints(c).SuppressesRetry() { - return false + return PolicyDecision{Action: "stop", Reason: "pinned_channel", Source: "channel_constraint"} } - if types.IsChannelError(openaiErr) { - return true + if types.IsChannelError(err) { + return PolicyDecision{Action: "retry", Reason: "channel_error", Source: "system"} } - if types.IsSkipRetryError(openaiErr) { - return false + if types.IsSkipRetryError(err) { + return PolicyDecision{Action: "stop", Reason: "non_retryable_error", Source: "system"} } if retryTimes <= 0 { - return false + return PolicyDecision{Action: "stop", Reason: "attempt_budget_exhausted", Source: "global"} } - code := openaiErr.StatusCode + code := err.StatusCode if code >= 200 && code < 300 { - return false + return PolicyDecision{Action: "stop", Reason: "system_retry_exclusion", Source: "system"} } if code < 100 || code > 599 { - return true + return PolicyDecision{Action: "retry", Reason: "unrecognized_status", Source: "system"} } - if operation_setting.IsAlwaysSkipRetryCode(openaiErr.GetErrorCode()) { - return false + if operation_setting.IsAlwaysSkipRetryCode(err.GetErrorCode()) || operation_setting.IsAlwaysSkipRetryStatusCode(code) { + return PolicyDecision{Action: "stop", Reason: "system_retry_exclusion", Source: "system"} } - return operation_setting.ShouldRetryByStatusCode(code) + if operation_setting.ShouldRetryByStatusCode(code) { + return PolicyDecision{Action: "retry", Reason: "retry_status_matched", Source: "global"} + } + return PolicyDecision{Action: "stop", Reason: "status_not_retryable", Source: "global"} +} + +func ShouldRetryRelayError(c *gin.Context, openaiErr *types.NewAPIError, retryTimes int) bool { + return DecideRelayRetry(c, openaiErr, retryTimes).Action == "retry" } func ProcessChannelError(c *gin.Context, channelError types.ChannelError, err *types.NewAPIError, relayInfo *relaycommon.RelayInfo) { diff --git a/service/relay_error_test.go b/service/relay_error_test.go index 8b71844eea..6bcfe696cc 100644 --- a/service/relay_error_test.go +++ b/service/relay_error_test.go @@ -124,3 +124,90 @@ func TestProcessChannelErrorMasksDisableReasonAndNotification(t *testing.T) { assert.NotContains(t, notification.Content, "review-secret") assert.Equal(t, http.StatusUnauthorized, apiErr.StatusCode) } + +func TestDecideRelayRetryReasons(t *testing.T) { + upstream := func(status int) *types.NewAPIError { + return types.NewOpenAIError(errors.New("upstream"), types.ErrorCodeBadResponseStatusCode, status) + } + for _, tc := range []struct { + name string + err *types.NewAPIError + retries int + setup func(*gin.Context) + want PolicyDecision + }{ + {name: "retry status matched", err: upstream(http.StatusTooManyRequests), retries: 1, want: PolicyDecision{Action: "retry", Reason: "retry_status_matched", Source: "global"}}, + {name: "status outside retry rules", err: upstream(http.StatusBadRequest), retries: 1, want: PolicyDecision{Action: "stop", Reason: "status_not_retryable", Source: "global"}}, + {name: "attempt budget exhausted", err: upstream(http.StatusTooManyRequests), retries: 0, want: PolicyDecision{Action: "stop", Reason: "attempt_budget_exhausted", Source: "global"}}, + {name: "always skipped status", err: upstream(http.StatusGatewayTimeout), retries: 1, want: PolicyDecision{Action: "stop", Reason: "system_retry_exclusion", Source: "system"}}, + {name: "success status never retries", err: upstream(http.StatusOK), retries: 1, want: PolicyDecision{Action: "stop", Reason: "system_retry_exclusion", Source: "system"}}, + {name: "skip retry error", err: types.NewErrorWithStatusCode(errors.New("local"), types.ErrorCodeInvalidRequest, http.StatusBadRequest, types.ErrOptionWithSkipRetry()), retries: 1, want: PolicyDecision{Action: "stop", Reason: "non_retryable_error", Source: "system"}}, + {name: "channel error retries without budget", err: types.NewError(errors.New("no key"), types.ErrorCodeChannelNoAvailableKey), retries: 0, want: PolicyDecision{Action: "retry", Reason: "channel_error", Source: "system"}}, + {name: "single attempt pin", err: upstream(http.StatusTooManyRequests), retries: 1, setup: func(c *gin.Context) { + GetChannelConstraints(c).AddPin(dto.ChannelPin{ChannelId: 1, Source: dto.PinSourceToken, Rank: dto.PinRankToken, RetryMode: dto.PinRetrySingleAttempt}) + }, want: PolicyDecision{Action: "stop", Reason: "pinned_channel", Source: "channel_constraint"}}, + {name: "strict session", err: upstream(http.StatusTooManyRequests), retries: 1, setup: func(c *gin.Context) { + c.Set(ginKeyChannelAffinitySkipRetry, true) + RequestPolicy(c).SessionModeSource = "global" + }, want: PolicyDecision{Action: "stop", Reason: "strict_session", Source: "global"}}, + {name: "nil error", retries: 1, want: PolicyDecision{Action: "stop", Reason: "request_completed", Source: "system"}}, + } { + t.Run(tc.name, func(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + if tc.setup != nil { + tc.setup(c) + } + decision := DecideRelayRetry(c, tc.err, tc.retries) + assert.Equal(t, tc.want, decision) + assert.Equal(t, tc.want.Action == "retry", ShouldRetryRelayError(c, tc.err, tc.retries)) + }) + } +} + +func TestRequestPolicyEventsReachLogAdminInfo(t *testing.T) { + previousAutoDisable := common.AutomaticDisableChannelEnabled + common.AutomaticDisableChannelEnabled = true + t.Cleanup(func() { common.AutomaticDisableChannelEnabled = previousAutoDisable }) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + c.Set("auto_ban", true) + c.Set("channel_id", 7) + state := RequestPolicy(c) + state.BeginAttempt(&model.Channel{Id: 7}, "default") + apiErr := types.NewOpenAIError(errors.New("invalid credential"), types.ErrorCodeBadResponseStatusCode, http.StatusUnauthorized) + RecordPolicyFailure(c, 7, apiErr, DecideRelayRetry(c, apiErr, 0)) + + failed := model.NewLogOther() + AppendRelayLogAdminInfo(c, nil, failed) + events, ok := failed.Snapshot()["admin_info"].(map[string]any)["request_policy"].([]PolicyEvent) + require.True(t, ok, "a failed relay exposes its decision events to administrators") + require.Len(t, events, 3) + assert.Equal(t, PolicyDecision{Action: "attempt", Reason: "channel_selected", Source: "routing"}, events[0].Decision) + assert.Equal(t, "default", events[0].Group) + assert.Equal(t, PolicyDecision{Action: "failure", Reason: "upstream_failure", Source: "upstream"}, events[1].Decision) + assert.Equal(t, http.StatusUnauthorized, events[1].Status) + assert.Equal(t, PolicyDecision{Action: "stop", Reason: "attempt_budget_exhausted", Source: "global"}, events[2].Decision) + assert.Equal(t, "channel_disable_requested", events[2].Health, "the health entry follows the automatic disable rules") + common.SetContextKey(c, constant.ContextKeyChannelIsMultiKey, true) + RecordPolicyFailure(c, 7, apiErr, DecideRelayRetry(c, apiErr, 0)) + assert.Equal(t, "key_disable_requested", state.Events()[4].Health) + + state.BeginAttempt(&model.Channel{Id: 8}, "default") + c.Set("channel_id", 8) + MarkRequestPolicySuccess(c, nil) + MarkRequestPolicySuccess(c, nil) + succeeded := model.NewLogOther() + AppendRelayLogAdminInfo(c, nil, succeeded) + events, ok = succeeded.Snapshot()["admin_info"].(map[string]any)["request_policy"].([]PolicyEvent) + require.True(t, ok, "a successful relay exposes its decision events to administrators") + require.Len(t, events, 7, "the outcome is recorded once") + assert.Equal(t, PolicyDecision{Action: "success", Reason: "request_completed", Source: "upstream"}, events[6].Decision) + assert.Equal(t, 8, events[6].ChannelID) + assert.Equal(t, 2, events[6].Attempt) + assert.True(t, state.Successful) + + untouched, _ := gin.CreateTestContext(httptest.NewRecorder()) + other := model.NewLogOther() + AppendRelayLogAdminInfo(untouched, nil, other) + assert.NotContains(t, other.Snapshot()["admin_info"], "request_policy", "requests without decisions do not carry an empty record") +} diff --git a/service/request_policy.go b/service/request_policy.go new file mode 100644 index 0000000000..d73ab45db1 --- /dev/null +++ b/service/request_policy.go @@ -0,0 +1,182 @@ +package service + +import ( + "slices" + "sync" + "time" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/constant" + "github.com/QuantumNous/new-api/model" + relaycommon "github.com/QuantumNous/new-api/relay/common" + "github.com/QuantumNous/new-api/relaykit/types" + "github.com/QuantumNous/new-api/setting/operation_setting" + "github.com/gin-gonic/gin" +) + +const requestPolicyContextKey = "request_policy_state" + +type PolicyDecision struct { + Action string `json:"action"` + Reason string `json:"reason"` + Source string `json:"source"` +} + +type PolicyEvent struct { + Attempt int `json:"attempt"` + ChannelID int `json:"channel_id,omitempty"` + Group string `json:"group,omitempty"` + Rule string `json:"rule,omitempty"` + Status int `json:"status,omitempty"` + ErrorCode string `json:"error_code,omitempty"` + ErrorSource string `json:"error_source,omitempty"` + ElapsedMS int64 `json:"elapsed_ms"` + Decision PolicyDecision `json:"decision"` + Health string `json:"health,omitempty"` +} + +// RequestPolicyState records how one request was routed so administrators can +// read the decision flow in the log details. Channel selection and the retry +// decision stay in the relay flows; this state only records them. +type RequestPolicyState struct { + FinalLogged bool + StartedAt time.Time + Attempts int + SelectedGroup string + SessionMode string + SessionModeSource string + RuleName string + Successful bool + OutcomeRecorded bool + mu sync.Mutex + events []PolicyEvent +} + +func RequestPolicy(c *gin.Context) *RequestPolicyState { + if c != nil { + if value, ok := c.Get(requestPolicyContextKey); ok { + return value.(*RequestPolicyState) + } + } + state := &RequestPolicyState{StartedAt: time.Now()} + if c != nil { + c.Set(requestPolicyContextKey, state) + } + return state +} + +func (s *RequestPolicyState) AddEvent(event PolicyEvent) { + event.Attempt, event.ElapsedMS = s.Attempts, time.Since(s.StartedAt).Milliseconds() + if event.Group == "" { + event.Group = s.SelectedGroup + } + if event.Rule == "" { + event.Rule = s.RuleName + } + s.mu.Lock() + defer s.mu.Unlock() + if len(s.events) < 512 { + s.events = append(s.events, event) + } +} + +func (s *RequestPolicyState) Events() []PolicyEvent { + s.mu.Lock() + defer s.mu.Unlock() + return slices.Clone(s.events) +} + +func (s *RequestPolicyState) BeginAttempt(channel *model.Channel, group string) { + s.Attempts++ + s.Successful = false + s.OutcomeRecorded = false + s.SelectedGroup = group + s.AddEvent(PolicyEvent{ChannelID: channel.Id, Decision: PolicyDecision{Action: "attempt", Reason: "channel_selected", Source: "routing"}}) +} + +// RecordPolicyFailure appends the failed attempt and the retry decision made +// for it. The health entry mirrors the check in ProcessChannelError, which +// performs the actual disable. +func RecordPolicyFailure(c *gin.Context, channelID int, err *types.NewAPIError, decision PolicyDecision) { + if c == nil || err == nil { + return + } + source := "upstream" + switch { + case types.IsChannelError(err): + source = "channel" + case err.GetErrorCode() == types.ErrorCodeDoRequestFailed: + source = "transport" + case err.GetErrorType() == types.ErrorTypeNewAPIError: + source = "local" + } + state := RequestPolicy(c) + event := PolicyEvent{ChannelID: channelID, Status: err.StatusCode, ErrorCode: string(err.GetErrorCode()), ErrorSource: source, Decision: PolicyDecision{Action: "failure", Reason: "upstream_failure", Source: source}} + if source == "local" { + event.Decision.Reason = "local_rejection" + } + state.AddEvent(event) + event.Decision, event.Health = decision, "unchanged" + if source != "local" && c.GetBool("auto_ban") && ShouldDisableChannel(err) { + event.Health = "channel_disable_requested" + if common.GetContextKeyBool(c, constant.ContextKeyChannelIsMultiKey) { + event.Health = "key_disable_requested" + } + } + state.AddEvent(event) +} + +func MarkRequestPolicySuccess(c *gin.Context, stream *relaycommon.StreamStatus) { + state := RequestPolicy(c) + if state.OutcomeRecorded { + return + } + state.OutcomeRecorded = true + state.Successful = stream == nil || stream.IsNormalEnd() && !stream.HasErrors() && (stream.ResponseOutcome() == "" || stream.ResponseOutcome() == "completed") + decision := PolicyDecision{Action: "success", Reason: "request_completed", Source: "upstream"} + if !state.Successful { + decision = PolicyDecision{Action: "stop", Reason: "stream_not_successful", Source: "system"} + } + channelID := 0 + if c != nil { + channelID = c.GetInt("channel_id") + } + state.AddEvent(PolicyEvent{ChannelID: channelID, Decision: decision}) +} + +// Rules explicitly inherit the global default or override it. Rules without a +// mode retain their legacy retry behavior until an administrator changes them. +func EffectiveSessionMode(setting *operation_setting.ChannelAffinitySetting, rule operation_setting.ChannelAffinityRule) (mode, source string) { + if rule.SessionMode == "inherit" { + if setting.SessionMode != "" { + return setting.SessionMode, "global" + } + return "prefer", "global" + } + if rule.SessionMode != "" { + return rule.SessionMode, "session_rule" + } + if rule.SkipRetryOnFailure { + return "strict", "session_rule" + } + return "prefer", "session_rule" +} + +// RecordRequestPolicyTermination appends the final decision after routing has +// stopped. It never writes a log row itself: the per-channel error log written +// by ProcessChannelError already carries the decision record, so a second row +// here would duplicate it. +func RecordRequestPolicyTermination(c *gin.Context, apiErr *types.NewAPIError) { + if c == nil || apiErr == nil { + return + } + state := RequestPolicy(c) + if state.FinalLogged { + return + } + state.FinalLogged = true + events := state.Events() + if len(events) == 0 || events[len(events)-1].Decision.Action != "stop" { + state.AddEvent(PolicyEvent{ChannelID: c.GetInt("channel_id"), Status: apiErr.StatusCode, ErrorCode: string(apiErr.GetErrorCode()), Decision: PolicyDecision{Action: "stop", Reason: "request_failed", Source: "system"}, Health: "unchanged"}) + } +} diff --git a/setting/operation_setting/channel_affinity_setting.go b/setting/operation_setting/channel_affinity_setting.go index 79c5af3c2f..8267cefbb7 100644 --- a/setting/operation_setting/channel_affinity_setting.go +++ b/setting/operation_setting/channel_affinity_setting.go @@ -21,6 +21,9 @@ type ChannelAffinityRule struct { ParamOverrideTemplate map[string]any `json:"param_override_template,omitempty"` SkipRetryOnFailure bool `json:"skip_retry_on_failure"` + // "inherit" uses the global default; off/prefer/strict override it. + // Empty preserves the legacy SkipRetryOnFailure behavior. + SessionMode string `json:"session_mode,omitempty"` IncludeUsingGroup bool `json:"include_using_group"` IncludeModelName bool `json:"include_model_name"` @@ -28,7 +31,9 @@ type ChannelAffinityRule struct { } type ChannelAffinitySetting struct { - Enabled bool `json:"enabled"` + Enabled bool `json:"enabled"` + // Default for rules with SessionMode "inherit". Empty defaults to "prefer". + SessionMode string `json:"session_mode"` SwitchOnSuccess bool `json:"switch_on_success"` KeepOnChannelDisabled bool `json:"keep_on_channel_disabled"` MaxEntries int `json:"max_entries"` diff --git a/web/.oxlintrc.json b/web/.oxlintrc.json index 9faf2d7e32..7120abb125 100644 --- a/web/.oxlintrc.json +++ b/web/.oxlintrc.json @@ -120,6 +120,9 @@ "getOperationsSectionNavItems", "getOperationsSectionContent", "getOperationsSectionMeta", + "getPolicySectionNavItems", + "getPolicySectionContent", + "getPolicySectionMeta", "getSecuritySectionNavItems", "getSecuritySectionContent", "getSecuritySectionMeta", diff --git a/web/src/components/layout/config/system-settings.config.ts b/web/src/components/layout/config/system-settings.config.ts index 8469c02786..06a6f045ad 100644 --- a/web/src/components/layout/config/system-settings.config.ts +++ b/web/src/components/layout/config/system-settings.config.ts @@ -16,9 +16,10 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import { type TFunction } from 'i18next' +import type { TFunction } from 'i18next' import { Box, + Route, CreditCard, Layout, Settings, @@ -32,6 +33,7 @@ import { getBillingSectionNavItems } from '@/features/system-settings/billing/se import { getContentSectionNavItems } from '@/features/system-settings/content/section-registry.tsx' import { getModelsSectionNavItems } from '@/features/system-settings/models/section-registry.tsx' import { getOperationsSectionNavItems } from '@/features/system-settings/operations/section-registry.tsx' +import { getPolicySectionNavItems } from '@/features/system-settings/request-policies/section-registry' import { getSecuritySectionNavItems } from '@/features/system-settings/security/section-registry.tsx' import { getSiteSectionNavItems } from '@/features/system-settings/site/section-registry.tsx' @@ -66,10 +68,15 @@ function getSystemSettingsNavGroups(t: TFunction): NavGroup[] { items: getBillingSectionNavItems(t), }, { - title: t('Models & Routing'), + title: t('Models'), icon: Box, items: getModelsSectionNavItems(t), }, + { + title: t('Request policies'), + icon: Route, + items: getPolicySectionNavItems(t), + }, { title: t('Security & Limits'), icon: ShieldAlert, diff --git a/web/src/features/channels/api.ts b/web/src/features/channels/api.ts index 489834d19f..a581552b98 100644 --- a/web/src/features/channels/api.ts +++ b/web/src/features/channels/api.ts @@ -143,8 +143,13 @@ export async function getChannel(id: number): Promise { /** * Get channel operations summary for administrators */ -export async function getChannelOps(): Promise { - const res = await api.get('/api/channel/ops', channelActionConfig()) +export async function getChannelOps( + autoBan?: boolean +): Promise { + const res = await api.get('/api/channel/ops', { + ...channelActionConfig(), + params: autoBan === undefined ? undefined : { auto_ban: autoBan }, + }) return res.data } diff --git a/web/src/features/channels/components/__tests__/channel-configuration.test.tsx b/web/src/features/channels/components/__tests__/channel-configuration.test.tsx index 6fcc46c333..d1504e9984 100644 --- a/web/src/features/channels/components/__tests__/channel-configuration.test.tsx +++ b/web/src/features/channels/components/__tests__/channel-configuration.test.tsx @@ -17,6 +17,12 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { + createRouter, + createRootRoute, + createMemoryHistory, + RouterContextProvider, +} from '@tanstack/react-router' import { act, cleanup, @@ -95,18 +101,28 @@ function ConfigurationHarness(props: { clearRowOnClose?: boolean }) { const [open, setOpen] = useState(props.initialOpen ?? true) + const [router] = useState(() => + createRouter({ + routeTree: createRootRoute(), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + ) return ( - - - - + + + + + + ) } diff --git a/web/src/features/channels/components/__tests__/inference-status.test.tsx b/web/src/features/channels/components/__tests__/inference-status.test.tsx index d92b8aac20..5ce7a77da6 100644 --- a/web/src/features/channels/components/__tests__/inference-status.test.tsx +++ b/web/src/features/channels/components/__tests__/inference-status.test.tsx @@ -17,6 +17,12 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { + createRouter, + createRootRoute, + createMemoryHistory, + RouterContextProvider, +} from '@tanstack/react-router' import { act, cleanup, @@ -485,15 +491,21 @@ it.each([ vi.spyOn(api, 'get').mockImplementation(async (url) => ({ data: { success: true, data: url === '/api/channel/42' ? channel : [] }, })) + const router = createRouter({ + routeTree: createRootRoute(), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) render( - - - + + + + + ) expect(await screen.findByDisplayValue('Inference')).toBeInTheDocument() diff --git a/web/src/features/channels/components/channel-quick-options.tsx b/web/src/features/channels/components/channel-quick-options.tsx index bad53311b4..b9213914b7 100644 --- a/web/src/features/channels/components/channel-quick-options.tsx +++ b/web/src/features/channels/components/channel-quick-options.tsx @@ -24,6 +24,7 @@ import { FieldGroup } from '@/components/ui/field' import { Label } from '@/components/ui/label' import { Switch } from '@/components/ui/switch' import { SettingsSwitchField } from '@/features/system-settings/components/settings-form-layout' +import { ChannelHealthSource } from '@/features/system-settings/request-policies/related-policy-link' import { cn } from '@/lib/utils' import { CHANNEL_TYPE_TASK_PLUGIN, MODEL_FETCHABLE_TYPES } from '../constants' @@ -89,7 +90,7 @@ export function ChannelQuickOptions(props: ChannelQuickOptionsProps) { options.push({ key: 'auto-ban', label: t('Auto-disable channel'), - description: t('Disable channels on repeated failures'), + description: , checked: (autoBan ?? 1) === 1, onCheckedChange: (value) => form.setValue('auto_ban', value ? 1 : 0, { diff --git a/web/src/features/channels/index.tsx b/web/src/features/channels/index.tsx index 28c27d587d..a34d037f34 100644 --- a/web/src/features/channels/index.tsx +++ b/web/src/features/channels/index.tsx @@ -64,8 +64,8 @@ export function Channels() { aria-label={t('Retry Settings')} render={ } /> diff --git a/web/src/features/channels/types.ts b/web/src/features/channels/types.ts index efc4e0943f..e817448a75 100644 --- a/web/src/features/channels/types.ts +++ b/web/src/features/channels/types.ts @@ -182,6 +182,10 @@ export interface ChannelOpsResponse { message?: string data?: { retry_times: number + request_policy?: { + automatic_disable: boolean + source: string + } } } diff --git a/web/src/features/keys/components/api-keys-mutate-drawer.tsx b/web/src/features/keys/components/api-keys-mutate-drawer.tsx index 6a3a79f15f..6d60c08205 100644 --- a/web/src/features/keys/components/api-keys-mutate-drawer.tsx +++ b/web/src/features/keys/components/api-keys-mutate-drawer.tsx @@ -62,6 +62,7 @@ import { } from '@/components/ui/sheet' import { Switch } from '@/components/ui/switch' import { Textarea } from '@/components/ui/textarea' +import { RelatedPolicyLink } from '@/features/system-settings/request-policies/related-policy-link' import { useStatus } from '@/hooks/use-status' import { getUserModels, getUserGroups } from '@/lib/api' import { getCurrencyDisplay, getCurrencyLabel } from '@/lib/currency' @@ -500,6 +501,7 @@ export function ApiKeysMutateDrawer({ {t( 'When enabled, if channels in the current group fail, it will try channels in the next group in order.' )} + diff --git a/web/src/features/system-settings/components/settings-accordion.tsx b/web/src/features/system-settings/components/settings-accordion.tsx index 6ef06c8f1d..45f243d242 100644 --- a/web/src/features/system-settings/components/settings-accordion.tsx +++ b/web/src/features/system-settings/components/settings-accordion.tsx @@ -28,6 +28,7 @@ type SettingsAccordionProps = { title: string children: React.ReactNode className?: string + keepMounted?: boolean } export function SettingsAccordion({ @@ -35,6 +36,7 @@ export function SettingsAccordion({ title, children, className, + keepMounted, }: SettingsAccordionProps) { return ( @@ -43,7 +45,9 @@ export function SettingsAccordion({
{title}
- {children} + + {children} +
) } diff --git a/web/src/features/system-settings/components/settings-page.tsx b/web/src/features/system-settings/components/settings-page.tsx index 678b387e0c..2e04b25fe1 100644 --- a/web/src/features/system-settings/components/settings-page.tsx +++ b/web/src/features/system-settings/components/settings-page.tsx @@ -20,6 +20,7 @@ import { useParams } from '@tanstack/react-router' import { useMemo, useState, type ReactNode } from 'react' import { useTranslation } from 'react-i18next' +import { ErrorState } from '@/components/error-state' import { SectionPageLayout } from '@/components/layout' import { useSystemOptions, getOptionValue } from '../hooks/use-system-options' @@ -111,7 +112,7 @@ export function SettingsPage< resolveSettings, }: SettingsPageProps) { const { t } = useTranslation() - const { data, isLoading } = useSystemOptions() + const { data, isLoading, isError, refetch } = useSystemOptions() // eslint-disable-next-line @typescript-eslint/no-explicit-any const params = useParams({ from: routePath as any }) const activeSection = (params?.section ?? defaultSection) as TSectionId @@ -137,6 +138,17 @@ export function SettingsPage< ) } + if (isError && !data) { + return ( + + void refetch()} + /> + + ) + } + const sectionContent = getSectionContent( activeSection, settings, diff --git a/web/src/features/system-settings/general/channel-affinity/index.tsx b/web/src/features/system-settings/general/channel-affinity/index.tsx index f24a68fe3f..e97446620d 100644 --- a/web/src/features/system-settings/general/channel-affinity/index.tsx +++ b/web/src/features/system-settings/general/channel-affinity/index.tsx @@ -16,36 +16,43 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import { Edit, FileText, Plus, RefreshCw, Trash2, X } from 'lucide-react' -import { useCallback, useEffect, useState, type ReactNode } from 'react' +import { + Braces, + Database, + FileText, + ListFilter, + Plus, + RefreshCw, + Trash2, +} from 'lucide-react' +import { useCallback, useEffect, useMemo, useState } from 'react' import { useTranslation } from 'react-i18next' import { toast } from 'sonner' -import { StaticDataTable } from '@/components/data-table' -import { Dialog } from '@/components/dialog' +import { ConfirmDialog } from '@/components/confirm-dialog' import { JsonCodeEditor } from '@/components/json-code-editor' -import { StatusBadge, StatusBadgeList } from '@/components/status-badge' -import { Alert, AlertDescription } from '@/components/ui/alert' +import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { DropdownMenu, DropdownMenuContent, + DropdownMenuGroup, DropdownMenuItem, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu' -import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Separator } from '@/components/ui/separator' +import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' +import { toIntlLocale } from '@/i18n/languages' +import { formatNumber } from '@/lib/format' import { handleServerError } from '@/lib/handle-server-error' +import { cn } from '@/lib/utils' -import { SettingsSwitchField } from '../../components/settings-form-layout' -import { SettingsPageActionsPortal } from '../../components/settings-page-context' -import { SettingsSection } from '../../components/settings-section' -import { useUpdateOption } from '../../hooks/use-update-option' import { getCacheStats, clearAllCache, clearRuleCache } from './api' import { RULE_TEMPLATES, cloneTemplate, makeUniqueName } from './constants' import { RuleEditorDialog } from './rule-editor-dialog' -import type { AffinityRule, CacheStats, ChannelAffinitySettings } from './types' +import { SessionRulesTable } from './session-rules-table' +import type { AffinityRule, CacheStats, SessionMode } from './types' function parseRules(jsonStr: string): AffinityRule[] { try { @@ -60,138 +67,33 @@ function parseRules(jsonStr: string): AffinityRule[] { } } -function RuleBadgeList(props: { items: string[] }) { - return ( - item} - renderItem={(item) => ( - - )} - /> - ) -} - -function ChannelAffinityConfirmDialog(props: { - open: boolean - onOpenChange: (open: boolean) => void - title: ReactNode - desc: ReactNode - handleConfirm: () => void - destructive?: boolean -}) { - const { t } = useTranslation() - - return ( - - - - - } - > -
{props.desc}
-
- ) -} - function serializeRules(rules: AffinityRule[]): string { return JSON.stringify(rules.map(({ id: _, ...rest }) => rest)) } interface Props { - defaultValues: ChannelAffinitySettings + rulesJson: string + onRulesChange: (rules: string) => void + enabled?: boolean + globalSessionMode?: SessionMode | '' } export function ChannelAffinitySection(props: Props) { - const { t } = useTranslation() - const updateOption = useUpdateOption() - - const [enabled, setEnabled] = useState( - props.defaultValues['channel_affinity_setting.enabled'] - ) - const [switchOnSuccess, setSwitchOnSuccess] = useState( - props.defaultValues['channel_affinity_setting.switch_on_success'] - ) - const [keepOnChannelDisabled, setKeepOnChannelDisabled] = useState( - props.defaultValues['channel_affinity_setting.keep_on_channel_disabled'] - ) - const [maxEntries, setMaxEntries] = useState( - props.defaultValues['channel_affinity_setting.max_entries'] - ) - const [defaultTtl, setDefaultTtl] = useState( - props.defaultValues['channel_affinity_setting.default_ttl_seconds'] - ) - const [rules, setRules] = useState(() => - parseRules(props.defaultValues['channel_affinity_setting.rules']) - ) - + const { t, i18n } = useTranslation() + const locale = toIntlLocale(i18n.resolvedLanguage || i18n.language) + const rules = useMemo(() => parseRules(props.rulesJson), [props.rulesJson]) const [editMode, setEditMode] = useState<'visual' | 'json'>('visual') - const [jsonText, setJsonText] = useState(() => - JSON.stringify( - parseRules(props.defaultValues['channel_affinity_setting.rules']).map( - ({ id: _, ...r }) => r - ), - null, - 2 - ) - ) const [cacheStats, setCacheStats] = useState(null) const [cacheLoading, setCacheLoading] = useState(false) - const [saving, setSaving] = useState(false) const [ruleEditorOpen, setRuleEditorOpen] = useState(false) const [editingRule, setEditingRule] = useState(null) const [ruleTemplateKey, setRuleTemplateKey] = useState(null) + const [deletingRule, setDeletingRule] = useState(null) const [clearAllDialogOpen, setClearAllDialogOpen] = useState(false) const [clearRuleName, setClearRuleName] = useState(null) const [fillTemplateDialogOpen, setFillTemplateDialogOpen] = useState(false) - useEffect(() => { - setEnabled(props.defaultValues['channel_affinity_setting.enabled']) - setSwitchOnSuccess( - props.defaultValues['channel_affinity_setting.switch_on_success'] - ) - setKeepOnChannelDisabled( - props.defaultValues['channel_affinity_setting.keep_on_channel_disabled'] - ) - setMaxEntries(props.defaultValues['channel_affinity_setting.max_entries']) - setDefaultTtl( - props.defaultValues['channel_affinity_setting.default_ttl_seconds'] - ) - const parsed = parseRules( - props.defaultValues['channel_affinity_setting.rules'] - ) - setRules(parsed) - setJsonText( - JSON.stringify( - parsed.map(({ id: _, ...r }) => r), - null, - 2 - ) - ) - }, [props.defaultValues]) - const refreshCache = useCallback(async () => { setCacheLoading(true) try { @@ -209,7 +111,7 @@ export function ChannelAffinitySection(props: Props) { }, [t]) useEffect(() => { - refreshCache() + void refreshCache() }, [refreshCache]) const appendCliTemplates = () => { @@ -224,9 +126,7 @@ export function ChannelAffinitySection(props: Props) { return { ...base, name } }) - setRules((prev) => - [...prev, ...templates].map((r, idx) => ({ ...r, id: idx })) - ) + props.onRulesChange(serializeRules([...rules, ...templates])) toast.success(t('Templates appended')) setFillTemplateDialogOpen(false) } @@ -239,124 +139,15 @@ export function ChannelAffinitySection(props: Props) { } } - const handleSave = async () => { - let rulesJson: string - if (editMode === 'json') { - try { - const parsed = JSON.parse(jsonText) - if (!Array.isArray(parsed)) { - toast.error(t('Rules JSON must be an array')) - return - } - rulesJson = JSON.stringify(parsed) - } catch { - toast.error(t('Invalid rules JSON format')) - return - } - } else { - rulesJson = serializeRules(rules) - } - - setSaving(true) - try { - const updates: { key: string; value: string }[] = [] - - if (enabled !== props.defaultValues['channel_affinity_setting.enabled']) { - updates.push({ - key: 'channel_affinity_setting.enabled', - value: String(enabled), - }) - } - if ( - switchOnSuccess !== - props.defaultValues['channel_affinity_setting.switch_on_success'] - ) { - updates.push({ - key: 'channel_affinity_setting.switch_on_success', - value: String(switchOnSuccess), - }) - } - if ( - keepOnChannelDisabled !== - props.defaultValues['channel_affinity_setting.keep_on_channel_disabled'] - ) { - updates.push({ - key: 'channel_affinity_setting.keep_on_channel_disabled', - value: String(keepOnChannelDisabled), - }) - } - if ( - maxEntries !== - props.defaultValues['channel_affinity_setting.max_entries'] - ) { - updates.push({ - key: 'channel_affinity_setting.max_entries', - value: String(maxEntries), - }) - } - if ( - defaultTtl !== - props.defaultValues['channel_affinity_setting.default_ttl_seconds'] - ) { - updates.push({ - key: 'channel_affinity_setting.default_ttl_seconds', - value: String(defaultTtl), - }) - } - - const origRules = props.defaultValues['channel_affinity_setting.rules'] - const origSerialized = (() => { - try { - return JSON.stringify(JSON.parse(origRules || '[]')) - } catch { - return '[]' - } - })() - if (rulesJson !== origSerialized) { - updates.push({ - key: 'channel_affinity_setting.rules', - value: rulesJson, - }) - } - - if (updates.length === 0) { - toast.info(t('No changes')) - return - } - - for (const u of updates) { - await updateOption.mutateAsync(u) - } - toast.success(t('Saved successfully')) - } catch (error) { - handleServerError(error, t('Failed to save')) - } finally { - setSaving(false) - } - } - const handleRuleSave = (rule: AffinityRule) => { - setRules((prev) => { - const existIdx = prev.findIndex( - (r) => r.id === rule.id || (rule.name && r.name === editingRule?.name) - ) - if (existIdx >= 0) { - const next = [...prev] - next[existIdx] = { ...rule, id: existIdx } - return next - } - return [...prev, { ...rule, id: prev.length }] - }) + const index = rules.findIndex((item) => item.id === editingRule?.id) + const next = [...rules] + if (index >= 0) next[index] = rule + else next.push(rule) + props.onRulesChange(serializeRules(next)) setEditingRule(null) } - const handleDeleteRule = (idx: number) => { - setRules((prev) => - prev.filter((_, i) => i !== idx).map((r, i) => ({ ...r, id: i })) - ) - toast.success(t('Deleted successfully')) - } - const handleClearAll = async () => { try { const res = await clearAllCache() @@ -389,7 +180,7 @@ export function ChannelAffinitySection(props: Props) { } const switchToJsonMode = () => { - setJsonText( + props.onRulesChange( JSON.stringify( rules.map(({ id: _, ...r }) => r), null, @@ -401,17 +192,11 @@ export function ChannelAffinitySection(props: Props) { const switchToVisualMode = () => { try { - const parsed = JSON.parse(jsonText) + const parsed: unknown = JSON.parse(props.rulesJson) if (!Array.isArray(parsed)) { toast.error(t('Rules JSON must be an array')) return } - setRules( - parsed.map( - (r: Record, i: number) => - ({ id: i, ...r }) as AffinityRule - ) - ) setEditMode('visual') } catch { toast.error(t('Invalid rules JSON format')) @@ -420,276 +205,197 @@ export function ChannelAffinitySection(props: Props) { return ( <> - - - - {t( - 'Channel affinity reuses the last successful channel based on keys extracted from the request context or JSON body.' - )} - - - - {/* Basic Settings */} -
- -
- - setMaxEntries(Number(e.target.value))} - /> -
-
- - setDefaultTtl(Number(e.target.value))} - /> +
+
+
+

{t('Session rules')}

+ + {rules.length} +
+

+ {t('How a session is identified and which channel it keeps.')} +

- - - - - - - - - - - } - > - - {t('Add Rule')} - - - { - setEditingRule(null) - setRuleTemplateKey(null) - setRuleEditorOpen(true) - }} + { + if (value === 'json') switchToJsonMode() + else switchToVisualMode() + }} + className='gap-0' + > +
+ + + + + + +
+ - - - - {cacheStats && ( - - {t('Cache Entries')}: {cacheStats.total} /{' '} - {cacheStats.cache_capacity} - - )} - - - {/* Rules Table or JSON Editor */} - {editMode === 'visual' ? ( - rule.name || '-', - }, - { - id: 'model-regex', - header: t('Model Regex'), - cell: (rule) => ( - - ), - }, - { - id: 'key-sources', - header: t('Key Sources'), - cell: (rule) => ( - - `${src.type}:${src.type === 'gjson' ? src.path : src.key}` - )} - /> - ), - }, - { - id: 'ttl', - header: t('TTL'), - cell: (rule) => rule.ttl_seconds || '-', - }, - { - id: 'retry', - header: t('Retry'), - cell: (rule) => ( - - ), - }, - { - id: 'scope', - header: t('Scope'), - cell: (rule) => { - const scopeItems = [ - rule.include_using_group && t('Group'), - rule.include_model_name && t('Model'), - rule.include_rule_name && t('Rule'), - ].filter(Boolean) as string[] - if (scopeItems.length === 0) return '-' - return - }, - }, - { - id: 'cache', - header: t('Cache'), - cell: (rule) => - rule.include_rule_name && cacheStats?.by_rule_name - ? cacheStats.by_rule_name[rule.name] || 0 - : 'N/A', - }, - { - id: 'actions', - header: t('Actions'), - className: 'text-right', - cellClassName: 'text-right', - cell: (rule, idx) => ( -
- {rule.include_rule_name && ( - - )} - + + } + > + + + + { - setEditingRule(rule) + setEditingRule(null) setRuleTemplateKey(null) setRuleEditorOpen(true) }} > - - - -
- ), - }, - ]} - /> - ) : ( -
- - + Codex CLI + + { + setEditingRule(null) + setRuleTemplateKey('claudeCli') + setRuleEditorOpen(true) + }} + > + Claude CLI + + + + +
- )} - + + + { + setEditingRule(rule) + setRuleTemplateKey(null) + setRuleEditorOpen(true) + }} + onDelete={setDeletingRule} + onClearCache={setClearRuleName} + onFillTemplates={handleFillTemplates} + /> + + +
+ +

+ {t('Switch to visual mode to add rules or apply templates.')} +

+ +
+
+ + +
+
+
+
+ + +
+
+
+ + {deletingRule !== null && ( + !open && setDeletingRule(null)} + title={t('Delete Rule')} + desc={t( + 'Delete session rule “{{name}}”? Save your changes to apply the removal.', + { name: deletingRule.name } + )} + confirmText={t('Delete Rule')} + handleConfirm={() => { + props.onRulesChange( + serializeRules( + rules.filter((rule) => rule.id !== deletingRule.id) + ) + ) + setDeletingRule(null) + }} + destructive + /> + )} - {clearRuleName !== null && ( - !v && setClearRuleName(null)} title={t('Confirm clearing cache for this rule')} @@ -721,7 +428,7 @@ export function ChannelAffinitySection(props: Props) { /> )} - ): KeySource { const type = (src?.type || 'gjson') as KeySource['type'] - if (type === 'gjson') return { type, key: '', path: src?.path || '' } - return { type, key: src?.key || '', path: '' } + if (type === 'gjson') return { ...src, type, key: '', path: src?.path || '' } + return { ...src, type, key: src?.key || '', path: '' } } interface Props { @@ -105,6 +108,7 @@ interface Props { rule: AffinityRule | null onSave: (rule: AffinityRule) => void templateKey?: string | null + globalSessionMode?: SessionMode | '' } export function RuleEditorDialog(props: Props) { @@ -122,6 +126,7 @@ export function RuleEditorDialog(props: Props) { const form = useForm({ defaultValues: { + session_mode: 'inherit', name: '', model_regex_text: '', path_regex_text: '', @@ -141,6 +146,8 @@ export function RuleEditorDialog(props: Props) { const resetFromRule = (r: Partial) => { form.reset({ + session_mode: + r.session_mode || (r.skip_retry_on_failure ? 'strict' : 'prefer'), name: r.name || '', model_regex_text: (r.model_regex || []).join('\n'), path_regex_text: (r.path_regex || []).join('\n'), @@ -173,6 +180,7 @@ export function RuleEditorDialog(props: Props) { resetFromRule(RULE_TEMPLATES[props.templateKey]) } else { form.reset({ + session_mode: 'inherit', name: '', model_regex_text: '', path_regex_text: '', @@ -198,7 +206,7 @@ export function RuleEditorDialog(props: Props) { } const validKeySources = keySources - .map(normalizeKeySource) + .map(({ rowId: _, ...source }) => normalizeKeySource(source)) .filter((s) => s.type && (s.type === 'gjson' ? s.path : s.key)) if (validKeySources.length === 0) { toast.error(t('At least one valid key source is required')) @@ -225,6 +233,8 @@ export function RuleEditorDialog(props: Props) { } const rule: AffinityRule = { + ...props.rule, + session_mode: values.session_mode || 'inherit', id: props.rule?.id, name: values.name.trim(), model_regex: modelRegex, @@ -249,7 +259,7 @@ export function RuleEditorDialog(props: Props) { open={props.open} onOpenChange={props.onOpenChange} title={isEdit ? t('Edit Rule') : t('Add Rule')} - contentClassName='max-w-2xl' + contentClassName='sm:max-w-5xl' contentHeight='auto' bodyClassName='pr-2' footer={ @@ -273,8 +283,11 @@ export function RuleEditorDialog(props: Props) { className='min-w-0 space-y-4 overflow-x-clip' >
- + @@ -299,11 +312,36 @@ export function RuleEditorDialog(props: Props) {
- form.setValue('skip_retry_on_failure', v)} - label={t('Skip retry on failure')} - /> +
+ + + + {t('Inherit global default')} + + + {t('Do not keep sessions')} + + + {t('Prefer the original channel, allow switching')} + + + {t('Require the original channel')} + + +

+ {t('Global default: {{mode}}', { + mode: policyLabel(t, props.globalSessionMode || 'prefer'), + })} +

+
diff --git a/web/src/features/system-settings/general/channel-affinity/session-rules-table.tsx b/web/src/features/system-settings/general/channel-affinity/session-rules-table.tsx new file mode 100644 index 0000000000..2813370472 --- /dev/null +++ b/web/src/features/system-settings/general/channel-affinity/session-rules-table.tsx @@ -0,0 +1,298 @@ +/* +Copyright (C) 2023-2026 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { + ArrowLeftRight, + Edit, + FileText, + Link2Off, + ListFilter, + LockKeyhole, + Trash2, +} from 'lucide-react' +import { useTranslation } from 'react-i18next' + +import { + DataTableRowActionMenu, + StaticDataTable, + TruncatedCell, +} from '@/components/data-table' +import { EmptyState } from '@/components/empty-state' +import { StatusBadge, StatusBadgeList } from '@/components/status-badge' +import { Badge } from '@/components/ui/badge' +import { Button } from '@/components/ui/button' +import { + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuSeparator, +} from '@/components/ui/dropdown-menu' +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from '@/components/ui/tooltip' +import { toIntlLocale } from '@/i18n/languages' +import { formatNumber } from '@/lib/format' + +import { policyLabel } from '../../request-policies/policy-label' +import type { AffinityRule, CacheStats, SessionMode } from './types' + +interface SessionRulesTableProps { + rules: AffinityRule[] + cacheStats: CacheStats | null + enabled?: boolean + globalSessionMode?: SessionMode | '' + onEdit: (rule: AffinityRule) => void + onDelete: (rule: AffinityRule) => void + onClearCache: (name: string) => void + onFillTemplates: () => void +} + +export function SessionRulesTable(props: SessionRulesTableProps) { + const { t, i18n } = useTranslation() + const locale = toIntlLocale(i18n.resolvedLanguage || i18n.language) + + if (props.rules.length === 0) { + return ( + +