database

package
v0.1.3-stable Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2026 License: MIT Imports: 22 Imported by: 0

README

Database Package

Purpose & Responsibilities

The database package provides data persistence for the LLM Proxy. It handles:

  • Database connection management and configuration
  • Token and project CRUD operations
  • Audit event storage and retrieval
  • Database migrations using goose
  • Support for SQLite (default), PostgreSQL, and MySQL
  • Connection pooling and transaction management

Architecture

graph TB
    subgraph Database["Database Package"]
        DB[DB Struct]
        F[Factory]
        M[Migrations]
    end
    
    subgraph Entities
        P[Project]
        T[Token]
        A[AuditEvent]
    end
    
    subgraph Drivers
        SQLite[(SQLite)]
        PG[(PostgreSQL)]
        MySQL[(MySQL)]
    end
    
    F --> DB
    DB --> P
    DB --> T
    DB --> A
    DB --> SQLite
    DB --> PG
    DB --> MySQL
    M --> DB

Data Model

erDiagram
    PROJECT ||--o{ TOKEN : has
    PROJECT {
        string id PK
        string name
        string openai_api_key
        bool is_active
        timestamp deactivated_at
        timestamp created_at
        timestamp updated_at
    }
    TOKEN {
        string token PK
        string project_id FK
        timestamp expires_at
        bool is_active
        timestamp deactivated_at
        int request_count
        int max_requests
        timestamp created_at
        timestamp last_used_at
        int cache_hit_count
    }
    AUDIT_EVENT {
        string id PK
        timestamp timestamp
        string action
        string actor
        string project_id FK
        string outcome
        string metadata
    }

Key Types & Interfaces

Type Description
DB Main database connection wrapper
Config SQLite-specific configuration
FullConfig Multi-driver configuration (SQLite + PostgreSQL + MySQL)
Project Project entity model
Token Token entity model
AuditEvent Audit log entry model
DriverType Database driver enum (SQLite, Postgres, MySQL)
Constructor Functions
Function Description
New(config) Creates SQLite database connection
NewFromFullConfig(config) Creates database with driver selection
ConfigFromEnv() Loads configuration from environment
Operations

The DB struct provides CRUD operations for all entities:

Category Methods
Connection Close(), HealthCheck(), Transaction()
Projects CreateProject(), GetProjectByID(), UpdateProject(), DeleteProject(), ListProjects()
Tokens CreateToken(), GetTokenByID(), UpdateToken(), DeleteToken(), ListTokens(), IncrementTokenUsage()
Audit CreateAuditEvent(), GetAuditEventByID(), ListAuditEvents()

Configuration

SQLite Configuration
Field Description Default
Path Database file path data/llm-proxy.db
MaxOpenConns Max open connections 10
MaxIdleConns Max idle connections 5
ConnMaxLifetime Connection max lifetime 1 hour
Environment Variables
Variable Description Default
DB_DRIVER Database driver (sqlite, postgres, mysql) sqlite
DATABASE_PATH SQLite database path data/llm-proxy.db
DATABASE_URL PostgreSQL or MySQL connection URL -
DATABASE_POOL_SIZE Max open connections 10
DATABASE_MAX_IDLE_CONNS Max idle connections 5
DATABASE_CONN_MAX_LIFETIME Connection lifetime 1h
Database Comparison
Feature SQLite PostgreSQL MySQL
Setup Zero configuration Requires server Requires server
Concurrency Single writer Multiple writers Multiple writers
Use case Development, single instance Production, multi-instance Production, multi-instance
Connection string File path URL with credentials DSN with tcp()
Build tag None -tags postgres -tags mysql

Migration Workflow

graph LR
    subgraph Migrations
        S[Schema Files]
        R[Runner]
    end
    
    subgraph Process
        U[Up]
        D[Down]
        ST[Status]
    end
    
    S --> R
    R --> U
    R --> D
    R --> ST

Migrations are managed using goose and stored in migrations/sql/:

Migration Description
00001_initial_schema.sql Creates projects, tokens, and audit_events tables
00002_add_deactivation_columns.sql Adds deactivation tracking
00003_add_cache_hit_count.sql Adds cache hit tracking

Migrations run automatically on New(). See internal/database/migrations/README.md for manual commands.

Testing Guidance

  • Use in-memory SQLite (Config{Path: ":memory:"}) for unit tests
  • Use MockProjectStore and MockTokenStore for isolated testing
  • See *_test.go files for comprehensive test patterns
  • Set MaxOpenConns = 1 for in-memory database tests

Troubleshooting

Common Errors
Error Cause Solution
failed to create database directory Parent directory doesn't exist Create directory or use absolute path
failed to open database Invalid path or permissions Check file permissions
failed to run migrations Migration files not found Verify migrations directory path
database is locked Concurrent writes (SQLite) Use PostgreSQL for concurrent access
ErrProjectNotFound Project doesn't exist Check project ID
ErrTokenNotFound Token doesn't exist Check token ID
Connection Issues
Symptom Cause Solution
Connection timeouts Pool exhaustion Increase MaxOpenConns
Slow queries Missing indexes Check migration indexes
Memory growth Connection leaks Ensure Close() is called
SQLite-Specific Issues
Symptom Cause Solution
"database is locked" Concurrent writes Use WAL mode (enabled by default)
Slow writes Missing WAL Check connection string includes ?_journal=WAL
Test failures Shared in-memory DB Use MaxOpenConns = 1 for :memory:
Package Relationship
token Uses TokenStore interface from database
proxy Uses ProjectStore interface from database
server Initializes database for API handlers
audit Stores audit events in database

Files

File Description
database.go Core DB struct, connection, and migrations
factory.go Multi-driver database factory
factory_postgres.go PostgreSQL-specific factory
factory_mysql.go MySQL-specific factory
models.go Data models (Project, Token, AuditEvent)
project.go Project CRUD operations
token.go Token CRUD operations
audit.go Audit event operations
utils.go Helper functions and query utilities
mock_project.go Mock project store for testing
mock_token.go Mock token store for testing
migrations/ Database migration files and runner

Documentation

Overview

Package database provides SQLite database operations for the LLM Proxy.

Package database provides database operations for the LLM Proxy.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrProjectNotFound is returned when a project is not found.
	ErrProjectNotFound = errors.New("project not found")
	// ErrProjectExists is returned when a project already exists.
	ErrProjectExists = errors.New("project already exists")
)
View Source
var (
	// ErrTokenNotFound is returned when a token is not found.
	ErrTokenNotFound = errors.New("token not found")
	// ErrTokenExists is returned when a token already exists.
	ErrTokenExists = errors.New("token already exists")
)

