Documentation
¶
Overview ¶
Package tablelog is an append-only, versioned key/value table kept entirely on the object store — the Delta/Iceberg ("Snowflake/Databricks-style") pattern, scaled down to application metadata. There is no database process: a table is a set of immutable Avro data files plus a transaction log of JSON entries, and the only coordination primitive is the object store's atomic create (PutIfAbsent: an atomic create).
Layout ¶
Everything for one table lives under tables/<tenant>/<table>/:
data/<hex>.avro immutable Avro OCF rows (key, op put|del, ts, payload, ver, ord)
_log/%020d.json commit N: {version, parent, ts, writer, add, remove, op}
_checkpoint/%020d.avro the full live file set as of version N
_checkpoint/_last the newest checkpoint version — a HINT only
A data file's name is 16 hex digits of its creation time (unix µs) followed by 32 random hex digits (crypto/rand). The time prefix lets Vacuum age an orphan without reading it and without trusting server mtimes, which many object stores do not expose.
Commit ¶
Optimistic concurrency: read the head (the _last hint, then a LIST of _log/), write the data file, then PutIfAbsent(_log/<head+1>). Losing that race yields ErrExists; the writer re-reads the head and conflict-checks. Appends never conflict. A compaction conflicts when a file it removes is no longer live; it then re-plans from the new head. Retries use jittered exponential backoff up to MaxAttempts. Versions are therefore dense: 1, 2, 3, … with no gaps.
Read ¶
State = checkpoint + replay of later log entries. Rows merge by key with last-writer-wins on (version, ordinal); a del row is a tombstone. Snapshot(v) reads the table as of any retained version (time travel).
Encryption is the Store's business, not this package's ¶
tablelog does not encrypt anything. It hands bytes to the Store and reads them back, so whether objects are sealed at rest is entirely a property of the implementation you supply.
If you do seal them, bind the ciphertext to the object's KEY. Every key here already encodes tenant, table and path (tables/<tenant>/<table>/<path>), so binding to the key gives you the property worth having: a data file copied into another tenant's or table's prefix fails to open rather than being served as that table's data. A scheme that binds only to the bucket, or to nothing, will decrypt a misplaced file happily.
What it is not ¶
No joins, no multi-table transactions, no secondary indexes, no uniqueness beyond the key, no SQL. Workloads that need those stay on Litestream-replicated SQLite. See the package section of the store README.
Index ¶
- Constants
- Variables
- type Change
- type CompactResult
- type MemStore
- func (m *MemStore) Delete(ctx context.Context, key string) error
- func (m *MemStore) Get(ctx context.Context, key string) (io.ReadCloser, error)
- func (m *MemStore) Len() int
- func (m *MemStore) List(ctx context.Context, prefix string) ([]string, error)
- func (m *MemStore) Overwrite(key string, data []byte)
- func (m *MemStore) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
- func (m *MemStore) PutIfAbsent(ctx context.Context, key string, data []byte) error
- type Option
- type Record
- type Row
- type Snapshot
- type Store
- type Table
- func (t *Table) Compact(ctx context.Context) (CompactResult, error)
- func (t *Table) Delete(ctx context.Context, keys ...string) (int64, error)
- func (t *Table) Get(ctx context.Context, key string) (Record, bool, error)
- func (t *Table) LastCheckpointError() error
- func (t *Table) Latest(ctx context.Context) (*Snapshot, error)
- func (t *Table) Put(ctx context.Context, rows ...Row) (int64, error)
- func (t *Table) Scan(ctx context.Context, prefix string) ([]Record, error)
- func (t *Table) Snapshot(ctx context.Context, version int64) (*Snapshot, error)
- func (t *Table) Vacuum(ctx context.Context, retention time.Duration) (VacuumResult, error)
- func (t *Table) Version(ctx context.Context) (int64, error)
- type VacuumResult
Constants ¶
const ( // MinRetention is the smallest retention Vacuum accepts. It must exceed // MaxCommitAge, so an in-flight commit's data files are never vacuumed. MinRetention = 10 * time.Minute // MaxCommitAge is how long a commit may take from writing its data files to // winning its log version. Past it the commit fails with ErrStaleCommit. MaxCommitAge = 5 * time.Minute )
Variables ¶
var ( // ErrExists is what a Store's PutIfAbsent must return (or wrap) when the // key already exists. It is the single primitive the table's correctness // rests on: two writers racing for the same log version, and exactly one // of them winning. A Store that reports a lost race any other way will // corrupt the table rather than retry, so implementations should wrap this // error rather than inventing their own. ErrExists = errors.New("tablelog: object already exists") // ErrConflict: a compaction's removed file was already removed by a // concurrent commit. Compact handles it by re-planning; it only surfaces // when re-planning also runs out of attempts. ErrConflict = errors.New("tablelog: commit conflict") // ErrRetriesExhausted: every attempt lost the race for the next log version. ErrRetriesExhausted = errors.New("tablelog: commit retries exhausted") // ErrNoVersion: the requested version has not been committed. ErrNoVersion = errors.New("tablelog: no such version") // ErrCorrupt: the log or a checkpoint is inconsistent (a gap in versions, an // entry that removes a file that is not live, a malformed entry). ErrCorrupt = errors.New("tablelog: corrupt table") // ErrStaleCommit: the commit's data files are older than MaxCommitAge, so a // concurrent Vacuum may already have treated them as orphans. The commit is // refused rather than risk a log entry that references a deleted file. ErrStaleCommit = errors.New("tablelog: commit too old to be vacuum-safe") )
Functions ¶
This section is empty.
Types ¶
type Change ¶
type Change struct {
Record
// Ord is the row's position within its commit. (Version, Ord) is the row's
// total order in the table.
Ord int64
// Deleted marks a tombstone written by Delete; Payload is then empty.
Deleted bool
}
Change is one row committed after a given version, as ChangesSince reads it.
type CompactResult ¶
type CompactResult struct {
Version int64
Removed int // files merged away
Added int // files written (0 when every surviving row was a dropped tombstone)
Rows int // rows in the output
}
CompactResult describes one Compact call. Version 0 means there was nothing worth compacting and no commit was made.
type MemStore ¶
type MemStore struct {
// FailPutIfAbsent, when set, is consulted before every atomic create. A
// non-nil return is returned to the caller instead of performing it, which
// is how a test injects a crash between the data write and the log write.
FailPutIfAbsent func(key string) error
// contains filtered or unexported fields
}
MemStore is an in-memory Store: the reference implementation, and enough to run a table in a test without any infrastructure.
It is NOT a toy. It implements the one guarantee the table's correctness rests on — PutIfAbsent is an atomic create — and it is safe for concurrent use, so the optimistic-concurrency paths can be exercised honestly rather than simulated. What it is not is durable: everything is lost when it goes out of scope.
Use it to try the package, to test code that writes tables, and as the shortest correct example of what a real Store must do.
func (*MemStore) Delete ¶
Delete removes key. Deleting something absent is not an error: Vacuum may race another Vacuum, and both should succeed.
func (*MemStore) Len ¶
Len reports how many objects are stored, for tests that assert a Vacuum actually removed something.
func (*MemStore) List ¶
List returns the keys under prefix, sorted. The order matters: the log is read by version, and an unsorted List would replay commits out of order.
func (*MemStore) Overwrite ¶ added in v0.7.0
Overwrite replaces an object unconditionally, which no Store method can do. It exists so a test can corrupt a specific object and check that the table reports it rather than reading past it; production code must go through PutIfAbsent so a lost race is still a lost race.
func (*MemStore) Put ¶
func (m *MemStore) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
Put writes key, overwriting any existing object.
func (*MemStore) PutIfAbsent ¶
PutIfAbsent creates key only if it does not exist, and returns ErrExists if it does. This is the atomic create the table's correctness depends on: two writers racing for the same log version, exactly one winning.
type Option ¶
type Option func(*config)
Option configures a Table.
func WithCheckpointInterval ¶
WithCheckpointInterval writes a checkpoint every k versions (default 10; 0 disables writing them — reading still uses any that exist).
func WithCompaction ¶
WithCompaction sets which files Compact merges: files smaller than smallFileBytes, and files whose tombstone fraction is at least tombstoneRatio. Defaults: 1 MiB and 0.3.
func WithMaxAttempts ¶
WithMaxAttempts bounds how many times a commit retries after losing the race for the next version (default 32).
type Record ¶
type Record struct {
Key string
Payload []byte
Version int64 // the commit that wrote this value
TS time.Time // when the writer wrote it
}
Record is one live row as read back.
type Snapshot ¶
type Snapshot struct {
// contains filtered or unexported fields
}
Snapshot is an immutable view of the table at one version.
func (*Snapshot) ChangesSince ¶
ChangesSince returns the rows with the prefix committed after version `after` that this snapshot can still see, in commit order: by Version, then Ord. It is the incremental read for a consumer that keeps its own derived state (an index, a cache) and has already applied everything up to `after`.
It reads only the live files that a commit after `after` added; a file added at or before `after` cannot hold a later row. Rows are NOT merged by key. In a table whose keys are each written once (an append-only log, store/twin) that is exactly every row committed in (after, Version()]. When a key is written more than once, a compaction that merged its rows keeps only the winner, so an overwritten intermediate row can be missing; the newest row of every key is always present. A whole-table compaction drops tombstones, so a Delete can be missing too when everything it covered was compacted away.
Unlike Snapshot(v) for an old v, it never needs a vacuumed file: it reads only files live at this snapshot.
type Store ¶
type Store interface {
Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
PutIfAbsent(ctx context.Context, key string, data []byte) error
Get(ctx context.Context, key string) (io.ReadCloser, error)
List(ctx context.Context, prefix string) ([]string, error)
Delete(ctx context.Context, key string) error
}
Store is the object-store surface tablelog needs. Implement it over S3, GCS, MinIO, a filesystem, or anything else with an atomic create; it is an interface so tests can inject faults too (a crash between the data write and the log write, say).
PutIfAbsent must be an atomic create that reports a lost race as an error wrapping ErrExists. Everything the table correctness rests on is that one primitive.
type Table ¶
type Table struct {
// contains filtered or unexported fields
}
Table is a handle on one tenant's table. It is safe for concurrent use, and any number of Tables — in this process or others — may write the same table.
func Open ¶
Open returns a handle on tables/<tenant>/<table>/. It does no I/O: an empty table is simply one with no log entries yet (version 0).
func (*Table) Compact ¶
func (t *Table) Compact(ctx context.Context) (CompactResult, error)
Compact merges small and tombstone-heavy files into one file, keeping only the winning row per key.
Tombstones are dropped only when the merge covers every live file: then any file outside it was committed later, so nothing older can be resurrected. A partial merge keeps them. Rows keep their original (version, ordinal), so a compaction that commits after a concurrent append never beats that append.
On a conflict (a concurrent compaction already removed one of these files) the output is deleted and Compact re-plans from the new head, up to MaxAttempts times.
func (*Table) Delete ¶
Delete writes tombstones for keys in one commit and returns its version. Deleting an absent key is not an error.
func (*Table) LastCheckpointError ¶
LastCheckpointError reports the most recent failure to write a checkpoint, or nil. A checkpoint failure never fails the commit that triggered it (the commit is already durable); it only makes later cold reads replay more log.
func (*Table) Put ¶
Put upserts rows in one commit and returns its version. Within one call a repeated key resolves to its last occurrence.
A non-nil error does not always mean nothing was committed: if the log write itself fails ambiguously (a network error after the server applied it) the commit may have landed. Put never retries such an error, so it never commits twice.
func (*Table) Snapshot ¶
Snapshot returns the table as of version (time travel). Version 0 is the empty table. Versions whose files Vacuum has deleted fail on read.
func (*Table) Vacuum ¶
Vacuum deletes data files that no retained version needs:
- files removed (by compaction) at a commit older than retention, and
- orphans — files no commit ever added, left by a writer that crashed or lost its commit — created longer ago than retention.
Live files, and files still reachable from a version within the window, are kept. Log entries and checkpoints are never deleted (they are small, and the log is what makes the table readable); time travel to a version whose removed files have been vacuumed fails on read.
retention must be at least MinRetention, so an in-flight commit's freshly written files are never mistaken for orphans (commits older than MaxCommitAge refuse to publish).
type VacuumResult ¶
type VacuumResult struct {
Deleted []string // table-relative paths
Skipped []string // objects under data/ with names this package did not write
}
VacuumResult lists what Vacuum deleted and what it left alone.