engine

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 31 Imported by: 0 modules, 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

Overview

Package engine is skylite's storage engine: it keeps a database in object storage as decision record 0004 (docs/content/docs/decisions/0004-storage-engine.md) lays it out, in the objects package format encodes. It creates a database (Create), reads its pages as of a transaction number (Open, Reader), opens read-only SQLite snapshots (Follow, Follower), and takes office by lease, epoch swap and epoch bump (Takeover, Office, Lease).

Reading

A Reader reads one state of the database: the state after one transaction number. Open reads the manifest, which names the base, the group objects the database's pages were last compacted into, current to the manifest's transaction number. It then reads the commit log above that number by direct reads of consecutive names, the header and then the page table of each commit, up to the requested transaction or, for the head, until a name is absent. The log is never listed. From those it keeps an index from page number to the newest commit that holds the page; it takes memory in proportion to the pages in the log above the manifest, which compaction keeps short, not to the size of the database.

ReadPage serves a page from the newest commit at or below the reader's transaction that holds it, else from the page's group object in the base, else as zeros: a group the manifest gives no object, or a page that was beyond the database size at some commit after its last write, reads as zeros. Each page costs one ranged read of its record, verified by the record's checksum, which binds it to its page, object and database. Every header read is checked against its key, every object against the database identifier, and every log object's version token is pinned when it is indexed and checked on every later read of it that reaches storage; a cache hit returns the bytes of the version the reader pinned.

Looking for the head, a reader probes one name above the first absent one: a present name there is a gap in the log. A reader walks at most 65,536 commits and indexes at most 4,194,304 page entries above the manifest, and fails closed with ErrLimit beyond them. Readers whose manifests hold equal group references share one copy of them.

Falling behind

Compaction folds the log into a newer base and then retires the commits it covers and deletes base objects no manifest references any more. A reader that finds a retired commit above its manifest's transaction number, a log object whose version changed, or a missing base object re-reads the manifest. A newer manifest at or below the reader's transaction re-anchors it: the same state, built from the newer base and the commits above it that the reader has already indexed. A newer manifest above the reader's transaction means that state can no longer be built, and the read fails with ErrCompacted; Advance moves the reader on. A changed or missing object that no newer manifest explains is ErrCorrupt. Every re-anchoring needs a manifest with a higher transaction number than the last, so it cannot repeat without bound.

Index

Constants

View Source
const FollowerMaxWait = 500 * time.Millisecond

FollowerMaxWait bounds the time spent waiting for a fresh snapshot.

Variables

View Source
var (
	// ErrNotCommitted means the transaction is not in the durable history
	// and never will be.
	ErrNotCommitted = errors.New("engine: transaction not committed")
	// ErrUnknown means the transaction may be in the durable history, now
	// or later. The leader has stopped.
	ErrUnknown = errors.New("engine: commit outcome unknown")
	// ErrRetry, with ErrNotCommitted, means the transaction was refused or
	// rolled back while the leader brings its local WAL or its log tail
	// back under their bounds, and can be retried.
	ErrRetry = errors.New("engine: writes are refused for now; retry")
	// ErrTooLarge, with ErrNotCommitted, means the transaction does not fit
	// in one commit object or in the local WAL bound.
	ErrTooLarge = errors.New("engine: transaction too large")
	// ErrTailBound, with ErrNotCommitted, means the log above the manifest
	// is at the leader's tail bound. Reads and writes are refused until a
	// compaction clears it, and the error also matches ErrRetry. If the
	// leader cannot compact, because the new manifest would pass its
	// maximum size, it does not match ErrRetry and says why: the refusal
	// lasts for the life of the leader.
	ErrTailBound = errors.New("engine: the log tail is at its bound until a compaction clears it")
	// ErrBroken means the Run panicked outside the commit path, as on a
	// stack overflow in SQLite, or its function reported the connection
	// broken by returning an error that wraps ErrBroken. The engine has
	// discarded the connection without SQLite's cooperation and released its
	// locks; nothing of the Run's open transaction is visible. With
	// ErrNotCommitted the Run committed nothing; with a nonzero txn its
	// commit stands and the connection broke after it. The break does not
	// stop the leader (record 0004, decision 6); a connection that could not
	// be discarded stops it instead, and its Run does not report ErrBroken.
	ErrBroken = errors.New("engine: connection broken and discarded")
	// ErrFenced means another candidacy's epoch bump holds the leader's next
	// transaction number. The leader has stopped.
	ErrFenced = errors.New("engine: fenced by another leader's epoch bump")
	// ErrStopped means the leader no longer serves the database on this
	// node: it failed, was fenced or was closed. It serves again only
	// through a new takeover.
	ErrStopped = errors.New("engine: the leader has stopped")
)

