Documentation
¶
Index ¶
- Constants
- Variables
- func AcSearch(findText string, dict []string, stopImmediately bool) (bool, []string)
- func AppendChannelAffinityAdminInfo(c *gin.Context, other *model.LogOther)
- func AppendRelayLogAdminInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, other *model.LogOther)
- func AppendResponseModelLogInfo(relayInfo *relaycommon.RelayInfo, other *model.LogOther)
- func AppendUsedChannel(c *gin.Context, channelID int)
- func ApplyChannelAffinityOverrideTemplate(c *gin.Context, paramOverride map[string]any) (map[string]any, bool)
- func ApplyResponsesUsage(dst *dto.Usage, src *dto.Usage)
- func AuthSessionErrorCode(err error) (int, string)
- func BuildTieredTokenParams(usage *dto.Usage, isClaudeUsageSemantic bool, usedVars map[string]bool) billingexpr.TokenParams
- func CacheGetRandomSatisfiedChannel(param *RetryParam) (*model.Channel, string, error)
- func CalcOpenRouterCacheCreateTokens(usage dto.Usage, priceData types.PriceData) int
- func ChargeViolationFeeIfNeeded(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, apiErr *types.NewAPIError) bool
- func ChatCompletionsRequestToResponsesRequest(req *dto.GeneralOpenAIRequest) (*dto.OpenAIResponsesRequest, error)
- func ChatCompletionsResponseToResponsesResponse(resp *dto.OpenAITextResponse, id string) (*dto.OpenAIResponsesResponse, *dto.Usage, error)
- func CheckNotificationLimit(userId int, notifyType string) (bool, error)
- func CheckSensitiveMessages(messages []dto.Message) ([]string, error)
- func CheckSensitiveText(text string) (bool, []string)
- func ClaudeErrorWrapper(err error, code string, statusCode int) *dto.ClaudeErrorWithStatusCode
- func ClaudeErrorWrapperLocal(err error, code string, statusCode int) *dto.ClaudeErrorWithStatusCode
- func ClaudeToOpenAIRequest(claudeRequest dto.ClaudeRequest, info *relaycommon.RelayInfo) (*dto.GeneralOpenAIRequest, error)
- func CleanupFileSources(c *gin.Context)
- func ClearChannelAffinityCacheAll() int
- func ClearChannelAffinityCacheByRuleName(ruleName string) (int, error)
- func ClearCurrentChannelAffinityCache(c *gin.Context) bool
- func ClearRefreshCookie(c *gin.Context)
- func CloseActiveWebSocketsForChannel(channelID int, reason string) int
- func CloseActiveWebSocketsForChannels(channelIDs []int, reason string) int
- func CloseResponseBodyGracefully(httpResponse *http.Response)
- func CompleteLoginVerification(token string, verification *LoginVerification, method, ip, userAgent string) (*AuthBundle, *LegacyGitHubMigration, error)
- func ConsumeCodexWhamRateLimitResetCredit(ctx context.Context, client *http.Client, baseURL string, accessToken string, ...) (statusCode int, body []byte, err error)
- func ConsumeOperationProof(raw string, identity AuthIdentity, operation VerificationOperation) (*model.AuthFlowAuthorization, error)
- func ConvertRequest(c *gin.Context, info *relaycommon.RelayInfo, target types.RelayFormat, ...) (*relayconvert.RequestResult, error)
- func ConvertRequestByID(c *gin.Context, info *relaycommon.RelayInfo, converter string, request any) (*relayconvert.RequestResult, error)
- func ConvertRequestVia(c *gin.Context, info *relaycommon.RelayInfo, request any, ...) (*relayconvert.RequestResult, error)
- func ConvertResponse(c *gin.Context, info *relaycommon.RelayInfo, target types.RelayFormat, ...) (*relayconvert.ResponseResult, error)
- func ConvertStreamResponse(c *gin.Context, info *relaycommon.RelayInfo, target types.RelayFormat, ...) (*relayconvert.ResponseResult, error)
- func ConvertStreamResponseChunk(c *gin.Context, info *relaycommon.RelayInfo, ...) ([]relayconvert.ResponseResult, error)
- func CountAudioTokenInput(audioBase64 string, audioFormat string) (int, error)
- func CountAudioTokenOutput(audioBase64 string, audioFormat string) (int, error)
- func CountRequestToken(c *gin.Context, meta *types.TokenCountMeta, info *relaycommon.RelayInfo) (int, error)
- func CountTextToken(text string, model string) int
- func CountTokenInput(input any, model string) int
- func CountTokenRealtime(info *relaycommon.RelayInfo, request dto.RealtimeEvent, model string) (int, int, error)
- func CreateWaffoPancakePrimaryProduct(ctx context.Context, merchantID, privateKey, storeID, returnURL string) (string, error)
- func CreateWaffoPancakePrimaryStore(ctx context.Context, merchantID, privateKey string) (string, error)
- func DecodeBase64AudioData(audioBase64 string) (string, error)
- func DecodeBase64FileData(base64String string) (string, string, error)
- func DecodeBase64ImageData(base64String string) (image.Config, string, string, error)
- func DecodeUrlImageData(imageUrl string) (image.Config, string, error)
- func DetectFileType(mimeType string) types.FileType
- func DisableChannel(channelError types.ChannelError, reason string)
- func DoDownloadRequest(originUrl string, reason ...string) (resp *http.Response, err error)
- func DoWorkerRequest(req *WorkerRequest) (*http.Response, error)
- func EffectiveSessionMode(setting *operation_setting.ChannelAffinitySetting, ...) (mode, source string)
- func EnableChannel(channelId int, usingKey string, channelName string)
- func EnqueueSystemTask(taskType string, payload any) (*model.SystemTask, bool, error)
- func EstimateRequestToken(c *gin.Context, meta *types.TokenCountMeta, info *relaycommon.RelayInfo) (int, error)
- func EstimateToken(provider Provider, text string) int
- func EstimateTokenByModel(model, text string) int
- func ExtractCodexAccountIDFromJWT(token string) (string, bool)
- func ExtractEmailFromJWT(token string) (string, bool)
- func ExtractOutputTextFromResponses(resp *dto.OpenAIResponsesResponse) string
- func FetchCodexChannelModels(channel *model.Channel) ([]string, error)
- func FetchCodexModels(ctx context.Context, client *http.Client, baseURL string, ...) (statusCode int, models []string, err error)
- func FetchCodexWhamRateLimitResetCredits(ctx context.Context, client *http.Client, baseURL string, accessToken string, ...) (statusCode int, body []byte, err error)
- func FetchCodexWhamUsage(ctx context.Context, client *http.Client, baseURL string, accessToken string, ...) (statusCode int, body []byte, err error)
- func FilterUserTokenAutoGroups(userGroup string, groups []string) []string
- func FinalizeStreamResponse(c *gin.Context, info *relaycommon.RelayInfo, ...) ([]relayconvert.ResponseResult, error)
- func FinishEmailBinding(identity AuthIdentity, token, newCode, oldCode string) (*model.EmailBindingState, error)
- func FinishTwoFASetup(identity AuthIdentity, flowToken, code string) error
- func FormatAuthError(err error) string
- func GeminiToOpenAIRequest(geminiRequest *dto.GeminiChatRequest, info *relaycommon.RelayInfo) (*dto.GeneralOpenAIRequest, error)
- func GenerateAudioOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.Usage, ...) *model.LogOther
- func GenerateClaudeOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, ...) *model.LogOther
- func GenerateMjOtherInfo(relayInfo *relaycommon.RelayInfo, priceData hosttypes.PriceData) *model.LogOther
- func GenerateTextOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, ...) *model.LogOther
- func GenerateWssOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.RealtimeUsage, ...) *model.LogOther
- func GetBase64Data(c *gin.Context, source types.FileSource, reason ...string) (string, string, error)
- func GetCallbackAddress() string
- func GetChannelConstraints(c *gin.Context) *dto.ChannelConstraints
- func GetFileBase64FromUrl(c *gin.Context, url string, reason ...string) (*types.LocalFileData, error)
- func GetFileTypeFromUrl(c *gin.Context, url string, reason ...string) (string, error)
- func GetGroupsEnabledModels(groups []string) []string
- func GetHttpClient() *http.Client
- func GetHttpClientWithProxy(rawProxyURL string) (*http.Client, error)
- func GetHttpClientWithProxySettings(rawProxyURL string, settings dto.ChannelSettings) (*http.Client, error)
- func GetImageConfig(c *gin.Context, source types.FileSource) (image.Config, string, error)
- func GetImageFromUrl(url string) (mimeType string, data string, err error)
- func GetLatestCodexClientVersion(ctx context.Context, client *http.Client) (string, error)
- func GetMimeType(c *gin.Context, source types.FileSource) (string, error)
- func GetMimeTypeByExtension(ext string) string
- func GetOAuthVerificationBinding(identity AuthIdentity, scope, provider string) (string, error)
- func GetPreferredChannelByAffinity(c *gin.Context, modelName string, usingGroup string) (int, bool)
- func GetRequestAutoGroups(c *gin.Context, userGroup string) []string
- func GetSSRFProtectedHTTPClient() *http.Client
- func GetUsedChannelIDs(c *gin.Context) []int
- func GetUserAutoGroup(userGroup string) []string
- func GetUserGroupRatio(userGroup, group string) float64
- func GetUserUsableGroups(userGroup string) map[string]string
- func GroupInUserUsableGroups(userGroup, groupName string) bool
- func HasCSAMViolationMarker(err *types.NewAPIError) bool
- func IOCopyBytesGracefully(c *gin.Context, src *http.Response, data []byte)
- func InitAc(dict []string) *goahocorasick.Machine
- func InitHttpClient()
- func InitTokenEncoders()
- func InjectTieredBillingInfo(other *model.LogOther, relayInfo *relaycommon.RelayInfo, ...)
- func InvalidateProxyClient(rawProxyURL string)
- func IsUserSelectableGroup(userGroup, groupName string) bool
- func IsViolationFeeCode(code types.ErrorCode) bool
- func IssueAccessToken(identity AuthIdentity) (string, int64, error)
- func IssueSecurityProof(identity AuthIdentity, method string, binding VerificationBinding) (string, int64, error)
- func LoadFileSource(c *gin.Context, source types.FileSource, reason ...string) (*types.CachedFileData, error)
- func MarkChannelAffinityUsed(c *gin.Context, selectedGroup string, channelID int)
- func MarkRequestPolicySuccess(c *gin.Context, stream *relaycommon.StreamStatus)
- func NewProxyHttpClient(proxyURL string) (*http.Client, error)
- func NewSystemTaskProgressReporter(task *model.SystemTask, runnerID string) func(processed, total int)
- func NormalizeCacheCreationSplit(totalTokens int, tokens5m int, tokens1h int) (int, int)
- func NormalizeProxyURL(rawProxyURL string) (string, error)
- func NormalizeViolationFeeError(err *types.NewAPIError) *types.NewAPIError
- func NotifyAccountSecurityChange(email, event string) error
- func NotifyRootUser(t string, subject string, content string)
- func NotifyUpstreamModelUpdateWatchers(subject string, content string)
- func NotifyUser(userId int, userEmail string, userSetting dto.UserSetting, data dto.Notify) error
- func ObserveChannelAffinityUsageCacheByRelayFormat(c *gin.Context, usage *dto.Usage, relayFormat types.RelayFormat)
- func ObserveChannelAffinityUsageCacheFromContext(c *gin.Context, usage *dto.Usage, cachedTokenRateMode string)
- func ObserveResponsesOutcome(info *relaycommon.RelayInfo, event *dto.ResponsesStreamResponse)
- func PaymentReturnURL(suffix string) string
- func PostAudioConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.Usage, ...)
- func PostConsumeQuota(relayInfo *relaycommon.RelayInfo, quota int, preConsumedQuota int, ...) error
- func PostTextConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.Usage, ...)
- func PostWssConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, modelName string, ...)
- func PreConsumeBilling(c *gin.Context, preConsumedQuota int, relayInfo *relaycommon.RelayInfo) *types.NewAPIError
- func PreConsumeTokenQuota(relayInfo *relaycommon.RelayInfo, quota int) error
- func PreWssConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.RealtimeUsage) error
- func PrepareImageBillingForRequest(c *gin.Context, info *relaycommon.RelayInfo, count int) *types.NewAPIError
- func PrepareTieredBillingForSelectedGroup(c *gin.Context, relayInfo *relaycommon.RelayInfo) *types.NewAPIError
- func ProcessChannelError(c *gin.Context, channelError types.ChannelError, err *types.NewAPIError, ...)
- func RecordChannelAffinity(c *gin.Context, channelID int)
- func RecordPolicyFailure(c *gin.Context, channelID int, err *types.NewAPIError, decision PolicyDecision)
- func RecordRequestPolicyTermination(c *gin.Context, apiErr *types.NewAPIError)
- func RefreshTokenSID(rawRefreshToken string) (string, bool)
- func RegisterSystemTaskHandler(h SystemTaskHandler)
- func RelayErrorHandler(ctx context.Context, resp *http.Response, showBodyWhenFail bool) (newApiErr *types.NewAPIError)
- func ReleaseTokenBudget(c *gin.Context, relayInfo *relaycommon.RelayInfo)
- func RemoveDuplicate(s []string) []string
- func ReportCurrentSystemInstance() error
- func ResetProxyClientCache()
- func ResetStatusCode(newApiErr *types.NewAPIError, statusCodeMappingStr string)
- func ResolveWaffoPancakeTradeNo(event *WaffoPancakeWebhookEvent) (string, error)
- func ResponseOpenAI2Claude(openAIResponse *dto.OpenAITextResponse, info *relaycommon.RelayInfo) *dto.ClaudeResponse
- func ResponseOpenAI2Gemini(openAIResponse *dto.OpenAITextResponse, info *relaycommon.RelayInfo) *dto.GeminiChatResponse
- func ResponseText2Usage(c *gin.Context, responseText string, modeName string, promptTokens int) *dto.Usage
- func ResponsesFinishReasonFromStatus(resp *dto.OpenAIResponsesResponse) (string, bool)
- func ResponsesRequestToChatCompletionsRequest(req *dto.OpenAIResponsesRequest) (*dto.GeneralOpenAIRequest, error)
- func ResponsesResponseToChatCompletionsResponse(resp *dto.OpenAIResponsesResponse, id string) (*dto.OpenAITextResponse, *dto.Usage, error)
- func RevokeByRefreshToken(rawRefreshToken, expectedSID, reason string) error
- func SaveWaffoPancakeConfig(ctx context.Context, ...) error
- func SendWebhookNotify(webhookURL string, secret string, data dto.Notify) error
- func SensitiveWordContains(text string) (bool, []string)
- func SensitiveWordReplace(text string, returnImmediately bool) (bool, []string, string)
- func SettleBilling(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, actualQuota int) error
- func SettleTokenBudget(c *gin.Context, relayInfo *relaycommon.RelayInfo, actual int)
- func ShouldChatCompletionsUseResponsesGlobal(channelID int, channelType int, model string) bool
- func ShouldChatCompletionsUseResponsesPolicy(policy model_setting.ChatCompletionsToResponsesPolicy, channelID int, ...) bool
- func ShouldCopyUpstreamHeader(c *gin.Context, k string, v []string) bool
- func ShouldDisableChannel(err *types.NewAPIError) bool
- func ShouldEnableChannel(newAPIError *types.NewAPIError, status int) bool
- func ShouldKeepChannelAffinityOnChannelDisabled() bool
- func ShouldRetryRelayError(c *gin.Context, openaiErr *types.NewAPIError, retryTimes int) bool
- func ShouldSkipRetryAfterChannelAffinityFailure(c *gin.Context) bool
- func StartAuthArtifactCleanup()
- func StartCodexCredentialAutoRefreshTask()
- func StartLogCleanupTask(targetTimestamp int64) (*model.SystemTask, error)
- func StartSystemInstanceReporter()
- func StartSystemTaskRunner()
- func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamResponse, info *relaycommon.RelayInfo) []*dto.ClaudeResponse
- func StreamResponseOpenAI2Gemini(openAIResponse *dto.ChatCompletionsStreamResponse, info *relaycommon.RelayInfo) *dto.GeminiChatResponse
- func SundaySearch(text string, pattern string) bool
- func TokenRateLimitMember(c *gin.Context) string
- func TryTieredSettle(relayInfo *relaycommon.RelayInfo, params billingexpr.TokenParams) (ok bool, quota int, result *billingexpr.TieredResult)
- func UnbindAccountOAuth(identity AuthIdentity, providerID int) error
- func ValidUsage(usage *dto.Usage) bool
- func ValidateAccountEmail(email string) (string, error)
- func ValidateFlowAuthorization(identity AuthIdentity, operation VerificationOperation, ...) error
- func ValidateLoginSession(identity AuthIdentity) (*model.UserSession, *model.UserBase, error)
- func ValidateProxyURL(rawProxyURL string) error
- func ValidateSSRFProtectedFetchURL(urlStr string) error
- func VerifyLoginCode(token, code, ip, userAgent string) (*AuthBundle, *LegacyGitHubMigration, error)
- func VerifyTwoFactorCode(twoFA *model.TwoFA, code string) error
- func WaffoPancakeBuyerIdentityFromUserID(userID int) string
- func WrapAsViolationFeeGrokCSAM(err *types.NewAPIError) *types.NewAPIError
- func WriteRefreshCookie(c *gin.Context, rawToken string)
- type AccountBindingContext
- type AccountUnbindingContext
- type AuthBundle
- func AdvanceCurrentSessionSecurity(identity AuthIdentity, reason string) (*AuthBundle, error)
- func AdvanceCurrentSessionToUserVersion(identity AuthIdentity, reason string) (*AuthBundle, error)
- func CreateLoginSession(userID int, loginMethod, ip, userAgent string) (*AuthBundle, error)
- func CreateLoginSessionAtAuthVersion(userID int, expectedAuthVersion int64, loginMethod, ip, userAgent string) (*AuthBundle, error)
- func RefreshLoginSession(rawRefreshToken, expectedSID, ip, userAgent string) (*AuthBundle, *model.User, error)
- type AuthIdentity
- type BillingSession
- type ChannelAffinityCacheStats
- type ChannelAffinityStatsContext
- type ChannelAffinityUsageCacheCounters
- type ChannelAffinityUsageCacheStats
- type ChannelKeyReadContext
- type ChannelSelectError
- type CodexCredentialRefreshOptions
- type CodexOAuthKey
- type CodexOAuthTokenResult
- type EmailBindingData
- type HTTPTransportPolicy
- type LegacyGitHubMigration
- type LogCleanupPayload
- type LogCleanupResult
- type LogCleanupState
- type LoginChallenge
- type LoginSessionView
- type LoginVerification
- type ModelHistoryModel
- type ModelHistoryPoint
- type ModelHistorySeries
- type OAuthVerificationFlow
- type PolicyDecision
- type PolicyEvent
- type Provider
- type QuotaInfo
- type RankedModel
- type RankedVendor
- type RankingBucket
- type RankingMover
- type RankingsResponse
- type RequestPolicyState
- type ResponsesUsageAccumulator
- type RetryParam
- type ScheduledSystemTaskHandler
- type SecurityProof
- func CompleteSecurityVerification(identity AuthIdentity, binding VerificationBinding, method string) (*SecurityProof, error)
- func FinishOAuthVerification(identity AuthIdentity, provider, actualUserID string, ...) (*SecurityProof, error)
- func VerifySecurityInput(identity AuthIdentity, input VerificationInput) (*SecurityProof, error)
- type SystemInstanceHostInfo
- type SystemInstanceInfo
- type SystemInstanceResourceUsage
- type SystemInstanceResources
- type SystemInstanceRoleInfo
- type SystemInstanceRuntimeInfo
- type SystemInstanceStorageMetrics
- type SystemTaskHandler
- type SystemTaskProgress
- type TieredResultWrapper
- type TokenBudgetDecision
- type TokenDetails
- type TokenRateLimits
- type ToolSurchargeItem
- type TwoFASetup
- type VendorSharePoint
- type VendorShareSeries
- type VendorShareVendor
- type VerificationBinding
- type VerificationInput
- type VerificationMethodOption
- type VerificationOAuthProvider
- type VerificationOperation
- type VerificationRequirements
- type WaffoPancakeCatalog
- type WaffoPancakeCatalogProduct
- type WaffoPancakeCatalogStore
- type WaffoPancakeCheckoutSession
- type WaffoPancakeCreateSessionParams
- type WaffoPancakePairResult
- type WaffoPancakePriceSnapshot
- type WaffoPancakeWebhookData
- type WaffoPancakeWebhookEvent
- type WalletFunding
- type WebhookPayload
- type WorkerRequest
Constants ¶
const ( AccessTokenTTL = 15 * time.Minute SecurityProofTTL = time.Minute LoginSessionTTL = 30 * 24 * time.Hour RefreshReplayWindow = 30 * time.Second )
const ( VerificationMethodTwoFA = "2fa" VerificationMethodPasskey = "passkey" VerificationMethodPassword = "password" VerificationMethodOAuth = "oauth" VerificationMethodSession = "session" VerificationScopeChannelKeyRead = "channel.key.read" VerificationScopePasskeyRegister = "passkey.register" VerificationScopePasskeyDelete = "passkey.delete" VerificationScopeTwoFASetup = "2fa.setup" VerificationScopeTwoFADisable = "2fa.disable" VerificationScopeTwoFABackupCodes = "2fa.backup_codes.regenerate" VerificationScopeLogin = "auth.login" VerificationScopeAccessTokenGenerate = "access_token.generate" VerificationScopeAccessTokenRevoke = "access_token.revoke" VerificationScopeAccountBind = "account.binding.bind" VerificationScopeAccountUnbind = "account.binding.unbind" VerificationScopePasswordSet = "account.password.set" VerificationScopePasswordChange = "account.password.change" VerificationScopeAccountDelete = "account.delete" )
const ( ViolationFeeCodePrefix = "violation_fee." CSAMViolationMarker = "Failed check: SAFETY_CHECK_TYPE" ContentViolatesUsageMarker = "Content violates usage guidelines" )
const ChannelDisabledCloseReason = "channel disabled or deleted"
const LoginVerificationTTL = 5 * time.Minute
const RefreshCookieName = "new_api_refresh"
const SessionHintCookieName = "new_api_has_session"
SessionHintCookieName is the script-readable companion to RefreshCookieName. See writeSessionHintCookie for why it exists and what it is not.
const SessionHintCookieValue = "1"
SessionHintCookieValue is the only value the hint ever carries.
Variables ¶
var ( ErrLoginSessionInvalid = errors.New("login session is invalid") ErrLoginSessionRevoked = errors.New("login session is revoked") ErrLoginSessionMismatch = errors.New("login session does not match the expected session") ErrRefreshTokenInvalid = errors.New("refresh token is invalid") ErrRefreshRace = errors.New("refresh token was already rotated") )
var ( ErrAuthTokenInvalid = errors.New("authentication token is invalid") ErrAuthTokenExpired = errors.New("authentication token has expired") ErrProofScope = errors.New("security proof scope mismatch") ErrProofMethod = errors.New("security proof method mismatch") ErrProofContext = errors.New("security proof context mismatch") ErrProofConsumed = errors.New("security proof has already been consumed") )
var ( ErrAccountEmailInvalid = errors.New("Please enter a valid email address") ErrAccountEmailRestricted = errors.New("This email address is not allowed by the administrator's email policy.") ErrEmailBindingDelivery = errors.New("Verification email could not be sent. Start email verification again.") )
var ( ErrVerificationFailed = errors.New("Verification failed. Please try again.") ErrVerificationLocked = errors.New("Two-factor authentication is temporarily locked.") ErrVerificationFlowRequired = errors.New("This verification method requires its dedicated verification flow.") ErrVerificationContextInvalid = errors.New("The action details are invalid.") ErrVerificationForbidden = errors.New("You do not have permission to perform this action.") )
var ErrInsufficientWalletQuota = errors.New("wallet quota insufficient")
ErrInsufficientWalletQuota 钱包原子预扣失败(余额不足),未发生任何扣减。 BillingSession 据此映射为 ErrorCodeInsufficientUserQuota。
var ErrOAuthAccountMismatch = errors.New("The OAuth account does not match the account linked to your profile.")
Functions ¶
func AppendRelayLogAdminInfo ¶
func AppendRelayLogAdminInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, other *model.LogOther)
AppendRelayLogAdminInfo records relay routing and conversion diagnostics in the admin-only scope shared by successful and failed request logs.
func AppendResponseModelLogInfo ¶
func AppendResponseModelLogInfo(relayInfo *relaycommon.RelayInfo, other *model.LogOther)
func AppendUsedChannel ¶
AppendUsedChannel records an attempted channel in the request's channel trail, which the retry log and the consume log's admin_info both read.
func ApplyChannelAffinityOverrideTemplate ¶
func ApplyChannelAffinityOverrideTemplate(c *gin.Context, paramOverride map[string]any) (map[string]any, bool)
ApplyChannelAffinityOverrideTemplate merges per-rule channel override templates onto the selected channel override config.
func AuthSessionErrorCode ¶
func BuildTieredTokenParams ¶
func BuildTieredTokenParams(usage *dto.Usage, isClaudeUsageSemantic bool, usedVars map[string]bool) billingexpr.TokenParams
BuildTieredTokenParams constructs billingexpr.TokenParams from a dto.Usage, normalizing P and C so they mean "tokens not separately priced by the expression". Sub-categories (cache, image, audio) are only subtracted when the expression references them via their own variable.
GPT-format APIs report prompt_tokens / completion_tokens as totals that include all sub-categories (cache, image, audio). Claude-format APIs report them as text-only. This function normalizes to text-only when sub-categories are separately priced.
func CacheGetRandomSatisfiedChannel ¶
func CacheGetRandomSatisfiedChannel(param *RetryParam) (*model.Channel, string, error)
CacheGetRandomSatisfiedChannel tries to get a random channel that satisfies the requirements. 尝试获取一个满足要求的随机渠道。
For "auto" tokenGroup with cross-group Retry enabled: 对于启用了跨分组重试的 "auto" tokenGroup:
Each group will exhaust all its priorities before moving to the next group. 每个分组会用完所有优先级后才会切换到下一个分组。
Uses ContextKeyAutoGroupIndex to track current group index. 使用 ContextKeyAutoGroupIndex 跟踪当前分组索引。
Uses ContextKeyAutoGroupRetryIndex to track the global Retry count when current group started. 使用 ContextKeyAutoGroupRetryIndex 跟踪当前分组开始时的全局重试次数。
priorityRetry = Retry - startRetryIndex, represents the priority level within current group. priorityRetry = Retry - startRetryIndex,表示当前分组内的优先级级别。
When GetRandomSatisfiedChannel returns nil (priorities exhausted), moves to next group. 当 GetRandomSatisfiedChannel 返回 nil(优先级用完)时,切换到下一个分组。
Example flow (2 groups, each with 2 priorities, RetryTimes=3): 示例流程(2个分组,每个有2个优先级,RetryTimes=3):
Retry=0: GroupA, priority0 (startRetryIndex=0, priorityRetry=0)
分组A, 优先级0
Retry=1: GroupA, priority1 (startRetryIndex=0, priorityRetry=1)
分组A, 优先级1
Retry=2: GroupA exhausted → GroupB, priority0 (startRetryIndex=2, priorityRetry=0)
分组A用完 → 分组B, 优先级0
Retry=3: GroupB, priority1 (startRetryIndex=2, priorityRetry=1)
分组B, 优先级1
func ChargeViolationFeeIfNeeded ¶
func ChargeViolationFeeIfNeeded(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, apiErr *types.NewAPIError) bool
ChargeViolationFeeIfNeeded charges an additional fee after the normal flow finishes (including refund). It uses Grok fee settings as the fee policy.
func ChatCompletionsRequestToResponsesRequest ¶
func ChatCompletionsRequestToResponsesRequest(req *dto.GeneralOpenAIRequest) (*dto.OpenAIResponsesRequest, error)
func ChatCompletionsResponseToResponsesResponse ¶
func ChatCompletionsResponseToResponsesResponse(resp *dto.OpenAITextResponse, id string) (*dto.OpenAIResponsesResponse, *dto.Usage, error)
func CheckNotificationLimit ¶
CheckNotificationLimit checks if the user has exceeded their notification limit Returns true if the user can send notification, false if limit exceeded
func CheckSensitiveText ¶
func ClaudeErrorWrapper ¶
func ClaudeErrorWrapper(err error, code string, statusCode int) *dto.ClaudeErrorWithStatusCode
func ClaudeErrorWrapperLocal ¶
func ClaudeErrorWrapperLocal(err error, code string, statusCode int) *dto.ClaudeErrorWithStatusCode
func ClaudeToOpenAIRequest ¶
func ClaudeToOpenAIRequest(claudeRequest dto.ClaudeRequest, info *relaycommon.RelayInfo) (*dto.GeneralOpenAIRequest, error)
func CleanupFileSources ¶
CleanupFileSources 清理请求中所有注册的 FileSource 应在请求结束时调用(通常由中间件自动调用)
func ClearChannelAffinityCacheAll ¶
func ClearChannelAffinityCacheAll() int
func ClearRefreshCookie ¶
func CompleteLoginVerification ¶
func CompleteLoginVerification(token string, verification *LoginVerification, method, ip, userAgent string) (*AuthBundle, *LegacyGitHubMigration, error)
CompleteLoginVerification must only run after a concrete factor ceremony. Recheck the bound version and method while consuming the flow and creating the session atomically; a different request cannot reuse this authorization. The returned migration is non-nil when the flow's pending GitHub binding rewrite was written together with the session.
func ConsumeOperationProof ¶
func ConsumeOperationProof(raw string, identity AuthIdentity, operation VerificationOperation) (*model.AuthFlowAuthorization, error)
ConsumeOperationProof accepts a proof at most once. The consumption commits before the caller performs its action; an action failure must not restore it.
func ConvertRequest ¶
func ConvertRequest(c *gin.Context, info *relaycommon.RelayInfo, target types.RelayFormat, request any) (*relayconvert.RequestResult, error)
ConvertRequest converts one request for the selected channel and records the hosted tool types the conversion wrote upstream, so the request-time tool price gate judges the upstream namespace rather than the client's. Every production conversion goes through here; see the relay handlers for the gate.
func ConvertRequestByID ¶
func ConvertRequestByID(c *gin.Context, info *relaycommon.RelayInfo, converter string, request any) (*relayconvert.RequestResult, error)
func ConvertRequestVia ¶
func ConvertRequestVia(c *gin.Context, info *relaycommon.RelayInfo, request any, path ...types.RelayFormat) (*relayconvert.RequestResult, error)
func ConvertResponse ¶
func ConvertResponse(c *gin.Context, info *relaycommon.RelayInfo, target types.RelayFormat, response any) (*relayconvert.ResponseResult, error)
func ConvertStreamResponse ¶
func ConvertStreamResponse(c *gin.Context, info *relaycommon.RelayInfo, target types.RelayFormat, response any) (*relayconvert.ResponseResult, error)
func ConvertStreamResponseChunk ¶
func ConvertStreamResponseChunk(c *gin.Context, info *relaycommon.RelayInfo, state *relayconvert.ResponseStreamState, response any) ([]relayconvert.ResponseResult, error)
func CountAudioTokenInput ¶
func CountAudioTokenOutput ¶
func CountRequestToken ¶
func CountRequestToken(c *gin.Context, meta *types.TokenCountMeta, info *relaycommon.RelayInfo) (int, error)
CountRequestToken counts request tokens regardless of the billing estimation switch. Utility endpoints such as Claude's messages/count_tokens must remain available even when operators disable request-token estimation for relays.
func CountTextToken ¶
CountTextToken 统计文本的token数量,仅OpenAI模型使用tokenizer,其余模型使用估算
func CountTokenInput ¶
func CountTokenRealtime ¶
func CountTokenRealtime(info *relaycommon.RelayInfo, request dto.RealtimeEvent, model string) (int, int, error)
func CreateWaffoPancakePrimaryProduct ¶
func CreateWaffoPancakePrimaryProduct(ctx context.Context, merchantID, privateKey, storeID, returnURL string) (string, error)
CreateWaffoPancakePrimaryProduct mints (and publishes) the wallet-top-up OnetimeProduct under storeID. Per-checkout price overrides via PriceSnapshot are what make the "1.00" seed price irrelevant at runtime.
func CreateWaffoPancakePrimaryStore ¶
func CreateWaffoPancakePrimaryStore(ctx context.Context, merchantID, privateKey string) (string, error)
CreateWaffoPancakePrimaryStore creates a Pancake Store using in-flight (not-yet-persisted) credentials and returns the new store ID.
func DecodeBase64AudioData ¶
func DecodeBase64ImageData ¶
return image.Config, format, clean base64 string, error
func DisableChannel ¶
func DisableChannel(channelError types.ChannelError, reason string)
disable & notify
func DoDownloadRequest ¶
func DoWorkerRequest ¶
func DoWorkerRequest(req *WorkerRequest) (*http.Response, error)
DoWorkerRequest 通过Worker发送请求
func EffectiveSessionMode ¶
func EffectiveSessionMode(setting *operation_setting.ChannelAffinitySetting, rule operation_setting.ChannelAffinityRule) (mode, source string)
Rules explicitly inherit the global default or override it. Rules without a mode retain their legacy retry behavior until an administrator changes them.
func EnableChannel ¶
func EnqueueSystemTask ¶
EnqueueSystemTask creates an on-demand task of the given type. The returned bool is true only when a new pending row was created; false means an active task of the same type already exists and was returned.
func EstimateRequestToken ¶
func EstimateRequestToken(c *gin.Context, meta *types.TokenCountMeta, info *relaycommon.RelayInfo) (int, error)
func EstimateToken ¶
EstimateToken 计算 Token 数量
func EstimateTokenByModel ¶
func ExtractEmailFromJWT ¶
func ExtractOutputTextFromResponses ¶
func ExtractOutputTextFromResponses(resp *dto.OpenAIResponsesResponse) string
func FetchCodexChannelModels ¶
func FetchCodexModels ¶
func FetchCodexWhamUsage ¶
func FilterUserTokenAutoGroups ¶
FilterUserTokenAutoGroups applies current permissions before the current per-token limit. It intentionally does not fall back to the global Auto list.
func FinalizeStreamResponse ¶
func FinalizeStreamResponse(c *gin.Context, info *relaycommon.RelayInfo, state *relayconvert.ResponseStreamState) ([]relayconvert.ResponseResult, error)
func FinishEmailBinding ¶
func FinishEmailBinding(identity AuthIdentity, token, newCode, oldCode string) (*model.EmailBindingState, error)
func FinishTwoFASetup ¶
func FinishTwoFASetup(identity AuthIdentity, flowToken, code string) error
func FormatAuthError ¶
func GeminiToOpenAIRequest ¶
func GeminiToOpenAIRequest(geminiRequest *dto.GeminiChatRequest, info *relaycommon.RelayInfo) (*dto.GeneralOpenAIRequest, error)
func GenerateAudioOtherInfo ¶
func GenerateClaudeOtherInfo ¶
func GenerateClaudeOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, modelRatio, groupRatio, completionRatio float64, cacheTokens int, cacheRatio float64, cacheCreationTokens int, cacheCreationRatio float64, cacheCreationTokens5m int, cacheCreationRatio5m float64, cacheCreationTokens1h int, cacheCreationRatio1h float64, modelPrice float64, userGroupRatio float64) *model.LogOther
func GenerateMjOtherInfo ¶
func GenerateTextOtherInfo ¶
func GenerateWssOtherInfo ¶
func GenerateWssOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.RealtimeUsage, modelRatio, groupRatio, completionRatio, audioRatio, audioCompletionRatio, modelPrice, userGroupRatio float64) *model.LogOther
func GetBase64Data ¶
func GetBase64Data(c *gin.Context, source types.FileSource, reason ...string) (string, string, error)
GetBase64Data 获取 base64 编码的数据
func GetCallbackAddress ¶
func GetCallbackAddress() string
func GetChannelConstraints ¶
func GetChannelConstraints(c *gin.Context) *dto.ChannelConstraints
func GetFileBase64FromUrl ¶
func GetFileBase64FromUrl(c *gin.Context, url string, reason ...string) (*types.LocalFileData, error)
GetFileBase64FromUrl 从 URL 获取文件的 base64 编码数据 Deprecated: 请使用 GetBase64Data 配合 types.NewURLFileSource 替代 此函数保留用于向后兼容,内部已重构为调用统一的文件服务
func GetFileTypeFromUrl ¶
GetFileTypeFromUrl 获取文件类型,返回 mime type, 例如 image/jpeg, image/png, image/gif, image/bmp, image/tiff, application/pdf 如果获取失败,返回 application/octet-stream
func GetGroupsEnabledModels ¶
GetGroupsEnabledModels 按 groups 顺序获取各分组启用的模型并去重。 非自用模式下会剔除未配置计费的模型:它们虽然可以路由,但转发时会被拒绝, 因此不应出现在任何面向用户的模型清单里(站内清单与 /v1/models 共用本函数)。
func GetHttpClient ¶
GetHttpClient returns the general outbound client used by relay/provider integrations. Do not attach the SSRF-protected dialer here: provider base URLs are root/operator-managed deployment targets, not arbitrary user-controlled input, and may legitimately point at private networks, private-link endpoints, self-hosted services, or local proxies. Code paths that fetch arbitrary user-controlled URLs must use GetSSRFProtectedHTTPClient or ValidateSSRFProtectedFetchURL instead.
func GetHttpClientWithProxy ¶
GetHttpClientWithProxy returns the default client or a cached proxy-enabled client.
func GetHttpClientWithProxySettings ¶
func GetHttpClientWithProxySettings(rawProxyURL string, settings dto.ChannelSettings) (*http.Client, error)
GetHttpClientWithProxySettings returns a cached HTTP client for the proxy URL and channel transport settings. Default auto + 1 shard shares the same client pool as GetHttpClientWithProxy / GetHttpClient for the empty-proxy case.
func GetImageConfig ¶
GetImageConfig 获取图片配置
func GetImageFromUrl ¶
GetImageFromUrl 获取图片的类型和base64编码的数据
func GetMimeType ¶
GetMimeType 获取文件的 MIME 类型
func GetMimeTypeByExtension ¶
func GetOAuthVerificationBinding ¶
func GetOAuthVerificationBinding(identity AuthIdentity, scope, provider string) (string, error)
func GetRequestAutoGroups ¶
GetRequestAutoGroups resolves the ordered Auto groups for the current token. The absence of the context value means that the token inherits the complete global Auto list; a present (even empty) value is an explicit token snapshot.
func GetSSRFProtectedHTTPClient ¶
GetSSRFProtectedHTTPClient 返回带拨号时 SSRF 校验的客户端。 ssrfProtectedHTTPClient 由 InitHttpClient 在启动时初始化,运行期只读。
func GetUsedChannelIDs ¶
GetUsedChannelIDs extracts the list of unique channel IDs attempted so far for this request, sourced from use_channel trail or context channel_id.
func GetUserAutoGroup ¶
GetUserAutoGroup 根据用户分组获取自动分组设置
func GetUserGroupRatio ¶
GetUserGroupRatio 获取用户使用某个分组的倍率 userGroup 用户分组 group 需要获取倍率的分组
func GetUserUsableGroups ¶
func GroupInUserUsableGroups ¶
func HasCSAMViolationMarker ¶
func HasCSAMViolationMarker(err *types.NewAPIError) bool
func IOCopyBytesGracefully ¶
func InitAc ¶
func InitAc(dict []string) *goahocorasick.Machine
func InitHttpClient ¶
func InitHttpClient()
func InitTokenEncoders ¶
func InitTokenEncoders()
func InjectTieredBillingInfo ¶
func InjectTieredBillingInfo(other *model.LogOther, relayInfo *relaycommon.RelayInfo, result *billingexpr.TieredResult)
InjectTieredBillingInfo overlays tiered billing fields onto an existing module-specific other map. Call this after GenerateTextOtherInfo / GenerateClaudeOtherInfo / etc. when the request used tiered_expr billing.
func InvalidateProxyClient ¶
func InvalidateProxyClient(rawProxyURL string)
InvalidateProxyClient removes every cached policy variant for one proxy and closes their idle connections (including all HTTP/2 shards).
func IsUserSelectableGroup ¶
func IsViolationFeeCode ¶
func IssueAccessToken ¶
func IssueAccessToken(identity AuthIdentity) (string, int64, error)
func IssueSecurityProof ¶
func IssueSecurityProof(identity AuthIdentity, method string, binding VerificationBinding) (string, int64, error)
func LoadFileSource ¶
func LoadFileSource(c *gin.Context, source types.FileSource, reason ...string) (*types.CachedFileData, error)
LoadFileSource 加载文件源数据 这是统一的入口,会自动处理缓存和不同的来源类型
func MarkChannelAffinityUsed ¶
func MarkRequestPolicySuccess ¶
func MarkRequestPolicySuccess(c *gin.Context, stream *relaycommon.StreamStatus)
func NewProxyHttpClient ¶
NewProxyHttpClient is kept for compatibility. Deprecated: use GetHttpClientWithProxy.
func NewSystemTaskProgressReporter ¶
func NewSystemTaskProgressReporter(task *model.SystemTask, runnerID string) func(processed, total int)
NewSystemTaskProgressReporter returns a throttled progress callback bound to a running task. Handlers call it with (processed, total) as they iterate work; it persists a {processed,total,progress} state at most once every ~2s, always emitting the first update and the final 100%. Lock-loss errors are ignored: the lease heartbeat cancels the handler ctx on loss, so progress writes are best-effort and never abort the run themselves. The returned func is single-goroutine only (call it from the handler loop).
func NormalizeProxyURL ¶
NormalizeProxyURL validates a proxy URL using runtime-compatible rules and returns its canonical cache key.
func NormalizeViolationFeeError ¶
func NormalizeViolationFeeError(err *types.NewAPIError) *types.NewAPIError
NormalizeViolationFeeError ensures: - if the CSAM marker is present, error.code is set to a stable violation-fee code and skip-retry is enabled. - if error.code already has the violation-fee prefix, skip-retry is enabled.
It must be called before retry decision logic.
func NotifyAccountSecurityChange ¶
NotifyAccountSecurityChange never includes credentials or tokens. The caller records delivery failure independently from the already-committed change.
func NotifyRootUser ¶
func NotifyUser ¶
func ObserveChannelAffinityUsageCacheByRelayFormat ¶
func ObserveChannelAffinityUsageCacheByRelayFormat(c *gin.Context, usage *dto.Usage, relayFormat types.RelayFormat)
ObserveChannelAffinityUsageCacheByRelayFormat records usage cache stats with a stable rate mode derived from relay format.
func ObserveResponsesOutcome ¶
func ObserveResponsesOutcome(info *relaycommon.RelayInfo, event *dto.ResponsesStreamResponse)
ObserveResponsesOutcome records the protocol outcome of one Responses event on the stream status for health classification. Only codes and types are kept; messages never leave the event.
func PaymentReturnURL ¶
func PostAudioConsumeQuota ¶
func PostConsumeQuota ¶
func PostTextConsumeQuota ¶
func PostWssConsumeQuota ¶
func PostWssConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, modelName string, usage *dto.RealtimeUsage, extraContent string)
func PreConsumeBilling ¶
func PreConsumeBilling(c *gin.Context, preConsumedQuota int, relayInfo *relaycommon.RelayInfo) *types.NewAPIError
PreConsumeBilling 创建 BillingSession 并执行预扣费。 会话存储在 relayInfo.Billing 上,供后续 Settle / Refund 使用。
func PreConsumeTokenQuota ¶
func PreConsumeTokenQuota(relayInfo *relaycommon.RelayInfo, quota int) error
func PreWssConsumeQuota ¶
func PreWssConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.RealtimeUsage) error
func PrepareImageBillingForRequest ¶
func PrepareImageBillingForRequest(c *gin.Context, info *relaycommon.RelayInfo, count int) *types.NewAPIError
PrepareImageBillingForRequest reserves the effective outbound image quantity before each attempt, including channel retries and parameter overrides. The client request body stays frozen; only the independent quantity is refreshed.
func PrepareTieredBillingForSelectedGroup ¶
func PrepareTieredBillingForSelectedGroup(c *gin.Context, relayInfo *relaycommon.RelayInfo) *types.NewAPIError
PrepareTieredBillingForSelectedGroup refreshes routing-dependent billing state before an upstream attempt. An existing session reserves any higher estimate before sending. If the initial group was free and skipped pre-consume, switching to a paid group creates the session at that point.
func ProcessChannelError ¶
func ProcessChannelError(c *gin.Context, channelError types.ChannelError, err *types.NewAPIError, relayInfo *relaycommon.RelayInfo)
func RecordChannelAffinity ¶
func RecordPolicyFailure ¶
func RecordPolicyFailure(c *gin.Context, channelID int, err *types.NewAPIError, decision PolicyDecision)
RecordPolicyFailure appends the failed attempt and the retry decision made for it. The health entry mirrors the check in ProcessChannelError, which performs the actual disable.
func RecordRequestPolicyTermination ¶
func RecordRequestPolicyTermination(c *gin.Context, apiErr *types.NewAPIError)
RecordRequestPolicyTermination appends the final decision after routing has stopped. It never writes a log row itself: the per-channel error log written by ProcessChannelError already carries the decision record, so a second row here would duplicate it.
func RefreshTokenSID ¶
func RegisterSystemTaskHandler ¶
func RegisterSystemTaskHandler(h SystemTaskHandler)
RegisterSystemTaskHandler registers a handler keyed by its Type(). It must be called before StartSystemTaskRunner (or any time, since the runner snapshots the registry every pass). Re-registering a type replaces the previous handler.
func RelayErrorHandler ¶
func ReleaseTokenBudget ¶
func ReleaseTokenBudget(c *gin.Context, relayInfo *relaycommon.RelayInfo)
ReleaseTokenBudget drops the reservation of a request that failed before it settled, so a rejection or an upstream error does not hold the key's budget.
func RemoveDuplicate ¶
func ReportCurrentSystemInstance ¶
func ReportCurrentSystemInstance() error
func ResetProxyClientCache ¶
func ResetProxyClientCache()
ResetProxyClientCache clears cached proxy and non-default direct policy clients and closes idle connections on every transport/shard. The package-level default httpClient pointer stays stable after InitHttpClient; it is only closed and re-registered in the policy cache so concurrent GetHttpClient readers never race a pointer replacement.
func ResetStatusCode ¶
func ResetStatusCode(newApiErr *types.NewAPIError, statusCodeMappingStr string)
func ResolveWaffoPancakeTradeNo ¶
func ResolveWaffoPancakeTradeNo(event *WaffoPancakeWebhookEvent) (string, error)
ResolveWaffoPancakeTradeNo maps a verified webhook event to a local TopUp trade_no via OrderMerchantExternalID, and rejects buyer-identity mismatches.
func ResponseOpenAI2Claude ¶
func ResponseOpenAI2Claude(openAIResponse *dto.OpenAITextResponse, info *relaycommon.RelayInfo) *dto.ClaudeResponse
func ResponseOpenAI2Gemini ¶
func ResponseOpenAI2Gemini(openAIResponse *dto.OpenAITextResponse, info *relaycommon.RelayInfo) *dto.GeminiChatResponse
func ResponseText2Usage ¶
func ResponsesFinishReasonFromStatus ¶
func ResponsesFinishReasonFromStatus(resp *dto.OpenAIResponsesResponse) (string, bool)
func ResponsesRequestToChatCompletionsRequest ¶
func ResponsesRequestToChatCompletionsRequest(req *dto.OpenAIResponsesRequest) (*dto.GeneralOpenAIRequest, error)
func ResponsesResponseToChatCompletionsResponse ¶
func ResponsesResponseToChatCompletionsResponse(resp *dto.OpenAIResponsesResponse, id string) (*dto.OpenAITextResponse, *dto.Usage, error)
func RevokeByRefreshToken ¶
func SaveWaffoPancakeConfig ¶
func SaveWaffoPancakeConfig(ctx context.Context, merchantID, privateKey, returnURL, storeID, productID string) error
SaveWaffoPancakeConfig persists the operator-controlled fields atomically at the end of the configuration flow via model.UpdateOptionsBulk (single DB transaction). A blank privateKey is treated as "keep current" (Stripe-style API-secret UX) and is omitted from the bulk payload.
func SendWebhookNotify ¶
SendWebhookNotify 发送 webhook 通知
func SensitiveWordContains ¶
SensitiveWordContains 是否包含敏感词,返回是否包含敏感词和敏感词列表
func SensitiveWordReplace ¶
SensitiveWordReplace 敏感词替换,返回是否包含敏感词和替换后的文本
func SettleBilling ¶
SettleBilling 执行计费结算。如果 RelayInfo 上有 BillingSession 则通过 session 结算, 否则回退到旧的 PostConsumeQuota 路径(兼容按次计费等场景)。
func SettleTokenBudget ¶
func SettleTokenBudget(c *gin.Context, relayInfo *relaycommon.RelayInfo, actual int)
SettleTokenBudget replaces the request's reserved token cost with the usage the upstream reported, so the minute window reflects what was actually consumed. A settlement for a key without a token budget is a no-op.
func ShouldChatCompletionsUseResponsesPolicy ¶
func ShouldChatCompletionsUseResponsesPolicy(policy model_setting.ChatCompletionsToResponsesPolicy, channelID int, channelType int, model string) bool
func ShouldCopyUpstreamHeader ¶
ShouldCopyUpstreamHeader checks whether a given upstream response header should be copied to the client response. It returns false for Content-Length (managed separately) and X-Oneapi-Request-Id (to preserve the local instance ID). When the upstream header is X-Oneapi-Request-Id, the value is captured into the Gin context for later logging.
func ShouldDisableChannel ¶
func ShouldDisableChannel(err *types.NewAPIError) bool
ShouldDisableChannel decides whether an error is evidence against the channel itself. SkipRetry is answered first: an error that declares itself terminal for every channel of the type is about the request or the channel's configuration (an unsupported format, a broken model mapping or param override), not about the channel being down, and taking it offline for a client-side mistake costs every other model on that channel. Errors that carry a channel: code without that flag (a missing or invalid key, a client the SDK could not build) still disable it.
func ShouldEnableChannel ¶
func ShouldEnableChannel(newAPIError *types.NewAPIError, status int) bool
func ShouldKeepChannelAffinityOnChannelDisabled ¶
func ShouldKeepChannelAffinityOnChannelDisabled() bool
func ShouldRetryRelayError ¶
func StartAuthArtifactCleanup ¶
func StartAuthArtifactCleanup()
StartAuthArtifactCleanup removes expired dashboard Sessions and old one-time authentication flows. Only the master instance performs cleanup.
func StartCodexCredentialAutoRefreshTask ¶
func StartCodexCredentialAutoRefreshTask()
func StartLogCleanupTask ¶
func StartLogCleanupTask(targetTimestamp int64) (*model.SystemTask, error)
func StartSystemInstanceReporter ¶
func StartSystemInstanceReporter()
func StartSystemTaskRunner ¶
func StartSystemTaskRunner()
func StreamResponseOpenAI2Claude ¶
func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamResponse, info *relaycommon.RelayInfo) []*dto.ClaudeResponse
func StreamResponseOpenAI2Gemini ¶
func StreamResponseOpenAI2Gemini(openAIResponse *dto.ChatCompletionsStreamResponse, info *relaycommon.RelayInfo) *dto.GeminiChatResponse
func SundaySearch ¶
func TokenRateLimitMember ¶
TokenRateLimitMember identifies one relay request inside a key's budgets. It is the request id the middleware and relay layers already carry, with a fallback for callers that never installed that middleware.
func TryTieredSettle ¶
func TryTieredSettle(relayInfo *relaycommon.RelayInfo, params billingexpr.TokenParams) (ok bool, quota int, result *billingexpr.TieredResult)
TryTieredSettle checks if the request uses tiered_expr billing and, if so, computes the actual quota using the captured BillingSnapshot. Returns:
- ok=true, quota, result when tiered billing applies
- ok=false, 0, nil when it doesn't (caller should fall through to existing logic)
func UnbindAccountOAuth ¶
func UnbindAccountOAuth(identity AuthIdentity, providerID int) error
func ValidUsage ¶
func ValidateAccountEmail ¶
ValidateAccountEmail is shared with registration mail delivery so binding cannot bypass the site's existing domain, alias and address-length rules.
func ValidateFlowAuthorization ¶
func ValidateFlowAuthorization(identity AuthIdentity, operation VerificationOperation, authorization *model.AuthFlowAuthorization) error
ValidateFlowAuthorization permits a dedicated configuration flow to outlive its consumed proof, while retaining its operation, session and method policy.
func ValidateLoginSession ¶
func ValidateLoginSession(identity AuthIdentity) (*model.UserSession, *model.UserBase, error)
func ValidateProxyURL ¶
ValidateProxyURL validates a channel proxy URL without connecting to it.
func VerifyLoginCode ¶
func VerifyLoginCode(token, code, ip, userAgent string) (*AuthBundle, *LegacyGitHubMigration, error)
func VerifyTwoFactorCode ¶
VerifyTwoFactorCode classifies the input before verification so one failed submission cannot increment the failure counter for both TOTP and backup codes.
func WaffoPancakeBuyerIdentityFromUserID ¶
WaffoPancakeBuyerIdentityFromUserID renders the canonical buyer identity for checkout. Webhook handlers compare against the value rendered here to reject identity mismatches, so both call sites must use this function.
func WrapAsViolationFeeGrokCSAM ¶
func WrapAsViolationFeeGrokCSAM(err *types.NewAPIError) *types.NewAPIError
func WriteRefreshCookie ¶
Types ¶
type AccountBindingContext ¶
type AccountUnbindingContext ¶
type AccountUnbindingContext struct {
ProviderID int `json:"provider_id"`
}
type AuthBundle ¶
type AuthBundle struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
AccessExpiresAt int64 `json:"access_expires_at"`
Session LoginSessionView `json:"session"`
RefreshToken string `json:"-"`
}
func AdvanceCurrentSessionSecurity ¶
func AdvanceCurrentSessionSecurity(identity AuthIdentity, reason string) (*AuthBundle, error)
AdvanceCurrentSessionSecurity increments the user's global auth version, preserves only the current browser session at a new session version and returns a replacement access token. Call after a successful 2FA/passkey security-setting mutation that did not already advance AuthVersion.
func AdvanceCurrentSessionToUserVersion ¶
func AdvanceCurrentSessionToUserVersion(identity AuthIdentity, reason string) (*AuthBundle, error)
AdvanceCurrentSessionToUserVersion is used when the security mutation and AuthVersion increment were committed in the same transaction (for example, a password change).
func CreateLoginSession ¶
func CreateLoginSession(userID int, loginMethod, ip, userAgent string) (*AuthBundle, error)
func CreateLoginSessionAtAuthVersion ¶
func CreateLoginSessionAtAuthVersion(userID int, expectedAuthVersion int64, loginMethod, ip, userAgent string) (*AuthBundle, error)
func RefreshLoginSession ¶
func RefreshLoginSession(rawRefreshToken, expectedSID, ip, userAgent string) (*AuthBundle, *model.User, error)
type AuthIdentity ¶
type AuthIdentity = model.AuthSessionIdentity
AuthIdentity is the server-validated identity attached to dashboard requests. Role, status and group are deliberately loaded from the user cache instead of JWT claims.
func ParseAccessToken ¶
func ParseAccessToken(raw string) (AuthIdentity, error)
func ParseDashboardAccessToken ¶
func ParseDashboardAccessToken(raw string) (identity AuthIdentity, internal bool, err error)
ParseDashboardAccessToken distinguishes new-api dashboard JWTs from opaque credentials. A token carrying the dashboard issuer, audience and a known token use is always treated as internal, even when its signature, lifetime or requested purpose is invalid, so it can never fall through to PAT or relay-token authentication.
func ValidateSessionReference ¶
func ValidateSessionReference(userID int, sid string) (AuthIdentity, error)
ValidateSessionReference validates a server-side flow bound to an existing dashboard session without requiring an access token on the callback request.
type BillingSession ¶
type BillingSession struct {
// contains filtered or unexported fields
}
BillingSession 封装单次请求的预扣费/结算/退款生命周期。 额度只从用户钱包余额预扣,按 token/用量计费。 实现 relaycommon.BillingSettler 接口。
func NewBillingSession ¶
func NewBillingSession(c *gin.Context, relayInfo *relaycommon.RelayInfo, preConsumedQuota int) (*BillingSession, *types.NewAPIError)
NewBillingSession 创建钱包计费会话并执行预扣费。
func (*BillingSession) GetPreConsumedQuota ¶
func (s *BillingSession) GetPreConsumedQuota() int
GetPreConsumedQuota 返回实际预扣的额度。
func (*BillingSession) NeedsRefund ¶
func (s *BillingSession) NeedsRefund() bool
NeedsRefund 返回是否存在需要退还的预扣状态。
func (*BillingSession) Refund ¶
func (s *BillingSession) Refund(c *gin.Context)
Refund 退还所有预扣费,幂等安全,异步执行。
func (*BillingSession) Reserve ¶
func (s *BillingSession) Reserve(targetQuota int) error
func (*BillingSession) Settle ¶
func (s *BillingSession) Settle(actualQuota int) error
Settle 根据实际消耗额度进行结算。 资金来源和令牌额度分两步提交:若资金来源已提交但令牌调整失败, 会标记 fundingSettled 防止 Refund 对已提交的资金来源执行退款。
type ChannelAffinityCacheStats ¶
type ChannelAffinityCacheStats struct {
Enabled bool `json:"enabled"`
Total int `json:"total"`
Unknown int `json:"unknown"`
ByRuleName map[string]int `json:"by_rule_name"`
CacheCapacity int `json:"cache_capacity"`
CacheAlgo string `json:"cache_algo"`
}
func GetChannelAffinityCacheStats ¶
func GetChannelAffinityCacheStats() ChannelAffinityCacheStats
type ChannelAffinityStatsContext ¶
type ChannelAffinityStatsContext struct {
RuleName string
UsingGroup string
KeyFingerprint string
TTLSeconds int64
}
func GetChannelAffinityStatsContext ¶
func GetChannelAffinityStatsContext(c *gin.Context) (ChannelAffinityStatsContext, bool)
type ChannelAffinityUsageCacheCounters ¶
type ChannelAffinityUsageCacheCounters struct {
CachedTokenRateMode string `json:"cached_token_rate_mode"`
Hit int64 `json:"hit"`
Total int64 `json:"total"`
WindowSeconds int64 `json:"window_seconds"`
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
TotalTokens int64 `json:"total_tokens"`
CachedTokens int64 `json:"cached_tokens"`
PromptCacheHitTokens int64 `json:"prompt_cache_hit_tokens"`
LastSeenAt int64 `json:"last_seen_at"`
}
type ChannelAffinityUsageCacheStats ¶
type ChannelAffinityUsageCacheStats struct {
RuleName string `json:"rule_name"`
UsingGroup string `json:"using_group"`
KeyFingerprint string `json:"key_fp"`
CachedTokenRateMode string `json:"cached_token_rate_mode"`
Hit int64 `json:"hit"`
Total int64 `json:"total"`
WindowSeconds int64 `json:"window_seconds"`
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
TotalTokens int64 `json:"total_tokens"`
CachedTokens int64 `json:"cached_tokens"`
PromptCacheHitTokens int64 `json:"prompt_cache_hit_tokens"`
LastSeenAt int64 `json:"last_seen_at"`
}
func GetChannelAffinityUsageCacheStats ¶
func GetChannelAffinityUsageCacheStats(ruleName, usingGroup, keyFp string) ChannelAffinityUsageCacheStats
type ChannelKeyReadContext ¶
type ChannelKeyReadContext struct {
ChannelID int `json:"channel_id"`
}
type ChannelSelectError ¶
type ChannelSelectError struct {
StatusCode int
Code types.ErrorCode
MessageID string
Params map[string]any
Message string
// FilterKind and Channel identify a candidate rejected by request filters.
FilterKind dto.ChannelFilterKind
Channel *model.Channel
// NoAvailableChannel marks the "no channel for this group and model"
// outcome, which the distributor reports as an unavailable model in the
// selected group.
NoAvailableChannel bool
}
ChannelSelectError explains why SelectChannelForRequest found no channel. Callers render it for their transport: the HTTP distributor localizes MessageID with its own helpers and the Responses WebSocket relay wraps it in a NewAPIError. Message is set instead of MessageID when the text is a fixed error code that clients match on.
func SelectChannelForRequest ¶
func SelectChannelForRequest(c *gin.Context, modelName string, retry *RetryParam) (*model.Channel, string, *ChannelSelectError)
SelectChannelForRequest resolves the channel for one attempt with the rules shared by the HTTP distributor and the Responses WebSocket relay: a pinned channel wins, then session affinity (first attempt only), then a random eligible channel; every candidate must satisfy the request's channel filters. The group the channel was chosen from is returned for auto-group callers. The caller still applies SetupContextForSelectedChannel.
type CodexCredentialRefreshOptions ¶
type CodexCredentialRefreshOptions struct {
ResetCaches bool
}
type CodexOAuthKey ¶
type CodexOAuthKey struct {
IDToken string `json:"id_token,omitempty"`
AccessToken string `json:"access_token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
AccountID string `json:"account_id,omitempty"`
LastRefresh string `json:"last_refresh,omitempty"`
Email string `json:"email,omitempty"`
Type string `json:"type,omitempty"`
Expired string `json:"expired,omitempty"`
}
func RefreshCodexChannelCredential ¶
func RefreshCodexChannelCredential(ctx context.Context, channelID int, opts CodexCredentialRefreshOptions) (*CodexOAuthKey, *model.Channel, error)
type CodexOAuthTokenResult ¶
func RefreshCodexOAuthToken ¶
func RefreshCodexOAuthToken(ctx context.Context, refreshToken string) (*CodexOAuthTokenResult, error)
type EmailBindingData ¶
type EmailBindingData struct {
FlowToken string `json:"flow_token"`
Email string `json:"email"`
CurrentEmail string `json:"current_email,omitempty"`
OldEmailRequired bool `json:"old_email_required"`
ExpiresAt int64 `json:"expires_at"`
ResendAt int64 `json:"resend_at"`
NotificationWarning bool `json:"notification_warning"`
}
func ResendAccountEmailBinding ¶
func ResendAccountEmailBinding(identity AuthIdentity, token string) (*EmailBindingData, error)
func StartEmailBinding ¶
func StartEmailBinding(identity AuthIdentity, authorization *model.AuthFlowAuthorization, email string) (*EmailBindingData, error)
type HTTPTransportPolicy ¶
type HTTPTransportPolicy struct {
Protocol string // dto.HTTPProtocolAuto or dto.HTTPProtocolHTTP1
Shards int // 1..dto.MaxHTTP2ConnectionShards
}
HTTPTransportPolicy is the runtime-normalized outbound HTTP transport policy for a channel. Unknown or out-of-range stored values are clamped safely.
func NormalizeHTTPTransportPolicy ¶
func NormalizeHTTPTransportPolicy(settings dto.ChannelSettings) HTTPTransportPolicy
NormalizeHTTPTransportPolicy converts channel settings into a safe runtime policy. Invalid stored values never panic; they clamp to defaults and warn once per bad value.
func (HTTPTransportPolicy) String ¶
func (p HTTPTransportPolicy) String() string
type LegacyGitHubMigration ¶
LegacyGitHubMigration is a GitHub binding rewrite from the stored login name to the numeric account ID. On the login path it waits for the login verification and is written in the transaction that issues the session.
type LogCleanupPayload ¶
type LogCleanupResult ¶
type LogCleanupState ¶
type LoginChallenge ¶
type LoginChallenge struct {
RequireVerification bool `json:"require_verification"`
FlowToken string `json:"flow_token"`
ExpiresAt int64 `json:"expires_at"`
Methods []VerificationMethodOption `json:"methods"`
}
func StartLoginVerification ¶
func StartLoginVerification(user *model.User, loginMethod string, migration *LegacyGitHubMigration) (*LoginChallenge, error)
type LoginSessionView ¶
type LoginSessionView struct {
SID string `json:"sid"`
Current bool `json:"current"`
LoginMethod string `json:"login_method"`
IP string `json:"ip"`
UserAgent string `json:"user_agent"`
CreatedAt int64 `json:"created_at"`
LastActiveAt int64 `json:"last_active_at"`
ExpiresAt int64 `json:"expires_at"`
}
func ListLoginSessions ¶
func ListLoginSessions(userID int, currentSID string) ([]LoginSessionView, error)
type LoginVerification ¶
type LoginVerification struct {
Flow *model.AuthFlow
State *model.UserVerificationState
// contains filtered or unexported fields
}
LoginVerification is server-owned state read from a primary-authenticated flow. It is never constructed from a user ID or an authentication claim in a request.
func RequireLoginVerification ¶
func RequireLoginVerification(token, method string) (*LoginVerification, error)
type ModelHistoryModel ¶
type ModelHistoryPoint ¶
type ModelHistorySeries ¶
type ModelHistorySeries struct {
Points []ModelHistoryPoint `json:"points"`
Models []ModelHistoryModel `json:"models"`
Buckets int `json:"buckets"`
// Timeline is the full x-axis: Buckets is its length.
Timeline []RankingBucket `json:"timeline"`
}
type OAuthVerificationFlow ¶
type OAuthVerificationFlow struct {
Scope string `json:"scope"`
ContextHash string `json:"context_hash"`
ProviderUserID string `json:"provider_user_id"`
UserAuthVersion int64 `json:"auth_version"`
SessionVersion int64 `json:"session_version"`
}
func StartOAuthVerification ¶
func StartOAuthVerification(identity AuthIdentity, operation VerificationOperation, provider string) (*OAuthVerificationFlow, error)
type PolicyDecision ¶
type PolicyDecision struct {
Action string `json:"action"`
Reason string `json:"reason"`
Source string `json:"source"`
}
func DecideRelayRetry ¶
func DecideRelayRetry(c *gin.Context, err *types.NewAPIError, retryTimes int) PolicyDecision
DecideRelayRetry is the single retry decision for relay attempts. The reason is recorded in the request policy decision events of the log details.
SkipRetry outranks the channel: prefix: a caller that sets it declares a condition every channel of the type would repeat (the client asked for a format this channel type does not serve, the channel's model mapping or param override does not fit), so it is not evidence about channel health and must not be retried. Deciding on the prefix first used to retry those errors RetryTimes times against the same channel.
type PolicyEvent ¶
type PolicyEvent struct {
Attempt int `json:"attempt"`
ChannelID int `json:"channel_id,omitempty"`
Group string `json:"group,omitempty"`
Rule string `json:"rule,omitempty"`
Status int `json:"status,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
ErrorSource string `json:"error_source,omitempty"`
ElapsedMS int64 `json:"elapsed_ms"`
Decision PolicyDecision `json:"decision"`
Health string `json:"health,omitempty"`
}
type QuotaInfo ¶
type QuotaInfo struct {
InputDetails TokenDetails
OutputDetails TokenDetails
ModelName string
UsePrice bool
ModelPrice float64
ModelRatio float64
GroupRatio float64
}
type RankedModel ¶
type RankedModel struct {
Rank int `json:"rank"`
PreviousRank *int `json:"previous_rank,omitempty"`
ModelName string `json:"model_name"`
Vendor string `json:"vendor"`
VendorIcon string `json:"vendor_icon,omitempty"`
Category string `json:"category"`
TotalTokens int64 `json:"total_tokens"`
GrowthPct float64 `json:"growth_pct"`
}
type RankedVendor ¶
type RankingBucket ¶
RankingBucket marks one bucket boundary of the requested period. Every boundary the range touches is listed, including the ones without traffic, so the histories can keep idle stretches on the x-axis.
type RankingMover ¶
type RankingsResponse ¶
type RankingsResponse struct {
Models []RankedModel `json:"models"`
Vendors []RankedVendor `json:"vendors"`
TopMovers []RankingMover `json:"top_movers"`
TopDroppers []RankingMover `json:"top_droppers"`
ModelsHistory ModelHistorySeries `json:"models_history"`
}
func GetRankingsSnapshot ¶
func GetRankingsSnapshot(period string) (*RankingsResponse, error)
type RequestPolicyState ¶
type RequestPolicyState struct {
FinalLogged bool
StartedAt time.Time
Attempts int
SelectedGroup string
SessionMode string
SessionModeSource string
RuleName string
Successful bool
OutcomeRecorded bool
// contains filtered or unexported fields
}
RequestPolicyState records how one request was routed so administrators can read the decision flow in the log details. Channel selection and the retry decision stay in the relay flows; this state only records them.
func RequestPolicy ¶
func RequestPolicy(c *gin.Context) *RequestPolicyState
func (*RequestPolicyState) AddEvent ¶
func (s *RequestPolicyState) AddEvent(event PolicyEvent)
func (*RequestPolicyState) BeginAttempt ¶
func (s *RequestPolicyState) BeginAttempt(channel *model.Channel, group string)
func (*RequestPolicyState) Events ¶
func (s *RequestPolicyState) Events() []PolicyEvent
type ResponsesUsageAccumulator ¶
type ResponsesUsageAccumulator struct {
// contains filtered or unexported fields
}
ResponsesUsageAccumulator owns the accounting facts for one Responses stream. HTTP SSE and WebSocket transports feed the same events into it, then settle Finish's usage through the normal text billing path, including interrupted streams. Observe and Finish must be called by the same stream owner.
func NewResponsesUsageAccumulator ¶
func NewResponsesUsageAccumulator(info *relaycommon.RelayInfo) *ResponsesUsageAccumulator
func (*ResponsesUsageAccumulator) Finish ¶
func (a *ResponsesUsageAccumulator) Finish() *dto.Usage
func (*ResponsesUsageAccumulator) Observe ¶
func (a *ResponsesUsageAccumulator) Observe(event *dto.ResponsesStreamResponse)
type RetryParam ¶
type RetryParam struct {
Ctx *gin.Context
TokenGroup string
ModelName string
RequestPath string
Retry *int
// contains filtered or unexported fields
}
func (*RetryParam) GetRetry ¶
func (p *RetryParam) GetRetry() int
func (*RetryParam) IncreaseRetry ¶
func (p *RetryParam) IncreaseRetry()
func (*RetryParam) ResetRetryNextTry ¶
func (p *RetryParam) ResetRetryNextTry()
func (*RetryParam) SetRetry ¶
func (p *RetryParam) SetRetry(retry int)
type ScheduledSystemTaskHandler ¶
type ScheduledSystemTaskHandler interface {
SystemTaskHandler
Enabled() bool
Interval() time.Duration
NewPayload() any
}
ScheduledSystemTaskHandler is a SystemTaskHandler that the scheduler also creates periodically when enabled and the configured interval has elapsed since the last run.
type SecurityProof ¶
type SecurityProof struct {
ProofToken string `json:"proof_token"`
ExpiresAt int64 `json:"expires_at"`
Method string `json:"method"`
Scope string `json:"scope"`
}
func CompleteSecurityVerification ¶
func CompleteSecurityVerification(identity AuthIdentity, binding VerificationBinding, method string) (*SecurityProof, error)
CompleteSecurityVerification runs after the concrete authentication ceremony. Recheck the session and policy after potentially slow external authentication.
func FinishOAuthVerification ¶
func FinishOAuthVerification(identity AuthIdentity, provider, actualUserID string, flow *OAuthVerificationFlow) (*SecurityProof, error)
FinishOAuthVerification only verifies an existing binding. It deliberately never calls OAuth's login or find-or-create-user paths.
func VerifySecurityInput ¶
func VerifySecurityInput(identity AuthIdentity, input VerificationInput) (*SecurityProof, error)
type SystemInstanceHostInfo ¶
type SystemInstanceHostInfo struct {
Hostname string `json:"hostname"`
}
type SystemInstanceInfo ¶
type SystemInstanceInfo struct {
SchemaVersion int `json:"schema_version"`
Node common.NodeIdentity `json:"node"`
Role SystemInstanceRoleInfo `json:"role"`
Runtime SystemInstanceRuntimeInfo `json:"runtime"`
Host SystemInstanceHostInfo `json:"host"`
Resources SystemInstanceResources `json:"resources"`
Extra map[string]any `json:"extra,omitempty"`
}
type SystemInstanceResourceUsage ¶
type SystemInstanceResourceUsage struct {
UsagePercent float64 `json:"usage_percent"`
}
type SystemInstanceResources ¶
type SystemInstanceResources struct {
CPU SystemInstanceResourceUsage `json:"cpu"`
Memory SystemInstanceResourceUsage `json:"memory"`
Storage SystemInstanceStorageMetrics `json:"storage"`
}
type SystemInstanceRoleInfo ¶
type SystemInstanceRoleInfo struct {
IsMaster bool `json:"is_master"`
}
type SystemTaskHandler ¶
type SystemTaskHandler interface {
Type() string
Run(ctx context.Context, task *model.SystemTask, runnerID string)
}
SystemTaskHandler executes a claimed task of a specific type. Run owns the task lifecycle from claim to terminal state: it MUST call model.FinishSystemTask (succeeded/failed) before returning and MUST honor ctx cancellation, which the runner triggers if the per-type lock is lost.
type SystemTaskProgress ¶
type SystemTaskProgress struct {
Total int `json:"total"`
Processed int `json:"processed"`
Progress int `json:"progress"`
}
SystemTaskProgress is the state shape used by handlers that report percentage progress (channel test, model update). The frontend reads the progress field (0-100) to render a per-task progress indicator.
type TieredResultWrapper ¶
type TieredResultWrapper = billingexpr.TieredResult
TieredResultWrapper wraps billingexpr.TieredResult for use at the service layer.
type TokenBudgetDecision ¶
TokenBudgetDecision is one token budget admission result.
func ReserveTokenBudget ¶
func ReserveTokenBudget(c *gin.Context, relayInfo *relaycommon.RelayInfo, cost int) (TokenBudgetDecision, bool)
ReserveTokenBudget charges the key's per-minute token budget with the request's admission estimate. allowed=false means the request would exceed the budget and must be rejected. A limiter error fails open so an unavailable Redis never takes the gateway down.
type TokenDetails ¶
type TokenRateLimits ¶
TokenRateLimits are the per-key limits the token authenticator stored on the request context. Zero means the dimension is unlimited.
func GetTokenRateLimits ¶
func GetTokenRateLimits(c *gin.Context) TokenRateLimits
type ToolSurchargeItem ¶
type ToolSurchargeItem struct {
Name string `json:"name"`
Count int `json:"count"`
Price float64 `json:"price"`
}
ToolSurchargeItem is one billable tool-call line for consume logs.
type TwoFASetup ¶
type TwoFASetup struct {
Secret string `json:"secret"`
QRCodeData string `json:"qr_code_data"`
BackupCodes []string `json:"backup_codes"`
FlowToken string `json:"flow_token"`
ExpiresAt int64 `json:"expires_at"`
}
func StartTwoFASetup ¶
func StartTwoFASetup(identity AuthIdentity, authorization *model.AuthFlowAuthorization) (*TwoFASetup, error)
type VendorSharePoint ¶
type VendorSharePoint struct {
}
type VendorShareSeries ¶
type VendorShareSeries struct {
Timeline []RankingBucket `json:"timeline"`
}
type VendorShareVendor ¶
type VendorShareVendor struct {
}
type VerificationBinding ¶
type VerificationBinding struct {
Scope string `json:"scope"`
ContextHash string `json:"context_hash"`
}
VerificationBinding contains no original operation parameters. It can safely travel through a signed proof or a server-owned interactive verification flow.
func BindVerificationOperation ¶
func BindVerificationOperation(operation VerificationOperation) (VerificationBinding, error)
type VerificationInput ¶
type VerificationInput struct {
Method string `json:"method"`
Scope string `json:"scope"`
Context json.RawMessage `json:"context,omitempty"`
Code string `json:"code,omitempty"`
Password string `json:"password,omitempty"`
PasswordEncrypted string `json:"password_encrypted,omitempty"`
EncryptionKeyID string `json:"encryption_key_id,omitempty"`
}
type VerificationOperation ¶
type VerificationOperation struct {
Scope string `json:"scope"`
Context json.RawMessage `json:"context,omitempty"`
}
VerificationOperation describes the action being authorized, independently of its authentication method. Each scope owns a strict, normalized context schema.
type VerificationRequirements ¶
type VerificationRequirements struct {
Scope string `json:"scope"`
Methods []VerificationMethodOption `json:"methods"`
OAuthProviders []VerificationOAuthProvider `json:"oauth_providers"`
PasswordEncryptionEnabled bool `json:"password_encryption_enabled"`
}
func GetVerificationRequirements ¶
func GetVerificationRequirements(identity AuthIdentity, scope string) (*VerificationRequirements, error)
func RequireVerificationMethod ¶
func RequireVerificationMethod(identity AuthIdentity, scope, method string) (*VerificationRequirements, error)
type WaffoPancakeCatalog ¶
type WaffoPancakeCatalog struct {
Stores []WaffoPancakeCatalogStore `json:"stores"`
}
func ListWaffoPancakeCatalog ¶
func ListWaffoPancakeCatalog(ctx context.Context, merchantID, privateKey string) (*WaffoPancakeCatalog, error)
ListWaffoPancakeCatalog queries Pancake's GraphQL `stores` for the merchant's stores + onetime products. A successful call also proves the supplied credentials authenticate (doubles as a credential probe).
type WaffoPancakeCatalogStore ¶
type WaffoPancakeCatalogStore struct {
ID string `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
ProdEnabled bool `json:"prodEnabled"`
OnetimeProducts []WaffoPancakeCatalogProduct `json:"onetimeProducts"`
}
WaffoPancakeCatalogStore nests its OnetimeProducts so the UI can render a dependent store→product select without a second round-trip.
type WaffoPancakeCheckoutSession ¶
type WaffoPancakeCheckoutSession struct {
SessionID string
CheckoutURL string
ExpiresAt string
OrderID string
Token string
TokenExpiresAt string
}
WaffoPancakeCheckoutSession is the response of CreateWaffoPancakeCheckoutSession. CheckoutURL already carries the `#token=...` fragment; Token / TokenExpiresAt are exposed separately for self-service flows driven from new-api's own UI.
func CreateWaffoPancakeCheckoutSession ¶
func CreateWaffoPancakeCheckoutSession(ctx context.Context, params *WaffoPancakeCreateSessionParams) (*WaffoPancakeCheckoutSession, error)
CreateWaffoPancakeCheckoutSession creates an Authenticated-mode checkout session: the order is bound to BuyerIdentity (stable per user) so it stays attributable even if the buyer edits the email on Waffo's checkout form.
type WaffoPancakeCreateSessionParams ¶
type WaffoPancakeCreateSessionParams struct {
ProductID string
BuyerIdentity string
PriceSnapshot *WaffoPancakePriceSnapshot
BuyerEmail string
ExpiresInSeconds *int
OrderMerchantExternalID string
}
WaffoPancakeCreateSessionParams is the input to CreateWaffoPancakeCheckoutSession. BuyerIdentity must be stable per user (see WaffoPancakeBuyerIdentityFromUserID). OrderMerchantExternalID = our trade_no; Pancake echoes it back in webhooks.
type WaffoPancakePairResult ¶
type WaffoPancakePairResult struct {
StoreID string
StoreName string
ProductID string
ProductName string
OrphanStore bool
}
WaffoPancakePairResult is the response of CreateWaffoPancakePrimaryPair. When OrphanStore is true the store was created but the product wasn't, so the caller can surface a partial-failure message with StoreID.
func CreateWaffoPancakePrimaryPair ¶
func CreateWaffoPancakePrimaryPair(ctx context.Context, merchantID, privateKey, returnURL string) (*WaffoPancakePairResult, error)
CreateWaffoPancakePrimaryPair mints a Store + OnetimeProduct in one round-trip — the canonical "+ Create" entry point. Nothing is persisted to settings; the operator's final Save commits the chosen IDs.
type WaffoPancakePriceSnapshot ¶
WaffoPancakePriceSnapshot is the per-session price override sent with checkout.
type WaffoPancakeWebhookData ¶
type WaffoPancakeWebhookEvent ¶
type WaffoPancakeWebhookEvent struct {
ID string
Timestamp string
EventType string
EventID string
StoreID string
Mode string
Data WaffoPancakeWebhookData
}
WaffoPancakeWebhookEvent mirrors the SDK's WebhookEvent shape using plain strings so controllers don't have to import the SDK package.
func VerifyConfiguredWaffoPancakeWebhook ¶
func VerifyConfiguredWaffoPancakeWebhook(payload string, signatureHeader string) (*WaffoPancakeWebhookEvent, error)
VerifyConfiguredWaffoPancakeWebhook verifies the signature header. The SDK picks the matching test / prod public key from the payload's `mode` field.
func (*WaffoPancakeWebhookEvent) NormalizedEventType ¶
func (e *WaffoPancakeWebhookEvent) NormalizedEventType() string
NormalizedEventType returns the event type or empty string for a nil event.
type WalletFunding ¶
type WalletFunding struct {
// contains filtered or unexported fields
}
WalletFunding 从用户钱包余额预扣、补扣与退还额度。 额度只来自钱包余额,按 token/用量计费。
func (*WalletFunding) PreConsume ¶
func (w *WalletFunding) PreConsume(amount int) error
func (*WalletFunding) Refund ¶
func (w *WalletFunding) Refund() error
func (*WalletFunding) Settle ¶
func (w *WalletFunding) Settle(delta int) error
type WebhookPayload ¶
type WebhookPayload struct {
Type string `json:"type"`
Title string `json:"title"`
Content string `json:"content"`
Values []any `json:"values,omitempty"`
Timestamp int64 `json:"timestamp"`
}
WebhookPayload webhook 通知的负载数据
type WorkerRequest ¶
type WorkerRequest struct {
URL string `json:"url"`
Key string `json:"key"`
Method string `json:"method,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Body json.RawMessage `json:"body,omitempty"`
}
WorkerRequest Worker请求的数据结构
Source Files
¶
- account_security.go
- audio.go
- auth_cleanup.go
- auth_session.go
- auth_token.go
- billing.go
- billing_session.go
- billing_usage.go
- channel.go
- channel_affinity.go
- channel_select.go
- codex_channel_models.go
- codex_credential_refresh.go
- codex_credential_refresh_task.go
- codex_models.go
- codex_oauth.go
- codex_wham_usage.go
- convert.go
- download.go
- email_binding.go
- epay.go
- error.go
- file_decoder.go
- file_service.go
- funding_source.go
- group.go
- http.go
- http_client.go
- http_transport_policy.go
- http_transport_sharded.go
- image.go
- image_billing.go
- log_info_generate.go
- login_verification.go
- notify-limit.go
- oauth_verification.go
- openai_chat_responses_compat.go
- openai_chat_responses_mode.go
- protected_fetch_client.go
- quota.go
- rankings.go
- relay_error.go
- request_converter.go
- request_policy.go
- response_converter.go
- responses_usage.go
- return_path.go
- security_verification.go
- sensitive.go
- str.go
- system_instance.go
- system_task.go
- text_quota.go
- tiered_settle.go
- token_counter.go
- token_estimator.go
- token_rate_limit.go
- tokenizer.go
- twofa.go
- usage_helpr.go
- user_notify.go
- violation_fee.go
- waffo_pancake.go
- webhook.go
- ws_close.go