db

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2026 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Overview

Package db provides a central GORM-based database layer that supports both SQLite (default, file-based) and PostgreSQL (DSN-based). All persistent tables (e.g. HITL approvals) are registered here as GORM models and auto-migrated via AutoMigrate.

SQLite is selected when Config.DBFile is set (or defaulted). PostgreSQL is selected when Config.DSN is set. If both are set, DSN takes precedence.

Usage (SQLite):

gormDB, err := db.OpenConfig(db.DefaultConfig())
db.AutoMigrate(gormDB)

Usage (PostgreSQL):

gormDB, err := db.OpenConfig(db.Config{DSN: "postgres://user:pass@host:5432/genie"})
db.AutoMigrate(gormDB)

Package db — session_store.go provides a GORM-backed implementation of the trpc-agent-go session.Service interface, modeled after the storage builder pattern in trpc-agent-go/storage (e.g. storage/mysql).

Architecture: This wraps an inmemory.SessionService to handle all the complex session logic (event filtering, summarization, state merging) while persisting data to the database on writes and loading from DB on reads. The inmemory service acts as the hot cache; the DB is the durable store.

Usage:

gormDB, _ := db.Open(db.DefaultPath())
sessionSvc := db.NewSessionStore(gormDB,
    db.WithSessionStoreInMemoryOpts(
        inmemory.WithSummarizer(summary.NewSummarizer(model, ...)),
    ),
    db.WithSessionStoreEventLimit(100),
)
runner.NewRunner("agent", agent, runner.WithSessionService(sessionSvc))

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AutoMigrate

func AutoMigrate(db *gorm.DB) error

AutoMigrate runs GORM auto-migration for all registered models. Call this after Open() to ensure all tables exist with the correct schema.

func Close

func Close(db *gorm.DB) error

Close closes the underlying database connection.

func NewRetryCheckpointSaver added in v0.1.7

func NewRetryCheckpointSaver(inner graph.CheckpointSaver, opts ...RetryOption) graph.CheckpointSaver

NewRetryCheckpointSaver wraps a CheckpointSaver with automatic retry on transient DB errors.

func Open deprecated

func Open(dbPath string) (*gorm.DB, error)

Open opens (or creates) a SQLite database at dbPath using GORM. It uses the pure-Go modernc.org/sqlite driver (already registered as "sqlite"). WAL journal mode is enabled for better concurrent read/write performance.

Deprecated: Use OpenConfig instead, which supports both SQLite and PostgreSQL.

func OpenConfig added in v0.1.7

func OpenConfig(cfg Config) (*gorm.DB, error)

OpenConfig opens a database connection based on the given Config. If DSN is set, PostgreSQL is used. Otherwise, SQLite is used with the DBFile path (defaulting to ~/.genie/genie.db).

Types

type AppState

type AppState struct {
	AppName   string    `gorm:"primaryKey;type:text" json:"app_name"`
	Key       string    `gorm:"primaryKey;type:text" json:"key"`
	Value     []byte    `json:"value"`
	UpdatedAt time.Time `gorm:"not null" json:"updated_at"`
}

AppState is the GORM model for app-level state.

func (AppState) TableName

func (AppState) TableName() string

type Approval

type Approval struct {
	ID            string     `gorm:"primaryKey;type:text" json:"id"`
	ThreadID      string     `gorm:"type:text;not null;index:idx_approvals_thread" json:"thread_id"`
	RunID         string     `gorm:"type:text;not null" json:"run_id"`
	TenantID      string     `gorm:"type:text;default:'';index:idx_approvals_tenant" json:"tenant_id,omitempty"`
	ToolName      string     `gorm:"type:text;not null" json:"tool_name"`
	Args          string     `gorm:"type:text;not null;default:''" json:"args"`
	Status        string     `gorm:"type:text;not null;default:'pending';index:idx_approvals_status" json:"status"`
	CreatedAt     time.Time  `gorm:"not null" json:"created_at"`
	ExpiresAt     *time.Time `gorm:"index:idx_approvals_expires" json:"expires_at,omitempty"`
	ResolvedAt    *time.Time `json:"resolved_at,omitempty"`
	ResolvedBy    string     `gorm:"type:text;default:''" json:"resolved_by,omitempty"`
	CreatedBy     string     `gorm:"type:text;default:''" json:"created_by,omitempty"`
	Feedback      string     `gorm:"type:text;default:''" json:"feedback,omitempty"`
	SenderContext string     `gorm:"type:text;default:''" json:"sender_context,omitempty"`
	Question      string     `gorm:"type:text;default:''" json:"question,omitempty"`
}

