engine

package
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 39 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// KeySortIDAsc preserves the original key listing and recovery cursor order.
	KeySortIDAsc = "id_asc"
	// KeySortCreatedDesc lists newest keys first, breaking timestamp ties by ID.
	KeySortCreatedDesc = "created_desc"
)
View Source
const (
	// DefaultMaxMessageBytes is the default body-size cap (1 MiB, design §14-Q7).
	DefaultMaxMessageBytes = 1 << 20
	// DefaultMaxSubscriptions bounds retained subscription metadata and fan-out growth.
	// Deleting subscriptions continue to count until bounded cleanup removes them.
	DefaultMaxSubscriptions = 10_000
)
View Source
const (
	ReasonMaxDeliveryCount = "MaxDeliveryCountExceeded"
	ReasonTTLExpired       = "TTLExpired"
	ReasonAppRequested     = "AppRequested"
)

Dead-letter reasons.

View Source
const MaxRenewBatch = settleChunk

RenewBatch extends the lock lease of many messages in ONE STATEMENT — deliberately not a transaction — returning a per-item result so the caller can see exactly which leases still held when that statement finished. One statement means one clock reading: Ok cannot mean "live" for some items and "stale" for others in the same call.

Renewing a batch message-by-message does not scale: over a network each Renew is a separate round trip, so N messages × the link latency can easily exceed the lease itself and the locks expire *while they are being renewed* — a 64-message batch on a 50ms link needs 3.2s of renewals against a 2s lease and loses most of them (review round-3). One request, one transaction, one lease deadline for the whole batch.

It is also SET-BASED rather than a loop of single-row updates, and that matters just as much: against a remote Turso/libSQL store every statement is its own Hrana round trip, so an N-statement renewal is N remote round trips — the same O(N) latency, reintroduced one layer down. Since the new deadline is computed once, a slow enough pass would commit leases that had already expired while it ran.

Like Renew, an item whose lock was already lost simply comes back Ok=false; that is the contract, not an error for the batch. Fencing is on LockToken, exactly as in CompleteBatch. MaxRenewBatch is the most messages one RenewBatch call may renew.

It is exactly one statement's worth, and that is a CONTRACT, not a tuning knob. RenewBatch promises that every Ok it returns means a live lease at the moment it returns. Across several statements that promise is unkeepable: the first chunk commits, later chunks run (each a network round trip on a remote store), and with a short lock duration the first chunk's lease can expire — and be reaped — before the call has even finished, while its result still says Ok. Renewing in one statement is what makes the answer honest.

It is also not a limit anyone meets by accident: Receive hands out at most 256 messages, so a consumer holding a batch of leases never has more than that. A caller holding more should renew in several calls, each of which then reports honestly about its own.

Variables

View Source
var (
	ErrNotFound         = errors.New("mqlite: not found")
	ErrQueueNotFound    = error(queueNotFoundError{})
	ErrLockLost         = errors.New("mqlite: lock lost or already settled")
	ErrUnauthenticated  = errors.New("mqlite: unauthenticated (bad or missing token)")
	ErrPermissionDenied = errors.New("mqlite: permission denied")
	ErrKeyConflict      = errors.New("mqlite: access key id already exists")
	ErrOutcomeUnknown   = errors.New("mqlite: operation outcome unknown (the acknowledgement was lost or invalid; reconcile the operation's state before retrying)")
	ErrDedupConflict    = errors.New("mqlite: dedup conflict (same id, different body)")
	// ErrUnsupported: the BROKER does not serve this operation — an older broker that predates
	// it. Distinct from ErrNotFound ("the queue/message does not exist"), which the same broker
	// answers with a 404 too. A client can use it to fall back to an older equivalent.
	ErrUnsupported           = errors.New("mqlite: operation not supported by this broker")
	ErrClosed                = errors.New("mqlite: engine closed")
	ErrMessageTooLarge       = errors.New("mqlite: message body exceeds max size")
	ErrQueueNotEmpty         = errors.New("mqlite: queue still contains messages; drain all states before deleting")
	ErrSubscriptionNotFound  = errors.New("mqlite: subscription not found")
	ErrSubscriptionNotEmpty  = errors.New("mqlite: subscription still contains messages; drain all states before deleting")
	ErrSubscriptionLimit     = errors.New("mqlite: subscription limit reached")
	ErrNameConflict          = errors.New("mqlite: name already in use by another queue or topic")
	ErrGroupRequired         = errors.New("mqlite: group id required for group_fifo queue")
	ErrDBLocked              = errors.New("mqlite: database file is already open by another process")
	ErrSchemaVersionMismatch = errors.New("mqlite: database schema version is incompatible with this build")
	ErrInvalidFilter         = errors.New("mqlite: invalid subscription filter expression")
	// ErrInvalidArgument is a caller-side request/config error (empty name, unknown
	// enum, malformed body) — the server maps it to 400 invalid_argument rather than
	// letting it leak out as an opaque 500 (MQLITE-86).
	ErrInvalidArgument = errors.New("mqlite: invalid argument")
)

Sentinel errors. The server maps these onto Connect/HTTP error codes.

Functions

func MaintenanceTaskNames added in v0.3.2

func MaintenanceTaskNames() []string

func MessageEventNames added in v0.3.2

func MessageEventNames() []string

MessageEventNames returns the complete bounded event vocabulary. A delivery or enqueue includes its redelivered/scheduled subset; never sum events as a ledger.

Types

type AccessKey added in v0.3.1

type AccessKey struct {
	ID, Name                              string
	Permissions                           KeyPermissions
	CreatedAtMs, ExpiresAtMs, RevokedAtMs int64
}

AccessKey contains public metadata only: neither the token nor its digest.

type AccessKeyPage added in v0.3.1

type AccessKeyPage struct {
	Keys        []AccessKey
	NextAfterID string
}

AccessKeyPage includes revoked and expired records in the requested order.

