1 parent
09f5ff03cc
commit
55875207c9
19 files changed
+348
-36
No files matched your search
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -29,6 +30,10 @@ type AdminChannelModelFetchResult struct {
|
||||
Added int64 `json:"added"`
|
||||
}
|
||||
|
||||
type AdminChannelModelTestResult struct {
|
||||
DurationMs int64 `json:"durationMs"`
|
||||
}
|
||||
|
||||
func (s *Service) EnsureSystemChannelModels() error {
|
||||
channels, err := s.repo.SystemChannels(true)
|
||||
if err != nil {
|
||||
@@ -107,23 +112,9 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
modelKey := strings.TrimPrefix(strings.TrimSpace(req.ModelKey), "models/")
|
||||
if modelKey == "" {
|
||||
return nil, BadAuthRequest("请填写模型标识")
|
||||
}
|
||||
capability := normalizeCapability(req.Capability)
|
||||
if capability == "" {
|
||||
return nil, BadAuthRequest("请选择模型能力")
|
||||
}
|
||||
protocol := model.ChannelInterfaceType(strings.TrimSpace(req.Protocol))
|
||||
if !validChannelInterfaceType(protocol) {
|
||||
return nil, BadAuthRequest("请选择有效的模型请求协议")
|
||||
}
|
||||
if (protocol == model.ChannelInterfaceVolcengineJiMengImage || protocol == model.ChannelInterfaceVolcengineJiMengVideo) && (strings.TrimSpace(channel.APIKey) == "" || strings.TrimSpace(channel.SecretKey) == "") {
|
||||
return nil, BadAuthRequest("即梦官方协议需要先在渠道中配置 Access Key 和 Secret Key")
|
||||
}
|
||||
if expected := capabilityForProtocol(protocol); expected != "" && expected != capability {
|
||||
return nil, BadAuthRequest("模型能力与请求协议不匹配")
|
||||
modelKey, capability, protocol, err := normalizeChannelModelContract(channel, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
billingMode := strings.TrimSpace(req.BillingMode)
|
||||
if billingMode == "" {
|
||||
@@ -168,6 +159,109 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (s *Service) TestAdminChannelModel(ctx context.Context, actor *model.User, channelID string, req ChannelModelRequest) (*AdminChannelModelTestResult, error) {
|
||||
if err := s.RequireAdmin(actor); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channel, err := s.repo.AdminSystemChannel(channelID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
modelKey, capability, protocol, err := normalizeChannelModelContract(channel, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(channel.BaseURL) == "" || strings.TrimSpace(channel.APIKey) == "" {
|
||||
return nil, BadAuthRequest("请先在渠道中配置 Base URL 和 API Key")
|
||||
}
|
||||
|
||||
prompt := map[string]string{
|
||||
"text": "Reply with OK.",
|
||||
"image": "A simple gray circle on a white background.",
|
||||
"video": "A static gray circle on a white background.",
|
||||
"audio": "Model test.",
|
||||
}[capability]
|
||||
videoSeconds := "6"
|
||||
videoSecondsValue := 6
|
||||
if protocol == model.ChannelInterfaceVolcengineJiMengVideo {
|
||||
videoSeconds = "5"
|
||||
videoSecondsValue = 5
|
||||
}
|
||||
input := canvasGenerationInput{
|
||||
Mode: capability,
|
||||
Prompt: prompt,
|
||||
Config: providerConfig{
|
||||
ChannelID: channel.ID,
|
||||
APIFormat: channel.APIFormat,
|
||||
InterfaceType: string(protocol),
|
||||
BaseURL: channel.BaseURL,
|
||||
APIKey: channel.APIKey,
|
||||
SecretKey: channel.SecretKey,
|
||||
Model: modelKey,
|
||||
Size: map[string]string{"image": "1024x1024", "video": "16:9"}[capability],
|
||||
Quality: "auto",
|
||||
Count: "1",
|
||||
VideoSeconds: videoSeconds,
|
||||
VQuality: "720",
|
||||
VideoGenerateAudio: "false",
|
||||
VideoWatermark: "false",
|
||||
AudioVoice: "alloy",
|
||||
AudioFormat: "mp3",
|
||||
AudioSpeed: "1",
|
||||
},
|
||||
Metadata: map[string]interface{}{},
|
||||
}
|
||||
|
||||
// 测试复用真实生成协议、运行时并发和熔断策略,但不创建用户任务或计费订单。
|
||||
testCtx, cancel := context.WithTimeout(ctx, 10*time.Minute)
|
||||
defer cancel()
|
||||
testCtx = context.WithValue(testCtx, providerAnalyticsKey{}, providerAnalyticsContext{
|
||||
Service: s, UserID: actor.ID, ChannelID: channel.ID, Capability: capability,
|
||||
Operation: "admin_model_test", Model: modelKey, VideoSeconds: videoSecondsValue,
|
||||
})
|
||||
startedAt := time.Now()
|
||||
switch capability {
|
||||
case "text":
|
||||
_, err = runTextTask(testCtx, input)
|
||||
case "image":
|
||||
_, err = runImageTask(testCtx, input)
|
||||
case "video":
|
||||
_, err = runVideoTask(testCtx, input)
|
||||
case "audio":
|
||||
_, err = runAudioTask(testCtx, input)
|
||||
}
|
||||
if err != nil {
|
||||
status := http.StatusBadGateway
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
status = http.StatusGatewayTimeout
|
||||
}
|
||||
return nil, &AuthError{Status: status, Message: "模型测试失败:" + truncateRunes(err.Error(), 1000)}
|
||||
}
|
||||
return &AdminChannelModelTestResult{DurationMs: time.Since(startedAt).Milliseconds()}, nil
|
||||
}
|
||||
|
||||
func normalizeChannelModelContract(channel *model.ModelChannel, req ChannelModelRequest) (string, string, model.ChannelInterfaceType, error) {
|
||||
modelKey := strings.TrimPrefix(strings.TrimSpace(req.ModelKey), "models/")
|
||||
if modelKey == "" {
|
||||
return "", "", "", BadAuthRequest("请填写模型标识")
|
||||
}
|
||||
capability := normalizeCapability(req.Capability)
|
||||
if capability == "" {
|
||||
return "", "", "", BadAuthRequest("请选择模型能力")
|
||||
}
|
||||
protocol := model.ChannelInterfaceType(strings.TrimSpace(req.Protocol))
|
||||
if !validChannelInterfaceType(protocol) {
|
||||
return "", "", "", BadAuthRequest("请选择有效的模型请求协议")
|
||||
}
|
||||
if expected := capabilityForProtocol(protocol); expected != "" && expected != capability {
|
||||
return "", "", "", BadAuthRequest("模型能力与请求协议不匹配")
|
||||
}
|
||||
if (protocol == model.ChannelInterfaceVolcengineJiMengImage || protocol == model.ChannelInterfaceVolcengineJiMengVideo) && (strings.TrimSpace(channel.APIKey) == "" || strings.TrimSpace(channel.SecretKey) == "") {
|
||||
return "", "", "", BadAuthRequest("即梦官方协议需要先在渠道中配置 Access Key 和 Secret Key")
|
||||
}
|
||||
return modelKey, capability, protocol, nil
|
||||
}
|
||||
|
||||
func (s *Service) DeleteAdminChannelModel(actor *model.User, channelID string, id string) error {
|
||||
if err := s.RequireAdmin(actor); err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
)
|
||||
|
||||
func TestNormalizeChannelModelContract(t *testing.T) {
|
||||
channel := &model.ModelChannel{APIKey: "test-key"}
|
||||
modelKey, capability, protocol, err := normalizeChannelModelContract(channel, ChannelModelRequest{
|
||||
ModelKey: "models/gpt-test", Capability: "text", Protocol: string(model.ChannelInterfaceChatCompletion),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("normalizeChannelModelContract() error = %v", err)
|
||||
}
|
||||
if modelKey != "gpt-test" || capability != "text" || protocol != model.ChannelInterfaceChatCompletion {
|
||||
t.Fatalf("contract = %q, %q, %q", modelKey, capability, protocol)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeChannelModelContractRejectsCapabilityMismatch(t *testing.T) {
|
||||
channel := &model.ModelChannel{APIKey: "test-key"}
|
||||
_, _, _, err := normalizeChannelModelContract(channel, ChannelModelRequest{
|
||||
ModelKey: "image-test", Capability: "text", Protocol: string(model.ChannelInterfaceOpenAIImage),
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("normalizeChannelModelContract() should reject a mismatched capability")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeChannelModelContractRequiresJiMengSecret(t *testing.T) {
|
||||
channel := &model.ModelChannel{APIKey: "access-key"}
|
||||
_, _, _, err := normalizeChannelModelContract(channel, ChannelModelRequest{
|
||||
ModelKey: "jimeng-test", Capability: "image", Protocol: string(model.ChannelInterfaceVolcengineJiMengImage),
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("normalizeChannelModelContract() should require JiMeng credentials")
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,10 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxOutboundRedirects = 5
|
||||
const (
|
||||
maxOutboundRedirects = 5
|
||||
DefaultOutboundUserAgent = "InfiniteCanvas/1.0 (+https://github.com/ddcat-ai/open-ai-canvas)"
|
||||
)
|
||||
|
||||
var (
|
||||
outboundTransport = newOutboundTransport(resolveOutboundHost)
|
||||
@@ -97,6 +100,14 @@ func CustomRelayHTTPClient(timeout time.Duration) *http.Client {
|
||||
}
|
||||
}
|
||||
|
||||
// ApplyDefaultOutboundHeaders 为所有服务端出网请求提供可识别的产品标识,
|
||||
// 避免 Go 默认 User-Agent 被部分 WAF 或中转网关拦截。
|
||||
func ApplyDefaultOutboundHeaders(req *http.Request) {
|
||||
if req != nil && strings.TrimSpace(req.Header.Get("User-Agent")) == "" {
|
||||
req.Header.Set("User-Agent", DefaultOutboundUserAgent)
|
||||
}
|
||||
}
|
||||
|
||||
func newOutboundTransport(resolveHost func(context.Context, string) ([]net.IP, error)) *http.Transport {
|
||||
dialer := &net.Dialer{Timeout: 15 * time.Second, KeepAlive: 30 * time.Second}
|
||||
return &http.Transport{
|
||||
|
||||
@@ -8,6 +8,23 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestApplyDefaultOutboundHeaders(t *testing.T) {
|
||||
request, err := http.NewRequest(http.MethodGet, "https://example.com", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ApplyDefaultOutboundHeaders(request)
|
||||
if got := request.Header.Get("User-Agent"); got != DefaultOutboundUserAgent {
|
||||
t.Fatalf("User-Agent = %q, want %q", got, DefaultOutboundUserAgent)
|
||||
}
|
||||
|
||||
request.Header.Set("User-Agent", "custom-agent")
|
||||
ApplyDefaultOutboundHeaders(request)
|
||||
if got := request.Header.Get("User-Agent"); got != "custom-agent" {
|
||||
t.Fatalf("custom User-Agent = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateOutboundURLRejectsPrivateHosts(t *testing.T) {
|
||||
t.Setenv("CANVAS_ALLOW_PRIVATE_UPSTREAMS", "false")
|
||||
t.Setenv("CANVAS_ALLOWED_PRIVATE_UPSTREAM_HOSTS", "")
|
||||
|
||||
@@ -1593,6 +1593,7 @@ func doBinary(req *http.Request) ([]byte, string, error) {
|
||||
recordProviderRequest(req, startedAt, 0, nil, err)
|
||||
return nil, "", err
|
||||
}
|
||||
ApplyDefaultOutboundHeaders(req)
|
||||
client := OutboundHTTPClient(requestTimeout)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
|
||||
@@ -197,6 +197,7 @@ func postJiMengJSON(ctx context.Context, config providerConfig, action string, b
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
ApplyDefaultOutboundHeaders(req)
|
||||
credentials := base.Credentials{
|
||||
AccessKeyID: strings.TrimSpace(config.APIKey),
|
||||
SecretAccessKey: strings.TrimSpace(config.SecretKey),
|
||||
|
||||
Reference in new issue
Block a user