service

package
v0.16.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 20, 2026 License: MIT Imports: 29 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package service contains the business logic layer: checkin, balance, notify, OAuth, and backup services.

Package service provides time and date formatting utilities that mirror the TS localTimeService.ts behavior.

Package service hosts the SQL-backed routing store that feeds the token router (moved from app/proxy_upstream.go so the app layer stays pure wiring). The channel/account/site join columns used by several loaders are kept in the channelAccountSiteSelect fragment so a store schema change is a one-line edit here instead of a silent drift across three queries.

Index

Constants

View Source
const (
	TokenValueStatusReady         = "ready"
	TokenValueStatusMaskedPending = "masked_pending"
)
View Source
const EffectiveProxyTokensOnActiveSitesSQL = `` /* 187-byte string literal not displayed */

EffectiveProxyTokensOnActiveSitesSQL is EffectiveProxyTokensSQL plus a site-status branch that zeroes rows of disabled sites. Use only for LEFT JOIN paths that keep all rows for counting but must not pollute token aggregates; requires the `s` alias. Under an INNER JOIN + active filter the branch is a no-op, so prefer the base expression there.

View Source
const EffectiveProxyTokensSQL = `` /* 153-byte string literal not displayed */

EffectiveProxyTokensSQL returns a SQL expression that prefers total_tokens and falls back to prompt_tokens + completion_tokens. Avoids under-counting partial upstream usage payloads and avoids double-counting when both are set. Requires the proxy_logs alias `pl`; site filtering (if any) is done by the caller's WHERE clause.

View Source
const SiteSelectColumns = `` /* 408-byte string literal not displayed */

SiteSelectColumns lists known sites columns for SELECT (never SELECT *). Shared PG CI DBs may have leftover probe columns from schema experiments; SELECT * would fail struct scan with "missing destination name...".

Variables

This section is empty.

Functions

func AccountFor added in v0.13.0

func AccountFor(account *store.Account, site *store.Site) string

AccountFor returns the stable Resin account identity for an existing account. The identity is acc-{Account.ID} using the immutable auto-increment PK. Returns "" when the account row has no ID yet (pre-account flows should use TempAccountFor instead).

func ApplyRedirectFixes

func ApplyRedirectFixes(ctx context.Context, db *sqlx.DB, candidates []RedirectFixCandidate) (int, error)

ApplyRedirectFixes removes the disabled entries that ListRedirectFixCandidates reports (only after operator confirmation). Returns the number removed.

func ApplySiteStatusSideEffects

func ApplySiteStatusSideEffects(db *sqlx.DB, siteID int64, siteName string, newStatus string) error

ApplySiteStatusSideEffects handles status change side effects for sites.

func BatchUpdateTokenStatus

func BatchUpdateTokenStatus(db *sqlx.DB, tokenIDs []int64, enabled bool) error

BatchUpdateTokenStatus batch-updates enabled status for tokens.

func BuildMergedSub2ApiAuth

func BuildMergedSub2ApiAuth(existingExtraConfig *string, refreshToken *string, tokenExpiresAt *int64, extraConfigPatch map[string]any) map[string]any

BuildMergedSub2ApiAuth builds the next sub2apiAuth object for a sub2api account. Sources (later wins for the same field): 1. existing extraConfig.sub2apiAuth 2. optional nested extraConfigPatch["sub2apiAuth"] 3. top-level refreshToken / tokenExpiresAt pointers

Returns nil when there are no valid fields to write (caller should leave extraConfig alone).

func BuildPlatformProxyConfig

func BuildPlatformProxyConfig(cfg *config.Config, account *store.Account, site *store.Site) *platform.ProxyConfig

BuildPlatformProxyConfig resolves account and site proxy settings for platform calls.

Precedence (highest to lowest):

  1. key proxy (applied separately via proxy.ApplyKeyProxyOverride)
  2. account extraConfig.proxyUrl (explicit per-account proxy)
  3. site.ProxyURL (explicit per-site proxy)
  4. Resin sticky forward proxy (when RESIN_ENABLED and identity available)
  5. system proxy (account extraConfig.useSystemProxy or site.UseSystemProxy)
  6. direct (no proxy)

The Resin tier sits between explicit proxy URLs and the generic system-proxy opt-in so an operator who sets a per-account/per-site proxy still wins, but Resin takes priority over the shared SYSTEM_PROXY_URL. Resin requires a business identity: acc-{account.ID} when the account row exists. For pre-account flows (verify/login/create) with no account row yet, use BuildPlatformProxyConfigForToken which derives a deterministic temp identity.

func BuildPlatformProxyConfigForToken added in v0.13.0

func BuildPlatformProxyConfigForToken(cfg *config.Config, site *store.Site, rawToken string) *platform.ProxyConfig

BuildPlatformProxyConfigForToken is the pre-account variant of BuildPlatformProxyConfig for verify-token / login / create flows where no Account row exists yet. It derives a deterministic temp Resin identity from (siteID, rawToken) so all pre-account requests for the same token share an egress IP, then (in Tier 2) inherit-lease can transfer the lease to the stable acc-{id} identity after INSERT.

Precedence matches BuildPlatformProxyConfig with the temp identity filling the resin tier: site.ProxyURL > resin(temp) > system > direct.

func BuildStoredSub2ApiSubscriptionSummary

func BuildStoredSub2ApiSubscriptionSummary(summary any) map[string]any

BuildStoredSub2ApiSubscriptionSummary builds a storable subscription summary.

func BuildTimeFootnote

func BuildTimeFootnote(t time.Time) string

BuildTimeFootnote builds the time footnote string for notifications.

func CanonicalFromActual

func CanonicalFromActual(actual string, candidates []string) (canonical string, ok bool)

CanonicalFromActual finds the canonical candidate for an actual model name. Rule priority: exact (case-folded) → date suffix → version suffix. Returns ok=false when no candidate matches. candidates are case-folded canonical names; canonicalName is the original (unfolded) form matched against.

func CanonicalizeSiteURL

func CanonicalizeSiteURL(rawURL string) string

CanonicalizeSiteURL returns a canonical URL for persistence. Mirrors TS analyzePrimarySiteUrl().persistedUrl behavior.

func ClearResinLeasesForTest added in v0.13.0

func ClearResinLeasesForTest()

ClearResinLeasesForTest empties the lease tracker. Test-only — production relies on ActiveLeases' lazy pruning.

func CreateEvent

func CreateEvent(db *sqlx.DB, eventType string, title string, message string, level string, relatedID int64, relatedType string) error

CreateEvent creates an event entry.

func CreateSite

func CreateSite(db *sqlx.DB, siteData map[string]any) (int64, error)

CreateSite creates a new site with apiEndpoints in a transaction.

func DecryptAccountPassword

func DecryptAccountPassword(cfg *config.Config, cipherText string) string

DecryptAccountPassword decrypts a ciphertext produced by EncryptAccountPassword. Returns empty string on any failure (mirrors TS: returns null/error silently).