type CollectionStatus added in v0.3.2

type CollectionStatus struct {
	State           string  `json:"state"`
	LastSuccessAtMs int64   `json:"last_success_at_ms"`
	DurationSeconds float64 `json:"duration_seconds"`
	ErrorCode       string  `json:"error_code"`
}

CollectionStatus describes availability, not a healthy zero on collection failure. ErrorCode is a fixed classification; no underlying database error is exposed.

type CreateAccessKeyOptions added in v0.3.1

type CreateAccessKeyOptions struct {
	ID, Name    string
	Permissions KeyPermissions
	ExpiresAtMs int64
}

CreateAccessKeyOptions describes an independently revocable broker credential. ID must be generated and retained by the caller before requesting creation.

type DeleteOptions added in v0.4.0

type DeleteOptions struct{ Force bool }

DeleteOptions controls explicit destruction of a queue or subscription. Force discards every message state, including deliveries already in flight.

type DeleteResult added in v0.4.0

type DeleteResult struct {
	Deleted bool   `json:"deleted"`
	State   string `json:"state"`
}

DeleteResult distinguishes logical deletion from completed physical cleanup. A deleting entity cannot receive work and keeps its name until cleanup finishes.

type DurationHistogram added in v0.3.2

type DurationHistogram struct {
	BoundsSeconds []float64 `json:"bounds_seconds"`
	BucketCounts  []uint64  `json:"bucket_counts"`
	Count         uint64    `json:"count"`
	SumSeconds    float64   `json:"sum_seconds"`
}

DurationHistogram has cumulative finite buckets; Count is also its +Inf bucket. Seconds are a serialization of monotonic elapsed time, independent of the engine clock.

type Engine

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

Engine is the embeddable queue core: a Store plus Service Bus semantics, independent of any network/transport (design §12.3). Both the in-process embedded API and the network broker drive this same type.

func Open

func Open(ctx context.Context, opts Options) (*Engine, error)

Open opens the store (initializing the schema), performs startup lease recovery according to Options, and starts background maintenance loops.

func (*Engine) Abandon

func (e *Engine) Abandon(ctx context.Context, queue string, seq int64, token string, delayMs int64) error

Abandon releases the lock and redelivers, or dead-letters if delivery_count has reached the queue's max (§8.5). delayMs applies exponential-backoff style re-visibility when requeued: with delayMs>0 the message parks in 'scheduled' (not 'active' with a future visible_at) until the backoff lapses — the head-of-line probe covers 'scheduled', so on an ordered queue the backing-off head keeps blocking its group and successors cannot overtake it (MQLITE-66); the scheduler re-activates it at visible_at. delayMs=0 redelivers immediately.

func (*Engine) AuthenticateAccessKey added in v0.3.1

func (e *Engine) AuthenticateAccessKey(ctx context.Context, token string) (AccessKey, error)

AuthenticateAccessKey validates a database credential without caching it or updating the record. A request starting after a successful revocation is denied.

func (*Engine) AuthenticateAccessKeyWithOutcome added in v0.3.2

func (e *Engine) AuthenticateAccessKeyWithOutcome(ctx context.Context, token string) (AccessKey, string, error)

AuthenticateAccessKeyWithOutcome exposes only a bounded internal observation reason. HTTP adapters must continue returning generic authentication errors.

func (*Engine) Cancel

func (e *Engine) Cancel(ctx context.Context, queue string, seq int64) error

Cancel deletes a scheduled message that has never been delivered (delivery_count=0) — the delayed-Send case. An over-max redelivery or a delayed-Abandon backoff can also sit in 'scheduled', but those rows have already been delivered and stay under the retry/DLQ discipline (max_delivery_count, Reject); Cancel must not silently remove them (MQLITE-66).

func (*Engine) Close

func (e *Engine) Close() error

Close stops the background workers and shuts the store down. It refuses new operations immediately (they get ErrClosed) and then waits for the operations already in flight — a statement executing, a transaction committing — to finish before releasing the single-writer file lock, so the lock is never dropped out from under a live write.

Admitted operations get up to five seconds to finish before background contexts are canceled. This is not a deadline for Close: it still joins admitted foreground work and background cleanup.

Because it waits for in-flight work, Close MUST NOT be called from inside an operation it would wait for — in particular, not from within an Engine.Tx callback (see Tx). Doing so deadlocks.

func (*Engine) Compact added in v0.1.1

func (e *Engine) Compact(ctx context.Context, full bool) error

Compact reclaims free database pages to the OS (MQLITE-31). New local DBs use auto_vacuum=INCREMENTAL, so the default drives the incremental reclaim — a WAL checkpoint, incremental_vacuum to completion, then a second checkpoint that hands the truncated tail back to the OS (the same reclaimPages the background janitor runs) — bounded, no global lock, janitor-friendly. full=true runs a full `VACUUM`, which rewrites the whole file and holds a global write lock (a maintenance-window operation). Both are local-only — a remote Turso/libSQL store manages its own storage.

func (*Engine) Complete

func (e *Engine) Complete(ctx context.Context, queue string, seq int64, token string) error

Complete removes a successfully-processed message while its lock lease is live.

func (*Engine) CompleteBatch added in v0.1.1

func (e *Engine) CompleteBatch(ctx context.Context, queue string, items []SettleItem) ([]SettleResult, error)

CompleteBatch completes many messages in ONE TRANSACTION and one round-trip — the broker-side fix for the drain N+1 (Receive returns a batch, but settling it one-by-one is one HTTP call per message). Each item is fenced on its own lock_token and recorded idempotently, exactly like Complete; a per-item failure (expired/wrong token) returns Ok=false rather than failing the whole batch.

Like RenewBatch it is SET-BASED — a fixed number of statements, not one (or two) per message. Against a remote Turso/libSQL store every statement is its own round trip, so the old item-by-item loop made a 256-message settle ~512 remote round trips, on the very RPC whose latency lets the batch's own locks expire while it runs (review round-3).

