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 AppendTaskPluginAuditInfo(other *model.LogOther, snapshot *model.TaskPluginSnapshot)
- func AppendTaskPluginContextAuditInfo(ctx *gin.Context, other *model.LogOther)
- func AppendTaskPluginIdentityFilter(c *gin.Context, pluginKey string)
- func ApplyChannelAffinityOverrideTemplate(c *gin.Context, paramOverride map[string]interface{}) (map[string]interface{}, bool)
- func AuthSessionErrorCode(err error) (int, string)
- func BuildTaskArtifactContentURL(taskID, artifactKey string) (string, error)
- func BuildTaskPluginView(task *model.Task) (dto.TaskView, error)
- 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 CloseResponseBodyGracefully(httpResponse *http.Response)
- func ConsumeCodexWhamRateLimitResetCredit(ctx context.Context, client *http.Client, baseURL string, accessToken string, ...) (statusCode int, body []byte, err 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 ConvertSimpleChangeParams(content string) *dto.MidjourneyRequest
- 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 CoverPlusActionToNormalAction(midjRequest *dto.MidjourneyRequest) *dto.MidjourneyResponse
- func CoverTaskActionToModelName(platform constant.TaskPlatform, action string) string
- func CovertMjpActionToModelName(mjAction string) string
- func CreateWaffoPancakePrimaryProduct(ctx context.Context, merchantID, privateKey, storeID, returnURL string) (string, error)
- func CreateWaffoPancakePrimaryStore(ctx context.Context, merchantID, privateKey string) (string, error)
- func CreateWaffoPancakeProductForPlan(ctx context.Context, ...) (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 DispatchPlatformUpdate(ctx context.Context, platform constant.TaskPlatform, ...)
- func DoDownloadRequest(originUrl string, reason ...string) (resp *http.Response, err error)
- func DoMidjourneyHttpRequest(c *gin.Context, timeout time.Duration, fullRequestURL string) (*dto.MidjourneyResponseWithStatusCode, []byte, error)
- func DoWorkerRequest(req *WorkerRequest) (*http.Response, error)
- 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 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 GetMjRequestModel(relayMode int, midjRequest *dto.MidjourneyRequest) (string, *dto.MidjourneyResponse, bool)
- func GetPreferredChannelByAffinity(c *gin.Context, modelName string, usingGroup string) (int, bool)
- func GetRequestAutoGroups(c *gin.Context, userGroup string) []string
- func GetSSRFProtectedHTTPClient() *http.Client
- 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, scopes []string) (string, int64, error)
- func IssueTaskArtifactAccess(taskID, artifactKey string) (string, error)
- func LoadFileSource(c *gin.Context, source types.FileSource, reason ...string) (*types.CachedFileData, error)
- func LogTaskConsumption(c *gin.Context, info *relaycommon.RelayInfo, task *model.Task)
- func MarkChannelAffinityUsed(c *gin.Context, selectedGroup string, channelID int)
- func MidjourneyErrorWithStatusCodeWrapper(code int, desc string, statusCode int) *taskdto.MidjourneyResponseWithStatusCode
- func MidjourneyErrorWrapper(code int, desc string) *taskdto.MidjourneyResponse
- 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 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 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 PrepareMidjourneyTaskBilling(relayInfo *relaycommon.RelayInfo, task *model.Midjourney, quota int, ...) (bool, error)
- func PrepareTieredBillingForSelectedGroup(c *gin.Context, relayInfo *relaycommon.RelayInfo) *types.NewAPIError
- func RecalculateTaskQuota(ctx context.Context, task *model.Task, actualQuota int, reason string, ...)
- func RecalculateTaskQuotaByTokens(ctx context.Context, task *model.Task, totalTokens int) bool
- func RecordChannelAffinity(c *gin.Context, channelID int)
- func RefreshTokenSID(rawRefreshToken string) (string, bool)
- func RefundMidjourneyQuota(ctx context.Context, task *model.Midjourney, reason string) bool
- func RefundTaskQuota(ctx context.Context, task *model.Task, reason string) bool
- func RegisterSystemTaskHandler(h SystemTaskHandler)
- func RelayErrorHandler(ctx context.Context, resp *http.Response, showBodyWhenFail bool) (newApiErr *types.NewAPIError)
- func RemoveDuplicate(s []string) []string
- func ReportCurrentSystemInstance() error
- func ResetProxyClientCache()
- func ResetStatusCode(newApiErr *types.NewAPIError, statusCodeMappingStr string)
- func ResolveWaffoPancakeSubscriptionTradeNo(event *WaffoPancakeWebhookEvent) (string, error)
- 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 SettleMidjourneyTaskBilling(relayInfo *relaycommon.RelayInfo, task *model.Midjourney, prepared bool) (bool, error)
- 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 ShouldSkipRetryAfterChannelAffinityFailure(c *gin.Context) bool
- func StartAuthArtifactCleanup()
- func StartCodexCredentialAutoRefreshTask()
- func StartLogCleanupTask(targetTimestamp int64) (*model.SystemTask, error)
- func StartSubscriptionQuotaResetTask()
- 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 TaskErrorFromAPIError(apiErr *types.NewAPIError) *taskdto.TaskError
- func TaskErrorWrapper(err error, code string, statusCode int) *taskdto.TaskError
- func TaskErrorWrapperLocal(err error, code string, statusCode int) *taskdto.TaskError
- func TaskExecutionSnapshotFromContext(ctx *gin.Context) *model.TaskExecutionSnapshot
- func TryTieredSettle(relayInfo *relaycommon.RelayInfo, params billingexpr.TokenParams) (ok bool, quota int, result *billingexpr.TieredResult)
- func UpdateBatchTasks(ctx context.Context, adaptor BatchTaskPollingAdaptor, ...) error
- func UpdateVideoTasks(ctx context.Context, platform constant.TaskPlatform, ...) error
- func ValidUsage(usage *dto.Usage) bool
- func ValidateLoginSession(identity AuthIdentity) (*model.UserSession, *model.UserBase, error)
- func ValidateProxyURL(rawProxyURL string) error
- func ValidateSSRFProtectedFetchURL(urlStr string) error
- func ValidateTaskArtifactBaseURL(raw string) error
- func VerifySecurityProof(raw string, identity AuthIdentity, requiredScope string, ...) (string, error)
- func VerifyTaskArtifactAccess(access, taskID, artifactKey string) bool
- func WaffoPancakeBuyerIdentityFromUserID(userID int) string
- func WrapAsViolationFeeGrokCSAM(err *types.NewAPIError) *types.NewAPIError
- func WriteRefreshCookie(c *gin.Context, rawToken string)
- 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 BatchTaskPollingAdaptor
- type BatchTaskResult
- type BillingSession
- type ChannelAffinityCacheStats
- type ChannelAffinityStatsContext
- type ChannelAffinityUsageCacheCounters
- type ChannelAffinityUsageCacheStats
- type CodexCredentialRefreshOptions
- type CodexOAuthKey
- type CodexOAuthTokenResult
- type FundingSource
- type HTTPTransportPolicy
- type LogCleanupPayload
- type LogCleanupResult
- type LogCleanupState
- type LoginSessionView
- type ModelHistoryModel
- type ModelHistoryPoint
- type ModelHistorySeries
- type Provider
- type QuotaInfo
- type RankedModel
- type RankedVendor
- type RankingMover
- type RankingsResponse
- type RetryParam
- type ScheduledSystemTaskHandler
- type StoredArtifactRef
- type SubscriptionFunding
- type SystemInstanceHostInfo
- type SystemInstanceInfo
- type SystemInstanceResourceUsage
- type SystemInstanceResources
- type SystemInstanceRoleInfo
- type SystemInstanceRuntimeInfo
- type SystemInstanceStorageMetrics
- type SystemTaskHandler
- type SystemTaskProgress
- type TaskArtifactStore
- type TaskPollSummary
- type TaskPollingAdaptor
- type TieredResultWrapper
- type TokenDetails
- type ToolSurchargeItem
- type VendorSharePoint
- type VendorShareSeries
- type VendorShareVendor
- 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 = 5 * time.Minute LoginSessionTTL = 30 * 24 * time.Hour RefreshReplayWindow = 30 * time.Second )
const ( BillingSourceWallet = "wallet" BillingSourceSubscription = "subscription" )
const ( ViolationFeeCodePrefix = "violation_fee." CSAMViolationMarker = "Failed check: SAFETY_CHECK_TYPE" ContentViolatesUsageMarker = "Content violates usage guidelines" )
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.
const (
TaskArtifactAccessQueryParameter = "access"
)
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") )
var ErrInsufficientWalletQuota = errors.New("wallet quota insufficient")
ErrInsufficientWalletQuota 钱包原子预扣失败(余额不足),未发生任何扣减。 BillingSession 据此映射为 ErrorCodeInsufficientUserQuota, 使 wallet_first 等计费偏好可以回退到订阅。
var ErrTaskArtifactAccessInvalid = errors.New("task artifact access is invalid")
var ErrTaskArtifactStoreDisabled = errors.New("task artifact store is disabled")
var GetTaskAdaptorFunc func(platform constant.TaskPlatform) TaskPollingAdaptor
GetTaskAdaptorFunc 由 main 包注入,用于获取指定平台的任务适配器。 打破 service -> relay -> relay/channel -> service 的循环依赖。
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 AppendTaskPluginAuditInfo ¶
func AppendTaskPluginAuditInfo(other *model.LogOther, snapshot *model.TaskPluginSnapshot)
AppendTaskPluginAuditInfo writes role-separated, credential-free plugin provenance into a usage log.
func AppendTaskPluginContextAuditInfo ¶
AppendTaskPluginContextAuditInfo is used before a task row exists, such as an upstream submission error log.
func ApplyChannelAffinityOverrideTemplate ¶ added in v0.11.2
func ApplyChannelAffinityOverrideTemplate(c *gin.Context, paramOverride map[string]interface{}) (map[string]interface{}, bool)
ApplyChannelAffinityOverrideTemplate merges per-rule channel override templates onto the selected channel override config.
func AuthSessionErrorCode ¶
func BuildTaskArtifactContentURL ¶
BuildTaskArtifactContentURL returns an absolute, long-lived capability URL. TaskPublicAddress wins when configured; ServerAddress is the only fallback. Request Host headers are intentionally not involved.
func BuildTaskPluginView ¶
BuildTaskPluginView converts a persisted task into the deliberately narrow public shape permitted at JavaScript plugin boundaries.
func BuildTieredTokenParams ¶ added in v0.13.0
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 ¶ added in v0.10.8
CleanupFileSources 清理请求中所有注册的 FileSource 应在请求结束时调用(通常由中间件自动调用)
func ClearChannelAffinityCacheAll ¶
func ClearChannelAffinityCacheAll() int
func ClearRefreshCookie ¶
func ConvertRequest ¶
func ConvertRequest(c *gin.Context, info *relaycommon.RelayInfo, target types.RelayFormat, request any) (*relayconvert.RequestResult, error)
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 ConvertSimpleChangeParams ¶
func ConvertSimpleChangeParams(content string) *dto.MidjourneyRequest
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 CoverPlusActionToNormalAction ¶
func CoverPlusActionToNormalAction(midjRequest *dto.MidjourneyRequest) *dto.MidjourneyResponse
func CoverTaskActionToModelName ¶
func CoverTaskActionToModelName(platform constant.TaskPlatform, action string) string
func CovertMjpActionToModelName ¶ added in v0.11.0
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 CreateWaffoPancakeProductForPlan ¶
func CreateWaffoPancakeProductForPlan(ctx context.Context, merchantID, privateKey, storeID, name, amount, returnURL string) (string, error)
CreateWaffoPancakeProductForPlan mints (and publishes) a Pancake OnetimeProduct priced at `amount` USD, used as a subscription plan's SubscriptionPlan.WaffoPancakeProductId.
OnetimeProduct (not SubscriptionProduct) because new-api has no renewal- event handling; Pancake auto-renewing without new-api extending user access would be a UX divergence. Revisit if renewal handling is added.
func DecodeBase64AudioData ¶
func DecodeBase64ImageData ¶
return image.Config, format, clean base64 string, error
func DetectFileType ¶ added in v0.10.8
DetectFileType 检测文件类型
func DisableChannel ¶
func DisableChannel(channelError types.ChannelError, reason string)
disable & notify
func DispatchPlatformUpdate ¶ added in v0.11.0
func DispatchPlatformUpdate(ctx context.Context, platform constant.TaskPlatform, taskChannelM map[int][]string, taskM map[string]*model.Task)
DispatchPlatformUpdate 按平台分发轮询更新
func DoDownloadRequest ¶
func DoMidjourneyHttpRequest ¶
func DoWorkerRequest ¶
func DoWorkerRequest(req *WorkerRequest) (*http.Response, error)
DoWorkerRequest 通过Worker发送请求
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 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 ¶ added in v0.10.8
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 顺序获取各分组启用的模型并去重
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 ¶ added in v0.10.8
GetImageConfig 获取图片配置
func GetImageFromUrl ¶
GetImageFromUrl 获取图片的类型和base64编码的数据
func GetMimeType ¶ added in v0.10.8
GetMimeType 获取文件的 MIME 类型
func GetMimeTypeByExtension ¶
func GetMjRequestModel ¶
func GetMjRequestModel(relayMode int, midjRequest *dto.MidjourneyRequest) (string, *dto.MidjourneyResponse, bool)
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 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 ¶ added in v0.13.0
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 IssueTaskArtifactAccess ¶
IssueTaskArtifactAccess creates a stable capability bound to exactly one public task ID and artifact key. It contains no user or upstream data.
func LoadFileSource ¶ added in v0.10.8
func LoadFileSource(c *gin.Context, source types.FileSource, reason ...string) (*types.CachedFileData, error)
LoadFileSource 加载文件源数据 这是统一的入口,会自动处理缓存和不同的来源类型
func LogTaskConsumption ¶ added in v0.11.0
LogTaskConsumption 记录任务消费日志和统计信息(仅记录,不涉及实际扣费)。 实际扣费已由 BillingSession(PreConsumeBilling + SettleBilling)完成。
func MarkChannelAffinityUsed ¶
func MidjourneyErrorWithStatusCodeWrapper ¶
func MidjourneyErrorWithStatusCodeWrapper(code int, desc string, statusCode int) *taskdto.MidjourneyResponseWithStatusCode
func MidjourneyErrorWrapper ¶
func MidjourneyErrorWrapper(code int, desc string) *taskdto.MidjourneyResponse
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 NormalizeCacheCreationSplit ¶ added in v0.12.2
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 NotifyRootUser ¶
func NotifyUpstreamModelUpdateWatchers ¶ added in v0.11.2
func NotifyUser ¶
func ObserveChannelAffinityUsageCacheByRelayFormat ¶ added in v0.11.0
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 PaymentReturnURL ¶
func PostAudioConsumeQuota ¶
func PostConsumeQuota ¶
func PostTextConsumeQuota ¶ added in v0.11.9
func PostWssConsumeQuota ¶
func PostWssConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, modelName string, usage *dto.RealtimeUsage, extraContent string)
func PreConsumeBilling ¶ added in v0.10.8
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 PrepareMidjourneyTaskBilling ¶
func PrepareMidjourneyTaskBilling(relayInfo *relaycommon.RelayInfo, task *model.Midjourney, quota int, shouldBill bool) (bool, error)
PrepareMidjourneyTaskBilling sets the durable refund marker before the task is inserted.
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 RecalculateTaskQuota ¶ added in v0.11.0
func RecalculateTaskQuota(ctx context.Context, task *model.Task, actualQuota int, reason string, clamps ...*common.QuotaClamp)
RecalculateTaskQuota 通用的异步差额结算。 actualQuota 是任务完成后的实际应扣额度,与预扣额度 (task.Quota) 做差额结算。 reason 用于日志记录(例如 "token重算" 或 "adaptor调整")。 clamps 可选:若计算 actualQuota 时发生额度饱和,将其记入日志 admin_info(仅管理员可见)。
func RecalculateTaskQuotaByTokens ¶ added in v0.11.0
RecalculateTaskQuotaByTokens 根据实际 token 消耗重新计费(异步差额结算)。 当任务成功且返回了 totalTokens 时,根据模型倍率和分组倍率重新计算实际扣费额度, 与预扣费的差额进行补扣或退还。支持钱包和订阅计费来源。
func RecordChannelAffinity ¶
func RefreshTokenSID ¶
func RefundMidjourneyQuota ¶
RefundMidjourneyQuota reverses every accounting element recorded for a billed legacy task.
func RefundTaskQuota ¶ added in v0.11.0
RefundTaskQuota 统一的任务失败退款逻辑。 当异步任务失败时,退还资金与令牌额度,并回减用户和渠道用量。 返回资金来源是否已成功退还;失败时保留 quota,供显式重试或人工对账。
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 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 ResolveWaffoPancakeSubscriptionTradeNo ¶
func ResolveWaffoPancakeSubscriptionTradeNo(event *WaffoPancakeWebhookEvent) (string, error)
ResolveWaffoPancakeSubscriptionTradeNo is the SubscriptionOrder counterpart of ResolveWaffoPancakeTradeNo.
func ResolveWaffoPancakeTradeNo ¶ added in v0.12.15
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 ¶ added in v0.10.8
SettleBilling 执行计费结算。如果 RelayInfo 上有 BillingSession 则通过 session 结算, 否则回退到旧的 PostConsumeQuota 路径(兼容按次计费等场景)。
func SettleMidjourneyTaskBilling ¶
func SettleMidjourneyTaskBilling(relayInfo *relaycommon.RelayInfo, task *model.Midjourney, prepared bool) (bool, error)
SettleMidjourneyTaskBilling charges a persisted legacy task and records the applied stages.
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
func ShouldEnableChannel ¶
func ShouldEnableChannel(newAPIError *types.NewAPIError, status int) bool
func ShouldKeepChannelAffinityOnChannelDisabled ¶
func ShouldKeepChannelAffinityOnChannelDisabled() bool
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 StartSubscriptionQuotaResetTask ¶ added in v0.10.8
func StartSubscriptionQuotaResetTask()
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 TaskErrorFromAPIError ¶ added in v0.11.0
func TaskErrorFromAPIError(apiErr *types.NewAPIError) *taskdto.TaskError
TaskErrorFromAPIError 将 PreConsumeBilling 返回的 NewAPIError 转换为 TaskError。
func TaskErrorWrapper ¶
func TaskErrorWrapperLocal ¶
func TaskExecutionSnapshotFromContext ¶
func TaskExecutionSnapshotFromContext(ctx *gin.Context) *model.TaskExecutionSnapshot
TaskExecutionSnapshotFromContext captures immutable request and plugin provenance at submission time. It never copies plugin source or payloads.
func TryTieredSettle ¶ added in v0.13.0
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 UpdateBatchTasks ¶
func UpdateVideoTasks ¶ added in v0.11.0
func UpdateVideoTasks(ctx context.Context, platform constant.TaskPlatform, taskChannelM map[int][]string, taskM map[string]*model.Task) error
UpdateVideoTasks 按渠道更新所有视频任务
func ValidUsage ¶
func ValidateLoginSession ¶
func ValidateLoginSession(identity AuthIdentity) (*model.UserSession, *model.UserBase, error)
func ValidateProxyURL ¶
ValidateProxyURL validates a channel proxy URL without connecting to it.
func ValidateTaskArtifactBaseURL ¶
ValidateTaskArtifactBaseURL validates configuration syntax only. It deliberately performs no DNS lookup or reachability probe.
func VerifySecurityProof ¶
func VerifyTaskArtifactAccess ¶
VerifyTaskArtifactAccess verifies the route binding without reading task, user, or token state. Signature comparison is constant-time.
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 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 ¶
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 BatchTaskPollingAdaptor ¶
type BatchTaskResult ¶
type BillingSession ¶ added in v0.10.8
type BillingSession struct {
// contains filtered or unexported fields
}
BillingSession 封装单次请求的预扣费/结算/退款生命周期。 实现 relaycommon.BillingSettler 接口。
func NewBillingSession ¶ added in v0.10.8
func NewBillingSession(c *gin.Context, relayInfo *relaycommon.RelayInfo, preConsumedQuota int) (*BillingSession, *types.NewAPIError)
NewBillingSession 根据用户计费偏好创建 BillingSession,处理 subscription_first / wallet_first 的回退。
func (*BillingSession) GetPreConsumedQuota ¶ added in v0.10.8
func (s *BillingSession) GetPreConsumedQuota() int
GetPreConsumedQuota 返回实际预扣的额度。
func (*BillingSession) NeedsRefund ¶ added in v0.10.8
func (s *BillingSession) NeedsRefund() bool
NeedsRefund 返回是否存在需要退还的预扣状态。
func (*BillingSession) Refund ¶ added in v0.10.8
func (s *BillingSession) Refund(c *gin.Context)
Refund 退还所有预扣费,幂等安全,异步执行。
func (*BillingSession) Reserve ¶ added in v0.13.0
func (s *BillingSession) Reserve(targetQuota int) error
func (*BillingSession) Settle ¶ added in v0.10.8
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 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)
func RefreshCodexOAuthTokenWithProxy ¶ added in v0.11.0
type FundingSource ¶ added in v0.10.8
type FundingSource interface {
// Source 返回资金来源标识:"wallet" 或 "subscription"
Source() string
// PreConsume 从该资金来源预扣 amount 额度
PreConsume(amount int) error
// Settle 根据差额调整资金来源(正数补扣,负数退还)
Settle(delta int) error
// Refund 退还所有预扣费
Refund() error
}
FundingSource 抽象了预扣费的资金来源。
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 LogCleanupPayload ¶
type LogCleanupResult ¶
type LogCleanupResult struct {
DeletedCount int64 `json:"deleted_count"`
}
type LogCleanupState ¶
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 ModelHistoryModel ¶
type ModelHistoryPoint ¶
type ModelHistorySeries ¶
type ModelHistorySeries struct {
Points []ModelHistoryPoint `json:"points"`
Models []ModelHistoryModel `json:"models"`
Buckets int `json:"buckets"`
}
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 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 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 StoredArtifactRef ¶
type StoredArtifactRef struct {
Backend string
Bucket string
ObjectKey string
MimeType string
Size int64
}
StoredArtifactRef describes a persisted artifact object. No reference is produced until a concrete storage backend is implemented.
type SubscriptionFunding ¶ added in v0.10.8
type SubscriptionFunding struct {
// 以下字段在 PreConsume 成功后填充,供 RelayInfo 同步使用
AmountTotal int64
AmountUsedAfter int64
PlanId int
PlanTitle string
// contains filtered or unexported fields
}
func (*SubscriptionFunding) PreConsume ¶ added in v0.10.8
func (s *SubscriptionFunding) PreConsume(_ int) error
func (*SubscriptionFunding) Refund ¶ added in v0.10.8
func (s *SubscriptionFunding) Refund() error
func (*SubscriptionFunding) Settle ¶ added in v0.10.8
func (s *SubscriptionFunding) Settle(delta int) error
func (*SubscriptionFunding) Source ¶ added in v0.10.8
func (s *SubscriptionFunding) Source() string
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,omitempty"`
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 TaskArtifactStore ¶
type TaskArtifactStore interface {
Enabled() bool
Resolve(task *model.Task, artifactKey string) (*StoredArtifactRef, error)
Persist(ctx context.Context, task *model.Task, artifact types.TaskArtifact, content io.Reader) (*StoredArtifactRef, error)
Serve(c *gin.Context, task *model.Task, ref *StoredArtifactRef) error
}
TaskArtifactStore is the persistence boundary for generated artifact bytes. types.TaskArtifact is re-exported by relay/channel as channel.TaskArtifact.
func GetTaskArtifactStore ¶
func GetTaskArtifactStore() TaskArtifactStore
GetTaskArtifactStore returns the process-wide artifact storage backend. This release always returns the disabled implementation.
type TaskPollSummary ¶
type TaskPollSummary struct {
UnfinishedTasks int `json:"unfinished_tasks"`
PlatformsScanned int `json:"platforms_scanned"`
NullTasksFailed int `json:"null_tasks_failed"`
}
TaskPollSummary is the result recorded on an async_task_poll system task row, summarizing one polling pass.
func RunTaskPollingOnce ¶
func RunTaskPollingOnce(ctx context.Context, report func(processed, total int)) TaskPollSummary
RunTaskPollingOnce performs one async-task (Suno/video) polling pass synchronously. It honors ctx cancellation (the system-task runner cancels it when the lease is lost) and, when report is non-nil, reports progress as (processedPlatforms, totalPlatforms). It returns immediately if the task adaptor factory has not been wired yet, to avoid a nil call during startup.
type TaskPollingAdaptor ¶ added in v0.11.0
type TaskPollingAdaptor interface {
Init(info *relaycommon.RelayInfo)
FetchTask(baseURL string, key string, task *model.Task, proxy string) (*http.Response, error)
ParseTaskResult(task *model.Task, resp *http.Response, body []byte) (*relaycommon.TaskInfo, error)
// AdjustBillingOnComplete 在任务到达终态(成功/失败)时由轮询循环调用。
// 返回正数触发差额结算(补扣/退还),返回 0 保持预扣费金额不变。
AdjustBillingOnComplete(task *model.Task, taskResult *relaycommon.TaskInfo) int
}
TaskPollingAdaptor 定义轮询所需的最小适配器接口,避免 service -> relay 的循环依赖
type TieredResultWrapper ¶ added in v0.13.0
type TieredResultWrapper = billingexpr.TieredResult
TieredResultWrapper wraps billingexpr.TieredResult for use at the service layer.
type TokenDetails ¶
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 VendorSharePoint ¶
type VendorSharePoint struct {
}
type VendorShareSeries ¶
type VendorShareSeries struct {
}
type VendorShareVendor ¶
type VendorShareVendor struct {
}
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 ¶ added in v0.12.15
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 ¶ added in v0.12.15
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 ¶ added in v0.12.15
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 ¶ added in v0.12.15
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 ¶ added in v0.12.15
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 ¶ added in v0.10.8
type WalletFunding struct {
// contains filtered or unexported fields
}
func (*WalletFunding) PreConsume ¶ added in v0.10.8
func (w *WalletFunding) PreConsume(amount int) error
func (*WalletFunding) Refund ¶ added in v0.10.8
func (w *WalletFunding) Refund() error
func (*WalletFunding) Settle ¶ added in v0.10.8
func (w *WalletFunding) Settle(delta int) error
func (*WalletFunding) Source ¶ added in v0.10.8
func (w *WalletFunding) Source() string
type WebhookPayload ¶
type WebhookPayload struct {
Type string `json:"type"`
Title string `json:"title"`
Content string `json:"content"`
Values []interface{} `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
¶
- 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
- 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
- log_info_generate.go
- midjourney.go
- notify-limit.go
- openai_chat_responses_compat.go
- openai_chat_responses_mode.go
- protected_fetch_client.go
- quota.go
- rankings.go
- request_converter.go
- response_converter.go
- return_path.go
- sensitive.go
- str.go
- subscription_reset_task.go
- system_instance.go
- system_task.go
- task.go
- task_artifact_access.go
- task_artifact_store.go
- task_billing.go
- task_plugin_audit.go
- task_plugin_view.go
- task_polling.go
- text_quota.go
- tiered_settle.go
- token_counter.go
- token_estimator.go
- tokenizer.go
- usage_helpr.go
- user_notify.go
- violation_fee.go
- waffo_pancake.go
- webhook.go