pail

package module
v0.0.0-...-d88c8fd Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: MIT Imports: 18 Imported by: ? 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.

README

pail for Go

github.com/ArchAstro/pail/go reads and writes pail repositories from Go. A Go service and the pail CLI can share one bucket: the library writes the formats the Rust pail writes, byte for byte where it matters (commit ids, page hashes, chunk boundaries).

Package What it has
store The bucket: Open("gs://b/p" | "s3://b/p" | "file:///dir" | "memory://"), reads, ranged reads, create-only writes, compare-and-swap, delete, list. Per-caller credentials through CredentialSource.
pail Hashes, blobs, packs, chunking, manifest pages, commits and refs; Repo reads refs, history, trees, diffs and files, checking every object against its hash.
policy Branch policy: Load a repository's policy.json, Decide a request, RequestOp for a proxy.

Not ported yet: publishing commits (leases, intents, the ref swap and its retries), rewrites, gc and drafts. Each will come with the same Quint checks as the Rust code.

repo, err := pail.Open(ctx, "gs://bucket/acme/app", store.Options{Credentials: creds})
ref, _, ok, err := repo.ReadRef(ctx, "main")
c, err := repo.Commit(ctx, ref.Commit)
e, ok, err := repo.Entry(ctx, c.Root, "README.md")
data, err := repo.ReadFile(ctx, e)

Repo.MaxObject bounds every object a read fetches, for hosts that read repositories they do not trust.

How it is checked

  • Store contract. store/store_refinement_test.go runs every backend through the scenarios of verify/store_spec.qnt, the model the Rust backends are checked against: the same objects, versions and replies after every call. It runs memory and file stores always, gs:// against pail-gcs-emulator (PAIL_GCS_EMULATOR), and any URLs in PAIL_TEST_STORES (CI: S3 on moto).
  • Branch policy. policy/policy_refinement_test.go runs Parse, Decide and RequestOp through verify/policy_scenarios.qnt, as tests/policy_refinement.rs does for Rust.
  • Rust and Go on one bucket. interop_test.go has the pail CLI (PAIL_BIN) write every kind of file and checks that Go reads each back and re-encodes every page and commit to the same hash; then Go writes a commit with packs, chunks and a change list and pail cat, log and show read it.

The generated files (*_gen_test.go, *-refinements.json) come from verify/ (npm run compile); do not edit them.

cargo build --release --bin pail --bin pail-gcs-emulator
cd go && PAIL_BIN=../target/release/pail PAIL_GCS_EMULATOR=../target/release/pail-gcs-emulator go test ./...

In CI (CI set), a test whose binary or store is missing fails instead of skipping.

Documentation

Overview

Package pail reads and writes pail repositories in an object store, in the formats the Rust pail writes (src/hash.rs, enc.rs, pack.rs, manifest.rs, objects.rs): a Go program and the pail CLI can share one bucket.

Index

Constants

View Source
const (
	// InlineMax is the largest file stored inside its manifest entry.
	InlineMax = 64
	// ChunkThreshold is the smallest file split into chunks instead of packed.
	ChunkThreshold = 1 << 20
	// PackMax is the size at which a pack is closed.
	PackMax = 64 << 20
)
View Source
const MaintenanceMeta = "pail.maintenance"

MaintenanceMeta marks a commit that changes how files are stored, not what they are.

Variables

View Source
var (
	// ErrNotFound: an object, ref or path that does not exist.
	ErrNotFound = errors.New("pail: not found")
	// ErrCorrupt: an object that does not decode, or does not match its hash.
	ErrCorrupt = errors.New("pail: corrupt object")
	// ErrLimit: an object larger than the reader allows.
	ErrLimit = errors.New("pail: limit exceeded")
)
View Source
var EmptyRoot = func() Hash {
	b, _ := BuildPage(&Page{})
	return b.Hash
}()

EmptyRoot is the root of the empty tree: a leaf with no entries. It is never stored.

Functions

func BuildTree

func BuildTree(entries []Entry) (Hash, []BuiltPage, error)

BuildTree builds every page of a tree holding entries, sorted by path, and returns its root.

func BuildUpper

func BuildUpper(children []Child) (Hash, []BuiltPage, error)

BuildUpper builds the internal levels above an ordered, complete list of leaves and returns the root with every internal page built.

func ChunkKey

func ChunkKey(h Hash) string

ChunkKey is a chunk's object name.

func ChunkSpans

func ChunkSpans(data []byte) [][2]int

ChunkSpans splits data into (offset, length) chunks.

func CommitKey

func CommitKey(h Hash) string

Object names.

func DecodeBlob

func DecodeBlob(stored []byte, rawLen uint64) ([]byte, error)