Unlike RenewBatch it may span several statements (it chunks), because completion is TERMINAL: a message deleted by an earlier chunk cannot un-delete itself while a later chunk runs. Renewal makes a claim about the future — "this lease is live" — which is why it must fit in one statement; completion only reports what already happened.

func (*Engine) CompletedCounts added in v0.2.0

func (e *Engine) CompletedCounts() map[string]uint64

CompletedCounts is a legacy projection of the canonical committed event counters.

func (*Engine) CreateAccessKey added in v0.3.1

func (e *Engine) CreateAccessKey(ctx context.Context, opts CreateAccessKeyOptions) (AccessKey, string, error)

CreateAccessKey persists a digest and returns the new secret exactly once. Repeated IDs fail with ErrKeyConflict; an existing secret is never recovered.

func (*Engine) CreateQueue

func (e *Engine) CreateQueue(ctx context.Context, name string, cfg QueueConfig) error

func (*Engine) Defer

func (e *Engine) Defer(ctx context.Context, queue string, seq int64, token string) error

Defer sets a message aside; it is later retrieved by seq via ReceiveDeferred.

func (*Engine) DeleteQueue added in v0.3.3

func (e *Engine) DeleteQueue(ctx context.Context, name string) error

DeleteQueue removes an empty plain queue. An accepted deletion returns nil whether bounded physical cleanup completed in this call or continues in the background. DeleteQueueWithOptions exposes the detailed state and the explicit force-discard option.

func (*Engine) DeleteQueueWithOptions added in v0.4.0

func (e *Engine) DeleteQueueWithOptions(ctx context.Context, name string, opts DeleteOptions) (DeleteResult, error)

DeleteQueueWithOptions logically retires one plain queue, then performs a bounded cleanup batch. Empty-only is the default; Force is durable permission to discard all retained messages. Maintenance resumes unfinished cleanup.

func (*Engine) DeleteSubscription added in v0.4.0

func (e *Engine) DeleteSubscription(ctx context.Context, topic, name string) error

DeleteSubscription removes an empty subscription and its topic membership.

func (*Engine) DeleteSubscriptionWithOptions added in v0.4.0

func (e *Engine) DeleteSubscriptionWithOptions(ctx context.Context, topic, name string, opts DeleteOptions) (DeleteResult, error)

DeleteSubscriptionWithOptions logically retires the exact topic/name mapping. Force is explicit permission to discard every retained message state.

func (*Engine) ListAccessKeys added in v0.3.1

func (e *Engine) ListAccessKeys(ctx context.Context, afterID string, limit int) (AccessKeyPage, error)

ListAccessKeys lists public metadata in ID order, using a bounded cursor page.

func (*Engine) ListAccessKeysWithOptions added in v0.3.1

func (e *Engine) ListAccessKeysWithOptions(ctx context.Context, opts ListAccessKeysOptions) (AccessKeyPage, error)

ListAccessKeysWithOptions lists metadata using the selected stable keyset order. New keys ahead of a descending cursor do not shift or repeat subsequent pages.

func (*Engine) ListQueues

func (e *Engine) ListQueues(ctx context.Context) ([]QueueInfo, error)

ListQueues lists all queues/subscriptions.

func (*Engine) ListSubscriptions added in v0.2.0

func (e *Engine) ListSubscriptions(ctx context.Context) ([]SubscriptionInfo, error)

ListSubscriptions returns every active, unexpired subscription with its topic and filter expression, ordered by topic then name. (ListQueues shows the backing queues; this exposes the topic membership + filter that ListQueues does not.)

Compatibility note: use ListSubscriptionsWithOptions for bounded inventory and lifecycle reconciliation, including deleting name reservations.

func (*Engine) ListSubscriptionsWithOptions added in v0.4.0

func (e *Engine) ListSubscriptionsWithOptions(ctx context.Context, opts ListSubscriptionsOptions) (SubscriptionPage, error)

ListSubscriptionsWithOptions returns one bounded keyset page. Active-only is the public default; IncludeDeleting exposes retained name reservations for management and reconciliation.

func (*Engine) Observability added in v0.3.2

func (e *Engine) Observability(ctx context.Context) ObservabilitySnapshot

func (*Engine) Peek

func (e *Engine) Peek(ctx context.Context, queue string, opts PeekOptions) ([]*PeekedMessage, error)

Peek browses messages without locking or settling them (§7.3). Useful for triage and for recovering the seq_number of a deferred message.

func (*Engine) Purge

func (e *Engine) Purge(ctx context.Context, queue string, opts RedriveOptions) (int, error)

Purge permanently deletes dead-lettered messages from a queue's DLQ (§7.3). Use after a redrive, or to discard poison messages that will never be reprocessed. opts.Max / opts.OlderThanMs scope the purge; both zero purges the whole DLQ. Returns the number of rows deleted.

func (*Engine) Receive

func (e *Engine) Receive(ctx context.Context, queue string, opts ReceiveOptions) ([]*Message, error)

Receive claims up to opts.MaxMessages messages (Peek-Lock by default), with long-poll up to opts.WaitMs (clamped to 20s, §11.3).

func (*Engine) ReceiveDeferred

func (e *Engine) ReceiveDeferred(ctx context.Context, queue string, seqs ...int64) ([]*Message, error)

ReceiveDeferred locks previously-deferred messages by seq_number (§8.7).

func (*Engine) Redrive

func (e *Engine) Redrive(ctx context.Context, dlq string, opts RedriveOptions) (int, error)

func (*Engine) Reject

func (e *Engine) Reject(ctx context.Context, queue string, seq int64, token, reason, desc string) error

Reject moves a locked message to the dead-letter state with a reason.

func (*Engine) Remote

func (e *Engine) Remote() bool

Remote reports whether the underlying store is a remote Turso/libSQL DB.

