db

package
v0.260430.1 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: MPL-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	HealthStatusOK      = "ok"
	HealthStatusError   = "error"
	HealthStatusNotInit = "not_initialized"
)

Health status constants

View Source
const (
	// DefaultAdminUserID is the user ID for the default admin user
	// This is used for usage records created before multi-tenant support
	DefaultAdminUserID = "admin"
)
View Source
const (
	ToolTypeMCPRuntime = "mcp_runtime" // MCP runtime tool sources

)

ToolType constants for different tool configuration types

Variables

This section is empty.

Functions

This section is empty.

Types

type APITokenRecord added in v0.260418.2200

type APITokenRecord struct {
	ID           uint       `gorm:"primaryKey;autoIncrement;column:id"`
	TokenID      string     `gorm:"uniqueIndex;column:token_id;not null;size:64"` // Token identifier (jti)
	UserID       string     `gorm:"index:idx_api_token_user_id;not null;column:user_id;size:64"`
	DisplayName  string     `gorm:"column:display_name;size:256"`
	Enabled      bool       `gorm:"column:enabled;default:true"`
	ExpiresAt    *time.Time `gorm:"column:expires_at;index"`
	LastUsedAt   *time.Time `gorm:"column:last_used_at"`
	CreatedAt    time.Time  `gorm:"column:created_at"`
	CreatedBy    string     `gorm:"column:created_by;size:64"`
	RevokedAt    *time.Time `gorm:"column:revoked_at"`
	RevokeReason string     `gorm:"column:revoke_reason;size:512"`
}

APITokenRecord represents a user API token for multi-tenant authentication

func (APITokenRecord) TableName added in v0.260418.2200

func (APITokenRecord) TableName() string

TableName specifies the table name for GORM

type APITokenStore added in v0.260418.2200

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

APITokenStore manages API tokens for multi-tenant authentication

func NewAPITokenStore added in v0.260418.2200

func NewAPITokenStore(baseDir string) (*APITokenStore, error)

NewAPITokenStore creates or loads an API token store using SQLite database.

func (*APITokenStore) CleanupExpiredTokens added in v0.260418.2200

func (s *APITokenStore) CleanupExpiredTokens(olderThan time.Duration) (int64, error)

CleanupExpiredTokens removes expired tokens older than the specified duration

func (*APITokenStore) Close added in v0.260418.2200

func (s *APITokenStore) Close() error

Close closes the database connection

func (*APITokenStore) CreateTokenWithTokenID added in v0.260418.2200

func (s *APITokenStore) CreateTokenWithTokenID(userID, tokenID, displayName, createdBy string, expiresAt *time.Time) (*APITokenRecord, error)

CreateTokenWithTokenID creates a new API token record with a specific token ID

func (*APITokenStore) DeleteToken added in v0.260418.2200

func (s *APITokenStore) DeleteToken(tokenID string) error

DeleteToken permanently deletes a token record

func (*APITokenStore) GetDB added in v0.260418.2200

func (s *APITokenStore) GetDB() *gorm.DB

GetDB returns the underlying GORM DB instance (for testing)

func (*APITokenStore) GetToken added in v0.260418.2200

func (s *APITokenStore) GetToken(tokenID string) (*APITokenRecord, error)

GetToken retrieves a token by token ID

func (*APITokenStore) ListTokens added in v0.260418.2200

func (s *APITokenStore) ListTokens(userID string, enabled *bool, limit, offset int) ([]APITokenRecord, int64, error)

ListTokens returns tokens matching filters

func (*APITokenStore) RevokeToken added in v0.260418.2200

func (s *APITokenStore) RevokeToken(tokenID, reason string) error

RevokeToken revokes a token by setting enabled to false

func (*APITokenStore) SetTokenEnabled added in v0.260418.2200

func (s *APITokenStore) SetTokenEnabled(tokenID string, enabled bool) error

SetTokenEnabled enables or disables a token

func (*APITokenStore) UpdateLastUsed added in v0.260418.2200

func (s *APITokenStore) UpdateLastUsed(tokenID string) error

UpdateLastUsed updates the last_used_at timestamp for a token

func (*APITokenStore) UpdateTokenString added in v0.260418.2200

func (s *APITokenStore) UpdateTokenString(tokenID, newTokenString string) error

UpdateTokenString updates the token string for a token (for regeneration)

func (*APITokenStore) ValidateToken added in v0.260418.2200

func (s *APITokenStore) ValidateToken(tokenID string) (*APITokenRecord, error)

ValidateToken validates a token ID and returns the associated token record

type AggregatedStat