DecodeBlob is EncodeBlob's inverse; rawLen is the file's size, which bounds the output.

func EncodeBlob

func EncodeBlob(raw []byte) []byte

EncodeBlob stores raw: zstd when that saves at least 5%, raw otherwise.

func EncodeChanges

func EncodeChanges(changes map[string]FileChange) (json.RawMessage, error)

EncodeChanges is a change list as a commit stores it (objects.rs Changes::new).

func EncodePage

func EncodePage(p *Page) ([]byte, error)

EncodePage is a page's canonical encoding, the bytes its hash covers. It refuses what the Rust pail could not read back: keys that are not UTF-8 or not in order, unknown kinds.

func NowDate

func NowDate() string

NowDate is the current time as a Git-style date, "<unix seconds> +0000". PAIL_DATE ("<unix seconds> [<+zone>]") stands in for it, as in the Rust pail.

func PackKey

func PackKey(h Hash) string

PackKey is a pack's object name.

func PageKey

func PageKey(h Hash) string

func ParseChanges

func ParseChanges(raw json.RawMessage) (map[string]FileChange, error)

ParseChanges reads a commit's change list.

func RefKey

func RefKey(branch string) string

func ReflogKey

func ReflogKey(branch, id string) string

func ValidateBranch

func ValidateBranch(name string) error

ValidateBranch checks a branch name as pail does: ASCII letters, digits and -_./, no empty, . or .. segment.

Types

type BuiltPage

type BuiltPage struct {
	Hash Hash
	// Data is the zstd-compressed encoding, as stored at pages/<hash>.
	Data []byte
	Page *Page
}

BuiltPage is a page ready to upload.

func BuildLeaves

func BuildLeaves(entries []Entry) ([]BuiltPage, error)

BuildLeaves builds the leaf pages of a sorted run of entries that starts on a boundary.

func BuildPage

func BuildPage(p *Page) (BuiltPage, error)

BuildPage encodes and compresses a page.

type Change

type Change struct {
	Path     string
	Old, New *Entry
}

Change is one path's change between two trees.

func DiffSorted

func DiffSorted(a, b []Entry) []Change

DiffSorted merge-joins two sorted entry lists into the changes from a to b.

type Child

type Child struct {
	// Key is the largest path in the child's subtree.
	Key   string
	Hash  Hash
	Files uint64
	Bytes uint64
}

Child is an internal page's reference to a child page.

func ChildOf

func ChildOf(b BuiltPage) Child

ChildOf is the reference a parent page holds to b.

type ChunkRef

type ChunkRef struct {
	Hash Hash
	Len  uint64
}

ChunkRef is one chunk of a large file.

type Commit

type Commit struct {
	Parent *Hash `json:"parent"`
	// Root is the manifest's root page.
	Root Hash `json:"root"`
	// Generation is the depth in history; a root commit is 0.
	Generation uint64 `json:"generation"`
	Files      uint64 `json:"files"`
	Bytes      uint64 `json:"bytes"`
	// Author and Committer are "Name <email>"; dates are "<unix seconds> <+hhmm>".
	Author        string            `json:"author"`
	AuthorDate    string            `json:"author_date"`
	Committer     string            `json:"committer"`
	CommitterDate string            `json:"committer_date"`
	Message       string            `json:"message"`
	Meta          map[string]string `json:"meta,omitempty"`
	// Changes lists every path the commit changed against its parent, kept as the JSON it
	// was stored as; nil in commits written before change lists.
	Changes json.RawMessage `json:"changes,omitempty"`
}

Commit is one commit. Linear history: at most one parent.

func DecodeCommit

func DecodeCommit(id Hash, data []byte) (*Commit, error)

DecodeCommit checks data against the commit's id and decodes it.

func (*Commit) ChangeList

func (c *Commit) ChangeList() ([]Change, error)

ChangeList is the commit's changes in path order, or nil if it records none.

func (*Commit) Encode

func (c *Commit) Encode() (Hash, []byte, error)

Encode is the commit's stored bytes and id, the bytes serde_json writes for it.

func (*Commit) IsMaintenance

func (c *Commit) IsMaintenance() bool

IsMaintenance reports whether the commit is maintenance (a repack), not work.

func (*Commit) Subject

func (c *Commit) Subject() string

Subject is the message's first line.

type Entry

type Entry struct {
	Path string
	Kind Kind
	Size uint64
	Hash Hash
	Loc  Loc
}

Entry is one file in a manifest.

func (Entry) SameContent

func (e Entry) SameContent(o Entry) bool

SameContent reports whether two entries are the same file to a user: kind and content.

type FileChange