Errors a commit, a connection or the leader report. A commit's outcome is exactly one of: committed (Run returns its transaction number), not committed (the error wraps ErrNotCommitted) or unknown (it wraps ErrUnknown). Decision 6 of record 0004 defines them.

View Source
var (
	// ErrCorrupt means storage holds something that breaks a rule relating
	// objects to each other: a gap in the log, a changed or missing object
	// no newer manifest explains, a manifest that went backwards or that
	// disagrees with the commit at its transaction number, or an object
	// whose size or page size contradicts its header or manifest. Errors the
	// decoders of package format find wrap their own classes instead.
	ErrCorrupt = errors.New("engine: storage contradicts the log or the manifest")
	// ErrCompacted means the requested transaction is below the base of the
	// current manifest, so its state can no longer be built.
	ErrCompacted = errors.New("engine: transaction is below the current base")
	// ErrBeyondHead means the requested transaction is not in the log.
	ErrBeyondHead = errors.New("engine: transaction is beyond the head of the log")
	// ErrPageRange means a page number is 0 or above the database size.
	ErrPageRange = errors.New("engine: page number out of range")
	// ErrLimit means the log above the manifest has more commits or page
	// entries than a reader indexes, or reaches the largest transaction
	// number. The reader fails closed; a compaction brings the log back
	// within the limits.
	ErrLimit = errors.New("engine: the log above the manifest is beyond the reader's limits")
)
View Source
var (
	// ErrLost means a candidacy ended without office because another
	// candidacy changed the manifest: the epoch swap was beaten, or the
	// manifest no longer carries the candidate's epoch and nonce. The
	// candidate never serves at that epoch; a node may start a new
	// candidacy. Lease.Retake returns it when the manifest has moved past
	// the lease's epoch: its leader is deposed.
	ErrLost = errors.New("engine: candidacy lost to another")
	// ErrExhausted means an epoch or a transaction number is at its maximum,
	// so the database cannot take another takeover or another commit. It
	// stops instead of wrapping (invariant 1).
	ErrExhausted = errors.New("engine: epoch or transaction number at its maximum")
)
View Source
var ErrBehind = errors.New("engine: follower is behind")

ErrBehind means the follower did not observe a fresh snapshot at or above the requested transaction within its catch-up budget.

View Source
var ErrExists = errors.New("engine: a database already exists under this prefix")

ErrExists means another creator's database already holds the prefix.

View Source
var ErrLeaseHeld = errors.New("engine: the lease is held by another holder")

ErrLeaseHeld means another holder holds the lease: its last renewal is younger than the lease's time to live, or it replaced this holder's lease. Every error that matches it is a *LeaseHeldError.

View Source
var ErrStale = fmt.Errorf("%w: no fresh snapshot", ErrBehind)

ErrStale means the follower has no fresh observation of the log's end.

Functions

func Create

func Create(ctx context.Context, st storage.Store, keys format.Keys, pageSize, groupSize uint32) (format.DatabaseID, error)

Create creates a new database under keys' prefix, as decision 3 of the storage engine record describes: it draws a database identifier, creates the first commit object (transaction 1, epoch 1, holding the empty WAL-mode database at pageSize) and only after that create has resolved as its own creates the first manifest. It returns the new database's identifier.

If another creator's manifest is already there, Create returns that database's identifier and an error wrapping ErrExists; the caller uses the database that won. A manifest present before Create starts is found by reading it, and nothing is written. Objects a losing or abandoned creator wrote stay under an identifier no manifest names. Create gives up with an error when it cannot resolve either create within its attempts; an error that wraps storage.ErrOutcomeUnknown means a create may still land.

