Files
new-api/relay/relay_task_test.go
Calcium-Ion 7b857f5a1e feat(plugins): add provider plugins, request plugins and a community marketplace (#8271)
* feat(plugins): add provider plugins, request plugins and a community marketplace

- Provider plugins turn an upstream vendor into a channel type: routes,
  protocol conversion, models, static keys, sign-in flows with token
  refresh, balance queries, per-channel config and a scheduled hook.
- Request plugins run on requests and replies (ingress, request,
  outbound, egress, reply, report), with instances by scope, model
  ranges, dry runs and per-log records. Built-ins: request filter,
  request redaction, parameter override, auto reasoning effort, image
  compression and content moderation. Sensitive words move into a
  request filter instance on first start.
- Node sync: a system_sync_topics table lets every node reload settings,
  channels, plugins and other data within seconds, and the system info
  page shows each node's state.
- Marketplace: a community source next to the official one, lookup by
  plugin code for official and community plugins, key rules for
  community plugins, install counts and takedown warnings.

* docs(plugins): name request protocols and host-only members in the plugin API

- Protocol names: ctx.format and samples use relaykit's protocol names.
  The spec lists the client paths and body of each name, so every host
  passes the same names to plugins.
- Host-specific members: channel, group, user, token, channelTypes,
  channelOther and utils.paramOverride exist only on new-api. The types
  mark them optional.
- Relay routes: the spec now writes out the route keys and the converters
  each incoming path accepts. The schema lists the converter names.

* feat(plugins): show recommended plugins from the official list too

The site now marks official plugins as recommended in its index. The
built-in official and community lists both get a Recommended group;
lists added by the administrator still cannot recommend plugins.

* feat(plugins): fall back to www.newapi.pro when www.newapi.ai does not answer

Plugin lists, plugin files and logos from www.newapi.ai are downloaded
from www.newapi.pro, the mainland China site, when newapi.ai gives no
answer within 10 seconds; the browser remembers this for a day. The
marketplace toolbar has a download site picker: Auto, or Mainland China
to always use www.newapi.pro. Saved source addresses stay on newapi.ai,
and every file is still checked against its sha256.

Community install counts go to newapi.ai first and to newapi.pro when
newapi.ai cannot be reached.

* fix(plugins): leaving the page does not switch the plugin site to www.newapi.pro

Reloading or leaving the marketplace cancels requests still running.
That was read as www.newapi.ai not answering, so the browser moved to
www.newapi.pro for a day although newapi.ai was reachable. Requests
cut off by leaving the page are no longer counted.

* feat(plugins): choose the plugin download site by hand

The marketplace no longer switches between plugin sites by itself. The
toolbar menu lists the main site www.newapi.ai, the backup site
www.newapi.pro and the other plugin lists; picking an entry is the only
thing that changes where plugins are downloaded from, and the main site
can always be picked again.

A browser that the earlier automatic switch had moved to www.newapi.pro
opens on the main site again. The download site, the source choice and
managing sources now share one menu in the list header.

* feat(plugins): show plugin usage guides and require README and changelog

Every marketplace plugin version now ships a usage guide, README.md, and a
changelog, CHANGELOG.md, next to plugin.js. The install dialog shows the
guide in the reader's language when a translation is listed, falls back to
English, and links to the source file. A guide or changelog that breaks the
format is reported with its file, line and rule instead of being shown.

The plugin API document describes both formats, the translations they may
list, and the checks the community marketplace runs before it accepts a
version: readme_missing, readme_invalid, changelog_missing and
changelog_invalid. Versions accepted before these checks are not checked
again.

* fix(plugins): address review findings on plugin parts, limits and access

- Only the root user reads request plugin instance configs; an admin who
  may bind instances to channels gets them without configs.
- Outbound hooks that grow the body are held to MAX_REQUEST_BODY_MB, as
  ingress hooks are, and answer 413 without a retry.
- An admin who cannot read plugin options keeps the balance and model
  list actions on plugin channels; the server answers whether they work.
- Reading the parts of a plugin source gives up when the source does not
  parse or code elsewhere refers to meta, as the meta preview does.

* fix(plugins): address review findings on request processing, documents and node sync

- PDF checks resolve indirect parameters and bound every value the parser
  allocates or loops on: predictor columns, object stream counts, nested
  object streams, cross-reference streams and ToUnicode ranges. Font and
  CMap work checks the deadline.
- A WebP frame must match its declared canvas, and keyword search stops at
  its match limit.
- Request processing treats a body as JSON whenever the gateway parses it
  as JSON, keeps Gemini reply parts in place, scopes instances by the
  settled auto group, hides channel header overrides from plugin param
  overrides, and captures replies only for report instances in scope.
- Request processing no longer follows the plugin master switch, which now
  covers plugin tasks and channels only.
- json.patch copies stop at MAX_REQUEST_BODY_MB, and provider prepareRequest
  effects past it answer 413.
- Image billing reads the count from the final upstream body, including the
  count members of SiliconFlow, Imagen and Replicate and the Imagen default.
- Automatic channel status changes no longer reload every node's channel
  cache. A credential refresh holds no channel lock while it waits on the
  vendor. A key that needs login is disabled and the request can retry.
- Balance requests must go to the channel host or allowedHosts, and provider
  stream events a plugin drops keep the stream alive.
- Node sync: OAuth provider writes bump inside their transaction, a failed
  startup load is retried, and each node is judged by its own topics.
- request-filter checks the text the old sensitive-word check did,
  request-redact and content-moderation handle large inputs, and
  image-compress lossless mode leaves JPEG and WebP alone.

* fix(plugins): address the second review on balances, egress and routes

- Channel other_info writes (status changes, balance queries and manual
  multi-key actions) only land while other_info is still the value read,
  and retry otherwise, so a write on one node no longer overwrites another
  node's balance or status reason. They write only their own columns.
- On the Responses path egress reads the body after the channel finalizes
  it, which is the body sent upstream.
- The Vertex AI plugin picks the region by the model the client asked for,
  as the built-in Vertex AI channel does.
- /request-processing and /security are reserved route namespaces, and a
  test checks that every console page is reserved.
- The plugin API docs say what egress reads on a provider plugin channel.

* feat(channels): run the balance update as a system task with progress

"Update all balances" now queues a channel_balance system task instead of
starting a goroutine guarded by an in-process flag. The task row holds the
progress (enabled channels queried of total), so any node can answer it,
and its active key keeps one run at a time across nodes. The
CHANNEL_UPDATE_FREQUENCY schedule becomes the same task's schedule, so
manual and scheduled runs no longer overlap.

GET /api/channel/update_balance answers with the task id, and with the
running one when a run is already queued. GET
/api/channel/update_balance/task/:task_id, under the same channel
permission, returns the status, progress and failure of balance update
tasks only. The channel list follows the task, reloads as more channels
are queried and once more at the end, and reports how the run ended.

* feat(system): sync nodes through system tasks and clean up task history

Node sync no longer needs its own table. A write to synced data adds a
pending sync_<topic> system task. Every node polls the newest task of each
topic it keeps every 3 s and reloads when that task is newer than the one
it applied. Custom OAuth providers still add their task inside the write
transaction, and lock the newest task of the topic first, so tasks commit
in id order. The master marks a sync task succeeded once every online node
that keeps the topic has applied it. Until then the task shows how many
nodes have applied it and why the others have not. The
system_sync_topics table is gone.

A composite (type, id) index answers the newest task of a type from the
index. The latest-per-type and earliest-pending queries now read ids first,
because MySQL 5.7 scanned the whole table for them.

A daily system_task_cleanup task deletes finished system tasks older than
system_task_setting.retention_days (default 30, at least 1), in batches.
It never deletes active tasks or the newest task of any type. The
retention is set under Operations > Log maintenance.
2026-11-12 20:50:58 +08:00

889 lines
45 KiB
Go

package relay
import (
"encoding/base64"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/i18n"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/pkg/billingexpr"
pluginruntime "github.com/QuantumNous/new-api/pkg/jsplugin"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relay/helper"
kitdto "github.com/QuantumNous/new-api/relaykit/dto"
kittypes "github.com/QuantumNous/new-api/relaykit/types"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/billing_setting"
"github.com/QuantumNous/new-api/setting/config"
"github.com/QuantumNous/new-api/setting/ratio_setting"
"github.com/gin-gonic/gin"
"github.com/glebarez/sqlite"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
func setupRelayChannelDB(t *testing.T) *gorm.DB {
t.Helper()
previousDB := model.DB
previousType := common.MainDatabaseType()
previousCache := common.MemoryCacheEnabled
database, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
sqlDB, err := database.DB()
require.NoError(t, err)
sqlDB.SetMaxOpenConns(1)
require.NoError(t, database.AutoMigrate(&model.Channel{}))
model.DB = database
common.SetMainDatabaseType(common.DatabaseTypeSQLite)
common.MemoryCacheEnabled = false
t.Cleanup(func() {
model.DB = previousDB
common.SetMainDatabaseType(previousType)
common.MemoryCacheEnabled = previousCache
require.NoError(t, sqlDB.Close())
})
return database
}
func TestRealtimeFetchAppliesChannelHeaderOverrides(t *testing.T) {
database := setupRelayChannelDB(t)
service.InitHttpClient()
requests := make(chan *http.Request, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests <- r.Clone(r.Context())
_, _ = w.Write([]byte(`{"name":"operations/task-1","done":false}`))
}))
t.Cleanup(server.Close)
headerOverride := `{"X-API-Key":"{api_key}"}`
channel := &model.Channel{
Name: "realtime-header-override", Type: constant.ChannelTypeGemini,
Key: "channel-key", BaseURL: &server.URL, HeaderOverride: &headerOverride,
}
require.NoError(t, database.Create(channel).Error)
task := &model.Task{
TaskID: "public-task", ChannelId: channel.Id,
Status: model.TaskStatusInProgress, Progress: "50%",
PrivateData: model.TaskPrivateData{
Key: "saved-key", UpstreamTaskID: base64.RawURLEncoding.EncodeToString([]byte("operations/task-1")),
},
}
tryRealtimeFetch(task, true)
require.Len(t, requests, 1)
request := <-requests
assert.Equal(t, "/v1beta/operations/task-1", request.URL.Path)
assert.Equal(t, "saved-key", request.Header.Get("X-API-Key"))
assert.Equal(t, "saved-key", request.Header.Get("X-Goog-Api-Key"))
}
func TestRealtimeFetchRefundsTaskItFindsFailed(t *testing.T) {
database := setupRelayChannelDB(t)
require.NoError(t, database.AutoMigrate(&model.Task{}, &model.User{}, &model.Log{}))
previousLogDB := model.LOG_DB
previousFactory := service.GetTaskAdaptorFunc
previousRedis := common.RedisEnabled
model.LOG_DB = database
common.RedisEnabled = false
service.GetTaskAdaptorFunc = func(platform constant.TaskPlatform) service.TaskPollingAdaptor {
if adaptor := GetTaskAdaptor(platform); adaptor != nil {
return adaptor
}
return nil
}
t.Cleanup(func() {
model.LOG_DB = previousLogDB
service.GetTaskAdaptorFunc = previousFactory
common.RedisEnabled = previousRedis
})
service.InitHttpClient()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`{"name":"operations/task-1","done":true,"error":{"code":3,"message":"blocked by safety"}}`))
}))
t.Cleanup(server.Close)
channel := &model.Channel{Name: "realtime-refund", Type: constant.ChannelTypeGemini, Key: "channel-key", BaseURL: &server.URL}
require.NoError(t, database.Create(channel).Error)
require.NoError(t, database.Create(&model.User{Id: 7, Username: "realtime-owner", Quota: 100}).Error)
task := &model.Task{
TaskID: "public-task", Platform: constant.TaskPlatform(strconv.Itoa(constant.ChannelTypeGemini)),
UserId: 7, ChannelId: channel.Id, Quota: 1000,
Status: model.TaskStatusInProgress, Progress: "50%",
PrivateData: model.TaskPrivateData{
Key: "channel-key", UpstreamTaskID: base64.RawURLEncoding.EncodeToString([]byte("operations/task-1")),
},
}
require.NoError(t, database.Create(task).Error)
tryRealtimeFetch(task, true)
var stored model.Task
require.NoError(t, database.First(&stored, task.ID).Error)
assert.Equal(t, model.TaskStatus(model.TaskStatusFailure), stored.Status)
assert.Equal(t, "blocked by safety", stored.FailReason)
assert.Zero(t, stored.Quota, "the failed task is refunded")
var user model.User
require.NoError(t, database.First(&user, 7).Error)
assert.Equal(t, 1100, user.Quota)
}
func TestApplyChannelPinPreservesOriginTasksAndRetryMode(t *testing.T) {
database := setupRelayChannelDB(t)
channel := &model.Channel{Name: "origin-channel", Key: "sk-test", Status: common.ChannelStatusEnabled, Type: constant.ChannelTypeDoubaoVideo}
require.NoError(t, database.Create(channel).Error)
originTask := &model.Task{
TaskID: "task-lock", ChannelId: channel.Id, Action: "text_to_video", Status: model.TaskStatusSuccess,
PrivateData: model.TaskPrivateData{UpstreamTaskID: "upstream-task-lock"},
Data: []byte(`{"id":"upstream-task-lock"}`),
}
for _, tc := range []struct {
name string
tokenPin bool
apply func(*gin.Context, *relaycommon.RelayInfo) *dto.TaskError
}{
{name: "origin affinity", apply: ApplyOriginTaskAffinity},
{name: "same channel retry", apply: ApplyChannelPin},
{name: "token pin suppresses channel lock", tokenPin: true, apply: ApplyChannelPin},
} {
t.Run(tc.name, func(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
common.SetContextKey(c, constant.ContextKeyOriginTasks, []*model.Task{originTask})
constraints := service.GetChannelConstraints(c)
constraints.AddPin(dto.ChannelPin{ChannelId: channel.Id, Source: dto.PinSourceOriginTask, Rank: dto.PinRankOriginTask, RetryMode: dto.PinRetrySameChannel})
if tc.tokenPin {
constraints.AddPin(dto.ChannelPin{ChannelId: channel.Id, Source: dto.PinSourceToken, Rank: dto.PinRankToken, RetryMode: dto.PinRetrySingleAttempt})
}
info := &relaycommon.RelayInfo{TaskRelayInfo: &relaycommon.TaskRelayInfo{}}
require.Nil(t, tc.apply(c, info))
if tc.tokenPin {
assert.Nil(t, info.LockedChannel)
} else {
locked, ok := info.LockedChannel.(*model.Channel)
require.True(t, ok)
require.NotNil(t, locked)
assert.Equal(t, channel.Id, locked.Id)
}
require.Len(t, info.OriginTasks, 1)
assert.Equal(t, "task-lock", info.OriginTasks[0].TaskID)
assert.Equal(t, "upstream-task-lock", info.OriginTasks[0].UpstreamTaskID)
assert.Equal(t, "text_to_video", info.OriginTasks[0].Action)
assert.Equal(t, string(model.TaskStatusSuccess), info.OriginTasks[0].Status)
assert.Equal(t, []byte(originTask.Data), info.OriginTasks[0].Data)
})
}
}
func TestTaskModel2DtoNormalizesLegacyAction(t *testing.T) {
task := &model.Task{Action: "firstTailGenerate"}
dtoTask := TaskModel2Dto(task)
assert.Equal(t, constant.TaskActionFirstTailToVideo, dtoTask.Action)
assert.Equal(t, "firstTailGenerate", task.Action)
}
const mappingOrderSubmitPlugin = `
export const meta = {apiVersion:1,key:"maporder",name:"Map Order",version:"1.0.0",author:{name:"Test"},models:["declared-model"],fetchMode:"per_task"};
export function buildSubmitRequest(ctx) {
return {url: ctx.baseUrl+"/submit", method:"POST", body:{upstreamModel: ctx.upstreamModel, model: ctx.model}, action:"text_to_video"};
}
export function parseSubmitResponse(){return {taskId:"1"};}
export function buildQueryRequest(){return {url:"https://provider.example"};}
export function parseTaskResult(){return {status:"SUCCESS"};}
`
const mappingOrderRewritePlugin = `
export const meta = {apiVersion:1,key:"maporder-rw",name:"Map Order RW",version:"1.0.0",author:{name:"Test"},models:["declared-model"],fetchMode:"per_task"};
export function buildSubmitRequest(ctx) {
return {url: ctx.baseUrl+"/submit", method:"POST", body:{upstreamModel: ctx.upstreamModel}, rewriteModel:"rewritten"};
}
export function parseSubmitResponse(){return {taskId:"1"};}
export function buildQueryRequest(){return {url:"https://provider.example"};}
export function parseTaskResult(){return {status:"SUCCESS"};}
`
func pinMappingOrderPlugin(t *testing.T, c *gin.Context, source string) {
t.Helper()
plugin, err := pluginruntime.NewRegistry().Register(source, pluginruntime.Options{})
require.NoError(t, err)
c.Set(pluginruntime.ContextKeyPinnedPlugin, pluginruntime.PinnedPlugin{Plugin: plugin})
}
func newTaskSubmitContext(t *testing.T, originalModel, mapping string) (*gin.Context, *relaycommon.RelayInfo) {
t.Helper()
require.NoError(t, i18n.Init())
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/videos", nil)
common.SetContextKey(c, constant.ContextKeyOriginalModel, originalModel)
common.SetContextKey(c, constant.ContextKeyChannelBaseUrl, "https://provider.example")
if mapping != "" {
c.Set("model_mapping", mapping)
}
c.Set("task_request", map[string]any{"prompt": "p"})
return c, &relaycommon.RelayInfo{TaskRelayInfo: &relaycommon.TaskRelayInfo{}}
}
func TestRelayTaskSubmitMapsBeforeValidateWhenOriginSet(t *testing.T) {
const mapping = `{"alias-model":"mid-model","mid-model":"declared-model"}`
c, info := newTaskSubmitContext(t, "alias-model", mapping)
pinMappingOrderPlugin(t, c, mappingOrderSubmitPlugin)
info.OriginModelName = "alias-model"
_, taskErr := RelayTaskSubmit(c, info)
require.NotNil(t, taskErr)
assert.Equal(t, "model_price_error", taskErr.Code)
assert.Equal(t, "alias-model", info.OriginModelName)
assert.Equal(t, "declared-model", info.UpstreamModelName)
assert.True(t, info.IsModelMapped)
}
func TestRelayTaskSubmitDeclaredNameWithoutMappingIsUnchanged(t *testing.T) {
c, info := newTaskSubmitContext(t, "declared-model", "")
pinMappingOrderPlugin(t, c, mappingOrderSubmitPlugin)
info.OriginModelName = "declared-model"
_, taskErr := RelayTaskSubmit(c, info)
require.NotNil(t, taskErr)
assert.Equal(t, "model_price_error", taskErr.Code)
assert.Equal(t, "declared-model", info.OriginModelName)
assert.Equal(t, "declared-model", info.UpstreamModelName)
assert.False(t, info.IsModelMapped)
}
func TestRelayTaskSubmitDoesNotApplyMappingTwice(t *testing.T) {
c, info := newTaskSubmitContext(t, "alias-model", `{"alias-model":"declared-model"}`)
pinMappingOrderPlugin(t, c, mappingOrderRewritePlugin)
info.OriginModelName = "alias-model"
_, taskErr := RelayTaskSubmit(c, info)
require.NotNil(t, taskErr)
assert.Equal(t, "model_price_error", taskErr.Code)
assert.Equal(t, "rewritten", info.UpstreamModelName, "late mapping would overwrite rewriteModel with the chain tail")
assert.Equal(t, "alias-model", info.OriginModelName)
}
func TestRelayTaskSubmitEmptyOriginKeepsLateMapping(t *testing.T) {
plugin, err := pluginruntime.NewRegistry().Register(mappingOrderSubmitPlugin, pluginruntime.Options{})
require.NoError(t, err)
synthesized := service.CoverTaskActionToModelName(constant.TaskPlatform(plugin.Meta.Key), "text_to_video")
c, info := newTaskSubmitContext(t, "pre-validate-upstream",
`{"pre-validate-upstream":"should-not-apply-early","`+synthesized+`":"legacy-tail"}`)
c.Set(pluginruntime.ContextKeyPinnedPlugin, pluginruntime.PinnedPlugin{Plugin: plugin})
info.OriginModelName = ""
_, taskErr := RelayTaskSubmit(c, info)
require.NotNil(t, taskErr)
assert.Equal(t, "model_price_error", taskErr.Code)
assert.Equal(t, synthesized, info.OriginModelName)
assert.Equal(t, "legacy-tail", info.UpstreamModelName)
assert.True(t, info.IsModelMapped)
}
const billingFallbackPlugin = `
export const meta = {apiVersion:1,key:"bill-fallback",name:"Bill Fallback",version:"1.0.0",author:{name:"Test"},models:["declared-model"],fetchMode:"per_task"};
export function buildSubmitRequest(ctx) {
return {url: ctx.baseUrl+"/submit", method:"POST", body:{upstreamModel: ctx.upstreamModel, model: ctx.model}, action:"text_to_video"};
}
export function parseSubmitResponse(){return {taskId:"1"};}
export function buildQueryRequest(){return {url:"https://provider.example"};}
export function parseTaskResult(){return {status:"SUCCESS"};}
`
func saveBillingConfig(t *testing.T) {
t.Helper()
saved := map[string]string{}
require.NoError(t, config.GlobalConfig.SaveToDB(func(key, value string) error {
saved[key] = value
return nil
}))
t.Cleanup(func() {
require.NoError(t, config.GlobalConfig.LoadFromDB(saved))
})
}
func TestRelayTaskSubmitAliasBillingIdentityAndExprFallback(t *testing.T) {
const mapping = `{"alias-model":"declared-model"}`
const aliasExpr = `tier("alias", 2)`
const tailExpr = `tier("tail", 3)`
const legacyExpr = `tier("legacy", u("old_units") * 2)`
tests := []struct {
name string
modes map[string]string
exprs map[string]string
wantTiered bool
wantExpr string
source string
}{
{
name: "alias own tiered wins",
modes: map[string]string{"alias-model": "tiered_expr", "declared-model": "tiered_expr"},
exprs: map[string]string{"alias-model": aliasExpr, "declared-model": tailExpr},
wantTiered: true,
wantExpr: aliasExpr,
},
{
name: "fallback uses tail expr",
modes: map[string]string{"declared-model": "tiered_expr"},
exprs: map[string]string{"declared-model": tailExpr},
wantTiered: true,
wantExpr: tailExpr,
},
{
name: "stored expression keeps running after schema narrows",
modes: map[string]string{"declared-model": "tiered_expr"},
exprs: map[string]string{"declared-model": legacyExpr},
wantTiered: true,
wantExpr: legacyExpr,
source: strings.Replace(billingFallbackPlugin, `fetchMode:"per_task"`, `fetchMode:"per_task", usageSchema:{old_units:{type:"number",unit:"count"}}, usageProfiles:[{models:["declared-model"],schema:{seconds:{type:"number",unit:"second"}}}]`, 1) + `
export function extractUsage(){return {old_units:2};}
`,
},
{
name: "neither tiered uses ordinary pricing",
wantTiered: false,
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
saveBillingConfig(t)
if len(testCase.modes) > 0 {
modeJSON, marshalErr := common.Marshal(testCase.modes)
require.NoError(t, marshalErr)
exprJSON, marshalErr := common.Marshal(testCase.exprs)
require.NoError(t, marshalErr)
require.NoError(t, config.GlobalConfig.LoadFromDB(map[string]string{
"billing_setting.billing_mode": string(modeJSON),
"billing_setting.billing_expr": string(exprJSON),
}))
if testCase.wantExpr == aliasExpr {
require.Equal(t, billing_setting.BillingModeTieredExpr, billing_setting.GetBillingMode("alias-model"))
} else {
require.Equal(t, billing_setting.BillingModeRatio, billing_setting.GetBillingMode("alias-model"))
require.Equal(t, billing_setting.BillingModeTieredExpr, billing_setting.GetBillingMode("declared-model"))
}
}
c, info := newTaskSubmitContext(t, "alias-model", mapping)
c.Set("group", "default")
info.UserGroup = "default"
info.UsingGroup = "default"
source := testCase.source
if source == "" {
source = billingFallbackPlugin
}
pinMappingOrderPlugin(t, c, source)
info.OriginModelName = "alias-model"
_, taskErr := RelayTaskSubmit(c, info)
require.NotNil(t, taskErr)
assert.Equal(t, "alias-model", info.OriginModelName)
assert.Equal(t, "declared-model", info.UpstreamModelName)
assert.True(t, info.IsModelMapped)
task := model.InitTask(constant.TaskPlatform("bill-fallback"), info)
assert.Equal(t, "alias-model", task.Properties.OriginModelName)
assert.Equal(t, "declared-model", task.Properties.UpstreamModelName)
if testCase.wantTiered {
require.NotNil(t, info.TieredBillingSnapshot, "submission error: %+v", taskErr)
assert.Equal(t, "alias-model", info.TieredBillingSnapshot.ModelName)
assert.Equal(t, testCase.wantExpr, info.TieredBillingSnapshot.ExprString)
assert.Equal(t, billingexpr.ExprHashString(testCase.wantExpr), info.TieredBillingSnapshot.ExprHash)
assert.NotEqual(t, "model_price_error", taskErr.Code)
if testCase.wantExpr == legacyExpr {
assert.Equal(t, 4*common.QuotaPerUnit, info.TieredBillingSnapshot.EstimatedQuotaBeforeGroup)
}
} else {
assert.Nil(t, info.TieredBillingSnapshot)
assert.Equal(t, "model_price_error", taskErr.Code)
}
})
}
}
func TestSharedTaskBillingExpressionSelectionAndFrozenSettlement(t *testing.T) {
const baseExpr = `tier("base", u("seconds") * 2)`
const alphaExpr = `tier("alpha", u("seconds") * 3)`
const betaExpr = `tier("beta", u("credits") * 5)`
const aliasExpr = `tier("alias", u("credits") * 7)`
for _, tc := range []struct {
name, plugin, model, mapping, modelExpr, mode, wantExpr string
variants map[string]string
wantPriceError, profiled bool
}{
{name: "executing plugin override", plugin: "billing-beta", model: "declared-model", modelExpr: baseExpr, mode: "tiered_expr", variants: map[string]string{"billing-alpha::declared-model": alphaExpr, "billing-beta::declared-model": betaExpr}, wantExpr: betaExpr},
{name: "override ignores model mode", plugin: "billing-beta", model: "declared-model", modelExpr: baseExpr, mode: "ratio", variants: map[string]string{"billing-beta::declared-model": betaExpr}, wantExpr: betaExpr},
{name: "model expression fallback", plugin: "billing-alpha", model: "declared-model", modelExpr: baseExpr, mode: "tiered_expr", wantExpr: baseExpr},
{name: "alias override precedes mapped override", plugin: "billing-beta", model: "alias-model", mapping: `{"alias-model":"declared-model"}`, modelExpr: baseExpr, mode: "tiered_expr", variants: map[string]string{"billing-beta::declared-model": betaExpr, "billing-beta::alias-model": aliasExpr}, wantExpr: aliasExpr},
{name: "mapped override precedes model fallback", plugin: "billing-beta", model: "alias-model", mapping: `{"alias-model":"declared-model"}`, modelExpr: baseExpr, mode: "tiered_expr", variants: map[string]string{"billing-beta::declared-model": betaExpr}, wantExpr: betaExpr},
{name: "unconfigured plugin cannot use another schema", plugin: "billing-beta", model: "declared-model", modelExpr: baseExpr, mode: "tiered_expr", wantPriceError: true},
{name: "missing usage in skipped branch remains incompatible", plugin: "billing-beta", model: "declared-model", modelExpr: `true ? tier("free", 0) : tier("missing", u("seconds"))`, mode: "tiered_expr", wantPriceError: true},
{name: "fixed pricing is still rejected", plugin: "billing-beta", model: "declared-model", variants: map[string]string{"billing-beta::declared-model": `tier("fixed", fixed(1))`}, wantPriceError: true},
{name: "endpoint mapping keeps the declared profile", plugin: "billing-beta", model: "declared-model", mapping: `{"declared-model":"ep-endpoint"}`, modelExpr: baseExpr, mode: "tiered_expr", variants: map[string]string{"billing-beta::declared-model": betaExpr}, wantExpr: betaExpr, profiled: true},
} {
t.Run(tc.name, func(t *testing.T) {
saveBillingConfig(t)
registry := pluginruntime.NewRegistry()
for _, spec := range []struct{ key, field, unit string }{{"billing-alpha", "seconds", "second"}, {"billing-beta", "credits", "credit"}} {
source := strings.ReplaceAll(billingFallbackPlugin, "bill-fallback", spec.key)
schema := `usageSchema:{` + spec.field + `:{type:"number",unit:"` + spec.unit + `"}}`
if tc.profiled && spec.key == "billing-beta" {
// The endpoint ID is undeclared, so only the declared model's profile carries this schema.
schema = `usageSchema:{seconds:{type:"number",unit:"second"}},usageProfiles:[{models:["declared-model"],schema:{` + spec.field + `:{type:"number",unit:"` + spec.unit + `"}}}]`
}
source = strings.Replace(source, `fetchMode:"per_task"`, `fetchMode:"per_task",`+schema, 1)
source += `export function extractUsage(){return {` + spec.field + `:2};}`
_, err := registry.Register(source, pluginruntime.Options{})
require.NoError(t, err)
}
variants := tc.variants
if variants == nil {
variants = map[string]string{}
}
rawVariants, err := common.Marshal(variants)
require.NoError(t, err)
modes, err := common.Marshal(map[string]string{"declared-model": tc.mode})
require.NoError(t, err)
expressions, err := common.Marshal(map[string]string{"declared-model": tc.modelExpr})
require.NoError(t, err)
require.NoError(t, config.GlobalConfig.LoadFromDB(map[string]string{
billing_setting.PluginBillingExprOption: string(rawVariants), "billing_setting.billing_mode": string(modes), "billing_setting.billing_expr": string(expressions),
}))
c, info := newTaskSubmitContext(t, tc.model, tc.mapping)
c.Set("group", "default")
c.Set("task_plugin_key", tc.plugin)
info.UserGroup = "default"
info.UsingGroup = "default"
info.OriginModelName = tc.model
plugin, ok := registry.Generation().Get(tc.plugin)
require.True(t, ok)
c.Set(pluginruntime.ContextKeyPinnedPlugin, pluginruntime.PinnedPlugin{Generation: registry.Generation(), Plugin: plugin})
_, taskErr := RelayTaskSubmit(c, info)
require.NotNil(t, taskErr) // This fixture stops at reservation, before upstream submission.
if tc.wantPriceError {
assert.Equal(t, "model_price_error", taskErr.Code)
assert.Nil(t, info.TieredBillingSnapshot)
return
}
require.NotNil(t, info.TieredBillingSnapshot, "submission error: %+v", taskErr)
assert.Equal(t, tc.wantExpr, info.TieredBillingSnapshot.ExprString)
assert.NotEqual(t, "model_price_error", taskErr.Code)
require.NoError(t, config.GlobalConfig.LoadFromDB(map[string]string{billing_setting.PluginBillingExprOption: `{}`, "billing_setting.billing_expr": `{}`}))
field := "seconds"
if tc.plugin == "billing-beta" {
field = "credits"
}
result, usage, err := service.EvaluateTaskCompletionUsage(info.TieredBillingSnapshot, map[string]any{field: float64(4)})
require.NoError(t, err)
assert.Equal(t, float64(4), usage[field])
assert.Equal(t, float64(2), info.TieredBillingSnapshot.UsageFacts[field])
assert.Equal(t, 2*info.TieredBillingSnapshot.EstimatedQuotaAfterGroup, result.ActualQuotaAfterGroup)
assert.Equal(t, tc.wantExpr, info.TieredBillingSnapshot.ExprString)
})
}
}
func TestSharedEndpointBillingKeepsOrdinaryAndPluginPricesSeparate(t *testing.T) {
require.NoError(t, i18n.Init())
const taskExpr = `tier("images", u("image_count") * 0.05)`
const ordinaryExpr = `tier("images", fixed(0.04)) * image_count`
savedPrices := ratio_setting.ModelPrice2JSONString()
t.Cleanup(func() { require.NoError(t, ratio_setting.UpdateModelPriceByJSONString(savedPrices)) })
for _, tc := range []struct {
name, expression, override string
ordinaryQuota, taskQuota, taskFinal int
wantError string
alias, shared, legacy bool
}{
{name: "task usage price is rejected by ordinary relay", expression: taskExpr, taskQuota: 50000, taskFinal: 75000, wantError: "task usage expression"},
{name: "enum fallback cannot silently bill zero", expression: `u("output_image_type") == "2k" ? tier("2k", u("image_count") * 0.08) : tier("1k", 0.04)`, taskQuota: 20000, taskFinal: 20000, wantError: "task usage expression"},
{name: "unselected usage branch is rejected", expression: `true ? tier("flat", 0.04) : tier("images", u("image_count"))`, taskQuota: 20000, taskFinal: 20000, wantError: "task usage expression"},
{name: "dynamic usage key is rejected", expression: `tier("images", u(u("unit")) * 0.05)`, taskQuota: 50000, taskFinal: 75000, wantError: "task usage expression"},
{name: "plain task USD price is ambiguous", expression: `tier("flat", 0.04)`, taskQuota: 20000, taskFinal: 20000, wantError: "shares its billing expression"},
{name: "alias retains task USD price", expression: `tier("flat", 0.04)`, taskQuota: 20000, taskFinal: 20000, wantError: "shares its billing expression", alias: true},
{name: "per image relay and plugin overrides", expression: ordinaryExpr, override: taskExpr, ordinaryQuota: 40000, taskQuota: 50000, taskFinal: 75000},
{name: "mapped plugin override", expression: ordinaryExpr, override: taskExpr, ordinaryQuota: 40000, taskQuota: 50000, taskFinal: 75000, alias: true},
{name: "token relay and plugin overrides", expression: `tier("tokens", p * 2)`, override: taskExpr, ordinaryQuota: 1000, taskQuota: 50000, taskFinal: 75000},
{name: "ordinary constant has ordinary units with plugin override", expression: `tier("flat", 80000)`, override: taskExpr, ordinaryQuota: 40000, taskQuota: 50000, taskFinal: 75000},
{name: "another plugin still inherits task USD units", expression: `tier("flat", 0.04)`, override: taskExpr, taskQuota: 50000, taskFinal: 75000, wantError: "shares its billing expression", shared: true},
{name: "legacy per image pricing stays shared", ordinaryQuota: 40000, taskQuota: 40000, legacy: true},
} {
t.Run(tc.name, func(t *testing.T) {
saveBillingConfig(t)
name, mapping, mappedModel := "declared-model", "", ""
if tc.alias {
name, mapping, mappedModel = "alias-model", `{"alias-model":"declared-model"}`, "declared-model"
}
mode := billing_setting.BillingModeTieredExpr
if tc.legacy {
mode = billing_setting.BillingModeRatio
}
variants := map[string]string{}
if tc.override != "" {
variants["bill-fallback::declared-model"] = tc.override
}
modes, err := common.Marshal(map[string]string{name: mode})
require.NoError(t, err)
expressions, err := common.Marshal(map[string]string{name: tc.expression})
require.NoError(t, err)
overrides, err := common.Marshal(variants)
require.NoError(t, err)
require.NoError(t, config.GlobalConfig.LoadFromDB(map[string]string{
"billing_setting.billing_mode": string(modes), "billing_setting.billing_expr": string(expressions),
billing_setting.PluginBillingExprOption: string(overrides), "group_ratio_setting.group_ratio": `{"default":1}`,
}))
prices, err := common.Marshal(map[string]float64{name: 0.04})
require.NoError(t, err)
require.NoError(t, ratio_setting.UpdateModelPriceByJSONString(string(prices)))
registry := pluginruntime.NewRegistry()
source := strings.Replace(billingFallbackPlugin, `fetchMode:"per_task"`, `fetchMode:"per_task",usageSchema:{image_count:{type:"number",unit:"count",description:"Image generation unit price"},output_image_type:{enum:["1k","2k"]},unit:{enum:["image_count"]}}`, 1)
source += `export function extractUsage(){return {image_count:2,output_image_type:"1k",unit:"image_count"};}`
plugin, err := registry.Register(source, pluginruntime.Options{})
require.NoError(t, err)
candidates := []pluginruntime.ProtocolBinding{{Plugin: plugin}}
if tc.shared {
other, err := registry.Register(strings.ReplaceAll(source, "bill-fallback", "other-images"), pluginruntime.Options{})
require.NoError(t, err)
candidates = append(candidates, pluginruntime.ProtocolBinding{Plugin: other})
}
ordinaryContext, _ := gin.CreateTestContext(httptest.NewRecorder())
ordinaryContext.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil)
ordinaryContext.Request.Header.Set("Accept-Language", "en")
ordinaryContext.Set(pluginruntime.ContextKeyRelayEndpoint, pluginruntime.PinnedEndpoint{Generation: registry.Generation(), Model: name, MappedModel: mappedModel, Candidates: candidates})
ordinary := &relaycommon.RelayInfo{
OriginModelName: name, UserGroup: "default", UsingGroup: "default", RelayFormat: kittypes.RelayFormatOpenAIImage,
Request: &kitdto.ImageRequest{Model: name, N: common.GetPointer(uint(2))}, BillingRequestInput: &billingexpr.RequestInput{},
}
ordinaryPrice, err := helper.ModelPriceHelper(ordinaryContext, ordinary, 1000, &kittypes.TokenCountMeta{})
if tc.wantError != "" {
require.ErrorContains(t, err, tc.wantError)
assert.Nil(t, ordinary.TieredBillingSnapshot)
assert.Nil(t, ordinary.Billing, "pricing must fail before reservation")
} else {
require.NoError(t, err)
assert.Equal(t, tc.ordinaryQuota, ordinaryPrice.QuotaToPreConsume)
}
pluginContext, task := newTaskSubmitContext(t, name, mapping)
pluginContext.Set("group", "default")
pluginContext.Set(pluginruntime.ContextKeyPinnedPlugin, pluginruntime.PinnedPlugin{Generation: registry.Generation(), Plugin: plugin})
task.OriginModelName, task.UserGroup, task.UsingGroup = name, "default", "default"
_, taskErr := RelayTaskSubmit(pluginContext, task)
require.NotNil(t, taskErr) // This fixture stops at reservation, before upstream submission.
assert.NotEqual(t, "model_price_error", taskErr.Code)
assert.Equal(t, tc.taskQuota, task.PriceData.Quota)
if tc.legacy {
assert.Nil(t, task.TieredBillingSnapshot)
assert.Nil(t, ordinary.TieredBillingSnapshot)
return
}
require.NotNil(t, task.TieredBillingSnapshot)
assert.True(t, task.TieredBillingSnapshot.TaskUsageBilling)
// Updating live prices must not change either in-flight meter.
require.NoError(t, config.GlobalConfig.LoadFromDB(map[string]string{
"billing_setting.billing_expr": `{}`, billing_setting.PluginBillingExprOption: `{}`,
}))
settlement, _, err := service.EvaluateTaskCompletionUsage(task.TieredBillingSnapshot, map[string]any{"image_count": float64(3)})
require.NoError(t, err)
assert.Equal(t, tc.taskFinal, settlement.ActualQuotaAfterGroup)
if tc.wantError != "" {
return
}
require.NotNil(t, ordinary.TieredBillingSnapshot)
assert.False(t, ordinary.TieredBillingSnapshot.TaskUsageBilling)
settlement, err = billingexpr.ComputeTieredQuotaWithRequest(ordinary.TieredBillingSnapshot, billingexpr.TokenParams{P: 1000, Len: 1000}, *ordinary.BillingRequestInput)
require.NoError(t, err)
assert.Equal(t, tc.ordinaryQuota, settlement.ActualQuotaAfterGroup)
})
}
}
// One plugin serves a model on chat paths and as a task. The model-level price
// prices both only when it is per call or reads usage facts; otherwise tasks
// need the plugin's own price. Chat request quantities (token counts, bare
// image_count) never price a task, for any model.
func TestRelayTaskSubmitPricesModelsAPluginAlsoRelays(t *testing.T) {
require.NoError(t, i18n.Init())
const chatRoute = `[{incoming_path:"/v1/chat/completions",upstream_path:"/v1/chat/completions"}]`
const tokenExpr = `tier("tokens", p * 2 + c * 8)`
const usageExpr = `tier("seconds", u("seconds") * 0.3)`
const notConfigured = "Model declared-model has no task price for plugin bill-fallback"
savedPrices, savedRatios := ratio_setting.ModelPrice2JSONString(), ratio_setting.ModelRatio2JSONString()
t.Cleanup(func() {
require.NoError(t, ratio_setting.UpdateModelPriceByJSONString(savedPrices))
require.NoError(t, ratio_setting.UpdateModelRatioByJSONString(savedRatios))
})
for _, tc := range []struct {
name, relay, price, ratio, expr, override string
// The chat side is checked when chatQuota or chatErr is set.
chatQuota int
chatErr string
taskErr, taskExpr string
taskQuota int
}{
{name: "per-call price prices chat and tasks", relay: chatRoute, price: "0.04", chatQuota: 20000, taskQuota: 40000},
{name: "token ratio alone leaves tasks unpriced", relay: chatRoute, ratio: "10", chatQuota: 10000, taskErr: notConfigured},
{name: "token expression is the chat price", relay: chatRoute, expr: tokenExpr, chatQuota: 1000, taskErr: notConfigured},
{name: "constant expression is the chat price", relay: chatRoute, expr: `tier("flat", 0.04)`, taskErr: notConfigured},
{name: "usage expression prices tasks only", relay: chatRoute, expr: usageExpr, chatErr: "task usage expression", taskExpr: usageExpr, taskQuota: 300000},
{name: "plugin price splits a chat price", relay: chatRoute, expr: tokenExpr, override: usageExpr, chatQuota: 1000, taskExpr: usageExpr, taskQuota: 300000},
{name: "plugin price splits a token ratio", relay: chatRoute, ratio: "10", override: usageExpr, taskExpr: usageExpr, taskQuota: 300000},
{name: "plugin price reading token counts is rejected", expr: usageExpr, override: `tier("tokens", p * 2 + u("seconds"))`, taskErr: notConfigured},
{name: "task model token expression no longer bills zero", expr: tokenExpr, taskErr: notConfigured},
// image_count is the chat request's image count: a task would read 1.
{name: "task model image count expression no longer bills one image", expr: `tier("images", image_count * 0.04)`, taskErr: notConfigured},
{name: "plugin price reading image count is rejected", expr: usageExpr, override: `tier("images", image_count * 0.04 + u("seconds"))`, taskErr: notConfigured},
{name: "task model token ratio keeps the legacy per-call price", ratio: "10", taskQuota: 5000000},
{name: "task model constant expression is a task price", expr: `tier("flat", 0.04)`, taskExpr: `tier("flat", 0.04)`, taskQuota: 20000},
{name: "model list route does not relay the model", relay: `[{incoming_path:"/v1/models",upstream_path:"/v1/models"}]`, ratio: "10", taskQuota: 5000000},
{name: "route for other models does not relay this one", relay: `[{incoming_path:"/v1/chat/completions",upstream_path:"/v1/chat/completions",models:["other-model"]}]`, expr: `tier("flat", 0.04)`, taskExpr: `tier("flat", 0.04)`, taskQuota: 20000},
} {
t.Run(tc.name, func(t *testing.T) {
saveBillingConfig(t)
modes, expressions, overrides := map[string]string{}, map[string]string{}, map[string]string{}
if tc.expr != "" {
modes["declared-model"], expressions["declared-model"] = billing_setting.BillingModeTieredExpr, tc.expr
}
if tc.override != "" {
overrides["bill-fallback::declared-model"] = tc.override
}
options := map[string]string{"group_ratio_setting.group_ratio": `{"default":1}`}
for key, value := range map[string]map[string]string{"billing_setting.billing_mode": modes, "billing_setting.billing_expr": expressions, billing_setting.PluginBillingExprOption: overrides} {
encoded, err := common.Marshal(value)
require.NoError(t, err)
options[key] = string(encoded)
}
require.NoError(t, config.GlobalConfig.LoadFromDB(options))
prices, ratios := `{}`, `{}`
if tc.price != "" {
prices = `{"declared-model":` + tc.price + `}`
}
if tc.ratio != "" {
ratios = `{"declared-model":` + tc.ratio + `}`
}
require.NoError(t, ratio_setting.UpdateModelPriceByJSONString(prices))
require.NoError(t, ratio_setting.UpdateModelRatioByJSONString(ratios))
meta := `fetchMode:"per_task",usageSchema:{seconds:{type:"number",unit:"second"}}`
if tc.relay != "" {
meta += `,relay:` + tc.relay
}
source := strings.Replace(billingFallbackPlugin, `fetchMode:"per_task"`, meta, 1) + `export function extractUsage(){return {seconds:2};}`
registry := pluginruntime.NewRegistry()
plugin, err := registry.Register(source, pluginruntime.Options{})
require.NoError(t, err)
if tc.chatQuota != 0 || tc.chatErr != "" {
chatContext, _ := gin.CreateTestContext(httptest.NewRecorder())
chatContext.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
chatContext.Request.Header.Set("Accept-Language", "en")
chat := &relaycommon.RelayInfo{
OriginModelName: "declared-model", UserGroup: "default", UsingGroup: "default", RelayFormat: kittypes.RelayFormatOpenAI,
Request: &kitdto.GeneralOpenAIRequest{Model: "declared-model"}, BillingRequestInput: &billingexpr.RequestInput{},
}
chatPrice, err := helper.ModelPriceHelper(chatContext, chat, 1000, &kittypes.TokenCountMeta{})
if tc.chatErr != "" {
require.ErrorContains(t, err, tc.chatErr)
} else {
require.NoError(t, err)
assert.Equal(t, tc.chatQuota, chatPrice.QuotaToPreConsume)
}
}
c, info := newTaskSubmitContext(t, "declared-model", "")
c.Request.Header.Set("Accept-Language", "en")
c.Set("group", "default")
c.Set(pluginruntime.ContextKeyPinnedPlugin, pluginruntime.PinnedPlugin{Generation: registry.Generation(), Plugin: plugin})
info.OriginModelName, info.UserGroup, info.UsingGroup = "declared-model", "default", "default"
_, taskErr := RelayTaskSubmit(c, info)
require.NotNil(t, taskErr) // This fixture stops at reservation, before upstream submission.
if tc.taskErr != "" {
assert.Equal(t, "model_price_error", taskErr.Code)
assert.Equal(t, http.StatusBadRequest, taskErr.StatusCode)
assert.Contains(t, taskErr.Message, tc.taskErr)
assert.Nil(t, info.TieredBillingSnapshot)
return
}
assert.NotEqual(t, "model_price_error", taskErr.Code, "submission error: %+v", taskErr)
assert.Equal(t, tc.taskQuota, info.PriceData.Quota)
if tc.taskExpr == "" {
assert.Nil(t, info.TieredBillingSnapshot)
return
}
require.NotNil(t, info.TieredBillingSnapshot)
assert.Equal(t, tc.taskExpr, info.TieredBillingSnapshot.ExprString)
})
}
}
// Issue #7478: task APIs answer 201 Created or 202 Accepted on submission.
// Every 2xx must reach parseSubmitResponse; only other statuses are upstream
// failures that keep the upstream status and body.
func TestRelayTaskSubmitAcceptsAnySuccessfulUpstreamStatus(t *testing.T) {
service.InitHttpClient()
const source = `
export const meta = {apiVersion:1,key:"status-echo",name:"Status Echo",version:"1.0.0",author:{name:"Test"},models:["declared-model"],fetchMode:"per_task"};
export function buildSubmitRequest(ctx) { return {url: ctx.baseUrl+"/submit", method:"POST", body:{model: ctx.model}, action:"text_to_video"}; }
export function parseSubmitResponse(ctx, response) { return {taskId: response.body.id, taskData: {status: response.statusCode}}; }
export function buildQueryRequest(ctx) { return {url: ctx.baseUrl+"/query"}; }
export function parseTaskResult() { return {status:"SUCCESS"}; }
`
for _, tc := range []struct {
status int
wantCode string
}{
{status: http.StatusOK},
{status: http.StatusCreated},
{status: http.StatusAccepted},
{status: http.StatusBadRequest, wantCode: "fail_to_fetch_task"},
{status: http.StatusBadGateway, wantCode: "fail_to_fetch_task"},
} {
t.Run(strconv.Itoa(tc.status), func(t *testing.T) {
saveBillingConfig(t)
require.NoError(t, config.GlobalConfig.LoadFromDB(map[string]string{
"billing_setting.billing_mode": `{"declared-model":"tiered_expr"}`,
"billing_setting.billing_expr": `{"declared-model":"tier(\"flat\", 3)"}`,
}))
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(tc.status)
_, _ = w.Write([]byte(`{"id":"job-42","message":"upstream body"}`))
}))
defer server.Close()
c, info := newTaskSubmitContext(t, "declared-model", "")
common.SetContextKey(c, constant.ContextKeyChannelBaseUrl, server.URL)
c.Set("group", "default")
info.UserGroup, info.UsingGroup = "default", "default"
info.OriginModelName = "declared-model"
// An existing reservation stands in for the wallet so the fixture reaches the upstream call.
info.Billing = &imageReservation{limit: 1 << 30}
pinMappingOrderPlugin(t, c, source)
result, taskErr := RelayTaskSubmit(c, info)
if tc.wantCode != "" {
require.NotNil(t, taskErr)
assert.Equal(t, tc.wantCode, taskErr.Code)
assert.Equal(t, tc.status, taskErr.StatusCode)
assert.Contains(t, taskErr.Message, "upstream body")
assert.Nil(t, result)
return
}
require.Nil(t, taskErr, "submission error: %+v", taskErr)
require.NotNil(t, result)
assert.Equal(t, "job-42", result.UpstreamTaskID)
assert.JSONEq(t, `{"status":`+strconv.Itoa(tc.status)+`}`, string(result.TaskData))
})
}
}
// A retry prices the plugin it lands on from scratch and holds that price
// before the upstream sees the request. Plugin A fails upstream on the first
// attempt; the retry runs on plugin B, pinned the way
// SetupContextForSelectedChannel pins another candidate plugin's channel.
func TestRelayTaskSubmitRetryRepricesAndReservesBeforeUpstream(t *testing.T) {
service.InitHttpClient()
const source = `
export const meta = {apiVersion:1,key:"KEY",name:"KEY",version:"1.0.0",author:{name:"Test"},models:["declared-model"],fetchMode:"per_task",usageSchema:{seconds:{type:"number",unit:"second",description:"Video generation unit price"}}};
export function buildSubmitRequest(ctx) { return {url: ctx.baseUrl+"/submit", method:"POST", body:{model: ctx.model}, action:"text_to_video"}; }
export function parseSubmitResponse(ctx, response) { return {taskId: response.body.id}; }
export function buildQueryRequest(ctx) { return {url: ctx.baseUrl+"/query"}; }
export function parseTaskResult() { return {status:"SUCCESS"}; }
export function extractUsage() { return {seconds:2}; }
`
pricier := map[string]string{"retry-a::declared-model": `tier("a", u("seconds") * 0.05)`, "retry-b::declared-model": `tier("b", u("seconds") * 0.4)`}
for _, tc := range []struct {
name, perCallPrice, wantCode string
expressions map[string]string
wallet, wantQuota int
wantSubmitted []string
}{
{name: "per-call plugin drops the previous expression", expressions: map[string]string{"retry-a::declared-model": `tier("a", u("seconds") * 0.02)`}, perCallPrice: `{"declared-model":0.04}`, wallet: 1 << 30, wantQuota: 40000, wantSubmitted: []string{"a", "b"}},
{name: "pricier plugin is held before submission", expressions: pricier, perCallPrice: `{}`, wallet: 1 << 30, wantQuota: 400000, wantSubmitted: []string{"a", "b"}},
{name: "unaffordable plugin is never submitted", expressions: pricier, perCallPrice: `{}`, wallet: 100000, wantCode: "insufficient_user_quota", wantSubmitted: []string{"a"}},
} {
t.Run(tc.name, func(t *testing.T) {
saveBillingConfig(t)
savedPrices := ratio_setting.ModelPrice2JSONString()
t.Cleanup(func() { require.NoError(t, ratio_setting.UpdateModelPriceByJSONString(savedPrices)) })
require.NoError(t, ratio_setting.UpdateModelPriceByJSONString(tc.perCallPrice))
expressions, err := common.Marshal(tc.expressions)
require.NoError(t, err)
require.NoError(t, config.GlobalConfig.LoadFromDB(map[string]string{
billing_setting.PluginBillingExprOption: string(expressions),
"billing_setting.billing_mode": `{}`,
"billing_setting.billing_expr": `{}`,
"group_ratio_setting.group_ratio": `{"default":1}`,
}))
registry := pluginruntime.NewRegistry()
for _, key := range []string{"retry-a", "retry-b"} {
_, err := registry.Register(strings.ReplaceAll(source, "KEY", key), pluginruntime.Options{})
require.NoError(t, err)
}
// The fake stands in for the session the first attempt created; its
// limit is the most the wallet can hold.
billing := &imageReservation{limit: tc.wallet}
var submitted []string
var heldAtSubmit []int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
attempt, _, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/")
submitted = append(submitted, attempt)
heldAtSubmit = append(heldAtSubmit, billing.held)
w.Header().Set("Content-Type", "application/json")
if attempt == "a" {
w.WriteHeader(http.StatusInternalServerError)
}
_, _ = w.Write([]byte(`{"id":"job-` + attempt + `"}`))
}))
defer server.Close()
c, info := newTaskSubmitContext(t, "declared-model", "")
c.Set("group", "default")
info.UserGroup, info.UsingGroup, info.OriginModelName = "default", "default", "declared-model"
info.Billing = billing
var result *TaskSubmitResult
var taskErr *dto.TaskError
for _, attempt := range []string{"a", "b"} {
plugin, ok := registry.Generation().Get("retry-" + attempt)
require.True(t, ok)
c.Set(pluginruntime.ContextKeyPinnedPlugin, pluginruntime.PinnedPlugin{Generation: registry.Generation(), Plugin: plugin})
c.Set("task_plugin_key", plugin.Meta.Key)
common.SetContextKey(c, constant.ContextKeyChannelBaseUrl, server.URL+"/"+attempt)
result, taskErr = RelayTaskSubmit(c, info)
if attempt == "a" {
require.NotNil(t, taskErr)
require.Equal(t, http.StatusInternalServerError, taskErr.StatusCode, "the first attempt fails upstream and is retried")
}
}
require.Equal(t, tc.wantSubmitted, submitted)
if tc.wantCode != "" {
require.NotNil(t, taskErr)
assert.Equal(t, tc.wantCode, taskErr.Code)
assert.Equal(t, http.StatusForbidden, taskErr.StatusCode)
return
}
require.Nil(t, taskErr, "submission error: %+v", taskErr)
assert.Equal(t, tc.wantQuota, result.Quota)
assert.Equal(t, tc.wantQuota, heldAtSubmit[1], "plugin B must not see the request before its price is held")
if tc.perCallPrice != `{}` {
assert.Nil(t, info.TieredBillingSnapshot, "a per-call plugin must not settle with the previous plugin's expression")
return
}
require.NotNil(t, info.TieredBillingSnapshot)
assert.Equal(t, tc.expressions["retry-b::declared-model"], info.TieredBillingSnapshot.ExprString)
})
}
}