type AggregatedStat struct {
	Key              string  `json:"key"`
	ProviderUUID     string  `json:"provider_uuid,omitempty"`
	ProviderName     string  `json:"provider_name,omitempty"`
	Model            string  `json:"model,omitempty"`
	Scenario         string  `json:"scenario,omitempty"`
	UserID           string  `json:"user_id,omitempty"`
	RequestCount     int64   `json:"request_count"`
	TotalTokens      int64   `json:"total_tokens"`
	InputTokens      int64   `json:"total_input_tokens"`
	OutputTokens     int64   `json:"total_output_tokens"`
	CacheInputTokens int64   `json:"cache_input_tokens"`
	SystemTokens     int64   `json:"system_tokens"`
	AvgInputTokens   float64 `json:"avg_input_tokens"`
	AvgOutputTokens  float64 `json:"avg_output_tokens"`
	AvgLatencyMs     float64 `json:"avg_latency_ms"`
	ErrorCount       int64   `json:"error_count"`
	ErrorRate        float64 `json:"error_rate"`
	StreamedCount    int64   `json:"streamed_count"`
	StreamedRate     float64 `json:"streamed_rate"`
}

AggregatedStat represents aggregated usage statistics

type EndpointType

type EndpointType string

EndpointType defines the type of API endpoint

const (
	EndpointTypeChat      EndpointType = "chat"
	EndpointTypeResponses EndpointType = "responses"
)

type HealthStatus

type HealthStatus struct {
	Healthy         bool              `json:"healthy"`
	TotalStores     int               `json:"total_stores"`
	HealthyStores   int               `json:"healthy_stores"`
	UnhealthyStores int               `json:"unhealthy_stores"`
	StoreStatus     map[string]string `json:"store_status"`
}

HealthStatus represents the health of all stores.

type ImBotSettingsRecord

type ImBotSettingsRecord struct {
	BotUUID       string `gorm:"primaryKey;column:bot_uuid"`
	Name          string `gorm:"column:name"`
	Platform      string `gorm:"column:platform;index:idx_platform"`
	AuthType      string `gorm:"column:auth_type"`
	AuthConfig    string `gorm:"column:auth_config;type:text"` // JSON string of auth map
	ProxyURL      string `gorm:"column:proxy_url"`
	ChatIDLock    string `gorm:"column:chat_id_lock"`
	BashAllowlist string `gorm:"column:bash_allowlist;type:text"` // JSON array string
	DefaultCwd    string `gorm:"column:default_cwd"`              // Default working directory
	DefaultAgent  string `gorm:"column:default_agent"`            // Default Agent UUID
	Enabled       bool   `gorm:"column:enabled;index:idx_enabled"`

	// Output behavior settings
	Debug   bool  `gorm:"column:debug;default:false"`  // Show message IDs in output
	Verbose *bool `gorm:"column:verbose;default:true"` // Send intermediate messages (nil = true)

	// SmartGuide model configuration (required for @tb agent)
	SmartGuideProvider string `gorm:"column:smartguide_provider"` // Provider UUID
	SmartGuideModel    string `gorm:"column:smartguide_model"`    // Model identifier

	CreatedAt time.Time `gorm:"column:created_at"`
	UpdatedAt time.Time `gorm:"column:updated_at"`
}

ImBotSettingsRecord is the GORM model for persisting ImBot credentials

func (*ImBotSettingsRecord) GetVerbose

func (r *ImBotSettingsRecord) GetVerbose() bool

GetVerbose returns verbose setting with default true

func (ImBotSettingsRecord) TableName

func (ImBotSettingsRecord) TableName() string

TableName specifies the table name for GORM

type ImBotSettingsStore

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

ImBotSettingsStore persists ImBot settings in SQLite using GORM.

func NewImBotSettingsStore

func NewImBotSettingsStore(baseDir string) (*ImBotSettingsStore, error)

NewImBotSettingsStore creates or loads an ImBot settings store using SQLite database.

func (*ImBotSettingsStore) CreateSettings

func (s *ImBotSettingsStore) CreateSettings(settings Settings) (Settings, error)

CreateSettings creates a new ImBot configuration.

func (*ImBotSettingsStore) DeleteSettings

func (s *ImBotSettingsStore) DeleteSettings(uuid string) error

DeleteSettings deletes an ImBot configuration.

func (*ImBotSettingsStore) GetSettingsByUUID

func (s *ImBotSettingsStore) GetSettingsByUUID(uuid string) (Settings, error)

GetSettingsByUUID returns a single ImBot configuration by UUID.

func (*ImBotSettingsStore) GetSettingsByUUIDInterface

func (s *ImBotSettingsStore) GetSettingsByUUIDInterface(uuid string) (interface{}, error)

GetSettingsByUUIDInterface returns settings as interface{} for SettingsStore interface

func (*ImBotSettingsStore) ListEnabledSettings

func (s *ImBotSettingsStore) ListEnabledSettings() ([]Settings, error)

ListEnabledSettings returns all enabled ImBot configurations.

func (*ImBotSettingsStore) ListEnabledSettingsInterface

func (s *ImBotSettingsStore) ListEnabledSettingsInterface() (interface{}, error)

ListEnabledSettingsInterface returns settings as interface{} for SettingsStore interface