func Takeover

func Takeover(ctx context.Context, st storage.Store, keys format.Keys, c Candidate) (Office, *Lease, error)

Takeover runs one candidacy for the database under keys' prefix, as decision 9 of the storage engine record describes, and returns the resulting Office and the node's lease:

  1. It reads the manifest and takes the lease for the manifest's epoch plus one.
  2. It swaps the manifest to that epoch with a new writer nonce, conditioned on the version it read, and resolves the outcome as decision 6 says, recognising its own swap by its bytes.
  3. It walks the commit log from the manifest's transaction number to the head. A retired commit or a log object whose version changes under it sends it back to the manifest. Once a third of the lease's time to live has passed since its last lease write, or its last attempt at one, it tries to renew the lease; the outcome ends nothing, because only the manifest decides whether the candidacy goes on.
  4. Before every attempt at its epoch-bump commit it re-reads the manifest and gives up unless the manifest still carries its epoch and nonce. It creates the bump at the head plus one, recognising its own bump by its bytes, which its epoch determines, reading back at most one byte more than the bump. If another object holds the name, it walks on and tries again; it moves only past a name another object occupies, so a candidacy has at most one bump in the log, and a walk that does not reach that name is corruption.
  5. It reads the manifest again and takes office only if the manifest still carries its epoch and nonce. If a renewal in step 3 found the lease taken, it takes it back by step 1's rules, best effort.

Another candidacy can take the lease while this one runs, so the returned Lease may be one that another holder holds: its Renew then reports ErrLeaseHeld.

Every conditional write is repeated identically after an unknown outcome until it has a definite answer, up to a bound. Without a definite success for its swap or its bump the candidate gives up: Takeover returns an error, and one that wraps storage.ErrOutcomeUnknown means that write may still land. An error means the candidate never serves at that epoch. It holds no Office and gets no Lease. A candidacy whose swap definitely did not land releases the lease it took; any other leaves it to expire, or to be taken back by the same holder's next candidacy.

Types

type Cache

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

Cache holds verified page bodies fetched from storage, up to a fixed number of bytes of heap, and evicts the least recently used. Entries are keyed by the immutable identity of what was fetched (object key, version token and offset), so a hit is always the bytes that object version holds there; which object a page is read from is decided by the reader, never by the cache. Correctness never depends on it. A Cache is safe for concurrent use, and its lock is never held while storage is read. A nil *Cache caches nothing.

func NewCache

func NewCache(budget int64) *Cache

NewCache returns a cache that holds at most budget bytes: keys, page bodies and a fixed overhead per entry. A budget of zero or less caches nothing.

type Candidate

type Candidate struct {
	// Holder names the node in the lease: 1 to 128 of A-Z a-z 0-9 . _ -.
	// Two processes that run at once never share it.
	Holder string
	// TTL is how long a lease lasts after its last renewal.
	TTL time.Duration
	// Now is the clock the lease is stamped and judged by.
	Now func() time.Time
}

Candidate is a node attempting a takeover.

type Config

type Config struct {
	// WALBound is the largest the local WAL file may grow, in bytes. A
	// write past it rolls its transaction back and starts maintenance.
	WALBound int64
	// TailBound is how many commits, epoch bumps included, the log may
	// hold above the manifest's transaction number, at most 32,768. Once it
	// holds that many, or 2,097,152 page entries, commits are refused and
	// maintenance starts, which compacts. Those are half of what a reader
	// walks (record 0004 decision 10). Compaction starts in the background
	// at half of either, or at CompactBytes.
	TailBound uint64
	// CompactBytes starts a compaction once the commit objects above the
	// manifest hold this many bytes; 256 MiB if 0.
	CompactBytes int64
	// CompactInterval starts a compaction once this long has passed since
	// the last one and the log above the manifest is not empty; a minute if
	// 0.
	CompactInterval time.Duration
	// Grace is how long a manifest has been current before the commits it
	// covers are retired, and how long base objects found to be garbage
	// wait before they are deleted, so that readers on older manifests
	// usually finish; five minutes if 0. Safety does not depend on it.
	Grace time.Duration
	// MaxMemory is each connection's SQLite memory ceiling in bytes.
	MaxMemory int64
	// TempBudget is the most bytes SQLite's temporary files (sorts,
	// temporary tables, statement journals) may hold at once over all the
	// leader's connections. A write past it fails its statement with
	// SQLITE_FULL, which can make SQLite roll back the whole transaction;
	// the budget is shared, so another connection's sort can cause that.
	TempBudget int64
	// Cache holds pages read from storage; it may be shared.
	Cache *Cache
}

