mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 00:05:30 +00:00
- 转发结果记录上游端点价格倍数:Gemini 请求实际发往 us/eu 且模型在 vertexModelLocations 中声明支持该多区域时为 1.1,发往 global 时为 1; 引用显式缓存的请求按缓存所在区域判断 - 倍数只作用于按 token 计费的费用(输入、输出、缓存读取、缓存创建), 按次与按张计费不变,显式缓存存储费与联网搜索费在其后按原价叠加 - 建缓存的预扣报价与记账按缓存所在区域带上倍数 - 账号统计成本按模型定价文件计算时同样乘倍数,自定义规则与渠道计费档不变
487 lines
16 KiB
Go
487 lines
16 KiB
Go
package service
|
||
|
||
import (
|
||
"bytes"
|
||
"context"
|
||
"crypto/sha256"
|
||
"encoding/hex"
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"io"
|
||
"log/slog"
|
||
"net/http"
|
||
"net/url"
|
||
"regexp"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/Wei-Shaw/sub2api/internal/pkg/proxyurl"
|
||
"github.com/Wei-Shaw/sub2api/internal/pkg/proxyutil"
|
||
"github.com/Wei-Shaw/sub2api/internal/pkg/servertiming"
|
||
"github.com/golang-jwt/jwt/v5"
|
||
)
|
||
|
||
const (
|
||
vertexDefaultLocation = "us-central1"
|
||
vertexDefaultTokenURL = "https://oauth2.googleapis.com/token"
|
||
vertexCloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"
|
||
vertexServiceAccountCacheSkew = 5 * time.Minute
|
||
vertexLockWaitTime = 200 * time.Millisecond
|
||
vertexAnthropicVersion = "vertex-2023-10-16"
|
||
vertexGlobalHost = "aiplatform.googleapis.com"
|
||
vertexAuthModeAPIKey = "apikey"
|
||
)
|
||
|
||
var (
|
||
vertexLocationPattern = regexp.MustCompile(`^[a-z0-9-]+$`)
|
||
vertexAnthropicDatedModelIDPattern = regexp.MustCompile(`^(.+)-([0-9]{8})$`)
|
||
vertexAnthropicAlreadyDatedIDPattern = regexp.MustCompile(`^.+@[0-9]{8}$`)
|
||
)
|
||
|
||
// vertexServiceAccountTokenURL 是换取 SA access token 的端点,测试中替换为本地服务。
|
||
var vertexServiceAccountTokenURL = vertexDefaultTokenURL
|
||
|
||
type vertexServiceAccountKey struct {
|
||
Type string `json:"type"`
|
||
ProjectID string `json:"project_id"`
|
||
PrivateKeyID string `json:"private_key_id"`
|
||
PrivateKey string `json:"private_key"`
|
||
ClientEmail string `json:"client_email"`
|
||
TokenURI string `json:"token_uri"`
|
||
}
|
||
|
||
type vertexTokenResponse struct {
|
||
AccessToken string `json:"access_token"`
|
||
TokenType string `json:"token_type"`
|
||
ExpiresIn int64 `json:"expires_in"`
|
||
Error string `json:"error"`
|
||
ErrorDesc string `json:"error_description"`
|
||
}
|
||
|
||
func (a *Account) IsVertexServiceAccount() bool {
|
||
return a != nil && a.Type == AccountTypeServiceAccount
|
||
}
|
||
|
||
// IsVertexAPIKey 判断 Gemini 平台的 Vertex 账号是否使用 API Key 认证(credentials.auth_mode=apikey)。
|
||
// Anthropic 平台的 Vertex 账号只支持 Service Account JSON。
|
||
func (a *Account) IsVertexAPIKey() bool {
|
||
return a.IsVertexServiceAccount() && a.Platform == PlatformGemini &&
|
||
strings.TrimSpace(a.GetCredential("auth_mode")) == vertexAuthModeAPIKey
|
||
}
|
||
|
||
func (a *Account) VertexProjectID() string {
|
||
if a == nil {
|
||
return ""
|
||
}
|
||
if v := strings.TrimSpace(a.GetCredential("project_id")); v != "" {
|
||
return v
|
||
}
|
||
key, err := parseVertexServiceAccountKey(a)
|
||
if err == nil {
|
||
return strings.TrimSpace(key.ProjectID)
|
||
}
|
||
return ""
|
||
}
|
||
|
||
// VertexLocation 返回模型请求使用的区域:vertex_model_locations 显式指定优先;否则取账号区域,
|
||
// Gemini 账号区域为多区域(us/eu)时按 vertexModelLocations 判断模型是否支持,不支持的走 global。
|
||
func (a *Account) VertexLocation(model string) string {
|
||
if a == nil {
|
||
return vertexDefaultLocation
|
||
}
|
||
if model != "" && a.Credentials != nil {
|
||
if raw, ok := a.Credentials["vertex_model_locations"].(map[string]any); ok {
|
||
if loc, ok := raw[model].(string); ok && strings.TrimSpace(loc) != "" {
|
||
return strings.TrimSpace(loc)
|
||
}
|
||
}
|
||
}
|
||
location := a.vertexAccountLocation()
|
||
if a.Platform != PlatformGemini {
|
||
return location
|
||
}
|
||
return resolveVertexModelLocation(location, model)
|
||
}
|
||
|
||
// vertexAccountLocation 返回账号配置的区域,未配置时为 vertexDefaultLocation。
|
||
func (a *Account) vertexAccountLocation() string {
|
||
if v := strings.TrimSpace(a.GetCredential("location")); v != "" {
|
||
return v
|
||
}
|
||
if v := strings.TrimSpace(a.GetCredential("vertex_location")); v != "" {
|
||
return v
|
||
}
|
||
return vertexDefaultLocation
|
||
}
|
||
|
||
func parseVertexServiceAccountKey(account *Account) (*vertexServiceAccountKey, error) {
|
||
if account == nil || account.Credentials == nil {
|
||
return nil, errors.New("service account credentials not configured")
|
||
}
|
||
|
||
if raw := strings.TrimSpace(account.GetCredential("service_account_json")); raw != "" {
|
||
return parseVertexServiceAccountJSON([]byte(raw))
|
||
}
|
||
if raw := strings.TrimSpace(account.GetCredential("service_account")); raw != "" {
|
||
return parseVertexServiceAccountJSON([]byte(raw))
|
||
}
|
||
if nested, ok := account.Credentials["service_account_json"].(map[string]any); ok {
|
||
b, _ := json.Marshal(nested)
|
||
return parseVertexServiceAccountJSON(b)
|
||
}
|
||
if nested, ok := account.Credentials["service_account"].(map[string]any); ok {
|
||
b, _ := json.Marshal(nested)
|
||
return parseVertexServiceAccountJSON(b)
|
||
}
|
||
return nil, errors.New("service_account_json not found in credentials")
|
||
}
|
||
|
||
func parseVertexServiceAccountJSON(raw []byte) (*vertexServiceAccountKey, error) {
|
||
var key vertexServiceAccountKey
|
||
if err := json.Unmarshal(raw, &key); err != nil {
|
||
return nil, fmt.Errorf("invalid service account json: %w", err)
|
||
}
|
||
if strings.TrimSpace(key.ClientEmail) == "" {
|
||
return nil, errors.New("service account json missing client_email")
|
||
}
|
||
if strings.TrimSpace(key.PrivateKey) == "" {
|
||
return nil, errors.New("service account json missing private_key")
|
||
}
|
||
if strings.TrimSpace(key.ProjectID) == "" {
|
||
return nil, errors.New("service account json missing project_id")
|
||
}
|
||
// Always use the well-known Google token endpoint to prevent SSRF via crafted token_uri.
|
||
key.TokenURI = vertexServiceAccountTokenURL
|
||
return &key, nil
|
||
}
|
||
|
||
func vertexServiceAccountCacheKey(account *Account, key *vertexServiceAccountKey) string {
|
||
fingerprint := ""
|
||
if key != nil {
|
||
sum := sha256.Sum256([]byte(key.ClientEmail + "\x00" + key.PrivateKeyID))
|
||
fingerprint = hex.EncodeToString(sum[:8])
|
||
}
|
||
if fingerprint == "" && account != nil {
|
||
fingerprint = fmt.Sprintf("account:%d", account.ID)
|
||
}
|
||
return "vertex:service_account:" + fingerprint
|
||
}
|
||
|
||
// getVertexServiceAccountAccessToken obtains an access token for a Vertex service account,
|
||
// using the shared cache and distributed lock to avoid redundant exchanges.
|
||
func getVertexServiceAccountAccessToken(ctx context.Context, cache GeminiTokenCache, account *Account) (string, error) {
|
||
key, err := parseVertexServiceAccountKey(account)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
cacheKey := vertexServiceAccountCacheKey(account, key)
|
||
|
||
if cache != nil {
|
||
if token, err := cache.GetAccessToken(ctx, cacheKey); err == nil && strings.TrimSpace(token) != "" {
|
||
return token, nil
|
||
}
|
||
}
|
||
|
||
locked := false
|
||
if cache != nil {
|
||
var lockErr error
|
||
locked, lockErr = cache.AcquireRefreshLock(ctx, cacheKey, 30*time.Second)
|
||
if lockErr == nil && locked {
|
||
defer func() { _ = cache.ReleaseRefreshLock(ctx, cacheKey) }()
|
||
} else if lockErr != nil {
|
||
slog.Warn("vertex_service_account_token_lock_failed", "account_id", account.ID, "error", lockErr)
|
||
} else {
|
||
time.Sleep(vertexLockWaitTime)
|
||
if token, err := cache.GetAccessToken(ctx, cacheKey); err == nil && strings.TrimSpace(token) != "" {
|
||
return token, nil
|
||
}
|
||
}
|
||
}
|
||
|
||
accessToken, ttl, err := exchangeVertexServiceAccountToken(ctx, key, vertexServiceAccountProxyURL(account))
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
if cache != nil {
|
||
_ = cache.SetAccessToken(ctx, cacheKey, accessToken, ttl)
|
||
}
|
||
return accessToken, nil
|
||
}
|
||
|
||
func vertexServiceAccountProxyURL(account *Account) string {
|
||
if account == nil || account.ProxyID == nil || account.Proxy == nil {
|
||
return ""
|
||
}
|
||
return account.Proxy.URL()
|
||
}
|
||
|
||
func newVertexServiceAccountHTTPClient(proxyURL string) (*http.Client, error) {
|
||
proxyURL = strings.TrimSpace(proxyURL)
|
||
if proxyURL == "" {
|
||
return servertiming.InstrumentClient(&http.Client{Timeout: 15 * time.Second}), nil
|
||
}
|
||
|
||
_, parsedProxy, err := proxyurl.Parse(proxyURL)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
defaultTransport, ok := http.DefaultTransport.(*http.Transport)
|
||
if !ok {
|
||
return nil, fmt.Errorf("unexpected default transport type %T", http.DefaultTransport)
|
||
}
|
||
transport := defaultTransport.Clone()
|
||
transport.Proxy = nil
|
||
if err := proxyutil.ConfigureTransportProxy(transport, parsedProxy); err != nil {
|
||
return nil, err
|
||
}
|
||
return servertiming.InstrumentClient(&http.Client{Timeout: 15 * time.Second, Transport: transport}), nil
|
||
}
|
||
|
||
func exchangeVertexServiceAccountToken(ctx context.Context, key *vertexServiceAccountKey, proxyURL string) (string, time.Duration, error) {
|
||
now := time.Now()
|
||
claims := jwt.MapClaims{
|
||
"iss": key.ClientEmail,
|
||
"scope": vertexCloudPlatformScope,
|
||
"aud": key.TokenURI,
|
||
"iat": now.Unix(),
|
||
"exp": now.Add(time.Hour).Unix(),
|
||
}
|
||
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
|
||
if strings.TrimSpace(key.PrivateKeyID) != "" {
|
||
token.Header["kid"] = key.PrivateKeyID
|
||
}
|
||
privateKey, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(key.PrivateKey))
|
||
if err != nil {
|
||
return "", 0, fmt.Errorf("parse service account private key: %w", err)
|
||
}
|
||
assertion, err := token.SignedString(privateKey)
|
||
if err != nil {
|
||
return "", 0, fmt.Errorf("sign service account assertion: %w", err)
|
||
}
|
||
|
||
values := url.Values{}
|
||
values.Set("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer")
|
||
values.Set("assertion", assertion)
|
||
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, key.TokenURI, strings.NewReader(values.Encode()))
|
||
if err != nil {
|
||
return "", 0, err
|
||
}
|
||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||
|
||
client, err := newVertexServiceAccountHTTPClient(proxyURL)
|
||
if err != nil {
|
||
return "", 0, fmt.Errorf("configure service account token proxy: %w", err)
|
||
}
|
||
resp, err := client.Do(req)
|
||
if err != nil {
|
||
return "", 0, fmt.Errorf("service account token request failed: %w", err)
|
||
}
|
||
defer func() { _ = resp.Body.Close() }()
|
||
|
||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||
var parsed vertexTokenResponse
|
||
_ = json.Unmarshal(body, &parsed)
|
||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||
msg := strings.TrimSpace(parsed.ErrorDesc)
|
||
if msg == "" {
|
||
msg = strings.TrimSpace(parsed.Error)
|
||
}
|
||
if msg == "" {
|
||
msg = string(bytes.TrimSpace(body))
|
||
}
|
||
return "", 0, &vertexTokenRequestError{
|
||
StatusCode: resp.StatusCode,
|
||
Code: strings.TrimSpace(parsed.Error),
|
||
Description: strings.TrimSpace(parsed.ErrorDesc),
|
||
Message: msg,
|
||
}
|
||
}
|
||
if strings.TrimSpace(parsed.AccessToken) == "" {
|
||
return "", 0, errors.New("service account token response missing access_token")
|
||
}
|
||
ttl := time.Duration(parsed.ExpiresIn) * time.Second
|
||
if ttl <= 0 {
|
||
ttl = time.Hour
|
||
}
|
||
if ttl > vertexServiceAccountCacheSkew {
|
||
ttl -= vertexServiceAccountCacheSkew
|
||
}
|
||
return parsed.AccessToken, ttl, nil
|
||
}
|
||
|
||
// vertexTokenRequestError 是 token 端点对换取 SA access token 请求返回的非 2xx 响应。
|
||
type vertexTokenRequestError struct {
|
||
StatusCode int
|
||
Code string // 响应的 error 字段,如 invalid_grant
|
||
Description string // 响应的 error_description 字段
|
||
Message string
|
||
}
|
||
|
||
func (e *vertexTokenRequestError) Error() string {
|
||
return fmt.Sprintf("service account token request returned %d: %s", e.StatusCode, e.Message)
|
||
}
|
||
|
||
// vertexServiceAccountNotFoundError 识别 SA 已不存在:token 端点返回
|
||
// 400 {"error":"invalid_grant","error_description":"Invalid grant: account not found"}。
|
||
// 该凭据再也换不到 token,账号需要人工更换凭据。
|
||
func vertexServiceAccountNotFoundError(err error) (*vertexTokenRequestError, bool) {
|
||
var tokenErr *vertexTokenRequestError
|
||
if !errors.As(err, &tokenErr) {
|
||
return nil, false
|
||
}
|
||
if tokenErr.StatusCode != http.StatusBadRequest || tokenErr.Code != "invalid_grant" ||
|
||
!strings.Contains(strings.ToLower(tokenErr.Description), "account not found") {
|
||
return nil, false
|
||
}
|
||
return tokenErr, true
|
||
}
|
||
|
||
// buildVertexGeminiAccountURL 按账号构造 Vertex Gemini 请求地址:未配置 project_id 的 API Key 账号
|
||
// 走 Express mode 全局端点,其余账号走项目级端点。cachedContentLocation 是请求引用的显式缓存所在区域,
|
||
// 非空时按该区域发送(缓存只能在其所在区域的端点上引用),为空时按 VertexLocation 选区域。
|
||
func buildVertexGeminiAccountURL(account *Account, model, action string, stream bool, cachedContentLocation string) (string, error) {
|
||
if account.IsVertexAPIKey() && account.VertexProjectID() == "" {
|
||
return buildVertexGeminiExpressURL(model, action, stream)
|
||
}
|
||
location := vertexGeminiRequestLocation(account, model, cachedContentLocation)
|
||
return buildVertexGeminiURL(account.VertexProjectID(), location, model, action, stream)
|
||
}
|
||
|
||
// buildVertexGeminiExpressURL 构造不带项目与区域的全局端点地址,仅 API Key 认证可用。
|
||
func buildVertexGeminiExpressURL(model, action string, stream bool) (string, error) {
|
||
model = strings.TrimSpace(model)
|
||
action = strings.TrimSpace(action)
|
||
if model == "" {
|
||
return "", errors.New("vertex model is required")
|
||
}
|
||
if err := validateVertexGeminiAction(action); err != nil {
|
||
return "", err
|
||
}
|
||
u := fmt.Sprintf("https://%s/v1/publishers/google/models/%s:%s", vertexGlobalHost, url.PathEscape(model), action)
|
||
if stream {
|
||
u += "?alt=sse"
|
||
}
|
||
return u, nil
|
||
}
|
||
|
||
func validateVertexGeminiAction(action string) error {
|
||
switch action {
|
||
case "generateContent", "streamGenerateContent", "countTokens":
|
||
return nil
|
||
default:
|
||
return fmt.Errorf("unsupported vertex gemini action: %s", action)
|
||
}
|
||
}
|
||
|
||
// setVertexGeminiAuth 给 Vertex Gemini 请求设置认证头:API Key 账号用 x-goog-api-key,
|
||
// Service Account JSON 账号用换取的 Bearer access token。
|
||
func setVertexGeminiAuth(ctx context.Context, req *http.Request, account *Account, tokenProvider *GeminiTokenProvider) error {
|
||
if account.IsVertexAPIKey() {
|
||
apiKey := strings.TrimSpace(account.GetCredential("api_key"))
|
||
if apiKey == "" {
|
||
return errors.New("vertex api_key not configured")
|
||
}
|
||
req.Header.Set("x-goog-api-key", apiKey)
|
||
return nil
|
||
}
|
||
if tokenProvider == nil {
|
||
return errors.New("gemini token provider not configured")
|
||
}
|
||
accessToken, err := tokenProvider.GetAccessToken(ctx, account)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||
return nil
|
||
}
|
||
|
||
func buildVertexGeminiURL(projectID, location, model, action string, stream bool) (string, error) {
|
||
projectID = strings.TrimSpace(projectID)
|
||
location = strings.TrimSpace(location)
|
||
model = strings.TrimSpace(model)
|
||
action = strings.TrimSpace(action)
|
||
if projectID == "" {
|
||
return "", errors.New("vertex project_id is required")
|
||
}
|
||
if location == "" {
|
||
location = vertexDefaultLocation
|
||
}
|
||
if !vertexLocationPattern.MatchString(location) {
|
||
return "", fmt.Errorf("invalid vertex location: %s", location)
|
||
}
|
||
if model == "" {
|
||
return "", errors.New("vertex model is required")
|
||
}
|
||
if err := validateVertexGeminiAction(action); err != nil {
|
||
return "", err
|
||
}
|
||
host := vertexAPIHost(location)
|
||
u := fmt.Sprintf(
|
||
"https://%s/v1/projects/%s/locations/%s/publishers/google/models/%s:%s",
|
||
host,
|
||
url.PathEscape(projectID),
|
||
url.PathEscape(location),
|
||
url.PathEscape(model),
|
||
action,
|
||
)
|
||
if stream {
|
||
u += "?alt=sse"
|
||
}
|
||
return u, nil
|
||
}
|
||
|
||
func buildVertexAnthropicURL(projectID, location, model string, stream bool) (string, error) {
|
||
projectID = strings.TrimSpace(projectID)
|
||
location = strings.TrimSpace(location)
|
||
model = strings.TrimSpace(model)
|
||
if projectID == "" {
|
||
return "", errors.New("vertex project_id is required")
|
||
}
|
||
if location == "" {
|
||
location = vertexDefaultLocation
|
||
}
|
||
if !vertexLocationPattern.MatchString(location) {
|
||
return "", fmt.Errorf("invalid vertex location: %s", location)
|
||
}
|
||
if model == "" {
|
||
return "", errors.New("vertex model is required")
|
||
}
|
||
action := "rawPredict"
|
||
if stream {
|
||
action = "streamRawPredict"
|
||
}
|
||
host := vertexAPIHost(location)
|
||
escapedModel := strings.ReplaceAll(url.PathEscape(model), "%40", "@")
|
||
return fmt.Sprintf(
|
||
"https://%s/v1/projects/%s/locations/%s/publishers/anthropic/models/%s:%s",
|
||
host,
|
||
url.PathEscape(projectID),
|
||
url.PathEscape(location),
|
||
escapedModel,
|
||
action,
|
||
), nil
|
||
}
|
||
|
||
func normalizeVertexAnthropicModelID(model string) string {
|
||
model = strings.TrimSpace(model)
|
||
if model == "" || vertexAnthropicAlreadyDatedIDPattern.MatchString(model) {
|
||
return model
|
||
}
|
||
if m := vertexAnthropicDatedModelIDPattern.FindStringSubmatch(model); len(m) == 3 {
|
||
return m[1] + "@" + m[2]
|
||
}
|
||
return model
|
||
}
|
||
|
||
func buildVertexAnthropicRequestBody(body []byte) ([]byte, error) {
|
||
var payload map[string]any
|
||
if err := json.Unmarshal(body, &payload); err != nil {
|
||
return nil, fmt.Errorf("parse anthropic vertex request body: %w", err)
|
||
}
|
||
delete(payload, "model")
|
||
payload["anthropic_version"] = vertexAnthropicVersion
|
||
return json.Marshal(payload)
|
||
}
|