func (*ImBotSettingsStore) ListSettings

func (s *ImBotSettingsStore) ListSettings() ([]Settings, error)

ListSettings returns all ImBot configurations.

func (*ImBotSettingsStore) ToggleSettings

func (s *ImBotSettingsStore) ToggleSettings(uuid string) (bool, error)

ToggleSettings toggles the enabled status of an ImBot configuration.

func (*ImBotSettingsStore) UpdateSettings

func (s *ImBotSettingsStore) UpdateSettings(uuid string, settings Settings) error

UpdateSettings updates an existing ImBot configuration. Only updates fields that are non-zero/empty in the settings struct.

type ModelCapability

type ModelCapability struct {
	ProviderUUID string       `gorm:"primaryKey;column:provider_uuid"`
	ModelID      string       `gorm:"primaryKey;column:model_id"`
	EndpointType EndpointType `gorm:"primaryKey;column:endpoint_type"`
	Available    bool         `gorm:"column:available"`
	LatencyMs    int          `gorm:"column:latency_ms"`
	LastChecked  time.Time    `gorm:"column:last_checked"`
	ErrorMessage string       `gorm:"column:error_message"`
	CreatedAt    time.Time    `gorm:"column:created_at"`
	UpdatedAt    time.Time    `gorm:"column:updated_at"`
}

ModelCapability stores endpoint capability information for each model

func (ModelCapability) TableName

func (ModelCapability) TableName() string

TableName specifies the table name for ModelCapability

type ModelCapabilityStore

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

ModelCapabilityStore persists model endpoint capability information in SQLite using GORM.

func NewModelCapabilityStore

func NewModelCapabilityStore(baseDir string) (*ModelCapabilityStore, error)

NewModelCapabilityStore creates or loads a model capability store using SQLite database.

func (*ModelCapabilityStore) GetCapability

func (mcs *ModelCapabilityStore) GetCapability(providerUUID, modelID string, endpointType EndpointType) (ModelCapability, bool)

GetCapability retrieves a single endpoint capability for a model

func (*ModelCapabilityStore) GetModelCapability

func (mcs *ModelCapabilityStore) GetModelCapability(providerUUID, modelID string) (ModelEndpointCapability, bool)

GetModelCapability retrieves aggregated capabilities for a model

func (*ModelCapabilityStore) GetProviderCapabilities

func (mcs *ModelCapabilityStore) GetProviderCapabilities(providerUUID string) map[string]ModelEndpointCapability

GetProviderCapabilities retrieves all capabilities for a provider

func (*ModelCapabilityStore) IsStale

func (mcs *ModelCapabilityStore) IsStale(providerUUID, modelID string, maxAge time.Duration) bool

IsStale checks if capabilities are stale (older than specified duration)

func (*ModelCapabilityStore) RemoveModel

func (mcs *ModelCapabilityStore) RemoveModel(providerUUID, modelID string) error

RemoveModel removes capabilities for a specific model

func (*ModelCapabilityStore) RemoveProvider

func (mcs *ModelCapabilityStore) RemoveProvider(providerUUID string) error

RemoveProvider removes all capabilities for a provider

func (*ModelCapabilityStore) SaveCapability

func (mcs *ModelCapabilityStore) SaveCapability(providerUUID, modelID string, endpointType EndpointType, available bool, latencyMs int, errorMsg string) error

SaveCapability saves a single endpoint capability for a model

type ModelEndpointCapability

type ModelEndpointCapability struct {
	ProviderUUID       string
	ModelID            string
	SupportsChat       bool
	ChatLatencyMs      int
	ChatError          string
	SupportsResponses  bool
	ResponsesLatencyMs int
	ResponsesError     string
	PreferredEndpoint  string // "chat", "responses", or ""
	LastVerified       time.Time
}

ModelEndpointCapability represents aggregated endpoint capabilities for a model

type ModelStore

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

ModelStore persists provider model information in SQLite using GORM.

func NewModelStore

func NewModelStore(baseDir string) (*ModelStore, error)

NewModelStore creates or loads a model store using SQLite database.

func (*ModelStore) GetAllModelRecords

func (ms *ModelStore) GetAllModelRecords() []ProviderModelRecord

GetAllModelRecords returns all provider records (with metadata)

func (*ModelStore) GetAllProviders

func (ms *ModelStore) GetAllProviders() []string

GetAllProviders returns all provider UUIDs that have models

func (*ModelStore) GetModelCount

func (ms *ModelStore) GetModelCount(providerUUID string) int

GetModelCount returns the number of models for a provider

func (*ModelStore) GetModels

func (ms *ModelStore) GetModels(providerUUID string) []string

GetModels returns models for a provider by UUID

func (*ModelStore) GetProviderInfo

func (ms *ModelStore) GetProviderInfo(providerUUID string) (apiBase string, lastUpdated string, exists bool)

GetProviderInfo returns basic info about a provider (apiBase, lastUpdated, exists)

