dao

package
v0.0.21 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2026 License: MIT Imports: 38 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RebuildTargetTokenDaily   = "token_daily"
	RebuildTargetChannelDaily = "channel_daily"
)

Rebuild target identifiers. Empty Targets means rebuild all of them.

View Source
const (
	ErrCodeNameRequired       = "name_required"
	ErrCodeNameTooLong        = "name_too_long"
	ErrCodeNameContainsComma  = "name_contains_comma"
	ErrCodeMembersInvalidJSON = "members_invalid_json"
	ErrCodeMembersEmpty       = "members_empty"
	ErrCodeMembersTooMany     = "members_too_many"
	ErrCodeRefEmpty           = "ref_empty"
	ErrCodeInvalidRef         = "invalid_ref"
	ErrCodeCycleDetected      = "cycle_detected"
	ErrCodeMaxDepth           = "max_depth"
	ErrCodeReferencedBy       = "referenced_by"
	ErrCodeInvalidScope       = "invalid_scope"
	ErrCodeInvalidScopeOwner  = "invalid_scope_owner"
	ErrCodeTokenNotFound      = "token_not_found"
	ErrCodeDBError            = "db_error"
	ErrCodeNotFound           = "not_found"
)
View Source
const BaseURLUsagePreviewLimit = 50