func DecryptPassword

func DecryptPassword(cfg *config.Config, cipherText string) string

DecryptPassword decrypts a password from extraConfig.

func DeleteAccount

func DeleteAccount(db *sqlx.DB, id int64) error

DeleteAccount deletes an account by ID.

func DeleteSite

func DeleteSite(db *sqlx.DB, siteID int64) error

DeleteSite deletes a site by ID (cascade via DB foreign keys).

func DeleteTokenByID

func DeleteTokenByID(db *sqlx.DB, tokenID int64) error

DeleteTokenByID deletes a token by ID with upstream-first strategy. The caller must handle the upstream deletion before calling this.

func EncryptAccountPassword

func EncryptAccountPassword(cfg *config.Config, password string) (string, error)

EncryptAccountPassword encrypts a password with AES-256-GCM. Returns "v1:base64url(iv):base64url(tag):base64url(ciphertext)". Mirrors TS encryptAccountPassword().

func EncryptPassword

func EncryptPassword(cfg *config.Config, password string) (string, error)

EncryptPassword encrypts a password for storage in extraConfig.autoRelogin.passwordCipher.

func EnsureDefaultTokenForAccount

func EnsureDefaultTokenForAccount(db *sqlx.DB, accountID int64, tokenValue string, name, source, tokenGroup string, enabled bool) (int64, error)

EnsureDefaultTokenForAccount ensures a token exists and is default for a given account. Mirrors TS ensureDefaultTokenForAccount(), with preserve semantics: on an existing token match by value, operator-set name and enabled are kept (callers often pass name="default"; that must not clobber a real key name).

func EstimateRewardWithTodayIncomeFallback

func EstimateRewardWithTodayIncomeFallback(input EstimateRewardInput) float64

EstimateRewardWithTodayIncomeFallback estimates reward using todayIncome fallback. Mirrors TS estimateRewardWithTodayIncomeFallback().

func FormatLocalDate

func FormatLocalDate(t time.Time) string

FormatLocalDate formats a time in the local timezone as "2006-01-02". Mirrors TS formatLocalDate().

func FormatLocalDateTime

func FormatLocalDateTime(t time.Time) string

FormatLocalDateTime formats a time in the local timezone as "2006-01-02 15:04:05". Mirrors TS formatLocalDateTime().

func FormatUtcSqlDateTime

func FormatUtcSqlDateTime(t time.Time) string

FormatUtcSqlDateTime formats a time as "YYYY-MM-DD HH:MM:SS" in UTC. Mirrors TS formatUtcSqlDateTime().

func ForwardProxyURL added in v0.13.0

func ForwardProxyURL(cfg *config.Config, platform, account string) (string, bool)

ForwardProxyURL builds the HTTP forward-proxy URL with embedded proxy-auth userinfo. The username is "{Platform}.{Account}" and the password is the resin token. Go's http.Transport reads the proxy URL userinfo and emits the Proxy-Authorization: Basic header automatically — no manual header needed.

Returns ("", false) when Resin is misconfigured or platform/account empty.

func GenerateModelRedirects

func GenerateModelRedirects(ctx context.Context, db *sqlx.DB, accountID int64, actualModels []string) (int, error)

GenerateModelRedirects sync-generates mappings for one account's actual model list. Best-effort: never overwrites manual rows, idempotent (upsert), updates last_seen_at for still-visible actual names. Returns the number of created mappings.

func GetAccountByID

func GetAccountByID(db *sqlx.DB, id int64) (*store.Account, error)

GetAccountByID fetches an account by its ID.

func GetDefaultTokenForAccount

func GetDefaultTokenForAccount(db *sqlx.DB, accountID int64) (*store.AccountToken, error)

GetDefaultTokenForAccount returns the default token for an account.

func GetLocalTokenGroups

func GetLocalTokenGroups(db *sqlx.DB, accountID int64) ([]string, error)

GetLocalTokenGroups returns distinct token groups stored for the account.

func GetNextAccountSortOrder

func GetNextAccountSortOrder(db *sqlx.DB) (int64, error)

GetNextAccountSortOrder returns the next sortOrder value for new accounts.

func GetPlatformUserIdFromExtraConfig

func GetPlatformUserIdFromExtraConfig(extraConfig *string) (int64, bool)

GetPlatformUserIdFromExtraConfig reads platformUserId from extraConfig.

func GetProxyURLFromExtraConfig

func GetProxyURLFromExtraConfig(extraConfig *string) string

GetProxyURLFromExtraConfig reads proxyUrl from extraConfig.

func GetResolvedTimeZone

func GetResolvedTimeZone() string

GetResolvedTimeZone returns the current system timezone identifier. Mirrors TS getResolvedTimeZone().

func GetSub2ApiAuthFromExtraConfig

func GetSub2ApiAuthFromExtraConfig(extraConfig *string) map[string]any

GetSub2ApiAuthFromExtraConfig reads sub2apiAuth from extraConfig.

func GetTodayIncomeDelta

func GetTodayIncomeDelta(extraConfig *string, day string) float64

GetTodayIncomeDelta returns the income delta for the current day. Mirrors TS getTodayIncomeDelta().

func GetTodayIncomeValue

func GetTodayIncomeValue(extraConfig *string, day string) float64

GetTodayIncomeValue returns the latest income value for the given day. Mirrors TS getTodayIncomeValue().

func GetTodayUnixSecondsRange

func GetTodayUnixSecondsRange(t time.Time) (start, end int64)

GetTodayUnixSecondsRange returns the start and end of today as Unix timestamps. Mirrors TS getTodayUnixSecondsRange().

func GetTokenByID

func GetTokenByID(db *sqlx.DB, id int64) (*store.AccountToken, error)

GetTokenByID fetches a token by its ID.

func GetTokenGroups

func GetTokenGroups(
	ctx context.Context,
	db *sqlx.DB,
	accountID int64,
	adapter platform.PlatformAdapter,
	baseURL, accessToken string,
	platformUserID *int,
	proxy *platform.ProxyConfig,
) ([]string, error)

GetTokenGroups prefers platform.GetUserGroups for session accounts when an adapter and access token are available. Falls back to local DISTINCT token_group on adapter nil, missing access token, upstream error, or empty upstream result. Upstream errors are swallowed so local groups remain usable.

func GetUseSystemProxyFromExtraConfig

func GetUseSystemProxyFromExtraConfig(extraConfig *string) bool

GetUseSystemProxyFromExtraConfig reads useSystemProxy from extraConfig.

func GuessPlatformUserIdFromUsername

func GuessPlatformUserIdFromUsername(username *string) int64

GuessPlatformUserIdFromUsername attempts to parse the username as a numeric user ID.

func HasSessionToken

func HasSessionToken(accessToken string) bool

HasSessionToken checks whether the account has a valid session token value.

func InsertAccount

func InsertAccount(db *sqlx.DB, account map[string]any) (int64, error)

InsertAccount inserts a new account and returns the ID.

func InvalidateSiteCaches