func (*ModelStore) HasModels

func (ms *ModelStore) HasModels(providerUUID string) bool

HasModels checks if a provider has models

func (*ModelStore) RemoveProvider

func (ms *ModelStore) RemoveProvider(providerUUID string) error

RemoveProvider removes all models for a provider by UUID

func (*ModelStore) SaveModels

func (ms *ModelStore) SaveModels(provider *typ.Provider, apiBase string, models []string) error

SaveModels saves models for a provider by UUID

type ProviderModelRecord

type ProviderModelRecord struct {
	ProviderUUID string    `gorm:"primaryKey;column:provider_uuid"`
	ProviderName string    `gorm:"column:provider_name;index"`
	APIBase      string    `gorm:"column:api_base"`
	Models       string    `gorm:"column:models;type:text"` // JSON array of model names
	LastUpdated  time.Time `gorm:"column:last_updated"`
	CreatedAt    time.Time `gorm:"column:created_at"`
	UpdatedAt    time.Time `gorm:"column:updated_at"`
}

ProviderModelRecord is the GORM model for persisting provider models

func (ProviderModelRecord) TableName

func (ProviderModelRecord) TableName() string

TableName specifies the table name for GORM

type ProviderRecord

type ProviderRecord struct {
	UUID     string `gorm:"primaryKey;column:uuid"`
	Name     string `gorm:"column:name;not null;index"`
	APIBase  string `gorm:"column:api_base;not null"`
	APIStyle string `gorm:"column:api_style;not null"` // "openai" or "anthropic"
	AuthType string `gorm:"column:auth_type;not null"` // "api_key" or "oauth"

	// Configuration fields
	NoKeyRequired bool   `gorm:"column:no_key_required;default:false"`
	Enabled       bool   `gorm:"column:enabled;default:true"`
	ProxyURL      string `gorm:"column:proxy_url"`
	Timeout       int64  `gorm:"column:timeout"`
	Tags          string `gorm:"column:tags;type:text"` // JSON array
	LastUpdated   string `gorm:"column:last_updated"`

	// Credential fields - stored with provider as a unit
	// For api_key auth: stores the API key
	// For oauth auth: stores OAuth access token
	Token             string `gorm:"column:token"`                        // API key or access token
	OAuthProviderType string `gorm:"column:oauth_provider_type"`          // For oauth: provider type
	OAuthUserID       string `gorm:"column:oauth_user_id"`                // For oauth: user ID
	OAuthRefreshToken string `gorm:"column:oauth_refresh_token"`          // For oauth: refresh token
	OAuthExpiresAt    string `gorm:"column:oauth_expires_at"`             // For oauth: token expiration (RFC3339)
	OAuthExtraFields  string `gorm:"column:oauth_extra_fields;type:text"` // For oauth: JSON

	CreatedAt time.Time `gorm:"column:created_at"`
	UpdatedAt time.Time `gorm:"column:updated_at"`
}

ProviderRecord is the GORM model for persisting a complete provider This includes both configuration and credentials as one logical entity

func (ProviderRecord) TableName

func (ProviderRecord) TableName() string

TableName specifies the table name for GORM

type ProviderStore

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

ProviderStore manages providers as complete units (configuration + credentials)

func NewProviderStore

func NewProviderStore(baseDir string) (*ProviderStore, error)

NewProviderStore creates or loads a provider store using SQLite database.

func (*ProviderStore) Close

func (ps *ProviderStore) Close() error

Close closes the database connection

func (*ProviderStore) Count

func (ps *ProviderStore) Count() (int64, error)

Count returns the total number of providers

func (*ProviderStore) Delete

func (ps *ProviderStore) Delete(uuid string) error

Delete removes a provider by UUID

func (*ProviderStore) Exists

func (ps *ProviderStore) Exists(uuid string) bool

Exists checks if a provider exists by UUID

func (*ProviderStore) GetAccessToken

func (ps *ProviderStore) GetAccessToken(uuid string) (string, error)

GetAccessToken returns the access token for a provider (convenience method)

func (*ProviderStore) GetByName

func (ps *ProviderStore) GetByName(name string) (*typ.Provider, error)

GetByName returns a provider by name

func (*ProviderStore) GetByUUID

func (ps *ProviderStore) GetByUUID(uuid string) (*typ.Provider, error)

GetByUUID returns a provider by UUID

func (*ProviderStore) GetDB

func (ps *ProviderStore) GetDB() *gorm.DB

GetDB returns the underlying GORM DB instance (for testing/advanced usage)

func (*ProviderStore) IsOAuthExpired

func (ps *ProviderStore) IsOAuthExpired(uuid string) (bool, error)

IsOAuthExpired checks if the OAuth token for a provider is expired

func (*ProviderStore) List

func (ps *ProviderStore) List() ([]*typ.Provider, error)

List returns all providers

func (*ProviderStore) ListEnabled