Approval is the GORM model for the approvals table. Each non-readonly tool call creates one Approval row before execution.

func (Approval) TableName

func (Approval) TableName() string

TableName overrides the default GORM table name.

type Clarification

type Clarification struct {
	ID            uuid.UUID     `gorm:"primaryKey;type:text" json:"id"`
	Question      string        `gorm:"type:text;not null" json:"question"`                                                 // the question shown to the user
	Context       string        `gorm:"type:text;default:''" json:"context,omitempty"`                                      // optional LLM-provided context
	Answer        string        `gorm:"type:text;default:''" json:"answer,omitempty"`                                       // the user's response (empty until answered)
	Status        ClarifyStatus `gorm:"type:text;not null;default:'pending';index:idx_clarifications_status" json:"status"` // pending → answered | expired
	SenderContext string        `gorm:"type:text;default:''" json:"sender_context,omitempty"`                               // opaque platform sender ID (e.g. "slack:U1234:C5678")
	CreatedAt     time.Time     `gorm:"not null" json:"created_at"`
	AnsweredAt    *time.Time    `json:"answered_at,omitempty"` // set when status transitions to answered or expired
}

Clarification is the GORM model for the "clarifications" table. Each invocation of the ask_clarifying_question tool creates one row. Rows are durable across server restarts, enabling [clarify.RecoverPending] to re-register waiter channels for questions still awaiting answers.

func (Clarification) TableName

func (Clarification) TableName() string

TableName overrides the default GORM table name.

type ClarifyStatus

type ClarifyStatus string

ClarifyStatus represents the lifecycle state of a Clarification row.

const (
	// ClarifyStatusPending indicates the question is waiting for a user answer.
	ClarifyStatusPending ClarifyStatus = "pending"
	// ClarifyStatusAnswered indicates the user has provided an answer.
	ClarifyStatusAnswered ClarifyStatus = "answered"
	// ClarifyStatusExpired indicates the question was not answered within the
	// allowed window and was expired during startup recovery.
	ClarifyStatusExpired ClarifyStatus = "expired"
)

type Config

type Config struct {
	// DBFile is the path to the SQLite database file.
	// Defaults to ~/.genie/genie.db when neither DBFile nor DSN is set.
	DBFile string `json:"db_file" toml:"db_file,omitempty" yaml:"db_file,omitempty"`

	// DSN is a PostgreSQL connection string (e.g. "postgres://user:pass@host:5432/dbname?sslmode=disable").
	// When set, PostgreSQL is used instead of SQLite.
	DSN string `json:"dsn,omitempty" toml:"dsn,omitempty" yaml:"dsn,omitempty"`
}

Config holds the database connection configuration. Set DSN for PostgreSQL, or DBFile for SQLite (the default). If both are set, DSN takes precedence.

func DefaultConfig

func DefaultConfig() Config

func (Config) DisplayPath added in v0.1.7

func (c Config) DisplayPath() string

DisplayPath returns a human-readable string describing the database location — either the DSN (with password masked) or the SQLite file path.

type CronHistory