Functions

func DBInitForTests

func DBInitForTests(d *DB) error

DBInitForTests is a helper to ensure schema exists in tests. No-op if db is nil.

func ExportTokenData

func ExportTokenData(t Token) token.TokenData

func MigrationsPathForDriver

func MigrationsPathForDriver(driver DriverType) (string, error)

MigrationsPathForDriver returns the migrations directory for the given driver type. Note: Only PostgreSQL and MySQL use migrations. SQLite uses schema.sql directly. This ensures CLI and server code share the same dialect-aware lookup logic.

func TestMockTokenStore_EdgeCases

func TestMockTokenStore_EdgeCases(t *testing.T)

func ToProxyProject

func ToProxyProject(dbProject Project) proxy.Project

ToProxyProject converts a database.Project to a proxy.Project

Types

type AuditEvent

type AuditEvent struct {
	ID            string    `json:"id"`
	Timestamp     time.Time `json:"timestamp"`
	Action        string    `json:"action"`
	Actor         string    `json:"actor"`
	ProjectID     *string   `json:"project_id,omitempty"`
	RequestID     *string   `json:"request_id,omitempty"`
	CorrelationID *string   `json:"correlation_id,omitempty"`
	ClientIP      *string   `json:"client_ip,omitempty"`
	Method        *string   `json:"method,omitempty"`
	Path          *string   `json:"path,omitempty"`
	UserAgent     *string   `json:"user_agent,omitempty"`
	Outcome       string    `json:"outcome"`
	Reason        *string   `json:"reason,omitempty"`
	TokenID       *string   `json:"token_id,omitempty"`
	Metadata      *string   `json:"metadata,omitempty"` // JSON string
}

AuditEvent represents an audit log entry in the database.

type AuditEventFilters

type AuditEventFilters struct {
	Action        string
	ClientIP      string
	ProjectID     string
	StartTime     *string // RFC3339 format
	EndTime       *string // RFC3339 format
	Outcome       string
	Actor         string
	RequestID     string
	CorrelationID string
	Method        string
	Path          string
	Search        string // Full-text search over reason/metadata
	Limit         int
	Offset        int
}