type FileChange struct {
	Old, New *FileState
}

FileChange is one path's change: nil Old is an add, nil New a delete.

type FileState

type FileState struct {
	Kind Kind
	Size uint64
	Hash Hash
	// Loc is where its bytes live; Unresolved for an old side, which carries none.
	Loc Loc
}

FileState is one version of a file in a change list.

func StateOf

func StateOf(e Entry, withLoc bool) FileState

StateOf is an entry as a change list records it; withLoc keeps where its bytes live.

func (FileState) Entry

func (s FileState) Entry(path string) Entry

Entry is the file at path in this state.

type Hash

type Hash [32]byte

Hash is a BLAKE3 content hash: the identity of every immutable object and of file content.

func HashOf

func HashOf(data []byte) Hash

HashOf hashes data.

func ParseHash

func ParseHash(s string) (Hash, error)

ParseHash reads a hash from 64 hex characters.

func (Hash) Hex

func (h Hash) Hex() string

Hex is the hash in lowercase hex, as object names and JSON carry it.

func (Hash) MarshalText

func (h Hash) MarshalText() ([]byte, error)

MarshalText writes the hash as hex, so JSON carries it as a string.

func (Hash) Short

func (h Hash) Short() string

Short is the first six bytes in hex, as pail prints commit ids.

func (Hash) String

func (h Hash) String() string

func (*Hash) UnmarshalText

func (h *Hash) UnmarshalText(b []byte) error

UnmarshalText reads a hex hash.

type Kind

type Kind uint8

Kind is a file's kind.

const (
	File    Kind = 0
	Exec    Kind = 1
	Symlink Kind = 2
)

type Landed

type Landed struct {
	Intent string `json:"intent"`
	Commit Hash   `json:"commit"`
}

Landed is an intent and the commit it landed as.

type Lineage

type Lineage struct {
	Epoch   uint64  `json:"epoch,omitempty"`
	Rewrite *string `json:"rewrite,omitempty"`
}

Lineage says which version of a branch's history a ref holds: a rewrite bumps Epoch and names its reflog record.

type Loc

type Loc struct {
	Kind LocKind
	// Inline bytes.
	Data []byte
	// A pack, and the range of it holding the stored blob (codec byte included).
	Pack     Hash
	Off, Len uint64
	// Chunks, in order.
	Chunks []ChunkRef
}

Loc is where a file's bytes live.

type LocKind

type LocKind uint8

LocKind says where a file's bytes live.

const (
	// Inline: in the entry itself (files of InlineMax bytes or fewer, and symlinks).
	Inline LocKind = 0
	// Packed: a range of a pack object.
	Packed LocKind = 1
	// Chunked: content-defined chunks, each its own object.
	Chunked LocKind = 2
	// Unresolved: an old version named by a change list; never stored in a page.
	Unresolved LocKind = 3
)

type LogEntry

type LogEntry struct {
	ID     Hash
	Commit *Commit
}

LogEntry is one commit of a history.

type PackBlob

type PackBlob struct {
	Hash             Hash
	Off, Len, RawLen uint64
}

PackBlob is one blob in a pack's footer.

func PackIndex

func PackIndex(pack []byte) ([]PackBlob, error)

PackIndex reads a pack's footer: each blob's content hash and where it is stored.

type PackBuilder

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

PackBuilder builds one pack: blobs back to back, then a footer index for gc and fsck.

func (*PackBuilder) Add

func (p *PackBuilder) Add(hash Hash, raw []byte) (off, length uint64)

Add appends a file's bytes under their content hash and returns where they are stored.

func (*PackBuilder) AddStored

func (p *PackBuilder) AddStored(hash Hash, stored []byte, rawLen uint64) (off, length uint64)

AddStored appends a blob already encoded ([codec][data]), copied verbatim.

func (*PackBuilder) Empty

func (p *PackBuilder) Empty() bool

Empty reports whether no blob was added.

func (*PackBuilder) Finish

func (p *PackBuilder) Finish() (Hash, []byte)

Finish appends the footer and returns the pack's hash and bytes.

func (*PackBuilder) Len

func (p *PackBuilder) Len() int

Len is the pack's size so far.

type Page

type Page struct {
	Level    uint8
	Entries  []Entry
	Children []Child
}

Page is a decoded manifest page: a leaf (Level 0) of entries or a node of children.

func DecodePage

func DecodePage(raw []byte) (*Page, error)

DecodePage reads EncodePage's output. It checks what a hostile page could abuse: counts against the bytes left, sorted keys, pack indexes, and no trailing bytes.

func DecodeStoredPage

func DecodeStoredPage(want Hash, stored []byte) (*Page, error)

