Documentation
¶
Overview ¶
Package sql is the msgin channel adapter for any database/sql-compatible SQL database, using a table as a durable, at-least-once message queue: a polling SELECT ... FOR UPDATE SKIP LOCKED inbound and an INSERT outbound. The generic database/sql package is stdlib and the SQL driver is caller-injected, so this adapter imports no driver and lives in the core module (ADR 0003).
Import alias ¶
The package is named sql and collides with the standard library's database/sql, which callers also need (to hold the *sql.DB they inject). Import this package under an alias — the convention throughout msgin is msginsql:
import ( "database/sql" msginsql "github.com/kartaladev/msgin/adapter/database/sql" )
Schema ownership ¶
The caller provisions the schema; msgin never runs DDL on the production path. Use postgres.DDL(table) (adapter/database/sql/postgres) / mysql.DDL(table) (adapter/database/sql/mysql) to obtain the reference CREATE TABLE (+ index) for your migration tool, or call the optional, idempotent EnsureSchema in dev and tests.
Dialects ¶
The exported LeaseDialect SPI owns the complete SQL for every operation, so no cross-dialect statement ever runs. Every adapter constructor (NewPollingSource, NewOutboundAdapter, NewInboxDeduper) takes the dialect as an explicit, required argument — there is no driver auto-detect (ADR 0011): a nil dialect is refused at construction with ErrNilDialect, so the wrong SQL is never silently generated for an unrecognized or wire-compatible-derivative driver. The built-ins are postgres.LeaseDialect() (adapter/database/sql/ postgres, its own module) and mysql.LeaseDialect() (adapter/database/sql/ mysql, its own module). They are behavior-identical — same lease/claim predicate, fence semantics, and delivery_count/lease_epoch bumps — over each engine's own SQL (Postgres has RETURNING; MySQL has none, so its claim runs an atomic two-step SELECT ... FOR UPDATE SKIP LOCKED + UPDATE in one transaction). All persisted timestamps use the DB server clock (Postgres now() / MySQL UTC_TIMESTAMP(6)); only scheduling (poll interval, backoff) uses the app clock. This split keeps lease-expiry and visibility comparisons free of app↔DB skew.
Dialect-author SPI ¶
A caller implementing their own LeaseDialect/InboxDialect (for a wire-compatible derivative, or a new engine) validates every table (or derived index) identifier with msginsql.ValidateIdent before dialect-quoting and interpolating it into SQL — the sole injection guard, since the identifier cannot be a bound parameter. A LockDialect implementation's ClaimLock/AckLock/NackLock builds its carried transaction with msginsql.BeginLockTx and settles it with msginsql.SettleLockTx, which guarantee the always-commit-on-success / rollback-on-error contract so a pooled connection is never leaked.
Index ¶
- Constants
- Variables
- func BeginLockTx(ctx context.Context, q Querier) (*stdsql.Tx, error)
- func DecodeHeaders(b []byte) (msgin.Headers, error)
- func EncodeHeaders(h msgin.Headers) ([]byte, error)
- func SettleLockTx(ctx context.Context, tx *stdsql.Tx, query string, args ...any) error
- func ValidateIdent(name string) error
- func ValidateMaxMembers(site string, maxMembers int) error
- type ClaimedGroup
- type ClaimedRow
- type GroupDialect
- type GroupRows
- type GroupStore
- func (s *GroupStore) AbandonGroup(ctx context.Context, claim msgin.MessageGroupClaim) error
- func (s *GroupStore) Add(ctx context.Context, key string, msg msgin.Message[any]) (msgin.MessageGroup, error)
- func (s *GroupStore) ClaimGroup(ctx context.Context, key string) (msgin.MessageGroupClaim, error)
- func (s *GroupStore) EmitsLiveValue() bool
- func (b GroupStore) EnsureSchema(ctx context.Context) error
- func (s *GroupStore) Expired(ctx context.Context, before time.Time) ([]msgin.MessageGroup, error)
- func (b GroupStore) Ready(ctx context.Context) error
- func (s *GroupStore) RecoverInterval() time.Duration
- func (s *GroupStore) SettleGroup(ctx context.Context, claim msgin.MessageGroupClaim) error
- type GroupStoreOption
- type InboxDeduper
- func (d *InboxDeduper) EnsureSchema(ctx context.Context) error
- func (d *InboxDeduper) MarkProcessed(ctx context.Context, tx *stdsql.Tx, msgID string) (already bool, err error)
- func (d *InboxDeduper) Purge(ctx context.Context, olderThan time.Duration) (int64, error)
- func (d *InboxDeduper) Ready(ctx context.Context) error
- type InboxDialect
- type InboxOption
- type LeaseDialect
- type LockDialect
- type LockedRow
- type MemberRow
- type Option
- type Outbound
- type Querier
- type QueueStore
- func (q *QueueStore) Claim(ctx context.Context, max int) ([]msgin.Delivery, error)
- func (q *QueueStore) EmitsLiveValue() bool
- func (q *QueueStore) Enqueue(ctx context.Context, msg msgin.Message[any]) error
- func (q *QueueStore) EnsureSchema(ctx context.Context) error
- func (q *QueueStore) NativeDeadLetter() bool
- func (q *QueueStore) NativeRedelivery() bool
- func (q *QueueStore) Ready(ctx context.Context) error
- type Source
- type Strategy
- type TransactionResolver
Constants ¶
const RecommendedMaxPayloadBytes = 1 << 20 // 1 MiB
RecommendedMaxPayloadBytes is the recommended value to pass to the runtime's WithMaxPayloadBytes when consuming from a sql source (ADR 0010 D7). The byte cap is a runtime concern, not an adapter default — the adapter never sees the typed payload and cannot divert an over-size row — so the sql package ships this copy-pasteable recommendation (1 MiB) rather than forcing a default. A DB message table is populated by trusted producers, so it is less exposed than an untrusted network firehose; size this to your largest legitimate message.
const UnboundedGroupMembers = -1
UnboundedGroupMembers is the ONLY value of GroupDialect.AddMember's maxMembers that requests an UNBOUNDED group — one whose member table may grow without limit. Every other non-positive value, INCLUDING 0, is rejected by ValidateMaxMembers with msgin.ErrInvalidCapacity.
Who would pass it, and what they are accepting ¶
A DIRECT caller of the GroupDialect SPI that has not adopted Spec 017's per-group bound — a caller driving AddMember on its own *sql.Tx, or a migration running against groups that already exceed any cap it would choose. sql.GroupStore never passes it: NewGroupStore range-checks WithMaxGroupMembers to [1, 1048576] at construction, so a store-driven flow cannot reach this value at all.
The risk is the whole of what Spec 017 exists to close. With no bound, one correlation key whose release never fires accumulates member rows forever; each AddMember re-SELECTs the group's entire live set, so the per-arrival cost is linear in the group and the total cost quadratic. There is no back pressure and no diagnostic — the table simply grows.
Why -1 and not 0 (ADR 0033 D-AV) ¶
The zero value must not be the dangerous value. maxMembers is a POSITIONAL SPI parameter, so an omitted or unset-config-field argument arrives as 0 with no signal that anything was omitted; making 0 mean "unbounded" turned that mistake into a silent fail-open. -1 has to be typed on purpose. (Contrast endpoint.WithMaxPayloadBytes, whose `n <= 0 disables` is defensible because it is reached through an OPTION, where omission genuinely means "unset".)
Variables ¶
var ( // ErrInvalidTableName is returned when a table identifier fails validation // against ^[A-Za-z_][A-Za-z0-9_]*$. The table name cannot be a bound // parameter, so it is validated and dialect-quoted before interpolation; // an invalid identifier is refused up front rather than interpolated into // SQL (ADR 0010 D3, closing the only injection surface). ErrInvalidTableName = errors.New("msgin/sql: invalid table name") // ErrSchemaNotReady reports that the adapter's table is not initialized — // the caller has not applied the reference DDL (see postgres.DDL / // mysql.DDL) or called EnsureSchema. It is exported so callers can // errors.Is it; the source and outbound wrap it naming the offending table // (ADR 0010 D2). ErrSchemaNotReady = errors.New("msgin/sql: schema not ready") // ErrNilDialect is a construction error from NewPollingSource, // NewOutboundAdapter, and NewInboxDeduper when the required dialect argument // is nil. The dialect is an explicit, required constructor argument (ADR // 0011) — there is no driver auto-detect to fall back on — so a nil dialect // is refused up front rather than deferring a nil-pointer panic to the first // Poll/Send/MarkProcessed. ErrNilDialect = errors.New("msgin/sql: nil dialect") // ErrInvalidLeaseTTL is a construction error from NewPollingSource when // WithLeaseTTL is given a non-positive duration. Unset leaves the safe 5m // default in place; an explicit non-positive value is a caller mistake, not a // request for the default (ADR 0010 D4). ErrInvalidLeaseTTL = errors.New("msgin/sql: lease TTL must be > 0") // ErrStaleLease is returned by a Source delivery's Ack/Nack closure when the // fenced settle matched no row — the handler outran the lease TTL and another // worker re-claimed the message (a different lease_epoch). It is NON-nil by // design so the runtime suppresses the phantom OnAck/eviction for a settle // this worker did not actually perform; the row is safely owned by the worker // that re-leased it and will be settled there. It is exported so callers can // errors.Is it in logs/hooks (ADR 0010 D4). ErrStaleLease = errors.New("msgin/sql: stale lease; message was re-claimed by another worker") // ErrInvalidStrategy is a construction error from NewPollingSource when // WithStrategy is given a value outside the defined Strategy range // (StrategyLeaseClaim, StrategyLockForUpdate). Unset leaves the safe // lease/claim default in place; an out-of-range value is a caller mistake, // not a request for the default (ADR 0010 D5). ErrInvalidStrategy = errors.New("msgin/sql: invalid strategy") // ErrLockStrategyUnsupported is a construction error from NewPollingSource // when WithStrategy(StrategyLockForUpdate) is selected but the resolved // LeaseDialect does not also implement LockDialect (the segregated lock/FOR // UPDATE SPI, ADR 0010 D5). The built-in postgres.LeaseDialect()/ // mysql.LeaseDialect() implement it; a custom lease-only LeaseDialect must // add LockDialect to be usable with the lock strategy. The wrapped message // names the offending dialect type. ErrLockStrategyUnsupported = errors.New("msgin/sql: lock strategy requires a LeaseDialect that implements LockDialect") // ErrInvalidPayload is returned by Outbound.Send when the message's payload // is not []byte. The Outbound is a wire adapter, not a LiveValueSource, so // endpoint.NewProducer always JSON-encodes T to []byte before calling Send; a // non-[]byte payload here means Send was invoked directly (bypassing the // producer) with the wrong payload shape — a defensive case trusted // producers do not hit (ADR 0010 D8). ErrInvalidPayload = errors.New("msgin/sql: outbound payload must be []byte") // WithSharedTransaction (the strict mode), when the injected // TransactionResolver reports no caller transaction present in ctx // ((nil, nil)). Strict mode never silently dual-writes: it refuses the // standalone insert and returns this error instead, so a caller that // forgot to thread its business tx into ctx fails loudly rather than // silently losing the outbox's atomicity guarantee. Use // WithOpportunisticSharedTransaction to fall back to a standalone insert // instead (ADR 0010 D8). ErrNoSharedTransaction = errors.New("msgin/sql: no shared transaction in context") // ErrNilResolver is a construction error from NewOutboundAdapter when // WithSharedTransaction or WithOpportunisticSharedTransaction is given a // nil TransactionResolver. Caught at construction time rather than // deferred to the first Send, which would otherwise panic on a nil-func // call (ADR 0010 D8). ErrNilResolver = errors.New("msgin/sql: nil TransactionResolver") // ErrNilTx is returned by InboxDeduper.MarkProcessed when the caller's // business transaction is nil. MarkProcessed records the dedup row inside // the caller's tx by design (ADR 0010 D10) — the concrete *sql.Tx type // already bars passing the auto-committing pool — so a nil tx is refused up // front with this typed error rather than dereferenced into a panic // (upholding the no-panic-on-caller-input rule). ErrNilTx = errors.New("msgin/sql: nil transaction") // ErrInvalidRetention is returned by InboxDeduper.Purge when olderThan is // non-positive. A non-positive retention would set the delete cutoff to // now() (or the future), purging the ENTIRE inbox — after which every id // reads already=false on redelivery and is double-processed, the exact // failure the deduper exists to prevent. So it is refused up front (before // any DB call) rather than executed. A positive olderThan is still the // caller's responsibility to size above the source's max redelivery window // (see Purge's godoc). It is exported so callers can errors.Is it (ADR 0010 // D10 MEDIUM, hardened per the Task 10 review). ErrInvalidRetention = errors.New("msgin/sql: retention (olderThan) must be > 0") // ErrInboxNoUniqueConstraint is returned by InboxDeduper.Ready when the inbox // table exists but its msg_id column carries NO unique/primary-key // constraint. Without it, MySQL/MariaDB's INSERT IGNORE never detects a // conflict, so the dedup silently never works (Postgres would already fail // loudly on ON CONFLICT). Ready probes for the constraint and fails fast with // this error (naming the table) so a mis-provisioned schema is caught at boot, // not after messages have been silently double-processed. The reference DDL // (see InboxDDL) provides the constraint. It is exported so callers can // errors.Is it (ADR 0010 D10, added per the Task 10 review, the user's robust // choice). ErrInboxNoUniqueConstraint = errors.New("msgin/sql: inbox msg_id column has no unique constraint") // ErrInboxInsertFailed is returned by the MySQL InboxDialect when an inbox // INSERT IGNORE affected no row AND a verifying SELECT finds no matching row // — meaning INSERT IGNORE demoted a genuine (non-duplicate) data error to a // warning (ADR 0010 D10 MEDIUM 6). The message is NOT deduplicated (which // would silently drop it); the error surfaces so the caller retries. It is // exported so callers can errors.Is it. Postgres has no equivalent path (its // ON CONFLICT ... RETURNING distinguishes insert from conflict exactly). ErrInboxInsertFailed = errors.New("msgin/sql: inbox insert did not take effect and is not a duplicate") // ErrMissingMsgID is returned by GroupStore.Add (and, defensively, by a // GroupDialect's own AddMember) when the message being added carries an // empty msgin.message-id. Group members are keyed (group_key, msg_id) for // idempotent, redelivery-safe add, so durable aggregation REQUIRES message // ids (audit R1 H3, ADR 0021 §2) — a source delivery always carries // msgin.HeaderMessageID and the Splitter stamps a deterministic child id, so this // is not a real-world restriction. GroupStore.Add checks this at the // facade (belt-and-suspenders with the dialect's own check) so the error // is returned before any query runs. ErrMissingMsgID = errors.New("msgin/sql: group member requires a non-empty message id") )
Functions ¶
func BeginLockTx ¶
BeginLockTx is part of the LockDialect-author SPI (ADR 0010 D5, ADR 0011): it resolves the transaction that will carry a lock delivery from q, the Querier a dialect's ClaimLock receives. It is the shared helper every LockDialect implementation's ClaimLock calls to open its carried transaction.
- q is the pool (*sql.DB, the txBeginner path — the Source always passes the pool): begins a NEW transaction on ctx.
- q is already an open *sql.Tx (a defensive/future path): carried directly, unchanged — the caller retains ownership of committing/rolling it back.
- q is neither: a clear, wrapped error naming the actual type — never a panic or a silently-nil transaction.
Neither of the first two cases is an error. ctx drives BeginTx, so the caller controls the transaction's cancellation lifetime; the Source passes a cancellation-detached context so graceful shutdown does not auto-rollback an in-flight claim before the drain deadline (ADR 0010 D5 HIGH 3).
func DecodeHeaders ¶
DecodeHeaders reconstructs Headers from the framed JSON bytes written by EncodeHeaders, per the on-wire format documented on EncodeHeaders (the stability contract): msgin.timestamp is parsed back to a time.Time, msgin.delivery-count back to an int, and (ADR 0021 §2 M-1) msgin.sequence-number / msgin.sequence-size back to an int. Custom keys are returned with the types JSON produces (a numeric custom header comes back as float64 — the standard encoding/json behavior, so callers store immutable, JSON-round-trippable values). Empty input yields empty Headers; malformed JSON is an error.
func EncodeHeaders ¶
EncodeHeaders frames a message's Headers into the JSON bytes stored in the headers column (spec 001 §8 — envelope framing, type-agnostic).
On-wire header format (stability contract) ¶
This is public API: the JSON shape below is a stability contract that a custom LeaseDialect, an external tool, or a direct reader of the headers column may depend on. A single JSON object maps each header key to its value, with two reserved keys normalized so they round-trip losslessly:
- msgin.timestamp is written as an RFC3339 (nanosecond) string. A time.Time would otherwise marshal to a string that DecodeHeaders could not restore to a time.Time.
- msgin.delivery-count, msgin.sequence-number, and msgin.sequence-size are each written as a JSON number and restored to an int by DecodeHeaders (ADR 0021 §2 M-1).
All other keys — the reserved string keys (msgin.message-id, msgin.content-type, msgin.correlation-id) and any custom keys — are marshaled as-is; a numeric custom value therefore returns as float64 (the standard encoding/json behavior). A value JSON cannot marshal (a channel, a func) surfaces as an error rather than being silently dropped.
EncodeHeaders/DecodeHeaders are the only serialization the adapter performs.
func SettleLockTx ¶
SettleLockTx is part of the LockDialect-author SPI (ADR 0010 D5, ADR 0011): it runs the settle statement on the carried transaction tx (opened by BeginLockTx) and commits it, closing the transaction exactly once. Every LockDialect implementation's AckLock/NackLock calls this to settle.
The contract a dialect author relies on: this ALWAYS commits on success and ALWAYS rolls back on any error, so a dialect's AckLock/NackLock never leaks a pooled connection regardless of which statement or commit fails. This is the lock strategy's ALWAYS-COMMIT settle path (ADR 0010 D5): AckLock (DELETE) and NackLock (clear-lock UPDATE) both commit on success, because the strategy has no business writes to undo — a successful settle persists (the Ack's delete or the Nack's delivery_count++/visible_after) and releases the FOR UPDATE lock.
func ValidateIdent ¶
ValidateIdent returns ErrInvalidTableName unless name matches identPattern (^[A-Za-z_][A-Za-z0-9_]*$ — no quote, semicolon, or whitespace). It is part of the dialect-author SPI (ADR 0010 D3, ADR 0011): every LeaseDialect/ InboxDialect method and every reference-DDL builder validates its table (or derived index) identifier with ValidateIdent BEFORE dialect-quoting and interpolating it into SQL — the identifier cannot be a bound parameter, so this is the sole injection guard. A dialect author implementing a new LeaseDialect/InboxDialect MUST call ValidateIdent first in every method that takes a table name.
func ValidateMaxMembers ¶
ValidateMaxMembers reports whether maxMembers is a legal GroupDialect.AddMember bound: it must be UnboundedGroupMembers, or in [1, 1048576] (maxGroupMembersCeiling — the same ceiling WithMaxGroupMembers enforces at construction). Anything else is a typed msgin.ErrInvalidCapacity naming site, the offending value, the accepted range and the sentinel.
Every GroupDialect implementation MUST call it BEFORE any statement runs — the same validate-before-I/O placement ErrMissingMsgID has. It lives here, once, rather than being copy-pasted into postgres/mysql/sqlite, so the parameter's contract is executable in ONE place instead of prose in three (ADR 0033 D-AV; Spec 017 §3.6a.2). site is the calling dialect's own "msgin/sql/<engine>: AddMember" string, so an operator learns which engine was driven with the bad bound.
It rejects 0, and that is the point ¶
maxMembers <= 0 once meant UNBOUNDED, which made the ZERO VALUE the dangerous value on an exported SPI. It now means "invalid"; opting out is spelled UnboundedGroupMembers. This is a behavioral break for a direct dialect caller that passed 0 — loud, one line to fix, and free at pre-v1.
It keeps the cap comparison reachable at every accepted value ¶
Before this check, AddMember(…, math.MaxInt, …) delivered NO bound at all, by two independent routes (whole-branch review finding R-15). Only ONE of them still exists, so this section says which:
- SURVIVING, and the reason this check is still load-bearing: the cap comparison `n > int64(maxMembers)` can never fire at math.MaxInt, since no group can hold more rows than that. Nothing structural prevents it — only this validator does, by keeping maxMembers in [1, 1048576].
- GONE, structurally: the dialects used to derive a live-member fetch limit as maxMembers+1, which overflowed to math.MinInt so the `limit > 0` guard emitted no LIMIT clause. That derivation no longer exists. Finding R-1 showed the LIMIT truncated the snapshot whenever a group held more rows than the CURRENT cap (a lowered cap, or two instances disagreeing), so AddMember's live fetch is now unlimited, joining ClaimGroup and ExpiredGroups (ADR 0033 D-AS). There is no sum left to overflow.
The rejection is msgin.Permanent, unlike checkRange's constructor arms ¶
The other msgin.ErrInvalidCapacity producers are OPTION validators, whose error is handed back at construction and never carried through a MessageHandler, so they stay bare (ADR 0029 D-M). This one is returned from AddMember — a per-message hot-path surface. An invalid constant argument fails identically on every redelivery, so a transient classification would Nack-loop with no delay and no log under the shipped zero-value msgin.RetryPolicy (the B-1 hot spin D-AM and D-AU both exist to prevent). Permanent settles it terminally instead. errors.Is(err, msgin.ErrInvalidCapacity) is unaffected — permanentError unwraps transparently. This mirrors ADR 0031 D-V, which likewise wraps a sizing fault in Permanent when it surfaces at USE time rather than at construction.
Types ¶
type ClaimedGroup ¶
type ClaimedGroup struct {
GroupRows
// Epoch is the fence token stamped on the claimed member set and the group
// row's lease. SettleGroup/AbandonGroup take effect only while the group's
// current epoch still matches; a lease that expired and was re-claimed
// (epoch bumped) makes a stale holder's settle/abandon a no-op.
Epoch int64
}
ClaimedGroup is a GroupRows frozen at claim time, plus the fence epoch ClaimGroup assigned it. Members is the CLAIMED set (claimed_epoch == Epoch), not the live set — a member that arrives after the claim is NOT included and survives as a fresh residual group (ADR 0021 §2 "Why claimed_epoch on members").
type ClaimedRow ¶
type ClaimedRow struct {
ID int64
MsgID string
Headers []byte
Payload []byte
DeliveryCount int
LeaseEpoch int64
}
ClaimedRow is one row returned by LeaseDialect.Claim: the persisted envelope plus the lease bookkeeping. Headers and Payload are the raw framed bytes (JSON headers, wire body); the runtime, not the adapter, decodes the payload into its typed value. DeliveryCount is the post-increment claim count (populates the msgin.delivery-count header); LeaseEpoch is the fence token used to make Ack/Nack idempotent against an expired-and-reclaimed lease.
type GroupDialect ¶
type GroupDialect interface {
// AddMember durably, idempotently appends one member to the group table,
// in ONE transaction: it upserts the group row (created_at set once, via
// the DB server clock — never a caller-supplied now) with a statement
// that SERIALIZES concurrent same-key adds BEFORE any member row is read
// or written — by a group-row lock on postgres and mysql, by BEGIN
// IMMEDIATE's database-wide write lock on sqlite (ADR 0033 D-AP; there
// is no one mechanism, and an implementer for a new engine must supply
// one of their own). Serialization is required, not stylistic (audit R1
// H1: under READ COMMITTED, two processes each adding one member of a
// size-N group would otherwise each snapshot only their own
// uncommitted-elsewhere member and neither would observe completion). It
// then upserts the member row (ON CONFLICT(group_key,msg_id) DO NOTHING
// / INSERT IGNORE, so a redelivered member is a no-op), and finally
// SELECTs the group's current CreatedAt plus its LIVE members
// (claimed_epoch IS NULL), ordered by seq then msg_id. Commits
// atomically. An empty msgID is rejected with a typed error
// (ErrMissingMsgID) BEFORE any statement runs — audit R1 H3, durable
// aggregation requires message ids. seq is msgin.HeaderSequenceNumber (0
// if the member's headers carried none); headers/payload are the
// already-framed bytes (EncodeHeaders output / runtime-codec wire body)
// to persist verbatim.
//
// # The member cap is enforced IN THIS TRANSACTION (Spec 017 §3.6)
//
// maxMembers is the bound on how many members ONE group may hold —
// sql.GroupStore threads its WithMaxGroupMembers here. AFTER the member
// upsert (so an idempotent re-add of an existing id at exactly the cap
// stays a no-op), the implementation MUST count EVERY member row for the
// key — LIVE AND CLAIMED, i.e. SELECT count(*) with no claimed_epoch
// predicate — and, if that count exceeds maxMembers, MUST abort the
// transaction and return msgin.ErrOverflowDropped wrapped as
// "%w: msgin/sql/<engine>: AddMember: group %q holds %d members, limit %d".
// Counting only the live set does not bound anything: ClaimGroup stamps
// every live member, so the next maxMembers arrivals see an empty live
// set and the table grows by maxMembers per claim cycle, forever.
//
// The rejection is classified by whether the group's lease is LIVE, using
// the SAME predicate the implementation's own ClaimGroup steals on —
// locked_by IS NULL OR locked_at <= now() - leaseTTL, evaluated on the DB
// SERVER CLOCK, never the app clock. An expired-or-absent lease means
// nothing will drain the group on its own, so the error MUST be wrapped
// in msgin.Permanent and the runtime settles it terminally instead of
// hot-spinning on the shipped zero-value msgin.RetryPolicy; a LIVE lease
// means a claim is in flight that will drain it, so the error stays bare
// and transient.
//
// 🔴 TESTING locked_by ALONE IS NOT ENOUGH, and that is why leaseTTL is a
// parameter (ADR 0033 D-AU, whole-branch review finding R-7). A non-NULL
// locked_by proves a row was STAMPED, not that a holder is alive: a
// crashed or stranded releaser leaves the group leased with nothing
// draining it, and every subsequent over-cap add is then classified
// transient FOREVER — the exact infinite zero-delay Nack loop this
// classification exists to prevent.
//
// The group's remaining LIVE members SHOULD be returned in the GroupRows
// ALONGSIDE that error, with the just-upserted member filtered out, so
// the Aggregator can re-evaluate its release strategy against a group
// that is full but complete (Spec 017 §3.3a).
//
// maxMembers MUST be validated with ValidateMaxMembers BEFORE any
// statement runs — the same validate-before-I/O placement ErrMissingMsgID
// has. The accepted set is UnboundedGroupMembers or [1, 1048576]; 0 is an
// ERROR, not a synonym for unbounded (ADR 0033 D-AV). Only
// UnboundedGroupMembers skips the count, and it cannot arrive from
// sql.GroupStore, whose constructor rejects anything outside
// [1, 1048576]; it exists so a direct dialect caller that has not opted
// into a bound can keep the pre-Spec-017 behavior — explicitly, and at
// the risk UnboundedGroupMembers documents.
//
// # PRECONDITION: the rollback is only ours when the transaction is
//
// The cap is enforced BY ROLLBACK, and a dialect only rolls back a
// transaction it OWNS — the one it begins when q is a *sql.DB. When a
// DIRECT caller passes its own *sql.Tx as q, the dialect runs on that
// transaction and neither commits nor rolls it back: the over-cap member
// row is already inserted into the caller's open transaction when the
// error is returned. Such a caller MUST treat msgin.ErrOverflowDropped as
// a rollback trigger; committing anyway exceeds the cap durably. A
// library must not roll back a transaction it cannot see the rest of, so
// this is stated rather than engineered away. It does not apply to
// sql.GroupStore, which always owns its transaction (see
// WithMaxGroupMembers).
AddMember(ctx context.Context, q Querier, table, groupKey, msgID string, seq int64, headers, payload []byte, maxMembers int, leaseTTL time.Duration) (GroupRows, error)
// ClaimGroup atomically leases the group's current members, in ONE
// transaction: it bumps the group row's epoch and stamps
// locked_by/locked_at (the DB server clock), FENCED so the UPDATE
// matches only when the row is unleased or its existing lease has aged
// past leaseTTL — exactly one concurrent claimant's UPDATE affects a row
// (the winner). The winner is detected by rowsAffected==1 (a dialect MAY
// additionally use RETURNING where the engine supports it; a dialect
// without RETURNING reads the bumped epoch via a SELECT inside the SAME
// transaction, while the row lock from the UPDATE is still held — never
// a separate-transaction read another claimant could race, audit R1
// M3). It returns (nil, nil), with NO error and NO transaction side
// effects, when the group is absent or is actively (unexpired) leased by
// another holder.
//
// Having won, ClaimGroup RE-ABSORBS a possibly-superseded prior claim's
// members (audit R1 H2): it stamps claimed_epoch = the NEW epoch on
// every member row where claimed_epoch IS NULL OR claimed_epoch <
// newEpoch — NOT merely IS NULL. Tagging only IS NULL would leave a
// CRASHED holder's already-tagged-but-never-settled members permanently
// orphaned (the re-claim would see zero members, emit nothing, and the
// real members are neither emitted nor deleted — a silent, permanent
// loss). Because the group-row lease fence guarantees at most one ACTIVE
// claim at a time, every claimed_epoch < newEpoch is provably a dead
// (crashed or already-settled-elsewhere) claim and is always safe to
// re-absorb — this re-absorption is what makes "a crashed holder's
// lease ages out, another worker re-claims" resolve to a duplicate
// (safe, at-least-once), never a loss. It then SELECTs the newly-claimed
// member set (claimed_epoch == newEpoch), ordered by seq then msg_id,
// and returns it with the new epoch as *ClaimedGroup. Commits
// atomically.
ClaimGroup(ctx context.Context, q Querier, table, groupKey, lockedBy string, leaseTTL time.Duration) (*ClaimedGroup, error)
// SettleGroup finalizes a successful release, in ONE transaction: it
// LOCKS THE GROUP ROW FIRST (SELECT ... FOR UPDATE or equivalent —
// uniform group-then-member lock order, audit R2 H-B, see the interface
// doc's "Lock order" section), then DELETEs only the CLAIMED member set
// (claimed_epoch == epoch) — never a blind delete by group_key, so a
// member that arrived during the lease (claimed_epoch still NULL)
// survives untouched. If members remain after the delete (a residual —
// exactly that late-arrival case), it clears the group row's lease
// (locked_by/locked_at = NULL) AND RESETS created_at to the DB server
// clock — audit R1 M2, so the residual is treated as a FRESH group for
// expiry purposes, matching memory.GroupStore's residual semantics.
// Otherwise (no members remain) it deletes the group row entirely. The
// whole operation is FENCED on (group_key, locked_by, epoch): a lease
// that expired and was re-claimed (a bumped epoch, or a different
// locked_by) makes this call a no-op. applied reports whether the fence
// matched (true) or missed (false, nil error — a fence miss is not an
// error; it means another holder already owns or settled this group).
SettleGroup(ctx context.Context, q Querier, table, groupKey, lockedBy string, epoch int64) (applied bool, err error)
// AbandonGroup releases a claim WITHOUT deleting anything, in ONE
// transaction: it LOCKS THE GROUP ROW FIRST (same order as SettleGroup,
// audit R2 H-B), un-tags the claimed member set (claimed_epoch = NULL
// for rows where claimed_epoch == epoch, so they return to LIVE — a
// retry or the next AddMember/reaper tick sees them again), and clears
// the group row's lease (locked_by/locked_at = NULL) — the epoch itself
// is left bumped, so a stale holder's later Settle/Abandon on the OLD
// epoch still fences correctly as a no-op. FENCED on
// (group_key, locked_by, epoch), exactly like SettleGroup: applied is
// false (nil error) on a fence miss.
AbandonGroup(ctx context.Context, q Querier, table, groupKey, lockedBy string, epoch int64) (applied bool, err error)
// ExpiredGroups returns the groups the Aggregator's reaper sweep must
// re-examine (audit R2 H-A — the crash-recovery mechanism): every group
// whose LEASE has expired — locked_by IS NOT NULL AND the DB server
// clock now() - locked_at > leaseTTL (a crashed holder), REGARDLESS OF
// AGE — PLUS, only when before is non-zero, every UNLEASED group whose
// created_at is strictly before before (the age-based expiry path).
// Currently-actively-leased groups (an unexpired lease) are EXCLUDED in
// both cases — they are being actively worked. Each returned GroupRows
// carries the group's current LIVE members (claimed_epoch IS NULL),
// ordered by seq then msg_id; results are ordered oldest-created_at
// first and capped at limit. A zero before value means "crash-recovery
// sweep only" (no age-based candidates) — callers running a store with
// no configured expiry timeout still get crash recovery this way.
ExpiredGroups(ctx context.Context, q Querier, table string, before time.Time, leaseTTL time.Duration, limit int) ([]GroupRows, error)
// EnsureGroupSchema idempotently creates the two-table schema (CREATE ...
// IF NOT EXISTS — both the group-lease table and its member table) and
// any supporting index. It is optional and opt-in; msgin never runs DDL
// implicitly on the production path (mirrors LeaseDialect.EnsureSchema).
EnsureGroupSchema(ctx context.Context, q Querier, table string) error
// SchemaExists reports whether the group-lease table exists, via a
// portable information_schema probe that imports no SQL driver (mirrors
// LeaseDialect.SchemaExists / InboxDialect.SchemaExists).
SchemaExists(ctx context.Context, q Querier, table string) (bool, error)
}
GroupDialect is the exported SPI a caller supplies, as the required dialect argument to NewGroupStore, to teach sql.GroupStore a database's exact group-aggregation SQL — a NEW, segregated interface (interface-segregation, like InboxDialect vs LeaseDialect): group-keyed idempotent add, a per-group lease, claimed-set fencing, and an expiry scan are not row-oriented queue operations, so they do not belong on LeaseDialect, and a LeaseDialect author must not be forced to implement them (ADR 0021 §3). The built-ins are postgres.GroupDialect(), mysql.GroupDialect() (covers MariaDB), and sqlite.GroupDialect(), each in its own module.
Every method fully owns its statement(s) and any multi-statement transaction orchestration; no cross-dialect SQL ever runs. Every method validates table with ValidateIdent BEFORE dialect-quoting and interpolating it into SQL — the table identifier cannot be a bound parameter, so this is the sole injection guard (mirrors LeaseDialect/InboxDialect). table is the BASE identifier from which a dialect derives BOTH the two-table schema's names (ADR 0021 §2) — the group-lease table and its append-only member table (e.g. table and a dialect-owned derived name such as table+"_member"); the exact derivation is a dialect implementation detail, documented by each built-in. All persisted timestamps and lease/expiry comparisons use the DB server clock (now()), never the app clock, and leaseTTL is passed as an interval-typed duration parameter — no app<->DB skew (ADR 0010 D3/D4, reused here).
Lock order (deadlock avoidance) ¶
Every multi-statement method that touches both tables acquires the GROUP row lock (SELECT ... FOR UPDATE, or the engine's equivalent) BEFORE any member row is read or written, uniformly across AddMember, ClaimGroup, SettleGroup, and AbandonGroup. A member-first lock in any one method would let it ABBA-deadlock against a group-first method under concurrent load (ADR 0021 §4 "Settle / Abandon are fenced AND lock the group row FIRST", audit R2 H-B) — implementers MUST preserve this order.
Message ids are required ¶
Members are keyed (group_key, msg_id): AddMember rejects an empty msgID with a typed error (audit R1 H3) rather than silently colliding id-less members into one row. Durable aggregation therefore requires message ids — source deliveries carry msgin.HeaderMessageID and the Splitter stamps a deterministic child id, so this is not a real-world restriction (ADR 0021 §2).
A dialect author implementing GroupDialect for a new engine or wire-compatible derivative should add a compile-time assertion:
var _ msginsql.GroupDialect = (*yourDialect)(nil)
This is a pre-1.0 (v0) contract that may still evolve.
type GroupRows ¶
type GroupRows struct {
// GroupKey is the correlation key (msgin_group.group_key).
GroupKey string
// CreatedAt is the group's arrival-time clock, used for expiry: the first
// member's arrival, or (after a SettleGroup residual reset) the residual's
// reset time. Always the DB server clock — never the app clock.
CreatedAt time.Time
// Members are the group's live (claimed_epoch IS NULL) members, ordered by
// seq then msg_id.
Members []MemberRow
}
GroupRows is one correlation group plus its LIVE (unclaimed) members, as raw framed bytes — the carrier a GroupDialect method returns and sql.GroupStore decodes into a msgin.MessageGroup. Mirrors ClaimedRow's raw-bytes contract: Headers/Payload are the exact framed bytes written by AddMember (EncodeHeaders output / the runtime-codec wire body); the store, not the dialect, decodes them. Members are ordered by seq then msg_id (ADR 0021 §2 "Ordering").
type GroupStore ¶
type GroupStore struct {
// contains filtered or unexported fields
}
GroupStore is a durable, multi-process-safe msgin.MessageGroupStore backed by a database/sql table pair (ADR 0021): correlation-keyed groups of held messages, with a store-level atomic lease-claim (GroupDialect.ClaimGroup) that makes an Aggregator's release exactly-once WITHIN and ACROSS processes. It is a WIRE store (EmitsLiveValue()==false): headers are JSON-framed (EncodeHeaders/DecodeHeaders) and payloads are the runtime-codec []byte body, identical to sql.Outbound / sql.QueueStore — the paired typed runtime encodes/decodes (ADR 0001).
Delivery guarantee: at-least-once across restarts AND across processes. A crash between ClaimGroup and SettleGroup is recovered by lease expiry -> re-claim -> re-release (a duplicate emit, never a loss — ADR 0020 §8). Message ids are REQUIRED: Add rejects a message whose msgin.message-id is empty with ErrMissingMsgID (members are keyed (group_key, msg_id) for idempotent, redelivery-safe add — audit R1 H3). Source deliveries always carry msgin.HeaderMessageID and the Splitter stamps a deterministic child id, so this is not a real-world restriction.
go agg.Run(ctx) is REQUIRED for crash-recovery with a durable store ¶
RecoverInterval reports this store's configured lease TTL (not 0, unlike memory.GroupStore — audit R2 H-A), so an Aggregator built over a GroupStore only ever crash-recovers a stuck complete group (re-emitting it to the OUTPUT channel) if its reaper is actually running. A caller using sql.GroupStore for multi-process/crash safety MUST run go agg.Run(ctx), even with no WithGroupTimeout configured.
func NewGroupStore ¶
func NewGroupStore(db *stdsql.DB, table string, dialect GroupDialect, opts ...GroupStoreOption) (*GroupStore, error)
NewGroupStore builds a durable GroupStore over table on db, using dialect to generate the exact group-aggregation SQL (ADR 0021 §3 — dialect is a required, explicit constructor argument; there is no driver auto-detect, matching NewPollingSource/NewOutboundAdapter). table is the BASE identifier GroupDialect derives its two-table schema from (see GroupDialect's doc). A nil db is msgin.ErrNilAdapter; a bad table identifier is ErrInvalidTableName; a nil dialect is ErrNilDialect; an explicit non-positive WithGroupLeaseTTL is ErrInvalidLeaseTTL; a WithMaxGroupMembers outside [1, 1048576] is msgin.ErrInvalidCapacity. Call Ready/EnsureSchema once at boot, exactly like the Source (ADR 0010 D2) — msgin never runs DDL implicitly on the production path.
A nil ELEMENT of opts is a bare msgin.ErrNilFunc naming the element's 0-based index ("sql.NewGroupStore: nil option at index 1"), not a panic — checked as opts is applied. In the order enumerated above the nil-option check comes FIRST: the apply loop is this constructor's first statement that can fail, preceded only by the config-defaults initializer, which cannot fail, so it runs before the nil-db, table-identifier, nil-dialect, WithGroupLeaseTTL and WithMaxGroupMembers checks, every one of which loses to it.
func (*GroupStore) AbandonGroup ¶
func (s *GroupStore) AbandonGroup(ctx context.Context, claim msgin.MessageGroupClaim) error
AbandonGroup releases claim's lease without deleting: it passes claim.Key(), s.lockedBy, and claim.Epoch() to GroupDialect.AbandonGroup. A dialect applied=false (fence miss) is NOT an error, matching the core contract.
func (*GroupStore) Add ¶
func (s *GroupStore) Add(ctx context.Context, key string, msg msgin.Message[any]) (msgin.MessageGroup, error)
Add durably appends msg to group key: it frames msg's headers (EncodeHeaders) and requires a []byte payload (ErrInvalidPayload otherwise — GroupStore is a wire adapter, mirroring Outbound.Send/SendAfter; the paired runtime always encodes T to []byte before Add is reached), rejects an empty msgin.message-id with ErrMissingMsgID BEFORE any query runs (H3, belt-and-suspenders with GroupDialect.AddMember's own check), and delegates to GroupDialect.AddMember on the pool, threading the configured WithMaxGroupMembers cap AND the configured WithGroupLeaseTTL — exactly as ClaimGroup and ExpiredGroups already thread the latter (ADR 0033 D-AU). It returns the resulting group snapshot of the LIVE (unclaimed) members, decoded from the dialect's raw framed bytes.
The member-cap rejection carries a snapshot ¶
When the dialect refuses the member because the group is at its cap it returns msgin.ErrOverflowDropped — msgin.Permanent-wrapped when NO LIVE LEASE is draining the group (no lease at all, or one already aged past WithGroupLeaseTTL on the DB server clock), bare while a live claim is in flight (WithMaxGroupMembers, ADR 0033 D-AU) — TOGETHER with the group's post-rollback live members. Add propagates BOTH, so routing.Aggregator.Handle can re-evaluate the release strategy against a group that is complete but was never re-triggered (Spec 017 §3.3a). Only the overflow rejection carries a snapshot; every other dialect failure keeps the (nil, err) shape, as does an overflow whose members cannot be decoded.
That re-evaluation is CONDITIONAL, and this store is written to satisfy the conditions rather than to rely on them (Spec 017 §3.3a.1). Handle acts on a snapshot only when the error carries msgin.ErrOverflowDropped — which is precisely why the (nil, err) shape above is kept for every other fault — and it ignores a snapshot that is nil (TYPED NILS INCLUDED) or that holds zero members, returning the error unchanged in both cases. A zero-member snapshot here is not a defect: while a claim covers every member the live residual is legitimately empty, and Handle then reports the dialect's rejection as-is rather than running the release strategy against an empty group.
That pass-through carries WHICHEVER classification the dialect chose, which is NOT always the transient one. A claim that covers every member but whose holder has CRASHED leaves the same empty residual, and once its lease ages past WithGroupLeaseTTL the dialect classifies as msgin.Permanent — so the error Handle passes through terminally settles the member (see WithMaxGroupMembers' CLASSIFICATION section for the full timeline).
The error still routes through classifyQueryErr, which costs one extra SchemaExists round-trip. Both the sentinel and the Permanent marker survive it while the table exists; a genuinely dropped table wins and surfaces as ErrSchemaNotReady, which is the correct diagnosis. Because that diagnosis REPLACES the rejection rather than wrapping it, the snapshot goes with it: the whole branch is gated on the CLASSIFIED error, so a table dropped concurrently with an over-cap Add returns (nil, ErrSchemaNotReady) and never pairs a group with an error that no longer states the overflow contract.
func (*GroupStore) ClaimGroup ¶
func (s *GroupStore) ClaimGroup(ctx context.Context, key string) (msgin.MessageGroupClaim, error)
ClaimGroup atomically leases the group's current members via GroupDialect.ClaimGroup, passing this store's configured lockedBy and leaseTTL. It returns (nil, nil), with no error, when the dialect reports the group absent or actively (unexpired) leased by another holder — the caller then treats the group as held. A non-nil claim is decoded from the dialect's raw framed bytes, with Epoch wired from ClaimedGroup.Epoch.
func (*GroupStore) EmitsLiveValue ¶
func (s *GroupStore) EmitsLiveValue() bool
EmitsLiveValue reports false: GroupStore is a wire store ([]byte payloads, JSON-framed headers) — the paired typed runtime encodes/decodes (ADR 0001).
func (GroupStore) EnsureSchema ¶
EnsureSchema idempotently creates the two-table group schema. It is optional and opt-in (dev/test/opt-in callers); production callers provision the schema via the reference DDL (postgres.GroupDDL / mysql.GroupDDL / sqlite.GroupDDL) instead — msgin never runs DDL implicitly (ADR 0010 D2, reused here).
func (*GroupStore) Expired ¶
func (s *GroupStore) Expired(ctx context.Context, before time.Time) ([]msgin.MessageGroup, error)
Expired returns the groups the Aggregator's reaper sweep must re-examine: GroupDialect.ExpiredGroups(before, s.leaseTTL, defaultExpiredGroupsLimit), decoded from raw framed bytes into []msgin.MessageGroup.
func (GroupStore) Ready ¶
Ready is the fail-fast boot check (ADR 0010 D2, reused here): it returns ErrSchemaNotReady (naming the table) when the schema is not initialized, so a forgotten migration fails the deploy immediately instead of the caller hitting it on the first Add/ClaimGroup. Call it once at startup.
func (*GroupStore) RecoverInterval ¶
func (s *GroupStore) RecoverInterval() time.Duration
RecoverInterval returns this store's configured lease TTL (default 5m — WithGroupLeaseTTL), NOT 0: unlike memory.GroupStore's unconditional in-process lease, a sql lease is TTL-bounded and can be stranded by a crash, so the Aggregator's reaper must sweep at this cadence to recover it (audit R2 H-A). See GroupStore's doc "go agg.Run(ctx) is REQUIRED" section.
func (*GroupStore) SettleGroup ¶
func (s *GroupStore) SettleGroup(ctx context.Context, claim msgin.MessageGroupClaim) error
SettleGroup finalizes a successful release: it passes claim.Key(), s.lockedBy, and claim.Epoch() to GroupDialect.SettleGroup. A dialect applied=false (the fence missed — the lease was stolen or already settled) is NOT an error, matching the core msgin.MessageGroupStore contract (SettleGroup's fence-miss is a no-op).
type GroupStoreOption ¶
type GroupStoreOption func(*groupStoreConfig)
GroupStoreOption configures a GroupStore built by NewGroupStore.
func WithGroupLeaseTTL ¶
func WithGroupLeaseTTL(d time.Duration) GroupStoreOption
WithGroupLeaseTTL sets how long a ClaimGroup lease is held before it is treated as expired and the group becomes claimable again by another worker (the Aggregator's recovery-sweep reaper, driven at RecoverInterval). Unset, it defaults to 5m — the SAME safe default as the Source's WithLeaseTTL, and deliberately NOT a tighter value: see defaultGroupLeaseTTL's doc for why aggregation's release needs an equal-or-more-generous margin than a Source handler's (ADR 0021 §4, audit R3 M1).
Invariant (read before overriding) ¶
leaseTTL MUST exceed the worst-case release round-trip: the aggregate function PLUS output.Send (which, on a DirectChannel, drives a whole synchronous downstream sub-flow) PLUS SettleGroup latency — a margin. If release can take longer than leaseTTL, another worker re-claims a STILL-LIVE group mid-release and the aggregate is sent to output TWICE (not merely duplicated-on-crash) — a double emit that recurs every recovery-sweep tick under persistent slowness. Because RecoverInterval() reports this same TTL, a longer TTL also means a crashed group is recovered roughly one TTL later — a caller needing snappier crash-recovery, whose release is reliably fast, may lower this value, accepting the tighter steal window.
A non-positive d is a construction error (ErrInvalidLeaseTTL) rather than a silent default: an explicit zero/negative is a caller mistake, not a request for the default.
func WithGroupLockedBy ¶
func WithGroupLockedBy(id string) GroupStoreOption
WithGroupLockedBy sets the lease-owner id stamped on ClaimGroup and matched by the fenced SettleGroup/AbandonGroup. Unset, it defaults to a random 128-bit hex id (the Source's randomLockedBy generator) — the safe choice, since each GroupStore instance then owns a distinct id and two instances (or two processes) never mistake each other's leases. Override it only when you need a stable, human-readable owner for observability and you guarantee uniqueness per running GroupStore. An empty string is treated as unset (the random default is used).
func WithMaxGroupMembers ¶
func WithMaxGroupMembers(n int) GroupStoreOption
WithMaxGroupMembers bounds the number of members ONE correlation group may hold to n, which must be in [1, maxGroupMembersCeiling] (1,048,576); default 65,536 (see defaultMaxGroupMembers for why that number). n outside the range is a construction-time error (msgin.ErrInvalidCapacity), not a silent clamp. It is the durable twin of memory.WithMaxGroupMembers and carries the same name deliberately — one SPI concept, one name.
WHAT IT COUNTS: every member ROW the database still holds for the key — LIVE plus CLAIMED. ClaimGroup stamps claimed_epoch on every live member without deleting anything, so claimed members keep counting until SettleGroup deletes them; a group at exactly n therefore rejects new arrivals for the duration of a claim, even though its live set is empty. That is what makes the bound a bound: counting live members only would let every claim cycle admit n more rows, forever (Spec 017 §3.4). The count rendered in the error is "members retained at the moment of the check", and this store checks AFTER the idempotent member upsert — required, so that a re-add of an existing id at exactly the cap stays a no-op — so at n = 4 it renders "holds 5 members, limit 4", one more than memory's twin, which checks before its append.
WHERE IT IS ENFORCED: inside the dialect's own transaction, before the commit, so the over-cap row is rolled back rather than merely reported (Spec 017 §3.6). For a store built by NewGroupStore this bound is UNCONDITIONALLY DURABLE — the store always owns the transaction the dialect runs in, because NewGroupStore takes a concrete *sql.DB and Add always passes it. (A DIRECT caller of GroupDialect.AddMember may supply its own *sql.Tx; that caller owns the rollback. See GroupDialect.AddMember's godoc — the caveat cannot apply to a caller of this option.) The check costs one extra SELECT count(*) per Add, on every add rather than only on overflow; on sqlite that scan runs inside BEGIN IMMEDIATE's database-wide write lock.
AT THE BOUNDARY: an Add that would take the group past n returns msgin.ErrOverflowDropped, wrapped with the engine-naming site, the group key, the count and the limit — e.g. "msgin/sql/postgres: AddMember: group \"k\" holds 5 members, limit 4". The member row is NOT committed. The live snapshot is returned ALONGSIDE the error so routing.Aggregator.Handle can still re-evaluate the release: the member is rejected, the release is not.
CLASSIFICATION — the rejection is classified by CAUSE, from whether a LIVE LEASE is draining the group. The discriminator is "locked_by IS NOT NULL AND locked_at > now() - WithGroupLeaseTTL", evaluated in SQL on the DB SERVER clock by the same statement that reads created_at, at zero extra round-trips (ADR 0033 D-AU, review finding R-7; Spec 017 §3.6a.1).
A non-NULL locked_by ALONE is NOT the test, and this godoc said it was until R-7: that reading calls a CRASHED holder's stranded lease "live" forever and classifies every subsequent over-cap add transient — the unlogged, zero-delay Nack loop the permanent arm exists to prevent.
- NO LIVE LEASE — no lease at all, or one already aged past WithGroupLeaseTTL: nothing is draining the group, so nothing drains it without an expiry cutoff (with no routing.WithGroupTimeout the reaper's cutoff is zero and ExpiredGroups returns crashed-lease groups only). The error is msgin.Permanent-wrapped, which the runtime settles TERMINALLY — one attempt at the invalid-message sink, or the dead-letter sink as a fallback, never a Nack. This is deliberate: a plain transient rejection on the SHIPPED zero-value msgin.RetryPolicy (no MaxAttempts, no Backoff) is an unlogged, zero-delay redelivery loop, and here each iteration is a full rolled-back write transaction taking the group-row lock plus a SchemaExists probe, multiplied by endpoint.WithConcurrency — all contending on the very row a recovery would have to lock. With NEITHER sink configured the runtime WARNs, naming both missing options, and then ACKs — so the source DROPS the message. Configure endpoint.WithInvalidMessageSink (or RetryPolicy.DeadLetter) to turn that loss into a capture; the library cannot supply one.
- A LIVE LEASE is in flight: a claim is running and Settle/Abandon runs on every release path, so the retry genuinely succeeds afterwards. The error stays transient (unwrapped). Under the zero-value RetryPolicy that retry is a busy-wait for the width of the claim window; set RetryPolicy.Backoff if that matters.
A CRASHED RELEASER TAKES BOTH ARMS IN TURN, and the second one DISCARDS. Take a holder that dies mid-release at t0 on a full group:
- t0 .. t0+leaseTTL — the stranded lease still reads LIVE, so over-cap adds are TRANSIENT and retried. No holder is left to settle it, so that retry cannot succeed until the lease ages out; this is the transient arm's tail, and it is bounded by leaseTTL (5 minutes at the shipped default).
- t0+leaseTTL onward — the lease reads DEAD, so the arms SWAP and every arriving member for that key is msgin.Permanent-wrapped and terminally settled. On the shipped defaults (zero-value msgin.RetryPolicy, no endpoint.WithInvalidMessageSink, no RetryPolicy.DeadLetter) that is a WARN and an Ack — the messages are DROPPED, not held. This lasts until the reaper recovers the group, up to t0 + 2 x leaseTTL (about 10 minutes at the shipped defaults). Two terms compose: ELIGIBILITY, at t0 + leaseTTL, when ExpiredGroups' locked_at <= now - leaseTTL arm first matches; and DISCOVERY, at the first reaper tick AT OR AFTER that moment. Aggregator.Run builds its ticker at Run's own start time on an interval that, with no WithGroupTimeout, equals RecoverInterval() — this store's lease TTL — so eligibility landing just after a tick waits a further full interval. Both terms presume go agg.Run(ctx) is running at all; without it the group is never recovered and the permanent arm has NO upper bound (see GroupStore's "go agg.Run(ctx) is REQUIRED" section).
Configuring a sink is what turns that second window from a drop into a capture; shortening WithGroupLeaseTTL is what shortens the window itself.
A group that is full and unreleasable stays full: this option bounds growth, it does not provide liveness. Set routing.WithGroupTimeout to have the reaper expire such a group.
🔴 LOWERING n BELOW A CONFIGURED routing.WithCompletionSize DEADLOCKS THE GROUP, and nothing rejects the pair. The two options live in different packages, so neither constructor can see the other: n = 10 with WithCompletionSize(20) constructs cleanly, then refuses every arrival past the 10th while the release predicate declines at 10 < 20 — each refused member dead-lettered, or DROPPED outright with neither endpoint.WithInvalidMessageSink nor RetryPolicy.DeadLetter configured, and the group never releasing. The default cap is >= routing's completionSizeCeiling precisely so this cannot happen unless you lower it (see defaultMaxGroupMembers' INVARIANT). Keep n at or above the completion size; routing.WithGroupTimeout is the liveness escape if you cannot. This store's RecoverInterval is its lease TTL rather than 0, so its reaper DOES sweep by default — but with no WithGroupTimeout the age cutoff is zero and the sweep surfaces crashed-lease groups only, never an unleased full one, so the deadlock is exactly as permanent here as in adapter/memory.
type InboxDeduper ¶
type InboxDeduper struct {
// contains filtered or unexported fields
}
InboxDeduper is the idempotent-consumer dedup inbox (ADR 0010 D10, durable consume strategy 2): the different-DB idempotent consumer. It records each processed msgin.message-id in a dedup table so a redelivery (msgin sources are at-least-once) can be recognized and its business effect skipped — turning at-least-once delivery into exactly-once effect.
It is deliberately independent of a Source: a handler consuming from ANY source (any adapter, any strategy) may adopt it, and it records into whatever business database the handler writes to — which need not be the message source's database. That is what makes it the cross-DB strategy: when business data lives in a different database than the source (so no single transaction can span both), dedup-by-id gives exactly-once effect without a shared tx.
The zero-config baseline stays plain at-least-once with the caller responsible for idempotency; adopting the deduper is an explicit opt-in (the handler calls MarkProcessed inside its business transaction).
func NewInboxDeduper ¶
func NewInboxDeduper(businessDB *stdsql.DB, dialect InboxDialect, opts ...InboxOption) (*InboxDeduper, error)
NewInboxDeduper builds an InboxDeduper over businessDB — the database the consuming handler writes its business changes to (NOT necessarily the message source's database; that different-DB case is the point of this strategy, ADR 0010 D10) — using dialect to generate the exact SQL (ADR 0011 — the dialect is a required, explicit constructor argument; there is no driver auto-detect). Pass postgres.InboxDialect() (adapter/database/sql/postgres), mysql.InboxDialect() (adapter/database/sql/mysql), or your own InboxDialect implementation. The dedup table defaults to "msgin_inbox" (WithInboxTable).
A nil businessDB is msgin.ErrNilAdapter; an invalid table identifier is ErrInvalidTableName; a nil dialect is ErrNilDialect — all at construction, so misuse fails loudly up front rather than on the first MarkProcessed.
A nil ELEMENT of opts is a bare msgin.ErrNilFunc naming the element's 0-based index ("sql.NewInboxDeduper: nil option at index 1"), not a panic — checked as opts is applied. It falls in the MIDDLE of the order enumerated above, because the apply loop does: the nil-option check runs AFTER the nil-businessDB check and loses to it, and BEFORE the table-identifier and nil-dialect checks, which both lose to the nil option. So NewInboxDeduper(nil, dialect, nil) is ErrNilAdapter, while NewInboxDeduper(db, nil, nil) is the nil-option error.
func (*InboxDeduper) EnsureSchema ¶
func (d *InboxDeduper) EnsureSchema(ctx context.Context) error
EnsureSchema idempotently creates the dedup table (and its processed_at retention index) via the dialect's CREATE ... IF NOT EXISTS. It is optional and opt-in (dev/test/opt-in callers); production callers provision the schema from the reference InboxDDL instead — msgin never runs DDL implicitly on the production path (ADR 0010 D2).
func (*InboxDeduper) MarkProcessed ¶
func (d *InboxDeduper) MarkProcessed(ctx context.Context, tx *stdsql.Tx, msgID string) (already bool, err error)
MarkProcessed records msgID in the dedup table inside the caller's business transaction and reports whether the id was ALREADY processed. It is the heart of the idempotent consumer (ADR 0010 D10):
already, err := deduper.MarkProcessed(ctx, tx, msg.Headers.ID())
if err != nil { /* roll back tx; the message is retried */ }
if already {
// duplicate redelivery: skip the business effect, commit (or roll
// back) tx, and return nil so the runtime Acks the message.
}
// first time: apply the business effect on tx, then commit.
Why a concrete *sql.Tx (not a Querier) ¶
The parameter is the concrete *sql.Tx BY DESIGN (ADR 0010 D10 HIGH 5): it makes passing the auto-committing pool (*sql.DB) a COMPILE error. If the dedup row could be written on the pool it would commit independently of the business writes, so a crash after the dedup insert but before the business commit would mark the id processed while its effect never happened — the message would then be deduplicated and silently LOST on redelivery. Recording inside the caller's tx makes the dedup row and the business writes commit or roll back atomically, so a rolled-back attempt is genuinely retried (a later MarkProcessed reports already=false), never falsely deduped.
A nil tx is refused with ErrNilTx before any database call (the no-panic-on-caller-input rule); already is false on that error. already==true means genuinely a duplicate and nothing else — the verdict is derived precisely by the InboxDialect, never from rowsAffected (see InboxDialect).
msgID MUST fit the dedup column (the reference schema uses VARCHAR(255); msgin's own ids are far shorter). An over-length id can be silently truncated on MySQL/MariaDB, so two distinct ids sharing a 255-char prefix would collide (one falsely deduped) — keep ids within the column width.
func (*InboxDeduper) Purge ¶
Purge deletes dedup rows whose processed_at is older than olderThan (evaluated on the DB clock) and returns the number removed. It is manual — no background goroutine (D4 precedent) — so the caller schedules it (e.g. a periodic job).
Retention safety (read before choosing olderThan — ADR 0010 D10 MEDIUM 10) ¶
Purge is ONLY safe when the source has a FINITE msgin.RetryPolicy.MaxAttempts. olderThan MUST exceed the source's maximum redelivery window — the longest time a still-redeliverable copy of a message can remain in flight (attempts × backoff, plus lease/visibility margins). Purge a dedup row while a copy of that id can still be redelivered and the late redelivery reads already=false and DOUBLE-PROCESSES the effect — the exact failure the deduper exists to prevent. Under the DEFAULT MaxAttempts==0 (retry forever) the redelivery window is UNBOUNDED, so there is NO safe olderThan and you must not Purge (or set a finite MaxAttempts first).
A non-positive olderThan is REFUSED with ErrInvalidRetention before any DB call (a zero/negative cutoff is now()-or-future, which would purge the ENTIRE inbox and double-process every id). The library cannot pick a safe POSITIVE value for an unknown caller, so a positive olderThan is not further validated — sizing it above your source's max redelivery window (above) stays the caller's responsibility.
func (*InboxDeduper) Ready ¶
func (d *InboxDeduper) Ready(ctx context.Context) error
Ready is the fail-fast boot check (ADR 0010 D2, mirroring the Source): it returns ErrSchemaNotReady (naming the table) when the dedup table is not initialized, then ErrInboxNoUniqueConstraint (naming the table) when the table exists but its msg_id column carries no unique/primary-key constraint — the constraint the dedup depends on (without it MySQL/MariaDB's INSERT IGNORE never conflicts, so the dedup silently never works). Both are boot failures, so a forgotten migration or a mis-provisioned table fails the deploy immediately rather than after silently double-processing. The reference DDL (InboxDDL) provides the constraint. Call it once at startup.
type InboxDialect ¶
type InboxDialect interface {
// InsertInboxIfAbsent records msgID in the dedup table on q (the caller's
// business transaction) and reports whether it was ALREADY present. The
// verdict is derived precisely, never from rowsAffected: Postgres via
// INSERT ... ON CONFLICT (msg_id) DO NOTHING RETURNING (exact), MySQL via
// INSERT IGNORE plus a verifying SELECT (INSERT IGNORE demotes non-duplicate
// data errors to rowsAffected==0, which the SELECT distinguishes from a
// genuine duplicate — ErrInboxInsertFailed on the demoted case). So
// already==true means genuinely a duplicate, nothing else (ADR 0010 D10).
InsertInboxIfAbsent(ctx context.Context, q Querier, table, msgID string) (already bool, err error)
// PurgeInbox deletes dedup rows whose processed_at is older than olderThan
// (evaluated on the DB clock) and returns the number removed.
PurgeInbox(ctx context.Context, q Querier, table string, olderThan time.Duration) (int64, error)
// EnsureInboxSchema idempotently creates the dedup table (and its
// processed_at retention index) — CREATE ... IF NOT EXISTS. It is optional
// and opt-in; msgin never runs DDL implicitly on the production path (D2).
EnsureInboxSchema(ctx context.Context, q Querier, table string) error
// SchemaExists reports whether the table exists, via the same portable
// information_schema probe LeaseDialect uses (no SQL driver import, D2). It is
// shared with LeaseDialect — a built-in satisfies both with one implementation.
SchemaExists(ctx context.Context, q Querier, table string) (bool, error)
// MsgIDUniqueIndexExists reports whether the table's msg_id column
// participates in a unique or primary-key index — the constraint the dedup
// relies on (without it MySQL/MariaDB's INSERT IGNORE never conflicts and the
// dedup silently never works). It is a portable information_schema probe (no
// SQL driver import, matching SchemaExists) and is used by InboxDeduper.Ready
// to fail fast on a mis-provisioned schema (ErrInboxNoUniqueConstraint). Added
// per the Task 10 review (ADR 0010 D10).
MsgIDUniqueIndexExists(ctx context.Context, q Querier, table string) (bool, error)
}
InboxDialect is the narrow, segregated SPI for the idempotent-consumer dedup inbox (ADR 0010 D10). It is deliberately NOT the fat source LeaseDialect (interface-segregation): a derivative author fixing one Claim quirk must not be forced to implement inbox-dedup SQL, and a deduper never needs claim/lease SQL. The built-in postgres.InboxDialect() and mysql.InboxDialect() (the same stateless values as postgres.LeaseDialect()/mysql.LeaseDialect()) satisfy it and are passed as the required dialect argument to NewInboxDeduper; a caller may also supply their own InboxDialect for a wire-compatible derivative. Like LeaseDialect, every method fully owns its SQL and uses the DB server clock for processed_at; no cross-dialect SQL runs.
Reference-DDL generation is deliberately NOT a method here, for the same identifier-injection reason as LeaseDialect (above): the sole public entry point is the package-level InboxDDL, which validates the table first and dispatches to the built-in for its exact CREATE TABLE.
type InboxOption ¶
type InboxOption func(*inboxConfig)
InboxOption configures an InboxDeduper built by NewInboxDeduper. It is a distinct type from the Source's Option (interface-segregation): a deduper exposes only the dedup-relevant knobs (the table; the dialect is a required positional constructor argument, not an option), never claim/lease or transactional-outbox options.
func WithInboxTable ¶
func WithInboxTable(table string) InboxOption
WithInboxTable sets the dedup-inbox table name. Unset, it defaults to "msgin_inbox" (a sensible default, CLAUDE.md). An empty or otherwise invalid identifier is rejected by NewInboxDeduper with ErrInvalidTableName — it is not silently coerced back to the default, so a caller who passes "" learns of the mistake rather than unknowingly sharing the default table.
type LeaseDialect ¶
type LeaseDialect interface {
// Claim leases up to limit claimable rows for lockedBy, treating any lease
// older than leaseTTL as expired (and therefore claimable again — the
// reaper is inlined into the claim predicate). It returns the leased rows
// with delivery_count and lease_epoch already incremented.
Claim(ctx context.Context, q Querier, table string, limit int, lockedBy string, leaseTTL time.Duration) ([]ClaimedRow, error)
// Ack settles a delivery by deleting its row, fenced on id + lockedBy +
// epoch. applied is false (with a nil error) when the fence matches no row
// — the lease expired and another worker re-claimed it — so the caller can
// suppress a phantom success for a settle it did not actually perform.
Ack(ctx context.Context, q Querier, table string, id int64, lockedBy string, epoch int64) (applied bool, err error)
// Nack returns a delivery to the queue, fenced on id + lockedBy + epoch: it
// clears the lock and sets visible_after to now()+delay so the row is
// invisible until the delay elapses. applied is false (nil error) on a
// fence miss, as for Ack.
Nack(ctx context.Context, q Querier, table string, id int64, lockedBy string, epoch int64, delay time.Duration) (applied bool, err error)
// Insert writes a new message with the already-framed headers and payload,
// becoming visible after delay (delay 0 = immediately). q may be the pool
// or a caller's transaction (transactional outbox).
Insert(ctx context.Context, q Querier, table, msgID string, headers, payload []byte, delay time.Duration) error
// EnsureSchema idempotently creates the table and its claim index
// (CREATE ... IF NOT EXISTS). It is optional and opt-in; msgin never runs
// DDL implicitly on the production path.
EnsureSchema(ctx context.Context, q Querier, table string) error
// SchemaExists reports whether the table exists, via a portable
// information_schema probe that imports no SQL driver (ADR 0010 D2).
SchemaExists(ctx context.Context, q Querier, table string) (bool, error)
}
LeaseDialect is the exported SPI a caller supplies, as the required dialect argument to NewPollingSource/NewOutboundAdapter, to teach the sql adapter a database's exact SQL — the extension point for wire-compatible derivatives and per-engine quirks. The built-ins are postgres.LeaseDialect() and mysql.LeaseDialect(), each its own module (adapter/database/sql/postgres, adapter/database/sql/mysql). Every method fully owns its statement(s) and any multi-statement transaction orchestration; no cross-dialect SQL runs. All persisted timestamps use the DB server clock (now()), never the app clock, and durations are passed as interval-typed parameters, so there is no app↔DB skew in lease-expiry or visibility comparisons (ADR 0010 D3/D4).
The lease/claim strategy this LeaseDialect implements is: Claim leases claimable rows (bumping delivery_count and lease_epoch), Ack DELETEs a fenced row, and Nack clears the lock and pushes visible_after out by the requested delay.
This is a pre-1.0 (v0) contract that may still evolve; the lock/FOR UPDATE strategy's ClaimLock method is added in a later increment.
type LockDialect ¶
type LockDialect interface {
// ClaimLock begins a transaction on ctx and, within it, claims at most ONE
// visible, unlocked row via SELECT ... FOR UPDATE SKIP LOCKED and bumps its
// delivery_count, returning the row with the OPEN transaction carried in
// LockedRow.Tx (to be committed by AckLock/NackLock). It returns (nil, nil)
// when no row is claimable (rolling the transaction back first). On ANY error
// it rolls the transaction back before returning (nil, err), so a discarded
// claim never leaks a connection (the Poll no-partial-result / owns-cleanup
// contract). The caller (the Source) passes a cancellation-detached context
// (context.WithoutCancel) so graceful shutdown does not auto-rollback an
// in-flight claim before the drain deadline (ADR 0010 D5, HIGH 3).
ClaimLock(ctx context.Context, q Querier, table, lockedBy string) (*LockedRow, error)
// AckLock settles lr by DELETEing its row on lr.Tx and committing the carried
// transaction. On any error it rolls the transaction back (releasing the
// pooled connection) and returns the error.
AckLock(ctx context.Context, lr *LockedRow, table string) error
// NackLock returns lr to the queue: it clears the lock and sets
// visible_after to now()+delay on lr.Tx, then ALWAYS commits the carried
// transaction (delay may be 0). Committing persists the delivery_count++ made
// at claim and releases the FOR UPDATE lock — the lock strategy has no
// business writes to undo, so Nack never rolls back a successful update. On an
// UPDATE or commit error it rolls back (releasing the pooled connection) and
// returns the error.
NackLock(ctx context.Context, lr *LockedRow, table string, delay time.Duration) error
}
LockDialect is the OPTIONAL lock/FOR-UPDATE strategy extension of LeaseDialect (ADR 0010 D5). It is segregated from the core LeaseDialect (interface-segregation: a lease-only custom LeaseDialect is not forced to implement lock SQL) and exported so a wire-compatible derivative can supply its own lock semantics. The built-ins postgres.LeaseDialect() and mysql.LeaseDialect() implement it, so WithStrategy(StrategyLockForUpdate) works out of the box; a custom LeaseDialect that does not also satisfy LockDialect is rejected at construction with ErrLockStrategyUnsupported.
The transaction carried in a LockedRow is BEGUN by ClaimLock and COMMITTED by AckLock or NackLock; on any error along the way the implementation rolls it back so a pooled connection is never leaked. Unlike the lease strategy there is no lease_epoch fence and no lease-expiry predicate: the open FOR UPDATE transaction IS the exclusive lock, released only by commit (settle) or a process crash (auto-rollback).
type LockedRow ¶
type LockedRow struct {
ID int64
MsgID string
Headers []byte
Payload []byte
DeliveryCount int
Tx *stdsql.Tx
}
LockedRow is a lock-strategy claim (ADR 0010 D5): the persisted envelope plus the transaction that spans claim → settle. Headers and Payload are the raw framed bytes (JSON headers, wire body); the runtime decodes the payload. DeliveryCount is the post-increment claim count (populates the msgin.delivery-count header). Tx is the open FOR UPDATE transaction owning the row; it is committed by AckLock/NackLock and MUST NOT be used after settling.
type MemberRow ¶
type MemberRow struct {
// MsgID is the member's message id (msgin_group_member.msg_id) — the
// idempotency key for AddMember, and never empty (H3: AddMember rejects an
// empty msgID).
MsgID string
// Seq is the persisted msgin.HeaderSequenceNumber, or 0 when the member's
// headers carried none. It exists as a column purely so the group's
// members can be fetched pre-ordered by the DB (ORDER BY seq, msg_id)
// without decoding every row's headers first; the authoritative sequence
// value still lives in Headers (ADR 0021 §2).
Seq int64
// Headers is the framed JSON headers blob written by EncodeHeaders.
Headers []byte
// Payload is the raw wire body (the runtime-codec-encoded []byte); the
// paired typed runtime decodes it downstream — the store never sees T
// (EmitsLiveValue()==false, ADR 0001).
Payload []byte
}
MemberRow is one persisted group member, as raw framed bytes.
type Option ¶
type Option func(*config)
Option configures a Source built by NewPollingSource.
func WithLeaseTTL ¶
WithLeaseTTL sets how long a claim's lease is held before it is treated as expired and the message becomes claimable again by another poll (the inlined reaper). Unset, it defaults to 5m.
Invariant (read before overriding) ¶
leaseTTL MUST exceed the worst-case redelivery round-trip: handler execution + settle/Ack latency + a margin — NOT merely WithHandlerTimeout. If a handler (plus its Ack) can take longer than leaseTTL, another worker reclaims the message mid-flight and it is processed twice (the fenced Ack of the first worker then no-ops with ErrStaleLease). The lease expiry is evaluated on the DB server clock while WithHandlerTimeout is evaluated on the app clock, so account for app<->DB clock skew in the margin. The default is deliberately generous (5m) for exactly this reason; shrink it only when you know your handler round-trip is well under the new value.
A non-positive d is a construction error (ErrInvalidLeaseTTL) rather than a silent default: an explicit zero/negative is a caller mistake, not a request for the default.
func WithLockedBy ¶
WithLockedBy sets the lease-owner id stamped into locked_by on claim and matched by the fenced Ack/Nack. Unset, it defaults to a random 128-bit hex id, which is the safe choice: each Source instance owns a distinct id, so two instances (or two processes) never mistake each other's leases. Override it only when you need a stable, human-readable owner for observability and you guarantee uniqueness per running Source. An empty string is treated as unset (the random default is used).
func WithLogger ¶
WithLogger injects the structured logger the Source uses for its WARN/ERROR diagnostics (a stale-lease settle, a corrupt/foreign row skipped on Poll). The default is a discard logger, so the Source never logs to a package global (observability via injection, not globals — CLAUDE.md). A nil logger is ignored (the discard default stays in place).
func WithOpportunisticSharedTransaction ¶
func WithOpportunisticSharedTransaction(r TransactionResolver) Option
WithOpportunisticSharedTransaction is the explicitly-named UNSAFE variant of WithSharedTransaction: Send uses the caller's transaction (resolved from ctx by r) when present, but falls back to a standalone, auto-commit insert on the pool when r reports none present — logging the fallback at WARN ("no shared transaction in context; standalone insert — atomicity NOT achieved", with the message id only, never the payload) so the atomicity loss is observable rather than silent. Prefer WithSharedTransaction (strict) unless a caller genuinely needs Send to succeed even when no business transaction is active; opportunistic fallback reintroduces the exact dual-write the outbox pattern exists to prevent, so it is deliberately named to make that trade-off visible at the call site rather than hidden behind a boolean flag.
A nil r is a construction error (ErrNilResolver) from NewOutboundAdapter. The same "never Commit/Rollback the borrowed tx", same-database invariant, and DLQ-sink caveat documented on WithSharedTransaction apply here too.
func WithSharedTransaction ¶
func WithSharedTransaction(r TransactionResolver) Option
WithSharedTransaction enlists Outbound.Send's INSERT in the caller's active business transaction, resolved from ctx by r — the transactional-outbox pattern (ADR 0010 D8): a business write and the outbox INSERT then commit or roll back atomically, so a crash between them can neither lose the message nor publish one for a change that never committed. This is the STRICT, recommended default: if r reports no transaction present in ctx ((nil, nil)), Send returns ErrNoSharedTransaction rather than silently falling back to a standalone (non-atomic) insert — it never silently dual-writes. Use WithOpportunisticSharedTransaction for the explicit fallback-and-log variant instead.
A nil r is a construction error (ErrNilResolver) from NewOutboundAdapter — never a deferred nil-func panic on the first Send.
msgin never commits or rolls back the borrowed transaction ¶
The Querier r returns is BORROWED: Outbound only ever calls ExecContext/QueryContext/QueryRowContext on it for the INSERT. It never calls Commit or Rollback — the caller retains full ownership of the transaction's lifecycle and decides when (and whether) it commits.
Same-database invariant (unenforceable — read before using) ¶
The transaction r resolves MUST be open on the SAME database as this Outbound's table. A *sql.Tx does not expose the *sql.DB it was opened against, so this cannot be verified at runtime; a mismatched database silently defeats the atomicity this option exists to provide. There is no way to make this safe automatically — verify it by construction (e.g. build the Outbound's *sql.DB and the caller's transaction from the same pool).
Do not use as a DLQ / invalid-message sink (LOW audit) ¶
A strict shared-transaction Outbound must NOT be passed as a msgin.RetryPolicy.DeadLetter or endpoint.WithInvalidMessageSink target. The runtime's divert path calls Send on a settlement-scoped context that never carries the caller's business transaction, so r would report (nil, nil) on every poison message, Send would return ErrNoSharedTransaction, and the divert would treat that as "sink failed" — and the poison message never actually reaches the dead-letter table. On the DEAD-LETTER path that failure is retried forever; on the INVALID-message path the divert is single-shot, so the message is logged and DISCARDED instead. Neither outcome is what you wanted. Use a plain, non-shared-transaction Outbound (built without this option) as a DLQ/invalid sink — and note the advice binds MORE often now that a consumer with no invalid-message sink diverts invalid messages down its dead-letter sink too.
func WithStrategy ¶
WithStrategy selects the claim/settle strategy (ADR 0010 D4/D5). Unset, it is StrategyLeaseClaim — the default that scales to batches without pinning a connection. Pass StrategyLockForUpdate for stronger crash safety (a crash rolls back the carried FOR UPDATE tx, releasing the row immediately, with no lease-expiry double-processing window). An out-of-range value is a construction error (ErrInvalidStrategy); StrategyLockForUpdate additionally requires the resolved LeaseDialect to implement LockDialect (ErrLockStrategyUnsupported).
Lock strategy: mandatory DB-pool topology (read before choosing it) ¶
StrategyLockForUpdate pins ONE pooled connection per in-flight message for the whole message lifetime (claim → settle). Two invariants follow, neither statically enforceable (the Source cannot see the consumer's pool sizing or a sink's separate pool), so both are the caller's responsibility:
- Separate DLQ pool (mandate). On a permanent failure the runtime calls the DLQ/invalid sink's Send BEFORE it Acks (freeing the claim connection), so a sink that is itself a sql adapter on the SAME *sql.DB needs an ADDITIONAL connection while every claim connection is pinned — the divert INSERT then blocks on the exhausted pool and the flow stalls until the shutdown deadline. A lock-strategy consumer whose DLQ/invalid sink is a sql adapter MUST give that sink a SEPARATE *sql.DB (separate pool), or size one shared pool with headroom poolSize >= maxInFlight + divert-concurrency.
- Pool-coupling. Effective in-flight = min(WithMaxInFlight, WithConcurrency, poolSize - headroom). If the requested in-flight exceeds the pool, the poller stalls on an exhausted pool. Pair the lock strategy with db.SetMaxOpenConns(...), WithPollMaxBatch(1) (the lock claim returns at most one row regardless), and a separate DLQ pool.
WithLeaseTTL is inert under StrategyLockForUpdate (there is no lease).
type Outbound ¶
type Outbound struct {
// contains filtered or unexported fields
}
Outbound is the sql INSERT outbound channel adapter: it writes a message as a new, immediately-visible row (visible_after = now(), delay 0). Paired with a Task-5 Source polling the SAME table, it forms a durable, at-least-once produce/consume queue; Outbound is also usable directly as a msgin.RetryPolicy.DeadLetter sink or an endpoint.WithInvalidMessageSink target, since both are just an OutboundAdapter (but see WithSharedTransaction's DLQ-sink caveat before using a strict shared-tx Outbound that way).
func NewOutboundAdapter ¶
func NewOutboundAdapter(db *stdsql.DB, table string, dialect LeaseDialect, opts ...Option) (*Outbound, error)
NewOutboundAdapter builds an Outbound over table on db, using dialect to generate the exact SQL (ADR 0011 — the dialect is a required, explicit constructor argument; there is no driver auto-detect), the same explicit argument NewPollingSource takes. It validates the table identifier (ErrInvalidTableName). WithLeaseTTL/WithLockedBy are lease-Source-specific and are simply inert here. A nil db is msgin.ErrNilAdapter; a nil dialect is ErrNilDialect. A nil TransactionResolver passed to WithSharedTransaction/WithOpportunisticSharedTransaction is a construction error (ErrNilResolver), never a deferred nil-func panic on the first Send.
The returned Outbound implements msgin.OutboundAdapter; pass it to endpoint.NewProducer, msgin.RetryPolicy.DeadLetter, or endpoint.WithInvalidMessageSink. Call Ready once at boot to fail fast on an un-provisioned schema (ADR 0010 D2).
A nil ELEMENT of opts is a bare msgin.ErrNilFunc naming the element's 0-based index ("sql.NewOutboundAdapter: nil option at index 1"), not a panic — checked as opts is applied. The apply loop is this constructor's first statement that can fail, preceded only by the config-defaults initializer, which cannot fail, so the nil-option check runs BEFORE every other validation here — the ErrNilResolver check, then the nil-db/nil-dialect/table checks — and wins over all of them.
func (Outbound) EnsureSchema ¶
EnsureSchema idempotently creates the table and its claim index. It is optional and opt-in (dev/test/opt-in callers); production callers provision the schema via the reference DDL (see postgres.DDL / mysql.DDL) instead — msgin never runs DDL implicitly (ADR 0010 D2).
func (Outbound) Ready ¶
Ready is the fail-fast boot check (ADR 0010 D2): it returns ErrSchemaNotReady (naming the table) when the table is not initialized, so a forgotten migration fails the deploy immediately instead of the caller sitting in a silent poll/insert-error loop. Call it once at startup before NewConsumer.Run or before the first Producer.Send.
func (*Outbound) Send ¶
Send writes msg for immediate delivery. It is exactly SendAfter(ctx, msg, 0).
func (*Outbound) SendAfter ¶
func (o *Outbound) SendAfter(ctx context.Context, msg msgin.Message[any], delay time.Duration) error
SendAfter frames msg's headers (EncodeHeaders) and INSERTs a new row via the resolved LeaseDialect, becoming claimable only once delay elapses: visible_after = <db-now> + delay, computed on the DB server clock (skew-free). A delay <= 0 makes the row immediately visible. Implements msgin.ScheduledSender. msg's payload MUST be []byte — Outbound is a wire adapter (not a LiveValueSource), so endpoint.NewProducer always JSON-encodes T to []byte before calling Send/SendAfter; a non-[]byte payload here is a defensive case (ErrInvalidPayload) that trusted producers do not hit.
With no shared-transaction option configured, SendAfter inserts on the pool db, unchanged from the plain wire-adapter behavior. With WithSharedTransaction or WithOpportunisticSharedTransaction configured, SendAfter resolves the caller's transaction from ctx and applies the ADR 0010 D8 policy — see resolveQuerier.
An INSERT failure is wrapped as ErrSchemaNotReady iff a follow-up portable probe finds the table missing, otherwise the raw error propagates.
type Querier ¶
type Querier interface {
ExecContext(ctx context.Context, query string, args ...any) (stdsql.Result, error)
QueryContext(ctx context.Context, query string, args ...any) (*stdsql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...any) *stdsql.Row
}
Querier is the subset of *database/sql.DB and *database/sql.Tx that the LeaseDialect uses. Both *sql.DB and *sql.Tx satisfy it, so a LeaseDialect method runs unchanged on the connection pool or inside a caller-supplied transaction (e.g. the transactional-outbox Insert on a *sql.Tx).
type QueueStore ¶
type QueueStore struct {
// contains filtered or unexported fields
}
QueueStore is a durable, at-least-once msgin.ChannelStore backed by a single table. It is a thin facade pairing an Outbound (Enqueue = INSERT) with a Source (Claim = lease/claim, fenced Ack/Nack) over the SAME table — reusing the proven sql adapter machinery (ADR 0010/0011). Carries []byte (a wire store): the paired Producer JSON-encodes T, exactly as sql.Outbound. Named to mirror memory.QueueStore.
Delivery guarantee: at-least-once across restarts/crashes (Guaranteed Delivery). Back a channel.QueueChannel with this store when the flow segment must survive a restart.
func NewQueueStore ¶
func NewQueueStore(db *stdsql.DB, table string, dialect LeaseDialect, opts ...Option) (*QueueStore, error)
NewQueueStore builds a durable QueueStore over table on db with dialect. Options apply to both halves; lease-only options (WithLeaseTTL/WithStrategy/WithLockedBy) are inert on the Outbound and shared-tx options are inert on the Source, so there is no cross-misconfiguration (verified: options.go). A nil db is msgin.ErrNilAdapter; a nil dialect is ErrNilDialect; a bad table is ErrInvalidTableName. Call Ready once at boot (ADR 0010 D2).
A nil ELEMENT of opts is a bare msgin.ErrNilFunc naming the element's 0-based index ("sql.NewQueueStore: nil option at index 1"), not a panic. It is checked HERE, by a standalone pre-check above the delegation, so the position names sql.NewQueueStore rather than one of the two constructors it forwards to — a function the caller never invoked (Spec 015 §3.4). The pre-check is the function's first statement, so the nil-option check runs BEFORE the nil-db, nil-dialect and table checks the delegates perform, and wins over all of them.
func (*QueueStore) EmitsLiveValue ¶
func (q *QueueStore) EmitsLiveValue() bool
EmitsLiveValue reports false: this is a wire store ([]byte payloads).
func (*QueueStore) EnsureSchema ¶
func (q *QueueStore) EnsureSchema(ctx context.Context) error
func (*QueueStore) NativeDeadLetter ¶
func (q *QueueStore) NativeDeadLetter() bool
func (*QueueStore) NativeRedelivery ¶
func (q *QueueStore) NativeRedelivery() bool
NativeRedelivery / NativeDeadLetter forward the Source's capability (true / false): the DB row redelivers on nack/lease-expiry, and dead-lettering is the runtime's RetryPolicy. Forwarded so a QueueChannel over this store behaves identically to the raw Source.
type Source ¶
type Source struct {
// contains filtered or unexported fields
}
Source is the sql lease/claim inbound channel adapter: a durable, at-least-once message queue backed by a table, driven by the runtime's Poller. Each Poll leases a batch of claimable rows (bumping delivery_count and a fence token), and each delivery's Ack/Nack settles its row fenced on that token, so a lease that expired and was re-claimed by another worker cannot be settled twice.
requeue=false collapses to a delayed requeue ¶
An at-least-once source cannot silently drop a message, so a delivery's Nack(ctx, requeue=false, delay) is treated as Nack(ctx, requeue=true, 0): the row is made immediately claimable again rather than discarded. The runtime only ever sends the pull path requeue=true, so this collapse is a safety net, not a hot path (ADR 0010 D4).
Payload size cap ¶
The Source does not cap payload size; decoding is a runtime concern (the adapter never sees the typed payload). Pass WithMaxPayloadBytes to NewConsumer — RecommendedMaxPayloadBytes is a copy-pasteable starting value (ADR 0010 D7).
func NewPollingSource ¶
func NewPollingSource(db *stdsql.DB, table string, dialect LeaseDialect, opts ...Option) (*Source, error)
NewPollingSource builds a lease/claim Source over table on db, using dialect to generate the exact SQL (ADR 0011 — the dialect is a required, explicit constructor argument; there is no driver auto-detect). Pass postgres.LeaseDialect() (adapter/database/sql/postgres), mysql.LeaseDialect() (adapter/database/sql/mysql), or your own LeaseDialect implementation. It validates the table identifier (ErrInvalidTableName), and applies the sensible defaults documented on each option (5m lease TTL, a random lease owner, a discard logger). A nil db is msgin.ErrNilAdapter; a nil dialect is ErrNilDialect.
The returned Source implements msgin.PollingSource and msgin.NativeReliability; pass it to endpoint.NewConsumer. Call Ready once at boot to fail fast on an un-provisioned schema (ADR 0010 D2), and prefer a non-zero RetryPolicy.Backoff so a repeatedly-failing row idles the poll loop instead of hot-looping the DB (ADR 0010 D1 poison-recycle caveat).
A nil ELEMENT of opts is a bare msgin.ErrNilFunc naming the element's 0-based index ("sql.NewPollingSource: nil option at index 1"), not a panic — checked as opts is applied. The apply loop is this constructor's first statement that can fail, preceded only by the config-defaults initializer, which cannot fail, so the nil-option check runs BEFORE every other validation here — the nil-db/nil-dialect/table checks named above, the strategy and lock-dialect checks, and the WithLeaseTTL range check — and wins over all of them.
func (Source) EnsureSchema ¶
EnsureSchema idempotently creates the table and its claim index. It is optional and opt-in (dev/test/opt-in callers); production callers provision the schema via the reference DDL (see postgres.DDL / mysql.DDL) instead — msgin never runs DDL implicitly (ADR 0010 D2).
func (*Source) NativeDeadLetter ¶
NativeDeadLetter reports false: the Source has no built-in dead-letter, so the runtime's RetryPolicy (MaxAttempts -> DeadLetter sink) governs dead-lettering.
func (*Source) NativeRedelivery ¶
NativeRedelivery reports true: a nacked or lease-expired row persists and is re-leased by a later poll, so the runtime relies on the DB for redelivery rather than its in-process attempt tracker.
func (*Source) Poll ¶
Poll fetches up to max claimable rows as settleable deliveries (msgin.PollingSource), dispatching on the configured Strategy: the default lease/claim path (pollLease) or the lock/FOR UPDATE path (pollLock). Either way it upholds the Poll contract: at most max deliveries, and none alongside a non-nil error (each strategy owns rollback of its claim work on the error path). A claim query error is surfaced as ErrSchemaNotReady iff a follow-up portable probe finds the table missing, otherwise the raw error propagates to the poll-loop backoff.
func (Source) Ready ¶
Ready is the fail-fast boot check (ADR 0010 D2): it returns ErrSchemaNotReady (naming the table) when the table is not initialized, so a forgotten migration fails the deploy immediately instead of the caller sitting in a silent poll/insert-error loop. Call it once at startup before NewConsumer.Run or before the first Producer.Send.
type Strategy ¶
type Strategy int
Strategy selects how a Source claims and settles rows (ADR 0010 D4/D5). The zero value is StrategyLeaseClaim, so an unset strategy is the safe default.
const ( // StrategyLeaseClaim (the default) claims rows with a short, committed lease // tx (bumping delivery_count and a fence token) and settles each delivery in // a separate fenced tx. It scales to batches without pinning a connection per // in-flight message; an expired lease is reclaimed by the next poll (the // inlined reaper). See WithLeaseTTL (ADR 0010 D4). StrategyLeaseClaim Strategy = iota // StrategyLockForUpdate claims a single row inside a SELECT ... FOR UPDATE // SKIP LOCKED transaction that is CARRIED in the Delivery and owned by the // worker from claim to settle: Ack = DELETE + commit; Nack = clear-lock // UPDATE + commit (always commits — it persists delivery_count++ and releases // the lock; there are no business writes to roll back). A process crash (only) // auto-releases the row via tx rollback — no lease-expiry reaper, no fence // token. It gives stronger crash safety than the lease strategy at the cost of // one pinned pooled connection per in-flight message, so it requires care with // the DB pool topology — see WithStrategy for the mandatory pool invariants. // Requires a LeaseDialect that also implements LockDialect (ErrLockStrategyUnsupported // otherwise); the built-ins satisfy it. Under this strategy WithLeaseTTL is // inert (there is no lease). (ADR 0010 D5.) StrategyLockForUpdate )
type TransactionResolver ¶
TransactionResolver resolves the caller's active business transaction from ctx as a Querier — a *sql.Tx satisfies Querier, so a caller storing a raw *sql.Tx, an sqlx wrapper, or a unit-of-work/repository layer's tx can all be adapted to msgin's Querier with a one-line resolver. Returning (nil, nil) means no shared transaction is present in ctx (the outbox falls back to its configured no-tx policy — see WithSharedTransaction / WithOpportunisticSharedTransaction); a non-nil error aborts Send, which wraps and returns it without attempting any insert (ADR 0010 D8).