Config sets a leader's local limits.

type Conn

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

Conn is one SQLite connection to the leader's database. It is safe for concurrent use, one Run at a time.

func (*Conn) Aborted

func (c *Conn) Aborted() <-chan struct{}

Aborted returns a channel that is closed once the engine has ended the connection's transaction, or will refuse it, without its client asking: maintenance rolled it back (record 0004 decision 10, steps 4 and 5), or the leader stopped. The connection's next Run fails and says why. Close, and a discard after a panic, close it too. A server that holds its own write lock for the transaction waits on it to release that lock and report the failure (record 0005, requirement 15). SQLite itself rolls an explicit transaction back when it interrupts a write statement in it, as at the end of a Run's context: the channel stays open then, the Run's error is the signal, and the connection's transaction state is NONE.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection, rolling back an open transaction.

func (*Conn) Run

func (c *Conn) Run(ctx context.Context, id []byte, f func(db *sqlite3.Conn) error) (txn uint64, err error)

Run runs f on the connection. f may run any SQL, but must not keep db or statements beyond its return, and must not replace db's interrupt context. ctx ends f's statements when it is done, page reads from storage included; Close, and maintenance, end them too. id is the commit identifier, at most format.MaxCommitIDLen bytes, of the one transaction f may commit; a commit without one, or a second commit in one Run, is refused as not committed. A transaction that changes no page commits nothing and needs none. f may close a writing statement before stepping it to its end, as with an INSERT ... RETURNING whose rows it does not all read: in autocommit SQLite then commits it at the close, and the Run reports that commit as any other.

Every Run ends in exactly one of these classes:

  • txn is nonzero: f's commit is in the durable history. A non-nil error then means committed-then-failed: it reports what failed later in the Run and matches neither ErrNotCommitted nor ErrUnknown, so a caller must look at txn before err. It matches ErrBroken if the connection broke after the commit.
  • txn is 0 and err is nil: f succeeded and committed nothing.
  • err matches ErrNotCommitted: the Run committed nothing, and nothing of it can enter the history. It also matches ErrStopped if the leader stopped, ErrBroken if the connection broke and was discarded, ErrRetry if a retry can succeed, ErrTailBound at the tail bound, ErrTooLarge if no retry can, and wraps f's own error, if any. A transaction f left open stays open for the next Run unless maintenance rolled it back, which the error says, or SQLite did, which it does not: SQLite can roll the whole transaction back after SQLITE_FULL (the temporary-file budget's included), SQLITE_IOERR, SQLITE_NOMEM or an interrupt, so f reads db.GetAutocommit() after a failed statement (record 0005, decision 6).
  • err matches ErrUnknown: f's commit may be in the history, now or later. The leader has stopped.

type Follower

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

Follower tails the durable history of one database. Its published Reader and index are immutable and may be shared by any number of pins.

func Follow

func Follow(ctx context.Context, st storage.Store, keys format.Keys, cache *Cache) *Follower

Follow starts polling the database under keys' prefix. Before closing the store, cancel ctx, wait on Done and close its ReadConns. Open waits at most 500 ms for the initial walk, then returns ErrBehind. cache may be nil.

func (*Follower) Done

func (f *Follower) Done() <-chan struct{}

Done closes when the follower stops polling.

func (*Follower) Fresh

func (f *Follower) Fresh() bool

Fresh reports whether the follower can currently admit a snapshot.

func (*Follower) Open