AuditEventFilters provides filtering options for audit event queries

type AuditStore

type AuditStore interface {
	StoreAuditEvent(ctx context.Context, event *audit.Event) error
	ListAuditEvents(ctx context.Context, filters AuditEventFilters) ([]AuditEvent, error)
	CountAuditEvents(ctx context.Context, filters AuditEventFilters) (int, error)
	GetAuditEventByID(ctx context.Context, id string) (*AuditEvent, error)
}

AuditStore defines the interface for persisting audit events to database

type Config

type Config struct {
	// Path is the path to the SQLite database file.
	Path string
	// MaxOpenConns is the maximum number of open connections.
	MaxOpenConns int
	// MaxIdleConns is the maximum number of idle connections.
	MaxIdleConns int
	// ConnMaxLifetime is the maximum amount of time a connection may be reused.
	ConnMaxLifetime time.Duration
}

Config contains the database configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a default database configuration.

type DB

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

DB represents the database connection.

func New

func New(config Config) (*DB, error)

New creates a new database connection.

func NewFromConfig

func NewFromConfig(config FullConfig) (*DB, error)

NewFromConfig creates a new database connection based on the configuration.

func (*DB) BackupDatabase

func (d *DB) BackupDatabase(ctx context.Context, backupPath string) error

BackupDatabase creates a backup of the database. Note: This function is SQLite-specific. For PostgreSQL, use pg_dump. For MySQL, use mysqldump.

func (*DB) CleanExpiredTokens

func (d *DB) CleanExpiredTokens(ctx context.Context) (int64, error)

CleanExpiredTokens deletes expired tokens from the database.

func (*DB) Close

func (d *DB) Close() error

Close closes the database connection.

func (*DB) CountAuditEvents

func (d *DB) CountAuditEvents(ctx context.Context, filters AuditEventFilters) (int, error)

CountAuditEvents returns the total count of audit events matching the given filters

func (*DB) CreateProject

func (d *DB) CreateProject(ctx context.Context, p proxy.Project) error

func (*DB) CreateToken

func (d *DB) CreateToken(ctx context.Context, token Token) error

CreateToken creates a new token in the database. If token.ID is empty, a UUID will be generated automatically.

func (*DB) DB

func (d *DB) DB() *sql.DB

DB returns the underlying sql.DB instance.

func (*DB) DBCreateProject

func (d *DB) DBCreateProject(ctx context.Context, project Project) error

func (*DB) DBDeleteProject

func (d *DB) DBDeleteProject(ctx context.Context, projectID string) error

func (*DB) DBGetProjectByID

func (d *DB) DBGetProjectByID(ctx context.Context, projectID string) (Project, error)

func (*DB) DBListProjects

func (d *DB) DBListProjects(ctx context.Context) ([]Project, error)

Rename CRUD methods for DB store

func (*DB) DBUpdateProject

func (d *DB) DBUpdateProject(ctx context.Context, project Project) error

func (*DB) DeleteProject

func (d *DB) DeleteProject(ctx context.Context, id string) error

func (*DB) DeleteToken

func (d *DB) DeleteToken(ctx context.Context, tokenID string) error

DeleteToken deletes a token from the database.

func (*DB) Driver

func (d *DB) Driver() DriverType

Driver returns the database driver type.

func (*DB) ExecContextRebound

