Documentation
¶
Overview ¶
Package ledger is a durable record per key, changed only by conditional atomic commits, with an append-only history.
A Store keeps state opaque: a consumer such as go/dispatch's records package gives it types. Every Store.Commit names the Revision it was decided from, so two writers can never both commit decisions made from the same view; the second gets ErrConflict and re-reads. Ownership (Owner) and owner-checked commits (OwnerChecked) are optional capabilities found by type assertion.
This package is the contract and nothing else, and imports only the standard library. The v1 implementation, a file store on a local, host-bound filesystem, is in the file subpackage; the conformance suite every implementation passes is in storetest. The design is go/dispatch spec 0002, the job record store.
Example ¶
Example shows the conditional commit: a writer deciding from a stale view is rejected and must re-read. It runs the file store over an in-memory filesystem; production passes file.Options{}.
package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"github.com/spf13/afero"
"gitlab.com/phpboyscout/go/ledger"
"gitlab.com/phpboyscout/go/ledger/file"
"gitlab.com/phpboyscout/go/ledger/locktest"
)
func main() {
ctx := context.Background()
fsys := afero.NewMemMapFs()
store, err := file.Open(ctx, "/records", file.Options{
FS: fsys,
Locks: locktest.NewTable(fsys).Process("example"),
HostID: func() (string, string, error) { return "machine", "host", nil },
})
if err != nil {
fmt.Println(err)
return
}
sum := sha256.Sum256([]byte("submit job-1"))
view, _, err := store.Create(ctx, ledger.CreateRequest{
Key: "job-1",
Idem: ledger.Idempotency{Key: "submit-job-1", Digest: hex.EncodeToString(sum[:])},
State: []byte(`{"desired":"run"}`),
})
if err != nil {
fmt.Println(err)
return
}
cancel := ledger.Mutation{ID: "cancel-1", Events: []ledger.Entry{{
Envelope: ledger.EnvelopeVersion, Schema: "control/v1", Body: []byte(`{"intent":"cancel"}`), By: "matt",
}}}
committed, err := store.Commit(ctx, "job-1", ledger.Precondition{Revision: view.Revision}, cancel)
fmt.Println(committed.Revision, err)
_, err = store.Commit(ctx, "job-1", ledger.Precondition{Revision: view.Revision},
ledger.Mutation{ID: "hold-1", State: []byte(`{"desired":"hold"}`)})
fmt.Println(errors.Is(err, ledger.ErrConflict))
}
Output: 2 <nil> true
Index ¶
Examples ¶
Constants ¶
const DefaultLimit = 100
DefaultLimit is the page size a Query with a zero Limit gets.
const EnvelopeVersion = 1
EnvelopeVersion is the only envelope version this module reads and writes. It is frozen for v1's life (spec 0002 D4); every Entry carries it.
Variables ¶
var ( // ErrNotFound reports that no live record has the key. ErrNotFound = errors.New("ledger: not found") // ErrConflict reports a stale revision, a reused mutation ID with different content, or an // idempotency key (or record key) already used with a different digest or by a tombstone. ErrConflict = errors.New("ledger: conflict") // ErrNotOwner reports an owner token that is not the record's current owner in this process. ErrNotOwner = errors.New("ledger: not owner") // ErrOwned reports that another holder owns the record. ErrOwned = errors.New("ledger: owned") // ErrCorrupt reports a stored file that is undecodable, truncated, or fails its integrity check. ErrCorrupt = errors.New("ledger: corrupt") // ErrUnsupported reports an unknown envelope version, or a capability the store lacks. ErrUnsupported = errors.New("ledger: unsupported") ErrUnavailable = errors.New("ledger: unavailable") // ErrRefusedRoot reports a root the store will not use: an unaccepted filesystem type, or one // bound to another host. ErrRefusedRoot = errors.New("ledger: refused root") // ErrWouldBlock is returned by a [Locker] when the lock is held. A store's callers never see it. ErrWouldBlock = errors.New("ledger: lock would block") )
The sentinels of spec 0002 D3. A store adds them to the error chain beside the underlying cause, so errors.Is matches the sentinel and the cause is still reachable.
Functions ¶
This section is empty.
Types ¶
type CreateRequest ¶
type CreateRequest struct {
Key Key
Idem Idempotency
Labels Labels
State []byte
Events []Entry
}
CreateRequest is the first state of a record.
type Entry ¶
type Entry struct {
Envelope int // EnvelopeVersion
Schema string
Body []byte
By string // asserted identity, not authenticated
At time.Time // the writer's clock; informational
}
Entry is one event in a record's append-only history.
type Health ¶
type Health interface {
// Beat rewrites the owner's display fields with loopAt, the time its last loop completed;
// ErrNotOwner if tok is not this process's current acquisition.
Beat(ctx context.Context, tok OwnerToken, loopAt time.Time) error
// OwnerInfo reports whether key is owned and, for display only, the owner's fields.
OwnerInfo(ctx context.Context, key Key) (display OwnerDisplay, held bool, err error)
}
Health is the optional loop-health capability of an Owner store (spec 0002 D5). What it writes is display-only: it never bumps a revision, and nothing about safety may read it.
type Idempotency ¶
type Idempotency struct {
Key string
Digest string // sha256 of the canonical request, lowercase hex
}
Idempotency identifies a Create request so that a retry finds the record it made.
type Locker ¶
type Locker interface {
// TryFlock takes an exclusive, non-blocking flock; ErrWouldBlock if held.
TryFlock(path string) (unlock func() error, err error)
// TryOFD takes an exclusive, non-blocking OFD lock; ErrWouldBlock if held.
TryOFD(path string) (OwnedFile, error)
// ProbeOFD reports whether an OFD lock is held on path, and never takes it.
ProbeOFD(path string) (held bool, err error)
}
Locker is the file store's locking, which afero does not cover: flock on tx.lock and create.lock, and the OFD lock and probe on owner.lock (spec 0002 D5). Each call opens its own descriptor, so two calls conflict even within one process.
type Mutation ¶
type Mutation struct {
ID MutationID // retrying the same ID resolves a lost reply
State []byte // replaces the state; nil leaves it unchanged
Events []Entry // appended to the history
Labels Labels // replaces the labels; nil leaves them unchanged
}
Mutation is one conditional change to a record.
type OwnedFile ¶
type OwnedFile interface {
// Replace truncates owner.lock, then writes the display fields.
Replace(display []byte) error
// Held reports whether the lock is still this holder's; on the OS it is, until Close.
Held() (bool, error)
io.Closer
}
OwnedFile is owner.lock held under its OFD lock; closing it releases the lock.
type Owner ¶
type Owner interface {
// Acquire takes ownership of key for holder; ErrOwned if another acquisition holds it.
Acquire(ctx context.Context, key Key, holder string) (OwnerToken, error)
// Holder reports whether key is owned and, for display only, by whom.
Holder(ctx context.Context, key Key) (holder string, held bool, err error)
// Release gives up the ownership tok represents.
Release(ctx context.Context, tok OwnerToken) error
}
Owner is the optional ownership capability of a Store (spec 0002 D2).
type OwnerChecked ¶
type OwnerChecked interface {
Store
OwnerChecked()
}
OwnerChecked is implemented by a Store whose Commit and Tombstone check Precondition.Owner atomically with the revision. The method is a marker for the type assertion.
type OwnerDisplay ¶
type OwnerDisplay struct {
Holder string
PID int
MachineID string
Hostname string
Acquired time.Time
LoopAt time.Time // when the owner's last loop completed
}
OwnerDisplay is what an owner says about itself. Any field may be zero, meaning unknown: a read that catches the owner mid-rewrite, or an owner that has not completed a loop, reports nothing.
type OwnerToken ¶
type OwnerToken struct {
Key Key
Holder string
Nonce string // distinguishes two acquisitions by one holder
}
OwnerToken is one acquisition of a record's ownership.
type Precondition ¶
type Precondition struct {
Revision Revision
// Owner nil is valid for any commit; when set, an OwnerChecked store also requires current
// ownership, and any other store refuses it with ErrUnsupported.
Owner *OwnerToken
}
Precondition is what must still hold for a Commit or Tombstone to apply.
type Query ¶
type Query struct {
Labels map[string]string // every pair must match exactly; empty matches all
Before map[string]string // label key -> RFC 3339 time; the label must be present and earlier
After string // the Page.Next of the previous page; empty starts at the first
Limit int // 0 means DefaultLimit
}
Query selects records by their labels.
type Revision ¶
type Revision uint64
Revision is a record's version: 1 at Create, and one more on every commit.
type Store ¶
type Store interface {
// Create writes the first state and is idempotent on Idem.Key; the same key with a different
// Idem.Digest is ErrConflict. The bool reports whether this call created the record.
Create(ctx context.Context, req CreateRequest) (View, bool, error)
// Read returns the record's current view.
Read(ctx context.Context, key Key) (View, error)
// Commit applies m only if pre still holds; otherwise ErrConflict (revision) or ErrNotOwner.
Commit(ctx context.Context, key Key, pre Precondition, m Mutation) (View, error)
// List returns the records whose labels match q, ordered by key, a page at a time.
List(ctx context.Context, q Query) (Page, error)
// Tombstone removes a settled record, leaving its idempotency entry.
Tombstone(ctx context.Context, key Key, pre Precondition) error
}
Store is a durable record per key, changed only by conditional atomic commits.
type View ¶
type View struct {
Key Key
Revision Revision // strictly increases on every commit
Labels Labels
State []byte
Events []Entry // the whole history, oldest first
// Ephemeral reports a root the caller accepted as not surviving a reboot (spec 0002 D6).
Ephemeral bool
}
View is a record as of one revision.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package file is ledger's v1 store: one directory per record on a local filesystem bound to one host (go/dispatch spec 0002 D5 and D6).
|
Package file is ledger's v1 store: one directory per record on a local filesystem bound to one host (go/dispatch spec 0002 D5 and D6). |
|
Package locktest is an in-memory ledger.Locker lock table for tests over an afero filesystem.
|
Package locktest is an in-memory ledger.Locker lock table for tests over an afero filesystem. |
|
Package storetest is the conformance suite every ledger.Store passes (go/dispatch spec 0002, Testing), as far as it can run in one test process.
|
Package storetest is the conformance suite every ledger.Store passes (go/dispatch spec 0002, Testing), as far as it can run in one test process. |