mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 08:06:50 +00:00
feat(monitor): support ollama_cloud in channel monitors and account diagnostics
Increment 5-2a of the ollama_cloud plan (backend half): - M-1: accept provider=ollama_cloud for channel monitors (create/update binding oneof) and request templates (create binding oneof, historical short list intentionally not extended to the CN platforms); add the service-side monitorProviders/probeCapableProviders entries, an OpenAI- compatible chat adapter and merge-mode denylist entry; replace-mode body validation intentionally stays lenient (opencode_go precedent). - C36: route ollama_cloud accounts in TestAccountConnection to protocol- aware probes (adaptive = CC + Anthropic + native Responses; pinned protocols = single endpoint) instead of the Claude tester that appended ?beta=true; default the empty model to the account's first outbound model; share the native Responses probe with opencode_go; resolve the platform-default Anthropic base for pinned-anthropic accounts. - C29: quota-mode monitors read the OllamaCloudUsageService snapshot from account extra (no live fetch) and map windows/balance/plan to MonitorQuotaSnapshot; ineligible accounts (e.g. reverse-proxy base_url) and missing/failed snapshots yield explainable errors with the snapshot fetched_at instead of the generic usage-query error. - C28: verified no change needed - monitorAccountQuotaCapability already allows ollama_cloud via its default branch. - Pin the composite default-model candidate list: ollama_cloud explicitly contributes no static default list (admin_group.go), aligning with gateway_handler.
This commit is contained in:
1 parent
83ad970700
commit
f5deed85e5
12 files changed
+571
-8
No files matched your search
@@ -40,7 +40,7 @@ func NewChannelMonitorHandler(monitorService *service.ChannelMonitorService) *Ch
|
||||
|
||||
type channelMonitorCreateRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go"`
|
||||
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go ollama_cloud"`
|
||||
APIMode string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"`
|
||||
Endpoint string `json:"endpoint" binding:"omitempty,max=500"`
|
||||
APIKey string `json:"api_key" binding:"omitempty,max=2000"`
|
||||
@@ -64,7 +64,7 @@ type channelMonitorCreateRequest struct {
|
||||
|
||||
type channelMonitorUpdateRequest struct {
|
||||
Name *string `json:"name" binding:"omitempty,max=100"`
|
||||
Provider *string `json:"provider" binding:"omitempty,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go"`
|
||||
Provider *string `json:"provider" binding:"omitempty,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go ollama_cloud"`
|
||||
APIMode *string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"`
|
||||
Endpoint *string `json:"endpoint" binding:"omitempty,max=500"`
|
||||
APIKey *string `json:"api_key" binding:"omitempty,max=2000"`
|
||||
|
||||
@@ -25,8 +25,10 @@ func NewChannelMonitorRequestTemplateHandler(templateService *service.ChannelMon
|
||||
// --- DTO ---
|
||||
|
||||
type channelMonitorTemplateCreateRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok"`
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
// Provider 为历史短列表:CN 5 平台缺失属历史债(本批不扩),仅补 ollama_cloud
|
||||
// 与监控/模板的 service 层放行对齐。模板按 provider 与监控匹配(应用时校验一致)。
|
||||
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok ollama_cloud"`
|
||||
APIMode string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"`
|
||||
Description string `json:"description" binding:"max=500"`
|
||||
ExtraHeaders map[string]string `json:"extra_headers"`
|
||||
|
||||
@@ -1614,6 +1614,11 @@ func (a *Account) GetAnthropicProtocolBaseURL() string {
|
||||
return DefaultMiniMaxAnthropicBaseURL
|
||||
case PlatformOpenCodeGo:
|
||||
return a.openCodeDefaultAnthropicBaseURL()
|
||||
case PlatformOllamaCloud:
|
||||
// 与 adaptive 分支(defaultCNProtocolBaseURL)同源:官方 Anthropic
|
||||
// 兼容端点不带 /v1 前缀。缺失时 pinned-anthropic 的 ollama_cloud 账号
|
||||
// 会拿到空 base,转发与连接测试都报「no anthropic protocol base url」。
|
||||
return DefaultOllamaCloudAnthropicBaseURL
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -389,6 +389,10 @@ func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int
|
||||
return s.testOpenCodeGoAccountConnection(c, account, modelID, prompt)
|
||||
}
|
||||
|
||||
if account.IsOllamaCloud() {
|
||||
return s.testOllamaCloudAccountConnection(c, account, modelID, prompt)
|
||||
}
|
||||
|
||||
return s.testClaudeAccountConnection(c, account, modelID)
|
||||
}
|
||||
|
||||
@@ -415,13 +419,16 @@ func (s *AccountTestService) testOpenCodeGoAccountConnection(c *gin.Context, acc
|
||||
case APIProtocolAnthropic:
|
||||
return s.testCNProviderAnthropicConnection(c, account, testModelID)
|
||||
case APIProtocolResponses:
|
||||
return s.testOpenCodeGoResponsesConnection(c, account, testModelID)
|
||||
return s.testNativeResponsesConnection(c, account, testModelID)
|
||||
default:
|
||||
return s.testCNProviderChatCompletionsConnection(c, account, testModelID, prompt)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AccountTestService) testOpenCodeGoResponsesConnection(c *gin.Context, account *Account, testModelID string) error {
|
||||
// testNativeResponsesConnection probes a multi-protocol API-key account's
|
||||
// native Responses endpoint (the same probe the adaptive path uses, including
|
||||
// the stateless body normalization). Shared by OpenCode Go and Ollama Cloud.
|
||||
func (s *AccountTestService) testNativeResponsesConnection(c *gin.Context, account *Account, testModelID string) error {
|
||||
authToken := strings.TrimSpace(account.GetOpenAIProtocolAPIKey())
|
||||
if authToken == "" {
|
||||
return s.sendErrorAndEnd(c, "No API key available")
|
||||
@@ -435,6 +442,43 @@ func (s *AccountTestService) testOpenCodeGoResponsesConnection(c *gin.Context, a
|
||||
return s.testCNProviderAdaptiveResponsesConnection(c, account, testModelID, authToken)
|
||||
}
|
||||
|
||||
// testOllamaCloudAccountConnection probes an Ollama Cloud account's native
|
||||
// endpoints per GetAPIProtocol. Falling through to the generic Claude tester
|
||||
// sent Claude Code payloads to {base}/v1/messages?beta=true, so ollama accounts
|
||||
// always failed the connection test regardless of account health. Adaptive
|
||||
// (the default protocol for ollama_cloud) probes Chat Completions + Anthropic
|
||||
// + native Responses in sequence; a pinned protocol probes that single endpoint.
|
||||
func (s *AccountTestService) testOllamaCloudAccountConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
|
||||
testModelID := strings.TrimSpace(modelID)
|
||||
if testModelID == "" {
|
||||
// 无静态目录:默认探测账号自身的第一个可出站模型(保存期门禁保证
|
||||
// mapping 或 allowed_models 至少其一非空)。
|
||||
testModelID = defaultOllamaCloudTestModel(account)
|
||||
}
|
||||
switch account.GetAPIProtocol() {
|
||||
case APIProtocolAdaptive:
|
||||
// 复用 CN adaptive 三端点探针:base_url 解析、Anthropic Bearer 头与
|
||||
// Responses 无状态归一化均已按 ollama_cloud 适配。
|
||||
return s.testCNProviderAdaptiveConnection(c, account, testModelID, prompt)
|
||||
case APIProtocolAnthropic:
|
||||
return s.testCNProviderAnthropicConnection(c, account, testModelID)
|
||||
case APIProtocolResponses:
|
||||
return s.testNativeResponsesConnection(c, account, testModelID)
|
||||
default:
|
||||
return s.testCNProviderChatCompletionsConnection(c, account, testModelID, prompt)
|
||||
}
|
||||
}
|
||||
|
||||
// defaultOllamaCloudTestModel 返回 ollama_cloud 账号连接测试的默认模型:
|
||||
// model_mapping 目标优先,其次 extra.allowed_models 首项;两者皆空时退回
|
||||
// OpenAI 测试模型(仅出现在未过保存期门禁的账号上,由上游报错暴露)。
|
||||
func defaultOllamaCloudTestModel(account *Account) string {
|
||||
if models := ollamaCloudOutboundModelNames(account); len(models) > 0 {
|
||||
return models[0]
|
||||
}
|
||||
return openai.DefaultTestModel
|
||||
}
|
||||
|
||||
func (s *AccountTestService) testCNProviderChatCompletionsConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
|
||||
testModelID := strings.TrimSpace(modelID)
|
||||
if testModelID == "" {
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// ollamaCloudTestAccount 构造官方默认 base_url(credentials 不带 base_url)的
|
||||
// ollama_cloud 账号,让测试同时钉住「正确回落平台默认端点」这件事。
|
||||
func ollamaCloudTestAccount(id int64, credentials map[string]any) *Account {
|
||||
base := map[string]any{
|
||||
"api_key": "sk-ollama-test",
|
||||
}
|
||||
for key, value := range credentials {
|
||||
base[key] = value
|
||||
}
|
||||
return &Account{
|
||||
ID: id,
|
||||
Name: "ollama-cloud-test",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Concurrency: 1,
|
||||
Credentials: base,
|
||||
Extra: map[string]any{
|
||||
OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// C36 核心验收:adaptive(ollama_cloud 默认协议)账号依次探测 CC → Anthropic →
|
||||
// Responses 三个原生端点,URL 正确、无 ?beta=true,不再落入 Claude 测试路径。
|
||||
func TestAccountTestService_OllamaCloudAdaptiveProbesAllThreeEndpoints(t *testing.T) {
|
||||
account := ollamaCloudTestAccount(501, map[string]any{"api_protocol": APIProtocolAdaptive})
|
||||
svc, upstream := adaptiveCNAccountTestService(
|
||||
account,
|
||||
adaptiveCNChatTestResponse(),
|
||||
adaptiveCNAnthropicTestResponse(),
|
||||
adaptiveCNResponsesTestResponse(),
|
||||
)
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "gpt-oss:120b-cloud", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 3)
|
||||
require.Equal(t, "https://ollama.com/v1/chat/completions", upstream.requests[0].URL.String())
|
||||
require.Equal(t, "https://ollama.com/v1/messages", upstream.requests[1].URL.String())
|
||||
require.Equal(t, "https://ollama.com/v1/responses", upstream.requests[2].URL.String())
|
||||
for i, req := range upstream.requests {
|
||||
require.Empty(t, req.URL.RawQuery, "request %d must not carry the Claude tester ?beta=true suffix", i)
|
||||
}
|
||||
// ollama 官方 host 的 Anthropic 端点强制 Bearer(非 CN 的 x-api-key)。
|
||||
require.Equal(t, "Bearer sk-ollama-test", upstream.requests[1].Header.Get("Authorization"))
|
||||
require.Empty(t, upstream.requests[1].Header.Get("x-api-key"))
|
||||
// Responses 探针按无状态端点归一化:store=false。
|
||||
require.False(t, gjson.GetBytes(upstream.bodies[2], "store").Bool())
|
||||
|
||||
require.Equal(t, 1, strings.Count(recorder.Body.String(), `"type":"test_start"`))
|
||||
require.Equal(t, 1, strings.Count(recorder.Body.String(), `"type":"test_complete"`))
|
||||
require.Contains(t, recorder.Body.String(), "已通过原生 /responses 验证")
|
||||
}
|
||||
|
||||
// 空模型默认取账号 allowed_models 首项(保存期门禁保证非空清单存在)。
|
||||
func TestAccountTestService_OllamaCloudEmptyModelDefaultsToAllowedModels(t *testing.T) {
|
||||
account := ollamaCloudTestAccount(502, map[string]any{"api_protocol": APIProtocolChatCompletions})
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
require.Equal(t, "gpt-oss:120b-cloud", gjson.GetBytes(upstream.lastBody, "model").String())
|
||||
require.Contains(t, recorder.Body.String(), "gpt-oss:120b-cloud")
|
||||
}
|
||||
|
||||
// 钉 chat_completions:单端点探测,不触发 Anthropic/Responses。
|
||||
func TestAccountTestService_OllamaCloudPinnedChatProtocol(t *testing.T) {
|
||||
account := ollamaCloudTestAccount(503, map[string]any{"api_protocol": APIProtocolChatCompletions})
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "gpt-oss:120b-cloud", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
require.Equal(t, "https://ollama.com/v1/chat/completions", upstream.requests[0].URL.String())
|
||||
require.Equal(t, "Bearer sk-ollama-test", upstream.requests[0].Header.Get("Authorization"))
|
||||
require.NotContains(t, upstream.requests[0].URL.Path, "/messages")
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
|
||||
}
|
||||
|
||||
// 钉 anthropic:官方默认 Anthropic base(https://ollama.com)+ /v1/messages,
|
||||
// 无 ?beta=true,Bearer 鉴权。
|
||||
func TestAccountTestService_OllamaCloudPinnedAnthropicProtocol(t *testing.T) {
|
||||
account := ollamaCloudTestAccount(504, map[string]any{"api_protocol": APIProtocolAnthropic})
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNAnthropicTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "", "", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
req := upstream.requests[0]
|
||||
require.Equal(t, "https://ollama.com/v1/messages", req.URL.String())
|
||||
require.Empty(t, req.URL.RawQuery)
|
||||
require.Equal(t, "Bearer sk-ollama-test", req.Header.Get("Authorization"))
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
|
||||
}
|
||||
|
||||
// 钉 responses:单端点 /v1/responses + 无状态归一化(store=false)。
|
||||
func TestAccountTestService_OllamaCloudPinnedResponsesProtocol(t *testing.T) {
|
||||
account := ollamaCloudTestAccount(505, map[string]any{"api_protocol": APIProtocolResponses})
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNResponsesTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "gpt-oss:120b-cloud", "", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
req := upstream.requests[0]
|
||||
require.Equal(t, "https://ollama.com/v1/responses", req.URL.String())
|
||||
require.Equal(t, HTTPUpstreamProfileOpenAI, HTTPUpstreamProfileFromContext(req.Context()))
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool())
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
|
||||
}
|
||||
@@ -296,6 +296,12 @@ func defaultModelsListCandidateIDs(platform string) []string {
|
||||
return xai.DefaultModelIDs()
|
||||
case PlatformOpenCodeGo:
|
||||
return DefaultOpenCodeGoModelIDs()
|
||||
case PlatformOllamaCloud:
|
||||
// ollama_cloud 没有静态默认模型列表:可服务模型完全来自账号侧的
|
||||
// model_mapping / extra.allowed_models(缺失时 IsModelSupported 为
|
||||
// deny-all)。default 分支的 Claude 列表对它只会造成虚假广告;
|
||||
// 显式返回空,与 gateway_handler.defaultModelIDsForPlatform 对齐。
|
||||
return nil
|
||||
case PlatformComposite:
|
||||
return compositeDefaultModelsListCandidateIDs()
|
||||
default:
|
||||
|
||||
@@ -176,6 +176,10 @@ var providerAdapters = map[string]providerAdapter{
|
||||
MonitorProviderZhipu: providerZhipuChatAdapter,
|
||||
MonitorProviderDeepseek: providerDeepseekChatAdapter,
|
||||
MonitorProviderMiniMax: providerMiniMaxChatAdapter,
|
||||
// ollama_cloud:官方 OpenAI 兼容 Chat Completions(/v1/chat/completions),
|
||||
// 与国产 3 家同构;api_mode 仍只支持 chat_completions(responses 探活
|
||||
// 仅 openai,见 validateAPIMode)。
|
||||
MonitorProviderOllamaCloud: providerOllamaCloudChatAdapter,
|
||||
MonitorProviderAnthropic: {
|
||||
buildPath: func(string) string { return providerAnthropicPath },
|
||||
buildBody: func(model, prompt string) ([]byte, error) {
|
||||
@@ -230,6 +234,9 @@ var providerDeepseekChatAdapter = newOpenAICompatibleChatAdapter(providerOpenAIP
|
||||
//nolint:gochecknoglobals // 适配器表是只读静态数据,初始化后不变更。
|
||||
var providerMiniMaxChatAdapter = newOpenAICompatibleChatAdapter(providerOpenAIPath)
|
||||
|
||||
//nolint:gochecknoglobals // 适配器表是只读静态数据,初始化后不变更。
|
||||
var providerOllamaCloudChatAdapter = newOpenAICompatibleChatAdapter(providerOpenAIPath)
|
||||
|
||||
func newOpenAICompatibleChatAdapter(path string) providerAdapter {
|
||||
return providerAdapter{
|
||||
buildPath: func(string) string { return path },
|
||||
@@ -463,6 +470,8 @@ var bodyMergeKeyDenyList = map[string]map[string]bool{
|
||||
MonitorProviderZhipu: {"model": true, "messages": true, "stream": true},
|
||||
MonitorProviderDeepseek: {"model": true, "messages": true, "stream": true},
|
||||
MonitorProviderMiniMax: {"model": true, "messages": true, "stream": true},
|
||||
// ollama_cloud 同为 OpenAI Chat Completions 同构。
|
||||
MonitorProviderOllamaCloud: {"model": true, "messages": true, "stream": true},
|
||||
}
|
||||
|
||||
func checkAPIMode(opts *CheckOptions) string {
|
||||
|
||||
@@ -70,6 +70,9 @@ const (
|
||||
MonitorProviderZhipu = "zhipu"
|
||||
MonitorProviderDeepseek = "deepseek"
|
||||
MonitorProviderMiniMax = "minimax"
|
||||
// MonitorProviderOllamaCloud:官方提供 OpenAI 兼容 /v1/chat/completions,
|
||||
// 探活复用通用 OpenAI 兼容 adapter(与国产 3 家同构)。
|
||||
MonitorProviderOllamaCloud = "ollama_cloud"
|
||||
|
||||
// MonitorCheckMode 检测模式(channel_monitors.check_mode)。
|
||||
// probe - LLM 探活(默认,原有行为)
|
||||
@@ -152,7 +155,7 @@ var (
|
||||
"CHANNEL_MONITOR_NOT_FOUND", "channel monitor not found",
|
||||
)
|
||||
ErrChannelMonitorInvalidProvider = infraerrors.BadRequest(
|
||||
"CHANNEL_MONITOR_INVALID_PROVIDER", "provider must be one of openai/anthropic/gemini/grok/antigravity/kimi/zhipu/deepseek/minimax",
|
||||
"CHANNEL_MONITOR_INVALID_PROVIDER", "provider must be one of openai/anthropic/gemini/grok/antigravity/kimi/zhipu/deepseek/minimax/ollama_cloud",
|
||||
)
|
||||
ErrChannelMonitorInvalidCheckMode = infraerrors.BadRequest(
|
||||
"CHANNEL_MONITOR_INVALID_CHECK_MODE", "check_mode must be one of probe/quota/quota_probe; antigravity only supports quota",
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// --- provider 放行(M-1 的 service 层一半) ---
|
||||
|
||||
func TestOllamaCloudMonitorProviderAllowlists(t *testing.T) {
|
||||
require.NoError(t, validateProvider(MonitorProviderOllamaCloud))
|
||||
require.NoError(t, validateAPIMode(MonitorProviderOllamaCloud, ""))
|
||||
require.NoError(t, validateAPIMode(MonitorProviderOllamaCloud, MonitorAPIModeChatCompletions))
|
||||
// responses 探活仍仅 openai(与所有非 openai provider 一致)。
|
||||
require.ErrorIs(t, validateAPIMode(MonitorProviderOllamaCloud, MonitorAPIModeResponses), ErrChannelMonitorInvalidAPIMode)
|
||||
|
||||
// ollama_cloud 官方有 OpenAI 兼容 Chat Completions → 三种模式全部放行
|
||||
//(对比 antigravity 只允许 quota)。
|
||||
require.True(t, providerSupportsProbe(MonitorProviderOllamaCloud))
|
||||
require.NoError(t, validateCheckMode(MonitorProviderOllamaCloud, MonitorCheckModeProbe))
|
||||
require.NoError(t, validateCheckMode(MonitorProviderOllamaCloud, MonitorCheckModeQuota))
|
||||
require.NoError(t, validateCheckMode(MonitorProviderOllamaCloud, MonitorCheckModeQuotaProbe))
|
||||
}
|
||||
|
||||
// 行为钉:opencode_go 在 handler binding 里放行、但 service 层 monitorProviders
|
||||
// 没有(upstream 有单独修复,本分支尚未合入)——钉住现状,防止被误认为本批回归。
|
||||
func TestOpenCodeGoMonitorProviderStillMissingFromServiceAllowlist(t *testing.T) {
|
||||
require.ErrorIs(t, validateProvider("opencode_go"), ErrChannelMonitorInvalidProvider)
|
||||
}
|
||||
|
||||
// --- 探活 adapter ---
|
||||
|
||||
func TestOllamaCloudMonitorAdapterProbesOpenAIChatCompletions(t *testing.T) {
|
||||
h := &openAICaptureHandler{}
|
||||
endpoint := setupFakeOpenAI(t, h)
|
||||
|
||||
res := runCheckForModel(context.Background(), MonitorProviderOllamaCloud, endpoint+"/v1", "sk-ollama", "gpt-oss:120b-cloud", nil)
|
||||
|
||||
require.Equal(t, MonitorStatusOperational, res.Status)
|
||||
require.Equal(t, providerOpenAIPath, h.lastPath)
|
||||
require.Equal(t, "gpt-oss:120b-cloud", h.lastBody["model"])
|
||||
require.Equal(t, "Bearer sk-ollama", h.lastHeaders.Get("Authorization"))
|
||||
}
|
||||
|
||||
func TestOllamaCloudMonitorMergeDenyListProtectsChallenge(t *testing.T) {
|
||||
adapter, apiMode, ok := providerAdapterFor(MonitorProviderOllamaCloud, "")
|
||||
require.True(t, ok)
|
||||
require.Equal(t, MonitorAPIModeChatCompletions, apiMode)
|
||||
|
||||
body, err := buildRequestBody(adapter, MonitorProviderOllamaCloud, apiMode, "gpt-oss:120b-cloud", "2+2=?", &CheckOptions{
|
||||
BodyOverrideMode: MonitorBodyOverrideModeMerge,
|
||||
BodyOverride: map[string]any{"model": "evil", "temperature": 0.5},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
var parsed map[string]any
|
||||
require.NoError(t, json.Unmarshal(body, &parsed))
|
||||
require.Equal(t, "gpt-oss:120b-cloud", parsed["model"], "model 命中黑名单不得被覆盖")
|
||||
require.InDelta(t, 0.5, parsed["temperature"], 0.0001, "非黑名单 key 应正常合并")
|
||||
}
|
||||
|
||||
// --- quota 取数(C29) ---
|
||||
|
||||
func ollamaCloudQuotaTestAccount(id int64, extra map[string]any) *Account {
|
||||
return &Account{
|
||||
ID: id,
|
||||
Name: "ollama-quota-test",
|
||||
Platform: domain.PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-ollama",
|
||||
"base_url": "https://ollama.com/v1",
|
||||
},
|
||||
Extra: extra,
|
||||
}
|
||||
}
|
||||
|
||||
func ollamaCloudUsageSnapshotExtra(status string, fetchedAt time.Time, data *OllamaCloudUsageData, lastError string) map[string]any {
|
||||
snapshot := map[string]any{
|
||||
"status": status,
|
||||
"last_attempt_at": fetchedAt,
|
||||
"next_refresh_at": fetchedAt,
|
||||
"fetched_at": fetchedAt,
|
||||
}
|
||||
if data != nil {
|
||||
snapshot["data"] = data
|
||||
}
|
||||
if lastError != "" {
|
||||
snapshot["last_error"] = lastError
|
||||
}
|
||||
return map[string]any{
|
||||
OllamaCloudUsageSnapshotExtraKey: snapshot,
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaFetcher_OllamaCloudOkSnapshotMapsTiersAndBalance(t *testing.T) {
|
||||
fetcher, usage, cnQuota, cnBalance, accounts := newQuotaFetcherTestSetup(t)
|
||||
fetchedAt := time.Now().Add(-2 * time.Hour).UTC().Truncate(time.Second)
|
||||
accounts.accounts[31] = ollamaCloudQuotaTestAccount(31, ollamaCloudUsageSnapshotExtra(
|
||||
OllamaCloudUsageStatusOK, fetchedAt,
|
||||
&OllamaCloudUsageData{
|
||||
Plan: "pro",
|
||||
FiveHour: &OllamaCloudUsageWindow{UsedPercent: 42.5},
|
||||
SevenDay: &OllamaCloudUsageWindow{UsedPercent: 10},
|
||||
Balance: "$9.50",
|
||||
},
|
||||
"",
|
||||
))
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 31)
|
||||
|
||||
require.True(t, snapshot.Success)
|
||||
require.Equal(t, "ollama_quota", snapshot.Source)
|
||||
require.Equal(t, "pro", snapshot.PlanLevel)
|
||||
require.False(t, snapshot.CredentialInvalid)
|
||||
require.Empty(t, snapshot.Error)
|
||||
// 快照是被动抓取的历史值:FetchedAt 沿用真实抓取时间。
|
||||
require.True(t, fetchedAt.Equal(snapshot.FetchedAt))
|
||||
|
||||
require.Len(t, snapshot.Tiers, 2)
|
||||
require.Equal(t, "5h", snapshot.Tiers[0].Window)
|
||||
require.InDelta(t, 42.5, snapshot.Tiers[0].UsedPercent, 0.001)
|
||||
require.Equal(t, "7d", snapshot.Tiers[1].Window)
|
||||
require.InDelta(t, 10, snapshot.Tiers[1].UsedPercent, 0.001)
|
||||
|
||||
require.NotNil(t, snapshot.Balance)
|
||||
require.InDelta(t, 9.5, *snapshot.Balance, 0.001)
|
||||
require.Equal(t, "USD", snapshot.Currency)
|
||||
|
||||
require.Equal(t, 0, usage.getCalls(), "ollama 走快照读取,不得打海外 usage 服务")
|
||||
require.Equal(t, 0, cnQuota.calls)
|
||||
require.Equal(t, 0, cnBalance.calls)
|
||||
require.Equal(t, MonitorStatusOperational, deriveQuotaCheckResult(snapshot, "quota", time.Now()).Status)
|
||||
}
|
||||
|
||||
// credits 类账号:只有余额没有窗口 → only-balance 降级(余额文本可解析时透出)。
|
||||
func TestQuotaFetcher_OllamaCloudBalanceOnlySnapshot(t *testing.T) {
|
||||
fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
accounts.accounts[32] = ollamaCloudQuotaTestAccount(32, ollamaCloudUsageSnapshotExtra(
|
||||
OllamaCloudUsageStatusOK, time.Now(),
|
||||
&OllamaCloudUsageData{Balance: "USD$12"},
|
||||
"",
|
||||
))
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 32)
|
||||
|
||||
require.True(t, snapshot.Success)
|
||||
require.Empty(t, snapshot.Tiers)
|
||||
require.NotNil(t, snapshot.Balance)
|
||||
require.InDelta(t, 12, *snapshot.Balance, 0.001)
|
||||
}
|
||||
|
||||
// 无法解析的余额文本跳过(余额仅展示,不做停调判定)。
|
||||
func TestQuotaFetcher_OllamaCloudUnparsableBalanceSkipped(t *testing.T) {
|
||||
_, ok := parseOllamaCloudBalanceUSD("")
|
||||
require.False(t, ok)
|
||||
_, ok = parseOllamaCloudBalanceUSD("$9.50 / $20.00")
|
||||
require.False(t, ok)
|
||||
|
||||
value, ok := parseOllamaCloudBalanceUSD("USD$1,234.50")
|
||||
require.True(t, ok)
|
||||
require.InDelta(t, 1234.5, value, 0.001)
|
||||
}
|
||||
|
||||
// status!=ok(unauthorized/failed)→ 错误快照,带 last_error 与 fetched_at;
|
||||
// unauthorized 是抓取通道(settings 页会话)过期,不判凭据失效 → 推导 error 而非 failed。
|
||||
func TestQuotaFetcher_OllamaCloudFailedSnapshotsYieldErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status string
|
||||
wantSub string
|
||||
}{
|
||||
{name: "unauthorized session", status: OllamaCloudUsageStatusUnauthorized, wantSub: "session expired"},
|
||||
{name: "scrape failed", status: OllamaCloudUsageStatusFailed, wantSub: "usage page unreachable"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
fetchedAt := time.Now().Add(-3 * time.Hour).UTC()
|
||||
accounts.accounts[33] = ollamaCloudQuotaTestAccount(33, ollamaCloudUsageSnapshotExtra(
|
||||
tc.status, fetchedAt, nil, tc.wantSub,
|
||||
))
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 33)
|
||||
|
||||
require.False(t, snapshot.Success)
|
||||
require.False(t, snapshot.CredentialInvalid)
|
||||
require.Contains(t, snapshot.Error, tc.wantSub)
|
||||
require.Contains(t, snapshot.Error, "fetched at")
|
||||
require.Contains(t, snapshot.Error, fetchedAt.Format("2006-01-02"))
|
||||
require.Equal(t, MonitorStatusError, deriveQuotaCheckResult(snapshot, "quota", time.Now()).Status)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// eligible=false(host 门禁:反代域名)→ 带原因码的可解释错误,不是笼统报错。
|
||||
func TestQuotaFetcher_OllamaCloudIneligibleBaseURLYieldsExplainableError(t *testing.T) {
|
||||
fetcher, usage, _, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
account := ollamaCloudQuotaTestAccount(34, nil)
|
||||
account.Credentials["base_url"] = "https://proxy.example.com/v1"
|
||||
accounts.accounts[34] = account
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 34)
|
||||
|
||||
require.False(t, snapshot.Success)
|
||||
require.Contains(t, snapshot.Error, "unsupported_base_url")
|
||||
require.Equal(t, 0, usage.getCalls())
|
||||
}
|
||||
|
||||
// 尚无快照(未配置会话或还没有请求活动)→ 可解释错误。
|
||||
func TestQuotaFetcher_OllamaCloudNoSnapshotYieldsExplainableError(t *testing.T) {
|
||||
fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
accounts.accounts[35] = ollamaCloudQuotaTestAccount(35, nil)
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 35)
|
||||
|
||||
require.False(t, snapshot.Success)
|
||||
require.Contains(t, snapshot.Error, "no ollama cloud usage snapshot yet")
|
||||
}
|
||||
|
||||
// 回归:opencode_go 仍走 CN quota 路由,kimi coding 仍走 CN quota(kimi 已有
|
||||
// 独立用例,这里钉 opencode_go 与 ollama 互不串线)。
|
||||
func TestQuotaFetcher_OpenCodeGoStillRoutesToCNQuota(t *testing.T) {
|
||||
fetcher, usage, cnQuota, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
accounts.accounts[36] = &Account{ID: 36, Platform: domain.PlatformOpenCodeGo, Type: AccountTypeAPIKey}
|
||||
cnQuota.result = &CNProviderQuotaProbeResult{Success: true}
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 36)
|
||||
|
||||
require.True(t, snapshot.Success)
|
||||
require.Equal(t, "cn_quota", snapshot.Source)
|
||||
require.Equal(t, 1, cnQuota.calls)
|
||||
require.Equal(t, 0, usage.getCalls())
|
||||
}
|
||||
@@ -23,6 +23,8 @@ import (
|
||||
// - 国产 coding plan(kimi/zhipu/deepseek)→ CNProviderQuotaService.QueryUsageForAccount
|
||||
// - 国产 payg(kimi/deepseek)→ CNProviderBalanceService.QueryBalanceForAccount
|
||||
// (zhipu payg 无公开余额端点,探测会返回该错误,原样透出)
|
||||
// - ollama_cloud → 账号 extra 里的官方用量快照(OllamaCloudUsageService 随请求
|
||||
// 活动被动维护,此处只读取、不实时探测;数据可能陈旧,FetchedAt 如实透出)
|
||||
// 数据源统一接受已加载的 *Account:fetchUncached 路由前 GetByID 一次并传下去,
|
||||
// 下游服务不再各自重载(每次 GetByID 含 proxies/groups 联查)。
|
||||
//
|
||||
@@ -223,6 +225,8 @@ func (f *ChannelMonitorQuotaFetcher) fetchUncached(ctx context.Context, accountI
|
||||
return f.fetchCNBalance(ctx, account, now)
|
||||
case domain.PlatformOpenCodeGo:
|
||||
return f.fetchCNQuota(ctx, account, now)
|
||||
case domain.PlatformOllamaCloud:
|
||||
return f.fetchOllamaCloudQuota(account, now)
|
||||
default:
|
||||
return f.fetchUsage(ctx, account, now)
|
||||
}
|
||||
@@ -455,6 +459,118 @@ func (f *ChannelMonitorQuotaFetcher) fetchCNBalance(ctx context.Context, account
|
||||
return snapshot
|
||||
}
|
||||
|
||||
// fetchOllamaCloudQuota ollama_cloud:读取 OllamaCloudUsageService 维护在账号
|
||||
// extra 里的官方用量快照(请求活动驱动的被动抓取,此处不做实时探测),映射为
|
||||
// 配额快照;FetchedAt 沿用快照真实抓取时间——静默账号的数据会陈旧,时间戳
|
||||
// 如实透出,不伪装成刚刚抓取。eligible=false(如 base_url 为反代域名)或
|
||||
// 快照缺失/失败时返回带可解释原因的错误快照,而不是笼统的「不支持用量查询」。
|
||||
func (f *ChannelMonitorQuotaFetcher) fetchOllamaCloudQuota(account *Account, now time.Time) *domain.MonitorQuotaSnapshot {
|
||||
if reason := ollamaCloudUsageEligibilityReason(account); reason != "" {
|
||||
return quotaErrorSnapshot("ollama_quota", "ollama cloud usage unavailable: "+ollamaCloudUsageReasonHint(reason), now)
|
||||
}
|
||||
snapshot := decodeOllamaCloudUsageSnapshot(account.Extra)
|
||||
if snapshot == nil {
|
||||
return quotaErrorSnapshot("ollama_quota",
|
||||
"no ollama cloud usage snapshot yet; snapshots are captured from the official ollama.com usage page on request activity", now)
|
||||
}
|
||||
fetchedAt := now
|
||||
if snapshot.FetchedAt != nil {
|
||||
fetchedAt = *snapshot.FetchedAt
|
||||
}
|
||||
if snapshot.Status != OllamaCloudUsageStatusOK {
|
||||
return &domain.MonitorQuotaSnapshot{
|
||||
Source: "ollama_quota",
|
||||
// 401 是 settings 页会话过期(抓取通道凭据),不是账号 API key 失效,
|
||||
// 不置 CredentialInvalid——渠道本身可能仍然健康。
|
||||
Success: false,
|
||||
Error: truncateMessage(sanitizeErrorMessage(fmt.Sprintf(
|
||||
"ollama cloud usage snapshot status %s (fetched at %s): %s",
|
||||
snapshot.Status, formatOllamaCloudFetchedAt(snapshot.FetchedAt),
|
||||
firstNonEmpty(snapshot.LastError, "unknown error")))),
|
||||
FetchedAt: now,
|
||||
}
|
||||
}
|
||||
if snapshot.Data == nil {
|
||||
return quotaErrorSnapshot("ollama_quota",
|
||||
fmt.Sprintf("ollama cloud usage snapshot has no data (fetched at %s)", formatOllamaCloudFetchedAt(snapshot.FetchedAt)), now)
|
||||
}
|
||||
out := &domain.MonitorQuotaSnapshot{
|
||||
Source: "ollama_quota",
|
||||
Success: true,
|
||||
PlanLevel: snapshot.Data.Plan,
|
||||
FetchedAt: fetchedAt,
|
||||
}
|
||||
out.Tiers = ollamaCloudQuotaTiers(snapshot.Data)
|
||||
if balance, ok := parseOllamaCloudBalanceUSD(snapshot.Data.Balance); ok {
|
||||
out.Balance = &balance
|
||||
out.Currency = "USD"
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ollamaCloudQuotaTiers 把官方用量窗口归一为 tier 列表(窗口缺失时跳过)。
|
||||
func ollamaCloudQuotaTiers(data *OllamaCloudUsageData) []domain.MonitorQuotaTier {
|
||||
if data == nil {
|
||||
return nil
|
||||
}
|
||||
tiers := make([]domain.MonitorQuotaTier, 0, 2)
|
||||
appendOllamaCloudQuotaTier(&tiers, "5h", data.FiveHour)
|
||||
appendOllamaCloudQuotaTier(&tiers, "7d", data.SevenDay)
|
||||
if len(tiers) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tiers
|
||||
}
|
||||
|
||||
func appendOllamaCloudQuotaTier(tiers *[]domain.MonitorQuotaTier, window string, w *OllamaCloudUsageWindow) {
|
||||
if w == nil {
|
||||
return
|
||||
}
|
||||
tier := domain.MonitorQuotaTier{Window: window, UsedPercent: w.UsedPercent}
|
||||
if w.ResetAt != nil {
|
||||
tier.ResetAt = w.ResetAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
*tiers = append(*tiers, tier)
|
||||
}
|
||||
|
||||
// parseOllamaCloudBalanceUSD 把官方页面抓到的余额文本(如 "$9.50" / "USD$9.50")
|
||||
// 解析为美元数值;解析失败返回 false(余额仅作展示,无月度信用总额可用于
|
||||
// 派生百分比,故 credits 账号只透出余额,不参与 used_percent 告警)。
|
||||
func parseOllamaCloudBalanceUSD(raw string) (float64, bool) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw = strings.TrimPrefix(raw, "USD")
|
||||
raw = strings.TrimPrefix(raw, "$")
|
||||
raw = strings.ReplaceAll(strings.TrimSpace(raw), ",", "")
|
||||
if raw == "" {
|
||||
return 0, false
|
||||
}
|
||||
value, err := strconv.ParseFloat(raw, 64)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
return value, true
|
||||
}
|
||||
|
||||
// ollamaCloudUsageReasonHint 把 EligibleReason 原因码翻译成运维可读的提示
|
||||
// (原因码语义见 OllamaCloudUsageState.EligibleReason)。
|
||||
func ollamaCloudUsageReasonHint(reason string) string {
|
||||
switch reason {
|
||||
case ollamaCloudUsageIneligibleBaseURL:
|
||||
return "unsupported_base_url (base_url is not the official ollama.com host; usage snapshots are only captured for official-host accounts)"
|
||||
case ollamaCloudUsageIneligibleAccountType:
|
||||
return "wrong_account_type (usage snapshots require an apikey account)"
|
||||
default:
|
||||
return reason
|
||||
}
|
||||
}
|
||||
|
||||
func formatOllamaCloudFetchedAt(t *time.Time) string {
|
||||
if t == nil {
|
||||
return "unknown"
|
||||
}
|
||||
return t.UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
// quotaErrorSnapshot 构造统一错误快照。
|
||||
func quotaErrorSnapshot(source, message string, now time.Time) *domain.MonitorQuotaSnapshot {
|
||||
return &domain.MonitorQuotaSnapshot{
|
||||
|
||||
@@ -55,7 +55,7 @@ var (
|
||||
"CHANNEL_MONITOR_TEMPLATE_NOT_FOUND", "channel monitor request template not found",
|
||||
)
|
||||
ErrChannelMonitorTemplateInvalidProvider = infraerrors.BadRequest(
|
||||
"CHANNEL_MONITOR_TEMPLATE_INVALID_PROVIDER", "template provider must be one of openai/anthropic/gemini/grok",
|
||||
"CHANNEL_MONITOR_TEMPLATE_INVALID_PROVIDER", "template provider must be one of openai/anthropic/gemini/grok/ollama_cloud",
|
||||
)
|
||||
ErrChannelMonitorTemplateInvalidAPIMode = infraerrors.BadRequest(
|
||||
"CHANNEL_MONITOR_TEMPLATE_INVALID_API_MODE", "template api_mode must be chat_completions or responses; responses is only supported for openai",
|
||||
|
||||
@@ -23,6 +23,7 @@ var monitorProviders = map[string]struct{}{
|
||||
MonitorProviderZhipu: {},
|
||||
MonitorProviderDeepseek: {},
|
||||
MonitorProviderMiniMax: {},
|
||||
MonitorProviderOllamaCloud: {},
|
||||
}
|
||||
|
||||
// probeCapableProviders 支持探活(probe / quota_probe)的 provider。
|
||||
@@ -38,6 +39,8 @@ var probeCapableProviders = map[string]struct{}{
|
||||
MonitorProviderZhipu: {},
|
||||
MonitorProviderDeepseek: {},
|
||||
MonitorProviderMiniMax: {},
|
||||
// ollama_cloud 官方提供 OpenAI 兼容 /v1/chat/completions,可真实探活。
|
||||
MonitorProviderOllamaCloud: {},
|
||||
}
|
||||
|
||||
// validateProvider 校验 provider 字符串。
|
||||
|
||||
Reference in new issue
Block a user