func (f *Follower) Open(ctx context.Context, minTxn uint64) (*ReadConn, error)

Open pins a fresh snapshot at or above minTxn and opens a read-only SQLite connection on it. It waits at most 500 ms for the pin, subject to ctx. Each connection stays on its transaction until closed. Canceling the follower stops new admissions, and existing connections keep their pins.

func (*Follower) Pin

func (f *Follower) Pin(ctx context.Context, minTxn uint64) (*ReadPin, error)

Pin waits for a fresh snapshot at or above minTxn, subject to ctx and FollowerMaxWait. Opening SQLite on the pin can use a separate budget.

type Found

type Found int

Found is what a leader found at the name where it tried to create its next commit, after the create failed its precondition (decision 6).

const (
	// FoundUnknown is anything that is neither of the others. An invariant
	// is broken: the leader stops as for an indeterminate commit, and the
	// client is told unknown.
	FoundUnknown Found = iota
	// FoundOwn is the leader's own commit, live or retired: committed.
	FoundOwn
	// FoundBump is another candidacy's epoch bump: the leader is fenced, the
	// commit is definitely not committed, and the leader fail-stops.
	FoundBump
)

type Leader

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

Leader serves one database on this node while it holds office: SQLite in WAL mode with a main file served from object storage, and every commit created in the commit log before SQLite reports it, as record 0004 decisions 5 to 7 and 10 describe.

func Lead

func Lead(ctx context.Context, st storage.Store, keys format.Keys, dir string, office Office, cfg Config) (*Leader, error)

Lead serves the database as the holder of office. dir is a local directory for cache files: Lead keeps this database's files in a subdirectory named after its identifier, deletes whatever that subdirectory held, and deletes it again at Close. Lead reads the manifest and the log tail up to office.Head, never the database's pages.

func (*Leader) Close

func (l *Leader) Close() error

Close stops serving, closes every connection once its Run has returned, and deletes the database's local files.

func (*Leader) Err

func (l *Leader) Err() error

Err is nil while the leader serves, and otherwise wraps ErrStopped and says why it stopped.

func (*Leader) Head

func (l *Leader) Head() uint64

Head is the transaction number of the leader's last commit.

func (*Leader) Lookup

func (l *Leader) Lookup(id []byte, above uint64) (txn, firstBump, head uint64, ok bool)

Lookup answers a resolve (record 0005, decision 4) from the leader's headers, in one observation ordered against every head advance: txn is the transaction above `above` that carries commit identifier id, and firstBump the first epoch bump above `above`, each 0 if there is none, and head is the leader's head. Every value of above is valid. ok is false if the headers held do not cover every transaction from above+1 to head. This version holds the headers above the manifest it took office on and of each commit since, and once a compaction has passed them drops those more than 65,536 numbers below the head, so ok is false for `above` below that point; a caller must read that as unknown, never as not committed. It reads no header from storage. Lookup answers from memory on a stopped leader too: the caller does decision 4's step 1 itself, with Err. A caller that also reads a table of its own channels reads it before Lookup: a channel it found absent can then send no commit above head.

func (*Leader) Open

func (l *Leader) Open(ctx context.Context) (_ *Conn, err error)

Open opens a new SQLite connection to the database. ctx bounds the Open: its storage reads and SQLite's set-up statements end when ctx is done, and a panic in them discards the connection if SQLite then closes it, and otherwise stops the leader (record 0007, requirement 5). An Open that fails without a panic after maintenance has cancelled its storage reads fails with an error that matches ErrNotCommitted and ErrRetry, whatever ended it: SQLite reports a failed read as an I/O error without its cause, so a storage error during maintenance is told to retry too.

func (*Leader) Snapshot

func (l *Leader) Snapshot(ctx context.Context, start func() error) (uint64, error)