func (ps *ProviderStore) ListEnabled() ([]*typ.Provider, error)

ListEnabled returns all enabled providers

func (*ProviderStore) ListOAuth

func (ps *ProviderStore) ListOAuth() ([]*typ.Provider, error)

ListOAuth returns all OAuth-enabled providers

func (*ProviderStore) Save

func (ps *ProviderStore) Save(provider *typ.Provider) error

Save saves a provider (create or update)

func (*ProviderStore) UpdateCredential

func (ps *ProviderStore) UpdateCredential(uuid string, token string, oauthDetail *typ.OAuthDetail) error

UpdateCredential updates only the credential fields of a provider

func (*ProviderStore) UpdateOAuthAccessToken

func (ps *ProviderStore) UpdateOAuthAccessToken(uuid, accessToken string) error

UpdateOAuthAccessToken updates only the OAuth access token for a provider

type RuleServiceRecord

type RuleServiceRecord struct {
	RuleUUID         string `gorm:"primaryKey;column:rule_uuid"`
	CurrentServiceID string `gorm:"column:current_service_id"` // provider:model format
}

RuleServiceRecord stores the current service for each rule using provider+model as ID This is persisted to SQLite to avoid frequent config.json writes

func (RuleServiceRecord) TableName

func (RuleServiceRecord) TableName() string

TableName specifies the table name for GORM

type RuleStateStore

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

RuleStateStore manages rule state persistence separately from config

func NewRuleStateStore

func NewRuleStateStore(baseDir string) (*RuleStateStore, error)

NewRuleStateStore creates or loads a rule state store using SQLite database.

func (*RuleStateStore) ClearAll

func (rs *RuleStateStore) ClearAll() error

ClearAll removes all persisted rule state

func (*RuleStateStore) GetServiceID

func (rs *RuleStateStore) GetServiceID(ruleUUID string) (string, error)

GetServiceID retrieves the current service ID for a rule

func (*RuleStateStore) HydrateRules

func (rs *RuleStateStore) HydrateRules(rules []typ.Rule) error

HydrateRules loads service IDs from SQLite into the provided rules

func (*RuleStateStore) SetServiceID

func (rs *RuleStateStore) SetServiceID(ruleUUID string, serviceID string) error

SetServiceID sets the current service ID for a rule

type ServiceStatsRecord

type ServiceStatsRecord struct {
	// Composite primary key: provider + model (stats are global, not per-rule)
	Provider             string    `gorm:"primaryKey;column:provider"`
	Model                string    `gorm:"primaryKey;column:model"`
	ServiceID            string    `gorm:"column:service_id"`
	RequestCount         int64     `gorm:"column:request_count"`
	LastUsed             time.Time `gorm:"column:last_used"`
	WindowStart          time.Time `gorm:"column:window_start"`
	WindowRequestCount   int64     `gorm:"column:window_request_count"`
	WindowTokensConsumed int64     `gorm:"column:window_tokens_consumed"`
	WindowInputTokens    int64     `gorm:"column:window_input_tokens"`
	WindowOutputTokens   int64     `gorm:"column:window_output_tokens"`
	TimeWindow           int       `gorm:"column:time_window"`
}

ServiceStatsRecord is the GORM model for persisting service statistics

func (ServiceStatsRecord) TableName

func (ServiceStatsRecord) TableName() string

TableName specifies the table name for GORM

type Settings

type Settings struct {
	UUID          string            `json:"uuid,omitempty"`
	Name          string            `json:"name,omitempty"`
	Token         string            `json:"token,omitempty"` // Legacy: for backward compatibility
	Platform      string            `json:"platform"`
	AuthType      string            `json:"auth_type"`
	Auth          map[string]string `json:"auth"`
	ProxyURL      string            `json:"proxy_url,omitempty"`
	ChatIDLock    string            `json:"chat_id,omitempty"`
	BashAllowlist []string          `json:"bash_allowlist,omitempty"`
	DefaultCwd    string            `json:"default_cwd,omitempty"`   // Default working directory
	DefaultAgent  string            `json:"default_agent,omitempty"` // Default Agent UUID
	Enabled       bool              `json:"enabled"`
	// SmartGuide model configuration (required for @tb agent)
	SmartGuideProvider string    `json:"smartguide_provider,omitempty"` // Provider UUID
	SmartGuideModel    string    `json:"smartguide_model,omitempty"`    // Model identifier
	CreatedAt          time.Time `json:"created_at,omitempty"`
	UpdatedAt          time.Time `json:"updated_at,omitempty"`
}

Settings represents ImBot configuration (exported for use by remote_coder module)

type StatsStore

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

StatsStore persists service usage statistics in SQLite using GORM.

func NewStatsStore

func NewStatsStore(baseDir string) (*StatsStore, error)

NewStatsStore creates or loads a stats store using SQLite database.

func (*StatsStore) ClearAll

func (ss *StatsStore) ClearAll() error