func (*Engine) Renew

func (e *Engine) Renew(ctx context.Context, queue string, seq int64, token string) error

Renew extends a live lock lease by the queue's lock duration (§11.3).

func (*Engine) RenewBatch added in v0.3.0

func (e *Engine) RenewBatch(ctx context.Context, queue string, items []SettleItem) ([]SettleResult, error)

RenewBatch extends the lock lease of many messages in ONE statement, returning a per-item result so the caller can see exactly which leases still hold.

Renewing a batch message-by-message does not scale: over a network each Renew is a separate round trip, so N messages × the link latency can easily exceed the lease itself and the locks expire *while they are being renewed* — a 64-message batch on a 50ms link needs 3.2s of renewals against a 2s lease and loses most of them (review round-3). One request, one statement, one lease deadline for the whole batch.

Deliberately NOT in a transaction. Renewal has no cross-item invariant to protect — each lease stands or falls on its own token — so a transaction buys nothing and costs two real things: the deadline would have to survive the COMMIT as well as the write, and `Tx.Commit` takes no context (the pinned libSQL driver sends it on context.Background()), so a stalled commit is UNCANCELLABLE — and `mqlite receive` waits for its renewal goroutine before closing the client, which would hang the command despite cancelling it.

Like Renew, an item whose lock was already lost simply comes back Ok=false; that is the contract, not an error for the batch. Fencing is on LockToken, exactly as in CompleteBatch.

func (*Engine) RevokeAccessKey added in v0.3.1

func (e *Engine) RevokeAccessKey(ctx context.Context, id string) error

RevokeAccessKey permanently marks a database key revoked. Replays are idempotent; credentials issued by this key are independent and are not revoked with it.

func (*Engine) RunMaintenanceOnce

func (e *Engine) RunMaintenanceOnce(ctx context.Context)

RunMaintenanceOnce runs every maintenance pass synchronously. Tests with DisableBackground use this to drive time-based transitions deterministically.

func (*Engine) RuntimeStatus added in v0.3.2

func (e *Engine) RuntimeStatus(ctx context.Context) (Status, int, int)

RuntimeStatus shares legacy status facts and queue/subscription counting between the native SDK and HTTP adapters. Failed inventory retains the legacy zero counts.

func (*Engine) Schedule

func (e *Engine) Schedule(ctx context.Context, queue string, m OutMessage, atMs int64) (int64, error)

Schedule enqueues a message that becomes visible at `atMs` (epoch ms) (§8.7). As with SendOne, a dedup conflict surfaces as ErrDedupConflict while a publish that no subscription accepts is a no-op returning (0, nil).

func (*Engine) ScheduleBatch added in v0.3.0

func (e *Engine) ScheduleBatch(ctx context.Context, queue string, ms []OutMessage, atMs int64) ([]int64, error)

ScheduleBatch enqueues one or more messages to become visible at atMs, atomically: like Send, the whole batch commits in one transaction or none does — a mid-batch failure never leaves earlier items scheduled. A conflicting slot (same message_id, different body) comes back as seq 0 while the rest commit; a publish that matches no subscription is a valid no-op (seq 0). Use Schedule for a single message when you must tell a dedup conflict apart from a no-subscriber no-op.

func (*Engine) Send

func (e *Engine) Send(ctx context.Context, queue string, ms ...OutMessage) ([]int64, error)

Send enqueues one or many messages in one transaction (§11.3 Batch).

func (*Engine) SendOne

func (e *Engine) SendOne(ctx context.Context, queue string, m OutMessage) (int64, error)

SendOne enqueues one message, returning its seq_number. A dedup conflict (same id, different body) surfaces as ErrDedupConflict. Publishing to a topic that no subscription filter accepts is a valid no-op: it returns (0, nil).

func (*Engine) ServerTimeMs added in v0.4.3

func (e *Engine) ServerTimeMs() int64

ServerTimeMs returns the same injectable epoch-millisecond clock used for lease, scheduling, TTL, and settlement decisions. HTTP adapters expose this value so remote clients can translate absolute broker deadlines onto a local monotonic timeline without assuming synchronized wall clocks.

func (*Engine) Stats

func (e *Engine) Stats(ctx context.Context, queue string) (Metrics, error)

Stats returns pgmq-style counters for a queue (§7.3).

func (*Engine) Status added in v0.2.0

func (e *Engine) Status(ctx context.Context) Status

Status probes the engine's backend without exposing any secret. The ping is a real wall-clock read round-trip (most meaningful for a remote DB), independent of the injectable clock.

func (*Engine) Subscribe

func (e *Engine) Subscribe(ctx context.Context, topic, name string, filter *Filter) error

Subscribe registers subscription `name` under `topic`, creating the subscription's backing queue and the fan-out mapping (§10.1).

Names are guarded in BOTH directions so queue, subscription and topic names stay one disjoint namespace (MQLITE-57; ASB works the same way — entities share a namespace and same-name creation conflicts):

  • the subscription name must not belong to a plain queue or to a different topic's subscription — reusing it would silently merge two delivery targets into one backing queue (a pub/sub isolation breach);
  • the TOPIC name must not belong to any existing queue or subscription — otherwise queue and fan-out routing would share one address and a Send could not resolve it unambiguously;
  • topic == name is rejected: it would make the backing queue's own name resolve as the topic.

Per-topic-scoped subscription naming (reusing a name across topics) was considered and rejected in favor of this flat disjoint namespace — it moves the ambiguity into addressing instead of removing it.

func (*Engine) SubscribeWithOptions added in v0.4.0

func (e *Engine) SubscribeWithOptions(ctx context.Context, topic, name string, filter *Filter, opts SubscribeOptions) error

SubscribeWithOptions registers a subscription with an optional fixed lifetime. Re-subscribing may update the filter but never extends or changes the lifetime: an omitted TTL preserves it, the same positive TTL is idempotent, and a different positive TTL is rejected before any mutation.