BaseURLUsagePreviewLimit caps how many owner/channel pairs CountByBaseURLPrefix returns alongside the total count. The full count is unbounded; the preview list is bounded so admin UI never paginates an arbitrarily long affected-channel roster (and so we don't ship megabytes of rows over the wire for a hot prefix).

View Source
const MarketplacePerformanceHours = 30 * 24
View Source
const (
	// MaxHourRangeDays 限制 hour 粒度查询窗口最大天数。
	MaxHourRangeDays = 7
)

Variables

View Source
var (
	// ErrAPIBackendInUse reports that routes still reference the backend.
	ErrAPIBackendInUse = errors.New("api backend is still referenced by routes")
	// ErrAPIBackendNameConflict reports a duplicate backend name within one service.
	ErrAPIBackendNameConflict = errors.New("api backend name conflict")
)
View Source
var (
	// ErrCleanupTableNotAllowed rejects every table outside the static cleanup registry.
	ErrCleanupTableNotAllowed = errors.New("cleanup table not allowed")
	// ErrInvalidCleanupSnapshot identifies a malformed preview watermark supplied to deletion.
	ErrInvalidCleanupSnapshot = errors.New("invalid cleanup snapshot")
)
View Source
var ErrAgentRouteNotFound = errors.New("agent route not found")

ErrAgentRouteNotFound indicates that an AgentRoute update did not match exactly one row.

View Source
var ErrCrossDatabaseTransaction = errors.New("cross-database transaction access")
View Source
var ErrInvalidDatabaseLayout = errors.New("invalid database layout")
View Source
var ErrInvalidRebuildTarget = errors.New("invalid rebuild target")

ErrInvalidRebuildTarget is returned when a manual rebuild asks for a target other than the two log-owned daily billing tables.

View Source
var ErrInviteCodeUnavailable = errors.New("invite code unavailable")

ErrInviteCodeUnavailable 表示邀请码不存在 / 已用满 / 已过期(消费失败)。

View Source
var ErrLogDatabaseUnavailable = errors.New("log database unavailable")
View Source
var ErrMarketplaceUsageNotOwner = errors.New("marketplace usage offer is not owned by viewer")
View Source
var ErrQuotaOutOfRange = errors.New("quota out of range")
View Source
var ErrRangeOutOfBounds = listfilter.ErrRangeOutOfBounds

ErrRangeOutOfBounds 是从 listfilter 包导出的别名,保持现有 dao 调用站继续编译。新代码鼓励直接 import listfilter。 errors.Is(err, listfilter.ErrRangeOutOfBounds) 对用此变量的 err 同样成立。

View Source
var ErrTokenNotFoundOrOwnershipChanged = errors.New("token not found or ownership changed")
View Source
var ErrUnsupportedMarketShareDim = fmt.Errorf("unsupported market share dim: only model|channel supported")

ErrUnsupportedMarketShareDim 表示 MarketShareTrend 的 dim 参数非 model|channel。 author 维本期不支持(无 author 数据源),handler 侧应把它转成 400。

View Source
var ErrUnsupportedTrendDim = fmt.Errorf("unsupported metric trend dim: only model|channel supported")

ErrUnsupportedTrendDim mirrors ErrUnsupportedMarketShareDim for MetricTrendGrouped.

View Source
var ErrUnsupportedTrendMetric = fmt.Errorf("unsupported metric trend metric: only cost|requests|tokens|ttft|tps|cache_hit_rate supported")

ErrUnsupportedTrendMetric indicates MetricTrendGrouped's metric parameter isn't one of the known cost|requests|tokens|ttft|tps|cache_hit_rate metrics.

View Source
var ErrUnsupportedTrendStat = fmt.Errorf("unsupported metric trend statistic")

Functions

func CleanupTableKeys added in v0.0.15

func CleanupTableKeys() []string

CleanupTableKeys returns all allowed physical table keys in deterministic order.

func DeleteAPIPrincipalAccess added in v0.0.16

func DeleteAPIPrincipalAccess(db *gorm.DB, principalType models.APIPrincipalType, principalID uint) (uint, error)

DeleteAPIPrincipalAccess removes every binding owned by one principal and deletes its optional managed grant role. The caller owns the transaction.

func IsAgentRouteUniqueConflict added in v0.0.13

func IsAgentRouteUniqueConflict(err error) bool

IsAgentRouteUniqueConflict reports duplicate-key failures from translated GORM errors or SQLite.

func LockAPIPrincipal added in v0.0.16

func LockAPIPrincipal(db *gorm.DB, principalType models.APIPrincipalType, principalID uint) error

LockAPIPrincipal serializes deletion with every transaction that can add an API role binding or managed grant for the same principal.

func RunInCoreTx added in v0.0.14

func RunInCoreTx[T Context](ctx T, fn func(T) error) error

func RunInLogTx added in v0.0.14

func RunInLogTx[T Context](ctx T, fn func(T) error) error

func RunInTx

func RunInTx[T Context](ctx T, fn func(T) error) error

RunInTx executes fn within a database transaction. The transaction is committed if fn returns nil, rolled back otherwise. Type-safe: works with both Context and UserContext.

func WrapLogDatabaseError added in v0.0.14

func WrapLogDatabaseError(err error) error

Types

type APIBackendFilter added in v0.0.16

type APIBackendFilter struct {
	APIServiceID *uint
	Search       string
}

type APIBackendListItem added in v0.0.16

type APIBackendListItem struct {
	models.APIBackend
	RouteCount           int64
	UpstreamCount        int64
	EnabledUpstreamCount int64
	EndpointHosts        []string
}

type APIBackendMutation added in v0.0.16

type APIBackendMutation interface {
	Create(backend *models.APIBackend) error
	Update(id uint, fields map[string]any) error
	DeleteUnused(id uint) ([]models.APIUpstream, error)
}

type APIBackendQuery added in v0.0.16

type APIBackendQuery interface {
	GetByID(id uint) (*models.APIBackend, error)
	LockByID(id uint) (*models.APIBackend, error)
	List(opts ListOptions, filter APIBackendFilter) ([]APIBackendListItem, int64, error)
	RouteCount(id uint) (int64, error)
}

type APIRBACMutation added in v0.0.16

type APIRBACMutation interface {
	CreateRole(role *models.Role) error
	UpdateRole(id uint, patch map[string]any) error
	DeleteRole(id uint) error
	CreatePermission(permission *models.Permission) error
	UpdatePermission(id uint, patch map[string]any) error
	DeletePermission(id uint) error
	CreateRolePermission(permission *models.RolePermission) error
	DeleteRolePermission(id uint) error
	CreateRoleBinding(binding *models.RoleBinding) error
	ReplaceRoleBindingsByPrincipal(principalType models.APIPrincipalType, principalID uint, roleIDs []uint) error
	ReplaceCustomRoleBindingsByPrincipal(principalType models.APIPrincipalType, principalID uint, roleIDs []uint) error
	UpdateRoleBinding(id uint, patch map[string]any) error
	DeleteRoleBinding(id uint) error
}

type APIRBACQuery added in v0.0.16

type APIRBACQuery interface {
	ListUsersByIDs(ids []uint) ([]models.User, error)
	GetRoleByID(id uint) (*models.Role, error)
	GetPermissionByID(id uint) (*models.Permission, error)
	ListEnabledRoles() ([]models.Role, error)
	MaxEnabledRoleID() (uint, error)
	ListEnabledRolesKeyset(afterID, snapshotMaxID uint, limit int) ([]models.Role, error)
	CountEnabledRolesThroughID(snapshotMaxID uint) (int64, error)
	ListRolesByKey(key string) ([]models.Role, error)
	ListRoles(opts ListOptions, filter APIRoleFilter) ([]models.Role, int64, error)
	ListPermissions() ([]models.Permission, error)
	ListRolePermissions(roleID uint) ([]models.RolePermission, error)
	ListRolePermissionsByRoleIDs(roleIDs []uint) ([]models.RolePermission, error)
	ListPermissionsByIDs(permissionIDs []uint) ([]models.Permission, error)
	ListRoleBindings(roleID uint) ([]models.RoleBinding, error)
	ListRoleBindingsByRoleIDs(roleIDs []uint) ([]models.RoleBinding, error)
	ListRoleBindingsPage(opts ListOptions, filter APIRoleBindingFilter) ([]models.RoleBinding, int64, error)
	ListRoleBindingsByPrincipal(principalType models.APIPrincipalType, principalID uint) ([]models.RoleBinding, error)
	ListRoleSetBindingsByPrincipal(principalType models.APIPrincipalType, principalID uint) ([]models.RoleBinding, error)
	ListRoleSetBindingsByPrincipals(principalType models.APIPrincipalType, principalIDs []uint) ([]models.RoleBinding, error)
}

type APIRequestLogFilter added in v0.0.16

type APIRequestLogFilter struct {
	listfilter.TimeWindow
	UserID        *uint
	APIServiceID  *uint
	APIServiceIDs *[]uint
	APIRouteID    *uint
	APIUpstreamID *uint
	TokenID       *uint
	StatusCode    *int
	RequestID     string
}

type APIRequestLogQuery added in v0.0.16

type APIRequestLogQuery interface {
	GetByRequestID(requestID string) (*models.APIRequestLog, error)
	GetByRequestIDAndUserID(requestID string, userID uint) (*models.APIRequestLog, error)
	GetTraceByRequestID(requestID string) (*models.APIRequestTrace, error)
	List(opts ListOptions, filter APIRequestLogFilter) ([]models.APIRequestLog, int64, error)
}

type APIRoleBindingFilter added in v0.0.16

type APIRoleBindingFilter struct {
	PrincipalType *models.APIPrincipalType
	PrincipalID   *uint
	RoleID        *uint
	RoleKind      *models.APIRoleKind
}

type APIRoleFilter added in v0.0.16

type APIRoleFilter struct {
	Search     string
	Status     *int
	Assignable *bool
	RoleKind   *models.APIRoleKind
}

type APIRouteFilter added in v0.0.16

type APIRouteFilter struct {
	APIServiceID *uint
	Search       string
	Status       *int
	IDs          *[]uint
}

type APIRouteMutation added in v0.0.16

type APIRouteMutation interface {
	Create(route *models.APIRoute) error
	Update(id uint, patch map[string]any) error
	Delete(id uint) error
}

type APIRouteQuery added in v0.0.16

type APIRouteQuery interface {
	GetByID(id uint) (*models.APIRoute, error)
	LockByID(id uint) (*models.APIRoute, error)
	GetByServiceAndSlug(serviceID uint, slug string) (*models.APIRoute, error)
	ListOpenAPIPaths(serviceID uint, routeIDs *[]uint) ([]models.APIRoute, error)
	ListVisibleOpenAPIPaths(serviceID uint, routeIDs *[]uint) ([]models.APIRoute, error)
	List(opts ListOptions, filter APIRouteFilter) ([]models.APIRoute, int64, error)
	MaxID() (uint, error)
	ListKeyset(afterID, snapshotMaxID uint, limit int) ([]models.APIRoute, error)
	CountThroughID(snapshotMaxID uint) (int64, error)
}

type APIServiceFilter added in v0.0.16

type APIServiceFilter struct {
	Search string
	Status *int
	IDs    *[]uint
}

type APIServiceMutation added in v0.0.16

type APIServiceMutation interface {
	Create(service *models.APIService) error
	Update(id uint, patch map[string]any) error
	Delete(id uint) error
}

type APIServiceQuery added in v0.0.16

type APIServiceQuery interface {
	GetByID(id uint) (*models.APIService, error)
	LockByID(id uint) (*models.APIService, error)
	GetBySlug(slug string) (*models.APIService, error)
	GetOpenAPIDocument(id uint) (models.OpenAPIServiceDocument, int64, error)
	List(opts ListOptions, filter APIServiceFilter) ([]models.APIService, int64, error)
	MaxID() (uint, error)
	ListKeyset(afterID, snapshotMaxID uint, limit int) ([]models.APIService, error)
	CountThroughID(snapshotMaxID uint) (int64, error)
}

type APIUpstreamFilter added in v0.0.16

type APIUpstreamFilter struct {
	BackendID    *uint
	APIServiceID *uint
	Search       string
	Status       *int
}

type APIUpstreamMutation added in v0.0.16

type APIUpstreamMutation interface {
	Create(upstream *models.APIUpstream) error
	Update(id uint, patch map[string]any) error
	Delete(id uint) error
}

type APIUpstreamQuery added in v0.0.16

type APIUpstreamQuery interface {
	GetByID(id uint) (*models.APIUpstream, error)
	LockByID(id uint) (*models.APIUpstream, error)
	GetByBackendAndName(backendID uint, name string) (*models.APIUpstream, error)
	List(opts ListOptions, filter APIUpstreamFilter) ([]models.APIUpstream, int64, error)
	MaxID() (uint, error)
	ListKeyset(afterID, snapshotMaxID uint, limit int) ([]models.APIUpstream, error)
	CountThroughID(snapshotMaxID uint) (int64, error)
}

type AdminAgentMutation

type AdminAgentMutation interface {
	Create(agent *models.Agent) error
	CreateWithTransportPolicy(agent *models.Agent) error
	Update(id uint, updates map[string]any) error
	UpdateIfRelayConfigMatches(id uint, expectedMode, expectedURI string, updates map[string]any) (bool, error)
	Delete(id uint) error
	UpdateLastSeen(agentID string, lastSeen int64) error
	BatchUpdateLastSeen(updates map[string]int64) error
	UpdateHTTPAddresses(agentID string, addresses string) error
}

type AdminAgentQuery

type AdminAgentQuery interface {
	GetByID(id uint) (*models.Agent, error)
	GetByAgentID(agentID string) (*models.Agent, error)
	List(opts ListOptions, filter AgentListFilter) ([]models.Agent, int64, error)
	ListByAgentIDs(ids []string) ([]models.Agent, error)
	ListActive(excludeAgentID string) ([]models.Agent, error)
	MaxID() (uint, error)
	ListKeyset(afterID, snapshotMaxID uint, limit int) ([]models.Agent, error)
	CountThroughID(snapshotMaxID uint) (int64, error)
}

type AdminAgentRouteMutation

type AdminAgentRouteMutation interface {
	Create(route *models.AgentRoute) error
	Update(route *models.AgentRoute) error
	Delete(id uint) error
}

AdminAgentRouteMutation 定义写入接口。

type AdminAgentRouteQuery

type AdminAgentRouteQuery interface {
	GetByID(id uint) (*models.AgentRoute, error)
	List(opts ListOptions, filter AgentRouteListFilter) ([]models.AgentRoute, int64, error)
	ListOverview(opts ListOptions, filter AgentRouteOverviewFilter) ([]AgentRouteOverview, int64, error)
	ListAll() ([]models.AgentRoute, error)
	MaxID() (uint, error)
	ListKeyset(afterID uint, snapshotMaxID uint, limit int) ([]models.AgentRoute, error)
	CountThroughID(snapshotMaxID uint) (int64, error)
}

AdminAgentRouteQuery 定义查询接口。

type AdminBillingMutation

type AdminBillingMutation interface {
	UpsertHourlyBucket(log *models.UsageLog) error
	UpsertDurationHistogram(log *models.UsageLog) error
	UpsertTTFTHistogram(log *models.UsageLog) error
	UpsertTPSHistogram(log *models.UsageLog) error
	BatchUpsertHourlyBucket(rows []HourlyBucketRow) error
	BatchUpsertDurationHistogram(rows []DurationHistogramRow) error
	BatchUpsertTTFTHistogram(rows []TTFTHistogramRow) error
	BatchUpsertTPSHistogram(rows []TPSHistogramRow) error
}

type AdminBillingQuery

type AdminBillingQuery interface {
	ListTokenBilling(opts ListOptions, filter TokenBillingListFilter) ([]TokenBillingListItem, int64, error)
	GetTokenDaily(tokenID uint, filter TokenBillingListFilter) ([]TokenBillingDailyItem, error)
	GetBillingOverview(filter TokenBillingListFilter) (*BillingOverview, error)
	ListChannelBilling(opts ListOptions, filter ChannelBillingListFilter) ([]ChannelBillingListItem, int64, error)
	GetChannelDaily(channelID uint, filter ChannelBillingListFilter) ([]ChannelBillingDailyItem, error)
	// ListPrivateChannelDailyByOwner 返回指定 owner 的全部 BYOK channel daily rollup 行(owner_type="private"),
	// 通过 private_channels.owner_id JOIN 限定范围;admin 行被排除。
	ListPrivateChannelDailyByOwner(ownerID uint, filter ChannelBillingListFilter) ([]ChannelBillingDailyItem, error)
	// ListPrivateChannelByModelByOwner aggregates the owner's BYOK requests by model
	// from layout-aware request facts.
	ListPrivateChannelByModelByOwner(ownerID uint, filter ChannelBillingListFilter) ([]PrivateChannelByModelItem, error)
}

type AdminChannelMutation

type AdminChannelMutation interface {
	Create(channel *models.Channel) error
	Update(id uint, updates map[string]any) error
	UpdateByIDs(ids []uint, assignments map[string]any) (int64, error)
	// ReconcileLimit commits a limit evaluator decision only if every field used
	// to determine ownership still matches the snapshot.
	ReconcileLimit(snapshot models.Channel, status int, limitState models.ChannelDisableState) (bool, error)
	AutoDisable(id uint, revision uint64, state models.ChannelDisableState) (AutoDisableResult, error)
	Delete(id uint) error
}

type AdminChannelQuery

type AdminChannelQuery interface {
	GetByID(id uint) (*models.Channel, error)
	ListByIDs(ids []uint) ([]models.Channel, error)
	List(opts ListOptions, filter ChannelListFilter) ([]models.Channel, int64, error)
	ListAll() ([]models.Channel, error)
	ListByTag(tag string) ([]models.Channel, error)
	ListEnabled() ([]models.Channel, error)
	ChannelWindowUsage(channelID uint, wf WindowFilter) (ChannelUsage, error)
}

type AdminEnrollmentTokenMutation

type AdminEnrollmentTokenMutation interface {
	Create(token *models.EnrollmentToken) error
	Delete(id uint) error
}

type AdminEnrollmentTokenQuery

type AdminEnrollmentTokenQuery interface {
	GetValidByToken(token string) (*models.EnrollmentToken, error)
	List() ([]models.EnrollmentToken, error)
}

type AdminInviteCodeMutation added in v0.0.6

type AdminInviteCodeMutation interface {
	Create(code *models.InviteCode) error
	Delete(id uint) error
	// Redeem 原子消费:条件自增 used_count。不可用(不存在/用满/过期)返回 ErrInviteCodeUnavailable。
	Redeem(code string, now int64) (*models.InviteCode, error)
	RecordRedemption(r *models.InviteRedemption) error
}

type AdminInviteCodeQuery added in v0.0.6

type AdminInviteCodeQuery interface {
	GetByID(id uint) (*models.InviteCode, error)
	GetByCode(code string) (*models.InviteCode, error)
	ListAll(opts ListOptions, filter InviteCodeListFilter) ([]models.InviteCode, int64, error)
	CountActiveByCreator(creatorID uint, now int64) (int64, error)
}

type AdminLimiterBindingMutation added in v0.0.8

type AdminLimiterBindingMutation interface {
	Create(b *models.LimiterBinding) error
	Delete(id uint) error
	DeleteByLimiter(limiterID uint) error
}

type AdminLimiterBindingQuery added in v0.0.8

type AdminLimiterBindingQuery interface {
	ListAll() ([]models.LimiterBinding, error)
	ListByLimiter(limiterID uint) ([]models.LimiterBinding, error)
}

type AdminModelConfigMutation

type AdminModelConfigMutation interface {
	Create(config *models.ModelConfig) error
	Update(id uint, updates map[string]any) error
	Delete(id uint) error
	DeleteByModelName(name string) error
}

type AdminModelConfigQuery

type AdminModelConfigQuery interface {
	GetByID(id uint) (*models.ModelConfig, error)
	GetByModelName(name string) (*models.ModelConfig, error)
	List(opts ListOptions, filter ModelConfigListFilter) ([]models.ModelConfig, int64, error)
	ListAll() ([]models.ModelConfig, error)
}

type AdminModelRoutingMutation

type AdminModelRoutingMutation interface {
	Create(r *models.ModelRouting) *ValidateError
	Update(id uint, updates map[string]any) *ValidateError
	Delete(id uint) *ValidateError
	DeleteByToken(tokenID uint) error
}

AdminModelRoutingMutation 定义写入接口。

type AdminModelRoutingQuery

type AdminModelRoutingQuery interface {
	GetByID(id uint) (*models.ModelRouting, error)
	GetByName(scope string, userID, tokenID uint, name string) (*models.ModelRouting, error)
	List(opts ListOptions, filter ModelRoutingListFilter) ([]models.ModelRouting, int64, error)
	ListAllGlobal() ([]models.ModelRouting, error)
	ListByUser(userID uint) ([]models.ModelRouting, error)
	ListByToken(tokenID uint) ([]models.ModelRouting, error)
}

AdminModelRoutingQuery 定义查询接口。

type AdminMutation

type AdminMutation interface {
	User() AdminUserMutation
	Token() AdminTokenMutation
	Channel() AdminChannelMutation
	Agent() AdminAgentMutation
	ModelConfig() AdminModelConfigMutation
	UsageLog() AdminUsageLogMutation
	Billing() AdminBillingMutation
	Setting() AdminSettingMutation
	EnrollmentToken() AdminEnrollmentTokenMutation
	AgentRoute() AdminAgentRouteMutation
	RequestLimiter() AdminRequestLimiterMutation
	LimiterBinding() AdminLimiterBindingMutation
	TokenTemplate() AdminTokenTemplateMutation
	UserGroup() AdminUserGroupMutation
	OAuthProvider() AdminOAuthProviderMutation
	OAuthIdentity() AdminOAuthIdentityMutation
	ModelRouting() AdminModelRoutingMutation
	PrivateChannel() AdminPrivateChannelMutation
	PrivateChannelShare() AdminPrivateChannelShareMutation
	AdminScript() AdminScriptMutation
	InviteCode() AdminInviteCodeMutation
	APIService() APIServiceMutation
	APIBackend() APIBackendMutation
	APIRoute() APIRouteMutation
	APIUpstream() APIUpstreamMutation
	APIRBAC() APIRBACMutation
}

func NewAdminMutation

func NewAdminMutation(ctx Context) AdminMutation

type AdminOAuthIdentityMutation

type AdminOAuthIdentityMutation interface {
	Create(i *models.OAuthIdentity) error
	DeleteByIDForUser(id, userID uint) (affected int64, err error)
	DeleteByUserID(userID uint) error
}

type AdminOAuthIdentityQuery

type AdminOAuthIdentityQuery interface {
	GetByProviderSubject(providerID uint, subject string) (*models.OAuthIdentity, bool, error)
	ListByUserID(userID uint) ([]models.OAuthIdentity, error)
	CountByUserID(userID uint) (int64, error)
}

type AdminOAuthProviderMutation

type AdminOAuthProviderMutation interface {
	Create(p *models.OAuthProvider) error
	Update(id uint, updates map[string]any) error
	Delete(id uint) error
}

type AdminOAuthProviderQuery

type AdminOAuthProviderQuery interface {
	GetByID(id uint) (*models.OAuthProvider, error)
	GetByName(name string) (*models.OAuthProvider, error)
	List() ([]models.OAuthProvider, error)
	ListEnabled() ([]models.OAuthProvider, error)
}

type AdminOfferUsageScope added in v0.0.15

type AdminOfferUsageScope struct {
	Offers []MarketplaceUsageOffer
	Range  MarketplaceUsageRange
}

AdminOfferUsageScope is reachable only from the administrator finder path. It intentionally has no caller-supplied owner/user restriction.

type AdminPrivateChannelMutation added in v0.0.2

type AdminPrivateChannelMutation interface {
	Create(pc *models.PrivateChannel) error
	Update(id, ownerID uint, patch map[string]any) error
	UpdateKey(id, ownerID uint, newCipher []byte, newLast4 string) error
	Delete(id, ownerID uint) error
	// AdminDisable is the admin-only kill switch; does not check owner_id.
	AdminDisable(id uint) error
	AutoDisable(id uint, revision uint64, state models.ChannelDisableState) (AutoDisableResult, error)
	// DeleteByOwner removes every private_channel row owned by ownerID.
	// Used by the user-delete cascade to purge BYOK ciphertext when a user
	// account is removed (GDPR/SOC2 right-to-erasure).
	// Returns nil when no rows match.
	DeleteByOwner(ownerID uint) error
}

AdminPrivateChannelMutation is the write surface for PrivateChannel. Update/Delete use a double-factor (id, owner_id) WHERE clause to prevent cross-owner mutation via forged ids at the portal layer.

type AdminPrivateChannelQuery added in v0.0.2

type AdminPrivateChannelQuery interface {
	GetByID(id uint) (*models.PrivateChannel, error)
	ListOwnedBy(ownerID uint, opts ListOptions, filter PrivateChannelFilter) ([]models.PrivateChannel, int64, error)
	ListVisibleTo(userID uint, userGroupIDs []uint) ([]models.PrivateChannel, error)
	CountByOwner(ownerID uint) (int64, error)
	ListAcrossOwners(opts ListOptions, filter PrivateChannelFilter) ([]models.PrivateChannel, int64, error)
	// CountByBaseURLPrefix returns the total number of private_channels whose
	// BaseURL begins with the given prefix, plus a bounded preview of
	// (owner_id, channel_name) pairs (capped at BaseURLUsagePreviewLimit).
	// Used by admin UI to warn before deleting a BaseURL allowlist entry: if any
	// existing channel still references the prefix string, removal will cause
	// silent validation failure for that owner the next time they edit the
	// channel. prefix is bound through a parameterized LIKE — safe from injection.
	CountByBaseURLPrefix(prefix string) (int64, []ChannelOwnerPair, error)
}

AdminPrivateChannelQuery is the read-only DAO surface for PrivateChannel.

type AdminPrivateChannelShareMutation added in v0.0.2

type AdminPrivateChannelShareMutation interface {
	// DeleteSharesByTarget removes every share row where (target_type, target_id)
	// matches. Use PrivateShareTargetUser when cascading a user delete.
	// Returns nil when no rows match.
	DeleteSharesByTarget(targetType string, targetID uint) error
}

AdminPrivateChannelShareMutation is the write surface for PrivateChannelShare. Share rows are normally created/removed implicitly via channel ops; this mutation surface exists to support the user-delete cascade, which must strip every share whose target is the deleted user.

type AdminPrivateChannelShareQuery added in v0.0.2

type AdminPrivateChannelShareQuery interface {
	ListSharesForUser(userID uint, groupIDs []uint) ([]models.PrivateChannelShare, error)
	ListSharesByChannel(channelID uint) ([]models.PrivateChannelShare, error)
}

AdminPrivateChannelShareQuery is the read-only DAO surface for PrivateChannelShare. v1 only exposes Query operations; Mutation API is intentionally not provided here.

type AdminQuery

type AdminQuery interface {
	User() AdminUserQuery
	Token() AdminTokenQuery
	Channel() AdminChannelQuery
	Agent() AdminAgentQuery
	ModelConfig() AdminModelConfigQuery
	UsageLog() AdminUsageLogQuery
	Billing() AdminBillingQuery
	Setting() AdminSettingQuery
	EnrollmentToken() AdminEnrollmentTokenQuery
	Stats() AdminStatsQuery
	AgentRoute() AdminAgentRouteQuery
	RequestLimiter() AdminRequestLimiterQuery
	LimiterBinding() AdminLimiterBindingQuery
	TokenTemplate() AdminTokenTemplateQuery
	UserGroup() AdminUserGroupQuery
	OAuthProvider() AdminOAuthProviderQuery
	OAuthIdentity() AdminOAuthIdentityQuery
	ModelRouting() AdminModelRoutingQuery
	PrivateChannel() AdminPrivateChannelQuery
	PrivateChannelShare() AdminPrivateChannelShareQuery
	AdminScript() AdminScriptQuery
	InviteCode() AdminInviteCodeQuery
	APIService() APIServiceQuery
	APIBackend() APIBackendQuery
	APIRoute() APIRouteQuery
	APIUpstream() APIUpstreamQuery
	APIRBAC() APIRBACQuery
	APIRequestLog() APIRequestLogQuery
}

func NewAdminQuery

func NewAdminQuery(ctx Context) AdminQuery

type AdminRequestLimiterMutation added in v0.0.8

type AdminRequestLimiterMutation interface {
	Create(l *models.RequestLimiter) error
	Update(id uint, updates map[string]any) error
	Delete(id uint) error
}

type AdminRequestLimiterQuery added in v0.0.8

type AdminRequestLimiterQuery interface {
	GetByID(id uint) (*models.RequestLimiter, error)
	List(opts ListOptions) ([]models.RequestLimiter, int64, error)
	ListAll() ([]models.RequestLimiter, error)
}

type AdminScriptMutation added in v0.0.6

type AdminScriptMutation interface {
	Create(s *models.AdminScript) error
	Update(id uint, updates map[string]any) error
	Delete(id uint) error
}

type AdminScriptQuery added in v0.0.6

type AdminScriptQuery interface {
	GetByID(id uint) (*models.AdminScript, error)
	List(opts ListOptions, search string) ([]models.AdminScript, int64, error)
	ListAll() ([]models.AdminScript, error)
	ListEnabled() ([]models.AdminScript, error)
}

type AdminSettingMutation

type AdminSettingMutation interface {
	Set(key string, value string) error
	Delete(key string) error
}

type AdminSettingQuery

type AdminSettingQuery interface {
	Get(key string) (*models.Setting, error)
	Lookup(key string) (*models.Setting, bool, error)
	GetAll() ([]models.Setting, error)

	// LookupString returns the setting value for key, or fallback if the key
	// is missing or an error occurs while loading it.
	LookupString(key, fallback string) string
	// LookupInt parses the setting value as int. If the key is missing,
	// the value is empty, or strconv.Atoi fails, fallback is returned.
	LookupInt(key string, fallback int) int
	// LookupBool parses the setting value as bool. Accepted truthy spellings
	// (case-insensitive) are "true", "1", "yes"; falsy are "false", "0", "no".
	// If the key is missing, the value is empty, or it cannot be parsed as a
	// bool, fallback is returned.
	LookupBool(key string, fallback bool) bool
	// LookupFloat parses the setting value as float64. If the key is missing,
	// the value is empty, or strconv.ParseFloat fails, fallback is returned.
	LookupFloat(key string, fallback float64) float64
}

type AdminStatsQuery

type AdminStatsQuery interface {
	GetOverview() (*OverviewStats, error)
	GetTableCount(table KnownTable) (int64, error)
	GetTotalCost(filter UsageLogListFilter) (int64, error)
	GetTrend(days int, userID *uint) ([]TrendItem, error)
	HourlyTrend(r ObsRange, scope Scope, f ObsFilter) ([]TimeBucket, error)
	Distribution(by string, r ObsRange, scope Scope, f ObsFilter) ([]Bucket, error)
	ModelDistribution(r ObsRange, scope Scope, topN int, f ObsFilter) ([]Bucket, error)
	Leaderboard(by, metric string, limit int, r ObsRange, scope Scope, f ObsFilter) ([]LeaderRow, error)
	SpeedCompare(dimension string, r ObsRange, scope Scope, topN int, f ObsFilter) ([]SpeedRow, error)
	ChannelMetrics(r ObsRange) ([]ChannelMetric, error)
	ChannelModelBreakdown(channelID uint, r ObsRange) ([]ChannelModelBreakdownRow, error)
	AgentMetrics(r ObsRange) ([]AgentMetric, error)
	ErrorDistribution(by string, r ObsRange, scope Scope) ([]ErrBucket, error)
	StageLatencyP95(filter UsageLogListFilter, r ObsRange) (StageLatency, error)
	DashboardKpis(r ObsRange, scope Scope, f ObsFilter) (KpiBundle, error)
	DashboardTrend(r ObsRange, scope Scope, f ObsFilter) ([]TimeBucket, error)
	DashboardSuccessRate(r ObsRange, scope Scope, f ObsFilter) (KpiMetric, error)
	CostTrendStackedByModel(r ObsRange, scope Scope, topN int, f ObsFilter) (CostTrendStacked, error)
	MarketShareTrend(dim string, r ObsRange, scope Scope, topN int, f ObsFilter) (CostTrendStacked, error)
	MetricTrendGrouped(metric, stat, dim string, r ObsRange, scope Scope, topN int, f ObsFilter) (MetricTrendStacked, error)
	CacheSaving(r ObsRange, scope Scope, f ObsFilter) (CacheSaving, error)
	LogsTotals(r ObsRange, scope Scope) (LogsTotals, error)
	RecentAgentHealth(sinceUnix int64) ([]AgentRecentHealth, error)
}

type AdminTokenMutation

type AdminTokenMutation interface {
	Create(token *models.Token) error
	Update(id uint, updates map[string]any) error
	UpdateExisting(id uint, updates map[string]any) error
	UpdateOwned(id, userID uint, updates map[string]any) error
	Delete(id uint) error
	DeleteWithRoutings(id uint) ([]models.ModelRouting, uint, error)
	DisableAllForUser(userID uint) error
	BulkSyncFromTemplate(templateID uint, tpl *models.TokenTemplate, f models.SyncFields) (changedIDs []uint, total int, err error)
}

type AdminTokenQuery

type AdminTokenQuery interface {
	GetByID(id uint) (*models.Token, error)
	GetByKey(key string) (*models.Token, error)
	FindOwned(id, userID uint) (*models.Token, error)
	List(opts ListOptions, filter TokenListFilter) ([]models.Token, int64, error)
	ListByTemplateID(templateID uint) ([]models.Token, error)
	ListByIDs(ids []uint) ([]models.Token, error)
}

type AdminTokenTemplateMutation

type AdminTokenTemplateMutation interface {
	Create(tpl *models.TokenTemplate) error
	Update(id uint, updates map[string]any) error
	Delete(id uint) error
}

type AdminTokenTemplateQuery

type AdminTokenTemplateQuery interface {
	GetByID(id uint) (*models.TokenTemplate, error)
	List(opts ListOptions, filter TokenTemplateListFilter) ([]models.TokenTemplate, int64, error)
}

type AdminUsageLogMutation

type AdminUsageLogMutation interface {
	Create(log *models.UsageLog) error
	CreateTrace(trace *models.UsageLogTrace) error
}

type AdminUsageLogQuery

type AdminUsageLogQuery interface {
	List(opts ListOptions, filter UsageLogListFilter) ([]models.UsageLog, int64, error)
	GetByRequestID(requestID string) (*models.UsageLog, error)
	ExistsByRequestID(requestID string) (bool, error)
	GetTraceByRequestID(requestID string) (*models.UsageLogTrace, error)
	GetTracesByRequestID(requestID string) ([]*models.UsageLogTrace, error)
}

type AdminUserGroupMutation

type AdminUserGroupMutation interface {
	Create(g *models.UserGroup) error
	Update(id uint, updates map[string]any) error
	DeleteAndReassign(id uint) (affectedUserIDs []uint, deletedManagedRoleID uint, err error)
}

type AdminUserGroupQuery

type AdminUserGroupQuery interface {
	GetByID(id uint) (*models.UserGroup, error)
	GetByName(name string) (*models.UserGroup, error)
	FindIdentityAndAuthorizationForUser(userID uint) (*UserGroupIdentityAndAuthorization, error)
	List(opts ListOptions, filter UserGroupListFilter) ([]models.UserGroup, int64, error)
	MaxID() (uint, error)
	ListKeyset(afterID, snapshotMaxID uint, limit int) ([]models.UserGroup, error)
	CountThroughID(snapshotMaxID uint) (int64, error)
	CountUsers(id uint) (int64, error)
}

type AdminUserMutation

type AdminUserMutation interface {
	Create(user *models.User) error
	Update(id uint, updates map[string]any) error
	Delete(id uint) error
	UpdateQuota(id uint, delta int64) error
	DeductQuota(id uint, amount int64) (remainingQuota int64, err error)
}

type AdminUserQuery

type AdminUserQuery interface {
	GetByID(id uint) (*models.User, error)
	ListByIDs(ids []uint) ([]models.User, error)
	GetByUsername(username string) (*models.User, error)
	GetByEmail(email string) (*models.User, error)
	List(opts ListOptions, filter UserListFilter) ([]models.User, int64, error)
	ListWithGroup(opts ListOptions, filter UserListFilter) ([]UserListRow, int64, error)
	ListByGroupIDs(groupIDs []uint) ([]models.User, error)
}

type AgentListFilter

type AgentListFilter struct {
	Search string
	Status *int
}

type AgentMetric added in v0.0.2

type AgentMetric struct {
	ID           string  `json:"id"`
	Name         string  `json:"name"`
	Online       bool    `json:"online"`
	LastSeen     int64   `json:"last_seen"`
	Requests     int64   `json:"requests"`
	TTFTAvgMs    int64   `json:"ttft_avg_ms"`
	TTFTP95Ms    int64   `json:"ttft_p95_ms"`
	TPSAvg       float64 `json:"tps_avg"`
	TPSP5        float64 `json:"tps_p5"`
	LatencyP95Ms int64   `json:"latency_p95_ms"`
	Spark24h     []int64 `json:"spark_24h"`
}

AgentMetric 是 Monitoring 页面 agent 维度的一行,聚合 24h 内 agent 用量, 并从 core DB 批量读取 models.Agent 的 Name/Status/LastSeen 后在内存合并。 TTFTP95Ms / LatencyP95Ms 同 ChannelMetric,按 agent_id 一次性分组回填(Task 7)。 TTFTAvgMs / TPSP5 补齐 TTFT avg+p95 与 TPS avg+p5 双值口径(Task 16),与 ChannelMetric 对称。

type AgentRecentHealth added in v0.0.8

type AgentRecentHealth struct {
	AgentID  string `gorm:"column:agent_id"`
	Requests int64  `gorm:"column:requests"`
	Failed   int64  `gorm:"column:failed"`
}

AgentRecentHealth 是近窗内某 agent 的请求/失败计数(算错误率与 QPS 用)。

type AgentRouteListFilter

type AgentRouteListFilter struct {
	SourceType string
	SourceID   *uint
}

AgentRouteListFilter 定义列表筛选条件。

type AgentRouteOverview added in v0.0.15

type AgentRouteOverview struct {
	models.AgentRoute
	SourceName string
	AgentName  string
}

type AgentRouteOverviewFilter added in v0.0.15

type AgentRouteOverviewFilter struct {
	Query      string
	SourceType string
	SourceID   *uint
	Model      string
	AgentID    string
}

type AppProvider

type AppProvider interface {
	GetCoreDB() *gorm.DB
	GetLogDB() *gorm.DB
	GetDatabaseLayoutMode() app.DatabaseLayoutMode
}

AppProvider is the minimal interface dao needs from the application container. Satisfied by AppProvider without importing the app package (avoids import cycles).

type AutoDisableResult added in v0.0.15

type AutoDisableResult struct {
	Updated bool
	OwnerID uint
}

AutoDisableResult 表示带 revision 条件的自动禁用是否提交成功; 只有 BYOK 渠道更新成功时才返回 OwnerID。

type BillingLogDeleteBatchResult added in v0.0.15

type BillingLogDeleteBatchResult struct {
	Deleted int64
	HasMore bool
	Next    BillingLogDeleteCursor
}

func DeleteBillingLogsBeforeBatch added in v0.0.15

func DeleteBillingLogsBeforeBatch(ctx context.Context, db *gorm.DB, cutoff time.Time, after BillingLogDeleteCursor, limit int) (BillingLogDeleteBatchResult, error)

type BillingLogDeleteCursor added in v0.0.15

type BillingLogDeleteCursor struct {
	CreatedAt int64
	ID        uint
}

type BillingOverview

type BillingOverview struct {
	TotalCost    int64   `json:"total_cost"`
	RequestCount int64   `json:"request_count"`
	SuccessRate  float64 `json:"success_rate"`
	ActiveTokens int64   `json:"active_tokens"`
	TotalTokens  int64   `json:"total_tokens"` // 含 cache: prompt+completion+cache_read+cache_write
}

type BillingRebuildFilter

type BillingRebuildFilter struct {
	StartDate string
	EndDate   string
	// Targets selects which log-owned daily tables to rebuild. Empty means both.
	Targets []string
}

type BillingRebuildResult

type BillingRebuildResult struct {
	ReplayedLogs  int64 `json:"replayed_logs"`
	EffectiveFrom int64 `json:"effective_from,omitempty"`
	EffectiveTo   int64 `json:"effective_to,omitempty"`
}

type Bucket added in v0.0.2

type Bucket struct {
	Name  string  `json:"name"`
	Value int64   `json:"value"`
	Ratio float64 `json:"ratio"`
}

Bucket 是 Distribution 输出的统一桶,包含归一化 ratio。

type CacheSaving added in v0.0.2

type CacheSaving struct {
	HitRatio    float64 `json:"hit_ratio"`
	SavedTokens int64   `json:"saved_tokens"`
	SavedCost   int64   `json:"saved_cost"`
	VsLabel     string  `json:"vs_label"`
	ReadTokens  int64   `json:"read_tokens"`
	WriteTokens int64   `json:"write_tokens"`
}

CacheSaving 是 CacheSaving DAO 输出。 HitRatio = cache_read_tokens / (prompt_tokens + cache_read_tokens), 零安全。 SavedTokens = sum(cache_read_tokens) (本来要付费的 prompt token, 命中缓存后没付)。 SavedCost = saved_tokens * (sum(input_cost) / sum(prompt_tokens)); prompt_tokens=0 时回退为 0。 VsLabel 当前固定 "vs no-cache", 给前端展示对照基线用。 ReadTokens = sum(cache_read_tokens) 原始量;当前与 SavedTokens 等值,保留两字段以便后续语义分离(如引入折扣系数)。 WriteTokens = sum(cache_write_tokens),反映本期请求触发的缓存写入量。

type ChannelBillingDailyItem

type ChannelBillingDailyItem struct {
	Date             string `json:"date"`
	RequestCount     int64  `json:"request_count"`
	SuccessCount     int64  `json:"success_count"`
	FailedCount      int64  `json:"failed_count"`
	PromptTokens     int64  `json:"prompt_tokens"`
	CompletionTokens int64  `json:"completion_tokens"`
	CacheReadTokens  int64  `json:"cache_read_tokens"`
	CacheWriteTokens int64  `json:"cache_write_tokens"`
	InputCost        int64  `json:"input_cost"`
	OutputCost       int64  `json:"output_cost"`
	TotalCost        int64  `json:"total_cost"`
	RawCost          int64  `json:"raw_cost"`
	// ReferenceCost is populated only by the BYOK owner query after request-fact
	// completeness is proven. A nil value means historical upstream cost is unknown.
	ReferenceCost *int64 `json:"-" gorm:"-"`
	LastUsedAt    int64  `json:"last_used_at"`
	// BYOK-only descriptors. Populated by ListPrivateChannelDailyByOwner so the
	// caller can build per-channel breakdowns without re-querying private_channels.
	// For admin-daily callers (GetChannelDaily) these stay zero/empty.
	PrivateChannelID uint   `json:"private_channel_id,omitempty"`
	ChannelName      string `json:"channel_name,omitempty"`
	ChannelType      int    `json:"channel_type,omitempty"`
}

type ChannelBillingListFilter

type ChannelBillingListFilter struct {
	ChannelID   *uint
	StartDate   string
	EndDate     string
	NameSearch  string // channel_name LIKE %NameSearch%; "" = 不过滤
	ChannelType *int   // channel_type = *ChannelType; nil = 不过滤
	MinTokens   int64  // HAVING total_tokens >= MinTokens; 0 = 不过滤
}

type ChannelBillingListItem

type ChannelBillingListItem struct {
	ChannelID        uint   `json:"channel_id"`
	ChannelName      string `json:"channel_name"`
	ChannelType      int    `json:"channel_type"`
	RequestCount     int64  `json:"request_count"`
	SuccessCount     int64  `json:"success_count"`
	FailedCount      int64  `json:"failed_count"`
	PromptTokens     int64  `json:"prompt_tokens"`
	CompletionTokens int64  `json:"completion_tokens"`
	CacheReadTokens  int64  `json:"cache_read_tokens"`
	CacheWriteTokens int64  `json:"cache_write_tokens"`
	InputCost        int64  `json:"input_cost"`
	OutputCost       int64  `json:"output_cost"`
	TotalCost        int64  `json:"total_cost"`
	LastUsedAt       int64  `json:"last_used_at"`
}

type ChannelListFilter

type ChannelListFilter struct {
	Search string
	Type   *int
	Status *int
}

type ChannelMetric added in v0.0.2

type ChannelMetric struct {
	ID           uint    `json:"id"`
	Name         string  `json:"name"`
	Requests     int64   `json:"requests"`
	ErrorRatio   float64 `json:"error_ratio"`
	TTFTAvgMs    int64   `json:"ttft_avg_ms"`
	TTFTP95Ms    int64   `json:"ttft_p95_ms"`
	TPSAvg       float64 `json:"tps_avg"`
	TPSP5        float64 `json:"tps_p5"`
	LatencyP95Ms int64   `json:"latency_p95_ms"`
	Spark24h     []int64 `json:"spark_24h"`
}

ChannelMetric 是 Monitoring 页面 channel 维度的一行,聚合 24h 内 channel 用量。 TTFTP95Ms 来自 UsageTTFTHistogram、LatencyP95Ms 来自 UsageDurationHistogram, 均按 channel_id 一次性分组查询后回填(Task 7)。

type ChannelModelBreakdownRow added in v0.0.14

type ChannelModelBreakdownRow struct {
	ModelName        string `json:"model_name"`
	Requests         int64  `json:"requests"`
	PromptTokens     int64  `json:"prompt_tokens"`
	CompletionTokens int64  `json:"completion_tokens"`
	CacheReadTokens  int64  `json:"cache_read_tokens"`
	CacheWriteTokens int64  `json:"cache_write_tokens"`
	TotalCost        int64  `json:"total_cost"`
	RawCost          int64  `json:"raw_cost"`
}

ChannelModelBreakdownRow 是单渠道按 model_name 分组的计费细分行。 billed = TotalCost(折后实付), raw = RawCost(折前原价);两者差额即渠道折扣/免费让利。

type ChannelOwnerPair added in v0.0.2

type ChannelOwnerPair struct {
	OwnerID     uint   `json:"owner_id"`
	ChannelName string `json:"channel_name" gorm:"column:channel_name"`
}

ChannelOwnerPair is a (owner_id, channel_name) preview row returned by CountByBaseURLPrefix. It is intentionally a thin projection — admin UI only needs enough context to identify which user/channel will break if a prefix is removed from the allowlist; it does not need full channel detail.

type ChannelUsage added in v0.0.10

type ChannelUsage struct {
	Calls      int64
	BilledCost int64
	RawCost    int64
}

ChannelUsage 是某渠道某窗口的用量汇总。BilledCost=对用户结算后(SUM total_cost), RawCost=折扣前原价(SUM raw_cost),供限额按口径取数。

type CleanupBatchResult added in v0.0.15

type CleanupBatchResult struct {
	Deleted int64
	HasMore bool
}

func DeleteCleanupTableBatch added in v0.0.15

func DeleteCleanupTableBatch(ctx context.Context, coreDB, logDB *gorm.DB, req CleanupTableRequest) (CleanupBatchResult, error)

DeleteCleanupTableBatch deletes at most 500 rows inside one database transaction.

type CleanupTablePolicy added in v0.0.15

type CleanupTablePolicy string
const (
	CleanupTablePolicyPlain CleanupTablePolicy = "plain"
)

type CleanupTablePreview added in v0.0.15

type CleanupTablePreview struct {
	Database       string
	Table          string
	Total          int64
	ToDelete       int64
	SnapshotMaxKey string
}

func PreviewCleanupTable added in v0.0.15

func PreviewCleanupTable(ctx context.Context, coreDB, logDB *gorm.DB, req CleanupTableRequest) (CleanupTablePreview, error)

PreviewCleanupTable counts the complete physical table and the eligible rows frozen by its watermark.

type CleanupTableRequest added in v0.0.15

type CleanupTableRequest struct {
	Database       string
	Table          string
	Cutoff         time.Time
	SnapshotMaxKey string
}

type CleanupTableSpec added in v0.0.15

type CleanupTableSpec struct {
	Database        string
	Name            string
	TimeColumn      string
	SnapshotColumn  string
	DeleteKeyColumn string
	Policy          CleanupTablePolicy
}

CleanupTableSpec is a static, audited mapping from an API table key to its physical table.

func FindCleanupTable added in v0.0.15

func FindCleanupTable(database, table string) (CleanupTableSpec, bool)

FindCleanupTable performs only exact matching against the static registry.

type Context

type Context interface {
	GetCoreDB() *gorm.DB
	CoreDB() *gorm.DB
	LogDB() (*gorm.DB, error)
	RequestLogModel() (*gorm.DB, any, error)
	DatabaseLayoutMode() (app.DatabaseLayoutMode, error)
	WithTx(tx *gorm.DB) Context
	WithCoreTx(tx *gorm.DB) Context
	WithLogTx(tx *gorm.DB) Context
}

Context is the base DAO context for admin-scoped operations.

func NewContext

func NewContext(application AppProvider) Context

NewContext creates an admin-scoped DAO context.

func NewContextWithContext added in v0.0.13

func NewContextWithContext(application AppProvider, ctx context.Context) Context

type CostTrendStacked added in v0.0.2

type CostTrendStacked struct {
	Buckets     []StackedBucket `json:"buckets"`
	SeriesOrder []string        `json:"series_order"`
}

CostTrendStacked 是 CostTrendStackedByModel 输出。 SeriesOrder 按总成本降序列出 top-N model_name, 多余的折叠在末尾的 "others"。

type DailyBillingRebuildTargets added in v0.0.15

type DailyBillingRebuildTargets struct {
	TokenDaily   bool
	ChannelDaily bool
}

DailyBillingRebuildTargets is the normalized set of log-owned daily tables selected by a rebuild request.

func NormalizeDailyBillingRebuildTargets added in v0.0.15

func NormalizeDailyBillingRebuildTargets(targets []string) (DailyBillingRebuildTargets, error)

NormalizeDailyBillingRebuildTargets validates public target names. An empty request selects both daily tables.

type DurationHistogramRow added in v0.0.13

type DurationHistogramRow struct {
	Date             string
	Hour             int
	ChannelID        uint
	PrivateChannelID uint
	ModelName        string
	AgentID          string
	MaxDurationMs    int64
	Hist             [durhist.NumSlots]int64
	UpdatedAt        int64
}

DurationHistogramRow is the pre-aggregated input to BatchUpsertDurationHistogram. 只含 status=1(成功)请求;Hist 槽定义见 internal/pkg/durhist。

type ErrBucket added in v0.0.2

type ErrBucket struct {
	ID    uint    `json:"id,omitempty"`    // populated for by=channel
	Stage string  `json:"stage,omitempty"` // populated for by=stage
	Name  string  `json:"name,omitempty"`  // channel name when by=channel
	Count int64   `json:"count"`
	Ratio float64 `json:"ratio"`
}

ErrBucket 是 ErrorDistribution 输出的一行。 by="stage" 时仅 Stage/Count/Ratio 有效; by="channel" 时仅 ID/Name/Count/Ratio 有效。

type Gran added in v0.0.2

type Gran string

Gran 是聚合粒度。

const (
	GranHour Gran = "hour"
	GranDay  Gran = "day"
)

type HourlyBucketRow added in v0.0.2

type HourlyBucketRow struct {
	Date             string
	Hour             int
	ChannelID        uint
	PrivateChannelID uint
	ModelName        string
	AgentID          string
	ChannelName      string
	ChannelType      int
	OwnerType        string

	RequestCount     int64
	SuccessCount     int64
	FailedCount      int64
	PromptTokens     int64
	CompletionTokens int64
	CacheReadTokens  int64
	CacheWriteTokens int64
	InputCost        int64
	OutputCost       int64
	TotalCost        int64
	RawCost          int64

	StreamRequestCount        int64
	SumFirstResponseMs        int64
	SumGenerationMs           int64
	SumStreamCompletionTokens int64

	SumInboundDecodeMs    int64
	SumUpstreamDispatchMs int64
	SumUpstreamDecodeMs   int64
	SumOutboundEncodeMs   int64
	SumClientEncodeMs     int64

	LastUsedAt int64
	UpdatedAt  int64
}

HourlyBucketRow is the pre-aggregated input to BatchUpsertHourlyBucket. 18 counters span standard + stream-conditional + 5-segment latency.

type HourlyPerformanceComponents added in v0.0.15

type HourlyPerformanceComponents struct {
	Hour       time.Time
	Components PerformanceComponents
}

type InviteCodeListFilter added in v0.0.6

type InviteCodeListFilter struct {
	CreatorID *uint
	Search    string
}

type KnownTable

type KnownTable string

KnownTable constrains table names for stats queries.

const (
	TableUsers            KnownTable = "users"
	TableTokens           KnownTable = "tokens"
	TableChannels         KnownTable = "channels"
	TableAgents           KnownTable = "agents"
	TableModelConfigs     KnownTable = "model_configs"
	TableUsageLogs        KnownTable = "usage_logs"
	TableUsageLogTraces   KnownTable = "usage_log_traces"
	TableSettings         KnownTable = "settings"
	TableEnrollmentTokens KnownTable = "enrollment_tokens"
)

type KpiBundle added in v0.0.2

type KpiBundle struct {
	Requests    KpiMetric  `json:"requests"`
	Cost        KpiMetric  `json:"cost"`
	Tokens      KpiMetric  `json:"tokens"`
	Users       *KpiUsers  `json:"users,omitempty"`        // admin only
	SuccessRate *KpiMetric `json:"success_rate,omitempty"` // admin only
	Quota       *KpiQuota  `json:"quota,omitempty"`        // user only
}

KpiBundle 是 Dashboard KPI 卡片的统一返回结构。 admin scope 填充 Users / SuccessRate; user scope 填充 Quota。

type KpiMetric added in v0.0.2

type KpiMetric struct {
	Value int64   `json:"value"`
	Spark []int64 `json:"spark"`
	Delta float64 `json:"delta"`
}

KpiMetric 是单个 KPI 卡片的统一格式: Value=当前周期总量, Spark=逐小时序列, Delta=(current - prev) / prev (前一同长度周期); prev=0 时 Delta=0。 Spark 长度与 HourlyTrend 输出对齐 (range < 24h 时可能 < 24)。

type KpiQuota added in v0.0.2

type KpiQuota struct {
	Quota     int64 `json:"quota"`
	UsedQuota int64 `json:"used_quota"`
}

KpiQuota 仅 user 返回; 直接读 users 表的 quota/used_quota。

type KpiUsers added in v0.0.2

type KpiUsers struct {
	Value  int64 `json:"value"`
	Active int64 `json:"active"`
	New    int64 `json:"new"`
}

KpiUsers 仅 admin 返回; Value=总用户数, Active=range 内有 usage_log 的用户数, New=range 内注册用户数。

type LeaderRow added in v0.0.2

type LeaderRow struct {
	ID       uint    `json:"id,omitempty"`
	Name     string  `json:"name"`
	Cost     int64   `json:"cost"`
	Requests int64   `json:"requests"`
	Tokens   int64   `json:"tokens"`
	TPS      float64 `json:"tps,omitempty"`
	TTFTMs   int64   `json:"ttft_ms,omitempty"`
}

LeaderRow 是 Leaderboard 输出的统一行。 ID 字段含义随 by 维度变化: by="user" -> user_id, by="channel" -> channel_id, by="model" 时 ID = 0 (model 没有数字主键)。 TPS/TTFTMs 仅在底层数据有 stream 累计时才有意义。

type ListOptions

type ListOptions struct {
	Page     int
	PageSize int
}

ListOptions is shared pagination parameters.

func (ListOptions) Offset

func (o ListOptions) Offset() int

Offset returns the SQL offset for pagination.

type LogDailyBillingRebuilder added in v0.0.15

type LogDailyBillingRebuilder interface {
	FindRequestLogDateBounds(context.Context) (RequestLogDateBounds, error)
	FindNextRequestLogDate(context.Context, string, string) (string, bool, error)
	RebuildLogDailyDate(context.Context, string, uint, DailyBillingRebuildTargets) (*BillingRebuildResult, error)
}

LogDailyBillingRebuilder is the persistence boundary shared by automatic backfill and manually submitted daily rebuild jobs.

func NewLogDailyBillingRebuilder added in v0.0.15

func NewLogDailyBillingRebuilder(app AppProvider) LogDailyBillingRebuilder

type LogsTotals added in v0.0.2

type LogsTotals struct {
	Total       int64   `json:"total"`
	Failed      int64   `json:"failed"`
	P95Ms       int64   `json:"p95_ms"`
	SlowestMs   int64   `json:"slowest_ms"`
	SparkTotal  []int64 `json:"spark_total"`
	SparkFailed []int64 `json:"spark_failed"`
	SparkP95    []int64 `json:"spark_p95"`
}

LogsTotals 是 LogsTotals DAO 输出, 给 /v1/logs/insights 用。 Spark* 长度恒为 24, 槽位对应 r.End 前的最后 24 小时; SparkP95 用 MAX(duration) 作 p95 的近似 (per-bucket 真实 p95 要 24 个独立查询, 用 MAX 折中)。

type MarketplacePerformanceOfferKey added in v0.0.15

type MarketplacePerformanceOfferKey struct {
	ModelName string
	Kind      MarketplacePerformanceOfferKind
	SourceID  uint
}

MarketplacePerformanceOfferKey is the complete internal identity used for log facts and cache maps. It is deliberately unrelated to public offer_ref.

type MarketplacePerformanceOfferKind added in v0.0.15

type MarketplacePerformanceOfferKind string
const (
	MarketplacePerformanceOfferPlatform MarketplacePerformanceOfferKind = "platform"
	MarketplacePerformanceOfferPrivate  MarketplacePerformanceOfferKind = "private"
)

type MarketplacePrivateChannelScope added in v0.0.15

type MarketplacePrivateChannelScope struct {
	UserID      uint
	GroupIDs    []uint
	AdminGlobal bool
}

MarketplacePrivateChannelScope describes which BYOK channels a marketplace viewer may see. AdminGlobal is reserved for the administrator's unscoped diagnostic view; scoped views use UserID and GroupIDs for authorization but retain disabled metadata. Runtime availability comes only from the embedded Agent planner.

type MarketplaceRoutingScope added in v0.0.15

type MarketplaceRoutingScope struct {
	UserID      uint
	TokenID     uint
	GroupIDs    []uint
	AdminGlobal bool
}

MarketplaceRoutingScope describes the concrete runtime routing view. A token preview carries both its token and owner; GroupIDs are retained so every marketplace finder receives the same authorization context even though the current model_routings schema has no group-owned scope.

type MarketplaceUsageOffer added in v0.0.15

type MarketplaceUsageOffer struct {
	ModelName string
	Kind      MarketplaceUsageOfferKind
	SourceID  uint
}

MarketplaceUsageOffer is the complete internal request-fact identity. It is built from canonical offers already re-enumerated for the current viewer and is never decoded from an HTTP request.

type MarketplaceUsageOfferKind added in v0.0.15

type MarketplaceUsageOfferKind string
const (
	MarketplaceUsageOfferPlatform MarketplaceUsageOfferKind = "platform"
	MarketplaceUsageOfferPrivate  MarketplaceUsageOfferKind = "private"
)

type MarketplaceUsageRange added in v0.0.15

type MarketplaceUsageRange struct {
	Start int64
	End   int64
}

type MarketplaceUsageTotals added in v0.0.15

type MarketplaceUsageTotals struct {
	InputTokens       int64
	OutputTokens      int64
	CacheReadTokens   int64
	CacheWriteTokens  int64
	ReferenceCost     *int64
	GatewayChargeCost int64
}

type MetricStackedBucket added in v0.0.14

type MetricStackedBucket struct {
	Ts     int64              `json:"ts"`
	Label  string             `json:"label"`
	Series map[string]float64 `json:"series"`
}

MetricStackedBucket is one time-slot of MetricTrendGrouped output. Series keys are top-N model/channel names (or the "others" fold); values are the metric's already-divided per-bucket number (float64, since ttft/tps/ cache_hit_rate are not integers).

type MetricTrendStacked added in v0.0.14

type MetricTrendStacked struct {
	Buckets     []MetricStackedBucket `json:"buckets"`
	SeriesOrder []string              `json:"series_order"`
}

MetricTrendStacked is MetricTrendGrouped's output; SeriesOrder is ranked by total request volume (see assembleMetricStacked), independent of the metric being charted, so switching metrics on the same topN doesn't reshuffle which entities are "top" out from under the user.

type ModelConfigListFilter

type ModelConfigListFilter struct {
	Search      string
	PriceFilter string // "" or "all" = no filter, "no_price", "has_price"
}

type ModelMarketplacePerformanceQuery added in v0.0.15

type ModelMarketplacePerformanceQuery interface {
	FindGlobalPerformance(context.Context, time.Time) (map[MarketplacePerformanceOfferKey][]HourlyPerformanceComponents, error)
}

func NewModelMarketplacePerformanceQuery added in v0.0.15

func NewModelMarketplacePerformanceQuery(ctx Context) ModelMarketplacePerformanceQuery

type ModelMarketplaceQuery added in v0.0.15

type ModelMarketplaceQuery interface {
	ListEnabledMarketplaceModels(context.Context) ([]models.ModelConfig, error)
	ListMarketplaceChannels(context.Context) ([]models.Channel, error)
	ListMarketplacePrivateChannels(context.Context, MarketplacePrivateChannelScope) ([]models.PrivateChannel, error)
	ListMarketplaceRoutings(context.Context, MarketplaceRoutingScope) ([]models.ModelRouting, error)
}

ModelMarketplaceQuery is the batched read surface used to compose the model marketplace. Every method issues at most one SQL query regardless of how many models are returned.

func NewModelMarketplaceQuery added in v0.0.15

func NewModelMarketplaceQuery(ctx Context) ModelMarketplaceQuery

type ModelMarketplaceUsageQuery added in v0.0.15

func NewModelMarketplaceUsageQuery added in v0.0.15

func NewModelMarketplaceUsageQuery(ctx Context) ModelMarketplaceUsageQuery

type ModelRoutingListFilter

type ModelRoutingListFilter struct {
	Scope   string // "" | "global" | "user" | "token"
	UserID  *uint
	TokenID *uint
	Q       string // 名称模糊搜索
}

ModelRoutingListFilter 定义列表筛选条件。

type Mutation

type Mutation interface {
	User() UserMutation
}

func NewMutation

func NewMutation(ctx UserContext) Mutation

type NameProvider

type NameProvider interface {
	HasModel(name string) bool
	HasToken(tokenID uint) bool
	GetGlobalRouting(name string) *models.ModelRouting
	AllGlobalRoutings() []*models.ModelRouting
}

NameProvider 为校验函数提供名称查询能力,与 DB 解耦。

type ObsFilter added in v0.0.8

type ObsFilter struct {
	ModelName string
	UserID    uint
	TokenID   uint
}

ObsFilter 是观测查询的可选筛选维度,零值表示不筛。 ModelName="" 表示所有模型;UserID=0 表示不按用户筛(仅 admin 生效)。

func (ObsFilter) EffectiveUserID added in v0.0.8

func (f ObsFilter) EffectiveUserID(scope Scope) uint

EffectiveUserID 返回查询实际应锁定的 user_id。 非 admin 永远锁自己(忽略 f.UserID,防越权);admin 选了某用户则用之,否则 0(全局)。

type ObsRange added in v0.0.2

type ObsRange struct {
	Start int64 // unix sec, inclusive
	End   int64 // unix sec, exclusive
	Gran  Gran
}

ObsRange 描述聚合查询的时间窗口 + 粒度。 Start/End 是 unix 秒(inclusive/exclusive)。 Days() 委托到 listfilter.TimeWindow,与 listfilter 包共享同一逻辑; 调用站 struct-literal 写法不变(Start/End/Gran 仍是直接字段)。

func (ObsRange) Days added in v0.0.2

func (r ObsRange) Days() int

Days 返回 [Start, End) 跨多少天,向上取整。End ≤ Start 返回 0。 实现委托到 listfilter.TimeWindow.Days(),保持与 listfilter 同步。

func (ObsRange) TimeWindow added in v0.0.2

func (r ObsRange) TimeWindow() listfilter.TimeWindow

TimeWindow 把 ObsRange 的时间字段适配为 listfilter.TimeWindow, 可传给 listfilter.TimeWindow.Apply / Validate 等方法。

func (ObsRange) Validate added in v0.0.2

func (r ObsRange) Validate() error

Validate 按 Gran 应用对应的 max-days 限制。

type OverviewStats

type OverviewStats struct {
	UserCount        int64
	TokenCount       int64
	ChannelCount     int64
	AgentCount       int64
	ModelConfigCount int64
	UsageLogCount    int64
	TotalCost        int64
}

OverviewStats holds cross-entity aggregate counts for the admin dashboard.

type OwnerChannelUsageScope added in v0.0.15

type OwnerChannelUsageScope struct {
	ViewerUserID uint
	Offers       []MarketplaceUsageOffer
	Range        MarketplaceUsageRange
}

OwnerChannelUsageScope is constructed from MarketplaceViewer.UserID plus offers marked owned by server-side enumeration. The DAO rechecks every private_channel.owner_id in one core query before reading log facts.

type PerformanceComponents added in v0.0.15

type PerformanceComponents struct {
	RequestCount              int64
	SuccessCount              int64
	StreamRequestCount        int64
	SumFirstResponseMs        int64
	SumStreamCompletionTokens int64
	SumGenerationMs           int64
	InputTokens               int64
	OutputTokens              int64
	CacheReadTokens           int64
	CacheWriteTokens          int64
	TTFTHistogram             PerformanceHistogram
	TPSHistogram              PerformanceHistogram
	DurationHistogram         PerformanceHistogram
}

PerformanceComponents preserves every numerator and denominator needed to reproject summaries, health, and trends without averaging averages.

func (PerformanceComponents) Merge added in v0.0.15

Merge returns a new set of components. Integer overflow is an invalid aggregate instead of silently wrapping into a healthy-looking metric.

type PerformanceHistogram added in v0.0.15

type PerformanceHistogram struct {
	Counts [17]int64
	Max    int64
}

PerformanceHistogram keeps the existing fixed 17-slot codec plus the observed maximum used to interpolate the overflow slot.

type PrivateChannelByModelItem added in v0.0.2

type PrivateChannelByModelItem struct {
	ModelName        string `json:"model_name"`
	RequestCount     int64  `json:"request_count"`
	SuccessCount     int64  `json:"success_count"`
	FailedCount      int64  `json:"failed_count"`
	PromptTokens     int64  `json:"prompt_tokens"`
	CompletionTokens int64  `json:"completion_tokens"`
	CacheReadTokens  int64  `json:"cache_read_tokens"`
	CacheWriteTokens int64  `json:"cache_write_tokens"`
	InputCost        int64  `json:"input_cost"`
	OutputCost       int64  `json:"output_cost"`
	TotalCost        int64  `json:"total_cost"`
	RawCost          int64  `json:"-"`
	ReferenceMissing int64  `json:"-"`
	ReferenceCost    *int64 `json:"reference_cost" gorm:"-"`
}

PrivateChannelByModelItem 是 by-model 聚合的单行结果。

type PrivateChannelFilter added in v0.0.2

type PrivateChannelFilter struct {
	Search    string
	ModelName string
	Type      *int
	Status    *int
	OwnerID   *uint // only meaningful for admin cross-owner views
}

PrivateChannelFilter is the optional filter passed to list operations.

Search is name-only. Pre-Task-25 we additionally LIKE-matched against the JSON-encoded `models` text blob, but that conflated "find channel by name" with "find channel that exposes model X" (e.g. searching "gpt" hit every channel whose models array contained "gpt-4o"). Use ModelName for the model-membership filter — it matches the JSON token boundary (`"<name>"`) so substrings like "gpt-4" do NOT accidentally match "gpt-4-turbo".

type Query

type Query interface {
	User() UserQuery
	UsageLog() UsageLogQuery
}

func NewQuery

func NewQuery(ctx UserContext) Query

type QueryKey added in v0.0.14

type QueryKey struct {
	Name    string
	From    int64
	To      int64
	Scope   string
	UserID  uint
	TokenID uint
	Model   string
	Dim     string
	Metric  string
	Stat    string
	Gran    string
	TopN    int
}

QueryKey contains every dimension that can change a cached statistics result.

type RequestLogDateBounds added in v0.0.15

type RequestLogDateBounds struct {
	StartDate string
	EndDate   string
	Empty     bool
}

type Scope added in v0.0.2

type Scope struct {
	IsAdmin bool
	UserID  uint
}

Scope 是被聚合 DAO 共享的访问范围。IsAdmin=false 时 UserID 必须 > 0。

type SelectedTokenUsageScope added in v0.0.15

type SelectedTokenUsageScope struct {
	UserID  uint
	TokenID uint
	Offers  []MarketplaceUsageOffer
	Range   MarketplaceUsageRange
}

SelectedTokenUsageScope has no free-form filters: the current user's ID, selected persisted token, canonical offers, and validated window are all mandatory and simultaneously applied by FindSelectedTokenUsage.

type SigningKeyStore added in v0.0.13

type SigningKeyStore interface {
	LoadOrCreateActive(ctx context.Context) (*models.MasterSigningKey, error)
}

func NewMasterSigningKeyStore added in v0.0.13

func NewMasterSigningKeyStore(db *gorm.DB) SigningKeyStore

type SpeedRow added in v0.0.2

type SpeedRow struct {
	ID        uint    `json:"id,omitempty"`
	Name      string  `json:"name"`
	TTFTMs    int64   `json:"ttft_ms"`
	TPS       float64 `json:"tps"`
	TTFTP95Ms int64   `json:"ttft_p95_ms"`
	TPSP5     float64 `json:"tps_p5"`
}

SpeedRow 是 SpeedCompare 输出的一行 (维度: model | channel)。 ID 仅在 dimension=channel 时填充; model 维度无数字主键, ID=0。 TTFTP95Ms/TPSP5 与 TTFTMs/TPS(均值) 并列,来自 ttft/tps 直方图侧表 (Task 7)。

type StackedBucket added in v0.0.2

type StackedBucket struct {
	Ts     int64            `json:"ts"`
	Label  string           `json:"label"`
	Series map[string]int64 `json:"series"`
}

StackedBucket 是 CostTrendStackedByModel 输出的一行 (一个时间槽)。 Series 的 key 是 model_name (或 "others" 折叠桶); Value 是该槽内该 series 的总成本。

type StageLatency added in v0.0.2

type StageLatency struct {
	Stages []StageP95 `json:"stages"`
}

StageLatency 是 StageLatencyP95 输出, 固定 5 个 stage, 顺序由 stageLatencyColumns 决定。

type StageP95 added in v0.0.2

type StageP95 struct {
	Name  string `json:"name"`
	P95Ms int64  `json:"p95_ms"`
}

StageP95 是 StageLatency 的单条记录。

type StatsCache added in v0.0.14

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

StatsCache coalesces identical in-flight statistics queries and retains only a small, short-lived set of successful results.

func NewStatsCache added in v0.0.14

func NewStatsCache() *StatsCache

func (*StatsCache) Clear added in v0.0.15

func (c *StatsCache) Clear()

Clear invalidates completed entries and every current in-flight generation. A load that ignores its canceled context is still prevented from storing later.

func (*StatsCache) Get added in v0.0.14

func (c *StatsCache) Get(ctx context.Context, key QueryKey, load func(context.Context) (any, error)) (any, error)

Get returns an isolated copy of a cached value. Failed and canceled loads are never inserted. A canceled waiter does not need to wait for another caller's shared load to finish.

type TPSHistogramRow added in v0.0.14

type TPSHistogramRow struct {
	Date             string
	Hour             int
	ChannelID        uint
	PrivateChannelID uint
	ModelName        string
	AgentID          string
	MaxTps           int64
	Hist             [tpshist.NumSlots]int64
	UpdatedAt        int64
}

TPSHistogramRow is the pre-aggregated input to BatchUpsertTPSHistogram. 只含 IsStream && status=1 && completion_tokens>0 && 生成耗时>0 的请求; Hist 槽定义见 internal/pkg/tpshist。

type TTFTHistogramRow added in v0.0.14

type TTFTHistogramRow struct {
	Date               string
	Hour               int
	ChannelID          uint
	PrivateChannelID   uint
	ModelName          string
	AgentID            string
	MaxFirstResponseMs int64
	Hist               [ttfthist.NumSlots]int64
	UpdatedAt          int64
}

TTFTHistogramRow is the pre-aggregated input to BatchUpsertTTFTHistogram. 只含 IsStream && status=1 && first_response_ms>0 的请求; Hist 槽定义见 internal/pkg/ttfthist。

type TimeBucket added in v0.0.2

type TimeBucket struct {
	Ts               int64  `json:"ts"`
	Label            string `json:"label"`
	Cost             int64  `json:"cost"`
	Requests         int64  `json:"requests"`
	Tokens           int64  `json:"tokens"`
	PromptTokens     int64  `json:"prompt_tokens"`
	CompletionTokens int64  `json:"completion_tokens"`
	CacheReadTokens  int64  `json:"cache_read_tokens"`
	CacheWriteTokens int64  `json:"cache_write_tokens"`
	// TTFTMs/TPS 是该桶的均值(仅 stream 累计有效时才非零); CacheHitRate 是 0-100 百分比
	// (= cache_read/(prompt+cache_read)*100)。CacheHitRate 三条聚合路径都填充;
	// TTFTMs/TPS 在 hourlyTrendHybrid 与 hourlyTrendFromUsageLog 路径填充;
	// 完整 token_daily 日无 stream/first_response 逐请求列,因此这两项为 0。
	TTFTMs       int64   `json:"ttft_ms"`
	TPS          float64 `json:"tps"`
	CacheHitRate float64 `json:"cache_hit_rate"`
}

TimeBucket 是 trend 输出的统一桶。Tokens 含 cache(= 4 个分量之和)。

type TokenBillingDailyItem

type TokenBillingDailyItem struct {
	Date             string `json:"date"`
	RequestCount     int64  `json:"request_count"`
	SuccessCount     int64  `json:"success_count"`
	FailedCount      int64  `json:"failed_count"`
	PromptTokens     int64  `json:"prompt_tokens"`
	CompletionTokens int64  `json:"completion_tokens"`
	CacheReadTokens  int64  `json:"cache_read_tokens"`
	CacheWriteTokens int64  `json:"cache_write_tokens"`
	InputCost        int64  `json:"input_cost"`
	OutputCost       int64  `json:"output_cost"`
	TotalCost        int64  `json:"total_cost"`
	LastUsedAt       int64  `json:"last_used_at"`
}

type TokenBillingListFilter

type TokenBillingListFilter struct {
	UserID     *uint
	TokenID    *uint
	StartDate  string
	EndDate    string
	NameSearch string // token_name LIKE %NameSearch%; "" = 不过滤
	MinTokens  int64  // HAVING total_tokens >= MinTokens; 0 = 不过滤
}

type TokenBillingListItem

type TokenBillingListItem struct {
	UserID           uint   `json:"user_id"`
	TokenID          uint   `json:"token_id"`
	TokenName        string `json:"token_name"`
	RequestCount     int64  `json:"request_count"`
	SuccessCount     int64  `json:"success_count"`
	FailedCount      int64  `json:"failed_count"`
	PromptTokens     int64  `json:"prompt_tokens"`
	CompletionTokens int64  `json:"completion_tokens"`
	CacheReadTokens  int64  `json:"cache_read_tokens"`
	CacheWriteTokens int64  `json:"cache_write_tokens"`
	InputCost        int64  `json:"input_cost"`
	OutputCost       int64  `json:"output_cost"`
	TotalCost        int64  `json:"total_cost"`
	LastUsedAt       int64  `json:"last_used_at"`
}

type TokenListFilter

type TokenListFilter struct {
	Search      string
	ID          *uint
	UserID      *uint
	Status      *int
	UsableAt    *int64
	APIRoleMode *models.APIRoleMode
}

type TokenTemplateListFilter

type TokenTemplateListFilter struct {
	Search string
	Status *int
}

type TrendItem

type TrendItem struct {
	Date             string `json:"date"`
	Requests         int64  `json:"requests"`
	PromptTokens     int64  `json:"prompt_tokens"`
	CompletionTokens int64  `json:"completion_tokens"`
	Cost             int64  `json:"cost"`
}

TrendItem holds aggregated usage data for a single day.

type UsageLogListFilter

type UsageLogListFilter struct {
	listfilter.TimeWindow // embed: Start/End int64 unix sec
	UserID                *uint
	TokenID               *uint
	ChannelID             *uint
	ModelName             string
	Status                *int
	OwnerType             *string // nil = no filter; "admin" | "private"
	PrivateChannelID      *uint
	RequestID             string // 精确匹配(唯一索引);"" = 不过滤
}

type UsageLogQuery

type UsageLogQuery interface {
	List(opts ListOptions, filter UsageLogListFilter) ([]models.UsageLog, int64, error)
	GetByRequestID(requestID string) (*models.UsageLog, error)
	PercentileTTFT(filter UsageLogListFilter, p float64) (int64, error)
}

type UserContext

type UserContext interface {
	Context
	UserInfo() *app.UserInfo
}

UserContext extends Context with authenticated user identity. Required for all user-scoped DAO operations.

func NewUserContext

func NewUserContext(application AppProvider, userInfo *app.UserInfo) UserContext

NewUserContext creates a user-scoped DAO context.

func NewUserContextWithContext added in v0.0.13

func NewUserContextWithContext(application AppProvider, ctx context.Context, userInfo *app.UserInfo) UserContext

type UserGroupIdentityAndAuthorization added in v0.0.15

type UserGroupIdentityAndAuthorization struct {
	IdentityGroupID    uint
	AuthorizationGroup models.UserGroup
}

UserGroupIdentityAndAuthorization separates the persisted group identity from the group row whose authorization policy is applied. A dangling non-default identity borrows the default group's policy without becoming the default group.

type UserGroupListFilter

type UserGroupListFilter struct {
	Search string
	Status *int
}

type UserListFilter

type UserListFilter struct {
	Search  string
	Role    *int
	GroupID *uint
}

type UserListRow

type UserListRow struct {
	models.User
	GroupName string `gorm:"column:group_name" json:"group_name"`
}

type UserMutation

type UserMutation interface {
	UpdatePassword(hashedPwd string) error
	UpdateProfile(updates map[string]any) error
}

type UserQuery

type UserQuery interface {
	GetProfile() (*models.User, error)
}

type ValidateError

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

ValidateError 的 code 与 msg 分离:API 层按 code 做 i18n(前端见 ROUTING_ERROR_KEYS), msg 仅用于日志和兜底文案。

func ValidateDelete

func ValidateDelete(target *models.ModelRouting, np NameProvider) *ValidateError

ValidateDelete 检查是否有其他 global routing 引用待删除的 routing。

func ValidateRouting

func ValidateRouting(r *models.ModelRouting, np NameProvider) *ValidateError

ValidateRouting 校验 ModelRouting,包含名称规则、成员规则、引用检查、DFS 环检测和深度上限。

func (*ValidateError) Code

func (e *ValidateError) Code() string

func (*ValidateError) Details

func (e *ValidateError) Details() map[string]any

func (*ValidateError) Error

func (e *ValidateError) Error() string

type WindowFilter added in v0.0.6

type WindowFilter struct {
	Kind        string
	SinceDate   string // "YYYY-MM-DD"
	MonthPrefix string // "YYYY-MM"
}

WindowFilter 描述对 channel_daily_billings.date 的过滤方式。 Kind:

"all"   → 不限日期(lifetime)
"since" → date >= SinceDate
"month" → date LIKE MonthPrefix+'%'

func ResolveWindow added in v0.0.6

func ResolveWindow(window string, days int, now time.Time) (WindowFilter, error)

ResolveWindow 把限额窗口 + now 解析成 date 过滤条件。now 应为 UTC。

Jump to

Keyboard shortcuts

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