Documentation
¶
Overview ¶
Package store provides universal data access contracts for the Credo framework.
This package defines error sentinels, the typed Health report, and context-based transaction helpers. It has zero external dependencies — only the Go standard library and Credo's root/fault contracts are imported.
The companion package store/sqldb (a separate Go submodule) wraps *bun.DB with lifecycle management, query builder proxies, error mapping, and transaction support.
Universal Errors ¶
Store errors expose a transport-neutral semantic Kind. The default HTTP policy and future protocol adapters consume that kind independently:
if kind, ok := store.KindOf(err); ok {
// branch on KindNotFound, KindConstraint, KindDeadlock, ...
}
Error retains diagnostic code/constraint/resource metadata and the original cause without exposing them in Credo's default HTTP response. Its HTTP status comes from its kind alone, through fault.Provider: the error pipeline maps the kind to a status, and the kind is the response's code.
A Bound Store ¶
A store is a component like any other: it is bound with app.ProvideValue, or app.Provide with a constructor, with credo.Borrowed() for a handle the caller shares, and the binding alone is enough:
app.ProvideValue(db)
The start walk calls the store's Start, which pings it, before the components that depend on it start; /ready reports it through its Ready; and the App shuts it down after its consumers unless it is borrowed. A store adapter implements Start, Ready and Shutdown, as store/sqldb's *DB does. credo.OptionalReadiness() reports a store in /ready without letting it gate readiness, and credo.ComponentName names its entry.
Several bindings may hold one physical resource — a *sqldb.DB bound raw and a wrapper type that embeds it. A value that names its resource through credo.ResourceIdentifier is one resource with the other holders of that resource: one start, one readiness entry and one teardown, which happens once, after the last holder retires. Only a value without state of its own to release may share an identity.
Health.Cause carries typed diagnostics for logging while remaining excluded from JSON; free-form Details values are never interpreted as error causes.
Context-Based Transactions ¶
A custom adapter creates one typed TxScope per logical connection. The transaction type is fixed at construction, preventing a concrete/interface mismatch from silently selecting the fallback connection:
scope := store.NewTxScope[Client]() ctx = scope.WithTx(ctx, tx) conn := scope.Conn(ctx, base) tx, err := scope.RequireTx(ctx) // no fallback
The companion store/sqldb adapter owns a private typed scope per DB. Its proxy terminals participate automatically; db.Conn(ctx) is the transaction-aware Bun escape hatch. The scope's methods are the one transaction API.
Maturity: beta
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotFound indicates that the requested record does not exist. ErrNotFound error = newKindError(KindNotFound, "store: record not found") // ErrAlreadyExists indicates a unique or primary-key violation. ErrAlreadyExists error = newKindError(KindAlreadyExists, "store: duplicate record") // ErrConstraint indicates a persistent integrity constraint violation other // than a duplicate, such as foreign-key, not-null, or check failure. ErrConstraint error = newKindError(KindConstraint, "store: constraint violation") // ErrSerialization indicates that transaction serialization failed. ErrSerialization error = newKindError(KindSerialization, "store: serialization failure") // ErrDeadlock indicates that the database detected a deadlock. ErrDeadlock error = newKindError(KindDeadlock, "store: deadlock") // ErrContention indicates a transient lock/busy conflict whose safe retry // scope is not implied by this sentinel. ErrContention error = newKindError(KindContention, "store: contention") // ErrTimeout indicates that a database operation exceeded a verified // deadline or statement timeout. ErrTimeout error = newKindError(KindTimeout, "store: timeout") // temporarily unavailable. ErrUnavailable error = newKindError(KindUnavailable, "store: unavailable") // ErrReadOnly indicates that a write was attempted against a read-only // transaction or server. ErrReadOnly error = newKindError(KindReadOnly, "store: read-only") )
Sentinel errors for data access operations.
var ErrTxMissing = errors.New("store: transaction missing from context")
ErrTxMissing indicates that a transaction-required operation was called without a transaction in its context scope.
Functions ¶
func IsTransient ¶
IsTransient reports whether the primary store classification describes a condition that may clear. It never means an operation, transaction callback, or externally visible side effect is safe to retry.
Types ¶
type Error ¶
type Error struct {
Kind Kind
Op string
Resource string
Constraint string
Code string
Transient bool
Cause error
}
Error is a structured, transport-neutral data-access error.
Code, Constraint, Resource, and Cause are internal diagnostic metadata. The default HTTP renderer classifies only Kind and never serializes these fields. Transient describes whether the condition may clear; it does not guarantee that replaying the operation or transaction is safe.
type Health ¶
type Health struct {
// Status is the current health state.
Status HealthStatus
// Latency is the round-trip time of the health check probe.
Latency time.Duration
// Cause is the typed internal reason for a down or degraded result.
// It is excluded from JSON so unauthenticated readiness endpoints cannot
// leak connection targets or driver diagnostics. Credo logs it and exposes
// its text only when HealthConfig.ExposeErrors is explicitly enabled.
Cause error `json:"-"`
// Details holds adapter-specific information such as database version,
// connection pool statistics, or replication lag.
Details map[string]any
}
Health is the result of a connection health check.
type HealthStatus ¶
type HealthStatus string
HealthStatus represents the health state of a data store connection.
const ( // StatusUp indicates the connection is healthy. StatusUp HealthStatus = "UP" // StatusDown indicates the connection is unreachable. StatusDown HealthStatus = "DOWN" // StatusDegraded indicates the connection is available but impaired. StatusDegraded HealthStatus = "DEGRADED" )
type Kind ¶
Kind is the transport-neutral semantic category of a store error.
const ( KindUnknown Kind = fault.KindUnknown KindNotFound Kind = fault.KindNotFound KindAlreadyExists Kind = fault.KindAlreadyExists KindConstraint Kind = fault.KindConstraint KindSerialization Kind = fault.KindSerialization KindDeadlock Kind = fault.KindDeadlock KindContention Kind = fault.KindContention KindConflict Kind = fault.KindConflict KindTimeout Kind = fault.KindTimeout KindReadOnly Kind = fault.KindReadOnly )
Store error kinds. They are aliases of the shared transport-neutral kinds so Credo's HTTP policy and future gRPC policy can classify them without importing store and creating a package cycle.
type TxScope ¶
type TxScope[T any] struct { // contains filtered or unexported fields }
TxScope isolates transactions that share the same Go type but belong to different logical connections. T is fixed when the scope is created, so a concrete transaction cannot be stored and then silently missed by reading the same scope through a different interface type.
The marker field keeps TxScope non-zero-size on purpose: in Go, pointers to distinct zero-size structs may share an address, which would let two independent scopes collide as context keys. A non-empty field guarantees a unique address per NewTxScope call.
func NewTxScope ¶
NewTxScope creates a unique transaction scope whose transaction type is T.
func (*TxScope[T]) Conn ¶
Conn returns this scope's transaction from the context if present, otherwise the fallback connection — the call repositories make for opt-in scoped TX participation.
func (*TxScope[T]) GetTx ¶
GetTx retrieves this scope's transaction handle from the context, returning the zero value and false when none is stored.
func (*TxScope[T]) RequireTx ¶
RequireTx retrieves this scope's transaction handle or returns ErrTxMissing when none is stored. It never falls back to a base connection.