func InvalidateSiteCaches()

InvalidateSiteCaches invalidates both site proxy and token router caches.

func InvalidateSiteProxyCache

func InvalidateSiteProxyCache()

InvalidateSiteProxyCache refreshes process-local caches that depend on site/proxy config. Always invalidates the token-router route cache; then runs registered hooks (admin accounts snapshot, future proxy config caches).

func InvalidateTokenRouterCache

func InvalidateTokenRouterCache()

InvalidateTokenRouterCache signals that cached token-router state should be invalidated. Implemented in route_rebuild.go (delegates to routing.InvalidateCache).

func IsAPIKeyConnection

func IsAPIKeyConnection(account *store.Account) bool

IsAPIKeyConnection checks if an account is an API key connection.

func IsForbiddenSiteTargetURL

func IsForbiddenSiteTargetURL(raw string) bool

IsForbiddenSiteTargetURL reports whether a site/endpoint URL must be rejected as a first-hop SSRF risk to cloud metadata / link-local targets. RFC1918 private and localhost remain allowed for lab/docker operators.

func IsManagedSub2ApiTokenDue

func IsManagedSub2ApiTokenDue(tokenExpiresAt any) bool

IsManagedSub2ApiTokenDue checks if a managed Sub2Api token needs refresh. A token is "due" if it expires within sub2apiRefreshLeadSeconds of now.

func IsMaskedPendingAccountToken

func IsMaskedPendingAccountToken(token *store.AccountToken) bool

IsMaskedPendingAccountToken checks if a token is in masked-pending state.

func IsMaskedTokenValue

func IsMaskedTokenValue(token string) bool

IsMaskedTokenValue checks if a token value contains masking characters. Mirrors TS isMaskedTokenValue().

func IsSub2ApiPlatform

func IsSub2ApiPlatform(platform string) bool

IsSub2ApiPlatform checks if a platform is Sub2Api.

func IsUnsupportedCheckinRuntimeHealth

func IsUnsupportedCheckinRuntimeHealth(health *RuntimeHealthEntry) bool

IsUnsupportedCheckinRuntimeHealth checks if the runtime health state represents an unsupported checkin degraded state that should be preserved during balance refresh. Mirrors TS isUnsupportedCheckinRuntimeHealth().

func IsUsableAccountToken

func IsUsableAccountToken(token *store.AccountToken) bool

IsUsableAccountToken checks if a token is usable (ready + enabled).

func IsValidAPIEndpointURL

func IsValidAPIEndpointURL(raw string) bool

IsValidAPIEndpointURL checks whether a normalized URL is a valid http(s) URL. Also rejects cloud metadata / link-local targets via IsForbiddenSiteTargetURL so any future caller is safe by default (parity with).

func IsValidHTTPURL

func IsValidHTTPURL(raw string) bool

IsValidHTTPURL checks whether a string is a valid http/https URL (not socks). Empty is valid (optional field). Also rejects cloud metadata / link-local targets via IsForbiddenSiteTargetURL so externalCheckin and similar callers cannot store first-hop SSRF URLs (extends).

func IsValidProxyURL

func IsValidProxyURL(raw string) bool

IsValidProxyURL checks whether a string is a valid http(s)/socks proxy URL.

func ListAccountsWithSites

func ListAccountsWithSites(db *sqlx.DB) ([]map[string]any, error)

ListAccountsWithSites returns all accounts joined with their sites. Each account is enriched with nested site, capabilities, credentialMode, and effective runtimeHealth (expired status never reports healthy).

func ListAccountsWithSitesPaginated added in v0.13.0

func ListAccountsWithSitesPaginated(db *sqlx.DB, limit, offset int) ([]map[string]any, int64, error)

ListAccountsWithSitesPaginated returns a single page of accounts joined with their sites, plus the total row count matching the same join. Enrichment is identical to ListAccountsWithSites so a paginated page is byte-compatible with a slice of the unpaginated snapshot. Used by GET /api/accounts?page=... to bound the admin list response when the fleet grows (defensive pagination, same envelope as /api/channels and /api/checkin/logs).

func ListSites

func ListSites(db *sqlx.DB) ([]map[string]any, error)

ListSites returns all sites with apiEndpoints, totalBalance, and subscriptionSummary.

func ListTokensWithRelations

func ListTokensWithRelations(db *sqlx.DB, accountID *int64) ([]map[string]any, error)

ListTokensWithRelations returns tokens with account and site relations. Mirrors TS listTokensWithRelations().

func LoadSiteAPIEndpoints

func LoadSiteAPIEndpoints(db *sqlx.DB, siteIDs []int64) (map[int64][]store.SiteAPIEndpoint, error)

LoadSiteAPIEndpoints loads all api endpoints for a list of site IDs.

func LoadSiteWithEndpoints

func LoadSiteWithEndpoints(db *sqlx.DB, siteID int64) (map[string]any, error)

LoadSiteWithEndpoints loads a single site with its apiEndpoints attached.

func MarshalExtraConfig

func MarshalExtraConfig(config map[string]any) *string

MarshalExtraConfig marshals a map to a JSON string.

func MaskToken

func MaskToken(token, platform string) string

MaskToken masks a token value for display. Mirrors TS maskToken().

func MergeExtraConfig

func MergeExtraConfig(existing *string, patch map[string]any) *string

MergeExtraConfig merges a patch into an existing extraConfig JSON string.

func MergeSub2ApiAuth

func MergeSub2ApiAuth(existing map[string]any, refreshToken any, tokenExpiresAt any) map[string]any

MergeSub2ApiAuth merges managed auth fields onto an existing sub2apiAuth map. Valid new values overwrite; invalid/missing values preserve existing keys. Unrelated keys on existing are always preserved. Returns nil when empty.

func NormalizeGlobalWeight

func NormalizeGlobalWeight(input *float64) *float64

func NormalizeManagedRefreshToken

func NormalizeManagedRefreshToken(value any) (string, bool)

NormalizeManagedRefreshToken accepts a non-empty trimmed string refresh token. Returns ok=false for nil/empty/invalid values so callers preserve existing auth.

func NormalizeManagedTokenExpiresAt

func NormalizeManagedTokenExpiresAt(value any) (int64, bool)

NormalizeManagedTokenExpiresAt accepts a positive epoch-seconds value (number or numeric string). Returns ok=false when missing/invalid.

func NormalizeNullable

func NormalizeNullable(s *string) *string

NormalizeNullable returns nil for empty string, the value otherwise.

func NormalizeSiteAPIEndpointBaseUrl

func NormalizeSiteAPIEndpointBaseUrl(raw string) string

NormalizeSiteAPIEndpointBaseUrl normalizes a site API endpoint URL. Mirrors TS normalizeSiteApiEndpointBaseUrl(): parse URL, strip search/hash, remove trailing slash.

func NormalizeSortOrder

func NormalizeSortOrder(input *int) *int

func NormalizeTokenForDisplay

func NormalizeTokenForDisplay(token, platform string) string