DecodeStoredPage decompresses a stored page, checks it against its hash and decodes it.

type Ref

type Ref struct {
	Name   string
	Commit Hash
}

Ref is a branch and the commit it names.

type RefValue

type RefValue struct {
	Commit Hash `json:"commit"`
	// Root and Generation are the commit's, so a writer can build on the head without
	// fetching it.
	Root       *Hash   `json:"root,omitempty"`
	Generation *uint64 `json:"generation,omitempty"`
	// Recent lists the intents landed most recently, newest last.
	Recent []Landed `json:"recent,omitempty"`
	Lineage
}

RefValue is a ref's body.

func DecodeRef

func DecodeRef(data []byte) (*RefValue, error)

DecodeRef reads a ref's body.

func (*RefValue) Encode

func (r *RefValue) Encode() []byte

Encode is the ref's body as serde_json writes it.

type Repo

type Repo struct {
	Store *store.Store
	// MaxObject, when positive, bounds every object the repository reads (a commit, a page,
	// a pack range, a chunk), for a host that reads repositories it does not trust.
	MaxObject int64
	// contains filtered or unexported fields
}

Repo reads a pail repository in a store (src/repo.rs). Immutable objects it reads are checked against their hashes and cached in memory. It is safe for concurrent use.

func NewRepo

func NewRepo(s *store.Store) *Repo

NewRepo is a repository in s.

func Open

func Open(ctx context.Context, url string, opts store.Options) (*Repo, error)

Open opens the repository at a store URL (see store.Open).

func (*Repo) Commit

func (r *Repo) Commit(ctx context.Context, id Hash) (*Commit, error)

Commit reads a commit by id.

func (*Repo) DefaultBranch

func (r *Repo) DefaultBranch(ctx context.Context) (string, error)

DefaultBranch is the branch the store's HEAD names, or "" if it names none.

func (*Repo) Diff

func (r *Repo) Diff(ctx context.Context, a, b Hash) ([]Change, error)

Diff is the changes from tree a to tree b. Leaves the trees share are never read.

func (*Repo) Entries

func (r *Repo) Entries(ctx context.Context, root Hash) ([]Entry, error)

Entries is every file in the tree, in path order.

func (*Repo) Entry

func (r *Repo) Entry(ctx context.Context, root Hash, path string) (Entry, bool, error)

Entry is the file at path in the tree; ok is false if there is none.

func (*Repo) LeafRefs

func (r *Repo) LeafRefs(ctx context.Context, root Hash) ([]Child, error)

LeafRefs is the ordered list of leaves under root.

func (*Repo) ListRefs

func (r *Repo) ListRefs(ctx context.Context) ([]Ref, error)

ListRefs lists every branch, by name.

func (*Repo) Log

func (r *Repo) Log(ctx context.Context, start Hash, n int) ([]LogEntry, error)

Log is up to n commits of history from start, newest first.

func (*Repo) Page

func (r *Repo) Page(ctx context.Context, h Hash) (*Page, error)

Page reads a manifest page.

func (*Repo) ReadFile

func (r *Repo) ReadFile(ctx context.Context, e Entry) ([]byte, error)

ReadFile reads a file's bytes and checks them against its content hash.

func (*Repo) ReadRef

func (r *Repo) ReadRef(ctx context.Context, branch string) (ref *RefValue, v store.Version, ok bool, err error)

ReadRef reads a branch's ref and its version; ok is false if the branch does not exist.

type Rewrite

type Rewrite struct {
	Old   Hash    `json:"old"`
	New   Hash    `json:"new"`
	Epoch uint64  `json:"epoch"`
	Prev  *string `json:"prev,omitempty"`
	// Op is what rewrote it: rebase, undo or reset.
	Op   string `json:"op,omitempty"`
	By   string `json:"by,omitempty"`
	Date string `json:"date,omitempty"`
	// Map takes each rewritten commit of the old history to its successor (nil: dropped).
	Map map[Hash]*Hash `json:"map,omitempty"`
}

Rewrite is a rewrite of a branch, kept at reflog/<branch>/<id>.

Directories

Path Synopsis
Package policy is pail's branch policy (src/policy.rs): who may read a repository, write each branch, set its default branch and collect its garbage.
Package policy is pail's branch policy (src/policy.rs): who may read a repository, write each branch, set its default branch and collect its garbage.
Package store is pail's bucket (src/store.rs): immutable content-addressed objects plus compare-and-swap on mutable ones, over GCS, S3, a local directory or memory.
Package store is pail's bucket (src/store.rs): immutable content-addressed objects plus compare-and-swap on mutable ones, over GCS, S3, a local directory or memory.

Jump to

Keyboard shortcuts

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