func (*Engine) Tx

func (e *Engine) Tx(ctx context.Context, fn func(*EngineTx) error) error

Tx runs fn inside one transaction. A callback error or cancellation observed before commit rolls back the transaction. Otherwise Tx commits and notifies long-poll waiters for any written queue. Cancellation cannot interrupt a local callback: see SQL and Context for how callers should run their own statements and stop issuing them promptly.

fn MAY RUN MORE THAN ONCE on a remote store. inTx replays the whole closure when a transaction fails on a retryable connection/busy error — the database work of the failed attempt rolled back, so the DATA is correct either way, but anything fn did OUTSIDE the transaction happened twice. That is the contract, and it is not hypothetical: an HTTP call, a charge, a counter in memory does not roll back with a SQL transaction (round-4 §5.2). Keep fn to transaction-bound work.

Local file and :memory: stores never retry, so there fn runs zero or one time — zero when the caller was already cancelled before the transaction began.

fn MUST NOT call Close (directly or transitively). The transaction is a live operation that Close waits to finish before it tears the engine down, and fn cannot finish until it returns — so a Close from inside fn deadlocks, the same way locking a sync.Mutex you already hold does. Close the engine from outside its transactions.

type EngineTx

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

EngineTx is a transaction handle for same-DB transactional enqueue (§4.5). Business-table writes and queue enqueues commit together: "business success ⇔ message enqueued" — a natural outbox with no distributed-commit dilemma. Only valid in embedded mode against a local file / single libSQL connection.

func (*EngineTx) Context added in v0.3.0

func (t *EngineTx) Context() context.Context

Context is the context your own statements inside this transaction should use:

tx.SQL().ExecContext(tx.Context(), `INSERT INTO orders_tbl(id) VALUES (1)`)

Use it instead of the context you passed to Tx. On a LOCAL store it is deliberately not cancellable: interrupting a statement mid-transaction leaks the SQLite connection, which leaves the database locked (SQLITE_BUSY, permanently) — or, for `:memory:`, destroys it outright. The wait to enter the transaction still honours your context, and an already-cancelled caller never enters at all. A running statement is allowed to finish. Mqlite-owned statements (including SendOne) check the caller before each statement; raw SQL() calls do not. Check the original caller context between your own statements (see SQL).

There is no upper bound on how long "finish" takes — it is YOUR statement. On a remote store this IS your context, unchanged, and real statement cancellation still applies.

func (*EngineTx) SQL

func (t *EngineTx) SQL() *sql.Tx

SQL returns the underlying *sql.Tx so callers can run their business writes in the same transaction as the enqueue. It is for caller-owned tables; directly modifying mqlite's internal tables is unsupported and can bypass engine invariants. Engine owns BEGIN, COMMIT and ROLLBACK: do not take over those boundaries through SQL(). Early caller commits bypass rollback and safe-retry guarantees.

These are YOUR statements: mqlite cannot see where one ends and the next begins, so it cannot stop issuing them on your behalf the way it does for its own (see txn in db.go). Two things follow, and both matter on a local store, where this transaction holds the process's ONE writer:

  • Run them with Context(), never with the context you passed to Tx. Cancelling a statement mid-flight is what wedges the database.
  • Check the original caller context between your statements and return promptly on cancellation. SQL() bypasses mqlite's per-statement guards: statements using Context() can still execute after the caller cancels. If cancellation is observed before commit, Tx rolls back all writes after the callback returns, even if it returned nil. The callback holds the single writer until it returns; do slow work before opening the transaction.

func (*EngineTx) SendOne

func (t *EngineTx) SendOne(queue string, m OutMessage) (int64, error)

SendOne enqueues a message inside the open transaction.

type ErrorDetail added in v0.3.3

type ErrorDetail struct {
	AtMs        int64  `json:"at_ms"`
	Category    string `json:"category"`
	Message     string `json:"message"`
	Fingerprint string `json:"fingerprint"`
	HTTPStatus  int    `json:"http_status"`
	SQLiteCode  int    `json:"sqlite_code"`
}

ErrorDetail is safe for monitor credentials. Message is a generated description, never a provider response, SQL statement, URL, credential or message body. Fingerprint correlates it with the private operator log without exposing the text.

type Filter

type Filter struct {
	Expr string `json:"expr,omitempty"`
}

Filter is a subscription filter: a single expr-lang boolean predicate over a message. An empty Expr matches every message. The expression is type-checked and compiled once at Subscribe (a bad one is rejected with ErrInvalidFilter) and run per message at publish (fan-out). The language surface — the variables a filter sees, the helpers, and the fail-closed evaluator — lives in filter.go.

This replaces the earlier equality-AND + subject-prefix form: a filter is now just `subject_parts[0] == "orders" && properties["tier"] == "gold"` (MQLITE-17).

type FilterCounter added in v0.3.2

type FilterCounter struct {
	Stage string `json:"stage"`
	Count uint64 `json:"count"`
}

type FilterTestResult added in v0.2.0

type FilterTestResult struct {
	Valid   bool   `json:"valid"`           // the expression compiled
	Error   string `json:"error,omitempty"` // compile error, or a runtime/eval error when Ran
	Ran     bool   `json:"ran"`             // a sample message was evaluated
	Matched bool   `json:"matched"`         // the sample matched (meaningful only when Ran && Valid && Error == "")
}

FilterTestResult is a dry-run of a filter expression (TestFilter): whether it compiles and, if a sample message is given, whether it would match.

func TestFilter added in v0.2.0

func TestFilter(expr string, sample *OutMessage, enqueuedAtMs, visibleAtMs int64) FilterTestResult

TestFilter compiles a filter expression and, when sample != nil, evaluates it against that message exactly as publish-time fan-out would (same env, body-field gating, and fail-closed handling). It is pure and read-only — nothing is enqueued — so a console or `mqlite expr` REPL can validate / test an expression before it is used (MQLITE-17).