NormalizeTokenForDisplay normalizes a token for display. Mirrors TS normalizeTokenForDisplay().

func NormalizeTokenGroups

func NormalizeTokenGroups(groups []string) []string

NormalizeTokenGroups trims, de-duplicates, and ensures a non-empty result. When every input is blank, returns ["default"].

func ParseExtraConfig

func ParseExtraConfig(raw *string) map[string]any

ParseExtraConfig parses an extraConfig field (JSON string) as a map.

func PopulateRouteChannelsByModelPattern

func PopulateRouteChannelsByModelPattern(ctx context.Context, db *sqlx.DB, routeID int64, modelPattern string) (inserted int, err error)

PopulateRouteChannelsByModelPattern is the create-path helper: insert automatic channels for a newly created pattern route without wiping existing rows.

func ProxyAwareHTTPClient

func ProxyAwareHTTPClient(proxyURL string, timeout time.Duration) *http.Client

ProxyAwareHTTPClient creates an *http.Client that optionally routes through a proxy. If proxyURL is empty, returns a standard client.

The client always wires platform.RejectCrossOriginRedirect so callers (notably notify/telegram) cannot follow a public-origin 302 onto a different host.

func RebuildRoutesBestEffort

func RebuildRoutesBestEffort()

RebuildRoutesBestEffort rebuilds pattern-route channels from current model availability and invalidates the token-router cache. Failures are logged and swallowed so account/site mutation paths stay best-effort.

func RegisterSiteProxyCacheInvalidator

func RegisterSiteProxyCacheInvalidator(fn func())

RegisterSiteProxyCacheInvalidator appends a hook invoked by InvalidateSiteProxyCache. Safe for concurrent registration; hooks should be idempotent and non-blocking.

func ReloadRedirectRegistry

func ReloadRedirectRegistry(ctx context.Context, db *sqlx.DB)

ReloadRedirectRegistry reloads the in-process redirect registry from model_name_redirects so the routing hot path sees the latest canonical→actual mappings. Call at startup and after any redirect mutation (sync generation, manual edits, deletes). Best-effort: on query failure it logs and leaves the previous registry intact.

func RepairDefaultToken

func RepairDefaultToken(db *sqlx.DB, accountID int64) (*store.AccountToken, error)

RepairDefaultToken finds and sets a new default token for an account. Mirrors TS repairDefaultToken().

func ResinEnabled added in v0.13.0

func ResinEnabled(cfg *config.Config, site *store.Site) bool

ResinEnabled reports whether Resin is active for the given site.