Snapshot runs start, which must begin a read transaction on one of the leader's connections, and returns the transaction number of the snapshot that read holds (record 0005, requirement 12). The number is exact: Snapshot first waits until no commit is between its create and SQLite's completion of it, so the head is the newest commit SQLite has published, and while start runs no create begins, so neither changes before the read has taken its snapshot. That wait lasts for each commit it meets, a create of up to createAttempts attempts and SQLite's completion; a writer queued behind that commit can begin its create first, so the wait can span several commits. It ends with ctx's error when ctx is done. Commits wait while start runs, so start should only begin the read, with a statement that reads little, such as PRAGMA schema_version inside BEGIN; its storage reads end with its Run's context. start must not wait for SQLite's write lock: a writer holding it may be waiting for start to end before its create, so a BEGIN IMMEDIATE would wait out the busy timeout. A write transaction's number is Head() once BEGIN IMMEDIATE has returned: no commit lands while it holds the lock, and SQLite publishes a commit before it releases it.

type Lease

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

Lease is a node's hold on a database's lease object, the one at format.Keys.Lease. Decisions 3 and 9 of the storage engine record give the lease one purpose: it decides which node attempts a takeover, and when, so that takeovers make progress. It is never a fence. Holding it gives no right to write, losing it takes none away, and no safety argument reads it; a node in office is stopped only by the conditional writes of the log and the manifest (see Office.Recognise and Office.Holds).

A lease names its holder, the epoch the holder leads or intends to lead at, and the time of its last renewal by the holder's clock. Another node treats it as expired once its own clock is at least the time to live past that renewal, or more than the time to live before it, so clock skew between nodes moves only when takeovers start. Every write of the lease is conditional, so a holder never overwrites a lease it has not read. A write that fails its precondition and finds a lease with the writer's own holder and epoch finds the writer's own earlier write, whose outcome was unknown: holder names are unique among running processes, and each candidacy has its own epoch. The writer adopts its version and writes once more.

A node that leaves office cleanly calls Release. A node that fail-stops (decision 6) does neither Renew nor Release: it issues no further write for the database, and its lease expires. A Lease is not safe for concurrent use.

func (*Lease) Release

func (l *Lease) Release(ctx context.Context) error

Release gives the lease up on a clean stop, by rewriting it with renewal time 0, which every other node reads as expired. ErrLeaseHeld means another holder had already taken it.

func (*Lease) Renew

func (l *Lease) Renew(ctx context.Context) error

Renew refreshes the lease's renewal time. ErrLeaseHeld means another holder has taken it: a candidacy that is under way, or one that has since lost. Renew never takes the lease back; Retake does. The error does not depose the holder; only the log and the manifest can.

func (*Lease) Retake

func (l *Lease) Retake(ctx context.Context) error

Retake takes the lease back for this holder at its epoch, by the rules of a candidate's lease step: it writes the lease if the stored one is this holder's, or another holder's that is released or expired, and returns ErrLeaseHeld, writing nothing, if another holder's lease is live. A leader calls it when Renew reports ErrLeaseHeld and the lease reads as released or expired. The epoch it writes is the lease's own, never another.

It first reads the manifest and returns ErrLost, writing nothing, unless the manifest still carries the lease's epoch: a deposed leader must not hold back the next takeover. That check is not a fence. The manifest can move between the read and the lease write, so a deposed leader may still take the lease once; it remains deposed, because only the log and the manifest decide who leads. Retake gives no right to write. Renew does not read the manifest, so a lease retaken in that window is kept by Renew, and every other holder and candidate is refused it, until the holder reads the manifest: the caller must check the manifest on its renewal cadence, not only when Renew fails.

type LeaseHeldError

type LeaseHeldError struct {
	// Holder is the holder the lease names; empty if it does not decode.
	Holder string
	// Expires is when the lease expires by this node's clock unless it is
	// renewed: a candidate may try again then.
	Expires time.Time
	// contains filtered or unexported fields
}

LeaseHeldError is the error of a lease that another holder, or an earlier candidacy of the same holder, holds. It matches ErrLeaseHeld.

func (*LeaseHeldError) Error

func (e *LeaseHeldError) Error() string

func (*LeaseHeldError) Is

func (e *LeaseHeldError) Is(target error) bool

Is makes a LeaseHeldError match ErrLeaseHeld.

type Office