type KeyPermissions added in v0.3.1

type KeyPermissions uint8

KeyPermissions is a broker-wide set of access key capabilities.

const (
	KeySend   KeyPermissions = 1
	KeyListen KeyPermissions = 2
	// KeyManage includes sending, listening, entity administration and key issuance.
	KeyManage KeyPermissions = 7
)

func ParseKeyPermissions added in v0.3.1

func ParseKeyPermissions(names []string) (KeyPermissions, error)

ParseKeyPermissions validates and normalizes an explicit permission set. Manage includes send and listen; unknown names are rejected even beside manage.

func (KeyPermissions) Allows added in v0.3.1

func (p KeyPermissions) Allows(required KeyPermissions) bool

Allows reports whether a valid permission set grants every required capability.

func (KeyPermissions) Names added in v0.3.1

func (p KeyPermissions) Names() []string

Names returns the canonical public representation, or nil for an invalid set.

type ListAccessKeysOptions added in v0.3.1

type ListAccessKeysOptions struct {
	AfterID string
	Limit   int
	Sort    string
}

ListAccessKeysOptions selects a bounded page. An empty Sort means KeySortIDAsc. With KeySortCreatedDesc, AfterID must identify an existing key; its immutable creation time and ID form the page boundary, even if it is expired or revoked.

type ListSubscriptionsOptions added in v0.4.0

type ListSubscriptionsOptions struct {
	Topic           string
	After           string
	Limit           int
	IncludeDeleting bool
}

ListSubscriptionsOptions controls a bounded subscription inventory page. After is the opaque NextAfter cursor returned by the preceding request. Total and Subscriptions are read from one snapshot; later pages may observe changes.

type MaintenanceDiagnostics added in v0.3.3

type MaintenanceDiagnostics struct {
	LastOutcome         string               `json:"last_outcome"`
	LastRunAtMs         int64                `json:"last_run_at_ms"`
	ConsecutiveFailures uint64               `json:"consecutive_failures"`
	RecoveredAtMs       int64                `json:"recovered_at_ms"`
	RecentFailures      []MaintenanceFailure `json:"recent_failures"`
}

MaintenanceDiagnostics is an optional extension: absent means an older broker, not a healthy task. History is bounded to eight failed stages per task/process.

type MaintenanceFailure added in v0.3.3

type MaintenanceFailure struct {
	Stage string      `json:"stage"`
	Error ErrorDetail `json:"error"`
}

type MaintenanceObservation added in v0.3.2

type MaintenanceObservation struct {
	Enabled         bool                    `json:"enabled"`
	Task            string                  `json:"task"`
	Runs            uint64                  `json:"runs"`
	Interrupted     uint64                  `json:"interrupted"`
	Failures        uint64                  `json:"failures"`
	LastSuccessAtMs int64                   `json:"last_success_at_ms"`
	Duration        DurationHistogram       `json:"duration"`
	Diagnostics     *MaintenanceDiagnostics `json:"diagnostics,omitempty"`
}

type Message

type Message struct {
	SeqNumber     int64
	Body          []byte
	MessageID     string
	GroupID       string
	CorrelationID string
	ReplyTo       string
	Subject       string
	ContentType   string
	Properties    map[string]string
	DeliveryCount int
	EnqueuedAtMs  int64
	LockedUntilMs int64
	LockToken     string // fencing token; echoed back on settle
}

Message is a delivered message carrying the lock token (Peek-Lock).

type MessageCounter added in v0.3.2

type MessageCounter struct {
	Queue string `json:"queue"`
	Event string `json:"event"`
	Count uint64 `json:"count"`
}

type Metrics

type Metrics struct {
	Queue              string `json:"queue"`
	Active             int64  `json:"active"`
	Locked             int64  `json:"locked"`
	Deferred           int64  `json:"deferred"`
	Scheduled          int64  `json:"scheduled"`
	DeadLettered       int64  `json:"dead_lettered"`
	Total              int64  `json:"total"`
	OldestMessageAgeMs int64  `json:"oldest_message_age_ms"`
}

Metrics mirrors pgmq-style queue counters (§7.3 Stats).

type ObservabilitySnapshot added in v0.3.2

type ObservabilitySnapshot struct {
	SampledAtMs       int64                    `json:"sampled_at_ms"`
	ServerTimeMs      int64                    `json:"server_time_ms,omitempty"`
	StartedAtMs       int64                    `json:"started_at_ms"`
	Backend           string                   `json:"backend"`
	Runtime           RuntimeObservation       `json:"runtime"`
	Collection        CollectionStatus         `json:"collection"`
	QueueCount        int                      `json:"queue_count"`
	SubscriptionCount int                      `json:"subscription_count"`
	Queues            []QueueObservation       `json:"queues"`
	Messages          []MessageCounter         `json:"messages"`
	Storage           StorageObservation       `json:"storage"`
	Maintenance       []MaintenanceObservation `json:"maintenance"`
	Filters           []FilterCounter          `json:"filters"`
}

ObservabilitySnapshot is one engine-owned contract shared by native and Prometheus adapters. Counters are process-local, not a durable business ledger. Queues is nil when collection fails; the in-memory event domains remain usable.

type Options