type CronHistory struct {
	ID         uuid.UUID  `gorm:"primaryKey;type:text" json:"id"`
	TaskID     uuid.UUID  `gorm:"type:text;not null;index:idx_cron_history_task" json:"task_id"`
	TaskName   string     `gorm:"type:text;not null" json:"task_name"`
	StartedAt  time.Time  `gorm:"not null" json:"started_at"`
	FinishedAt *time.Time `json:"finished_at,omitempty"`
	Status     CronStatus `gorm:"type:text;not null;default:'running';index:idx_cron_history_status" json:"status"` // running, success, failed
	Error      string     `gorm:"type:text;default:''" json:"error,omitempty"`
	RunID      string     `gorm:"type:text;default:''" json:"run_id,omitempty"` // BackgroundWorker run ID
}

CronHistory is the GORM model for the cron_history table. Every cron execution is logged here for audit and health-check purposes.

func (CronHistory) TableName

func (CronHistory) TableName() string

TableName overrides the default GORM table name.

type CronStatus

type CronStatus string
const (
	CronStatusRunning CronStatus = "running"
	CronStatusSuccess CronStatus = "success"
	CronStatusFailed  CronStatus = "failed"
)

type CronTask

type CronTask struct {
	ID              uuid.UUID  `gorm:"primaryKey;type:text" json:"id"`
	Name            string     `gorm:"type:text;not null;uniqueIndex" json:"name"`
	Expression      string     `gorm:"type:text;not null" json:"expression"`
	Action          string     `gorm:"type:text;not null" json:"action"`
	Enabled         bool       `gorm:"not null;default:true" json:"enabled"`
	Source          string     `gorm:"type:text;not null;default:'config'" json:"source"` // "config" or "tool"
	LastTriggeredAt *time.Time `json:"last_triggered_at,omitempty"`                       // last successful dispatch
	NextRunAt       *time.Time `gorm:"index:idx_cron_tasks_next_run" json:"next_run_at"`  // pre-computed next due time
	CreatedAt       time.Time  `gorm:"not null" json:"created_at"`
	UpdatedAt       time.Time  `gorm:"not null" json:"updated_at"`
}

CronTask is the GORM model for the cron_tasks table. Each row represents a recurring task that the scheduler evaluates. Tasks can originate from configuration or be created dynamically via the create_recurring_task tool.

func (*CronTask) BeforeCreate

func (c *CronTask) BeforeCreate(tx *gorm.DB) (err error)

func (CronTask) String

func (c CronTask) String() string

func (CronTask) TableName

func (CronTask) TableName() string

TableName overrides the default GORM table name.

type GormCheckpointSaver

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

GormCheckpointSaver implements graph.CheckpointSaver for PostgreSQL via GORM. It mirrors the upstream SQLite saver but leverages GORM's dialect-aware query builder, removing hand-written SQL with dollar-sign placeholders.

Without this, the graph checkpoint system cannot store execution state when the underlying database is PostgreSQL (the default for guild).

func NewGormCheckpointSaver

func NewGormCheckpointSaver(db *gorm.DB) (*GormCheckpointSaver, error)

NewGormCheckpointSaver creates a new PostgreSQL checkpoint saver backed by GORM. It auto-migrates the checkpoints and checkpoint_writes tables on startup. Without this constructor, callers would have to manually create tables and wire up the GORM connection, which is error-prone.

func (*GormCheckpointSaver) Close

func (s *GormCheckpointSaver) Close() error

Close is a no-op because GORM manages the connection pool lifecycle externally. The caller that created the *gorm.DB is responsible for closing it. Without this method GormCheckpointSaver would not satisfy the graph.CheckpointSaver interface.

func (*GormCheckpointSaver) DeleteLineage

func (s *GormCheckpointSaver) DeleteLineage(ctx context.Context, lineageID string) error

DeleteLineage deletes all checkpoints and writes for the given lineage. Without this, old graph sessions would accumulate indefinitely, consuming disk and slowing queries.

func (*GormCheckpointSaver) Get

func (s *GormCheckpointSaver) Get(ctx context.Context, config map[string]any) (*graph.Checkpoint, error)

Get returns the checkpoint for the given config. It delegates to GetTuple and unwraps the checkpoint field. Without this, callers that only need the raw Checkpoint struct would have to call GetTuple and discard the wrapper themselves.

func (*GormCheckpointSaver) GetTuple

func (s *GormCheckpointSaver) GetTuple(ctx context.Context, config map[string]any) (*graph.CheckpointTuple, error)

GetTuple returns the full checkpoint tuple (checkpoint + metadata + writes) for the given config. When checkpoint_id is empty, the most recent checkpoint for the lineage/namespace is returned. Without this, the graph engine cannot resume execution from a prior state.

func (*GormCheckpointSaver) List

List returns checkpoints for the lineage/namespace, with optional filters (before cursor and limit). Each returned tuple includes writes and metadata. Without this, the graph system cannot enumerate prior execution states for replay, branching, or administrative inspection.

func (*GormCheckpointSaver) Put

Put stores the checkpoint and returns the updated config. An upsert is used so that re-saving the same checkpoint ID overwrites the previous data instead of producing a constraint violation. Without this, the graph engine cannot persist execution state.

func (*GormCheckpointSaver) PutFull

func (s *GormCheckpointSaver) PutFull(ctx context.Context, req graph.PutFullRequest) (map[string]any, error)

PutFull atomically stores a checkpoint with its pending writes in a single GORM transaction. Without this, a crash between the checkpoint insert and the writes insert could leave the store in an inconsistent state.

func (*GormCheckpointSaver) PutWrites

PutWrites stores write entries for a checkpoint. Each write is upserted individually so that retries don't produce duplicates. Without this, the graph engine cannot record intermediate channel writes needed for deterministic replay.

type Memory

type Memory struct {
	ID        uuid.UUID `gorm:"primaryKey;type:text" json:"id"`
	AppName   string    `gorm:"type:text;not null;index:idx_memories_key" json:"app_name"`
	UserID    string    `gorm:"type:text;not null;index:idx_memories_key" json:"user_id"`
	Content   string    `gorm:"type:text;not null" json:"content"`
	Topics    string    `gorm:"type:text;not null;default:'[]'" json:"topics"` // JSON encoded string array
	CreatedAt time.Time `gorm:"not null" json:"created_at"`
	UpdatedAt time.Time `gorm:"not null" json:"updated_at"`
}

Memory is the GORM model for the memories table. It stores conversation history and episodic memory.

func (Memory) TableName

func (Memory) TableName() string

TableName overrides the default GORM table name.

type MemoryStore

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

MemoryStore implements memory.Service backed by GORM.

func NewMemoryService

func NewMemoryService(db *gorm.DB) *MemoryStore

NewMemoryService creates a new GORM-backed memory service.

func (*MemoryStore) AddMemory

func (s *MemoryStore) AddMemory(ctx context.Context, userKey memory.UserKey, content string, topics []string) error

AddMemory adds or updates a memory for a user (idempotent). Uniques ID is generated from (AppName, UserID, Content) hash.

func (*MemoryStore) ClearMemories

func (s *MemoryStore) ClearMemories(ctx context.Context, userKey memory.UserKey) error

ClearMemories clears all memories for a user.

func (*MemoryStore) Close

func (s *MemoryStore) Close() error

Close is a no-op as DB lifecycle is managed externally.

func (*MemoryStore) DeleteMemory

func (s *MemoryStore) DeleteMemory(ctx context.Context, memoryKey memory.Key) error

DeleteMemory deletes a memory for a user.

func (*MemoryStore) EnqueueAutoMemoryJob

func (s *MemoryStore) EnqueueAutoMemoryJob(ctx context.Context, sess *session.Session) error

EnqueueAutoMemoryJob is a no-op for now.

func (*MemoryStore) ReadMemories

func (s *MemoryStore) ReadMemories(ctx context.Context, userKey memory.UserKey, limit int) ([]*memory.Entry, error)

ReadMemories reads memories for a user.

func (*MemoryStore) SearchMemories

func (s *MemoryStore) SearchMemories(ctx context.Context, userKey memory.UserKey, query string) ([]*memory.Entry, error)

SearchMemories searches memories for a user using basic text matching.

func (*MemoryStore) Tools

func (s *MemoryStore) Tools() []tool.Tool

Tools returns supported tools. Currently none for this adapter.

func (*MemoryStore) UpdateMemory

func (s *MemoryStore) UpdateMemory(ctx context.Context, memoryKey memory.Key, content string, topics []string) error

UpdateMemory updates an existing memory for a user.

type RetryOption added in v0.1.7

type RetryOption func(*retryCheckpointSaver)

RetryOption configures the retry behaviour of a retryCheckpointSaver.

func WithBaseDelay added in v0.1.7

func WithBaseDelay(d time.Duration) RetryOption

WithBaseDelay sets the initial backoff delay (default 500ms). Each subsequent retry doubles the delay.

func WithMaxRetries added in v0.1.7

func WithMaxRetries(n int) RetryOption

WithMaxRetries sets the maximum number of retry attempts (default 3).

func WithRetryLogger added in v0.1.7

func WithRetryLogger(l *slog.Logger) RetryOption

WithRetryLogger sets the logger for retry warnings.

type SessionEvent

type SessionEvent struct {
	ID        uint      `gorm:"primaryKey;autoIncrement" json:"id"`
	AppName   string    `gorm:"type:text;not null;index:idx_session_events_key" json:"app_name"`
	UserID    string    `gorm:"type:text;not null;index:idx_session_events_key" json:"user_id"`
	SessionID string    `gorm:"type:text;not null;index:idx_session_events_key" json:"session_id"`
	EventData string    `gorm:"type:text;not null" json:"event_data"` // JSON-encoded event.Event
	CreatedAt time.Time `gorm:"not null" json:"created_at"`
}

SessionEvent is the GORM model for session_events table.

func (SessionEvent) TableName

func (SessionEvent) TableName() string

type SessionRow

type SessionRow struct {
	AppName   string    `gorm:"primaryKey;type:text" json:"app_name"`
	UserID    string    `gorm:"primaryKey;type:text" json:"user_id"`
	SessionID string    `gorm:"primaryKey;type:text" json:"session_id"`
	CreatedAt time.Time `gorm:"not null" json:"created_at"`
	UpdatedAt time.Time `gorm:"not null;index:idx_sessions_updated" json:"updated_at"`
}

SessionRow is the GORM model for the sessions table.

func (SessionRow) TableName

func (SessionRow) TableName() string

type SessionState

type SessionState struct {
	AppName   string    `gorm:"primaryKey;type:text" json:"app_name"`
	UserID    string    `gorm:"primaryKey;type:text" json:"user_id"`
	SessionID string    `gorm:"primaryKey;type:text" json:"session_id"`
	Key       string    `gorm:"primaryKey;type:text" json:"key"`
	Value     []byte    `json:"value"`
	UpdatedAt time.Time `gorm:"not null" json:"updated_at"`
}

SessionState is the GORM model for session-level state key-value pairs.

func (SessionState) TableName

func (SessionState) TableName() string

type SessionStore

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

SessionStore implements session.Service backed by GORM/SQLite. It wraps an inmemory.SessionService for in-process session logic and persists all changes to the database for durability across restarts.

func NewSessionStore

func NewSessionStore(ctx context.Context, db *gorm.DB, opts ...SessionStoreOption) *SessionStore

NewSessionStore creates a new GORM-backed session store. This is the default SessionStoreBuilder.

func (*SessionStore) AppendEvent

func (s *SessionStore) AppendEvent(
	ctx context.Context,
	sess *session.Session,
	evt *event.Event,
	opts ...session.Option,
) error

func (*SessionStore) Checkpointer

func (s *SessionStore) Checkpointer() graph.CheckpointSaver

Checkpointer returns the underlying graph.CheckpointSaver if initialized.

func (*SessionStore) Close

func (s *SessionStore) Close() error

Close stops the inmemory service. DB lifecycle is managed externally.

func (*SessionStore) CreateSession

func (s *SessionStore) CreateSession(
	ctx context.Context,
	key session.Key,
	state session.StateMap,
	opts ...session.Option,
) (*session.Session, error)

func (*SessionStore) CreateSessionSummary

func (s *SessionStore) CreateSessionSummary(ctx context.Context, sess *session.Session, filterKey string, force bool) error

func (*SessionStore) DeleteAppState

func (s *SessionStore) DeleteAppState(ctx context.Context, appName string, key string) error

func (*SessionStore) DeleteSession

func (s *SessionStore) DeleteSession(
	ctx context.Context,
	key session.Key,
	opts ...session.Option,
) error

func (*SessionStore) DeleteUserState

func (s *SessionStore) DeleteUserState(ctx context.Context, userKey session.UserKey, key string) error

func (*SessionStore) EnqueueSummaryJob

func (s *SessionStore) EnqueueSummaryJob(ctx context.Context, sess *session.Session, filterKey string, force bool) error

func (*SessionStore) GetSession

func (s *SessionStore) GetSession(
	ctx context.Context,
	key session.Key,
	opts ...session.Option,
) (*session.Session, error)

func (*SessionStore) GetSessionSummaryText

func (s *SessionStore) GetSessionSummaryText(ctx context.Context, sess *session.Session, opts ...session.SummaryOption) (string, bool)

func (*SessionStore) ListAppStates

func (s *SessionStore) ListAppStates(ctx context.Context, appName string) (session.StateMap, error)

func (*SessionStore) ListSessions

func (s *SessionStore) ListSessions(
	ctx context.Context,
	userKey session.UserKey,
	opts ...session.Option,
) ([]*session.Session, error)

func (*SessionStore) ListUserStates

func (s *SessionStore) ListUserStates(ctx context.Context, userKey session.UserKey) (session.StateMap, error)

func (*SessionStore) UpdateAppState

func (s *SessionStore) UpdateAppState(ctx context.Context, appName string, state session.StateMap) error

func (*SessionStore) UpdateSessionState

func (s *SessionStore) UpdateSessionState(ctx context.Context, key session.Key, state session.StateMap) error

func (*SessionStore) UpdateUserState

func (s *SessionStore) UpdateUserState(ctx context.Context, userKey session.UserKey, state session.StateMap) error

type SessionStoreBuilder

type SessionStoreBuilder func(ctx context.Context, db *gorm.DB, opts ...SessionStoreOption) *SessionStore

SessionStoreBuilder is a function type that creates a SessionStore, analogous to mysql.clientBuilder in trpc-agent-go/storage/mysql.

var DefaultSessionStoreBuilder SessionStoreBuilder = NewSessionStore

DefaultSessionStoreBuilder is the default builder.

type SessionStoreOption

type SessionStoreOption func(*sessionStoreOpts)

SessionStoreOption configures a SessionStore (analogous to ClientBuilderOpt in trpc-agent-go/storage/mysql).

func WithSessionStoreEventLimit

func WithSessionStoreEventLimit(limit int) SessionStoreOption

WithSessionStoreEventLimit caps the number of events persisted per session. Older events are pruned on append. 0 = unlimited.

func WithSessionStoreInMemoryOpts

func WithSessionStoreInMemoryOpts(opts ...inmemory.ServiceOpt) SessionStoreOption

WithSessionStoreInMemoryOpts passes options through to the underlying inmemory.SessionService (e.g. WithSummarizer, WithSessionEventLimit).

type SessionSummaryRow

type SessionSummaryRow struct {
	AppName   string    `gorm:"primaryKey;type:text" json:"app_name"`
	UserID    string    `gorm:"primaryKey;type:text" json:"user_id"`
	SessionID string    `gorm:"primaryKey;type:text" json:"session_id"`
	FilterKey string    `gorm:"primaryKey;type:text" json:"filter_key"` // "" = full-session summary
	Summary   string    `gorm:"type:text;not null" json:"summary"`
	Topics    string    `gorm:"type:text;default:'[]'" json:"topics"` // JSON-encoded []string
	UpdatedAt time.Time `gorm:"not null" json:"updated_at"`
}