type Office struct {
	DB    format.DatabaseID
	Epoch uint64   // the epoch this node swapped into the manifest
	Head  uint64   // the transaction number of this node's epoch bump
	Nonce [16]byte // the writer nonce this node put in the manifest
}

Office is what a node holds once its takeover of a database has completed: the right to create commits at its epoch, starting after its own epoch bump.

func (Office) Holds

func (o Office) Holds(m format.Manifest) bool

Holds reports whether manifest m still carries office o's database, epoch and writer nonce. A leader that reads a manifest it does not hold stops compacting and leaves office (decision 8); a candidate takes office only if it holds the manifest after its bump (decision 9).

func (Office) Recognise

func (o Office) Recognise(built, found []byte) (Found, error)

Recognise decides what found, the bytes read at the name of the commit the leader in office o built as built, means (decision 6, "Resolving a create"). The first object created at a leader's next name is its own commit or some candidate's epoch bump, and it is the only object that name will ever hold. So found is FoundOwn if it is built or built's retired form, and FoundBump if it is a valid epoch bump of database o.DB at that name with an epoch other than o.Epoch. Anything else, an absent object (found empty) included, is FoundUnknown, with an error saying why.

built must be an ordinary commit of office o above o.Head, the office's epoch bump, which never changes: the commit path keeps its own head. A caller reads at most len(built)+1 bytes at the name: every object Recognise accepts is at most len(built) bytes long, because a retired form and a bump are a commit header, so a longer object cut there is FoundUnknown as it would be whole.

type ReadConn

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

ReadConn is a SQLite connection on one durable follower snapshot. Run and Close are serialized. The caller must close its statements before closing the connection.

func (*ReadConn) Close

func (c *ReadConn) Close() error

Close releases the connection and its snapshot.

func (*ReadConn) Run

func (c *ReadConn) Run(ctx context.Context, fn func(*sqlite3.Conn) error) (err error)

Run uses ctx for SQLite interrupts and reads from storage. The callback uses SQLite synchronously and must not retain the connection. SQL admission policy is the caller's responsibility. A panic in fn, or an error of fn's that wraps ErrBroken, breaks the connection: Run then fails with ErrBroken, later Runs refuse, and Close frees it without SQLite.

func (*ReadConn) Txn

func (c *ReadConn) Txn() uint64

Txn returns the snapshot's durable transaction number.

type ReadPin

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

ReadPin is one immutable follower snapshot. It retains its transaction even if compaction later makes that transaction unreadable.

func (*ReadPin) Open

func (p *ReadPin) Open(ctx context.Context) (*ReadConn, error)

Open opens a read-only SQLite connection on this pin, subject to ctx.

func (*ReadPin) Txn

func (p *ReadPin) Txn() uint64

Txn returns the pin's durable transaction number.

type Reader

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

Reader reads the pages of one database as of one transaction number. A Reader is not safe for concurrent use; many Readers may share a Store and a Cache.

func Open

func Open(ctx context.Context, st storage.Store, keys format.Keys, cache *Cache, txn uint64) (*Reader, error)

Open opens the database under keys' prefix for reading as of transaction txn, or as of the head of the log if txn is 0. A txn below the current manifest's is ErrCompacted, and one above the head ErrBeyondHead. cache may be shared between Readers; a nil cache caches nothing.

func (*Reader) Advance

func (r *Reader) Advance(ctx context.Context) error

Advance moves the reader to the head of the log. It reads only the commits it has not indexed yet, and the manifest only if its version changed; pages still current stay cached. On an error the reader stays where it was.

func (*Reader) PageSize

func (r *Reader) PageSize() uint32

PageSize is the database's page size in bytes.

func (*Reader) ReadPage

func (r *Reader) ReadPage(ctx context.Context, pgno uint32) ([]byte, error)

ReadPage returns page pgno, from 1 to Size, as of Txn. The caller owns the returned slice. On an error the reader stays at Txn and can be used again.

func (*Reader) Size

func (r *Reader) Size() uint32

Size is the database size in pages as of Txn.

func (*Reader) Txn

func (r *Reader) Txn() uint64

Txn is the transaction number the reader reads as of.

Jump to

Keyboard shortcuts

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