ClearAll removes all persisted stats.

func (*StatsStore) Get

func (ss *StatsStore) Get(provider, model string) (loadbalance.ServiceStats, bool)

Get returns stats for a specific provider/model combination.

func (*StatsStore) HydrateRules

func (ss *StatsStore) HydrateRules(rules []typ.Rule) error

HydrateRules injects stored stats into the provided rules and initializes missing entries.

func (*StatsStore) RecordUsage

func (ss *StatsStore) RecordUsage(service *loadbalance.Service, inputTokens, outputTokens int) (loadbalance.ServiceStats, error)

RecordUsage records usage for a service and persists the updated stats.

func (*StatsStore) ServiceKey

func (ss *StatsStore) ServiceKey(provider, model string) string

ServiceKey builds a unique key for a provider/model combination.

func (*StatsStore) Snapshot

func (ss *StatsStore) Snapshot() map[string]loadbalance.ServiceStats

Snapshot returns a copy of all stats keyed by provider:model.

func (*StatsStore) UpdateFromService

func (ss *StatsStore) UpdateFromService(service *loadbalance.Service) error

UpdateFromService stores the current stats from a service into the store.

type StoreManager

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

StoreManager manages all database stores with a shared GORM DB instance. It provides unified initialization, thread-safe access, and lifecycle management.

func NewStoreManager

func NewStoreManager(baseDir string) (*StoreManager, error)

NewStoreManager creates a new StoreManager and initializes all stores. It opens a single SQLite database connection shared by all stores.

Parameters:

baseDir - Base directory for database storage

Returns:

*StoreManager - Initialized store manager
error - Error if any store fails to initialize

func NewStoreManagerWithConfig

func NewStoreManagerWithConfig(config StoreManagerConfig) (*StoreManager, error)

NewStoreManagerWithConfig creates a StoreManager with custom configuration.

func (*StoreManager) APIToken added in v0.260418.2200

func (sm *StoreManager) APIToken() *APITokenStore

APIToken returns the APITokenStore (thread-safe). Returns nil if the store is not initialized or after Close() has been called.

func (*StoreManager) BaseDir

func (sm *StoreManager) BaseDir() string

BaseDir returns the base directory for this StoreManager.

func (*StoreManager) Close

func (sm *StoreManager) Close() error

Close closes all database connections and cleans up resources. After Close() is called, all accessor methods will return nil.

func (*StoreManager) HealthCheck

func (sm *StoreManager) HealthCheck() (*HealthStatus, error)

HealthCheck checks the health of all stores. Returns a HealthStatus with the state of each store.

func (*StoreManager) ImBotSettings

func (sm *StoreManager) ImBotSettings() *ImBotSettingsStore

ImBotSettings returns the ImBotSettingsStore (thread-safe). Returns nil if the store is not initialized or after Close() has been called.

func (*StoreManager) Model

func (sm *StoreManager) Model() *ModelStore

Model returns the ModelStore (thread-safe). Returns nil if the store is not initialized or after Close() has been called.

func (*StoreManager) ModelCapability

func (sm *StoreManager) ModelCapability() *ModelCapabilityStore

ModelCapability returns the ModelCapabilityStore (thread-safe). Returns nil if the store is not initialized or after Close() has been called.

func (*StoreManager) Provider

func (sm *StoreManager) Provider() *ProviderStore

Provider returns the ProviderStore (thread-safe). Returns nil if the store is not initialized or after Close() has been called.

func (*StoreManager) RuleState

func (sm *StoreManager) RuleState() *RuleStateStore

RuleState returns the RuleStateStore (thread-safe). Returns nil if the store is not initialized or after Close() has been called.

func (*StoreManager) Stats

func (sm *StoreManager) Stats() *StatsStore

Stats returns the StatsStore (thread-safe). Returns nil if the store is not initialized or after Close() has been called.

func (*StoreManager) ToolConfig

func (sm *StoreManager) ToolConfig() *ToolConfigStore

ToolConfig returns the ToolConfigStore (thread-safe). Returns nil if the store is not initialized or after Close() has been called.

func (*StoreManager) Usage

func (sm *StoreManager) Usage() *UsageStore

Usage returns the UsageStore (thread-safe). Returns nil if the store is not initialized or after Close() has been called.

type StoreManagerConfig

type StoreManagerConfig struct {
	BaseDir     string
	BusyTimeout int // Milliseconds, default 5000
}

StoreManagerConfig holds configuration for StoreManager initialization.

type TimeSeriesData

type TimeSeriesData struct {
	Timestamp        string  `json:"timestamp"`
	RequestCount     int64   `json:"request_count"`
	TotalTokens      int64   `json:"total_tokens"`
	InputTokens      int64   `json:"input_tokens"`
	OutputTokens     int64   `json:"output_tokens"`
	CacheInputTokens int64   `json:"cache_input_tokens"`
	SystemTokens     int64   `json:"system_tokens"`
	ErrorCount       int64   `json:"error_count"`
	AvgLatencyMs     float64 `json:"avg_latency_ms"`
}

