Documentation
¶
Overview ¶
Package datasources is the umbrella over the persistence backends HB Labs services use. The platform is single-store: MongoDB. The reasoning, briefly:
- One operational footprint. Running Postgres + Redis HA at small scale doubles the on-call burden without doubling the value; a Mongo replica set / sharded cluster covers structured data, ephemeral state with TTL, and high-cardinality logs in one cluster.
- TTL indexes give us "Redis-style" expiration on auth tokens, sessions, magic-link nonces and rate-limit blocks without a second store.
- Multi-document transactions on replica sets cover the atomic ops we actually need (membership flips, billing state).
- Schema flexibility removes the migration tax for early iterations of Site.Config and similar JSON-shaped fields.
Trade-off accepted: no native row-level security. The "every query filters by organization_id" invariant lives in the wrapper (see kit/mongo.Collection) so it's hard to accidentally leak across tenants.
Layout:
- datasource.go — Datasource interface (Get/Set/Delete/ Exists/Ping/Close) for code that only needs key/value with TTL.
- memory.go — in-process Datasource impl for tests.
- kit/mongo — typed Mongo client, implements Datasource on a kv collection, exposes the raw *mongo.Client and per-collection helpers for everything else.
The Datasource interface stays even with one backend so unit tests can swap a MemoryDatasource without spinning up Mongo. Production code typically reaches for the typed mongo client directly — Datasource is the narrow door, mongo is the wide one.
Index ¶
- Variables
- type Datasource
- type MemoryDatasource
- func (m *MemoryDatasource) Close() error
- func (m *MemoryDatasource) Delete(_ context.Context, key string) error
- func (m *MemoryDatasource) Exists(_ context.Context, key string) (bool, error)
- func (m *MemoryDatasource) Get(_ context.Context, key string) ([]byte, error)
- func (m *MemoryDatasource) Ping(context.Context) error
- func (m *MemoryDatasource) Set(_ context.Context, key string, value []byte, ttl time.Duration) error
- func (m *MemoryDatasource) SetClock(now func() time.Time)
Constants ¶
This section is empty.
Variables ¶
var ErrNegativeTTL = errors.New("datasources: negative ttl")
ErrNegativeTTL is what Datasource.Set returns when called with a negative duration. Sentinel rather than ad-hoc text so callers can distinguish a programming error (caught in tests / staging) from a real backend failure.
var ErrNotFound = errors.New("datasources: not found")
ErrNotFound is what Datasource.Get returns when a key has no value (never written, or expired). errors.Is(err, ErrNotFound) is the canonical check; backends wrap this so the underlying cause stays inspectable in logs.
Functions ¶
This section is empty.
Types ¶
type Datasource ¶
type Datasource interface {
// Get returns the bytes at key, or ErrNotFound. Any other error
// is a real backend failure — handlers MUST NOT treat it as a
// miss, or a flapping backend will silently regenerate work
// while the underlying problem hides.
Get(ctx context.Context, key string) ([]byte, error)
// Set writes value at key. ttl=0 means no expiration; negative
// ttl returns an error. Callers that want "set without changing
// the existing TTL" should fetch + delete + set, or reach for
// the typed client.
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
// Delete removes key. Idempotent: deleting a missing key returns
// nil. Errors only on a real backend failure.
Delete(ctx context.Context, key string) error
// Exists reports whether key currently holds a non-expired value.
// Faster than Get when the caller only needs the boolean — Redis
// returns a single integer, Postgres a count(*) — but the choice
// between them is style; both work.
Exists(ctx context.Context, key string) (bool, error)
// Ping verifies the underlying connection is healthy. Suitable
// for observability.Healthz; ctx timeout caps the check so a
// hung backend doesn't take the readiness probe down with it.
Ping(ctx context.Context) error
// Close releases the underlying connection pool. Call from a
// service's graceful-shutdown path. Safe to call once and only
// once — concrete impls don't promise idempotency.
Close() error
}
Datasource is the unified key/value contract every persistence backend in this umbrella implements. Methods take []byte rather than encoded strings so callers control the wire format (JSON, gob, protobuf, raw bytes — the store doesn't care).
Limits of the abstraction (knowingly accepted):
- No transactions across calls. A backend that has them (Postgres) exposes them through its typed client; cross-key consistency is not part of this interface.
- No conditional writes (CAS). Add a method only when a real consumer needs it — premature primitives leak.
- No range / prefix scans. Backends differ wildly here (Redis SCAN cursors vs Postgres SELECT…LIKE); callers that need scanning take the typed client.
In short: this is the "store an opaque blob under a key, maybe with a TTL" API. Anything more specific lives in the typed client or in a domain-level repository.
type MemoryDatasource ¶
type MemoryDatasource struct {
// contains filtered or unexported fields
}
MemoryDatasource is an in-process Datasource implementation for unit tests and local development. Honours TTL by stamping each entry with an expiration time; expired entries are filtered at read time (no background sweep — the test runs short enough that the map fits in memory).
Not for production. The production code path goes through the mongo subpackage.
func NewMemoryDatasource ¶
func NewMemoryDatasource() *MemoryDatasource
NewMemoryDatasource builds an empty store. Tests that want to assert TTL behaviour deterministically can override the clock by reassigning `Now` after construction.
func (*MemoryDatasource) Close ¶
func (m *MemoryDatasource) Close() error
Close implements Datasource. Drops every entry.
func (*MemoryDatasource) Delete ¶
func (m *MemoryDatasource) Delete(_ context.Context, key string) error
Delete implements Datasource. Idempotent.
func (*MemoryDatasource) Ping ¶
func (m *MemoryDatasource) Ping(context.Context) error
Ping implements Datasource. Always nil — the in-memory store has no remote dependency to check.
func (*MemoryDatasource) Set ¶
func (m *MemoryDatasource) Set(_ context.Context, key string, value []byte, ttl time.Duration) error
Set implements Datasource.
func (*MemoryDatasource) SetClock ¶
func (m *MemoryDatasource) SetClock(now func() time.Time)
SetClock swaps the time source. Useful for tests that want to fast-forward TTL boundaries without sleeping.