type Options struct {
	DB                string       // DB DSN: file:./mq.db | :memory: | libsql://host
	AuthToken         string       // injected from env; never compiled in
	Now               func() int64 // test clock (epoch ms)
	DisableBackground bool         // skip reaper/scheduler loops (tests)
	// PreserveUnexpiredLeases is retained for source compatibility. Open now
	// preserves live Peek-Lock deliveries by default, so setting this field is no
	// longer necessary. Resource lifecycle and message TTL remain authoritative.
	//
	// Deprecated: live leases are preserved unless ReclaimUnexpiredLeases is set.
	PreserveUnexpiredLeases bool
	// ReclaimUnexpiredLeases explicitly treats every live Peek-Lock delivery as an
	// orphan during Open. Use this only for an embedded owner that knows all of its
	// in-process handlers are gone. It invalidates their fencing tokens and can
	// dead-letter a message on its final delivery attempt.
	ReclaimUnexpiredLeases bool
	Synchronous            string // local SQLite PRAGMA synchronous: NORMAL(default)|FULL|OFF
	MaxMessageBytes        int64  // reject bodies larger than this; 0 -> 1 MiB (§11.4)
	MaxSubscriptions       int    // retained active + deleting subscriptions; 0 -> 10,000
	// DLQ retention bounds (MQLITE-21): a background pass drops dead letters
	// oldest-first past these. ONLY state='dead_lettered' is touched; 0 = that
	// dimension unbounded. Defaults are applied by the broker, not the engine.
	DLQMaxAgeMs int64        // dead letters older than this (by enqueued_at) are dropped
	DLQMaxCount int          // keep at most this many dead letters per queue (drop oldest)
	DLQMaxBytes int64        // cap total dead-letter body bytes per queue (drop oldest)
	Logger      *slog.Logger // background-loop failures log here; nil -> slog.Default()
}

Options configures Open.

type OrderingMode

type OrderingMode string

OrderingMode is a queue-level delivery-ordering policy.

OrderStandard   — best-effort FIFO per group; ungrouped messages are each
                  their own group (max parallelism). The default.
OrderGroupFIFO  — strict in-order delivery within a group; GroupID is
                  required on every message (claim behaves like standard).
OrderStrictFIFO — strict single-flight global FIFO: the queue head blocks
                  the whole queue until it is settled (no grouping).
const (
	OrderStandard   OrderingMode = "standard"
	OrderGroupFIFO  OrderingMode = "group_fifo"
	OrderStrictFIFO OrderingMode = "strict_fifo"
)

type OutMessage

type OutMessage struct {
	Body      []byte
	MessageID string // dedup / idempotency key; empty -> body SHA-256 used when dedup on
	// GroupID is an ordering / partition key (= SQS MessageGroupId, ASB SessionId):
	// messages sharing a GroupID are delivered strictly in-order (FIFO per group);
	// empty -> the message is its own group (max parallelism). It is NOT a consumer
	// group — competing consumers just Receive the same queue and peek-lock hands
	// each message to exactly one of them.
	GroupID       string
	CorrelationID string
	ReplyTo       string // = ASB ReplyTo; opaque address the consumer should reply to
	Subject       string // = ASB Label
	ContentType   string
	Properties    map[string]string // custom KV (headers), JSON-encoded; broker does not interpret
	TTLMs         int64             // 0 -> queue default; negative is invalid; a positive queue default caps longer values
}

OutMessage is a message to enqueue. Body is opaque; the broker never parses it.

type PeekOptions

type PeekOptions struct {
	FromSeq int64
	State   State // empty -> any state
	Max     int
}

PeekOptions controls a Peek call.

type PeekedMessage

type PeekedMessage struct {
	SeqNumber             int64
	State                 State
	Body                  []byte
	MessageID             string
	GroupID               string
	CorrelationID         string
	ReplyTo               string
	Subject               string
	ContentType           string
	Properties            map[string]string
	DeliveryCount         int
	EnqueuedAtMs          int64
	VisibleAtMs           int64
	ExpiresAtMs           int64 // 0 = no TTL
	LockedUntilMs         int64
	DeadLetterReason      string
	DeadLetterDescription string
}

PeekedMessage is a read-only browse result (no lock, cannot be settled).

type PoolObservation added in v0.3.2

type PoolObservation struct {
	MaxOpen             int     `json:"max_open"`
	Open                int     `json:"open"`
	InUse               int     `json:"in_use"`
	Idle                int     `json:"idle"`
	WaitCount           int64   `json:"wait_count"`
	WaitDurationSeconds float64 `json:"wait_duration_seconds"`
}

type QueueConfig

type QueueConfig struct {
	Kind               string       // "queue" (default) or "subscription"
	LockDurationMs     int64        // Peek-Lock duration; 0 -> 30000, otherwise 1000..3600000
	MaxDeliveryCount   int          // ordinary claim budget; 0 -> 10, and the final claim remains usable
	DefaultTTLMs       int64        // default and ceiling for message TTL; 0 -> unlimited
	DeadLetterOnExpire *bool        // nil -> true
	DedupWindowMs      int64        // 0 -> dedup disabled
	Ordering           OrderingMode // "" -> standard
	// Per-queue DLQ retention overrides (MQLITE-29). For each: 0 -> inherit the
	// broker/engine default; >0 -> this queue's own drop-oldest bound; -1 ->
	// explicitly unbounded (opt out of the default).
	DLQMaxAgeMs int64 // dead letters older than this (by enqueued_at) are dropped
	DLQMaxCount int   // keep at most this many dead letters in this queue
	DLQMaxBytes int64 // cap total dead-letter body bytes in this queue
}

QueueConfig configures a queue or subscription (entity-level defaults). Zero values mean "use the documented default".

type QueueInfo

type QueueInfo struct {
	State            string `json:"state"`
	Name             string `json:"name"`
	Kind             string `json:"kind"`
	LockDurationMs   int64  `json:"lock_duration_ms"`
	MaxDeliveryCount int    `json:"max_delivery_count"`
	DefaultTTLMs     int64  `json:"default_ttl_ms"`
	DedupWindowMs    int64  `json:"dedup_window_ms"`
}

QueueInfo describes a queue for listing.

type QueueObservation added in v0.3.2

type QueueObservation struct {
	Metrics
	Kind       string `json:"kind"`
	Unexpected int64  `json:"unexpected"`
}

QueueObservation is the canonical queue snapshot. Total includes unexpected retained states, which are reported separately rather than silently discarded.

type ReceiveMode

type ReceiveMode int