TimeSeriesData represents a single time bucket in time series data

type ToolConfigRecord

type ToolConfigRecord struct {
	UUID         string    `gorm:"primaryKey;column:uuid"`
	ProviderUUID string    `gorm:"column:provider_uuid;not null;index:idx_provider_uuid"`
	ToolType     string    `gorm:"column:tool_type;not null;index:idx_tool_type"`
	ConfigJSON   string    `gorm:"column:config_json;type:text"`
	Disabled     bool      `gorm:"column:disabled;default:false"`
	CreatedAt    time.Time `gorm:"column:created_at"`
	UpdatedAt    time.Time `gorm:"column:updated_at"`
}

ToolConfigRecord is the GORM model for persisting provider-specific tool configurations

func (ToolConfigRecord) TableName

func (ToolConfigRecord) TableName() string

TableName specifies the table name for GORM

type ToolConfigStore

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

ToolConfigStore manages provider-specific tool configurations

func NewToolConfigStore

func NewToolConfigStore(baseDir string) (*ToolConfigStore, error)

NewToolConfigStore creates or loads a tool config store using SQLite database. It uses the same database file as the provider store.

func (*ToolConfigStore) Close

func (tcs *ToolConfigStore) Close() error

Close closes the database connection

func (*ToolConfigStore) Delete

func (tcs *ToolConfigStore) Delete(uuid string) error

Delete removes a tool config by UUID

func (*ToolConfigStore) DeleteByProvider

func (tcs *ToolConfigStore) DeleteByProvider(providerUUID string) error

DeleteByProvider removes all tool configs for a provider

func (*ToolConfigStore) GetByProvider

func (tcs *ToolConfigStore) GetByProvider(providerUUID string) ([]*ToolConfigRecord, error)

GetByProvider returns all tool configs for a provider

func (*ToolConfigStore) GetByProviderAndType

func (tcs *ToolConfigStore) GetByProviderAndType(providerUUID string, toolType string) (*ToolConfigRecord, error)

GetByProviderAndType returns a tool config by provider UUID and tool type

func (*ToolConfigStore) GetDB

func (tcs *ToolConfigStore) GetDB() *gorm.DB

GetDB returns the underlying GORM DB instance (for testing/advanced usage)

func (*ToolConfigStore) GetToolConfig

func (tcs *ToolConfigStore) GetToolConfig(providerUUID, toolType string, target interface{}) (disabled, found bool, err error)

GetToolConfig returns the config for a specific provider and tool type (generic) target is a pointer to the config struct to unmarshal into Returns (disabled, found, error) - disabled: true if the tool is explicitly disabled for this provider - found: true if a config record exists for this provider/tool type - error: any unmarshaling error

func (*ToolConfigStore) Save

func (tcs *ToolConfigStore) Save(config *ToolConfigRecord) error

Save saves a tool config (create or update)

func (*ToolConfigStore) SetToolConfig

func (tcs *ToolConfigStore) SetToolConfig(providerUUID, toolType string, config interface{}, disabled bool) (string, error)

SetToolConfig sets the config for a specific provider and tool type (generic) config is any struct that can be marshaled to JSON Returns the UUID of the created/updated record

type UsageDailyRecord

type UsageDailyRecord struct {
	ID           uint      `gorm:"primaryKey;autoIncrement;column:id"`
	Date         time.Time `gorm:"column:date;index:idx_date;index:idx_date_provider_model;not null"`
	ProviderUUID string    `gorm:"column:provider_uuid;index:idx_date_provider_model;not null"`
	ProviderName string    `gorm:"column:provider_name;not null"`
	Model        string    `gorm:"column:model;index:idx_date_provider_model;not null"`
	RequestCount int64     `gorm:"column:request_count;not null"`
	TotalTokens  int64     `gorm:"column:total_tokens;not null"`
	InputTokens  int64     `gorm:"column:input_tokens;not null"`
	OutputTokens int64     `gorm:"column:output_tokens;not null"`
	// Cache tokens
	CacheInputTokens int64 `gorm:"column:cache_input_tokens;default:0"`
	// System tokens
	SystemTokens int64 `gorm:"column:system_tokens;default:0"`
	ErrorCount   int64 `gorm:"column:error_count;default:0"`
}

UsageDailyRecord is the GORM model for daily aggregated usage statistics

func (UsageDailyRecord) TableName

func (UsageDailyRecord) TableName() string

TableName specifies the table name for GORM

type UsageMonthlyRecord

