feat(platform): 模型管理与后台能力 - 新增逻辑模型路由和响应拦截
This commit is contained in:
1 parent
0002cdd2cb
commit
8c5f56a551
89 files changed
+21451
-1170
No files matched your search
@@ -20,6 +20,12 @@ func Models() []any {
|
||||
&model.EmailVerificationCode{},
|
||||
&model.ModelChannel{},
|
||||
&model.ChannelModel{},
|
||||
&model.IDSequence{},
|
||||
&model.LogicalModel{},
|
||||
&model.LogicalModelRevision{},
|
||||
&model.PhysicalCapabilityVariant{},
|
||||
&model.LogicalModelRoute{},
|
||||
&model.RouteAttempt{},
|
||||
&model.ApiCallLog{},
|
||||
&model.ModelPricing{},
|
||||
&model.CreditAccount{},
|
||||
@@ -81,6 +87,10 @@ func MigrateSchema(db *gorm.DB) error {
|
||||
if err := db.AutoMigrate(Models()...); err != nil {
|
||||
return err
|
||||
}
|
||||
// 为升级前已存在的逻辑模型回填版本序列,避免首次保存时从 0 重新分配。
|
||||
if err := db.Exec(`UPDATE logical_models SET revision_sequence = COALESCE((SELECT MAX(version) FROM logical_model_revisions WHERE logical_model_id = logical_models.id), 0) WHERE revision_sequence = 0`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// 逻辑删除后的同名模型允许重新添加,旧唯一索引不能继续覆盖已删除记录。
|
||||
if err := db.Exec("DROP INDEX IF EXISTS idx_channel_model_key").Error; err != nil {
|
||||
return err
|
||||
@@ -88,6 +98,9 @@ func MigrateSchema(db *gorm.DB) error {
|
||||
if err := db.Exec("DROP INDEX IF EXISTS idx_users_email").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := db.Exec("DROP INDEX IF EXISTS idx_route_attempt_task_number").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email_nonempty ON users(lower(email)) WHERE email <> ''").Error
|
||||
}
|
||||
|
||||
|
||||
@@ -116,7 +116,11 @@ func RegisterAuthRoutes(r *gin.RouterGroup, svc *service.Service) {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
channels, _ := svc.PublicSystemChannels()
|
||||
logicalModels, logicalModelsErr := svc.PublicLogicalModels(nil)
|
||||
if logicalModelsErr != nil {
|
||||
failService(c, logicalModelsErr)
|
||||
return
|
||||
}
|
||||
limits, err := svc.PublicRuntimeLimits()
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
@@ -132,10 +136,15 @@ func RegisterAuthRoutes(r *gin.RouterGroup, svc *service.Service) {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
ok(c, gin.H{"user": publicUser, "systemChannels": channels, "runtimeLimits": limits, "drawingEngine": drawingEngine, "features": features})
|
||||
ok(c, gin.H{"user": publicUser, "logicalModels": logicalModels, "runtimeLimits": limits, "drawingEngine": drawingEngine, "features": features})
|
||||
})
|
||||
r.GET("/channels/system", func(c *gin.Context) {
|
||||
if _, err := currentUser(c, svc); err != nil {
|
||||
actor, err := currentUser(c, svc)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
if err := svc.RequireAdmin(actor); err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ func RegisterCustomRelayRoutes(r *gin.RouterGroup, svc *service.Service) {
|
||||
return
|
||||
}
|
||||
defer release()
|
||||
proxyCustomRelayRequestWithCapabilities(c, policy.Request, svc.DesktopLocalChannelsEnabled())
|
||||
proxyCustomRelayRequestWithService(c, policy.Request, svc.DesktopLocalChannelsEnabled(), svc)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -55,6 +55,10 @@ func proxyCustomRelayRequest(c *gin.Context, policy service.RuntimeRequestPolicy
|
||||
}
|
||||
|
||||
func proxyCustomRelayRequestWithCapabilities(c *gin.Context, policy service.RuntimeRequestPolicy, desktopLocalChannelsEnabled bool) {
|
||||
proxyCustomRelayRequestWithService(c, policy, desktopLocalChannelsEnabled, nil)
|
||||
}
|
||||
|
||||
func proxyCustomRelayRequestWithService(c *gin.Context, policy service.RuntimeRequestPolicy, desktopLocalChannelsEnabled bool, svc *service.Service) {
|
||||
requestedAllowLocal := strings.TrimSpace(c.GetHeader(service.LocalChannelRequestHeader)) == "1"
|
||||
target, err := service.ValidateCustomRelayChannelURL(c.GetHeader("X-Canvas-Upstream-URL"), c.GetHeader(service.LocalChannelBaseURLHeader), requestedAllowLocal, desktopLocalChannelsEnabled)
|
||||
if err != nil {
|
||||
@@ -122,20 +126,20 @@ func proxyCustomRelayRequestWithCapabilities(c *gin.Context, policy service.Runt
|
||||
|
||||
resp, err := customRelayClient(time.Duration(policy.CustomRelayTimeoutMinutes)*time.Minute, target, requestedAllowLocal, desktopLocalChannelsEnabled).Do(upstreamReq)
|
||||
if err != nil {
|
||||
fail(c, http.StatusBadGateway, errors.New("自定义渠道上游连接失败"))
|
||||
fail(c, http.StatusBadGateway, errors.New(userFacingRelayError(svc, errors.New("自定义渠道上游连接失败"))))
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
allowBinary := customVideoContentPath.MatchString(target.EscapedPath()) || strings.HasSuffix(target.Path, "/audio/speech")
|
||||
writeCustomRelayResponse(c, resp, apiKey, policy.CustomRelayResponseMB<<20, allowBinary)
|
||||
writeCustomRelayResponse(c, svc, resp, apiKey, policy.CustomRelayResponseMB<<20, allowBinary)
|
||||
}
|
||||
|
||||
func writeCustomRelayResponse(c *gin.Context, resp *http.Response, apiKey string, responseLimit int64, allowBinary bool) {
|
||||
func writeCustomRelayResponse(c *gin.Context, svc *service.Service, resp *http.Response, apiKey string, responseLimit int64, allowBinary bool) {
|
||||
c.Header("Cache-Control", "no-store")
|
||||
c.Header("X-Content-Type-Options", "nosniff")
|
||||
mediaType, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||
writeCustomRelayError(c, resp, apiKey, mediaType)
|
||||
writeCustomRelayError(c, svc, resp, apiKey, mediaType)
|
||||
return
|
||||
}
|
||||
if mediaType == "text/event-stream" {
|
||||
@@ -149,33 +153,38 @@ func writeCustomRelayResponse(c *gin.Context, resp *http.Response, apiKey string
|
||||
if allowBinary && (strings.HasPrefix(mediaType, "video/") || strings.HasPrefix(mediaType, "audio/") || mediaType == "application/octet-stream") {
|
||||
body, err := readLimitedRelayBody(resp.Body, responseLimit)
|
||||
if err != nil {
|
||||
fail(c, http.StatusBadGateway, errors.New("自定义渠道上游返回了过大的媒体文件"))
|
||||
fail(c, http.StatusBadGateway, errors.New(userFacingRelayError(svc, errors.New("自定义渠道上游返回了过大的媒体文件"))))
|
||||
return
|
||||
}
|
||||
c.Data(resp.StatusCode, mediaType, body)
|
||||
return
|
||||
}
|
||||
if mediaType != "application/json" && !strings.HasSuffix(mediaType, "+json") {
|
||||
fail(c, http.StatusBadGateway, errors.New("自定义渠道上游返回了不支持的内容类型"))
|
||||
fail(c, http.StatusBadGateway, errors.New(userFacingRelayError(svc, errors.New("自定义渠道上游返回了不支持的内容类型"))))
|
||||
return
|
||||
}
|
||||
limit := responseLimit
|
||||
body, err := readLimitedRelayBody(resp.Body, limit)
|
||||
if err != nil || !json.Valid(body) {
|
||||
fail(c, http.StatusBadGateway, errors.New("自定义渠道上游返回无效或过大的 JSON"))
|
||||
fail(c, http.StatusBadGateway, errors.New(userFacingRelayError(svc, errors.New("自定义渠道上游返回无效或过大的 JSON"))))
|
||||
return
|
||||
}
|
||||
body = redactRelaySecret(body, apiKey)
|
||||
c.Data(resp.StatusCode, "application/json; charset=utf-8", body)
|
||||
}
|
||||
|
||||
func writeCustomRelayError(c *gin.Context, resp *http.Response, apiKey string, mediaType string) {
|
||||
func writeCustomRelayError(c *gin.Context, svc *service.Service, resp *http.Response, apiKey string, mediaType string) {
|
||||
body, err := readLimitedRelayBody(resp.Body, maxCustomRelayErrorResponseBytes)
|
||||
if err != nil {
|
||||
fail(c, http.StatusBadGateway, errors.New("自定义渠道上游请求失败"))
|
||||
fail(c, http.StatusBadGateway, errors.New(userFacingRelayError(svc, errors.New("自定义渠道上游请求失败"))))
|
||||
return
|
||||
}
|
||||
body = redactRelaySecret(body, apiKey)
|
||||
rawMessage := strings.TrimSpace(string(body))
|
||||
if intercepted := interceptedRelayText(svc, rawMessage); intercepted != rawMessage {
|
||||
fail(c, resp.StatusCode, errors.New(intercepted))
|
||||
return
|
||||
}
|
||||
if (mediaType == "application/json" || strings.HasSuffix(mediaType, "+json")) && json.Valid(body) {
|
||||
c.Data(resp.StatusCode, "application/json; charset=utf-8", body)
|
||||
return
|
||||
@@ -184,7 +193,21 @@ func writeCustomRelayError(c *gin.Context, resp *http.Response, apiKey string, m
|
||||
if len(snippet) > 200 {
|
||||
snippet = snippet[:200] + "..."
|
||||
}
|
||||
fail(c, resp.StatusCode, fmt.Errorf("自定义渠道上游请求失败(%s)%s", resp.Status, snippet))
|
||||
fail(c, resp.StatusCode, errors.New(userFacingRelayError(svc, fmt.Errorf("自定义渠道上游请求失败(%s)%s", resp.Status, snippet))))
|
||||
}
|
||||
|
||||
func userFacingRelayError(svc *service.Service, err error) string {
|
||||
if svc == nil {
|
||||
return err.Error()
|
||||
}
|
||||
return svc.UserFacingErrorMessage(err)
|
||||
}
|
||||
|
||||
func interceptedRelayText(svc *service.Service, raw string) string {
|
||||
if svc == nil {
|
||||
return raw
|
||||
}
|
||||
return svc.InterceptResponseText(raw)
|
||||
}
|
||||
|
||||
func copyCustomRelayStream(c *gin.Context, source io.Reader, apiKey string, maxBytes int64) {
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"infinite-canvas/backend/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func RegisterLogicalModelRoutes(r *gin.RouterGroup, svc *service.Service) {
|
||||
r.GET("/models", func(c *gin.Context) {
|
||||
if _, err := currentUser(c, svc); err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
models, err := svc.PublicLogicalModels(nil)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
ok(c, gin.H{"models": models})
|
||||
})
|
||||
r.POST("/models/available", func(c *gin.Context) {
|
||||
if _, err := currentUser(c, svc); err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
var intent service.ModelRequestIntent
|
||||
if err := c.ShouldBindJSON(&intent); err != nil {
|
||||
fail(c, http.StatusBadRequest, errors.New("模型能力请求格式错误"))
|
||||
return
|
||||
}
|
||||
models, err := svc.PublicLogicalModels(&intent)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
ok(c, gin.H{"models": models})
|
||||
})
|
||||
r.GET("/admin/logical-models", func(c *gin.Context) {
|
||||
actor, err := currentUser(c, svc)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
models, err := svc.AdminLogicalModels(actor)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
ok(c, gin.H{"models": models})
|
||||
})
|
||||
r.POST("/admin/logical-models", func(c *gin.Context) {
|
||||
saveAdminLogicalModel(c, svc, "")
|
||||
})
|
||||
r.PATCH("/admin/logical-models/:id", func(c *gin.Context) {
|
||||
saveAdminLogicalModel(c, svc, c.Param("id"))
|
||||
})
|
||||
r.GET("/admin/logical-models/physical-variants", func(c *gin.Context) {
|
||||
actor, err := currentUser(c, svc)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
items, err := svc.AdminPhysicalVariantsForChannelModel(actor, c.Query("channelModelId"))
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
ok(c, gin.H{"variants": items})
|
||||
})
|
||||
r.POST("/admin/logical-models/physical-variants", func(c *gin.Context) {
|
||||
saveAdminPhysicalVariant(c, svc, "")
|
||||
})
|
||||
r.PATCH("/admin/logical-models/physical-variants/:id", func(c *gin.Context) {
|
||||
saveAdminPhysicalVariant(c, svc, c.Param("id"))
|
||||
})
|
||||
r.POST("/admin/logical-models/:id/simulate", func(c *gin.Context) {
|
||||
actor, err := currentUser(c, svc)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
var intent service.ModelRequestIntent
|
||||
if err := c.ShouldBindJSON(&intent); err != nil {
|
||||
fail(c, http.StatusBadRequest, errors.New("路由模拟请求格式错误"))
|
||||
return
|
||||
}
|
||||
result, err := svc.SimulateLogicalModelRoute(actor, c.Param("id"), intent)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
ok(c, result)
|
||||
})
|
||||
}
|
||||
|
||||
func saveAdminLogicalModel(c *gin.Context, svc *service.Service, id string) {
|
||||
actor, err := currentUser(c, svc)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
var req service.LogicalModelRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
fail(c, http.StatusBadRequest, errors.New("前台模型参数格式错误"))
|
||||
return
|
||||
}
|
||||
item, err := svc.SaveAdminLogicalModel(actor, id, req)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
ok(c, gin.H{"model": item})
|
||||
}
|
||||
|
||||
func saveAdminPhysicalVariant(c *gin.Context, svc *service.Service, id string) {
|
||||
actor, err := currentUser(c, svc)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
var req service.PhysicalVariantRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
fail(c, http.StatusBadRequest, errors.New("可用配置参数格式错误"))
|
||||
return
|
||||
}
|
||||
item, err := svc.SaveAdminPhysicalVariant(actor, id, req)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
ok(c, gin.H{"variant": item})
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"infinite-canvas/backend/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func RegisterResponseInterceptionRoutes(r *gin.RouterGroup, svc *service.Service) {
|
||||
r.GET("/admin/settings/response-interception", func(c *gin.Context) {
|
||||
user, err := currentUser(c, svc)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
setting, err := svc.AdminResponseInterceptionSetting(user)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
ok(c, gin.H{"setting": setting})
|
||||
})
|
||||
|
||||
r.PATCH("/admin/settings/response-interception", func(c *gin.Context) {
|
||||
user, err := currentUser(c, svc)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 64<<10)
|
||||
var value service.ResponseInterceptionSetting
|
||||
if err := c.ShouldBindJSON(&value); err != nil {
|
||||
fail(c, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
setting, err := svc.UpdateResponseInterceptionSetting(user, value)
|
||||
if err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
ok(c, gin.H{"setting": setting})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
// IDSequence 为需要可读、稳定 ID 的业务对象提供数据库级自增序列。
|
||||
// 对象关联始终使用独立外键,不允许从带前缀 ID 中解析父子关系。
|
||||
type IDSequence struct {
|
||||
Name string `json:"name" gorm:"primaryKey;size:40"`
|
||||
Value int64 `json:"value"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type LogicalModel struct {
|
||||
ID string `json:"id" gorm:"primaryKey;size:36"`
|
||||
Code string `json:"code" gorm:"size:80;uniqueIndex"`
|
||||
Name string `json:"name" gorm:"size:120"`
|
||||
Icon string `json:"icon" gorm:"size:80"`
|
||||
Description string `json:"description" gorm:"size:500"`
|
||||
Capability string `json:"capability" gorm:"size:32;index"`
|
||||
Enabled bool `json:"enabled" gorm:"index"`
|
||||
SortOrder int `json:"sortOrder" gorm:"index"`
|
||||
// RevisionSequence 记录已经分配的 revision 版本号,由数据库原子递增。
|
||||
RevisionSequence int `json:"-" gorm:"not null;default:0"`
|
||||
ActiveRevisionID string `json:"activeRevisionId" gorm:"size:36;index"`
|
||||
PricePolicy string `json:"pricePolicy" gorm:"size:24;default:unified"`
|
||||
BillingMode string `json:"billingMode" gorm:"size:32"`
|
||||
UnitPriceMicrocredits int64 `json:"unitPriceMicrocredits"`
|
||||
InputPriceMicrocredits int64 `json:"inputPriceMicrocredits"`
|
||||
OutputPriceMicrocredits int64 `json:"outputPriceMicrocredits"`
|
||||
CachedPriceMicrocredits int64 `json:"cachedPriceMicrocredits"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// LogicalModelRevision 固化一次可发布的前台能力合同。默认值属于前台模型,不能由供应商隐式决定。
|
||||
type LogicalModelRevision struct {
|
||||
ID string `json:"id" gorm:"primaryKey;size:36"`
|
||||
LogicalModelID string `json:"logicalModelId" gorm:"size:36;index;uniqueIndex:idx_logical_revision_version,priority:1"`
|
||||
Version int `json:"version" gorm:"uniqueIndex:idx_logical_revision_version,priority:2"`
|
||||
CapabilitySpecJSON string `json:"-" gorm:"type:text"`
|
||||
DefaultOptionsJSON string `json:"-" gorm:"type:text"`
|
||||
CreatedBy string `json:"createdBy" gorm:"size:36;index"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
// PhysicalCapabilityVariant 描述一个真实模型可同时满足的一组能力。variant 内为 AND,多个 variant 之间为 OR。
|
||||
type PhysicalCapabilityVariant struct {
|
||||
ID string `json:"id" gorm:"primaryKey;size:36"`
|
||||
ChannelModelID string `json:"channelModelId" gorm:"size:36;index"`
|
||||
Name string `json:"name" gorm:"size:120"`
|
||||
Enabled bool `json:"enabled" gorm:"index"`
|
||||
CapabilitySpecJSON string `json:"-" gorm:"type:text"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type LogicalModelRoute struct {
|
||||
ID string `json:"id" gorm:"primaryKey;size:36"`
|
||||
LogicalModelRevisionID string `json:"logicalModelRevisionId" gorm:"size:36;index;uniqueIndex:idx_logical_route_member,priority:1"`
|
||||
PhysicalVariantID string `json:"physicalVariantId" gorm:"size:36;index;uniqueIndex:idx_logical_route_member,priority:2"`
|
||||
Enabled bool `json:"enabled" gorm:"index"`
|
||||
Priority int `json:"priority" gorm:"index"`
|
||||
Weight int `json:"weight"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type RouteAttempt struct {
|
||||
ID string `json:"id" gorm:"primaryKey;size:36"`
|
||||
TaskID string `json:"taskId" gorm:"size:36;index;uniqueIndex:idx_route_attempt_run_number,priority:1"`
|
||||
RouteRun int `json:"routeRun" gorm:"index;uniqueIndex:idx_route_attempt_run_number,priority:2"`
|
||||
AttemptNumber int `json:"attemptNumber" gorm:"uniqueIndex:idx_route_attempt_run_number,priority:3"`
|
||||
LogicalModelID string `json:"logicalModelId" gorm:"size:36;index"`
|
||||
LogicalModelRevisionID string `json:"logicalModelRevisionId" gorm:"size:36;index"`
|
||||
RouteID string `json:"routeId" gorm:"size:36;index"`
|
||||
PhysicalVariantID string `json:"physicalVariantId" gorm:"size:36;index"`
|
||||
ChannelModelID string `json:"channelModelId" gorm:"size:36;index"`
|
||||
ChannelID string `json:"channelId" gorm:"size:36;index"`
|
||||
Status string `json:"status" gorm:"size:32;index"`
|
||||
DispatchState string `json:"dispatchState" gorm:"size:32;index"`
|
||||
ProviderRequestID string `json:"providerRequestId" gorm:"size:160;index"`
|
||||
FailureCode string `json:"failureCode" gorm:"size:80"`
|
||||
FailureMessage string `json:"failureMessage" gorm:"size:1000"`
|
||||
StartedAt time.Time `json:"startedAt"`
|
||||
CompletedAt *time.Time `json:"completedAt"`
|
||||
}
|
||||
@@ -3,18 +3,24 @@ package model
|
||||
import "time"
|
||||
|
||||
type Task struct {
|
||||
ID string `json:"id" gorm:"primaryKey;size:36"`
|
||||
UserID string `json:"userId" gorm:"index;size:36;index:idx_tasks_user_created,priority:1"`
|
||||
SessionID string `json:"sessionId" gorm:"index;size:36"`
|
||||
ProjectID string `json:"projectId" gorm:"index;size:80"`
|
||||
Type string `json:"type" gorm:"index;size:64"`
|
||||
Status TaskStatus `json:"status" gorm:"index;size:24;index:idx_tasks_status_created,priority:1;index:idx_tasks_claim,priority:1;index:idx_tasks_provider_cancel,priority:1"`
|
||||
Stage string `json:"stage" gorm:"size:80"`
|
||||
Progress int `json:"progress"`
|
||||
Prompt string `json:"prompt"`
|
||||
Operation string `json:"operation" gorm:"size:64"`
|
||||
Provider string `json:"provider" gorm:"size:64"`
|
||||
Model string `json:"model" gorm:"size:120"`
|
||||
ID string `json:"id" gorm:"primaryKey;size:36"`
|
||||
UserID string `json:"userId" gorm:"index;size:36;index:idx_tasks_user_created,priority:1"`
|
||||
SessionID string `json:"sessionId" gorm:"index;size:36"`
|
||||
ProjectID string `json:"projectId" gorm:"index;size:80"`
|
||||
Type string `json:"type" gorm:"index;size:64"`
|
||||
Status TaskStatus `json:"status" gorm:"index;size:24;index:idx_tasks_status_created,priority:1;index:idx_tasks_claim,priority:1;index:idx_tasks_provider_cancel,priority:1"`
|
||||
Stage string `json:"stage" gorm:"size:80"`
|
||||
Progress int `json:"progress"`
|
||||
Prompt string `json:"prompt"`
|
||||
Operation string `json:"operation" gorm:"size:64"`
|
||||
Provider string `json:"provider" gorm:"size:64"`
|
||||
Model string `json:"model" gorm:"size:120"`
|
||||
LogicalModelID string `json:"logicalModelId,omitempty" gorm:"size:36;index"`
|
||||
LogicalModelRevisionID string `json:"logicalModelRevisionId,omitempty" gorm:"size:36;index"`
|
||||
RouteID string `json:"routeId,omitempty" gorm:"size:36;index"`
|
||||
PhysicalVariantID string `json:"physicalVariantId,omitempty" gorm:"size:36;index"`
|
||||
// RouteRun 只在用户主动重试时递增;worker 租约恢复不应创建新的路由选择世代。
|
||||
RouteRun int `json:"-" gorm:"index"`
|
||||
BillingOrderID string `json:"billingOrderId,omitempty" gorm:"index;size:36"`
|
||||
ProviderRequestID string `json:"providerRequestId,omitempty" gorm:"index;size:160"`
|
||||
ProviderCancelStatus ProviderCancelStatus `json:"providerCancelStatus,omitempty" gorm:"index;size:24;index:idx_tasks_provider_cancel,priority:2"`
|
||||
|
||||
@@ -211,8 +211,9 @@ func (r *Repository) CreateTaskWithActiveLimit(task *model.Task, activeTaskLimit
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) RetryTaskWithBilling(userID string, taskID string, order *model.BillingOrder, activeTaskLimit int) (*model.Task, error) {
|
||||
func (r *Repository) RetryTaskWithBilling(userID string, prepared *model.Task, order *model.BillingOrder, activeTaskLimit int) (*model.Task, error) {
|
||||
var task model.Task
|
||||
taskID := prepared.ID
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := enforceActiveTaskLimit(tx, userID, activeTaskLimit); err != nil {
|
||||
return err
|
||||
@@ -228,6 +229,10 @@ func (r *Repository) RetryTaskWithBilling(userID string, taskID string, order *m
|
||||
"provider_request_id": "", "poll_stage": "", "next_poll_at": nil,
|
||||
"provider_cancel_status": "", "provider_cancel_error": "", "provider_cancel_attempts": 0,
|
||||
"provider_cancel_requested_at": nil, "provider_cancelled_at": nil, "provider_cancel_next_check_at": nil,
|
||||
"route_run": gorm.Expr("route_run + ?", 1),
|
||||
"logical_model_revision_id": prepared.LogicalModelRevisionID, "route_id": prepared.RouteID,
|
||||
"physical_variant_id": prepared.PhysicalVariantID, "input_json": prepared.InputJSON,
|
||||
"model": prepared.Model, "provider": prepared.Provider,
|
||||
"lease_owner": "", "lease_expires_at": nil, "updated_at": time.Now(),
|
||||
}
|
||||
if order != nil {
|
||||
|
||||
@@ -0,0 +1,519 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type LogicalModelGraph struct {
|
||||
Model model.LogicalModel
|
||||
Revision *model.LogicalModelRevision
|
||||
Routes []model.LogicalModelRoute
|
||||
Variants []model.PhysicalCapabilityVariant
|
||||
ChannelModels []model.ChannelModel
|
||||
}
|
||||
|
||||
func (r *Repository) LogicalModels(includeDisabled bool) ([]model.LogicalModel, error) {
|
||||
var items []model.LogicalModel
|
||||
query := r.db.Order("sort_order asc, created_at asc")
|
||||
if !includeDisabled {
|
||||
query = query.Where("enabled = ?", true)
|
||||
}
|
||||
return items, query.Find(&items).Error
|
||||
}
|
||||
|
||||
func (r *Repository) LogicalModel(id string) (*model.LogicalModel, error) {
|
||||
var item model.LogicalModel
|
||||
if err := r.db.First(&item, "id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func (r *Repository) LogicalModelRevision(id string) (*model.LogicalModelRevision, error) {
|
||||
var item model.LogicalModelRevision
|
||||
if err := r.db.First(&item, "id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func (r *Repository) LogicalModelRevisions(logicalModelID string) ([]model.LogicalModelRevision, error) {
|
||||
var items []model.LogicalModelRevision
|
||||
return items, r.db.Where("logical_model_id = ?", logicalModelID).Order("version desc").Find(&items).Error
|
||||
}
|
||||
|
||||
func (r *Repository) LogicalModelRoutes(revisionID string, includeDisabled bool) ([]model.LogicalModelRoute, error) {
|
||||
var items []model.LogicalModelRoute
|
||||
query := r.db.Where("logical_model_revision_id = ?", revisionID).Order("priority desc, created_at asc")
|
||||
if !includeDisabled {
|
||||
query = query.Where("enabled = ? AND weight > ?", true, 0)
|
||||
}
|
||||
return items, query.Find(&items).Error
|
||||
}
|
||||
|
||||
func (r *Repository) LogicalModelRoute(id string) (*model.LogicalModelRoute, error) {
|
||||
var item model.LogicalModelRoute
|
||||
if err := r.db.First(&item, "id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func (r *Repository) PhysicalVariants(channelModelIDs []string, includeDisabled bool) ([]model.PhysicalCapabilityVariant, error) {
|
||||
var items []model.PhysicalCapabilityVariant
|
||||
if len(channelModelIDs) == 0 {
|
||||
return items, nil
|
||||
}
|
||||
query := r.db.Where("channel_model_id IN ?", channelModelIDs).Order("created_at asc")
|
||||
if !includeDisabled {
|
||||
query = query.Where("enabled = ?", true)
|
||||
}
|
||||
return items, query.Find(&items).Error
|
||||
}
|
||||
|
||||
func (r *Repository) PhysicalVariant(id string) (*model.PhysicalCapabilityVariant, error) {
|
||||
var item model.PhysicalCapabilityVariant
|
||||
if err := r.db.First(&item, "id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func (r *Repository) AllPhysicalVariants(includeDisabled bool) ([]model.PhysicalCapabilityVariant, error) {
|
||||
var items []model.PhysicalCapabilityVariant
|
||||
query := r.db.Order("created_at asc")
|
||||
if !includeDisabled {
|
||||
query = query.Where("enabled = ?", true)
|
||||
}
|
||||
return items, query.Find(&items).Error
|
||||
}
|
||||
|
||||
func (r *Repository) PhysicalVariantRouteCounts(ids []string) (map[string]int64, error) {
|
||||
counts := make(map[string]int64, len(ids))
|
||||
if len(ids) == 0 {
|
||||
return counts, nil
|
||||
}
|
||||
type row struct {
|
||||
PhysicalVariantID string `gorm:"column:physical_variant_id"`
|
||||
Count int64 `gorm:"column:count"`
|
||||
}
|
||||
var rows []row
|
||||
if err := r.db.Model(&model.LogicalModelRoute{}).
|
||||
Select("physical_variant_id, COUNT(*) AS count").
|
||||
Where("physical_variant_id IN ?", uniqueStrings(ids)).
|
||||
Group("physical_variant_id").
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, item := range rows {
|
||||
counts[item.PhysicalVariantID] = item.Count
|
||||
}
|
||||
return counts, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ChannelModelsByIDs(ids []string) ([]model.ChannelModel, error) {
|
||||
var items []model.ChannelModel
|
||||
if len(ids) == 0 {
|
||||
return items, nil
|
||||
}
|
||||
return items, r.db.Where("id IN ?", ids).Find(&items).Error
|
||||
}
|
||||
|
||||
func (r *Repository) SystemChannelsByIDs(ids []string, includeDisabled bool) ([]model.ModelChannel, error) {
|
||||
var items []model.ModelChannel
|
||||
if len(ids) == 0 {
|
||||
return items, nil
|
||||
}
|
||||
query := r.db.Where("id IN ? AND scope = ?", uniqueStrings(ids), model.ChannelScopeSystem)
|
||||
if !includeDisabled {
|
||||
query = query.Where("enabled = ?", true)
|
||||
}
|
||||
return items, query.Find(&items).Error
|
||||
}
|
||||
|
||||
func (r *Repository) ChannelModel(id string) (*model.ChannelModel, error) {
|
||||
var item model.ChannelModel
|
||||
if err := r.db.First(&item, "id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func (r *Repository) LogicalModelGraph(id string, includeDisabled bool) (*LogicalModelGraph, error) {
|
||||
item, err := r.LogicalModel(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !includeDisabled && !item.Enabled {
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
graphs, err := r.LogicalModelGraphs([]model.LogicalModel{*item}, includeDisabled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return graphs[item.ID], nil
|
||||
}
|
||||
|
||||
// LogicalModelGraphs 批量加载前台模型的当前 revision、供应线路、可用配置和渠道模型。
|
||||
// 管理列表与路由目录都需要同一张关系图,集中按 IN 查询避免逐模型 N+1。
|
||||
func (r *Repository) LogicalModelGraphs(items []model.LogicalModel, includeDisabled bool) (map[string]*LogicalModelGraph, error) {
|
||||
graphs := make(map[string]*LogicalModelGraph, len(items))
|
||||
if len(items) == 0 {
|
||||
return graphs, nil
|
||||
}
|
||||
|
||||
revisionIDs := make([]string, 0, len(items))
|
||||
for _, item := range items {
|
||||
graphs[item.ID] = &LogicalModelGraph{Model: item}
|
||||
if item.ActiveRevisionID != "" {
|
||||
revisionIDs = append(revisionIDs, item.ActiveRevisionID)
|
||||
}
|
||||
}
|
||||
if len(revisionIDs) == 0 {
|
||||
return graphs, nil
|
||||
}
|
||||
|
||||
var revisions []model.LogicalModelRevision
|
||||
if err := r.db.Where("id IN ?", uniqueStrings(revisionIDs)).Find(&revisions).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
revisionByID := make(map[string]model.LogicalModelRevision, len(revisions))
|
||||
for _, revision := range revisions {
|
||||
revisionByID[revision.ID] = revision
|
||||
}
|
||||
|
||||
routeRevisionIDs := make([]string, 0, len(revisions))
|
||||
for _, item := range items {
|
||||
graph := graphs[item.ID]
|
||||
revision, ok := revisionByID[item.ActiveRevisionID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
r := revision
|
||||
graph.Revision = &r
|
||||
routeRevisionIDs = append(routeRevisionIDs, revision.ID)
|
||||
}
|
||||
|
||||
var routes []model.LogicalModelRoute
|
||||
if len(routeRevisionIDs) > 0 {
|
||||
query := r.db.Where("logical_model_revision_id IN ?", uniqueStrings(routeRevisionIDs)).Order("priority desc, created_at asc")
|
||||
if !includeDisabled {
|
||||
query = query.Where("enabled = ? AND weight > ?", true, 0)
|
||||
}
|
||||
if err := query.Find(&routes).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
routesByRevision := make(map[string][]model.LogicalModelRoute, len(routeRevisionIDs))
|
||||
variantIDs := make([]string, 0, len(routes))
|
||||
for _, route := range routes {
|
||||
routesByRevision[route.LogicalModelRevisionID] = append(routesByRevision[route.LogicalModelRevisionID], route)
|
||||
variantIDs = append(variantIDs, route.PhysicalVariantID)
|
||||
}
|
||||
|
||||
variants, err := r.PhysicalVariantsByIDs(uniqueStrings(variantIDs), includeDisabled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
variantByID := make(map[string]model.PhysicalCapabilityVariant, len(variants))
|
||||
channelModelIDs := make([]string, 0, len(variants))
|
||||
for _, variant := range variants {
|
||||
variantByID[variant.ID] = variant
|
||||
channelModelIDs = append(channelModelIDs, variant.ChannelModelID)
|
||||
}
|
||||
channelModels, err := r.ChannelModelsByIDs(uniqueStrings(channelModelIDs))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channelModelByID := make(map[string]model.ChannelModel, len(channelModels))
|
||||
for _, channelModel := range channelModels {
|
||||
channelModelByID[channelModel.ID] = channelModel
|
||||
}
|
||||
|
||||
for _, item := range items {
|
||||
graph := graphs[item.ID]
|
||||
if graph.Revision == nil {
|
||||
continue
|
||||
}
|
||||
graph.Routes = routesByRevision[graph.Revision.ID]
|
||||
graph.Variants = make([]model.PhysicalCapabilityVariant, 0, len(graph.Routes))
|
||||
graph.ChannelModels = make([]model.ChannelModel, 0, len(graph.Routes))
|
||||
seenVariants := make(map[string]bool, len(graph.Routes))
|
||||
seenChannelModels := make(map[string]bool, len(graph.Routes))
|
||||
for _, route := range graph.Routes {
|
||||
variant, variantOK := variantByID[route.PhysicalVariantID]
|
||||
if !variantOK {
|
||||
continue
|
||||
}
|
||||
if !seenVariants[variant.ID] {
|
||||
seenVariants[variant.ID] = true
|
||||
graph.Variants = append(graph.Variants, variant)
|
||||
}
|
||||
if channelModel, channelOK := channelModelByID[variant.ChannelModelID]; channelOK && !seenChannelModels[channelModel.ID] {
|
||||
seenChannelModels[channelModel.ID] = true
|
||||
graph.ChannelModels = append(graph.ChannelModels, channelModel)
|
||||
}
|
||||
}
|
||||
}
|
||||
return graphs, nil
|
||||
}
|
||||
|
||||
func (r *Repository) PhysicalVariantsByIDs(ids []string, includeDisabled bool) ([]model.PhysicalCapabilityVariant, error) {
|
||||
var items []model.PhysicalCapabilityVariant
|
||||
if len(ids) == 0 {
|
||||
return items, nil
|
||||
}
|
||||
query := r.db.Where("id IN ?", ids).Order("created_at asc")
|
||||
if !includeDisabled {
|
||||
query = query.Where("enabled = ?", true)
|
||||
}
|
||||
return items, query.Find(&items).Error
|
||||
}
|
||||
|
||||
func uniqueStrings(values []string) []string {
|
||||
result := make([]string, 0, len(values))
|
||||
seen := make(map[string]bool, len(values))
|
||||
for _, value := range values {
|
||||
if value == "" || seen[value] {
|
||||
continue
|
||||
}
|
||||
seen[value] = true
|
||||
result = append(result, value)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (r *Repository) PhysicalVariantsForRoutes(routes []model.LogicalModelRoute, includeDisabled bool) ([]model.PhysicalCapabilityVariant, error) {
|
||||
ids := make([]string, 0, len(routes))
|
||||
for _, route := range routes {
|
||||
ids = append(ids, route.PhysicalVariantID)
|
||||
}
|
||||
var items []model.PhysicalCapabilityVariant
|
||||
if len(ids) == 0 {
|
||||
return items, nil
|
||||
}
|
||||
query := r.db.Where("id IN ?", ids)
|
||||
if !includeDisabled {
|
||||
query = query.Where("enabled = ?", true)
|
||||
}
|
||||
return items, query.Find(&items).Error
|
||||
}
|
||||
|
||||
func (r *Repository) SaveLogicalModel(item *model.LogicalModel) error { return r.db.Save(item).Error }
|
||||
func (r *Repository) CreateLogicalModel(item *model.LogicalModel) error {
|
||||
return r.db.Create(item).Error
|
||||
}
|
||||
func (r *Repository) CreateLogicalModelRevision(item *model.LogicalModelRevision) error {
|
||||
return r.db.Create(item).Error
|
||||
}
|
||||
func (r *Repository) SaveLogicalModelRevision(item *model.LogicalModelRevision) error {
|
||||
return r.db.Save(item).Error
|
||||
}
|
||||
func (r *Repository) CreatePhysicalVariant(item *model.PhysicalCapabilityVariant) error {
|
||||
return r.db.Create(item).Error
|
||||
}
|
||||
func (r *Repository) SavePhysicalVariant(item *model.PhysicalCapabilityVariant) error {
|
||||
return r.db.Save(item).Error
|
||||
}
|
||||
func (r *Repository) CreateLogicalModelRoute(item *model.LogicalModelRoute) error {
|
||||
return r.db.Create(item).Error
|
||||
}
|
||||
func (r *Repository) SaveLogicalModelRoute(item *model.LogicalModelRoute) error {
|
||||
return r.db.Save(item).Error
|
||||
}
|
||||
func (r *Repository) CreateRouteAttempt(item *model.RouteAttempt) error {
|
||||
return r.db.Create(item).Error
|
||||
}
|
||||
func (r *Repository) SaveRouteAttempt(item *model.RouteAttempt) error { return r.db.Save(item).Error }
|
||||
|
||||
func (r *Repository) LatestRouteAttempt(taskID string) (*model.RouteAttempt, error) {
|
||||
var item model.RouteAttempt
|
||||
if err := r.db.Where("task_id = ?", taskID).Order("route_run desc, attempt_number desc").First(&item).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func (r *Repository) PhysicalVariantRouteCount(id string) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.Model(&model.LogicalModelRoute{}).Where("physical_variant_id = ?", id).Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (r *Repository) RouteAttempts(taskID string, routeRun int) ([]model.RouteAttempt, error) {
|
||||
var items []model.RouteAttempt
|
||||
query := r.db.Where("task_id = ? AND route_run = ?", taskID, routeRun)
|
||||
return items, query.Order("attempt_number asc").Find(&items).Error
|
||||
}
|
||||
|
||||
// SwitchTaskLogicalRoute 同时更新任务执行目标和账单。跟随供应价格时会原子调整预留积分,
|
||||
// 保证明确未创建上游任务后的故障切线不会沿用上一条线路的价格快照。
|
||||
func (r *Repository) SwitchTaskLogicalRoute(taskID string, expectedRouteID string, routeID string, variantID string, inputJSON string, billingOrderID string, channelID string, channelModelID string, replacement *model.BillingOrder) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
updated := tx.Model(&model.Task{}).
|
||||
Where("id = ? AND status = ? AND route_id = ?", taskID, model.TaskStatusRunning, expectedRouteID).
|
||||
Updates(map[string]any{"route_id": routeID, "physical_variant_id": variantID, "input_json": inputJSON, "updated_at": time.Now()})
|
||||
if updated.Error != nil {
|
||||
return updated.Error
|
||||
}
|
||||
if updated.RowsAffected != 1 {
|
||||
return ErrTaskStateConflict
|
||||
}
|
||||
if billingOrderID == "" {
|
||||
return nil
|
||||
}
|
||||
var order model.BillingOrder
|
||||
if err := tx.First(&order, "id = ? AND task_id = ? AND status IN ?", billingOrderID, taskID, []model.BillingStatus{model.BillingStatusReserved, model.BillingStatusRunning}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
updates := map[string]any{"channel_id": channelID, "channel_model_id": channelModelID, "updated_at": now}
|
||||
if replacement != nil {
|
||||
if replacement.UserID != order.UserID || replacement.TaskID != taskID || replacement.AmountMicrocredits <= 0 {
|
||||
return ErrBillingStateConflict
|
||||
}
|
||||
reserved := order.ReservedAmountMicrocredits
|
||||
if reserved <= 0 {
|
||||
reserved = order.AmountMicrocredits
|
||||
}
|
||||
delta := replacement.AmountMicrocredits - reserved
|
||||
accountUpdates := map[string]any{"version": gorm.Expr("version + 1"), "updated_at": now}
|
||||
accountQuery := tx.Model(&model.CreditAccount{}).Where("user_id = ?", order.UserID)
|
||||
if delta > 0 {
|
||||
accountQuery = accountQuery.Where("available_microcredits >= ?", delta)
|
||||
accountUpdates["available_microcredits"] = gorm.Expr("available_microcredits - ?", delta)
|
||||
accountUpdates["reserved_microcredits"] = gorm.Expr("reserved_microcredits + ?", delta)
|
||||
} else if delta < 0 {
|
||||
release := -delta
|
||||
accountQuery = accountQuery.Where("reserved_microcredits >= ?", release)
|
||||
accountUpdates["available_microcredits"] = gorm.Expr("available_microcredits + ?", release)
|
||||
accountUpdates["reserved_microcredits"] = gorm.Expr("reserved_microcredits - ?", release)
|
||||
}
|
||||
if delta != 0 {
|
||||
accountUpdated := accountQuery.Updates(accountUpdates)
|
||||
if accountUpdated.Error != nil {
|
||||
return accountUpdated.Error
|
||||
}
|
||||
if accountUpdated.RowsAffected != 1 {
|
||||
if delta > 0 {
|
||||
return ErrInsufficientCredits
|
||||
}
|
||||
return errors.New("reserved credit balance is inconsistent")
|
||||
}
|
||||
var account model.CreditAccount
|
||||
if err := tx.First(&account, "user_id = ?", order.UserID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
entryType := model.CreditLedgerReserve
|
||||
if delta < 0 {
|
||||
entryType = model.CreditLedgerRefund
|
||||
}
|
||||
if err := tx.Create(&model.CreditLedgerEntry{
|
||||
ID: newRepositoryID(), UserID: order.UserID, Type: entryType,
|
||||
AvailableDeltaMicrocredits: -delta, ReservedDeltaMicrocredits: delta,
|
||||
AvailableAfterMicrocredits: account.AvailableMicrocredits, ReservedAfterMicrocredits: account.ReservedMicrocredits,
|
||||
BillingOrderID: order.ID, Model: order.Model, ChannelID: channelID, Scene: order.Scene,
|
||||
Note: "备用供应线路价格调整",
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
updates["billing_mode"] = replacement.BillingMode
|
||||
updates["price_version"] = replacement.PriceVersion
|
||||
updates["unit_price_microcredits"] = replacement.UnitPriceMicrocredits
|
||||
updates["multiplier_basis_points"] = replacement.MultiplierBasisPoints
|
||||
updates["quantity"] = replacement.Quantity
|
||||
updates["amount_microcredits"] = replacement.AmountMicrocredits
|
||||
updates["reserved_amount_microcredits"] = replacement.AmountMicrocredits
|
||||
updates["input_token_price_microcredits"] = replacement.InputTokenPriceMicrocredits
|
||||
updates["output_token_price_microcredits"] = replacement.OutputTokenPriceMicrocredits
|
||||
updates["cached_token_price_microcredits"] = replacement.CachedTokenPriceMicrocredits
|
||||
}
|
||||
billingUpdated := tx.Model(&model.BillingOrder{}).
|
||||
Where("id = ? AND task_id = ? AND status IN ?", billingOrderID, taskID, []model.BillingStatus{model.BillingStatusReserved, model.BillingStatusRunning}).
|
||||
Updates(updates)
|
||||
if billingUpdated.Error != nil {
|
||||
return billingUpdated.Error
|
||||
}
|
||||
if billingUpdated.RowsAffected != 1 {
|
||||
return ErrBillingStateConflict
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) SaveLogicalModelBundle(item *model.LogicalModel, revision *model.LogicalModelRevision, routes []model.LogicalModelRoute, creating bool) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if creating {
|
||||
if err := tx.Create(item).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
result := tx.Model(&model.LogicalModel{}).Where("id = ?", item.ID).Updates(map[string]any{
|
||||
"code": item.Code,
|
||||
"name": item.Name,
|
||||
"icon": item.Icon,
|
||||
"description": item.Description,
|
||||
"capability": item.Capability,
|
||||
"enabled": item.Enabled,
|
||||
"sort_order": item.SortOrder,
|
||||
"price_policy": item.PricePolicy,
|
||||
"billing_mode": item.BillingMode,
|
||||
"unit_price_microcredits": item.UnitPriceMicrocredits,
|
||||
"input_price_microcredits": item.InputPriceMicrocredits,
|
||||
"output_price_microcredits": item.OutputPriceMicrocredits,
|
||||
"cached_price_microcredits": item.CachedPriceMicrocredits,
|
||||
"updated_at": item.UpdatedAt,
|
||||
})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
}
|
||||
|
||||
// 版本号必须由模型行原子递增。MAX(version)+1 会让两个并发事务分配同一版本。
|
||||
result := tx.Model(&model.LogicalModel{}).
|
||||
Where("id = ?", item.ID).
|
||||
UpdateColumn("revision_sequence", gorm.Expr("revision_sequence + ?", 1))
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
var sequence struct{ RevisionSequence int }
|
||||
if err := tx.Model(&model.LogicalModel{}).
|
||||
Select("revision_sequence").
|
||||
Where("id = ?", item.ID).
|
||||
Take(&sequence).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
revision.Version = sequence.RevisionSequence
|
||||
if err := tx.Create(revision).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for index := range routes {
|
||||
routes[index].LogicalModelRevisionID = revision.ID
|
||||
if err := tx.Create(&routes[index]).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := tx.Model(&model.LogicalModel{}).Where("id = ?", item.ID).Updates(map[string]any{"active_revision_id": revision.ID, "updated_at": item.UpdatedAt}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
item.ActiveRevisionID = revision.ID
|
||||
item.RevisionSequence = revision.Version
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteLogicalModelRoute(id string) error {
|
||||
return r.db.Model(&model.LogicalModelRoute{}).Where("id = ?", id).Updates(map[string]any{"enabled": false, "weight": 0, "updated_at": time.Now()}).Error
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestSaveLogicalModelBundleAllocatesMonotonicRevisionSequence(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open("file:logical-model-revision-sequence?mode=memory&cache=shared"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.LogicalModel{}, &model.LogicalModelRevision{}, &model.LogicalModelRoute{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := New(db)
|
||||
|
||||
item := &model.LogicalModel{ID: "LMODEL_1", Code: "demo", Name: "Demo", Capability: "text", Enabled: true, PricePolicy: "unified", BillingMode: "fixed_request", CreatedAt: time.Now(), UpdatedAt: time.Now()}
|
||||
first := &model.LogicalModelRevision{ID: "REVISION_1", LogicalModelID: item.ID, CapabilitySpecJSON: `{"version":1,"capability":"text"}`, DefaultOptionsJSON: `{}`, CreatedAt: time.Now()}
|
||||
if err := repo.SaveLogicalModelBundle(item, first, nil, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var updated model.LogicalModel
|
||||
if err := db.First(&updated, "id = ?", item.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updated.Name = "Demo 2"
|
||||
updated.UpdatedAt = time.Now()
|
||||
second := &model.LogicalModelRevision{ID: "REVISION_2", LogicalModelID: item.ID, CapabilitySpecJSON: `{"version":1,"capability":"text"}`, DefaultOptionsJSON: `{}`, CreatedAt: time.Now()}
|
||||
if err := repo.SaveLogicalModelBundle(&updated, second, nil, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var revisions []model.LogicalModelRevision
|
||||
if err := db.Order("version asc").Find(&revisions).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(revisions) != 2 || revisions[0].Version != 1 || revisions[1].Version != 2 {
|
||||
t.Fatalf("revision versions = %#v, want [1 2]", revisions)
|
||||
}
|
||||
if updated.RevisionSequence != 2 || updated.ActiveRevisionID != "REVISION_2" {
|
||||
t.Fatalf("updated model state = %#v", updated)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package repository
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -48,6 +49,37 @@ func (r *Repository) Dialect() string {
|
||||
return r.db.Dialector.Name()
|
||||
}
|
||||
|
||||
// NextPrefixedID 在数据库事务中递增序列,避免 UUID/父子字符串拼接导致的不可读和不可排序 ID。
|
||||
// prefix 只决定展示前缀,关联关系仍由独立外键维护。
|
||||
func (r *Repository) NextPrefixedID(prefix string) (string, error) {
|
||||
return r.nextPrefixedID(r.db, prefix)
|
||||
}
|
||||
|
||||
func (r *Repository) nextPrefixedID(db *gorm.DB, prefix string) (string, error) {
|
||||
prefix = strings.ToUpper(strings.TrimSpace(prefix))
|
||||
if prefix == "" || len(prefix) > 16 {
|
||||
return "", errors.New("invalid id prefix")
|
||||
}
|
||||
sequence := "id:" + prefix
|
||||
var item model.IDSequence
|
||||
err := db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&model.IDSequence{Name: sequence, UpdatedAt: time.Now()}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&model.IDSequence{}).Where("name = ?", sequence).Updates(map[string]any{
|
||||
"value": gorm.Expr("value + ?", 1),
|
||||
"updated_at": time.Now(),
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.First(&item, "name = ?", sequence).Error
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("%s_%06d", prefix, item.Value), nil
|
||||
}
|
||||
|
||||
func (r *Repository) UserStorageUsage(userID string) (UserStorageUsage, error) {
|
||||
var usage UserStorageUsage
|
||||
query := `
|
||||
|
||||
@@ -504,7 +504,11 @@ func (s *Service) CreateSystemChannel(actor *model.User, req ChannelRequest) (*P
|
||||
if err := s.RequireAdmin(actor); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channel, err := s.channelFromRequest(req, model.ModelChannel{ID: newID(), UserID: actor.ID, Scope: model.ChannelScopeSystem, Enabled: true})
|
||||
channelID, err := s.repo.NextPrefixedID("CHANNEL")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channel, err := s.channelFromRequest(req, model.ModelChannel{ID: channelID, UserID: actor.ID, Scope: model.ChannelScopeSystem, Enabled: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -517,6 +521,7 @@ func (s *Service) CreateSystemChannel(actor *model.User, req ChannelRequest) (*P
|
||||
if err := s.syncInitialChannelModels(&channel, req.Models); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.invalidateRouteCatalog()
|
||||
items, err := s.repo.ChannelModels(channel.ID, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -560,6 +565,7 @@ func (s *Service) UpdateSystemChannel(actor *model.User, id string, req ChannelR
|
||||
if err := s.syncInitialChannelModels(&next, req.Models); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.invalidateRouteCatalog()
|
||||
items, err := s.repo.ChannelModels(next.ID, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -612,6 +618,9 @@ func (s *Service) DeleteSystemChannel(actor *model.User, id string) error {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return BadAuthRequest("系统渠道不存在或已删除")
|
||||
}
|
||||
if err == nil {
|
||||
s.invalidateRouteCatalog()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -180,7 +180,7 @@ func newChannelModelTestService(t *testing.T) (*Service, *gorm.DB) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.ModelChannel{}, &model.ChannelModel{}); err != nil {
|
||||
if err := db.AutoMigrate(&model.ModelChannel{}, &model.ChannelModel{}, &model.IDSequence{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &Service{repo: repository.New(db)}, db
|
||||
|
||||
@@ -116,12 +116,19 @@ func (s *Service) FetchAdminChannelModels(ctx context.Context, actor *model.User
|
||||
continue
|
||||
}
|
||||
// 自动发现不能绕过定价边界;新模型由管理员定价后再手动启用。
|
||||
missing = append(missing, model.ChannelModel{ID: newID(), ChannelID: channelID, ModelKey: name, DisplayName: name, BillingMode: "fixed_request", Enabled: false, PriceVersion: 1})
|
||||
modelID, idErr := s.repo.NextPrefixedID("MODEL")
|
||||
if idErr != nil {
|
||||
return nil, idErr
|
||||
}
|
||||
missing = append(missing, model.ChannelModel{ID: modelID, ChannelID: channelID, ModelKey: name, DisplayName: name, BillingMode: "fixed_request", Enabled: false, PriceVersion: 1})
|
||||
}
|
||||
added, err := s.repo.CreateMissingChannelModels(missing)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if added > 0 {
|
||||
s.invalidateRouteCatalog()
|
||||
}
|
||||
return &AdminChannelModelFetchResult{Models: models, Added: added}, nil
|
||||
}
|
||||
|
||||
@@ -137,7 +144,15 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if capability == "image" || capability == "video" {
|
||||
// 先检查同渠道重复模型,避免无关能力校验或生成无用序列号掩盖真正的冲突。
|
||||
conflict, conflictErr := s.repo.ChannelModelByKeyIncludingDisabled(channelID, modelKey)
|
||||
if conflictErr != nil && !errors.Is(conflictErr, gorm.ErrRecordNotFound) {
|
||||
return nil, conflictErr
|
||||
}
|
||||
if conflict != nil && conflict.ID != strings.TrimSpace(id) {
|
||||
return nil, BadAuthRequest("该渠道已存在模型 " + modelKey + ",请直接编辑已有模型")
|
||||
}
|
||||
if capability == "text" || capability == "image" || capability == "video" {
|
||||
if _, err := NormalizeModelCapabilityConfig(capability, string(protocol), req.CapabilityConfig); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -168,7 +183,11 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
|
||||
if req.InputTokenPriceMicrocredits > maxTokenPriceMicrocredits || req.OutputTokenPriceMicrocredits > maxTokenPriceMicrocredits || req.CachedTokenPriceMicrocredits > maxTokenPriceMicrocredits {
|
||||
return nil, BadAuthRequest("Token 每百万用量价格不能超过 1,000,000 积分")
|
||||
}
|
||||
item := &model.ChannelModel{ID: newID(), ChannelID: channelID, Enabled: true, PriceVersion: 1}
|
||||
modelID, err := s.repo.NextPrefixedID("MODEL")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item := &model.ChannelModel{ID: modelID, ChannelID: channelID, Enabled: true, PriceVersion: 1}
|
||||
if id != "" {
|
||||
item, err = s.repo.ChannelModelByID(channelID, id)
|
||||
if err != nil {
|
||||
@@ -176,13 +195,6 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
|
||||
}
|
||||
item.PriceVersion++
|
||||
}
|
||||
conflict, conflictErr := s.repo.ChannelModelByKeyIncludingDisabled(channelID, modelKey)
|
||||
if conflictErr != nil && !errors.Is(conflictErr, gorm.ErrRecordNotFound) {
|
||||
return nil, conflictErr
|
||||
}
|
||||
if conflict != nil && conflict.ID != item.ID {
|
||||
return nil, BadAuthRequest("该渠道已存在模型 " + modelKey + ",请直接编辑已有模型")
|
||||
}
|
||||
item.ModelKey = modelKey
|
||||
item.DisplayName = strings.TrimSpace(req.DisplayName)
|
||||
if item.DisplayName == "" {
|
||||
@@ -196,7 +208,7 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
|
||||
item.OutputTokenPriceMicrocredits = req.OutputTokenPriceMicrocredits
|
||||
item.CachedTokenPriceMicrocredits = req.CachedTokenPriceMicrocredits
|
||||
item.PriceConfigured = req.PriceConfigured
|
||||
if capability == "image" || capability == "video" {
|
||||
if capability == "text" || capability == "image" || capability == "video" {
|
||||
capabilityConfig, normalizeErr := NormalizeModelCapabilityConfig(capability, string(protocol), req.CapabilityConfig)
|
||||
if normalizeErr != nil {
|
||||
return nil, normalizeErr
|
||||
@@ -216,9 +228,12 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
|
||||
if req.Enabled != nil {
|
||||
item.Enabled = *req.Enabled
|
||||
}
|
||||
// 可用配置不再保存独立能力范围;路由能力会在读取时从当前渠道模型能力实时投影。
|
||||
// 因此修改尺寸、比例或数量时无需拿旧快照做冲突校验,也不会留下第二个事实来源。
|
||||
if err := s.repo.SaveChannelModel(item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.invalidateRouteCatalog()
|
||||
if err := s.syncChannelModelNames(channel); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -241,7 +256,7 @@ func (s *Service) TestAdminChannelModel(ctx context.Context, actor *model.User,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if capability == "image" || capability == "video" {
|
||||
if capability == "text" || capability == "image" || capability == "video" {
|
||||
if _, err := NormalizeModelCapabilityConfig(capability, string(protocol), req.CapabilityConfig); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -411,6 +426,9 @@ func (s *Service) DeleteAdminChannelModel(actor *model.User, channelID string, i
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return BadAuthRequest("渠道模型不存在或已删除")
|
||||
}
|
||||
if err == nil {
|
||||
s.invalidateRouteCatalog()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -437,7 +455,11 @@ func (s *Service) syncInitialChannelModels(channel *model.ModelChannel, names []
|
||||
}
|
||||
continue
|
||||
}
|
||||
item := model.ChannelModel{ID: newID(), ChannelID: channel.ID, ModelKey: name, DisplayName: name, BillingMode: "fixed_request", Enabled: false, PriceVersion: 1}
|
||||
modelID, idErr := s.repo.NextPrefixedID("MODEL")
|
||||
if idErr != nil {
|
||||
return idErr
|
||||
}
|
||||
item := model.ChannelModel{ID: modelID, ChannelID: channel.ID, ModelKey: name, DisplayName: name, BillingMode: "fixed_request", Enabled: false, PriceVersion: 1}
|
||||
if err := s.repo.SaveChannelModel(&item); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -209,6 +209,53 @@ func (c *runtimeCoordinator) recordChannelResult(ctx context.Context, channelID
|
||||
}
|
||||
}
|
||||
|
||||
const routeCatalogVersionKey = "canvas:logical-model-route-catalog:version"
|
||||
|
||||
func (c *runtimeCoordinator) routeCatalogVersion(ctx context.Context) (int64, error) {
|
||||
if c == nil || c.redis == nil {
|
||||
return 0, nil
|
||||
}
|
||||
value, err := c.redis.Get(ctx, routeCatalogVersionKey).Int64()
|
||||
if err == redis.Nil {
|
||||
return 0, nil
|
||||
}
|
||||
return value, err
|
||||
}
|
||||
|
||||
func (c *runtimeCoordinator) bumpRouteCatalogVersion(ctx context.Context) error {
|
||||
if c == nil || c.redis == nil {
|
||||
return nil
|
||||
}
|
||||
return c.redis.Incr(ctx, routeCatalogVersionKey).Err()
|
||||
}
|
||||
|
||||
func routeHealthKey(key string) string { return "canvas:logical-route-health:" + key }
|
||||
|
||||
func (c *runtimeCoordinator) routeBlockedUntil(ctx context.Context, key string) (time.Time, error) {
|
||||
if c == nil || c.redis == nil {
|
||||
return time.Time{}, nil
|
||||
}
|
||||
value, err := c.redis.Get(ctx, routeHealthKey(key)).Int64()
|
||||
if err == redis.Nil {
|
||||
return time.Time{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return time.UnixMilli(value), nil
|
||||
}
|
||||
|
||||
func (c *runtimeCoordinator) blockRoute(ctx context.Context, key string, until time.Time) error {
|
||||
if c == nil || c.redis == nil {
|
||||
return nil
|
||||
}
|
||||
ttl := time.Until(until)
|
||||
if ttl <= 0 {
|
||||
return c.redis.Del(ctx, routeHealthKey(key)).Err()
|
||||
}
|
||||
return c.redis.Set(ctx, routeHealthKey(key), until.UnixMilli(), ttl).Err()
|
||||
}
|
||||
|
||||
func envInt(key string, fallback int) int {
|
||||
value, err := strconv.Atoi(strings.TrimSpace(os.Getenv(key)))
|
||||
if err != nil || value <= 0 {
|
||||
|
||||
@@ -432,6 +432,9 @@ func (s *Service) taskBillingOrder(userID string, task *model.Task, input map[st
|
||||
if !enabled {
|
||||
return nil, nil
|
||||
}
|
||||
if task.LogicalModelID != "" {
|
||||
return s.newLogicalModelBillingOrder(userID, task, input)
|
||||
}
|
||||
config, _ := input["config"].(map[string]any)
|
||||
if config == nil {
|
||||
return nil, nil
|
||||
@@ -452,6 +455,76 @@ func (s *Service) taskBillingOrder(userID string, task *model.Task, input map[st
|
||||
return s.newBillingOrder(userID, task.ID, "task:"+task.ID+":"+newID(), channelID, modelKey, capability, scene, billingQuantity(capability, config["videoSeconds"]), estimateTaskBillingTokens(input, capability))
|
||||
}
|
||||
|
||||
func (s *Service) newLogicalModelBillingOrder(userID string, task *model.Task, input map[string]any) (*model.BillingOrder, error) {
|
||||
logicalModel, err := s.repo.LogicalModel(task.LogicalModelID)
|
||||
if err != nil || !logicalModel.Enabled || logicalModel.ActiveRevisionID != task.LogicalModelRevisionID {
|
||||
return nil, BadAuthRequest("所选模型计费配置已失效,请重新选择")
|
||||
}
|
||||
variant, err := s.repo.PhysicalVariant(task.PhysicalVariantID)
|
||||
if err != nil {
|
||||
return nil, BadAuthRequest("所选模型配置已更新,请重新选择")
|
||||
}
|
||||
channelModel, err := s.repo.ChannelModel(variant.ChannelModelID)
|
||||
if err != nil {
|
||||
return nil, BadAuthRequest("所选模型配置已更新,请重新选择")
|
||||
}
|
||||
config, _ := input["config"].(map[string]any)
|
||||
capability := normalizeCapability(fmt.Sprint(input["mode"]))
|
||||
if capability == "" {
|
||||
capability = capabilityFromTaskType(task.Type)
|
||||
}
|
||||
if logicalModel.PricePolicy == "channel" {
|
||||
order, priceErr := s.newBillingOrder(userID, task.ID, "task:"+task.ID+":"+newID(), channelModel.ChannelID, channelModel.ModelKey, capability, firstNonEmpty(strings.TrimSpace(task.Operation), task.Type), billingQuantity(capability, config["videoSeconds"]), estimateTaskBillingTokens(input, capability))
|
||||
if priceErr != nil {
|
||||
return nil, priceErr
|
||||
}
|
||||
// 用户账单只显示前台模型,供应线路仍保留在内部归属字段中。
|
||||
order.Model = logicalModel.Code
|
||||
return order, nil
|
||||
}
|
||||
if logicalModel.PricePolicy != "unified" {
|
||||
return nil, BadAuthRequest("当前模型价格策略无效")
|
||||
}
|
||||
quantity := int64(1)
|
||||
tokenEstimate := estimateTaskBillingTokens(input, capability)
|
||||
amount := int64(0)
|
||||
switch logicalModel.BillingMode {
|
||||
case "fixed_request":
|
||||
amount = logicalModel.UnitPriceMicrocredits
|
||||
case "per_second":
|
||||
quantity = billingQuantity(capability, config["videoSeconds"])
|
||||
if capability != "video" || quantity <= 0 {
|
||||
return nil, BadAuthRequest("当前模型按时长计费,但请求未提供有效时长")
|
||||
}
|
||||
amount, err = creditAmount(logicalModel.UnitPriceMicrocredits, quantity, 10_000)
|
||||
case "token":
|
||||
pricing := &model.ChannelModel{InputTokenPriceMicrocredits: logicalModel.InputPriceMicrocredits, OutputTokenPriceMicrocredits: logicalModel.OutputPriceMicrocredits, CachedTokenPriceMicrocredits: logicalModel.CachedPriceMicrocredits}
|
||||
amount, err = tokenEstimateAmount(pricing, tokenEstimate, 10_000)
|
||||
quantity = tokenEstimate.InputTokens + tokenEstimate.OutputTokens
|
||||
default:
|
||||
return nil, BadAuthRequest("当前模型计费方式暂不支持")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if amount <= 0 {
|
||||
return nil, BadAuthRequest("当前模型尚未配置有效的用户价格")
|
||||
}
|
||||
revision, err := s.repo.LogicalModelRevision(task.LogicalModelRevisionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &model.BillingOrder{
|
||||
ID: newID(), UserID: userID, IdempotencyKey: "task:" + task.ID + ":" + newID(), TaskID: task.ID,
|
||||
ChannelID: channelModel.ChannelID, ChannelModelID: channelModel.ID, Model: logicalModel.Code, Capability: capability,
|
||||
Scene: truncateRunes(firstNonEmpty(strings.TrimSpace(task.Operation), task.Type), 80), BillingMode: logicalModel.BillingMode, PriceVersion: int64(revision.Version),
|
||||
UnitPriceMicrocredits: logicalModel.UnitPriceMicrocredits, MultiplierBasisPoints: 10_000, Quantity: quantity, AmountMicrocredits: amount,
|
||||
ReservedAmountMicrocredits: amount, InputTokenPriceMicrocredits: logicalModel.InputPriceMicrocredits,
|
||||
OutputTokenPriceMicrocredits: logicalModel.OutputPriceMicrocredits, CachedTokenPriceMicrocredits: logicalModel.CachedPriceMicrocredits,
|
||||
Status: model.BillingStatusReserved,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) ReserveProxyBilling(userID string, channelID string, modelKey string, capability string, scene string, idempotencyKey string, quantity int64) (*model.BillingOrder, error) {
|
||||
return s.ReserveProxyBillingWithBody(userID, channelID, modelKey, capability, scene, idempotencyKey, quantity, nil)
|
||||
}
|
||||
@@ -483,7 +556,7 @@ func (s *Service) ReserveProxyBillingWithBody(userID string, channelID string, m
|
||||
func (s *Service) newBillingOrder(userID string, taskID string, idempotencyKey string, channelID string, modelKey string, capability string, scene string, requestedQuantity int64, tokenEstimate tokenBillingEstimate) (*model.BillingOrder, error) {
|
||||
item, err := s.repo.ChannelModelByKey(channelID, modelKey)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, BadAuthRequest("当前系统渠道模型未配置或已停用")
|
||||
return nil, BadAuthRequest("当前模型暂时不可用,请重新选择")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -491,9 +564,6 @@ func (s *Service) newBillingOrder(userID string, taskID string, idempotencyKey s
|
||||
if !item.PriceConfigured {
|
||||
return nil, BadAuthRequest("当前模型尚未配置用户积分价格")
|
||||
}
|
||||
if item.Protocol == model.ChannelInterfaceVolcengineJiMengVideo && requestedQuantity != 5 && requestedQuantity != 10 {
|
||||
return nil, BadAuthRequest("即梦视频仅支持 5 秒或 10 秒,请调整视频时长")
|
||||
}
|
||||
quantity := int64(1)
|
||||
amount := int64(0)
|
||||
switch item.BillingMode {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,147 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
)
|
||||
|
||||
func TestMatchCapabilityRoutesTextImagesOnlyToDeclaredProfiles(t *testing.T) {
|
||||
plainText := CapabilitySpec{
|
||||
Version: 1,
|
||||
Capability: "text",
|
||||
Inputs: map[string]InputConstraint{"image": {Min: 0, Max: 0}},
|
||||
}
|
||||
visionText := CapabilitySpec{
|
||||
Version: 1,
|
||||
Capability: "text",
|
||||
Inputs: map[string]InputConstraint{"image": {Min: 0, Max: 8}},
|
||||
}
|
||||
intent := ModelRequestIntent{Capability: "text", Inputs: map[string]int{"image": 2}}
|
||||
|
||||
if match := MatchCapability(plainText, intent); match.Matched {
|
||||
t.Fatalf("plain text profile unexpectedly matched image input: %#v", match)
|
||||
}
|
||||
if match := MatchCapability(visionText, intent); !match.Matched {
|
||||
t.Fatalf("vision text profile did not match image input: %#v", match)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchCapabilityAcceptsWildcardOptionValues(t *testing.T) {
|
||||
spec := CapabilitySpec{
|
||||
Version: 1,
|
||||
Capability: "image",
|
||||
Options: map[string]OptionConstraint{"size": {Values: []any{"*"}}},
|
||||
}
|
||||
intent := ModelRequestIntent{Capability: "image", Options: map[string]any{"size": "1024x1024"}}
|
||||
if match := MatchCapability(spec, intent); !match.Matched {
|
||||
t.Fatalf("wildcard option did not match custom value: %#v", match)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateProductSpecWithinRoutesRejectsUnsupportedCapabilityValue(t *testing.T) {
|
||||
routes := []CapabilitySpec{
|
||||
{
|
||||
Version: 1,
|
||||
Capability: "video",
|
||||
Operations: []string{"text_to_video"},
|
||||
Options: map[string]OptionConstraint{
|
||||
"vquality": {Values: []any{"720p"}},
|
||||
},
|
||||
},
|
||||
{
|
||||
Version: 1,
|
||||
Capability: "video",
|
||||
Operations: []string{"image_to_video"},
|
||||
Options: map[string]OptionConstraint{
|
||||
"vquality": {Values: []any{"1080p"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
product := CapabilitySpec{
|
||||
Version: 1,
|
||||
Capability: "video",
|
||||
Operations: []string{"text_to_video", "image_to_video"},
|
||||
Options: map[string]OptionConstraint{
|
||||
"vquality": {Values: []any{"720p", "4k"}},
|
||||
},
|
||||
}
|
||||
|
||||
err := validateProductSpecWithinRoutes(product, routes)
|
||||
if err == nil || !strings.Contains(err.Error(), "vquality") {
|
||||
t.Fatalf("validateProductSpecWithinRoutes() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateProductSpecWithinRoutesPreservesInputRangeCoverage(t *testing.T) {
|
||||
routes := []CapabilitySpec{
|
||||
{Version: 1, Capability: "image", Inputs: map[string]InputConstraint{"image": {Min: 0, Max: 4}}},
|
||||
{Version: 1, Capability: "image", Inputs: map[string]InputConstraint{"image": {Min: 5, Max: 9}}},
|
||||
}
|
||||
covered := CapabilitySpec{Version: 1, Capability: "image", Inputs: map[string]InputConstraint{"image": {Min: 0, Max: 9}}}
|
||||
if err := validateProductSpecWithinRoutes(covered, routes); err != nil {
|
||||
t.Fatalf("covered input range rejected: %v", err)
|
||||
}
|
||||
|
||||
routes[1].Inputs["image"] = InputConstraint{Min: 6, Max: 9}
|
||||
if err := validateProductSpecWithinRoutes(covered, routes); err == nil {
|
||||
t.Fatal("input range with an uncovered count was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogicalModelConfigurationErrorAfterRouteCoverageShrinks(t *testing.T) {
|
||||
product := CapabilitySpec{Version: 1, Capability: "image", Inputs: map[string]InputConstraint{"image": {Min: 0, Max: 9}}}
|
||||
complete := []CapabilitySpec{
|
||||
{Version: 1, Capability: "image", Inputs: map[string]InputConstraint{"image": {Min: 0, Max: 4}}},
|
||||
{Version: 1, Capability: "image", Inputs: map[string]InputConstraint{"image": {Min: 5, Max: 9}}},
|
||||
}
|
||||
if message := logicalModelConfigurationError(product, complete); message != "" {
|
||||
t.Fatalf("complete route coverage reported an error: %s", message)
|
||||
}
|
||||
if message := logicalModelConfigurationError(product, complete[:1]); !strings.Contains(message, "无法完整覆盖") {
|
||||
t.Fatalf("shrunk route coverage error = %q", message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogicalModelAvailabilityErrorRequiresSettlementReadyCoverage(t *testing.T) {
|
||||
product := CapabilitySpec{Version: 1, Capability: "image", Inputs: map[string]InputConstraint{"image": {Min: 0, Max: 9}}}
|
||||
structural := []CapabilitySpec{
|
||||
{Version: 1, Capability: "image", Inputs: map[string]InputConstraint{"image": {Min: 0, Max: 4}}},
|
||||
{Version: 1, Capability: "image", Inputs: map[string]InputConstraint{"image": {Min: 5, Max: 9}}},
|
||||
}
|
||||
|
||||
if message := logicalModelAvailabilityError("channel", product, structural, nil); !strings.Contains(message, "可结算价格") {
|
||||
t.Fatalf("missing settlement route error = %q", message)
|
||||
}
|
||||
if message := logicalModelAvailabilityError("channel", product, structural, structural[:1]); !strings.Contains(message, "部分创作端能力") {
|
||||
t.Fatalf("partial settlement coverage error = %q", message)
|
||||
}
|
||||
if message := logicalModelAvailabilityError("channel", product, structural, structural); message != "" {
|
||||
t.Fatalf("complete settlement coverage error = %q", message)
|
||||
}
|
||||
if message := logicalModelAvailabilityError("unified", product, structural, nil); message != "" {
|
||||
t.Fatalf("unified pricing unexpectedly required channel prices: %q", message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptionConstraintWithinRejectsFinerStepThanRealModel(t *testing.T) {
|
||||
physical := numericRange(6, 18, 6)
|
||||
tooBroad := numericRange(6, 18, 3)
|
||||
if optionConstraintWithin(tooBroad, physical) {
|
||||
t.Fatal("a route step finer than the channel model step was accepted")
|
||||
}
|
||||
if !optionConstraintWithin(numericRange(6, 18, 6), physical) {
|
||||
t.Fatal("the channel model step was rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateVariantWithinChannelModelRequiresExplicitImageCapability(t *testing.T) {
|
||||
channelModel := model.ChannelModel{Capability: "image", CapabilityConfigJSON: ""}
|
||||
spec := CapabilitySpec{Version: 1, Capability: "image"}
|
||||
|
||||
err := validateVariantWithinChannelModel(channelModel, spec)
|
||||
if err == nil || !strings.Contains(err.Error(), "渠道图片模型尚未配置能力参数") {
|
||||
t.Fatalf("validateVariantWithinChannelModel() error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -14,10 +14,23 @@ import (
|
||||
// ModelCapabilityConfig 是模型能力声明,不包含供应商字段名;协议适配器负责把统一参数映射到上游请求。
|
||||
type ModelCapabilityConfig struct {
|
||||
Version int `json:"version"`
|
||||
Text *TextCapabilityConfig `json:"text,omitempty"`
|
||||
Image *ImageCapabilityConfig `json:"image,omitempty"`
|
||||
Video *VideoCapabilityConfig `json:"video,omitempty"`
|
||||
}
|
||||
|
||||
type TextCapabilityConfig struct {
|
||||
References TextReferenceConfig `json:"references"`
|
||||
}
|
||||
|
||||
type TextReferenceConfig struct {
|
||||
PromptMaxChars int `json:"promptMaxChars"`
|
||||
MaxImages int `json:"maxImages"`
|
||||
MaxImageBytes int64 `json:"maxImageBytes"`
|
||||
MaxVideos int `json:"maxVideos"`
|
||||
MaxVideoBytes int64 `json:"maxVideoBytes"`
|
||||
}
|
||||
|
||||
type ImageCapabilityConfig struct {
|
||||
References ImageReferenceConfig `json:"references"`
|
||||
Size ImageSizeConfig `json:"size"`
|
||||
@@ -154,6 +167,8 @@ func defaultImageSizeValues() []string {
|
||||
}
|
||||
|
||||
func DefaultModelCapabilityConfigForModel(protocol string, modelName string) *ModelCapabilityConfig {
|
||||
// 文本模型是否支持视觉输入不能从协议或模型名可靠推断,默认关闭,由管理员按真实上游能力开启。
|
||||
text := &TextCapabilityConfig{References: TextReferenceConfig{PromptMaxChars: 32000}}
|
||||
video := &VideoCapabilityConfig{
|
||||
References: VideoReferenceConfig{PromptMaxChars: 1000, MinImages: 0, MaxImages: 9, MaxImageBytes: 30 * 1024 * 1024, MaxVideos: 0, MaxVideoBytes: 0, MaxVideoDuration: 0, MaxAudios: 0, MaxAudioBytes: 0, MaxAudioDuration: 0},
|
||||
Duration: VideoDurationConfig{Selection: "range", Min: 1, Max: 15, Step: 1, Default: 6},
|
||||
@@ -197,7 +212,7 @@ func DefaultModelCapabilityConfigForModel(protocol string, modelName string) *Mo
|
||||
video.Resolutions = []string{"1080p"}
|
||||
video.DefaultResolution = "1080p"
|
||||
}
|
||||
return &ModelCapabilityConfig{Version: 1, Image: DefaultImageCapabilityConfig(protocol, modelName), Video: video}
|
||||
return &ModelCapabilityConfig{Version: 1, Text: text, Image: DefaultImageCapabilityConfig(protocol, modelName), Video: video}
|
||||
}
|
||||
|
||||
func DecodeModelCapabilityConfig(raw string) (*ModelCapabilityConfig, error) {
|
||||
@@ -212,9 +227,19 @@ func DecodeModelCapabilityConfig(raw string) (*ModelCapabilityConfig, error) {
|
||||
}
|
||||
|
||||
func NormalizeModelCapabilityConfig(capability string, _ string, input *ModelCapabilityConfig) (*ModelCapabilityConfig, error) {
|
||||
if capability != "image" && capability != "video" {
|
||||
if capability != "text" && capability != "image" && capability != "video" {
|
||||
return nil, nil
|
||||
}
|
||||
if capability == "text" {
|
||||
if input == nil || input.Text == nil {
|
||||
return nil, BadAuthRequest("请配置文本模型能力参数")
|
||||
}
|
||||
value := &ModelCapabilityConfig{Version: 1, Text: input.Text}
|
||||
if err := validateTextCapabilityConfig(value.Text); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
if capability == "image" {
|
||||
if input == nil || input.Image == nil {
|
||||
return nil, BadAuthRequest("请配置图片模型能力参数")
|
||||
@@ -235,6 +260,110 @@ func NormalizeModelCapabilityConfig(capability string, _ string, input *ModelCap
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// CapabilitySpecFromModelCapabilityConfig 将渠道模型的真实供应能力投影为路由能力快照。
|
||||
// 这是唯一的转换入口:渠道模型能力参数负责定义事实,variant 只保存兼容路由表的投影,
|
||||
// 不再允许管理员在 variant 上重复维护尺寸、比例、数量等字段。
|
||||
func CapabilitySpecFromModelCapabilityConfig(config *ModelCapabilityConfig, capability string) (CapabilitySpec, error) {
|
||||
spec := CapabilitySpec{Version: 1, Capability: capability, Inputs: map[string]InputConstraint{}, Options: map[string]OptionConstraint{}}
|
||||
// 音频模型当前没有可编辑的渠道能力 JSON,使用空能力规格表示“无额外路由约束”。
|
||||
if capability == "audio" {
|
||||
return spec, nil
|
||||
}
|
||||
if config == nil {
|
||||
return spec, BadAuthRequest("渠道模型尚未配置能力参数")
|
||||
}
|
||||
switch capability {
|
||||
case "text":
|
||||
if config.Text == nil {
|
||||
return spec, BadAuthRequest("渠道文本模型尚未配置能力参数")
|
||||
}
|
||||
addInputConstraint(spec.Inputs, "image", 0, config.Text.References.MaxImages)
|
||||
addInputConstraint(spec.Inputs, "video", 0, config.Text.References.MaxVideos)
|
||||
case "image":
|
||||
if config.Image == nil {
|
||||
return spec, BadAuthRequest("渠道图片模型尚未配置能力参数")
|
||||
}
|
||||
image := config.Image
|
||||
addInputConstraint(spec.Inputs, "image", 0, image.References.MaxImages)
|
||||
if image.References.MaskSupported {
|
||||
addInputConstraint(spec.Inputs, "mask", 0, 1)
|
||||
}
|
||||
if image.Size.Parameter != "none" {
|
||||
if image.Size.AllowCustom {
|
||||
spec.Options["size"] = OptionConstraint{Values: []any{"*"}}
|
||||
} else {
|
||||
spec.Options["size"] = anyValues(image.Size.Values)
|
||||
}
|
||||
}
|
||||
if image.Quality.Supported {
|
||||
spec.Options["quality"] = anyValues(image.Quality.Values)
|
||||
}
|
||||
if image.TransparentBackground.Supported {
|
||||
spec.Options["transparentBackground"] = boolValues(true)
|
||||
} else {
|
||||
spec.Options["transparentBackground"] = boolValues(false)
|
||||
}
|
||||
spec.Options["count"] = numericRange(1, float64(image.MaxOutputs), 1)
|
||||
case "video":
|
||||
if config.Video == nil {
|
||||
return spec, BadAuthRequest("渠道视频模型尚未配置能力参数")
|
||||
}
|
||||
video := config.Video
|
||||
spec.Operations = append([]string(nil), video.Operations...)
|
||||
addInputConstraint(spec.Inputs, "image", video.References.MinImages, video.References.MaxImages)
|
||||
addInputConstraint(spec.Inputs, "video", 0, video.References.MaxVideos)
|
||||
addInputConstraint(spec.Inputs, "audio", 0, video.References.MaxAudios)
|
||||
if video.Duration.Selection == "enum" {
|
||||
values := make([]any, 0, len(video.Duration.Values))
|
||||
for _, value := range video.Duration.Values {
|
||||
values = append(values, value)
|
||||
}
|
||||
spec.Options["videoSeconds"] = OptionConstraint{Values: values}
|
||||
} else {
|
||||
spec.Options["videoSeconds"] = numericRange(float64(video.Duration.Min), float64(video.Duration.Max), float64(video.Duration.Step))
|
||||
}
|
||||
spec.Options["size"] = anyValues(video.Ratios)
|
||||
if len(video.Resolutions) > 0 {
|
||||
spec.Options["vquality"] = anyValues(video.Resolutions)
|
||||
}
|
||||
if video.GenerateAudio.Supported {
|
||||
spec.Options["videoGenerateAudio"] = boolValues(true)
|
||||
} else {
|
||||
spec.Options["videoGenerateAudio"] = boolValues(false)
|
||||
}
|
||||
if video.Watermark.Supported {
|
||||
spec.Options["videoWatermark"] = boolValues(true)
|
||||
} else {
|
||||
spec.Options["videoWatermark"] = boolValues(false)
|
||||
}
|
||||
default:
|
||||
return spec, BadAuthRequest("未知模型能力类型")
|
||||
}
|
||||
return spec, nil
|
||||
}
|
||||
|
||||
func addInputConstraint(inputs map[string]InputConstraint, name string, min int, max int) {
|
||||
if min <= 0 && max <= 0 {
|
||||
return
|
||||
}
|
||||
inputs[name] = InputConstraint{Min: min, Max: max}
|
||||
}
|
||||
|
||||
func validateTextCapabilityConfig(value *TextCapabilityConfig) error {
|
||||
if value.References.PromptMaxChars < 1 || value.References.PromptMaxChars > 1000000 {
|
||||
return BadAuthRequest("提示词最大字符数必须在 1-1000000 之间")
|
||||
}
|
||||
for name, number := range map[string]int{"最大图片引用数": value.References.MaxImages, "最大视频引用数": value.References.MaxVideos} {
|
||||
if number < 0 || number > 100 {
|
||||
return BadAuthRequest(name + "必须在 0-100 之间")
|
||||
}
|
||||
}
|
||||
if value.References.MaxImageBytes < 0 || value.References.MaxVideoBytes < 0 {
|
||||
return BadAuthRequest("引用素材大小限制不能小于 0")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateImageCapabilityConfig(value *ImageCapabilityConfig) error {
|
||||
if value.References.PromptMaxChars < 1 || value.References.PromptMaxChars > 1000000 {
|
||||
return BadAuthRequest("提示词最大字符数必须在 1-1000000 之间")
|
||||
|
||||
@@ -131,6 +131,59 @@ func TestNormalizeVideoCapabilityAllowsOmittedResolution(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapabilitySpecFromModelCapabilityConfigProjectsImageSizeOnce(t *testing.T) {
|
||||
config := &ModelCapabilityConfig{
|
||||
Version: 1,
|
||||
Image: &ImageCapabilityConfig{
|
||||
References: ImageReferenceConfig{MaxImages: 3, MaskSupported: false},
|
||||
Size: ImageSizeConfig{Parameter: "size", Values: []string{"1:1", "16:9"}, AllowCustom: true},
|
||||
MaxOutputs: 4,
|
||||
},
|
||||
}
|
||||
|
||||
spec, err := CapabilitySpecFromModelCapabilityConfig(config, "image")
|
||||
if err != nil {
|
||||
t.Fatalf("CapabilitySpecFromModelCapabilityConfig() error = %v", err)
|
||||
}
|
||||
if got := spec.Options["size"].Values; len(got) != 1 || got[0] != "*" {
|
||||
t.Fatalf("size projection = %#v, want wildcard", got)
|
||||
}
|
||||
if got := spec.Inputs["image"].Max; got != 3 {
|
||||
t.Fatalf("image input max = %d, want 3", got)
|
||||
}
|
||||
if got := spec.Options["count"].Max; got == nil || *got != 4 {
|
||||
t.Fatalf("count max = %v, want 4", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapabilitySpecFromModelCapabilityConfigProjectsCustomImageSizeAsWildcard(t *testing.T) {
|
||||
config := &ModelCapabilityConfig{
|
||||
Version: 1,
|
||||
Image: &ImageCapabilityConfig{
|
||||
Size: ImageSizeConfig{Parameter: "size", Values: []string{"1:1"}, AllowCustom: true},
|
||||
MaxOutputs: 1,
|
||||
},
|
||||
}
|
||||
|
||||
spec, err := CapabilitySpecFromModelCapabilityConfig(config, "image")
|
||||
if err != nil {
|
||||
t.Fatalf("CapabilitySpecFromModelCapabilityConfig() error = %v", err)
|
||||
}
|
||||
if got := spec.Options["size"].Values; len(got) != 1 || got[0] != "*" {
|
||||
t.Fatalf("custom size projection = %#v, want wildcard", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapabilitySpecFromModelCapabilityConfigAllowsAudioWithoutConfig(t *testing.T) {
|
||||
spec, err := CapabilitySpecFromModelCapabilityConfig(nil, "audio")
|
||||
if err != nil {
|
||||
t.Fatalf("audio projection error = %v", err)
|
||||
}
|
||||
if spec.Capability != "audio" || len(spec.Inputs) != 0 || len(spec.Options) != 0 {
|
||||
t.Fatalf("audio projection = %#v", spec)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateVideoTaskRequiresDeclaredMinimumImages(t *testing.T) {
|
||||
profile := DefaultModelCapabilityConfigForModel("newapi-channel-2", "image-required-video").Video
|
||||
profile.References.MinImages = 1
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -32,6 +32,7 @@ type canvasGenerationInput struct {
|
||||
ReferenceImages []providerMedia `json:"referenceImages"`
|
||||
ReferenceVideos []providerMedia `json:"referenceVideos"`
|
||||
ReferenceAudios []providerMedia `json:"referenceAudios"`
|
||||
TextHistory []providerTextMessage `json:"textHistory"`
|
||||
Mask *providerMedia `json:"mask"`
|
||||
Metadata map[string]interface{} `json:"metadata"`
|
||||
ImageCapability *ImageCapabilityConfig `json:"-"`
|
||||
@@ -39,6 +40,11 @@ type canvasGenerationInput struct {
|
||||
VideoCapability *VideoCapabilityConfig `json:"-"`
|
||||
}
|
||||
|
||||
type providerTextMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
type providerConfig struct {
|
||||
ChannelID string `json:"channelId"`
|
||||
APIFormat string `json:"apiFormat"`
|
||||
@@ -98,6 +104,7 @@ type providerHTTPError struct {
|
||||
StatusCode int
|
||||
Status string
|
||||
Body string
|
||||
RetryAfter time.Duration
|
||||
}
|
||||
|
||||
type providerAnalyticsKey struct{}
|
||||
@@ -1039,6 +1046,7 @@ func runChatCompletionsTextTask(ctx context.Context, input canvasGenerationInput
|
||||
if systemPrompt := strings.TrimSpace(input.Config.SystemPrompt); systemPrompt != "" {
|
||||
messages = append(messages, map[string]interface{}{"role": "system", "content": systemPrompt})
|
||||
}
|
||||
messages = append(messages, validatedTextHistory(input.TextHistory)...)
|
||||
userContent, err := textChatContent(input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -1054,13 +1062,14 @@ func runChatCompletionsTextTask(ctx context.Context, input canvasGenerationInput
|
||||
|
||||
func textResponseInput(input canvasGenerationInput) (interface{}, error) {
|
||||
systemPrompt := strings.TrimSpace(input.Config.SystemPrompt)
|
||||
if len(input.ReferenceImages) == 0 && len(input.ReferenceVideos) == 0 {
|
||||
if len(input.TextHistory) == 0 && len(input.ReferenceImages) == 0 && len(input.ReferenceVideos) == 0 {
|
||||
return withSystemPrompt(input.Config, input.Prompt), nil
|
||||
}
|
||||
messages := make([]map[string]interface{}, 0, 2)
|
||||
messages := make([]map[string]interface{}, 0, len(input.TextHistory)+2)
|
||||
if systemPrompt != "" {
|
||||
messages = append(messages, map[string]interface{}{"role": "system", "content": systemPrompt})
|
||||
}
|
||||
messages = append(messages, validatedTextHistory(input.TextHistory)...)
|
||||
content, err := textResponseContent(input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -1069,6 +1078,19 @@ func textResponseInput(input canvasGenerationInput) (interface{}, error) {
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
func validatedTextHistory(history []providerTextMessage) []map[string]interface{} {
|
||||
result := make([]map[string]interface{}, 0, len(history))
|
||||
for _, message := range history {
|
||||
role := strings.ToLower(strings.TrimSpace(message.Role))
|
||||
content := strings.TrimSpace(message.Content)
|
||||
if (role != "user" && role != "assistant") || content == "" {
|
||||
continue
|
||||
}
|
||||
result = append(result, map[string]interface{}{"role": role, "content": content})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func textResponseContent(input canvasGenerationInput) ([]map[string]interface{}, error) {
|
||||
content := []map[string]interface{}{{"type": "input_text", "text": input.Prompt}}
|
||||
for _, image := range input.ReferenceImages {
|
||||
@@ -2851,7 +2873,7 @@ func doBinary(req *http.Request) ([]byte, string, error) {
|
||||
if runtimeService != nil {
|
||||
_ = runtimeService.RecordChannelResult(req.Context(), channelID, resp.StatusCode >= 500)
|
||||
}
|
||||
httpErr := providerHTTPError{StatusCode: resp.StatusCode, Status: resp.Status, Body: string(data)}
|
||||
httpErr := providerHTTPError{StatusCode: resp.StatusCode, Status: resp.Status, Body: string(data), RetryAfter: parseRetryAfter(resp.Header.Get("Retry-After"), time.Now())}
|
||||
recordProviderRequest(req, startedAt, resp.StatusCode, data, httpErr)
|
||||
return nil, "", httpErr
|
||||
}
|
||||
@@ -2862,6 +2884,20 @@ func doBinary(req *http.Request) ([]byte, string, error) {
|
||||
return data, mimeType, nil
|
||||
}
|
||||
|
||||
func parseRetryAfter(value string, now time.Time) time.Duration {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return 0
|
||||
}
|
||||
if seconds, err := strconv.Atoi(value); err == nil && seconds > 0 {
|
||||
return time.Duration(seconds) * time.Second
|
||||
}
|
||||
if at, err := http.ParseTime(value); err == nil && at.After(now) {
|
||||
return at.Sub(now)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func providerPollingDeadline(ctx context.Context) time.Time {
|
||||
if deadline, ok := ctx.Deadline(); ok {
|
||||
return deadline
|
||||
|
||||
@@ -28,6 +28,8 @@ import (
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
|
||||
qiniuAuth "github.com/qiniu/go-sdk/v7/auth"
|
||||
qiniuStorage "github.com/qiniu/go-sdk/v7/storage"
|
||||
cos "github.com/tencentyun/cos-go-sdk-v5"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -747,8 +749,8 @@ func validateActiveOSSSetting(setting ossSettingValue, disabledMessage string, i
|
||||
if !setting.Enabled {
|
||||
return ossSettingValue{}, BadAuthRequest(disabledMessage)
|
||||
}
|
||||
if setting.Provider != aliyunOSSProvider && setting.Provider != tencentCOSProvider {
|
||||
return ossSettingValue{}, BadAuthRequest("仅支持阿里云 OSS 和腾讯云 COS")
|
||||
if setting.Provider != aliyunOSSProvider && setting.Provider != tencentCOSProvider && setting.Provider != qiniuKodoProvider {
|
||||
return ossSettingValue{}, BadAuthRequest("仅支持阿里云 OSS、腾讯云 COS 和七牛云 Kodo")
|
||||
}
|
||||
if setting.Bucket == "" || setting.Endpoint == "" || setting.AccessKeyID == "" || setting.AccessKeySecret == "" {
|
||||
return ossSettingValue{}, BadAuthRequest(incompleteMessage)
|
||||
@@ -782,9 +784,13 @@ func ossObjectKey(setting ossSettingValue, userID string, kind string, fileName
|
||||
}
|
||||
|
||||
func putOSSObject(setting ossSettingValue, objectKey string, mimeType string, size int64, body io.Reader) (string, error) {
|
||||
if normalizeOSSSetting(setting).Provider == tencentCOSProvider {
|
||||
setting = normalizeOSSSetting(setting)
|
||||
if setting.Provider == tencentCOSProvider {
|
||||
return putCOSObject(setting, objectKey, mimeType, size, body)
|
||||
}
|
||||
if setting.Provider == qiniuKodoProvider {
|
||||
return putQiniuObject(setting, objectKey, mimeType, size, body)
|
||||
}
|
||||
return putAliyunOSSObject(setting, objectKey, mimeType, size, body)
|
||||
}
|
||||
|
||||
@@ -828,6 +834,9 @@ func getOSSObjectRange(setting ossSettingValue, objectKey string, rangeHeader st
|
||||
if setting.Provider == tencentCOSProvider {
|
||||
return getCOSObjectRange(setting, objectKey, rangeHeader)
|
||||
}
|
||||
if setting.Provider == qiniuKodoProvider {
|
||||
return getQiniuObjectRange(setting, objectKey, rangeHeader)
|
||||
}
|
||||
return getAliyunOSSObjectRange(setting, objectKey, rangeHeader)
|
||||
}
|
||||
|
||||
@@ -874,6 +883,9 @@ func decimalDigits(value string) bool {
|
||||
|
||||
func signedOSSObjectURL(setting ossSettingValue, objectKey string, expiresAt time.Time) (string, error) {
|
||||
setting = normalizeOSSSetting(setting)
|
||||
if setting.Provider == qiniuKodoProvider {
|
||||
return signedQiniuObjectURL(setting, objectKey, expiresAt)
|
||||
}
|
||||
if setting.CDNBaseURL != "" {
|
||||
return ossCDNObjectURL(setting.CDNBaseURL, objectKey)
|
||||
}
|
||||
@@ -924,6 +936,30 @@ func putCOSObject(setting ossSettingValue, objectKey string, mimeType string, si
|
||||
return strings.Trim(resp.Header.Get("ETag"), `"`), nil
|
||||
}
|
||||
|
||||
func putQiniuObject(setting ossSettingValue, objectKey string, mimeType string, size int64, body io.Reader) (string, error) {
|
||||
if setting.AccessKeyID == "" || setting.AccessKeySecret == "" {
|
||||
return "", errors.New("七牛云 Kodo 访问密钥不可用")
|
||||
}
|
||||
if setting.Bucket == "" || objectKey == "" {
|
||||
return "", errors.New("七牛云 Kodo Bucket 或对象路径为空")
|
||||
}
|
||||
config := qiniuStorage.NewConfig()
|
||||
config.Region = qiniuRegion(setting.Region)
|
||||
config.UpHost = strings.TrimRight(setting.Endpoint, "/")
|
||||
uploader := qiniuStorage.NewFormUploader(config)
|
||||
policy := qiniuStorage.PutPolicy{Scope: setting.Bucket + ":" + strings.TrimLeft(objectKey, "/"), Expires: 3600}
|
||||
token := policy.UploadToken(qiniuAuth.New(setting.AccessKeyID, setting.AccessKeySecret))
|
||||
ret := qiniuStorage.PutRet{}
|
||||
extra := &qiniuStorage.PutExtra{MimeType: mimeType}
|
||||
if size < 0 {
|
||||
size = 0
|
||||
}
|
||||
if err := uploader.Put(context.Background(), &ret, token, strings.TrimLeft(objectKey, "/"), body, size, extra); err != nil {
|
||||
return "", fmt.Errorf("七牛云 Kodo 上传失败:%w", err)
|
||||
}
|
||||
return ret.Hash, nil
|
||||
}
|
||||
|
||||
func getCOSObjectRange(setting ossSettingValue, objectKey string, rangeHeader string) (*ossObjectStream, error) {
|
||||
client, err := newCOSClient(setting, 2*time.Minute)
|
||||
if err != nil {
|
||||
@@ -940,6 +976,31 @@ func getCOSObjectRange(setting ossSettingValue, objectKey string, rangeHeader st
|
||||
return &ossObjectStream{body: resp.Body, statusCode: resp.StatusCode, contentLength: resp.ContentLength, contentRange: resp.Header.Get("Content-Range"), acceptRanges: firstNonEmpty(resp.Header.Get("Accept-Ranges"), "bytes")}, nil
|
||||
}
|
||||
|
||||
func getQiniuObjectRange(setting ossSettingValue, objectKey string, rangeHeader string) (*ossObjectStream, error) {
|
||||
signedURL, err := signedQiniuObjectURL(setting, objectKey, time.Now().Add(directResourceURLTTL))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodGet, signedURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rangeHeader != "" {
|
||||
req.Header.Set("Range", rangeHeader)
|
||||
}
|
||||
ApplyDefaultOutboundHeaders(req)
|
||||
resp, err := OutboundHTTPClient(2 * time.Minute).Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("七牛云 Kodo 读取失败:%w", err)
|
||||
}
|
||||
if (resp.StatusCode < 200 || resp.StatusCode >= 300) && resp.StatusCode != http.StatusRequestedRangeNotSatisfiable {
|
||||
defer resp.Body.Close()
|
||||
detail, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
|
||||
return nil, fmt.Errorf("七牛云 Kodo 读取失败:%s %s", resp.Status, strings.TrimSpace(string(detail)))
|
||||
}
|
||||
return &ossObjectStream{body: resp.Body, statusCode: resp.StatusCode, contentLength: resp.ContentLength, contentRange: resp.Header.Get("Content-Range"), acceptRanges: firstNonEmpty(resp.Header.Get("Accept-Ranges"), "bytes")}, nil
|
||||
}
|
||||
|
||||
func getOSSObjectRangeViaCDN(setting ossSettingValue, objectKey string, rangeHeader string) (*ossObjectStream, error) {
|
||||
signedURL, err := signedOSSObjectURL(setting, objectKey, time.Now().Add(directResourceURLTTL))
|
||||
if err != nil {
|
||||
@@ -988,6 +1049,42 @@ func signedCOSObjectURL(setting ossSettingValue, objectKey string, expiresAt tim
|
||||
return signedURL.String(), nil
|
||||
}
|
||||
|
||||
func signedQiniuObjectURL(setting ossSettingValue, objectKey string, expiresAt time.Time) (string, error) {
|
||||
if setting.AccessKeyID == "" || setting.AccessKeySecret == "" {
|
||||
return "", errors.New("七牛云 Kodo 访问密钥不可用")
|
||||
}
|
||||
if setting.CDNBaseURL == "" {
|
||||
return "", errors.New("七牛云 Kodo 绑定域名为空")
|
||||
}
|
||||
objectKey = strings.TrimLeft(strings.TrimSpace(objectKey), "/")
|
||||
if objectKey == "" {
|
||||
return "", errors.New("七牛云 Kodo 对象路径为空")
|
||||
}
|
||||
deadline := expiresAt.Unix()
|
||||
if deadline <= time.Now().Unix() {
|
||||
return "", errors.New("七牛云 Kodo 签名有效期必须晚于当前时间")
|
||||
}
|
||||
mac := qiniuAuth.New(setting.AccessKeyID, setting.AccessKeySecret)
|
||||
return qiniuStorage.MakePrivateURLv2(mac, strings.TrimRight(setting.CDNBaseURL, "/"), objectKey, deadline), nil
|
||||
}
|
||||
|
||||
func qiniuRegion(region string) *qiniuStorage.Region {
|
||||
switch strings.ToLower(strings.TrimSpace(region)) {
|
||||
case "z1", "cn-north-1":
|
||||
return &qiniuStorage.ZoneHuabei
|
||||
case "z2", "cn-south-1":
|
||||
return &qiniuStorage.ZoneHuanan
|
||||
case "na0", "us-north-1":
|
||||
return &qiniuStorage.ZoneBeimei
|
||||
case "as0", "ap-southeast-1":
|
||||
return &qiniuStorage.ZoneXinjiapo
|
||||
case "cn-east-2", "zhejiang2":
|
||||
return &qiniuStorage.ZoneHuadongZheJiang2
|
||||
default:
|
||||
return &qiniuStorage.ZoneHuadong
|
||||
}
|
||||
}
|
||||
|
||||
func newCOSClient(setting ossSettingValue, timeout time.Duration) (*cos.Client, error) {
|
||||
bucketURL, err := cosBucketBaseURL(setting)
|
||||
if err != nil {
|
||||
|
||||
@@ -14,6 +14,9 @@ import (
|
||||
"time"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
|
||||
qiniuAuth "github.com/qiniu/go-sdk/v7/auth"
|
||||
qiniuStorage "github.com/qiniu/go-sdk/v7/storage"
|
||||
)
|
||||
|
||||
func (s *Service) deleteUserAssetWithResources(userID string, assetID string) error {
|
||||
@@ -288,6 +291,12 @@ func (s *Service) deleteStoredResourceObject(userID string, resource *model.Reso
|
||||
return fmt.Errorf("无法读取腾讯云 COS 配置:%w", err)
|
||||
}
|
||||
return deleteTencentCOSObject(setting, resource.ObjectKey)
|
||||
case qiniuKodoProvider:
|
||||
setting, err := s.ossSettingForResource(userID, resource)
|
||||
if err != nil {
|
||||
return fmt.Errorf("无法读取七牛云 Kodo 配置:%w", err)
|
||||
}
|
||||
return deleteQiniuObject(setting, resource.ObjectKey)
|
||||
default:
|
||||
return fmt.Errorf("资源 %s 使用了不支持的存储类型 %q", resource.ID, resource.Provider)
|
||||
}
|
||||
@@ -367,3 +376,21 @@ func deleteTencentCOSObject(setting ossSettingValue, objectKey string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func deleteQiniuObject(setting ossSettingValue, objectKey string) error {
|
||||
if setting.AccessKeyID == "" || setting.AccessKeySecret == "" {
|
||||
return errors.New("七牛云 Kodo 访问密钥不可用")
|
||||
}
|
||||
if setting.Bucket == "" || strings.TrimSpace(objectKey) == "" {
|
||||
return errors.New("七牛云 Kodo Bucket 或对象路径为空")
|
||||
}
|
||||
mac := qiniuAuth.New(setting.AccessKeyID, setting.AccessKeySecret)
|
||||
manager := qiniuStorage.NewBucketManager(mac, &qiniuStorage.Config{Region: qiniuRegion(setting.Region), UseHTTPS: true})
|
||||
if err := manager.Delete(setting.Bucket, strings.TrimLeft(objectKey, "/")); err != nil {
|
||||
if strings.Contains(strings.ToLower(err.Error()), "no such") || strings.Contains(strings.ToLower(err.Error()), "not found") {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("删除七牛云 Kodo 对象失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const responseInterceptionSettingKey = "response_interception"
|
||||
|
||||
const (
|
||||
maxResponseInterceptionRules = 100
|
||||
maxResponseInterceptionTextRunes = 200
|
||||
maxResponseInterceptionReplaceRunes = 500
|
||||
)
|
||||
|
||||
type ResponseInterceptionRule struct {
|
||||
Contains string `json:"contains"`
|
||||
Replace string `json:"replace"`
|
||||
}
|
||||
|
||||
type ResponseInterceptionSetting struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Rules []ResponseInterceptionRule `json:"rules"`
|
||||
}
|
||||
|
||||
func defaultResponseInterceptionSetting() ResponseInterceptionSetting {
|
||||
return ResponseInterceptionSetting{Rules: []ResponseInterceptionRule{}}
|
||||
}
|
||||
|
||||
func (s *Service) AdminResponseInterceptionSetting(actor *model.User) (*ResponseInterceptionSetting, error) {
|
||||
if err := s.RequireAdmin(actor); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
value, err := s.responseInterceptionSetting()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &value, nil
|
||||
}
|
||||
|
||||
func (s *Service) UpdateResponseInterceptionSetting(actor *model.User, value ResponseInterceptionSetting) (*ResponseInterceptionSetting, error) {
|
||||
if err := s.RequireAdmin(actor); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
value = normalizeResponseInterceptionSetting(value)
|
||||
if err := validateResponseInterceptionSetting(value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
before, err := s.responseInterceptionSetting()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
current, err := s.repo.SystemSetting(responseInterceptionSettingKey)
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
setting := &model.SystemSetting{Key: responseInterceptionSettingKey, ValueJSON: string(encoded), UpdatedBy: actor.ID}
|
||||
if current != nil {
|
||||
setting.CreatedAt = current.CreatedAt
|
||||
}
|
||||
if err := s.repo.SaveSystemSetting(setting); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.appendAdminAudit(actor, "response_interception.update", "system_setting", responseInterceptionSettingKey, "更新模型响应拦截", map[string]any{"before": before, "after": value}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &value, nil
|
||||
}
|
||||
|
||||
// InterceptResponseText 只投影用户可见文案,不修改上游响应或请求明细中的原始内容。
|
||||
func (s *Service) InterceptResponseText(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
setting, readErr := s.responseInterceptionSetting()
|
||||
if readErr != nil || !setting.Enabled {
|
||||
return raw
|
||||
}
|
||||
return interceptResponseMessage(setting, raw)
|
||||
}
|
||||
|
||||
// UserFacingErrorMessage 只投影用户可见错误,不修改上游响应或请求明细中的原始内容。
|
||||
func (s *Service) UserFacingErrorMessage(err error) string {
|
||||
return s.InterceptResponseText(taskFailureMessage(err))
|
||||
}
|
||||
|
||||
func interceptResponseMessage(setting ResponseInterceptionSetting, raw string) string {
|
||||
lower := strings.ToLower(raw)
|
||||
for _, rule := range setting.Rules {
|
||||
if strings.Contains(lower, strings.ToLower(rule.Contains)) {
|
||||
return rule.Replace
|
||||
}
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
func (s *Service) responseInterceptionSetting() (ResponseInterceptionSetting, error) {
|
||||
setting, err := s.repo.SystemSetting(responseInterceptionSettingKey)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return defaultResponseInterceptionSetting(), nil
|
||||
}
|
||||
if err != nil {
|
||||
return ResponseInterceptionSetting{}, err
|
||||
}
|
||||
value := defaultResponseInterceptionSetting()
|
||||
if strings.TrimSpace(setting.ValueJSON) == "" {
|
||||
return value, nil
|
||||
}
|
||||
if err := json.Unmarshal([]byte(setting.ValueJSON), &value); err != nil {
|
||||
return ResponseInterceptionSetting{}, fmt.Errorf("模型响应拦截配置格式错误: %w", err)
|
||||
}
|
||||
value = normalizeResponseInterceptionSetting(value)
|
||||
if err := validateResponseInterceptionSetting(value); err != nil {
|
||||
return ResponseInterceptionSetting{}, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func normalizeResponseInterceptionSetting(value ResponseInterceptionSetting) ResponseInterceptionSetting {
|
||||
if value.Rules == nil {
|
||||
value.Rules = []ResponseInterceptionRule{}
|
||||
}
|
||||
for index := range value.Rules {
|
||||
value.Rules[index].Contains = strings.TrimSpace(value.Rules[index].Contains)
|
||||
value.Rules[index].Replace = strings.TrimSpace(value.Rules[index].Replace)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func validateResponseInterceptionSetting(value ResponseInterceptionSetting) error {
|
||||
if len(value.Rules) > maxResponseInterceptionRules {
|
||||
return fmt.Errorf("模型响应拦截规则不能超过 %d 条", maxResponseInterceptionRules)
|
||||
}
|
||||
for index, rule := range value.Rules {
|
||||
if rule.Contains == "" {
|
||||
return fmt.Errorf("第 %d 条拦截规则的匹配文案不能为空", index+1)
|
||||
}
|
||||
if len([]rune(rule.Contains)) > maxResponseInterceptionTextRunes {
|
||||
return fmt.Errorf("第 %d 条拦截规则的匹配文案不能超过 %d 个字符", index+1, maxResponseInterceptionTextRunes)
|
||||
}
|
||||
if rule.Replace == "" {
|
||||
return fmt.Errorf("第 %d 条拦截规则的替换文案不能为空", index+1)
|
||||
}
|
||||
if len([]rune(rule.Replace)) > maxResponseInterceptionReplaceRunes {
|
||||
return fmt.Errorf("第 %d 条拦截规则的替换文案不能超过 %d 个字符", index+1, maxResponseInterceptionReplaceRunes)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInterceptResponseMessageMatchesCaseInsensitivelyAndStopsAtFirstRule(t *testing.T) {
|
||||
setting := ResponseInterceptionSetting{
|
||||
Enabled: true,
|
||||
Rules: []ResponseInterceptionRule{
|
||||
{Contains: "余额不足", Replace: "网络异常,请重试"},
|
||||
{Contains: "异常", Replace: "第二条"},
|
||||
},
|
||||
}
|
||||
if got := interceptResponseMessage(setting, "上游返回:余额不足"); got != "网络异常,请重试" {
|
||||
t.Fatalf("interceptResponseMessage() = %q", got)
|
||||
}
|
||||
if got := interceptResponseMessage(setting, "request failed: 429"); got != "request failed: 429" {
|
||||
t.Fatalf("unmatched message = %q", got)
|
||||
}
|
||||
if got := interceptResponseMessage(ResponseInterceptionSetting{Enabled: true, Rules: []ResponseInterceptionRule{{Contains: "429", Replace: "网络异常,请重试"}}}, "HTTP 429 Too Many Requests"); got != "网络异常,请重试" {
|
||||
t.Fatalf("case-insensitive match = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateResponseInterceptionSettingRejectsEmptyRuleText(t *testing.T) {
|
||||
for name, value := range map[string]ResponseInterceptionSetting{
|
||||
"contains": {Rules: []ResponseInterceptionRule{{Contains: " ", Replace: "替换"}}},
|
||||
"replace": {Rules: []ResponseInterceptionRule{{Contains: "429", Replace: " "}}},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if err := validateResponseInterceptionSetting(normalizeResponseInterceptionSetting(value)); err == nil {
|
||||
t.Fatal("validateResponseInterceptionSetting() error = nil")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeResponseInterceptionSettingTrimsRules(t *testing.T) {
|
||||
value := normalizeResponseInterceptionSetting(ResponseInterceptionSetting{Rules: []ResponseInterceptionRule{{Contains: " 429 ", Replace: " 网络异常,请重试 "}}})
|
||||
if value.Rules[0].Contains != "429" || value.Rules[0].Replace != "网络异常,请重试" {
|
||||
t.Fatalf("normalized rules = %#v", value.Rules)
|
||||
}
|
||||
if strings.TrimSpace(value.Rules[0].Contains) != value.Rules[0].Contains {
|
||||
t.Fatal("contains was not trimmed")
|
||||
}
|
||||
}
|
||||
@@ -22,20 +22,28 @@ import (
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
repo *repository.Repository
|
||||
dataDir string
|
||||
runtimeCapabilities RuntimeCapabilities
|
||||
cancelMu sync.Mutex
|
||||
registrationMu sync.Mutex
|
||||
emailCodeMu sync.Mutex
|
||||
redeemBatchMu sync.Mutex
|
||||
storageMu sync.Mutex
|
||||
characterTaskMu sync.Mutex
|
||||
activeCancels map[string]context.CancelFunc
|
||||
pendingStorage map[string]int64
|
||||
coordinator *runtimeCoordinator
|
||||
runtimeErr error
|
||||
workerID string
|
||||
repo *repository.Repository
|
||||
dataDir string
|
||||
runtimeCapabilities RuntimeCapabilities
|
||||
cancelMu sync.Mutex
|
||||
registrationMu sync.Mutex
|
||||
emailCodeMu sync.Mutex
|
||||
redeemBatchMu sync.Mutex
|
||||
storageMu sync.Mutex
|
||||
characterTaskMu sync.Mutex
|
||||
activeCancels map[string]context.CancelFunc
|
||||
pendingStorage map[string]int64
|
||||
coordinator *runtimeCoordinator
|
||||
runtimeErr error
|
||||
workerID string
|
||||
routeCatalogMu sync.RWMutex
|
||||
routeCatalogRefreshMu sync.Mutex
|
||||
routeCatalog *routeCatalogSnapshot
|
||||
routeCatalogTTL time.Duration
|
||||
routeCatalogMaxStale time.Duration
|
||||
routeCatalogVersion int64
|
||||
routeHealthMu sync.Mutex
|
||||
routeHealthBlocked map[string]time.Time
|
||||
}
|
||||
|
||||
const taskWorkerConcurrency = 3
|
||||
@@ -51,17 +59,19 @@ type CreateSessionRequest struct {
|
||||
ProjectStyle storyboardProjectStyle `json:"projectStyle"`
|
||||
Characters []storyboardCharacterCard `json:"characters"`
|
||||
Config providerConfig `json:"config"`
|
||||
LogicalModelID string `json:"logicalModelId"`
|
||||
}
|
||||
|
||||
type CreateTaskRequest struct {
|
||||
SessionID string `json:"sessionId"`
|
||||
ProjectID string `json:"projectId"`
|
||||
Type string `json:"type"`
|
||||
Operation string `json:"operation"`
|
||||
Prompt string `json:"prompt"`
|
||||
Provider string `json:"provider"`
|
||||
Model string `json:"model"`
|
||||
Input map[string]any `json:"input"`
|
||||
SessionID string `json:"sessionId"`
|
||||
ProjectID string `json:"projectId"`
|
||||
Type string `json:"type"`
|
||||
Operation string `json:"operation"`
|
||||
Prompt string `json:"prompt"`
|
||||
Provider string `json:"provider"`
|
||||
Model string `json:"model"`
|
||||
LogicalModelID string `json:"logicalModelId"`
|
||||
Input map[string]any `json:"input"`
|
||||
}
|
||||
|
||||
type SessionDetail struct {
|
||||
@@ -196,7 +206,7 @@ func New(repo *repository.Repository, dataDir string) *Service {
|
||||
|
||||
func NewWithRuntimeCapabilities(repo *repository.Repository, dataDir string, capabilities RuntimeCapabilities) *Service {
|
||||
coordinator, err := newRuntimeCoordinator(repo.Dialect())
|
||||
return &Service{repo: repo, dataDir: dataDir, runtimeCapabilities: capabilities, activeCancels: make(map[string]context.CancelFunc), coordinator: coordinator, runtimeErr: err, workerID: newID()}
|
||||
return &Service{repo: repo, dataDir: dataDir, runtimeCapabilities: capabilities, activeCancels: make(map[string]context.CancelFunc), coordinator: coordinator, runtimeErr: err, workerID: newID(), routeCatalogTTL: 30 * time.Second, routeCatalogMaxStale: 5 * time.Minute, routeHealthBlocked: make(map[string]time.Time)}
|
||||
}
|
||||
|
||||
func (s *Service) StartWorker() {
|
||||
@@ -277,7 +287,7 @@ func (s *Service) CreateSession(userID string, req CreateSessionRequest) (*Sessi
|
||||
return nil, err
|
||||
}
|
||||
s.storageMu.Unlock()
|
||||
taskReq := CreateTaskRequest{SessionID: session.ID, ProjectID: req.ProjectID, Type: "agent_storyboard", Operation: "storyboard", Prompt: prompt, Provider: "openai-compatible", Model: req.Config.Model, Input: map[string]any{"references": req.References, "canvasSnapshot": compactedSnapshot, "requirements": req.Requirements, "canvasAssets": req.CanvasAssets, "projectStyle": req.ProjectStyle, "characters": req.Characters, "config": req.Config}}
|
||||
taskReq := CreateTaskRequest{SessionID: session.ID, ProjectID: req.ProjectID, Type: "agent_storyboard", Operation: "storyboard", Prompt: prompt, Provider: "openai-compatible", Model: req.Config.Model, LogicalModelID: req.LogicalModelID, Input: map[string]any{"mode": "text", "references": req.References, "canvasSnapshot": compactedSnapshot, "requirements": req.Requirements, "canvasAssets": req.CanvasAssets, "projectStyle": req.ProjectStyle, "characters": req.Characters, "config": req.Config}}
|
||||
if _, err := s.CreateTask(userID, taskReq); err != nil {
|
||||
s.storageMu.Lock()
|
||||
cleanupErr := s.repo.DeleteSessionDraft(userID, session.ID)
|
||||
@@ -327,6 +337,16 @@ func (s *Service) CreateTask(userID string, req CreateTaskRequest) (*model.Task,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var routed *RoutedModel
|
||||
logicalModelID := strings.TrimSpace(req.LogicalModelID)
|
||||
if logicalModelID != "" {
|
||||
intent := ModelRequestIntentFromTaskInput(normalizedInput, req.Type, req.Operation)
|
||||
routed, err = s.ResolveLogicalModel(logicalModelID, intent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
normalizedInput = applyRoutedProviderSelection(normalizedInput, routed)
|
||||
}
|
||||
if err := s.requireCustomChannelsForTaskInput(normalizedInput); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -352,6 +372,15 @@ func (s *Service) CreateTask(userID string, req CreateTaskRequest) (*model.Task,
|
||||
taskType = "video_image_to_video"
|
||||
}
|
||||
task := model.Task{ID: newID(), UserID: userID, SessionID: req.SessionID, ProjectID: req.ProjectID, Type: taskType, Status: model.TaskStatusQueued, Stage: "等待队列调度", Progress: 5, Prompt: prompt, Operation: req.Operation, Provider: req.Provider, Model: req.Model}
|
||||
if routed != nil {
|
||||
task.LogicalModelID = routed.LogicalModel.ID
|
||||
task.LogicalModelRevisionID = routed.Revision.ID
|
||||
task.RouteID = routed.Route.ID
|
||||
task.PhysicalVariantID = routed.Variant.ID
|
||||
task.RouteRun = 1
|
||||
task.Model = routed.LogicalModel.Code
|
||||
task.Provider = "managed"
|
||||
}
|
||||
if err := s.ensureTaskProjectActive(userID, req.ProjectID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -382,6 +411,49 @@ func (s *Service) CreateTask(userID string, req CreateTaskRequest) (*model.Task,
|
||||
return taskForOutput(task), nil
|
||||
}
|
||||
|
||||
func applyRoutedProviderSelection(input map[string]any, routed *RoutedModel) map[string]any {
|
||||
config, _ := input["config"].(map[string]any)
|
||||
nextConfig := make(map[string]any, len(config)+2)
|
||||
for key, value := range config {
|
||||
switch key {
|
||||
case "channelId", "apiFormat", "interfaceType", "baseUrl", "allowLocalChannel", "apiKey", "secretKey", "headers", "model", "capabilityConfig":
|
||||
continue
|
||||
default:
|
||||
nextConfig[key] = value
|
||||
}
|
||||
}
|
||||
for key, value := range routed.Defaults {
|
||||
canonical := canonicalCapabilityOptionName(key)
|
||||
if existing, exists := nextConfig[canonical]; !exists || existing == nil || strings.TrimSpace(fmt.Sprint(existing)) == "" {
|
||||
nextConfig[canonical] = providerConfigOptionValue(value)
|
||||
}
|
||||
}
|
||||
// 路由匹配和真实请求必须使用同一组参数;逻辑能力参数覆盖空的页面配置,但不携带供应链字段。
|
||||
if options, ok := input["capabilityOptions"].(map[string]any); ok {
|
||||
for key, value := range options {
|
||||
canonical := canonicalCapabilityOptionName(key)
|
||||
if isProviderCapabilityOption(canonical) {
|
||||
nextConfig[canonical] = providerConfigOptionValue(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
nextConfig["channelId"] = routed.ChannelModel.ChannelID
|
||||
nextConfig["model"] = routed.ChannelModel.ModelKey
|
||||
input["config"] = nextConfig
|
||||
return input
|
||||
}
|
||||
|
||||
func providerConfigOptionValue(value any) string {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
return typed
|
||||
case json.Number:
|
||||
return typed.String()
|
||||
default:
|
||||
return fmt.Sprint(value)
|
||||
}
|
||||
}
|
||||
|
||||
// 所有任务输入先收敛为 JSON 对象,确保计费与密钥保护不会因 Go 结构体类型不同而被绕过。
|
||||
func normalizeTaskInput(input map[string]any) (map[string]any, error) {
|
||||
if input == nil {
|
||||
@@ -520,6 +592,11 @@ func (s *Service) RetryTask(userID string, id string) (*model.Task, error) {
|
||||
if task.ProviderCancelStatus == model.ProviderCancelStatusRequested {
|
||||
return nil, BadAuthRequest("上游取消状态仍在确认中,请确认费用结果后再重试")
|
||||
}
|
||||
if task.BillingOrderID != "" {
|
||||
if order, orderErr := s.repo.BillingOrder(task.BillingOrderID); orderErr == nil && order.Status == model.BillingStatusUncertain {
|
||||
return nil, BadAuthRequest("上一次调用费用仍在核对中,处理完成前不能重复提交")
|
||||
}
|
||||
}
|
||||
if isContentModerationFailure(task.Error) {
|
||||
return nil, BadAuthRequest(contentModerationRetryMessage)
|
||||
}
|
||||
@@ -531,6 +608,9 @@ func (s *Service) RetryTask(userID string, id string) (*model.Task, error) {
|
||||
if err := json.Unmarshal([]byte(decryptedInput), &billingInput); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.prepareLogicalTaskRetry(task, billingInput); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.requireCustomChannelsForTaskInput(billingInput); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -545,7 +625,7 @@ func (s *Service) RetryTask(userID string, id string) (*model.Task, error) {
|
||||
if err := s.ensureTaskProjectActive(userID, task.ProjectID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
task, err = s.repo.RetryTaskWithBilling(userID, task.ID, billingOrder, policy.Task.ActiveTaskLimit)
|
||||
task, err = s.repo.RetryTaskWithBilling(userID, task, billingOrder, policy.Task.ActiveTaskLimit)
|
||||
if errors.Is(err, repository.ErrInsufficientCredits) {
|
||||
return nil, BadAuthRequest("积分不足,请先使用兑换码充值")
|
||||
}
|
||||
@@ -811,6 +891,10 @@ func truncateRunes(value string, limit int) string {
|
||||
|
||||
func taskForOutput(task model.Task) *model.Task {
|
||||
task.InputJSON = publicTaskInputJSON(task.InputJSON)
|
||||
// 普通任务接口只暴露前台模型身份;可用配置和供应线路属于管理员内部信息。
|
||||
task.LogicalModelRevisionID = ""
|
||||
task.RouteID = ""
|
||||
task.PhysicalVariantID = ""
|
||||
return &task
|
||||
}
|
||||
|
||||
@@ -940,18 +1024,54 @@ func (s *Service) processClaimedTask(task *model.Task) error {
|
||||
task.Stage = "调用生成模型"
|
||||
task.Progress = 35
|
||||
_ = s.repo.UpdateTaskProgress(task.ID, task.Stage, task.Progress)
|
||||
routeAttempt, err := s.beginTaskRouteAttempt(task)
|
||||
if err != nil {
|
||||
task.Status = model.TaskStatusFailed
|
||||
task.Stage = "路由准备失败"
|
||||
task.Error = s.UserFacingErrorMessage(err)
|
||||
task.CompletedAt = ptr(time.Now())
|
||||
_, _ = s.repo.UpdateTaskTerminalState(task.ID, model.TaskStatusRunning, task.Status, task.Stage, task.Error, *task.CompletedAt)
|
||||
if isRouteDispatchUncertain(err) {
|
||||
_ = s.MarkBillingUncertain(task.BillingOrderID, task.Error)
|
||||
} else {
|
||||
_ = s.RefundBilling(task.BillingOrderID, "路由准备失败,上游请求未发出")
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := s.MarkBillingRunning(task.BillingOrderID); err != nil {
|
||||
task.Status = model.TaskStatusFailed
|
||||
task.Stage = "计费准备失败"
|
||||
task.Error = taskFailureMessage(err)
|
||||
task.Error = s.UserFacingErrorMessage(err)
|
||||
task.CompletedAt = ptr(time.Now())
|
||||
_, _ = s.repo.UpdateTaskTerminalState(task.ID, model.TaskStatusRunning, task.Status, task.Stage, task.Error, *task.CompletedAt)
|
||||
_ = s.RefundBilling(task.BillingOrderID, "计费准备失败,上游请求未发出")
|
||||
return err
|
||||
}
|
||||
result, canvasOps, err := s.processTask(ctx, *task)
|
||||
if stateErr := s.refreshTaskProviderState(task); stateErr != nil {
|
||||
return stateErr
|
||||
var result map[string]interface{}
|
||||
var canvasOps []map[string]interface{}
|
||||
for {
|
||||
if dispatchErr := s.markRouteAttemptDispatching(routeAttempt); dispatchErr != nil {
|
||||
err = dispatchErr
|
||||
break
|
||||
}
|
||||
result, canvasOps, err = s.processTask(ctx, *task)
|
||||
if stateErr := s.refreshTaskProviderState(task); stateErr != nil {
|
||||
return stateErr
|
||||
}
|
||||
s.finishTaskRouteAttempt(routeAttempt, task, err)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
nextAttempt, routeErr := s.nextRouteAttemptAfterFailure(task, routeAttempt, err)
|
||||
if routeErr != nil {
|
||||
_ = s.log(task.UserID, task.ID, "warn", "备用路由不可用,保留原始失败", routeErr.Error())
|
||||
break
|
||||
}
|
||||
if nextAttempt == nil {
|
||||
break
|
||||
}
|
||||
routeAttempt = nextAttempt
|
||||
_ = s.log(task.UserID, task.ID, "warn", "上游未创建任务,切换备用能力路由", nextAttempt.RouteID)
|
||||
}
|
||||
providerSucceeded := err == nil
|
||||
if err == nil {
|
||||
@@ -994,7 +1114,7 @@ func (s *Service) processClaimedTask(task *model.Task) error {
|
||||
}
|
||||
task.Status = model.TaskStatusFailed
|
||||
task.Stage = "任务失败"
|
||||
task.Error = taskFailureMessage(err)
|
||||
task.Error = s.UserFacingErrorMessage(err)
|
||||
task.CompletedAt = ptr(time.Now())
|
||||
_, _ = s.repo.UpdateTaskTerminalState(task.ID, model.TaskStatusRunning, task.Status, task.Stage, task.Error, *task.CompletedAt)
|
||||
if compactErr := s.finalizeTaskTextReplay(task.ID, model.TaskStatusFailed); compactErr != nil {
|
||||
@@ -1039,7 +1159,7 @@ func (s *Service) processClaimedTask(task *model.Task) error {
|
||||
}
|
||||
task.Status = model.TaskStatusFailed
|
||||
task.Stage = "任务结果保存失败"
|
||||
task.Error = taskFailureMessage(err)
|
||||
task.Error = s.UserFacingErrorMessage(err)
|
||||
task.CompletedAt = ptr(time.Now())
|
||||
_, _ = s.repo.UpdateTaskTerminalState(task.ID, model.TaskStatusRunning, task.Status, task.Stage, task.Error, *task.CompletedAt)
|
||||
if compactErr := s.finalizeTaskTextReplay(task.ID, model.TaskStatusFailed); compactErr != nil {
|
||||
|
||||
@@ -25,6 +25,7 @@ const encryptedSettingPrefix = "enc:v1:"
|
||||
const (
|
||||
aliyunOSSProvider = "aliyun"
|
||||
tencentCOSProvider = "tencent"
|
||||
qiniuKodoProvider = "qiniu"
|
||||
)
|
||||
|
||||
type OSSSettingRequest struct {
|
||||
@@ -457,8 +458,8 @@ func ossSettingFromRequest(req OSSSettingRequest, current ossSettingValue) (ossS
|
||||
PublicBaseURL: strings.TrimRight(strings.TrimSpace(req.PublicBaseURL), "/"),
|
||||
PathPrefix: strings.Trim(strings.TrimSpace(req.PathPrefix), "/"),
|
||||
})
|
||||
if next.Provider != aliyunOSSProvider && next.Provider != tencentCOSProvider {
|
||||
return next, BadAuthRequest("仅支持阿里云 OSS 和腾讯云 COS")
|
||||
if next.Provider != aliyunOSSProvider && next.Provider != tencentCOSProvider && next.Provider != qiniuKodoProvider {
|
||||
return next, BadAuthRequest("仅支持阿里云 OSS、腾讯云 COS 和七牛云 Kodo")
|
||||
}
|
||||
current = normalizeOSSSetting(current)
|
||||
// 不同云厂商的密钥不能复用;只有继续使用同一厂商时,留空才表示保留原密钥。
|
||||
@@ -473,6 +474,9 @@ func ossSettingFromRequest(req OSSSettingRequest, current ossSettingValue) (ossS
|
||||
if next.Provider == tencentCOSProvider {
|
||||
return next, BadAuthRequest("请填写腾讯云 COS Region 或 Endpoint")
|
||||
}
|
||||
if next.Provider == qiniuKodoProvider {
|
||||
return next, BadAuthRequest("请填写七牛云 Kodo 上传 Endpoint")
|
||||
}
|
||||
return next, BadAuthRequest("请填写阿里云 OSS Endpoint")
|
||||
}
|
||||
if _, err := ValidateOutboundURL(next.Endpoint); err != nil {
|
||||
@@ -486,11 +490,14 @@ func ossSettingFromRequest(req OSSSettingRequest, current ossSettingValue) (ossS
|
||||
return next, err
|
||||
}
|
||||
}
|
||||
if next.Provider == qiniuKodoProvider && next.CDNBaseURL == "" {
|
||||
return next, BadAuthRequest("请填写七牛云 Kodo 绑定域名")
|
||||
}
|
||||
if next.AccessKeyID == "" {
|
||||
return next, BadAuthRequest("请填写 AccessKey ID")
|
||||
return next, BadAuthRequest("请填写访问密钥 AccessKey")
|
||||
}
|
||||
if next.AccessKeySecret == "" {
|
||||
return next, BadAuthRequest("请填写 AccessKey Secret")
|
||||
return next, BadAuthRequest("请填写访问密钥 SecretKey")
|
||||
}
|
||||
}
|
||||
return next, nil
|
||||
|
||||
Reference in new issue
Block a user