Documentation
¶
Index ¶
- Constants
- Variables
- func Any2Type[T any](data any) (T, error)
- func ApiError(c *gin.Context, err error)
- func ApiErrorI18n(c *gin.Context, key string, args ...map[string]any)
- func ApiErrorMsg(c *gin.Context, msg string)
- func ApiSuccess(c *gin.Context, data any)
- func ApiSuccessI18n(c *gin.Context, key string, data any, args ...map[string]any)
- func AutoSMTPAuth(username, password string) smtp.Auth
- func BuildURL(base string, endpoint string) string
- func Bytes2Size(num int64) string
- func CanonicalJSONObjectDigest(input []byte) ([sha256.Size]byte, error)
- func ChannelQuotaAlertStatus(available float64, total *float64, settings ChannelQuotaAlertSettings) string
- func ChannelQuotaIdentityKeyFingerprint(key ChannelQuotaIdentityKey) (string, error)
- func ChannelQuotaIdentityLookupHMAC(key ChannelQuotaIdentityKey, provider, identityKind string, material []byte) (string, error)
- func ChannelType2APIType(channelType int) (int, bool)
- func CleanupBodyStorage(c *gin.Context)
- func CleanupOldCacheFiles()
- func CleanupOldDiskCacheFiles(maxAge time.Duration) error
- func CreateDiskCacheFile(cacheType DiskCacheType) (string, *os.File, error)
- func CreateDiskCacheFileIn(cacheType DiskCacheType, cachePath string) (string, *os.File, error)
- func DecodeJson(reader io.Reader, v any) error
- func DecodeJsonStrict(reader io.Reader, v any) error
- func DecrementDiskFiles(size int64)
- func DecrementMemoryBuffers(size int64)
- func DeepCopy[T any](src *T) (*T, error)
- func DeleteKey(key string, purpose string)
- func DiagnosticRequestPath(c *gin.Context) string
- func DiskCachePlacementPending() bool
- func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem
- func EncodeBase64(str string) string
- func EnsureDiskCacheDir() error
- func FatalLog(v ...any)
- func GenerateBackupCodes() ([]string, error)
- func GenerateHMAC(data string) string
- func GenerateHMACWithKey(key []byte, data string) string
- func GenerateKey() (string, error)
- func GenerateQRCodeData(secret, username string) string
- func GenerateRandomCharsKey(length int) (string, error)
- func GenerateRandomKey(length int) (string, error)
- func GenerateTOTPSecret(accountName string) (*otp.Key, error)
- func GenerateVerificationCode(length int) string
- func Get2FAIssuer() string
- func GetAnonymousRequestBodyLimitBytes() int64
- func GetAudioDuration(ctx context.Context, f io.ReadSeeker, ext string) (duration float64, err error)
- func GetContextKey(c *gin.Context, key constant.ContextKey) (any, bool)
- func GetContextKeyBool(c *gin.Context, key constant.ContextKey) bool
- func GetContextKeyInt(c *gin.Context, key constant.ContextKey) int
- func GetContextKeyString(c *gin.Context, key constant.ContextKey) string
- func GetContextKeyStringMap(c *gin.Context, key constant.ContextKey) map[string]any
- func GetContextKeyStringSlice(c *gin.Context, key constant.ContextKey) []string
- func GetContextKeyTime(c *gin.Context, key constant.ContextKey) time.Time
- func GetContextKeyType[T any](c *gin.Context, key constant.ContextKey) (T, bool)
- func GetDiskCacheDir() string
- func GetDiskCacheInfo() (fileCount int, totalSize int64, err error)
- func GetDiskCacheMaxSizeBytes() int64
- func GetDiskCachePath() string
- func GetDiskCacheThresholdBytes() int64
- func GetEndpointTypesByChannelType(channelType int, modelName string) []constant.EndpointType
- func GetEnvOrDefault(env string, defaultValue int) int
- func GetEnvOrDefaultBool(env string, defaultValue bool) bool
- func GetEnvOrDefaultString(env string, defaultValue string) string
- func GetIp() (ip string)
- func GetJsonString(data any) string
- func GetJsonType(data json.RawMessage) string
- func GetNetworkIps() []string
- func GetPointer[T any](v T) *T
- func GetRandomInt(max int) int
- func GetRandomString(length int) string
- func GetRequestBody(c *gin.Context) (io.Seeker, error)
- func GetStringIfEmpty(str string, defaultValue string) string
- func GetTimeString() string
- func GetTimestamp() int64
- func GetTopupGroupRatio(name string) float64
- func GetTrustQuota() int
- func GetUUID() string
- func HashBackupCode(code string) (string, error)
- func HashTaskRecoveryIdempotencyKey(rawKey string) (string, error)
- func HashTaskRecoveryRequestFingerprint(material TaskRecoveryRequestFingerprintMaterial) (string, error)
- func HmacSha256(message, key string) string
- func HmacSha256Raw(message, key []byte) []byte
- func IncrementDiskCacheHits()
- func IncrementDiskFiles(size int64)
- func IncrementMemoryBuffers(size int64)
- func IncrementMemoryCacheHits()
- func IndentJson(data []byte) ([]byte, error)
- func InitEnv()
- func InitRedisClient() (err error)
- func InitSessionCookieSettings() error
- func IntMax(a int, b int) int
- func Interface2String(inter interface{}) string
- func IsDiskCacheAvailable(requestSize int64) bool
- func IsDiskCacheEnabled() bool
- func IsIP(s string) bool
- func IsImageGenerationModel(modelName string) bool
- func IsIpInCIDRList(ip net.IP, cidrList []string) bool
- func IsJsonArray(str string) bool
- func IsJsonObject(str string) bool
- func IsOpenAIResponseOnlyModel(modelName string) bool
- func IsOpenAITextModel(modelName string) bool
- func IsPrivateIP(ip net.IP) bool
- func IsRequestBodyTooLargeError(err error) bool
- func IsRunningInContainer() bool
- func IsTaskRecoveryEnabled() bool
- func IsTaskRecoveryIdentityRequired() bool
- func IsTaskRecoveryNewSubmissionEnabled() bool
- func IsTaskRecoveryObligationRecoveryEnabled() bool
- func IsTaskRecoverySchemaCompatibilityEnabled() bool
- func IsValidateRole(role int) bool
- func JsonRawMessageToString(data json.RawMessage) string
- func LoadRelaySchedulingLimits()
- func LocalLogPreview(content string) string
- func LogStartupSuccess(startTime time.Time, port string)
- func LoginAuth(username, password string) smtp.Auth
- func MapToJsonStr(m map[string]interface{}) string
- func MarkSensitiveRequestDiagnostics(c *gin.Context)
- func Marshal(v any) ([]byte, error)
- func MarshalChannelQuotaAlertSettings(settings ChannelQuotaAlertSettings) (string, error)
- func MaskEmail(email string) string
- func MaskSensitiveInfo(str string) string
- func Max(a int, b int) int
- func MessageWithRequestId(message string, id string) string
- func Monitor()
- func NewRequestId() string
- func NormalizeBackupCode(code string) string
- func NormalizeBillingPreference(pref string) string
- func NormalizeOrigin(raw string) (string, error)
- func OpenBrowser(url string)
- func ParseIP(s string) net.IP
- func ParseMultipartFormReusable(c *gin.Context) (*multipart.Form, error)
- func ParseProxyURLRuntime(rawProxyURL string) (*url.URL, bool, error)
- func ParseProxyURLStrict(rawProxyURL string) (*url.URL, error)
- func ParseRedisOption() *redis.Options
- func Password2Hash(password string) (string, error)
- func QuotaFromDecimal(d decimal.Decimal) int
- func QuotaFromDecimalStrict(d decimal.Decimal) (int, error)
- func QuotaFromFloat(value float64) int
- func QuotaFromFloatStrict(value float64) (int, error)
- func QuotaRound(value float64) int
- func QuotaRoundStrict(value float64) (int, error)
- func RandomSleep()
- func ReadDiskCacheFile(filePath string) ([]byte, error)
- func ReadDiskCacheFileString(filePath string) (string, error)
- func RedisDel(key string) error
- func RedisDelKey(key string) error
- func RedisGet(key string) (string, error)
- func RedisHGetObj(key string, obj interface{}) error
- func RedisHIncrBy(key, field string, delta int64) error
- func RedisHSetField(key, field string, value interface{}) error
- func RedisHSetObj(key string, obj interface{}, expiration time.Duration) error
- func RedisIncr(key string, delta int64) error
- func RedisKeyCacheSeconds() int
- func RedisSet(key string, value string, expiration time.Duration) error
- func RegisterVerificationCodeWithKey(key string, code string, purpose string)
- func RelayCtxGo(ctx context.Context, f func())
- func RemoveDiskCacheFile(filePath string) error
- func ReplaceRequestBody(c *gin.Context, data []byte) error
- func ResetDiskCacheStats()
- func ResetDiskCacheUsage()
- func ResolveSQLitePath(configured string) string
- func SafeDiagnosticIdentifier(value string) string
- func SafeSendBool(ch chan bool, value bool) (closed bool)
- func SafeSendString(ch chan string, value string) (closed bool)
- func SafeSendStringTimeout(ch chan string, value string, timeout int) (closed bool)
- func SaveTmpFile(filename string, data io.Reader) (string, error)
- func Seconds2Time(num int) (time string)
- func SendEmail(subject string, receiver string, content string) error
- func SensitiveRequestDiagnostics(ctx context.Context) bool
- func SetContextKey(c *gin.Context, key constant.ContextKey, value any)
- func SetDatabaseTypes(mainType DatabaseType, logType DatabaseType)
- func SetDiskCacheConfig(config DiskCacheConfig)
- func SetLogDatabaseType(databaseType DatabaseType)
- func SetMainDatabaseType(databaseType DatabaseType)
- func SetPerformanceMonitorConfig(config PerformanceMonitorConfig)
- func Sha1(data []byte) string
- func Sha1Raw(data []byte) []byte
- func Sha256Raw(data []byte) []byte
- func ShouldUseDiskCache(dataSize int64) bool
- func StartPyroScope() error
- func StartSystemMonitor()
- func StrToJsonArray(str string) ([]interface{}, error)
- func StrToMap(str string) (map[string]interface{}, error)
- func String2Int(str string) int
- func StringToByteSlice(s string) []byte
- func StringsContains(strs []string, str string) bool
- func SupportsResponsesCompact(channelType, apiType int) bool
- func SyncDiskCacheStats()
- func SysError(s string)
- func SysLog(s string)
- func TaskRecoveryDeploymentRequested() bool
- func TaskRecoveryIdempotencyKeyVerifier() (string, error)
- func TopupGroupRatio2JSONString() string
- func UnescapeHTML(x string) interface{}
- func Unmarshal(data []byte, v any) error
- func UnmarshalBodyReusable(c *gin.Context, v any) error
- func UnmarshalJsonStr(data string, v any) error
- func UpdateTopupGroupRatioByJSONString(jsonStr string) error
- func UsingLogDatabase(databaseType DatabaseType) bool
- func UsingMainDatabase(databaseType DatabaseType) bool
- func ValidAccountQuotaThreshold(policy AccountQuotaThreshold) bool
- func ValidateBackupCode(code string) bool
- func ValidateChannelQuotaAlertOptionValue(key, value string) error
- func ValidateChannelQuotaAlertSettings(settings ChannelQuotaAlertSettings) error
- func ValidateChannelQuotaIdentityKeyring(keyring ChannelQuotaIdentityKeyring) error
- func ValidateNumericCode(code string) (string, error)
- func ValidatePasswordAndHash(password string, hash string) bool
- func ValidateRedirectURL(rawURL string) error
- func ValidateTOTPCode(secret, code string) bool
- func ValidateTopupGroupRatioJSON(jsonStr string) error
- func ValidateURLWithFetchSetting(urlStr string, enableSSRFProtection, allowPrivateIp bool, ...) error
- func ValidateUniqueJSONKeys(input []byte) error
- func VerifyCodeWithKey(key string, code string, purpose string) bool
- func WithAccountQuotaThreshold(ctx context.Context, policy AccountQuotaThreshold) context.Context
- func WriteDiskCacheFile(cacheType DiskCacheType, data []byte) (string, error)
- func WriteDiskCacheFileString(cacheType DiskCacheType, data string) (string, error)
- type AccountQuotaThreshold
- type BodyStorage
- type ChannelQuotaAlertEvent
- type ChannelQuotaAlertOccurrenceInput
- type ChannelQuotaAlertOccurrenceOutcome
- type ChannelQuotaAlertSettings
- type ChannelQuotaIdentityKey
- type ChannelQuotaIdentityKeyring
- type CustomEvent
- type DatabaseType
- type DiskCacheConfig
- type DiskCacheStats
- type DiskCacheType
- type DiskSpaceInfo
- type EndpointInfo
- type InMemoryRateLimiter
- func (l *InMemoryRateLimiter) Allow(key string, maxRequestNum int, duration int64) bool
- func (l *InMemoryRateLimiter) Commit(reservation RateLimitReservation, maxRequestNum int, duration int64)
- func (l *InMemoryRateLimiter) Init(expirationDuration time.Duration)
- func (l *InMemoryRateLimiter) Release(reservation RateLimitReservation)
- func (l *InMemoryRateLimiter) Request(key string, maxRequestNum int, duration int64) bool
- func (l *InMemoryRateLimiter) Reserve(key string, maxRequestNum int, duration int64) (RateLimitReservation, bool)
- type NodeIdentity
- type PageInfo
- type PerformanceMonitorConfig
- type QuotaClamp
- type QuotaClampKind
- type RateLimitReservation
- type ReplayableBody
- type SSRFProtection
- type SystemStatus
- type TaskRecoveryRequestFingerprintMaterial
Constants ¶
const ( ChannelQuotaAlertSettingsOptionKey = "ChannelQuotaAlertSettings" // Legacy scalar option keys remain readable for one-time migrations. ChannelQuotaAlertEnabledOptionKey = "ChannelQuotaAlertEnabled" ChannelQuotaAlertWarningPercentOptionKey = "ChannelQuotaAlertWarningPercent" ChannelQuotaAlertCriticalPercentOptionKey = "ChannelQuotaAlertCriticalPercent" )
ChannelQuotaAlertSettingsOptionKey is persisted through the existing, root-only /api/option/ settings API. Keeping the three values in one JSON option makes threshold updates atomic and avoids transient warning/critical inversions when a process reloads settings from the database.
const ( ChannelQuotaIdentityKindProviderAccount = "provider_account" ChannelQuotaIdentityKindCredential = "credential" )
const ( DefaultUserSessionActiveLimit = 50 DefaultUserSessionIssuanceLimit = 100 DefaultUserSessionIssuanceWindowSeconds = 24 * 60 * 60 DefaultUserSessionRevokedRetentionDays = 7 DefaultUserSessionHourlyAlertThreshold = 5000 // DefaultChannelQuotaSnapshotRetentionDays disables automatic cleanup. Set // CHANNEL_QUOTA_SNAPSHOT_RETENTION_DAYS to a positive value to bound history. DefaultChannelQuotaSnapshotRetentionDays = 0 // Channel quota alerts are opt-in. Thresholds are percentages of the // provider-reported total quota and are only used for read-only status // reporting; no notifications or routing changes are triggered. DefaultChannelQuotaAlertEnabled = false DefaultChannelQuotaAlertWarningPercent = 20.0 DefaultChannelQuotaAlertCriticalPercent = 10.0 DefaultChannelQuotaAlertCooldownSeconds = int64(60 * 60) DefaultChannelQuotaAlertNotifyOnRecovery = false )
const ( NodeNameSourceManual = "manual" NodeNameSourceHostname = "hostname" )
const ( RequestIdKey = "X-Oneapi-Request-Id" UpstreamRequestIdKey = "X-Upstream-Request-Id" )
const ( RoleGuestUser = 0 RoleCommonUser = 1 RoleAdminUser = 10 RoleRootUser = 100 )
const ( UserStatusEnabled = 1 // don't use 0, 0 is the default value! UserStatusDisabled = 2 // also don't use 0 )
const ( TokenStatusEnabled = 1 // don't use 0, 0 is the default value! TokenStatusDisabled = 2 // also don't use 0 TokenStatusExpired = 3 TokenStatusExhausted = 4 )
const ( RedemptionCodeStatusEnabled = 1 // don't use 0, 0 is the default value! RedemptionCodeStatusDisabled = 2 // also don't use 0 RedemptionCodeStatusUsed = 3 // also don't use 0 )
const ( ChannelStatusUnknown = 0 ChannelStatusEnabled = 1 // don't use 0, 0 is the default value! ChannelStatusManuallyDisabled = 2 // also don't use 0 ChannelStatusAutoDisabled = 3 )
const ( TopUpStatusPending = "pending" TopUpStatusSuccess = "success" TopUpStatusFailed = "failed" TopUpStatusExpired = "expired" )
const ( // DefaultSQLitePath is used for fresh MyAPI installations. DefaultSQLitePath = "my-api.db?_busy_timeout=30000" // LegacySQLitePath is retained as a read/write fallback for existing // installations that still have the historical database file. LegacySQLitePath = "one-api.db?_busy_timeout=30000" )
const ( MaxQuota = math.MaxInt32 MinQuota = math.MinInt32 )
Quota conversions are centralized here so every billing path shares one saturation + logging policy. Quota columns (user/token/log) are 32-bit integers in the database, so an oversized product must clamp to the int32 range instead of wrapping around and turning a charge into a credit.
const ( // 备用码配置 BackupCodeLength = 8 // 备用码长度 BackupCodeCount = 4 // 生成备用码数量 // 限制配置 MaxFailAttempts = 5 // 最大失败尝试次数 LockoutDuration = 300 // 锁定时间(秒) )
const ( EmailVerificationPurpose = "v" PasswordResetPurpose = "r" )
const ChannelQuotaIdentityKeysEnv = "CHANNEL_QUOTA_IDENTITY_KEYS"
const KeyBodyStorage = "key_body_storage"
const KeyRequestBody = "key_request_body"
const LocalLogContentLimit = 2048
const MaxChannelQuotaIdentityMaterialBytes = 64 * 1024
Variables ¶
var ( ErrChannelQuotaIdentityKeysInvalid = errors.New("channel quota identity key configuration is invalid") ErrChannelQuotaIdentityInputInvalid = errors.New("channel quota identity input is invalid") )
var ( UserSessionActiveLimit = DefaultUserSessionActiveLimit UserSessionIssuanceLimit = DefaultUserSessionIssuanceLimit UserSessionIssuanceWindowSeconds = int64(DefaultUserSessionIssuanceWindowSeconds) UserSessionRevokedRetentionDays = DefaultUserSessionRevokedRetentionDays UserSessionHourlyAlertThreshold = DefaultUserSessionHourlyAlertThreshold ChannelQuotaSnapshotRetentionDays = DefaultChannelQuotaSnapshotRetentionDays ChannelQuotaAlertEnabled = DefaultChannelQuotaAlertEnabled ChannelQuotaAlertWarningPercent = DefaultChannelQuotaAlertWarningPercent ChannelQuotaAlertCriticalPercent = DefaultChannelQuotaAlertCriticalPercent ChannelQuotaAlertCooldownSeconds = DefaultChannelQuotaAlertCooldownSeconds ChannelQuotaAlertNotifyOnRecovery = DefaultChannelQuotaAlertNotifyOnRecovery // Webhook delivery is disabled until an administrator configures an HTTPS URL. ChannelQuotaAlertWebhookURL = "" ChannelQuotaAlertWebhookSecret = "" )
var ( FileUploadPermission = RoleGuestUser FileDownloadPermission = RoleGuestUser ImageUploadPermission = RoleGuestUser ImageDownloadPermission = RoleGuestUser )
var ( GlobalApiRateLimitEnable bool GlobalApiRateLimitNum int GlobalApiRateLimitDuration int64 GlobalWebRateLimitEnable bool GlobalWebRateLimitNum int GlobalWebRateLimitDuration int64 CriticalRateLimitEnable bool CriticalRateLimitNum = 20 CriticalRateLimitDuration int64 = 20 * 60 UploadRateLimitNum = 10 UploadRateLimitDuration int64 = 60 DownloadRateLimitNum = 10 DownloadRateLimitDuration int64 = 60 // Per-user search rate limit (applies after authentication, keyed by user ID) SearchRateLimitEnable = true SearchRateLimitNum = 10 SearchRateLimitDuration int64 = 60 )
All duration's unit is seconds Shouldn't larger then RateLimitKeyExpirationDuration
var ( Port = flag.Int("port", 3000, "the listening port") PrintVersion = flag.Bool("version", false, "print version and exit") PrintHelp = flag.Bool("help", false, "print help and exit") LogDir = flag.String("log-dir", "./logs", "specify the log directory") )
var ( // OpenAIResponseOnlyModels is a list of models that are only available for OpenAI responses. OpenAIResponseOnlyModels = []string{ "o3-pro", "o3-deep-research", "o4-mini-deep-research", } ImageGenerationModels = []string{ "dall-e-3", "dall-e-2", "gpt-image-1", "prefix:imagen-", "flux-", "flux.1-", } OpenAITextModels = []string{ "gpt-", "o1", "o3", "o4", "chatgpt", } )
var AutomaticDisableChannelEnabled = false
var AutomaticEnableChannelEnabled = false
var BatchUpdateEnabled = false
var BatchUpdateInterval int
var ChannelDisableThreshold = 5.0
var CohereSafetySetting string
https://docs.cohere.com/docs/safety-modes Type; NONE/CONTEXTUAL/STRICT
var CryptoSecret = uuid.New().String()
var DataExportDefaultTime = "hour" // unit: minute
var DataExportEnabled = true
var DataExportInterval = 5 // unit: minute
var DebugEnabled bool
var DefaultCollapseSidebar = false // default value of collapse sidebar
var DefaultSSRFProtection = &SSRFProtection{ AllowPrivateIp: false, DomainFilterMode: true, DomainList: []string{}, IpFilterMode: true, IpList: []string{}, AllowedPorts: []int{}, }
DefaultSSRFProtection 默认SSRF防护配置
var DisplayInCurrencyEnabled = true
保留旧变量以兼容历史逻辑,实际展示由 general_setting.quota_display_type 控制
var DisplayTokenStatEnabled = true
var DrawingEnabled = true
var EmailAliasRestrictionEnabled = false // 是否启用邮箱别名限制
var EmailDomainRestrictionEnabled = false // 是否启用邮箱域名限制
var EmailDomainWhitelist = []string{
"gmail.com",
"163.com",
"126.com",
"qq.com",
"outlook.com",
"hotmail.com",
"icloud.com",
"yahoo.com",
"foxmail.com",
}
var EmailLoginAuthServerList = []string{
"smtp.sendcloud.net",
"smtp.azurecomm.net",
}
var EmailVerificationEnabled = false
var ErrCanonicalJSONObject = errors.New("canonical JSON object is invalid or exceeds limits")
var ErrRequestBodyTooLarge = errors.New("request body too large")
var ErrStorageClosed = fmt.Errorf("body storage is closed")
ErrStorageClosed 存储已关闭错误
var ErrTaskRecoveryIdempotencySecret = errors.New("task recovery requires a dedicated 32-byte hex idempotency secret")
var ErrTaskRecoveryRequestFingerprint = errors.New("task recovery request fingerprint input is invalid")
var GeminiSafetySetting string
var GitHubClientId = ""
var GitHubClientSecret = ""
var GitHubOAuthEnabled = false
var InsecureTLSConfig = &tls.Config{InsecureSkipVerify: true}
var IsMasterNode bool
var ItemsPerPage = 10
var LinuxDOClientId = ""
var LinuxDOClientSecret = ""
var LinuxDOMinimumTrustLevel = 0
var LinuxDOOAuthEnabled = false
var LogConsumeEnabled = true
var LogWriterMu sync.RWMutex
LogWriterMu protects concurrent access to gin.DefaultWriter/gin.DefaultErrorWriter during log file rotation. Acquire RLock when reading/writing through the writers, acquire Lock when swapping writers and closing old files.
var Logo = ""
var MaxRecentItems = 1000
var MemoryCacheEnabled bool
var NodeName = ""
NodeName 节点名称,优先从 NODE_NAME 环境变量读取,未配置时回退主机名。 用于审计日志和后台任务中标识节点身份;多实例部署时建议显式配置稳定 NODE_NAME。
var NodeNameManuallyConfigured bool
var NodeNameSource = NodeNameSourceHostname
NodeNameSource records how NodeName was chosen so future instance-management reporting can distinguish operator-configured names from automatic fallback.
var OptionMap map[string]string
var OptionMapRWMutex sync.RWMutex
var PasswordLoginEnabled = true
var PasswordRegisterEnabled = true
var PreConsumedQuota = 500
var QuotaForInvitee = 0
var QuotaForInviter = 0
var QuotaForNewUser = 0
var QuotaPerUnit = 500 * 1000.0 // $0.002 / 1K tokens
var ChatLink = "" var ChatLink2 = ""
var QuotaRemindThreshold = 1000
var RDB *redis.Client
var RateLimitKeyExpirationDuration = 20 * time.Minute
var RedisEnabled = true
var RegisterEnabled = true
var RelayFailoverTimeoutSeconds int
These opt-in limits do not change the legacy RELAY_TIMEOUT contract.
var RelayFailureCooldownSeconds int
var RelayIdleConnTimeout int // unit is second
var RelayMaxIdleConns int
var RelayMaxIdleConnsPerHost int
var RelayTimeout int // unit is second
var RequestInterval time.Duration
var RetryTimes = 0
var SMTPAccount = ""
var SMTPForceAuthLogin = false
var SMTPFrom = ""
var SMTPInsecureSkipVerify = false
var SMTPPort = 587
var SMTPSSLEnabled = false
var SMTPServer = ""
var SMTPStartTLSEnabled = false
var SMTPToken = ""
var SQLitePath = DefaultSQLitePath
SQLitePath is the effective SQLite DSN. InitEnv resolves it to the legacy path only when the canonical file does not exist and the legacy file does. An explicit SQLITE_PATH always wins, so operators can select either file.
var SessionCookieSecure = false
var SessionCookieTrustedURLs []string
var SessionSecret = uuid.New().String()
var StartTime = time.Now().Unix() // unit: second
var SyncFrequency int // unit is second
var SystemName = "MyAPI"
SystemName is the default user-visible runtime brand. Site settings may override it at startup, but a fresh installation should always identify as MyAPI rather than inheriting the upstream project's name.
var TLSInsecureSkipVerify bool
var TaskEnabled = true
var TaskRecoveryEnabled = false
TaskRecoveryEnabled is kept as the legacy alias for new durable submission creation. New callers must select the narrower capability they need so a rollout can stop accepting new work without abandoning pre-existing debt.
var TaskRecoveryNewSubmissionsEnabled = false
var TaskRecoveryObligationRecoveryEnabled = false
var TelegramBotName = ""
var TelegramBotToken = ""
var TelegramOAuthEnabled = false
var TopUpLink = ""
TranslateMessage is a helper function that calls i18n.T This function is defined here to avoid circular imports The actual implementation will be set during init
var TurnstileCheckEnabled = false
var TurnstileSecretKey = ""
var TurnstileSiteKey = ""
var Validate *validator.Validate
var VerificationValidMinutes = 10
var Version = "v0.0.0" // this hard coding will be replaced automatically when building, no need to manually change
var WeChatAccountQRCodeImageURL = ""
var WeChatAuthEnabled = false
var WeChatServerAddress = ""
var WeChatServerToken = ""
Functions ¶
func ApiErrorI18n ¶
ApiErrorI18n returns a translated error message based on the user's language preference key is the i18n message key, args is optional template data
func ApiErrorMsg ¶
func ApiSuccess ¶
func ApiSuccessI18n ¶
ApiSuccessI18n returns a translated success message based on the user's language preference
func AutoSMTPAuth ¶
func Bytes2Size ¶
func CanonicalJSONObjectDigest ¶
CanonicalJSONObjectDigest returns only a Merkle SHA-256 digest of one strictly parsed top-level JSON object. Object members are ordered by their decoded UTF-8 key bytes, array order is retained, strings are bound by their decoded value, and numbers retain their original valid JSON spelling. It deliberately performs no Unicode normalization.
The input is bounded to 1 MiB, 64 nested values, and 50,000 value nodes. Duplicate decoded object keys, a BOM, invalid UTF-8, a second root value, and trailing non-whitespace data are rejected. No error contains input data and this API never materializes or returns a canonical request body.
func ChannelQuotaAlertStatus ¶
func ChannelQuotaAlertStatus(available float64, total *float64, settings ChannelQuotaAlertSettings) string
ChannelQuotaAlertStatus derives the alert status only from a successful, provider-reported total. Unknown, non-finite, or non-positive totals remain unavailable rather than being interpreted as healthy.
func ChannelQuotaIdentityKeyFingerprint ¶
func ChannelQuotaIdentityKeyFingerprint(key ChannelQuotaIdentityKey) (string, error)
ChannelQuotaIdentityKeyFingerprint returns a fixed-domain lowercase-hex fingerprint suitable for binding a version to one deployment key. It is not used as the identity lookup digest and cannot replace the secret key.
func ChannelQuotaIdentityLookupHMAC ¶
func ChannelQuotaIdentityLookupHMAC(key ChannelQuotaIdentityKey, provider, identityKind string, material []byte) (string, error)
ChannelQuotaIdentityLookupHMAC derives a lowercase-hex HMAC over length-framed provider, identity kind, and identity material. Length framing makes component boundaries unambiguous, while the protocol prefix isolates these digests from every other HMAC domain in the process.
func ChannelType2APIType ¶
func CleanupBodyStorage ¶
CleanupBodyStorage 清理请求体存储(应在请求结束时调用)
func CleanupOldDiskCacheFiles ¶
CleanupOldDiskCacheFiles 清理旧的缓存文件 maxAge: 文件最大存活时间 注意:此函数只删除文件,不更新统计(因为无法知道每个文件的原始大小)
func CreateDiskCacheFile ¶
func CreateDiskCacheFile(cacheType DiskCacheType) (string, *os.File, error)
CreateDiskCacheFile 创建磁盘缓存文件(使用生效代目录) cacheType: 缓存类型(body/file) 返回文件路径和文件句柄
func CreateDiskCacheFileIn ¶
CreateDiskCacheFileIn 在指定缓存根目录下创建磁盘缓存文件。 cachePath 为空时使用系统临时目录。传入的路径必须来自调用方决策时 使用的同一生效代快照,保证一次决策的目录选择一致。
func DecodeJsonStrict ¶
DecodeJsonStrict decodes exactly one JSON value, rejecting unknown object fields and any trailing JSON value. Use it for persisted configuration where silently accepting additional data could hide a malformed or mistyped option.
func DecrementMemoryBuffers ¶
func DecrementMemoryBuffers(size int64)
DecrementMemoryBuffers 减少内存缓存计数
func DiagnosticRequestPath ¶
DiagnosticRequestPath retains the browser route without changing the canonical relay path used by routing, policy, or accounting.
func DiskCachePlacementPending ¶
func DiskCachePlacementPending() bool
DiskCachePlacementPending 报告配置代中的磁盘放置字段(Path/MaxSizeMB) 是否尚未进入生效代,即需要维护重建或重启才能生效。
func EmbedFolder ¶
func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem
func EncodeBase64 ¶
func GenerateHMAC ¶
func GenerateHMACWithKey ¶
func GenerateKey ¶
func GenerateQRCodeData ¶
GenerateQRCodeData 生成二维码数据
func GenerateRandomCharsKey ¶
func GenerateRandomKey ¶
func GenerateTOTPSecret ¶
GenerateTOTPSecret 生成TOTP密钥和配置
func GetAnonymousRequestBodyLimitBytes ¶
func GetAnonymousRequestBodyLimitBytes() int64
func GetAudioDuration ¶
func GetAudioDuration(ctx context.Context, f io.ReadSeeker, ext string) (duration float64, err error)
GetAudioDuration 使用纯 Go 库获取音频文件的时长(秒)。 它不再依赖外部的 ffmpeg 或 ffprobe 程序。
func GetContextKey ¶
func GetContextKeyBool ¶
func GetContextKeyBool(c *gin.Context, key constant.ContextKey) bool
func GetContextKeyInt ¶
func GetContextKeyInt(c *gin.Context, key constant.ContextKey) int
func GetContextKeyString ¶
func GetContextKeyString(c *gin.Context, key constant.ContextKey) string
func GetContextKeyStringMap ¶
func GetContextKeyStringSlice ¶
func GetContextKeyStringSlice(c *gin.Context, key constant.ContextKey) []string
func GetContextKeyTime ¶
func GetContextKeyType ¶
func GetDiskCacheDir ¶
func GetDiskCacheDir() string
GetDiskCacheDir 获取统一的磁盘缓存目录(生效代) 注意:每次调用都会按生效代重新计算
func GetDiskCacheInfo ¶
GetDiskCacheInfo 获取磁盘缓存目录信息
func GetDiskCacheMaxSizeBytes ¶
func GetDiskCacheMaxSizeBytes() int64
GetDiskCacheMaxSizeBytes 获取磁盘缓存最大大小(字节,生效代)
func GetDiskCacheThresholdBytes ¶
func GetDiskCacheThresholdBytes() int64
GetDiskCacheThresholdBytes 获取磁盘缓存阈值(字节,生效代)
func GetEndpointTypesByChannelType ¶
func GetEndpointTypesByChannelType(channelType int, modelName string) []constant.EndpointType
GetEndpointTypesByChannelType 获取渠道最优先端点类型(所有的渠道都支持 OpenAI 端点)
func GetEnvOrDefault ¶
func GetEnvOrDefaultBool ¶
func GetEnvOrDefaultString ¶
func GetJsonString ¶
func GetJsonType ¶
func GetJsonType(data json.RawMessage) string
func GetNetworkIps ¶
func GetNetworkIps() []string
func GetPointer ¶
func GetPointer[T any](v T) *T
func GetRandomInt ¶
func GetRandomString ¶
func GetStringIfEmpty ¶
func GetTimeString ¶
func GetTimeString() string
func GetTimestamp ¶
func GetTimestamp() int64
func GetTopupGroupRatio ¶
func GetTrustQuota ¶
func GetTrustQuota() int
func HashTaskRecoveryIdempotencyKey ¶
HashTaskRecoveryIdempotencyKey never persists or returns the raw client key. The protocol boundary is responsible for validating the HTTP header syntax.
func HashTaskRecoveryRequestFingerprint ¶
func HashTaskRecoveryRequestFingerprint(material TaskRecoveryRequestFingerprintMaterial) (string, error)
HashTaskRecoveryRequestFingerprint binds normalized request material to the deployment's dedicated, restart-stable task-recovery secret. Every field is length-framed under a versioned domain and the result is lowercase HMAC-SHA256 hex. The canonical body itself is never accepted or returned here.
func HmacSha256 ¶
func HmacSha256Raw ¶
func IncrementMemoryBuffers ¶
func IncrementMemoryBuffers(size int64)
IncrementMemoryBuffers 增加内存缓存计数
func IndentJson ¶
func InitRedisClient ¶
func InitRedisClient() (err error)
InitRedisClient This function is called after init()
func InitSessionCookieSettings ¶
func InitSessionCookieSettings() error
func Interface2String ¶
func Interface2String(inter interface{}) string
func IsDiskCacheAvailable ¶
IsDiskCacheAvailable 检查是否可以创建新的磁盘缓存
func IsImageGenerationModel ¶
func IsJsonArray ¶
func IsJsonObject ¶
func IsOpenAITextModel ¶
func IsPrivateIP ¶
func IsRunningInContainer ¶
func IsRunningInContainer() bool
IsRunningInContainer detects if the application is running inside a container
func IsTaskRecoveryEnabled ¶
func IsTaskRecoveryEnabled() bool
func IsTaskRecoveryIdentityRequired ¶
func IsTaskRecoveryIdentityRequired() bool
IsTaskRecoveryIdentityRequired reports whether any runtime recovery capability can use the stable deployment-to-database binding.
func IsTaskRecoveryNewSubmissionEnabled ¶
func IsTaskRecoveryNewSubmissionEnabled() bool
IsTaskRecoveryNewSubmissionEnabled controls creation of new durable task intents. It does not control recovery of already committed obligations.
func IsTaskRecoveryObligationRecoveryEnabled ¶
func IsTaskRecoveryObligationRecoveryEnabled() bool
IsTaskRecoveryObligationRecoveryEnabled controls recovery and projection of already persisted billing and delivery obligations. It intentionally remains independent from accepting a new client submission.
func IsTaskRecoverySchemaCompatibilityEnabled ¶
func IsTaskRecoverySchemaCompatibilityEnabled() bool
IsTaskRecoverySchemaCompatibilityEnabled is intentionally always true: schema reads and migrations must stay compatible even while all writers and workers are gated off.
func IsValidateRole ¶
func JsonRawMessageToString ¶
func JsonRawMessageToString(data json.RawMessage) string
JsonRawMessageToString returns JSON strings as their decoded value and other JSON values as raw text.
func LoadRelaySchedulingLimits ¶
func LoadRelaySchedulingLimits()
func LocalLogPreview ¶
LocalLogPreview limits log-only content unless debug logging is enabled.
func LogStartupSuccess ¶
func MapToJsonStr ¶
func MarkSensitiveRequestDiagnostics ¶
MarkSensitiveRequestDiagnostics prevents request or response content from entering diagnostics. Keep the marker on both context forms: Gin does not forward Value calls to Request.Context unless ContextWithFallback is enabled.
func MarshalChannelQuotaAlertSettings ¶
func MarshalChannelQuotaAlertSettings(settings ChannelQuotaAlertSettings) (string, error)
func MaskEmail ¶
MaskEmail masks a user email to prevent PII leakage in logs Returns "***masked***" if email is empty, otherwise shows only the domain part
func MaskSensitiveInfo ¶
MaskSensitiveInfo moved to the conversion kit (kitutil) because the types package error formatting depends on it; host callers keep this name.
func MessageWithRequestId ¶
func NewRequestId ¶
func NewRequestId() string
func NormalizeBackupCode ¶
NormalizeBackupCode 标准化备用码格式
func NormalizeBillingPreference ¶
NormalizeBillingPreference clamps the billing preference to valid values.
func NormalizeOrigin ¶
NormalizeOrigin validates and canonicalizes a browser origin. Only an exact scheme/host/effective-port match is meaningful; paths and wildcards are not accepted for authentication cookie endpoints.
func OpenBrowser ¶
func OpenBrowser(url string)
func ParseProxyURLRuntime ¶
ParseProxyURLRuntime validates and normalizes a proxy URL for runtime use. The boolean result reports whether a legacy path, query, or fragment was removed.
func ParseProxyURLStrict ¶
ParseProxyURLStrict validates and normalizes a proxy URL for persistence.
func ParseRedisOption ¶
func Password2Hash ¶
func QuotaFromDecimal ¶
QuotaFromDecimal converts a computed quota decimal to int with saturation. The decimal is rounded (half away from zero) before conversion.
func QuotaFromDecimalStrict ¶
QuotaFromDecimalStrict converts an in-range decimal quota and rejects a value that would otherwise be saturated at the database's int32 boundary.
func QuotaFromFloat ¶
QuotaFromFloat converts a computed quota value to int, truncating toward zero, with saturation. Use for float products of prices, ratios, and user-controlled multipliers (image n, video seconds, resolution ratios).
func QuotaFromFloatStrict ¶
QuotaFromFloatStrict converts an in-range value and returns a typed *QuotaClamp error instead of allowing a saturated result to reach billing.
func QuotaRound ¶
QuotaRound converts a float64 quota value to int using half-away-from-zero rounding, with saturation. Every tiered billing path (pre-consume, settlement, breakdown validation, log fields) MUST use this to avoid +-1 discrepancies.
func QuotaRoundStrict ¶
QuotaRoundStrict rounds an in-range value and returns a typed *QuotaClamp error instead of allowing a saturated result to reach billing.
func RandomSleep ¶
func RandomSleep()
func ReadDiskCacheFile ¶
ReadDiskCacheFile 读取磁盘缓存文件
func ReadDiskCacheFileString ¶
ReadDiskCacheFileString 读取磁盘缓存文件为字符串
func RedisDelKey ¶
func RedisHGetObj ¶
func RedisHIncrBy ¶
func RedisHSetField ¶
func RedisKeyCacheSeconds ¶
func RedisKeyCacheSeconds() int
func RelayCtxGo ¶
func RemoveDiskCacheFile ¶
RemoveDiskCacheFile 删除磁盘缓存文件
func ReplaceRequestBody ¶
ReplaceRequestBody atomically replaces every replay path for a request body. The existing request state is not changed unless both the new storage and an independent reader have been created successfully.
func ResolveSQLitePath ¶
ResolveSQLitePath selects the canonical SQLite file for new installations while preserving existing data without requiring a schema migration.
func SafeDiagnosticIdentifier ¶
SafeDiagnosticIdentifier admits only short machine identifiers, never free text, URLs, JSON, or base64 data URLs. Unknown identifiers are omitted.
func SafeSendBool ¶
func SafeSendString ¶
func SafeSendStringTimeout ¶
SafeSendStringTimeout send, return true, else return false
func SaveTmpFile ¶
SaveTmpFile saves data to a temporary file. The filename would be apppended with a random string.
func Seconds2Time ¶
func SetContextKey ¶
func SetContextKey(c *gin.Context, key constant.ContextKey, value any)
func SetDatabaseTypes ¶
func SetDatabaseTypes(mainType DatabaseType, logType DatabaseType)
func SetDiskCacheConfig ¶
func SetDiskCacheConfig(config DiskCacheConfig)
SetDiskCacheConfig 保存新的配置代。 热字段(Enabled、ThresholdMB)立即并入生效代,对新决策生效; 放置字段(Path、MaxSizeMB)只更新配置代,不迁移生效代。
func SetLogDatabaseType ¶
func SetLogDatabaseType(databaseType DatabaseType)
func SetMainDatabaseType ¶
func SetMainDatabaseType(databaseType DatabaseType)
func SetPerformanceMonitorConfig ¶
func SetPerformanceMonitorConfig(config PerformanceMonitorConfig)
SetPerformanceMonitorConfig 设置性能监控配置
func ShouldUseDiskCache ¶
ShouldUseDiskCache 判断是否应该使用磁盘缓存。 单次决策读取同一生效代快照,enabled/threshold/max 来自同一代,不混代。
func StartPyroScope ¶
func StartPyroScope() error
func StrToJsonArray ¶
func String2Int ¶
func StringToByteSlice ¶
StringToByteSlice []byte only read, panic on append
func StringsContains ¶
func TaskRecoveryDeploymentRequested ¶
func TaskRecoveryDeploymentRequested() bool
TaskRecoveryDeploymentRequested reports whether an operator explicitly asked to activate either runtime capability. InitDB uses it before opening a database so an invalid dedicated secret cannot silently turn a requested rollout into legacy behavior.
func TaskRecoveryIdempotencyKeyVerifier ¶
TaskRecoveryIdempotencyKeyVerifier binds a database to one deployment key without storing the key. A separate domain prevents its use as a client-key digest. It is an internal configuration verifier, not an authentication token.
func TopupGroupRatio2JSONString ¶
func TopupGroupRatio2JSONString() string
func UnescapeHTML ¶
func UnescapeHTML(x string) interface{}
func UnmarshalJsonStr ¶
func UsingLogDatabase ¶
func UsingLogDatabase(databaseType DatabaseType) bool
func UsingMainDatabase ¶
func UsingMainDatabase(databaseType DatabaseType) bool
func ValidAccountQuotaThreshold ¶
func ValidAccountQuotaThreshold(policy AccountQuotaThreshold) bool
func ValidateChannelQuotaAlertOptionValue ¶
ValidateChannelQuotaAlertOptionValue validates both the canonical JSON option and legacy scalar keys. Scalar keys remain accepted for migrations; new callers should persist ChannelQuotaAlertSettings atomically.
func ValidateChannelQuotaAlertSettings ¶
func ValidateChannelQuotaAlertSettings(settings ChannelQuotaAlertSettings) error
ValidateChannelQuotaAlertSettings enforces finite percentage thresholds and the ordering needed by the read-only alert derivation. It does not trigger notifications, provider calls, routing changes, or channel state changes.
func ValidateChannelQuotaIdentityKeyring ¶
func ValidateChannelQuotaIdentityKeyring(keyring ChannelQuotaIdentityKeyring) error
ValidateChannelQuotaIdentityKeyring checks programmatically constructed keyrings with the same invariants as the environment parser.
func ValidateNumericCode ¶
ValidateNumericCode 验证数字验证码格式
func ValidatePasswordAndHash ¶
func ValidateRedirectURL ¶
ValidateRedirectURL validates that a redirect URL is safe to use. It checks that:
- The URL is properly formatted
- The scheme is either http or https
- The domain is in the trusted domains list (exact match or subdomain)
Returns nil if the URL is valid and trusted, otherwise returns an error describing why the validation failed.
func ValidateURLWithFetchSetting ¶
func ValidateURLWithFetchSetting(urlStr string, enableSSRFProtection, allowPrivateIp bool, domainFilterMode bool, ipFilterMode bool, domainList, ipList, allowedPorts []string, applyIPFilterForDomain bool) error
ValidateURLWithFetchSetting 使用FetchSetting配置验证URL
func ValidateUniqueJSONKeys ¶
ValidateUniqueJSONKeys rejects duplicate decoded object keys and excessive structure without changing request bytes or number spelling. Callers retain their own byte limits and protocol-specific case/field rules. In particular, this does not change the stricter CanonicalJSONObjectDigest contract.
func WithAccountQuotaThreshold ¶
func WithAccountQuotaThreshold(ctx context.Context, policy AccountQuotaThreshold) context.Context
func WriteDiskCacheFile ¶
func WriteDiskCacheFile(cacheType DiskCacheType, data []byte) (string, error)
WriteDiskCacheFile 写入数据到磁盘缓存文件 返回文件路径
func WriteDiskCacheFileString ¶
func WriteDiskCacheFileString(cacheType DiskCacheType, data string) (string, error)
WriteDiskCacheFileString 写入字符串到磁盘缓存文件
Types ¶
type AccountQuotaThreshold ¶
type AccountQuotaThreshold struct {
TokenID int
Revision int64
MinimumRemainingBPS int
MaxAgeSeconds int64
}
This is an observed account/window routing precondition, not a per-Key percentage consumption ledger or a reservation against shared-account use.
func AccountQuotaThresholdFromContext ¶
func AccountQuotaThresholdFromContext(ctx context.Context) (AccountQuotaThreshold, bool)
type BodyStorage ¶
type BodyStorage interface {
io.ReadSeeker
io.Closer
// Bytes 获取全部内容
Bytes() ([]byte, error)
// Size 获取数据大小
Size() int64
// IsDisk 是否是磁盘存储
IsDisk() bool
// NewReader returns an independent reader positioned at the start of the
// stored payload. Each call returns a reader with its own cursor, so
// callers (e.g. http.Request.GetBody) can replay the body concurrently
// with, or after, other readers without sharing seek state. Closing the
// returned reader releases only that reader, never the storage itself;
// after the storage has been closed, NewReader returns ErrStorageClosed.
NewReader() (io.ReadCloser, error)
}
BodyStorage 请求体存储接口
func CreateBodyStorage ¶
func CreateBodyStorage(data []byte) (BodyStorage, error)
CreateBodyStorage 根据数据大小创建合适的存储
func CreateBodyStorageFromReader ¶
func CreateBodyStorageFromReader(reader io.Reader, contentLength int64, maxBytes int64) (BodyStorage, error)
CreateBodyStorageFromReader 从 Reader 创建存储(用于大请求的流式处理)
func GetBodyStorage ¶
func GetBodyStorage(c *gin.Context) (BodyStorage, error)
GetBodyStorage 获取请求体存储对象(用于需要多次读取的场景)
type ChannelQuotaAlertEvent ¶
type ChannelQuotaAlertEvent struct {
Status string `json:"status"`
Kind string `json:"kind"`
DedupKey string `json:"dedup_key"`
Suppressed bool `json:"suppressed"`
NextEligible int64 `json:"next_eligible_at,omitempty"`
}
ChannelQuotaAlertEvent is the notifier-neutral result of applying an alert policy to two consecutive observations. Keeping this decision pure allows the API/UI to preview state and lets a later notifier persist delivery state without coupling quota sampling to email/webhook credentials.
func EvaluateChannelQuotaAlertTransition ¶
func EvaluateChannelQuotaAlertTransition(subject, previousStatus, currentStatus string, observedAt, lastNotifiedAt int64, settings ChannelQuotaAlertSettings) ChannelQuotaAlertEvent
EvaluateChannelQuotaAlertTransition decides whether a transition is eligible for notification. Empty/unknown statuses never emit events. repeated warning/critical states are deduplicated by cooldown; recovery is opt-in. No notification is sent by this helper.
type ChannelQuotaAlertOccurrenceInput ¶
type ChannelQuotaAlertOccurrenceInput struct {
SubjectRef string
SourceSnapshotRef string
PreviousStatus string
CurrentStatus string
ObservedAt int64
LastDeliveredAt int64
SourceTrusted bool
HasProviderTotal bool
}
ChannelQuotaAlertOccurrenceInput is the bounded, redacted input required to derive an event identity for a future persistent alert pipeline. SubjectRef must be the canonical channel:<positive decimal id> form. SourceSnapshotRef must be the canonical snapshot:<positive decimal id> form; that snapshot ID identifies one immutable normalized observation. Neither accepts names, URLs, provider responses, credentials, request bodies, or arbitrary opaque identifiers. The future persistence boundary must verify that both IDs belong to the same authorized scope before calling this pure helper.
type ChannelQuotaAlertOccurrenceOutcome ¶
type ChannelQuotaAlertOccurrenceOutcome struct {
Status string `json:"status"`
Kind string `json:"kind"`
EventKey string `json:"event_key"`
Suppressed bool `json:"suppressed"`
NextEligible int64 `json:"next_eligible_at,omitempty"`
}
ChannelQuotaAlertOccurrenceOutcome is a notifier-neutral event candidate. EventKey is a SHA-256 digest over bounded redacted identifiers and the occurrence identity, so it does not expose the input references. A blank EventKey means no event may be persisted or delivered.
func EvaluateChannelQuotaAlertOccurrenceV2 ¶
func EvaluateChannelQuotaAlertOccurrenceV2(input ChannelQuotaAlertOccurrenceInput, settings ChannelQuotaAlertSettings) ChannelQuotaAlertOccurrenceOutcome
EvaluateChannelQuotaAlertOccurrenceV2 derives a versioned event identity without DB, network, notifier, routing, or configuration side effects.
Unlike the legacy EvaluateChannelQuotaAlertTransition helper, EventKey is tied to an immutable source snapshot and occurrence kind. A later healthy->critical transition or a later reminder therefore cannot be permanently suppressed by a historical <subject>:<status> delivery key. Invalid, untrusted, disabled, total-less, or unknown inputs fail closed.
type ChannelQuotaAlertSettings ¶
type ChannelQuotaAlertSettings struct {
Enabled bool `json:"enabled"`
WarningPercent float64 `json:"warning_percent"`
CriticalPercent float64 `json:"critical_percent"`
// CooldownSeconds controls how often a repeated alert for the same
// channel/status may be emitted by a future notifier. A zero value is
// accepted for backwards-compatible JSON options and uses the safe default
// during policy evaluation.
CooldownSeconds int64 `json:"cooldown_seconds"`
// NotifyOnRecovery opts in to a single healthy transition after a warning
// or critical state. It is metadata only until an outbound notifier is
// explicitly configured; this package never sends network requests.
NotifyOnRecovery bool `json:"notify_on_recovery"`
}
func DefaultChannelQuotaAlertSettings ¶
func DefaultChannelQuotaAlertSettings() ChannelQuotaAlertSettings
func ParseChannelQuotaAlertSettings ¶
func ParseChannelQuotaAlertSettings(raw string) (ChannelQuotaAlertSettings, error)
type ChannelQuotaIdentityKey ¶
ChannelQuotaIdentityKey is one HMAC key in the deployment-wide quota identity keyring. Secret is intentionally excluded from JSON output.
type ChannelQuotaIdentityKeyring ¶
type ChannelQuotaIdentityKeyring struct {
Active ChannelQuotaIdentityKey `json:"active"`
Retired []ChannelQuotaIdentityKey `json:"retired,omitempty"`
}
ChannelQuotaIdentityKeyring contains exactly one active key and up to four retired keys. Retired keys are lookup-only and allow aliases created before a rotation to converge on the same opaque subject.
func LoadChannelQuotaIdentityKeyring ¶
func LoadChannelQuotaIdentityKeyring() (ChannelQuotaIdentityKeyring, error)
LoadChannelQuotaIdentityKeyring reads the dedicated cross-node key configuration. It never falls back to SessionSecret or CryptoSecret.
func ParseChannelQuotaIdentityKeys ¶
func ParseChannelQuotaIdentityKeys(raw string) (ChannelQuotaIdentityKeyring, error)
ParseChannelQuotaIdentityKeys parses a comma-separated keyring. Every entry has the exact form "role:version:base64url-key", where role is active or retired and the key uses unpadded base64url. Example:
active:v2:<key>,retired:v1:<key>
Exactly one active entry is required. Version identifiers are 1-32 ASCII letters, digits, dots, underscores, or hyphens. Decoded keys must contain at least 32 bytes. Errors deliberately omit configuration contents.
type CustomEvent ¶
CustomEvent does not synchronize writes to the response writer. Streaming callers must serialize event writes at the stream level.
func (CustomEvent) Render ¶
func (r CustomEvent) Render(w http.ResponseWriter) error
func (CustomEvent) WriteContentType ¶
func (r CustomEvent) WriteContentType(w http.ResponseWriter)
type DatabaseType ¶
type DatabaseType string
const ( DatabaseTypeMySQL DatabaseType = "mysql" DatabaseTypeSQLite DatabaseType = "sqlite" DatabaseTypePostgreSQL DatabaseType = "postgres" DatabaseTypeClickHouse DatabaseType = "clickhouse" )
func LogDatabaseType ¶
func LogDatabaseType() DatabaseType
func MainDatabaseType ¶
func MainDatabaseType() DatabaseType
type DiskCacheConfig ¶
type DiskCacheConfig struct {
// Enabled 是否启用磁盘缓存
Enabled bool
// ThresholdMB 触发磁盘缓存的请求体大小阈值(MB)
ThresholdMB int
// MaxSizeMB 磁盘缓存最大总大小(MB)
MaxSizeMB int
// Path 磁盘缓存目录
Path string
}
DiskCacheConfig 磁盘缓存配置(由 performance_setting 包更新)
func GetDiskCacheConfig ¶
func GetDiskCacheConfig() DiskCacheConfig
GetDiskCacheConfig 获取磁盘缓存生效代快照。 单次调用返回同一代的全部字段,调用方应在一个决策内复用该快照, 而不是逐字段多次读取(避免代切换期间混代)。
func GetDiskCacheDesiredConfig ¶
func GetDiskCacheDesiredConfig() DiskCacheConfig
GetDiskCacheDesiredConfig 获取磁盘缓存配置代(最近保存值)快照。 用于维护端点与状态展示比对“已保存未生效”的放置字段。
func RebuildDiskCache ¶
func RebuildDiskCache() (DiskCacheConfig, error)
RebuildDiskCache 按配置代重建磁盘缓存放置(维护操作,带排空语义)。
先在旧生效代继续服务的前提下校验新目录可创建、可写;校验成功后一次性把 配置代的 Path/MaxSizeMB 换入生效代,此后新决策使用新目录/新容量。 已经打开的磁盘缓存实例按绝对路径读写/删除自己的文件,不受影响、不迁移。 校验失败时保留旧生效代并返回错误。
返回重建后的生效代快照。
type DiskCacheStats ¶
type DiskCacheStats struct {
// 当前活跃的磁盘缓存文件数
ActiveDiskFiles int64 `json:"active_disk_files"`
// 当前磁盘缓存总大小(字节)
CurrentDiskUsageBytes int64 `json:"current_disk_usage_bytes"`
// 当前内存缓存数量
ActiveMemoryBuffers int64 `json:"active_memory_buffers"`
// 当前内存缓存总大小(字节)
CurrentMemoryUsageBytes int64 `json:"current_memory_usage_bytes"`
// 磁盘缓存命中次数
DiskCacheHits int64 `json:"disk_cache_hits"`
// 内存缓存命中次数
MemoryCacheHits int64 `json:"memory_cache_hits"`
// 磁盘缓存最大限制(字节)
DiskCacheMaxBytes int64 `json:"disk_cache_max_bytes"`
// 磁盘缓存阈值(字节)
DiskCacheThresholdBytes int64 `json:"disk_cache_threshold_bytes"`
}
DiskCacheStats 磁盘缓存统计信息
type DiskCacheType ¶
type DiskCacheType string
DiskCacheType 磁盘缓存类型
const ( DiskCacheTypeBody DiskCacheType = "body" // 请求体缓存 DiskCacheTypeFile DiskCacheType = "file" // 文件数据缓存 )
type DiskSpaceInfo ¶
type DiskSpaceInfo struct {
// 总空间(字节)
Total uint64 `json:"total"`
// 可用空间(字节)
Free uint64 `json:"free"`
// 已用空间(字节)
Used uint64 `json:"used"`
// 使用百分比
UsedPercent float64 `json:"used_percent"`
}
DiskSpaceInfo 磁盘空间信息
func GetDiskSpaceInfo ¶
func GetDiskSpaceInfo() DiskSpaceInfo
GetDiskSpaceInfo 获取缓存目录所在磁盘的空间信息 (Unix/Linux/macOS)
type EndpointInfo ¶
func GetDefaultEndpointInfo ¶
func GetDefaultEndpointInfo(et constant.EndpointType) (EndpointInfo, bool)
GetDefaultEndpointInfo 返回指定端点类型的默认信息以及是否存在
type InMemoryRateLimiter ¶
type InMemoryRateLimiter struct {
// contains filtered or unexported fields
}
func (*InMemoryRateLimiter) Allow ¶
func (l *InMemoryRateLimiter) Allow(key string, maxRequestNum int, duration int64) bool
Allow reports whether a request would fit in the current window without recording it. This is used when the event is only countable after its outcome is known, such as successful upstream requests.
func (*InMemoryRateLimiter) Commit ¶
func (l *InMemoryRateLimiter) Commit(reservation RateLimitReservation, maxRequestNum int, duration int64)
Commit 把在途预留转正为窗口内的已提交记录。预留已随窗口过期时,仅在窗口 仍有空位时补记,绝不突破 maxRequestNum 上限。零值预留为空操作。
func (*InMemoryRateLimiter) Init ¶
func (l *InMemoryRateLimiter) Init(expirationDuration time.Duration)
func (*InMemoryRateLimiter) Release ¶
func (l *InMemoryRateLimiter) Release(reservation RateLimitReservation)
Release 释放失败请求的在途预留,额度立即可被新请求使用。零值预留或预留 已不存在时为无害空操作。
func (*InMemoryRateLimiter) Request ¶
func (l *InMemoryRateLimiter) Request(key string, maxRequestNum int, duration int64) bool
Request parameter duration's unit is seconds
func (*InMemoryRateLimiter) Reserve ¶
func (l *InMemoryRateLimiter) Reserve(key string, maxRequestNum int, duration int64) (RateLimitReservation, bool)
Reserve 在窗口内原子占位:窗口内已提交记录数 + 在途预留数永不超过 maxRequestNum。maxRequestNum<=0 时保持“不限制”语义,返回零值预留并放行。 调用方必须在请求结束后按结果结算:成功 Commit,失败 Release;结果未知 (无法执行结算的路径)则不结算,预留随窗口过期自然回收。
type NodeIdentity ¶
type NodeIdentity struct {
Name string `json:"name"`
Source string `json:"source"`
ManuallyConfigured bool `json:"manually_configured"`
ShouldConfigureManually bool `json:"should_configure_manually"`
}
func GetNodeIdentity ¶
func GetNodeIdentity() NodeIdentity
type PageInfo ¶
type PageInfo struct {
Page int `json:"page"` // page num 页码
PageSize int `json:"page_size"` // page size 页大小
Total int `json:"total"` // 总条数,后设置
Items any `json:"items"` // 数据,后设置
}
func GetPageQuery ¶
func (*PageInfo) GetPageSize ¶
func (*PageInfo) GetStartIdx ¶
type PerformanceMonitorConfig ¶
type PerformanceMonitorConfig struct {
Enabled bool
CPUThreshold int
MemoryThreshold int
DiskThreshold int
}
PerformanceMonitorConfig 性能监控配置
func GetPerformanceMonitorConfig ¶
func GetPerformanceMonitorConfig() PerformanceMonitorConfig
GetPerformanceMonitorConfig 获取性能监控配置
type QuotaClamp ¶
type QuotaClamp struct {
Op string `json:"op"` // "QuotaFromFloat" | "QuotaRound" | "QuotaFromDecimal"
Kind QuotaClampKind `json:"kind"` // "overflow" | "underflow" | "nan"
Original float64 `json:"original"` // best-effort pre-clamp value (decimal -> float64 approx)
Clamped int `json:"clamped"` // the saturated result actually used
}
QuotaClamp describes a single saturation event: a quota conversion whose input fell outside the representable int32 range (or was NaN) and was therefore clamped. It is surfaced to billing callers so the event can be recorded on the related consume/task log for admin auditing.
func QuotaFromDecimalChecked ¶
func QuotaFromDecimalChecked(d decimal.Decimal) (int, *QuotaClamp)
QuotaFromDecimalChecked is QuotaFromDecimal but also returns a non-nil *QuotaClamp when the value was clamped, so billing callers can audit it.
func QuotaFromFloatChecked ¶
func QuotaFromFloatChecked(value float64) (int, *QuotaClamp)
QuotaFromFloatChecked is QuotaFromFloat but also returns a non-nil *QuotaClamp when the value was clamped, so billing callers can audit it.
func QuotaRoundChecked ¶
func QuotaRoundChecked(value float64) (int, *QuotaClamp)
QuotaRoundChecked is QuotaRound but also returns a non-nil *QuotaClamp when the value was clamped, so billing callers can audit it.
func (*QuotaClamp) AuditMap ¶
func (c *QuotaClamp) AuditMap() map[string]interface{}
AuditMap renders the clamp as the marker stored under a log's admin_info.quota_saturation. Centralized here so every billing path (consume logs, task billing logs, task compensation logs) records the same shape.
func (*QuotaClamp) Error ¶
func (c *QuotaClamp) Error() string
Error lets the same typed value serve both as the settlement audit marker and as the fail-fast error returned by strict pre-consume conversions.
type QuotaClampKind ¶
type QuotaClampKind string
QuotaClampKind identifies why a quota conversion had to be saturated.
const ( QuotaClampOverflow QuotaClampKind = "overflow" QuotaClampUnderflow QuotaClampKind = "underflow" QuotaClampNaN QuotaClampKind = "nan" )
Clamp kinds reported by QuotaClamp.Kind.
type RateLimitReservation ¶
type RateLimitReservation struct {
// contains filtered or unexported fields
}
RateLimitReservation 是 Reserve 返回的在途预留句柄。零值表示未预留, Commit/Release 对零值是无害空操作。
type ReplayableBody ¶
ReplayableBody is an outbound request body that can report its byte size and create independent readers for transport-level retries.
func NewReplayableBodyReader ¶
func NewReplayableBodyReader(storage BodyStorage) ReplayableBody
NewReplayableBodyReader exposes the replay capabilities of storage without exposing io.Closer. This keeps ownership of the storage lifecycle with the caller instead of allowing net/http to close it as the request body.
type SSRFProtection ¶
type SSRFProtection struct {
AllowPrivateIp bool
DomainFilterMode bool // true: 白名单, false: 黑名单
DomainList []string // domain format, e.g. example.com, *.example.com
IpFilterMode bool // true: 白名单, false: 黑名单
IpList []string // CIDR or single IP
AllowedPorts []int // 允许的端口范围
ApplyIPFilterForDomain bool // 对域名启用IP过滤
}
SSRFProtection SSRF防护配置
func NewSSRFProtectionFromFetchSetting ¶
func NewSSRFProtectionFromFetchSetting(allowPrivateIp bool, domainFilterMode bool, ipFilterMode bool, domainList, ipList, allowedPorts []string, applyIPFilterForDomain bool) (*SSRFProtection, error)
NewSSRFProtectionFromFetchSetting builds an SSRFProtection from persisted fetch_setting values.
func (*SSRFProtection) IsIPAccessAllowed ¶
func (p *SSRFProtection) IsIPAccessAllowed(ip net.IP) bool
IsIPAccessAllowed 检查IP是否允许访问
func (*SSRFProtection) ValidateNetworkTarget ¶
func (p *SSRFProtection) ValidateNetworkTarget(host string, port int) error
ValidateNetworkTarget validates the host and port before dialing.
func (*SSRFProtection) ValidateResolvedIP ¶
func (p *SSRFProtection) ValidateResolvedIP(host string, ip net.IP) error
ValidateResolvedIP validates a domain's resolved IP immediately before dialing it.
func (*SSRFProtection) ValidateURL ¶
func (p *SSRFProtection) ValidateURL(urlStr string) error
ValidateURL 验证URL是否安全
type SystemStatus ¶
SystemStatus 系统状态信息
type TaskRecoveryRequestFingerprintMaterial ¶
type TaskRecoveryRequestFingerprintMaterial struct {
TokenID int64
HTTPMethod string
OperationKind string
RouteBinding string
ContentFamily string
CanonicalBodyDigest [sha256.Size]byte
}
TaskRecoveryRequestFingerprintMaterial is the normalized, non-secret scope of one submission request. It intentionally excludes the raw idempotency key, client/network identity, routing choice, model, price, and time.
Source Files
¶
- account_quota_threshold.go
- api_type.go
- audio.go
- body_storage.go
- canonical_json.go
- channel_quota_alert.go
- channel_quota_alert_status.go
- channel_quota_identity_keys.go
- constants.go
- copy.go
- crypto.go
- custom-event.go
- database.go
- disk_cache.go
- disk_cache_config.go
- email-outlook-auth.go
- email.go
- email_ntlm_auth.go
- embed-file-system.go
- endpoint_defaults.go
- endpoint_type.go
- env.go
- gin.go
- go-channel.go
- gopool.go
- hash.go
- init.go
- ip.go
- json.go
- model.go
- node_identity.go
- page_info.go
- performance_config.go
- pprof.go
- proxy_url.go
- pyro.go
- quota.go
- quota_math.go
- rate-limit.go
- redis.go
- relay_scheduling.go
- request_body_limit.go
- request_diagnostics.go
- session_cookie.go
- ssrf_protection.go
- str.go
- sys_log.go
- system_monitor.go
- system_monitor_unix.go
- task_recovery_key.go
- task_recovery_request_fingerprint.go
- topup-ratio.go
- totp.go
- url_validator.go
- utils.go
- validate.go
- verification.go