type UsageMonthlyRecord struct {
	ID           uint   `gorm:"primaryKey;autoIncrement;column:id"`
	Year         int    `gorm:"column:year;not null"`
	Month        int    `gorm:"column:month;not null"`
	ProviderUUID string `gorm:"column:provider_uuid;not null"`
	ProviderName string `gorm:"column:provider_name;not null"`
	Model        string `gorm:"column:model;not null"`
	RequestCount int64  `gorm:"column:request_count;not null"`
	TotalTokens  int64  `gorm:"column:total_tokens;not null"`
	InputTokens  int64  `gorm:"column:input_tokens;not null"`
	OutputTokens int64  `gorm:"column:output_tokens;not null"`
	// Cache tokens
	CacheInputTokens int64 `gorm:"column:cache_input_tokens;default:0"`
	// System tokens
	SystemTokens int64 `gorm:"column:system_tokens;default:0"`
	ErrorCount   int64 `gorm:"column:error_count;default:0"`
}

UsageMonthlyRecord is the GORM model for monthly aggregated usage statistics

func (UsageMonthlyRecord) TableName

func (UsageMonthlyRecord) TableName() string

TableName specifies the table name for GORM

type UsageRecord

type UsageRecord struct {
	ID           uint      `gorm:"primaryKey;autoIncrement;column:id"`
	ProviderUUID string    `gorm:"column:provider_uuid;index:idx_provider_model;not null"`
	ProviderName string    `gorm:"column:provider_name;not null"`
	Model        string    `gorm:"column:model;index:idx_provider_model;not null"`
	Scenario     string    `gorm:"column:scenario;index:idx_scenario;not null"`
	RuleUUID     string    `gorm:"column:rule_uuid;index:idx_rule"`
	UserID       string    `gorm:"column:user_id;index:idx_user;not null;default:''"`
	RequestModel string    `gorm:"column:request_model"`
	Timestamp    time.Time `gorm:"column:timestamp;index:idx_timestamp;index:idx_timestamp_scenario;not null"`
	InputTokens  int       `gorm:"column:input_tokens;not null"`
	OutputTokens int       `gorm:"column:output_tokens;not null"`
	TotalTokens  int       `gorm:"column:total_tokens;index;not null"`
	// Cache tokens (combined cache creation and read)
	CacheInputTokens int `gorm:"column:cache_input_tokens;default:0"`
	// System tokens (framework overhead, templates, etc.)
	SystemTokens int    `gorm:"column:system_tokens;default:0"`
	Status       string `gorm:"column:status;index;not null"` // success, error, partial
	ErrorCode    string `gorm:"column:error_code"`
	LatencyMs    int    `gorm:"column:latency_ms"`
	TTFTMs       int    `gorm:"column:ttft_ms;default:0"`
	Streamed     bool   `gorm:"column:streamed;type:integer"`
}

UsageRecord is the GORM model for persisting individual usage records

func (UsageRecord) TableName

func (UsageRecord) TableName() string

TableName specifies the table name for GORM

type UsageStatsQuery

type UsageStatsQuery struct {
	GroupBy   string // model, provider, scenario, rule, user, daily, hourly
	StartTime time.Time
	EndTime   time.Time
	Provider  string
	Model     string
	Scenario  string
	RuleUUID  string
	UserID    string
	Status    string
	Limit     int
	SortBy    string // total_tokens, request_count, avg_latency
	SortOrder string // asc, desc
}

GetAggregatedStats returns aggregated usage statistics based on query parameters

type UsageStore

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

UsageStore persists usage records in SQLite using GORM.

func NewUsageStore

func NewUsageStore(baseDir string) (*UsageStore, error)

NewUsageStore creates or loads a usage store using SQLite database.

func (*UsageStore) AggregateToDaily

func (us *UsageStore) AggregateToDaily(date time.Time) (int64, error)

AggregateToDaily aggregates records to daily summaries

func (*UsageStore) DeleteOlderThan

func (us *UsageStore) DeleteOlderThan(cutoffDate time.Time) (int64, error)

DeleteOlderThan deletes records older than the specified date

func (*UsageStore) GetAggregatedStats

func (us *UsageStore) GetAggregatedStats(query UsageStatsQuery) ([]AggregatedStat, error)

GetAggregatedStats returns aggregated statistics

func (*UsageStore) GetRecords

func (us *UsageStore) GetRecords(startTime, endTime time.Time, filters map[string]string, limit, offset int) ([]UsageRecord, int64, error)

GetRecords returns individual usage records (for debugging/audit)

func (*UsageStore) GetRecordsAfterID

func (us *UsageStore) GetRecordsAfterID(lastID uint, startTime time.Time, limit int) ([]UsageRecord, error)

GetRecordsAfterID returns usage records with id greater than lastID. On initial sync, startTime can be used to cap the historical backfill window.

func (*UsageStore) GetTimeSeries

func (us *UsageStore) GetTimeSeries(interval string, startTime, endTime time.Time, filters map[string]string) ([]TimeSeriesData, error)

GetTimeSeries returns time-series data for usage

func (*UsageStore) RecordUsage

func (us *UsageStore) RecordUsage(record *UsageRecord) error

RecordUsage records a single usage event

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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