Precedence:

  1. site.ResinEnabled non-nil → explicit per-site override wins (true = force-enable even when global is off; false = force-disable even when global is on). This is the Tier 2 per-site override (#678).
  2. site.ResinEnabled nil → fall back to the global RESIN_ENABLED flag, which itself requires a non-empty RESIN_URL.

When site is nil only the global flag is consulted (used by wss runtime paths that don't have a site row in scope — the URL-rewrite / header gates there are advisory; per-site filtering already happened upstream in BuildPlatformProxyConfig).

func ResinGlobalEnabled added in v0.13.0

func ResinGlobalEnabled(cfg *config.Config) bool

ResinGlobalEnabled reports whether the global RESIN_ENABLED flag is set and a non-empty RESIN_URL is configured. This is the configuration-only view (ignores per-site overrides) and is used by the /api/admin/resin/status endpoint to surface the operator-facing global toggle state.

func ResolveAccountTokenValueStatus

func ResolveAccountTokenValueStatus(tokenRow *store.AccountToken) string

ResolveAccountTokenValueStatus resolves the valueStatus for a token.

func ResolvePlatformUserID

func ResolvePlatformUserID(extraConfig *string, username *string) int64

ResolvePlatformUserID resolves the platform user ID from extraConfig or username.

func ResolvePlatformUserIDPtr

func ResolvePlatformUserIDPtr(account *store.Account) *int

ResolvePlatformUserIDPtr returns a *int platform user id when one can be resolved from account extraConfig or a numeric username.

func ResolveResinPlatform added in v0.13.0

func ResolveResinPlatform(cfg *config.Config, site *store.Site) string

ResolveResinPlatform resolves the Platform identity: explicit config value wins, otherwise fall back to the site's platform. Returns "" when neither is available.

func RewriteWSURL added in v0.13.0

func RewriteWSURL(targetURL string, cfg *config.Config, platform, account string) string

RewriteWSURL rewrites a target wss/ws URL into Resin reverse-proxy form:

ws://{host}:{port}/{token}/{Platform}/{protocol}/{targetHost}{path}?query

where protocol is "https" for wss targets and "http" for ws targets (Resin requires the client→resin leg to always be ws). The Account identity is NOT embedded in the URL — it is sent via the X-Resin-Account header (handled by the caller). Returns "" when Resin is misconfigured, the platform/account is empty, or the target URL is not ws/wss.

func SetAccountRuntimeHealth

func SetAccountRuntimeHealth(db *sqlx.DB, accountID int64, entry RuntimeHealthEntry) error

SetAccountRuntimeHealth writes runtime health state into the account's extraConfig. Mirrors TS setAccountRuntimeHealth().

func SetDefaultToken

func SetDefaultToken(db *sqlx.DB, tokenID int64) (bool, error)

SetDefaultToken sets a token as the default for its account. Mirrors TS setDefaultToken().

func SetRouteRebuildDB

func SetRouteRebuildDB(db *sqlx.DB)

SetRouteRebuildDB sets the SQL handle used by RebuildRoutesBestEffort when store.GetDB() is not initialized (tests). Pass nil to clear.

func TempAccountFor added in v0.13.0

func TempAccountFor(siteID int64, token string) string

TempAccountFor returns a deterministic temp Resin identity for pre-account flows (verify/login/create) so all requests for the same token land on the same egress IP. The identity is tmp-{sha1(siteID:token) first 16 hex chars}. siteID may be 0; the identity remains deterministic per token.

The identity NEVER contains '.' or ':' (sha1 hex output is [0-9a-f]) so it is safe for Resin's proxy-auth splitting.

func TouchResinLease added in v0.13.0

func TouchResinLease(accountID string)

TouchResinLease records that accountID used Resin "now". Safe for concurrent calls; no-op when accountID is empty.

func UTLSEnabled added in v0.13.0

func UTLSEnabled(cfg *config.Config, site *store.Site) bool

UTLSEnabled resolves whether uTLS TLS fingerprint masking is active for a site. Per-site UseUTLS overrides the global UTLS_ENABLED flag:

  • site.UseUTLS != nil → explicit per-site decision (true/false)
  • site.UseUTLS == nil → fall back to cfg.UTLSEnabled (global default)

Mirrors the ResinEnabled resolution pattern so operators can globally opt in via UTLS_ENABLED=true and selectively disable specific sites with use_utls=false.

func UpdateAccountFields

func UpdateAccountFields(db *sqlx.DB, accountID int64, updates map[string]any) error

UpdateAccountFields updates specific fields on an account. UpdateAccountFields writes a set of account columns in one UPDATE.

func UpdateAccountFieldsTx added in v0.16.2

func UpdateAccountFieldsTx(tx *sqlx.Tx, accountID int64, updates map[string]any) error

UpdateAccountFieldsTx is the transaction variant of UpdateAccountFields. Use it within the same transaction that read-locked the account row so the read-merge-write of extra_config commits atomically (no lost updates).

func UpdateSite

func UpdateSite(db *sqlx.DB, siteID int64, updates map[string]any) error

UpdateSite updates a site and its apiEndpoints in a transaction.

func UpdateTodayIncomeSnapshot

func UpdateTodayIncomeSnapshot(extraConfig *string, todayIncome float64, now time.Time) *string

UpdateTodayIncomeSnapshot updates the todayIncome snapshot in extraConfig. Mirrors TS updateTodayIncomeSnapshot().

func UpdateTokenFields

func UpdateTokenFields(db *sqlx.DB, tokenID int64, updates map[string]any) error

UpdateTokenFields updates specific fields on a token.

func UpsertSiteAPIEndpoints

func UpsertSiteAPIEndpoints(tx *sqlx.Tx, siteID int64, endpoints []store.SiteAPIEndpoint) error

UpsertSiteAPIEndpoints replaces all apiEndpoints for a site within a transaction.

func ValidateSiteInitializationPreset

func ValidateSiteInitializationPreset(presetID, platform, rawURL string) error

ValidateSiteInitializationPreset checks createSite initializationPresetId. Empty id is allowed (optional field). When set: 1. preset must exist 2. preset.platform must equal the resolved site platform 3. when the preset has host/path match rules, the URL must match those rules (or the defaultUrl persisted-url fallback when platform-filtered).

Types

type AccountCapabilities

type AccountCapabilities struct {
	CanCheckin        bool `json:"canCheckin"`
	CanRefreshBalance bool `json:"canRefreshBalance"`
	ProxyOnly         bool `json:"proxyOnly"`
}

AccountCapabilities describes what an account can do.

func BuildCapabilitiesForAccount

func BuildCapabilitiesForAccount(account *store.Account) AccountCapabilities

BuildCapabilitiesForAccount returns the capabilities for an account.

func BuildCapabilitiesFromCredentialMode

func BuildCapabilitiesFromCredentialMode(mode AccountCredentialMode, hasSessionToken bool) AccountCapabilities

BuildCapabilitiesFromCredentialMode returns capabilities from credential mode.

type AccountCredentialMode

type AccountCredentialMode string

AccountCredentialMode is the credential mode for an account.

const (
	CredentialModeAuto    AccountCredentialMode = "auto"
	CredentialModeSession AccountCredentialMode = "session"
	CredentialModeAPIKey  AccountCredentialMode = "apikey"
)

func GetCredentialModeFromExtraConfig

func GetCredentialModeFromExtraConfig(extraConfig *string) AccountCredentialMode

GetCredentialModeFromExtraConfig reads credentialMode from extraConfig JSON.

func NormalizeCredentialMode

func NormalizeCredentialMode(input string) AccountCredentialMode

NormalizeCredentialMode normalizes a credential mode string.

func ResolveRequestedCredentialMode

func ResolveRequestedCredentialMode(input *string) AccountCredentialMode

ResolveRequestedCredentialMode resolves the requested credential mode from input.

func ResolveStoredCredentialMode

func ResolveStoredCredentialMode(account *store.Account) AccountCredentialMode

ResolveStoredCredentialMode resolves the effective credential mode from storage. 1. Read extraConfig.credentialMode; if explicit and != "auto", return it 2. Treat legacy mirrored accessToken/apiToken rows as "apikey" 3. If accessToken is non-empty, return "session" 4. Otherwise return "apikey"

type AccountWithSite

type AccountWithSite struct {
	Account store.Account `db:"accounts"`
	Site    store.Site    `db:"sites"`
}

GetAccountWithSite joins account with site.

func GetAccountWithSiteByID

func GetAccountWithSiteByID(db *sqlx.DB, id int64) (*AccountWithSite, error)

GetAccountWithSiteByID reads an account joined with its site (no row lock).

func GetAccountWithSiteByIDForUpdate added in v0.16.2

func GetAccountWithSiteByIDForUpdate(q accountQueryExecer, id int64) (*AccountWithSite, error)

GetAccountWithSiteByIDForUpdate reads the account joined with its site while locking the accounts row (PostgreSQL only: FOR UPDATE OF a; SQLite's single-connection pool already serializes transactions). Call it inside a transaction to make read-merge-write of mutable columns — notably extra_config — safe against concurrent lost updates.

type AutoReloginConfig

type AutoReloginConfig struct {
	Username       string
	PasswordCipher string
}

AutoReloginConfig holds credentials for auto-relogin.

func GetAutoReloginConfig

func GetAutoReloginConfig(extraConfig *string) *AutoReloginConfig

GetAutoReloginConfig reads autoRelogin from extraConfig. Returns nil if not configured.

type DetectResult

type DetectResult struct {
	URL                    string  `json:"url"`
	CanonicalURL           string  `json:"canonicalUrl"`
	Platform               string  `json:"platform"`
	SiteType               string  `json:"siteType"`
	Confidence             float64 `json:"confidence"`
	InitializationPresetID *string `json:"initializationPresetId,omitempty"`
}

DetectResult is the result of platform detection.

Platform/SiteType both hold the detected platform (SiteType mirrors the TS "siteType" naming; Platform is retained for backward compatibility with the existing /api/sites/detect consumers). Confidence is a coarse signal of how the platform was resolved (preset match = 1.0, hostname heuristic = 0.8). CanonicalURL is the normalized URL suitable for persistence/dedup.

func DetectSite

func DetectSite(rawURL string) *DetectResult

DetectSite attempts to detect the platform for a given URL. When a site initialization preset matches the URL, the result uses the preset protocol family (openai/claude) and includes initializationPresetId. Otherwise falls back to hostname heuristics for vendor/platform tags.

type EstimateRewardInput

type EstimateRewardInput struct {
	Day               string
	SuccessCount      int
	ParsedRewardCount int
	RewardSum         float64
	ExtraConfig       *string
}

EstimateRewardInput is the input for EstimateRewardWithTodayIncomeFallback.

type ImportAccountInput added in v0.11.0

type ImportAccountInput struct {
	Username    *string `json:"username,omitempty"`
	AccessToken string  `json:"accessToken,omitempty"`
	APIToken    string  `json:"apiToken,omitempty"`
}

ImportAccountInput is a lightweight account definition attached to an imported site. Imported accounts are stored as skipModelFetch API-key style credentials: the import wizard defers upstream model discovery to the normal background refresh instead of blocking the batch on per-account verification.

type ImportDuplicateStrategy added in v0.11.0

type ImportDuplicateStrategy string

ImportDuplicateStrategy controls how already-present sites are handled.

const (
	ImportDuplicateSkip  ImportDuplicateStrategy = "skip"
	ImportDuplicateMerge ImportDuplicateStrategy = "merge"
)

type ImportSiteInput added in v0.11.0

type ImportSiteInput struct {
	Name              string                  `json:"name"`
	URL               string                  `json:"url"`
	Platform          string                  `json:"platform,omitempty"`
	GlobalWeight      *float64                `json:"globalWeight,omitempty"`
	MaxConcurrency    *int64                  `json:"maxConcurrency,omitempty"`
	DuplicateStrategy ImportDuplicateStrategy `json:"duplicateStrategy,omitempty"`
	Accounts          []ImportAccountInput    `json:"accounts,omitempty"`
}

ImportSiteInput is one candidate site in a batch import.

type ImportSiteItemResult added in v0.11.0

type ImportSiteItemResult struct {
	Name   string `json:"name"`
	URL    string `json:"url"`
	Status string `json:"status"` // imported | merged | skipped | failed
	Reason string `json:"reason,omitempty"`
	SiteID int64  `json:"siteId,omitempty"`
}

ImportSiteItemResult is the per-item outcome of a batch import.

type ImportSitesResult added in v0.11.0

type ImportSitesResult struct {
	Imported int                    `json:"imported"`
	Skipped  int                    `json:"skipped"`
	Failed   int                    `json:"failed"`
	Results  []ImportSiteItemResult `json:"results"`
}

ImportSitesResult is the batch import summary. Imported counts sites that were newly created plus sites whose accounts were merged into an existing site; skipped counts idempotent duplicate no-ops; failed counts hard errors.

func ImportSites added in v0.11.0

func ImportSites(db *sqlx.DB, items []ImportSiteInput, strategy ImportDuplicateStrategy) (*ImportSitesResult, error)

ImportSites creates sites (and optional accounts) idempotently. A site is considered a duplicate when (platform, canonical url) already exists; with skip it is a no-op, with merge any provided accounts are attached to the existing site. Re-running the same payload therefore converges to imported=0, skipped=N.

type LocalDayRange

type LocalDayRange struct {
	LocalDay string
	StartUTC string
	EndUTC   string
}

LocalDayRange holds the day range boundaries.

func GetLocalDayRangeUTC

func GetLocalDayRangeUTC(t time.Time) LocalDayRange

GetLocalDayRangeUTC returns the local day string and its UTC boundary timestamps. Mirrors TS getLocalDayRangeUtc().

type PrimarySiteURLAnalysis

type PrimarySiteURLAnalysis struct {
	CanonicalURL string
	PersistedURL string
	MatchedPath  string
	Action       string
}

PrimarySiteURLAnalysis mirrors web/shared/sitePrimaryUrl.js analyzePrimarySiteUrl.

func AnalyzePrimarySiteURL

func AnalyzePrimarySiteURL(rawURL string) PrimarySiteURLAnalysis

AnalyzePrimarySiteURL ports analyzePrimarySiteUrl for preset fallback matching.

type ProbeFilterConfig added in v0.11.0

type ProbeFilterConfig struct {
	Enabled       bool
	IncludeModels []string
	ExcludeModels []string
}

ProbeFilterConfig gates the route-rebuild probe filter (#625). IncludeModels/ExcludeModels are optional exact source-model names; empty means no-op. When Enabled, desired channels whose latest connectivity probe failed are dropped before any route_channels diff is written.

type ProxyRoutingStore added in v0.12.0

type ProxyRoutingStore struct {
	// contains filtered or unexported fields
}

func NewProxyRoutingStore added in v0.12.0

func NewProxyRoutingStore(db *store.DB) *ProxyRoutingStore

func (*ProxyRoutingStore) ClearAllRouteDecisionSnapshots added in v0.12.0

func (s *ProxyRoutingStore) ClearAllRouteDecisionSnapshots(ctx context.Context) error

ClearAllRouteDecisionSnapshots clears every route decision snapshot.

func (*ProxyRoutingStore) ClearChannelFailureStates added in v0.12.0

func (s *ProxyRoutingStore) ClearChannelFailureStates(ctx context.Context, channelIDs []int64) error

func (*ProxyRoutingStore) ClearRouteDecisionSnapshot added in v0.12.0

func (s *ProxyRoutingStore) ClearRouteDecisionSnapshot(ctx context.Context, routeID int64) error

ClearRouteDecisionSnapshot clears one route decision snapshot.

func (*ProxyRoutingStore) ClearRouteDecisionSnapshots added in v0.12.0

func (s *ProxyRoutingStore) ClearRouteDecisionSnapshots(ctx context.Context, routeIDs []int64) error

ClearRouteDecisionSnapshots clears decision snapshots for the given route IDs.

func (*ProxyRoutingStore) FindAllEnabledRoutes added in v0.12.0

func (s *ProxyRoutingStore) FindAllEnabledRoutes(ctx context.Context) ([]store.TokenRoute, error)

func (*ProxyRoutingStore) FindRouteIDsByOAuthRouteUnitID added in v0.12.0

func (s *ProxyRoutingStore) FindRouteIDsByOAuthRouteUnitID(ctx context.Context, unitID int64) ([]int64, error)

func (*ProxyRoutingStore) LoadChannelWithAccount added in v0.12.0

func (s *ProxyRoutingStore) LoadChannelWithAccount(ctx context.Context, channelID int64) (*struct {
	Channel store.RouteChannel
	Account store.Account
}, error)

func (*ProxyRoutingStore) LoadChannelWithAccountAndRoute added in v0.12.0

func (s *ProxyRoutingStore) LoadChannelWithAccountAndRoute(ctx context.Context, channelID int64) (*struct {
	Channel store.RouteChannel
	Account store.Account
	Route   store.TokenRoute
}, error)

func (*ProxyRoutingStore) LoadChannelsByAccountIDWithoutToken added in v0.12.0

func (s *ProxyRoutingStore) LoadChannelsByAccountIDWithoutToken(ctx context.Context, accountID int64) ([]store.RouteChannel, error)

func (*ProxyRoutingStore) LoadChannelsByTokenID added in v0.12.0

func (s *ProxyRoutingStore) LoadChannelsByTokenID(ctx context.Context, tokenID int64) ([]store.RouteChannel, error)

func (*ProxyRoutingStore) LoadCredentialScopedChannelIDs added in v0.12.0

func (s *ProxyRoutingStore) LoadCredentialScopedChannelIDs(ctx context.Context, channel store.RouteChannel, accountID int64) ([]int64, error)

func (*ProxyRoutingStore) LoadEnabledRoutes added in v0.12.0

func (s *ProxyRoutingStore) LoadEnabledRoutes(ctx context.Context) ([]store.TokenRoute, error)

func (*ProxyRoutingStore) LoadOAuthRouteUnitMembers added in v0.12.0

func (s *ProxyRoutingStore) LoadOAuthRouteUnitMembers(ctx context.Context, unitIDs []int64) (map[int64][]routing.OAuthRouteUnitMemberCandidate, error)

func (*ProxyRoutingStore) LoadOAuthRouteUnitSummaries added in v0.12.0

func (s *ProxyRoutingStore) LoadOAuthRouteUnitSummaries(ctx context.Context, unitIDs []int64) (map[int64]routing.OAuthRouteUnitSummary, error)

func (*ProxyRoutingStore) LoadRouteChannels added in v0.12.0

func (s *ProxyRoutingStore) LoadRouteChannels(ctx context.Context, routeIDs []int64) ([]struct {
	Channel store.RouteChannel
	Account store.Account
	Site    store.Site
	Token   *store.AccountToken
}, error)

func (*ProxyRoutingStore) LoadRouteGroupSources added in v0.12.0

func (s *ProxyRoutingStore) LoadRouteGroupSources(ctx context.Context, groupRouteIDs []int64) (map[int64][]int64, error)

func (*ProxyRoutingStore) LoadRouteUnitMemberWithAccount added in v0.12.0

func (s *ProxyRoutingStore) LoadRouteUnitMemberWithAccount(ctx context.Context, unitID, accountID int64) (*struct {
	Member  store.OAuthRouteUnitMember
	Account store.Account
	Unit    store.OAuthRouteUnit
}, error)

func (*ProxyRoutingStore) LoadRuntimeHealthChannelRows added in v0.12.0

func (s *ProxyRoutingStore) LoadRuntimeHealthChannelRows(ctx context.Context, channelIDs []int64) ([]struct {
	SiteID            int64
	SourceModel       *string
	RouteModelPattern string
}, error)

func (*ProxyRoutingStore) UpdateChannelCooldownFields added in v0.12.0

func (s *ProxyRoutingStore) UpdateChannelCooldownFields(ctx context.Context, channelIDs []int64, updates map[string]interface{}) error

func (*ProxyRoutingStore) UpdateChannelLastSelectedAt added in v0.12.0

func (s *ProxyRoutingStore) UpdateChannelLastSelectedAt(ctx context.Context, channelID int64, lastSelectedAt string) error

func (*ProxyRoutingStore) UpdateChannelSuccessFields added in v0.12.0

func (s *ProxyRoutingStore) UpdateChannelSuccessFields(ctx context.Context, channelID int64, updates map[string]interface{}) error

func (*ProxyRoutingStore) UpdateRouteDecisionSnapshot added in v0.12.0

func (s *ProxyRoutingStore) UpdateRouteDecisionSnapshot(ctx context.Context, routeID int64, snapshot string, refreshedAt string) error

UpdateRouteDecisionSnapshot persists a route decision explanation snapshot.

func (*ProxyRoutingStore) UpdateRouteUnitMemberCooldownFields added in v0.12.0

func (s *ProxyRoutingStore) UpdateRouteUnitMemberCooldownFields(ctx context.Context, memberID int64, updates map[string]interface{}) error

func (*ProxyRoutingStore) UpdateRouteUnitMemberLastSelectedAt added in v0.12.0

func (s *ProxyRoutingStore) UpdateRouteUnitMemberLastSelectedAt(ctx context.Context, unitID, accountID int64, lastSelectedAt string) error

func (*ProxyRoutingStore) UpdateRouteUnitMemberSuccessFields added in v0.12.0

func (s *ProxyRoutingStore) UpdateRouteUnitMemberSuccessFields(ctx context.Context, memberID int64, updates map[string]interface{}) error

type RebuildOptions added in v0.11.0

type RebuildOptions struct {
	ProbeFilter ProbeFilterConfig
}

RebuildOptions configures optional rebuild behavior. The zero value keeps the legacy non-probe path byte-for-byte identical.

type RedirectFixCandidate

type RedirectFixCandidate struct {
	SiteID    int64  `db:"site_id" json:"siteId"`
	SiteName  string `db:"site_name" json:"siteName"`
	AccountID int64  `db:"account_id" json:"accountId"`
	ModelName string `db:"model_name" json:"modelName"`
	Canonical string `db:"canonical" json:"canonical"`
	Actual    string `db:"actual" json:"actual"`
}

RedirectFixCandidate is one disabled-model entry that a redirect can fix.

func ListRedirectFixCandidates

func ListRedirectFixCandidates(ctx context.Context, db *sqlx.DB) ([]RedirectFixCandidate, error)

ListRedirectFixCandidates finds site_disabled_models entries whose model is a redirect canonical with an actually-available upstream model (available=1 in model_availability). These are safe to re-enable once confirmed.

type ResinLease added in v0.13.0

type ResinLease struct {
	AccountID string `json:"accountId"`
	LastUsed  string `json:"lastUsed"`
}

ResinLease is one entry in the active-lease snapshot returned by ActiveLeases and surfaced by GET /api/admin/resin/status.

func ActiveLeases added in v0.13.0

func ActiveLeases() []ResinLease

ActiveLeases returns the list of Resin account IDs whose last-used timestamp is fresher than resinLeaseStaleTTL, plus that timestamp in UTC RFC3339. Stale entries are pruned in-place so the snapshot stays bounded under long-running processes with high account churn.

type RouteRebuildStats

type RouteRebuildStats struct {
	RoutesConsidered int `json:"routesConsidered"`
	PatternRoutes    int `json:"patternRoutes"`
	GroupRoutes      int `json:"groupRoutes"`
	ChannelsInserted int `json:"channelsInserted"`
	ChannelsRemoved  int `json:"channelsRemoved"`
	ChannelsKept     int `json:"channelsKept"`
	// Changed is true when at least one automatic channel was inserted or removed.
	Changed bool `json:"changed"`
}

RouteRebuildStats summarizes a synchronous rebuild pass. explicit_group routes do not materialize their own channels; they expand source routes at selection time via route_group_sources.

func RebuildTokenRoutesFromAvailability

func RebuildTokenRoutesFromAvailability(ctx context.Context, db *sqlx.DB) (RouteRebuildStats, error)

RebuildTokenRoutesFromAvailability is the legacy (non-probe) rebuild entrypoint. It keeps byte-for-byte identical semantics: the probe filter is off and the in-process cache is always invalidated after the pass.

func RebuildTokenRoutesFromAvailabilityWithOptions added in v0.11.0

func RebuildTokenRoutesFromAvailabilityWithOptions(ctx context.Context, db *sqlx.DB, opts RebuildOptions) (RouteRebuildStats, error)

RebuildTokenRoutesFromAvailabilityWithOptions repopulates automatic (non-manual) channels for every pattern/exact route from dual sources: 1. channels on exact-model routes whose model_pattern matches the target pattern 2. token_model_availability + model_availability rows whose model_name matches

explicit_group routes are counted but not rewritten: their membership is route_group_sources, and channel expansion happens at select time. Manual override channels on pattern routes are never deleted.

When opts.ProbeFilter.Enabled is true, desired channels are filtered by include/exclude model lists plus the latest connectivity probe result before any diff is written, and the cache is invalidated only when the model set actually changes. The zero-value RebuildOptions{} preserves legacy behavior.

Concurrent rebuilds serialize on a process-wide mutex.

type RuntimeHealthEntry

type RuntimeHealthEntry struct {
	State     RuntimeHealthState  `json:"state"`
	Reason    string              `json:"reason"`
	Source    RuntimeHealthSource `json:"source"`
	CheckedAt *string             `json:"checkedAt,omitempty"`
}

RuntimeHealthEntry is a single runtime health record stored in extraConfig.

func BuildRuntimeHealthForAccount

func BuildRuntimeHealthForAccount(input RuntimeHealthInput) RuntimeHealthEntry

BuildRuntimeHealthForAccount returns the effective runtime health for admin list/detail. Expired account status always reports unhealthy (auth), never healthy — expired status. Mirrors TS buildRuntimeHealthForAccount().

func ExtractRuntimeHealth

func ExtractRuntimeHealth(extraConfig *string) *RuntimeHealthEntry

ExtractRuntimeHealth reads the runtime health from an account's extraConfig. Mirrors TS extractRuntimeHealth().

type RuntimeHealthInput

type RuntimeHealthInput struct {
	AccountStatus       string
	SiteStatus          string
	ExtraConfig         *string
	SessionCapable      *bool
	HasDiscoveredModels bool
	OAuthProvider       *string
}

RuntimeHealthInput is the input for effective runtime-health aggregation. Mirrors TS buildRuntimeHealthForAccount().

type RuntimeHealthSource

type RuntimeHealthSource string

RuntimeHealthSource is the source of a runtime health update.

const (
	HealthSourceCheckin RuntimeHealthSource = "checkin"
	HealthSourceBalance RuntimeHealthSource = "balance"
	HealthSourceAuth    RuntimeHealthSource = "auth"
	HealthSourceSystem  RuntimeHealthSource = "system"
	HealthSourceNone    RuntimeHealthSource = "none"
	HealthSourceModel   RuntimeHealthSource = "model-discovery"
)

type RuntimeHealthState

type RuntimeHealthState string

RuntimeHealthState is the health state of an account at runtime.

const (
	HealthHealthy   RuntimeHealthState = "healthy"
	HealthDegraded  RuntimeHealthState = "degraded"
	HealthUnhealthy RuntimeHealthState = "unhealthy"
	HealthDisabled  RuntimeHealthState = "disabled"
	HealthUnknown   RuntimeHealthState = "unknown"
)

type SiteInitializationPreset

type SiteInitializationPreset struct {
	ID                        string
	Label                     string
	ProviderLabel             string
	Description               string
	Platform                  string
	DefaultURL                string
	InitialSegment            string
	RecommendedSkipModelFetch bool
	RecommendedModels         []string
	DocsURL                   string
	// MatchHost + MatchPaths define host/path auto-detect rules.
	// Empty MatchHost means the preset is manual-only (matches always false).
	MatchHost  string
	MatchPaths []string
}

SiteInitializationPreset mirrors web/shared/siteInitializationPresets.js. Platform values are protocol families (openai/claude), not vendor brand tags.

func DetectSiteInitializationPreset

func DetectSiteInitializationPreset(rawURL, platform string) *SiteInitializationPreset

DetectSiteInitializationPreset mirrors the JS detectSiteInitializationPreset(url, platform). When platform is non-empty, only presets for that protocol family are considered.

func GetSiteInitializationPreset

func GetSiteInitializationPreset(id string) *SiteInitializationPreset

GetSiteInitializationPreset returns a preset by id, or nil when unknown.

func ListSiteInitializationPresets

func ListSiteInitializationPresets() []SiteInitializationPreset

ListSiteInitializationPresets returns a defensive copy of all known presets.

func (SiteInitializationPreset) HasURLMatchRules

func (p SiteInitializationPreset) HasURLMatchRules() bool

HasURLMatchRules reports whether the preset defines host/path auto-detect rules.

func (SiteInitializationPreset) MatchesURL

func (p SiteInitializationPreset) MatchesURL(rawURL string) bool

MatchesURL implements the JS preset.matches(url) host+paths check.

type TodayIncomeSnapshot

type TodayIncomeSnapshot struct {
	Day       string  `json:"day"`
	Baseline  float64 `json:"baseline"`
	Latest    float64 `json:"latest"`
	UpdatedAt string  `json:"updatedAt"`
}

TodayIncomeSnapshot tracks daily income baseline and latest.

type TokenSyncResult

type TokenSyncResult struct {
	Created         int
	Updated         int
	MaskedPending   int
	PendingTokenIDs []int64
	Total           int
	DefaultTokenID  *int64
}

TokenSyncResult summarizes SyncTokensFromUpstream outcomes.

func SyncTokensFromUpstream

func SyncTokensFromUpstream(db *sqlx.DB, accountID int64, upstreamTokens []UpstreamAPIToken) (*TokenSyncResult, error)

SyncTokensFromUpstream upserts account tokens from upstream listings. When an existing ready token matches by key, local enabled (and non-empty operator-set name) are preserved; upstream enable flags do not clobber operator disable/enable choices (upstream / ).

type UpstreamAPIToken

type UpstreamAPIToken struct {
	Name       string
	Key        string
	Enabled    bool
	TokenGroup string
}

UpstreamAPIToken is a token payload returned by platform adapters during sync.

func FetchUpstreamAPITokens

func FetchUpstreamAPITokens(
	ctx context.Context,
	adapter platform.PlatformAdapter,
	baseURL, accessToken string,
	platformUserID *int,
	proxy *platform.ProxyConfig,
) ([]UpstreamAPIToken, error)

FetchUpstreamAPITokens loads tokens via adapter.GetAPITokens, falling back to adapter.GetAPIToken when the list endpoint returns nothing.

func PlatformAPITokensToUpstream

func PlatformAPITokensToUpstream(tokens []platform.ApiTokenInfo) []UpstreamAPIToken

PlatformAPITokensToUpstream converts platform.ApiTokenInfo values to the local UpstreamAPIToken shape used by SyncTokensFromUpstream.

Directories

Path Synopsis
Package pricing provides pure, database-free functions for normalizing upstream pricing signals into a canonical product model and converting pricing multipliers (ratios) into USD per million tokens.
Package pricing provides pure, database-free functions for normalizing upstream pricing signals into a canonical product model and converting pricing multipliers (ratios) into USD per million tokens.
Package pricingcatalog serves official catalog pricing from models.dev as a cold-start cost signal for the token router.
Package pricingcatalog serves official catalog pricing from models.dev as a cold-start cost signal for the token router.
Package promptfilter implements a lightweight, pattern-based prompt safety filter that blocks high-risk prompts before they reach shared OAuth upstream accounts (Codex, Claude, Gemini CLI, Grok).
Package promptfilter implements a lightweight, pattern-based prompt safety filter that blocks high-risk prompts before they reach shared OAuth upstream accounts (Codex, Claude, Gemini CLI, Grok).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL