Documentation
¶
Overview ¶
Package strata provides a three-tier auto-caching data library unifying in-memory (L1), Redis (L2), and PostgreSQL (L3) behind a single API.
Index ¶
- Variables
- func GetTyped[T any](ctx context.Context, ds *DataStore, schemaName, id string) (*T, error)
- func Q() *queryBuilder
- func SearchTyped[T any](ctx context.Context, ds *DataStore, schemaName string, q *Query) ([]T, error)
- func Version() string
- type AES256GCM
- type Codec
- type Config
- type DataStore
- func (ds *DataStore) Close() error
- func (ds *DataStore) Count(ctx context.Context, schemaName string, q *Query) (int64, error)
- func (ds *DataStore) Delete(ctx context.Context, schemaName, id string) error
- func (ds *DataStore) Exists(ctx context.Context, schemaName, id string) (bool, error)
- func (ds *DataStore) FlushDirty(ctx context.Context) error
- func (ds *DataStore) Get(ctx context.Context, schemaName, id string, dest any) error
- func (ds *DataStore) Invalidate(ctx context.Context, schemaName, id string) error
- func (ds *DataStore) InvalidateAll(ctx context.Context, schemaName string) error
- func (ds *DataStore) Migrate(ctx context.Context) error
- func (ds *DataStore) MigrateFrom(ctx context.Context, dir string) error
- func (ds *DataStore) MigrationStatus(ctx context.Context) ([]MigrationRecord, error)
- func (ds *DataStore) Register(s Schema) error
- func (ds *DataStore) Search(ctx context.Context, schemaName string, q *Query, destSlice any) error
- func (ds *DataStore) SearchCached(ctx context.Context, schemaName string, q *Query, destSlice any) error
- func (ds *DataStore) Set(ctx context.Context, schemaName, id string, value any) error
- func (ds *DataStore) SetMany(ctx context.Context, schemaName string, pairs map[string]any) error
- func (ds *DataStore) Stats() Stats
- func (ds *DataStore) Tx(ctx context.Context) *Tx
- func (ds *DataStore) WarmCache(ctx context.Context, schemaName string, limit int) error
- type Encryptor
- type EvictionPolicy
- type Index
- type L1PoolConfig
- type L2PoolConfig
- type L3PoolConfig
- type Logger
- type MemPolicy
- type MetricsRecorder
- type MigrationRecord
- type PostgresPolicy
- type Query
- type RedisPolicy
- type Schema
- type SchemaHooks
- type Stats
- type Tx
- type WriteMode
Constants ¶
This section is empty.
Variables ¶
var ( ErrSchemaNotFound = errors.New("strata: schema not registered") ErrSchemaDuplicate = errors.New("strata: schema already registered") ErrNoPrimaryKey = errors.New("strata: struct has no primary_key field") ErrInvalidModel = errors.New("strata: model must be a non-nil pointer to a struct") ErrMissingPrimaryKey = errors.New("strata: value is missing primary key") )
Schema errors
var ( ErrNotFound = errors.New("strata: record not found") ErrDecodeFailed = errors.New("strata: failed to decode stored value") ErrEncodeFailed = errors.New("strata: failed to encode value for storage") )
Data errors
var ( )
Infrastructure errors
var ( ErrTxFailed = errors.New("strata: transaction failed") ErrTxTimeout = errors.New("strata: transaction timeout") )
Transaction errors
var ( // BuildDate is the date and time the binary was built. // Set by: -ldflags "-X 'github.com/AndrewDonelson/strata.BuildDate=2026.02.28-1750'" BuildDate = "0000.00.00-0000" // BuildEnv is the target environment for this build. // Set by: -ldflags "-X 'github.com/AndrewDonelson/strata.BuildEnv=dev'" BuildEnv = "dev" )
Build-time variables injected via -ldflags by the Makefile. Defaults represent an unversioned local development build.
BuildDate format : YYYY.MM.DD-HHMM (24-hour clock) BuildEnv values : dev | qa | prod
Full version example: "2026.02.28-1750-dev"
var (
ErrHookPanic = errors.New("strata: hook panicked")
)
Hook errors
var (
ErrInsufficientFunds = errors.New("strata: insufficient funds")
)
Domain errors
var (
ErrInvalidConfig = errors.New("strata: invalid configuration")
)
Config errors
var (
ErrWriteBehindMaxRetry = errors.New("strata: write-behind exceeded max retries")
)
Write-behind errors
Functions ¶
Types ¶
type AES256GCM ¶
type AES256GCM struct {
// contains filtered or unexported fields
}
AES256GCM implements AES-256-GCM authenticated encryption.
func NewAES256GCM ¶
NewAES256GCM creates an AES-256-GCM encryptor from a 32-byte key.
type Config ¶
type Config struct {
// DSNs
PostgresDSN string
RedisAddr string
RedisPassword string
RedisDB int
// Pool sizes
L1Pool L1PoolConfig
L2Pool L2PoolConfig
L3Pool L3PoolConfig
// TTLs
DefaultL1TTL time.Duration
DefaultL2TTL time.Duration
// Write behaviour
DefaultWriteMode WriteMode
WriteBehindFlushInterval time.Duration
WriteBehindFlushThreshold int
WriteBehindMaxRetry int
// Invalidation
InvalidationChannel string
// Optional overrideable components
Codec codec.Codec
Clock clock.Clock
Metrics metrics.MetricsRecorder
Logger Logger
// Encryption key (must be 32 bytes for AES-256-GCM; nil = disabled).
EncryptionKey []byte
}
Config contains all DataStore configuration.
type DataStore ¶
type DataStore struct {
// contains filtered or unexported fields
}
DataStore is the main entry-point for the Strata library.
func NewDataStore ¶
NewDataStore creates and initialises a DataStore from the provided Config.
func (*DataStore) FlushDirty ¶
FlushDirty blocks until all write-behind entries are flushed to L3.
func (*DataStore) Get ¶
Get fetches the record with the given id into dest. dest must be a pointer to the model type of the registered schema.
func (*DataStore) Invalidate ¶
Invalidate removes a key from all cache tiers and publishes an invalidation event.
func (*DataStore) InvalidateAll ¶
InvalidateAll flushes all cached entries for schemaName across L1 and L2.
func (*DataStore) MigrateFrom ¶
MigrateFrom applies SQL migration files from dir in NNN_description.sql order.
func (*DataStore) MigrationStatus ¶
func (ds *DataStore) MigrationStatus(ctx context.Context) ([]MigrationRecord, error)
MigrationStatus returns current migration state.
func (*DataStore) Search ¶
Search runs q against L3 and returns the results in destSlice (pointer to slice).
func (*DataStore) SearchCached ¶
func (ds *DataStore) SearchCached(ctx context.Context, schemaName string, q *Query, destSlice any) error
SearchCached runs q against L3; caches list result in L2 by SQL fingerprint.
type Encryptor ¶
type Encryptor interface {
Encrypt(plaintext []byte) ([]byte, error)
Decrypt(ciphertext []byte) ([]byte, error)
}
Encryptor encrypts and decrypts field values for fields tagged with "encrypted".
type EvictionPolicy ¶
type EvictionPolicy int
EvictionPolicy determines which L1 entry is evicted when MaxEntries is reached.
const ( EvictLRU EvictionPolicy = iota EvictLFU EvictFIFO )
type L1PoolConfig ¶
type L1PoolConfig struct {
MaxEntries int
Eviction EvictionPolicy
}
L1PoolConfig configures the in-memory L1 cache tier.
type L2PoolConfig ¶
type L2PoolConfig struct {
PoolSize int
DialTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
}
L2PoolConfig configures the Redis L2 cache tier client.
type L3PoolConfig ¶
type L3PoolConfig struct {
MaxConns int32
MinConns int32
MaxConnLifetime time.Duration
MaxConnIdleTime time.Duration
}
L3PoolConfig configures the PostgreSQL L3 connection pool.
type Logger ¶
type Logger interface {
Info(msg string, keysAndValues ...any)
Warn(msg string, keysAndValues ...any)
Error(msg string, keysAndValues ...any)
Debug(msg string, keysAndValues ...any)
}
Logger is the logging interface used internally by Strata. Implement this to route logs to zap, slog, logrus, etc.
type MemPolicy ¶
type MemPolicy struct {
TTL time.Duration
MaxEntries int
Eviction EvictionPolicy
}
MemPolicy configures L1 in-memory cache behavior for a schema.
type MetricsRecorder ¶
type MetricsRecorder = metrics.MetricsRecorder
Re-export types so callers only import this package.
type MigrationRecord ¶
MigrationRecord describes a single applied migration.
type PostgresPolicy ¶
PostgresPolicy configures L3 Postgres persistence for a schema.
type Query ¶
type Query struct {
Where string
Args []any
OrderBy string
Desc bool
Limit int
Offset int
Fields []string
ForceL3 bool
ForceL2 bool
}
Query specifies search parameters for the Search and SearchCached operations.
type RedisPolicy ¶
RedisPolicy configures L2 Redis cache behavior for a schema.
type Schema ¶
type Schema struct {
Name string
Model any
L1 MemPolicy
L2 RedisPolicy
L3 PostgresPolicy
WriteMode WriteMode
Indexes []Index
Hooks SchemaHooks
}
Schema defines one data collection and its caching policy.
type SchemaHooks ¶
type SchemaHooks struct {
BeforeSet func(ctx context.Context, value any) error
AfterSet func(ctx context.Context, value any)
BeforeGet func(ctx context.Context, id string)
AfterGet func(ctx context.Context, value any)
OnEvict func(ctx context.Context, key string, value any)
OnWriteError func(ctx context.Context, key string, err error)
}
SchemaHooks provides optional lifecycle callbacks.
type Stats ¶
type Stats struct {
Gets int64
Sets int64
Deletes int64
Errors int64
DirtyCount int64
L1Entries int64
}
Stats is the snapshot returned by DataStore.Stats().
type Tx ¶
type Tx struct {
// contains filtered or unexported fields
}
Tx is a lightweight transaction helper that queues L3 operations and updates caches on commit.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
clock
Package clock provides a testable clock interface for TTL calculations.
|
Package clock provides a testable clock interface for TTL calculations. |
|
codec
Package codec provides encode/decode interfaces for cache serialization.
|
Package codec provides encode/decode interfaces for cache serialization. |
|
l1
Package l1 provides a sharded, concurrent in-memory cache with TTL and eviction.
|
Package l1 provides a sharded, concurrent in-memory cache with TTL and eviction. |
|
l2
Package l2 provides the Redis tier cache adapter.
|
Package l2 provides the Redis tier cache adapter. |
|
l3
Package l3 provides the PostgreSQL persistence tier adapter.
|
Package l3 provides the PostgreSQL persistence tier adapter. |
|
metrics
Package metrics provides the MetricsRecorder interface and a noop implementation.
|
Package metrics provides the MetricsRecorder interface and a noop implementation. |