ReceiveMode selects Peek-Lock (default) or Receive-and-Delete (at-most-once fast path).

const (
	PeekLock ReceiveMode = iota
	ReceiveAndDelete
)

type ReceiveOptions

type ReceiveOptions struct {
	MaxMessages int
	WaitMs      int64 // long-poll up to 20000
	Mode        ReceiveMode
	// AttemptID, when set, makes Receive idempotent under client retries: a retry
	// with the same id replays the same batch while every Peek-Lock lease remains
	// valid. If any lease is no longer owned, the stale response is invalidated and
	// the retry safely performs a new claim. ReceiveAndDelete responses remain
	// replayable for the attempt lifetime. While a non-empty saved response is
	// live, every use of its ID must keep the original Mode (SQS ReceiveRequestAttemptId).
	AttemptID string
}

ReceiveOptions controls a Receive call.

type RedriveOptions

type RedriveOptions struct {
	Target      string // empty -> back to source queue (in-place); else cross-queue re-INSERT
	Max         int
	OlderThanMs int64
	RatePerSec  int
}

RedriveOptions controls a Redrive call (§11.2).

type RuntimeObservation added in v0.3.2

type RuntimeObservation struct {
	SchemaVersion   string  `json:"schema_version"`
	PingSeconds     float64 `json:"ping_seconds"`
	ReadAvailable   bool    `json:"read_available"`
	DBSizeBytes     int64   `json:"db_size_bytes"`
	DBSizeAvailable bool    `json:"db_size_available"`
}

RuntimeObservation holds the same probe used by legacy Status, without its administrative location. Durations retain monotonic sub-millisecond precision.

type SettleItem added in v0.1.1

type SettleItem struct {
	SeqNumber int64
	LockToken string
}

SettleItem identifies one message to settle in a batch (fenced on LockToken).

type SettleResult added in v0.1.1

type SettleResult struct {
	SeqNumber int64
	Ok        bool // true = succeeded (or a live receipt replays this exact settlement request)
	// LockedUntilMs is the deadline a RenewBatch actually committed (0 for other operations). The
	// caller needs it: without the new deadline it cannot know when to renew again, and would
	// either hammer the broker or let the lease it just extended lapse.
	LockedUntilMs int64
}

SettleResult is the per-item outcome of a batch settle.

type State

type State string

State is the lifecycle state of a message (design §6).

const (
	StateActive       State = "active"
	StateLocked       State = "locked"
	StateDeferred     State = "deferred"
	StateScheduled    State = "scheduled"
	StateCompleted    State = "completed"
	StateDeadLettered State = "dead_lettered"
)

type Status added in v0.2.0

type Status struct {
	Backend       string // "memory" | "local file" | "remote libSQL/Turso"
	Remote        bool
	Location      string // ":memory:", a local path, or libsql://***.host (masked)
	SchemaVersion string
	PingMs        int64 // a SELECT 1 read round-trip (the durable read latency); -1 if it failed
	SizeBytes     int64 // local on-disk footprint (db + -wal + -shm); 0 for memory/remote
	ServerTimeMs  int64 // the injectable engine clock after the runtime probe
}

Status is a desensitized snapshot of the engine's runtime, safe to surface in an admin UI. The location of a local DB is its on-disk path (shown to help operators); a remote DB's host is masked and its auth token is NEVER part of any field.

type StorageDimension added in v0.3.2

type StorageDimension struct {
	Operation string `json:"operation"`
	Outcome   string `json:"outcome"`
	ErrorCode string `json:"error_code"`
}

StorageDimension identifies one bounded storage operation measurement.

func StorageDimensions added in v0.3.2

func StorageDimensions() []StorageDimension

StorageDimensions returns a fresh copy of every required storage counter label. Future dimensions may be added without changing existing measurement meanings.

type StorageObservation added in v0.3.2

type StorageObservation struct {
	Operations []StorageOperation `json:"operations"`
	Pool       PoolObservation    `json:"pool"`
}

type StorageOperation added in v0.3.2

type StorageOperation struct {
	Operation string            `json:"operation"`
	Outcome   string            `json:"outcome"`
	ErrorCode string            `json:"error_code"`
	Duration  DurationHistogram `json:"duration"`
	Retries   uint64            `json:"retries"`
	LastError *ErrorDetail      `json:"last_error,omitempty"`
}

type SubscribeOptions added in v0.4.0

type SubscribeOptions struct {
	TTLMs int64
}

SubscribeOptions controls creation-only subscription properties. TTLMs is a fixed lifetime measured from the first successful creation. Zero creates a permanent subscription and, on a retry, preserves any existing lifetime.

type SubscriptionInfo added in v0.2.0

type SubscriptionInfo struct {
	Topic string `json:"topic"`
	Name  string `json:"name"`
	Expr  string `json:"expr,omitempty"` // the filter expression; "" = match all
}

SubscriptionInfo describes one topic→subscription mapping and its filter.

type SubscriptionPage added in v0.4.0

type SubscriptionPage struct {
	Subscriptions []SubscriptionPageItem `json:"subscriptions"`
	Total         int                    `json:"total"`
	NextAfter     string                 `json:"next_after,omitempty"`
}

SubscriptionPage is one keyset-ordered inventory page from a consistent current snapshot. Total is the exact number of subscriptions in the requested scope before applying After; separate page requests do not share a snapshot.

type SubscriptionPageItem added in v0.4.0

type SubscriptionPageItem struct {
	Topic       string `json:"topic"`
	Name        string `json:"name"`
	Expr        string `json:"expr,omitempty"` // the filter expression; "" = match all
	State       string `json:"state"`
	CreatedAtMs int64  `json:"created_at_ms"`
	ExpiresAtMs int64  `json:"expires_at_ms"`
}

SubscriptionPageItem is one subscription in the lifecycle-aware paged inventory. State is active or deleting.

Jump to

Keyboard shortcuts

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