SessionSummaryRow is the GORM model for session summaries.

func (SessionSummaryRow) TableName

func (SessionSummaryRow) TableName() string

type ShortMemory

type ShortMemory struct {
	// Key is the primary lookup key (e.g. a message ID for reaction correlation).
	Key string `gorm:"primaryKey;type:text" json:"key"`
	// MemoryType logically separates different subsystems sharing this table
	// (e.g. "reaction_ledger", "cooldown_tracker").
	MemoryType string `gorm:"primaryKey;type:text;index:idx_short_memory_type" json:"memory_type"`
	// Value stores the subsystem-specific data as JSON.
	Value string `gorm:"type:text;not null" json:"value"`
	// ExpiresAt is when this entry should be considered expired.
	// Queries should filter WHERE expires_at > NOW().
	ExpiresAt time.Time `gorm:"not null;index:idx_short_memory_expires" json:"expires_at"`
	// CreatedAt tracks when the entry was first created.
	CreatedAt time.Time `gorm:"not null" json:"created_at"`
}

ShortMemory is the GORM model for the short_memories table. It is a generic, TTL-bounded key-value store that different subsystems can use for short-lived data by setting a unique MemoryType. This avoids creating per-feature tables for transient data (e.g. reaction ledger, cooldown trackers, pending confirmations).

func (ShortMemory) TableName

func (ShortMemory) TableName() string

TableName overrides the default GORM table name.

type ShortMemoryStore

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

ShortMemoryStore provides a generic, TTL-bounded key-value store backed by the short_memories table. Different subsystems share the same table but are logically isolated via MemoryType (e.g. "reaction_ledger", "cooldown").

This replaces ad-hoc in-memory sync.Map / TTL map patterns with a durable, restart-safe store. Expired entries are cleaned up lazily on read and periodically via Cleanup().

func NewShortMemoryStore

func NewShortMemoryStore(db *gorm.DB) *ShortMemoryStore

NewShortMemoryStore creates a new store backed by the given GORM DB.

func (*ShortMemoryStore) Cleanup

func (s *ShortMemoryStore) Cleanup(ctx context.Context) (int64, error)

Cleanup removes all expired entries across all memory types. Call this periodically (e.g. on a timer) to prevent table bloat.

func (*ShortMemoryStore) Count

func (s *ShortMemoryStore) Count(ctx context.Context, memoryType string) (int64, error)

Count returns the number of non-expired entries for a given memory type. Primarily useful for monitoring and testing.

func (*ShortMemoryStore) Delete

func (s *ShortMemoryStore) Delete(ctx context.Context, memoryType, key string) error

Delete removes a specific entry.

func (*ShortMemoryStore) Get

func (s *ShortMemoryStore) Get(ctx context.Context, memoryType, key string) (string, bool, error)

Get retrieves a non-expired entry. Returns the value and true if found, or empty string and false if missing or expired.

func (*ShortMemoryStore) Set

func (s *ShortMemoryStore) Set(ctx context.Context, memoryType, key, value string, ttl time.Duration) error

Set inserts or updates a short memory entry with the given TTL. The value should be a JSON-encoded string containing subsystem-specific data.

type UserState

type UserState struct {
	AppName   string    `gorm:"primaryKey;type:text" json:"app_name"`
	UserID    string    `gorm:"primaryKey;type:text" json:"user_id"`
	Key       string    `gorm:"primaryKey;type:text" json:"key"`
	Value     []byte    `json:"value"`
	UpdatedAt time.Time `gorm:"not null" json:"updated_at"`
}

UserState is the GORM model for user-level state.

func (UserState) TableName

func (UserState) TableName() string

Jump to

Keyboard shortcuts

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