func (d *DB) ExecContextRebound(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

ExecContextRebound executes a query with automatic placeholder rebinding.

func (*DB) GetAPIKeyForProject

func (d *DB) GetAPIKeyForProject(ctx context.Context, projectID string) (string, error)

GetAPIKeyForProject retrieves the API key for a project by ID

func (*DB) GetAuditEventByID

func (d *DB) GetAuditEventByID(ctx context.Context, id string) (*AuditEvent, error)

GetAuditEventByID retrieves a specific audit event by its ID

func (*DB) GetProjectActive

func (d *DB) GetProjectActive(ctx context.Context, projectID string) (bool, error)

GetProjectActive retrieves the active status for a project by ID

func (*DB) GetProjectByID

func (d *DB) GetProjectByID(ctx context.Context, id string) (proxy.Project, error)

func (*DB) GetProjectByName

func (d *DB) GetProjectByName(ctx context.Context, name string) (Project, error)

GetProjectByName retrieves a project by name.

func (*DB) GetStats

func (d *DB) GetStats(ctx context.Context) (map[string]interface{}, error)

GetStats returns database statistics.

func (*DB) GetTokenByID

func (d *DB) GetTokenByID(ctx context.Context, id string) (Token, error)

GetTokenByID retrieves a token by its UUID.

func (*DB) GetTokenByToken

func (d *DB) GetTokenByToken(ctx context.Context, tokenString string) (Token, error)

GetTokenByToken retrieves a token by its token string (for authentication).

func (*DB) GetTokensByProjectID

func (d *DB) GetTokensByProjectID(ctx context.Context, projectID string) ([]Token, error)

GetTokensByProjectID retrieves all tokens for a project.

func (*DB) HealthCheck

func (d *DB) HealthCheck(ctx context.Context) error

HealthCheck performs a health check on the database connection. It verifies that the database is reachable and responsive.

func (*DB) IncrementCacheHitCount

func (d *DB) IncrementCacheHitCount(ctx context.Context, tokenID string, delta int) error

IncrementCacheHitCount increments the cache_hit_count for a single token.

func (*DB) IncrementCacheHitCountBatch

func (d *DB) IncrementCacheHitCountBatch(ctx context.Context, deltas map[string]int) error

IncrementCacheHitCountBatch increments cache_hit_count for multiple tokens in batch. The deltas map has token IDs as keys and increment values as values.

func (*DB) IncrementTokenUsage

func (d *DB) IncrementTokenUsage(ctx context.Context, tokenID string) error

IncrementTokenUsage increments the request count and updates the last_used_at timestamp.

func (*DB) IncrementTokenUsageBatch

func (d *DB) IncrementTokenUsageBatch(ctx context.Context, deltas map[string]int, lastUsedAt time.Time) error

IncrementTokenUsageBatch increments request_count for multiple tokens and updates last_used_at. The token IDs are token strings (sk-...).

func (*DB) IsTokenValid

func (d *DB) IsTokenValid(ctx context.Context, tokenID string) (bool, error)

IsTokenValid checks if a token is valid (exists, is active, not expired, and not rate limited).

func (*DB) ListAuditEvents

func (d *DB) ListAuditEvents(ctx context.Context, filters AuditEventFilters) ([]AuditEvent, error)

ListAuditEvents retrieves audit events from the database with optional filtering

func (*DB) ListProjects

func (d *DB) ListProjects(ctx context.Context) ([]proxy.Project, error)

--- proxy.ProjectStore interface adapters ---

func (*DB) ListTokens

func (d *DB) ListTokens(ctx context.Context) ([]Token, error)

ListTokens retrieves all tokens from the database.

func (*DB) MaintainDatabase

func (d *DB) MaintainDatabase(ctx context.Context) error

MaintainDatabase performs regular maintenance on the database. WARNING: VACUUM and ANALYZE can be expensive operations. In production, schedule this function to run periodically (e.g., daily) rather than on every call. The caller is responsible for scheduling.

func (*DB) Placeholder

func (d *DB) Placeholder(n int) string

Placeholder returns the appropriate placeholder for the driver. For SQLite and MySQL: ?, for PostgreSQL: $1, $2, etc.

func (*DB) PlaceholderList

func (d *DB) PlaceholderList(n int) string

PlaceholderList returns a comma-separated list of placeholders. For n=3: SQLite/MySQL return "?, ?, ?", PostgreSQL returns "$1, $2, $3".

func (*DB) Placeholders

func (d *DB) Placeholders(n int) []string

Placeholders returns a slice of placeholders for the driver. For n=3: SQLite/MySQL return ["?", "?", "?"], PostgreSQL returns ["$1", "$2", "$3"].

func (*DB) QueryContextRebound

func (d *DB) QueryContextRebound(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

QueryContextRebound queries multiple rows with automatic placeholder rebinding.

func (*DB) QueryRowContextRebound

func (d *DB) QueryRowContextRebound(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRowContextRebound queries a single row with automatic placeholder rebinding.

func (*DB) RebindQuery

func (d *DB) RebindQuery(query string) string

RebindQuery converts a query from ? placeholders to the appropriate placeholder style for the database driver.

IMPORTANT: This function performs a simple character replacement and does NOT handle ? characters inside SQL string literals (e.g., "WHERE name = 'what?'"). Since this codebase exclusively uses parameterized queries with ? as placeholders, this limitation does not affect normal usage. If you need to use literal ? in string values, use parameterized queries: "WHERE name = ?" with the value passed as an argument.

func (*DB) StoreAuditEvent

func (d *DB) StoreAuditEvent(ctx context.Context, event *audit.Event) error

StoreAuditEvent persists an audit event to the database

func (*DB) Transaction

func (d *DB) Transaction(ctx context.Context, fn func(*sql.Tx) error) error

Transaction executes the given function within a transaction.

func (*DB) UpdateProject

func (d *DB) UpdateProject(ctx context.Context, p proxy.Project) error

func (*DB) UpdateToken

func (d *DB) UpdateToken(ctx context.Context, token Token) error

UpdateToken updates a token in the database. It looks up the token by ID (UUID). If ID is empty, it falls back to looking up by token string for backward compatibility.

type DBTokenStoreAdapter

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

--- token.TokenStore interface adapter for *DB ---

func NewDBTokenStoreAdapter

func NewDBTokenStoreAdapter(db *DB) *DBTokenStoreAdapter

func (*DBTokenStoreAdapter) CreateToken

func (a *DBTokenStoreAdapter) CreateToken(ctx context.Context, td token.TokenData) error

func (*DBTokenStoreAdapter) DeleteToken

func (a *DBTokenStoreAdapter) DeleteToken(ctx context.Context, tokenID string) error

DeleteToken completely removes a token from storage

func (*DBTokenStoreAdapter) GetTokenByID

func (a *DBTokenStoreAdapter) GetTokenByID(ctx context.Context, id string) (token.TokenData, error)

func (*DBTokenStoreAdapter) GetTokenByToken

func (a *DBTokenStoreAdapter) GetTokenByToken(ctx context.Context, tokenString string) (token.TokenData, error)

func (*DBTokenStoreAdapter) GetTokensByProjectID

func (a *DBTokenStoreAdapter) GetTokensByProjectID(ctx context.Context, projectID string) ([]token.TokenData, error)

func (*DBTokenStoreAdapter) IncrementTokenUsage

func (a *DBTokenStoreAdapter) IncrementTokenUsage(ctx context.Context, tokenID string) error

func (*DBTokenStoreAdapter) ListTokens

func (a *DBTokenStoreAdapter) ListTokens(ctx context.Context) ([]token.TokenData, error)

func (*DBTokenStoreAdapter) RevokeBatchTokens

func (a *DBTokenStoreAdapter) RevokeBatchTokens(ctx context.Context, tokenIDs []string) (int, error)

RevokeBatchTokens revokes multiple tokens at once

func (*DBTokenStoreAdapter) RevokeExpiredTokens

func (a *DBTokenStoreAdapter) RevokeExpiredTokens(ctx context.Context) (int, error)

RevokeExpiredTokens revokes all tokens that have expired

func (*DBTokenStoreAdapter) RevokeProjectTokens

func (a *DBTokenStoreAdapter) RevokeProjectTokens(ctx context.Context, projectID string) (int, error)

RevokeProjectTokens revokes all tokens for a project

func (*DBTokenStoreAdapter) RevokeToken

func (a *DBTokenStoreAdapter) RevokeToken(ctx context.Context, tokenID string) error

RevokeToken disables a token by setting is_active to false and deactivated_at to current time

func (*DBTokenStoreAdapter) UpdateToken

func (a *DBTokenStoreAdapter) UpdateToken(ctx context.Context, td token.TokenData) error

type DriverType

type DriverType string

DriverType represents the database driver type.

const (
	// DriverSQLite represents the SQLite database driver.
	DriverSQLite DriverType = "sqlite"
	// DriverPostgres represents the PostgreSQL database driver.
	DriverPostgres DriverType = "postgres"
	// DriverMySQL represents the MySQL database driver.
	DriverMySQL DriverType = "mysql"
)

type FullConfig

type FullConfig struct {
	// Driver specifies which database driver to use (sqlite, postgres, mysql).
	Driver DriverType
	// SQLite-specific configuration
	// Path is the path to the SQLite database file.
	Path string
	// PostgreSQL and MySQL-specific configuration
	// DatabaseURL is the PostgreSQL or MySQL connection string.
	DatabaseURL string
	// Connection pool settings (used by all drivers)
	// MaxOpenConns is the maximum number of open connections.
	MaxOpenConns int
	// MaxIdleConns is the maximum number of idle connections.
	MaxIdleConns int
	// ConnMaxLifetime is the maximum amount of time a connection may be reused.
	ConnMaxLifetime time.Duration
}

FullConfig contains the complete database configuration for all drivers.

func ConfigFromEnv

func ConfigFromEnv() FullConfig

ConfigFromEnv creates a FullConfig from environment variables. Invalid configuration values are logged as warnings and defaults are used.

func DefaultFullConfig

func DefaultFullConfig() FullConfig

DefaultFullConfig returns a default database configuration.

type MockProjectStore

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

MockProjectStore is an in-memory implementation of ProjectStore for testing and development

func NewMockProjectStore

func NewMockProjectStore() *MockProjectStore

NewMockProjectStore creates a new MockProjectStore

func (*MockProjectStore) CreateMockProject

func (m *MockProjectStore) CreateMockProject(projectID, name, apiKey string) (Project, error)

CreateMockProject creates a new project in the mock store with the given parameters

func (*MockProjectStore) CreateProject

func (m *MockProjectStore) CreateProject(ctx context.Context, p proxy.Project) error

func (*MockProjectStore) DBCreateProject

func (m *MockProjectStore) DBCreateProject(ctx context.Context, project Project) error

CreateProject creates a new project in the store

func (*MockProjectStore) DBDeleteProject

func (m *MockProjectStore) DBDeleteProject(ctx context.Context, projectID string) error

DeleteProject deletes a project from the store

func (*MockProjectStore) DBGetProjectByID

func (m *MockProjectStore) DBGetProjectByID(ctx context.Context, projectID string) (Project, error)

GetProjectByID retrieves a project by ID

func (*MockProjectStore) DBListProjects

func (m *MockProjectStore) DBListProjects(ctx context.Context) ([]Project, error)

ListProjects retrieves all projects from the store

func (*MockProjectStore) DBUpdateProject

func (m *MockProjectStore) DBUpdateProject(ctx context.Context, project Project) error

UpdateProject updates a project in the store

func (*MockProjectStore) DeleteProject

func (m *MockProjectStore) DeleteProject(ctx context.Context, id string) error

func (*MockProjectStore) GetAPIKeyForProject

func (m *MockProjectStore) GetAPIKeyForProject(ctx context.Context, projectID string) (string, error)

GetAPIKeyForProject retrieves the API key for a project

func (*MockProjectStore) GetProjectActive

func (m *MockProjectStore) GetProjectActive(ctx context.Context, projectID string) (bool, error)

GetProjectActive retrieves the active status for a project by ID

func (*MockProjectStore) GetProjectByID

func (m *MockProjectStore) GetProjectByID(ctx context.Context, id string) (proxy.Project, error)

func (*MockProjectStore) ListProjects

func (m *MockProjectStore) ListProjects(ctx context.Context) ([]proxy.Project, error)

--- proxy.ProjectStore interface adapters ---

func (*MockProjectStore) UpdateProject

func (m *MockProjectStore) UpdateProject(ctx context.Context, p proxy.Project) error

type MockTokenStore

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

MockTokenStore is an in-memory implementation of TokenStore for testing and development

func NewMockTokenStore

func NewMockTokenStore() *MockTokenStore

NewMockTokenStore creates a new MockTokenStore

func (*MockTokenStore) CleanExpiredTokens

func (m *MockTokenStore) CleanExpiredTokens(ctx context.Context) (int64, error)

CleanExpiredTokens deletes expired tokens from the store

func (*MockTokenStore) CreateMockToken

func (m *MockTokenStore) CreateMockToken(tokenID, projectID string, expiresIn time.Duration, isActive bool, maxRequests *int) (Token, error)

CreateMockToken creates a new token in the mock store with the given parameters

func (*MockTokenStore) CreateToken

func (m *MockTokenStore) CreateToken(ctx context.Context, token Token) error

CreateToken creates a new token in the store

func (*MockTokenStore) DeleteToken

func (m *MockTokenStore) DeleteToken(ctx context.Context, tokenID string) error

DeleteToken deletes a token from the store

func (*MockTokenStore) GetTokenByID

func (m *MockTokenStore) GetTokenByID(ctx context.Context, tokenID string) (Token, error)

GetTokenByID retrieves a token by ID

func (*MockTokenStore) GetTokensByProjectID

func (m *MockTokenStore) GetTokensByProjectID(ctx context.Context, projectID string) ([]Token, error)

GetTokensByProjectID retrieves all tokens for a project

func (*MockTokenStore) IncrementTokenUsage

func (m *MockTokenStore) IncrementTokenUsage(ctx context.Context, tokenID string) error

IncrementTokenUsage increments the request count and updates the last_used_at timestamp

func (*MockTokenStore) ListTokens

func (m *MockTokenStore) ListTokens(ctx context.Context) ([]Token, error)

ListTokens retrieves all tokens from the store

func (*MockTokenStore) UpdateToken

func (m *MockTokenStore) UpdateToken(ctx context.Context, token Token) error

UpdateToken updates a token in the store

type Project

type Project struct {
	ID            string     `json:"id"`
	Name          string     `json:"name"`
	APIKey        string     `json:"-"` // Sensitive data, not included in JSON. Encrypted when ENCRYPTION_KEY is set.
	IsActive      bool       `json:"is_active"`
	DeactivatedAt *time.Time `json:"deactivated_at,omitempty"`
	CreatedAt     time.Time  `json:"created_at"`
	UpdatedAt     time.Time  `json:"updated_at"`
}

Project represents a project in the database.

func ToDBProject

func ToDBProject(proxyProject proxy.Project) Project

ToDBProject converts a proxy.Project to a database.Project

func (*Project) IsDeactivated

func (p *Project) IsDeactivated() bool

IsDeactivated returns true if the project has been explicitly deactivated.

type Token

type Token struct {
	ID            string     `json:"id"`
	Token         string     `json:"token"`
	ProjectID     string     `json:"project_id"`
	ExpiresAt     *time.Time `json:"expires_at,omitempty"`
	IsActive      bool       `json:"is_active"`
	DeactivatedAt *time.Time `json:"deactivated_at,omitempty"`
	RequestCount  int        `json:"request_count"`
	MaxRequests   *int       `json:"max_requests,omitempty"`
	CreatedAt     time.Time  `json:"created_at"`
	LastUsedAt    *time.Time `json:"last_used_at,omitempty"`
	CacheHitCount int        `json:"cache_hit_count"`
}

Token represents a token in the database.

func ImportTokenData

func ImportTokenData(td token.TokenData) Token

ImportTokenData and ExportTokenData helpers

func (*Token) IsDeactivated

func (t *Token) IsDeactivated() bool

IsDeactivated returns true if the token has been explicitly deactivated.

func (*Token) IsExpired

func (t *Token) IsExpired() bool

IsExpired returns true if the token has expired.

func (*Token) IsRateLimited

func (t *Token) IsRateLimited() bool

IsRateLimited returns true if the token has reached its maximum number of requests.

func (*Token) IsValid

func (t *Token) IsValid() bool

IsValid returns true if the token is active, not expired, and not rate limited.

type TokenStoreAdapter

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

TokenStoreAdapter adapts the database.DB to the token.TokenStore interface

func NewTokenStoreAdapter

func NewTokenStoreAdapter(store *MockTokenStore) *TokenStoreAdapter

NewTokenStoreAdapter creates a new TokenStoreAdapter

func (*TokenStoreAdapter) CreateToken

func (a *TokenStoreAdapter) CreateToken(ctx context.Context, td token.TokenData) error

CreateToken creates a new token in the store

func (*TokenStoreAdapter) GetTokenByID

func (a *TokenStoreAdapter) GetTokenByID(ctx context.Context, tokenID string) (token.TokenData, error)

GetTokenByID retrieves a token by ID

func (*TokenStoreAdapter) GetTokensByProjectID

func (a *TokenStoreAdapter) GetTokensByProjectID(ctx context.Context, projectID string) ([]token.TokenData, error)

GetTokensByProjectID retrieves all tokens for a project

func (*TokenStoreAdapter) IncrementTokenUsage

func (a *TokenStoreAdapter) IncrementTokenUsage(ctx context.Context, tokenID string) error

IncrementTokenUsage increments the request count and updates the last_used_at timestamp

func (*TokenStoreAdapter) ListTokens

func (a *TokenStoreAdapter) ListTokens(ctx context.Context) ([]token.TokenData, error)

ListTokens retrieves all tokens from the store

Directories

Path Synopsis
Package migrations provides database migration functionality using goose.
Package migrations provides database migration functionality using goose.

Jump to

Keyboard shortcuts

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