backup

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: CC0-1.0 Imports: 22 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 backup provides durable recovery files and the purge ledger.

Index

Constants

View Source
const (
	// LedgerPending records the intent to purge an exact set of entities.
	LedgerPending string = "pending"
	// LedgerComplete records completion of a purge and its recovery-file step.
	LedgerComplete string = "complete"
)
View Source
const (
	// MinKeepDaily is the minimum number of UTC calendar days retained.
	MinKeepDaily = 3
	// MinKeepWeekly is the minimum number of ISO calendar weeks retained.
	MinKeepWeekly = 1
)

Variables

View Source
var (
	// ErrNoJournal indicates there is no interrupted swap to recover.
	ErrNoJournal = errors.New("backup: no swap journal")
	// ErrNoRollback indicates a scrub or a swap whose old set was deleted.
	ErrNoRollback = errors.New("backup: this swap cannot be rolled back")
	// ErrRollbackInProgress prevents forward recovery once rollback has begun.
	ErrRollbackInProgress = errors.New("backup: rollback in progress; run `tkr restore --rollback`")
)

Functions

func CleanupTemps

func CleanupTemps(dataDir, backupDir string) (removed []string, err error)

CleanupTemps removes interrupted temporary artifacts, preserving journaled recovery paths. Callers must hold the instance lock throughout cleanup. The returned paths are removed files or whole removed directory trees.

func OpenLedger

func OpenLedger(path string) (*Ledger, LedgerHealth, error)

OpenLedger loads valid records, retaining complete corrupt lines on disk and truncating only an unterminated final line. A missing file is empty and healthy.

func ResumeSwap

func ResumeSwap(ctx context.Context, journalPath string) error

ResumeSwap completes a forward swap without invoking its original callback. Callers inspect OwnerTokenPending before resuming to handle lost owner tokens.

func RollbackSwap

func RollbackSwap(ctx context.Context, journalPath string) error

RollbackSwap restores a restore/import's old file set. Its own progress is journaled so a second rollback safely resumes after any interrupted rename.

func Swap

func Swap(ctx context.Context, journalPath string, j *SwapJournal, onInstalled func() error) error

Swap starts a journaled replacement. An outstanding journal must be recovered first. onInstalled runs once after installation and before journal removal; ResumeSwap never replays it, even if it failed or was interrupted.

AIDEV-NOTE: prepared -> moved-old -> installed -> (scrub: aside-deleted). Each action and both affected directories are synced before advancing the atomic journal. A missing source with a present destination means a rename already happened: old members in Aside are skipped individually, and New absent with Target present at moved-old means installation finished. Deletion tolerates absent members. Rollback journals its discard destination BEFORE renaming the installed file, then restores old members individually; replay must never mistake an already-restored Target for the new file to discard.

func Verify

func Verify(ctx context.Context, path string) (schemaVersion int, err error)

Verify checks a snapshot or staged copy with SQLite and both FTS indexes, returning its highest migration version. It opens the copy in DELETE mode; never pass a live database. No SQLite sidecars may remain after closing it.

func WithStepHook

func WithStepHook(ctx context.Context, h func(point string) error) context.Context

WithStepHook installs a crash-test hook scoped to ctx. A hook error returns immediately without cleanup, leaving recovery artifacts exactly where they are. Rollback member hooks use file basenames, e.g. rollback:moved:taskronin.db-wal.

Types

type FileSet

type FileSet struct{ DB string }

FileSet names a database and its optional -wal sibling. SHM is not copied.

type Kind

type Kind string

Kind identifies why a snapshot was taken.

const (
	// KindDaily identifies a scheduled daily snapshot.
	KindDaily Kind = "daily"
	// KindManual identifies a user-requested snapshot.
	KindManual Kind = "manual"
	// KindPremigrate identifies a snapshot taken before a schema migration.
	KindPremigrate Kind = "premigrate"
	// KindPrescrub identifies a snapshot taken before scrubbing recovery files.
	KindPrescrub Kind = "prescrub"
)

type Ledger

type Ledger struct {
	Path string
	// contains filtered or unexported fields
}

Ledger serializes access to a file and its cached valid records. OpenLedger must be called under the application's instance lock; Path must not be changed.

func (*Ledger) Append

func (l *Ledger) Append(r LedgerRecord) (err error)

Append computes the checksum and durably appends one record. A damaged ledger refuses both pending and complete records until explicitly repaired.

func (*Ledger) Health

func (l *Ledger) Health() LedgerHealth

Health returns a copy of the ledger's corruption status.

func (*Ledger) Pending

func (l *Ledger) Pending() ([]LedgerRecord, error)

Pending returns pending records with no later complete line for the same Rec, in file order. Timestamps do not determine completion order.

func (*Ledger) Records

func (l *Ledger) Records() ([]LedgerRecord, error)

Records returns independent copies of all valid records in file order.

func (*Ledger) Repair

func (l *Ledger) Repair() ([]int, error)

Repair atomically rewrites only valid records, returning the dropped 1-based line numbers. Health is cleared only after the replacement is durable.

type LedgerHealth

type LedgerHealth struct {
	Damaged      bool
	DroppedLines []int // 1-based line numbers; retained on disk until Repair
}

LedgerHealth identifies complete corrupt lines skipped while loading a ledger.

type LedgerRecord

type LedgerRecord struct {
	V             int              `json:"v"`
	Rec           string           `json:"rec"` // random 128-bit hex
	At            int64            `json:"at"`
	State         string           `json:"state"` // "pending" | "complete"
	Tasks         []domain.TaskID  `json:"tasks,omitempty"`
	Entries       []domain.EntryID `json:"entries,omitempty"`
	RecoveryFiles string           `json:"recovery_files,omitempty"` // complete lines: "deleted", "kept", or "none" (H1)
	Sum           string           `json:"sum"`                      // hex SHA-256 of this record's JSON encoding with Sum = ""
}

LedgerRecord is one checksummed JSON line describing a purge intent or completion.

type Manager

type Manager struct {
	Dir   string
	Clock clock.Clock
	Snap  *sql.DB
	// contains filtered or unexported fields
}

Manager serializes snapshots and rotations in Dir. Configure its fields before use; offline callers must also hold the application's instance lock.

func (*Manager) Rotate

func (m *Manager) Rotate(ctx context.Context, r Retention) (removed []string, err error)

Rotate deletes snapshots outside r and returns their basenames, newest first. It always keeps snapshots younger than 24 hours and the newest three overall. Foreign files, directories, and symlinks are untouched.

func (*Manager) Snapshot

func (m *Manager) Snapshot(ctx context.Context, kind Kind) (_ SnapshotInfo, err error)

Snapshot publishes a verified, private, durable copy from the snapshot pool. Settings updates and retention scheduling belong to the service layer.

type Retention

type Retention struct {
	Daily, Weekly int
}

Retention specifies the number of recent calendar days and ISO weeks to keep.

type SnapshotInfo

type SnapshotInfo struct {
	Name, Path    string
	Kind          Kind
	At            time.Time
	Size          int64
	SchemaVersion int
}

SnapshotInfo describes a snapshot file. List leaves SchemaVersion at zero.

func List

func List(dir string) ([]SnapshotInfo, error)

List returns regular snapshot files newest first, using only names and file metadata. It never opens databases; SchemaVersion remains zero.

func ParseSnapshotName

func ParseSnapshotName(name string) (SnapshotInfo, bool)

ParseSnapshotName parses a snapshot basename, rejecting foreign files and invalid dates. Path, Size and SchemaVersion are left at their zero values.

type Staged

type Staged struct{ Dir, Path string }

Staged owns a disposable directory containing a self-contained database.

func Stage

func Stage(ctx context.Context, stagingDir string, set FileSet) (_ *Staged, err error)

Stage copies a quiescent file set into an existing staging directory and recovers its WAL. Only the copy is opened with SQLite; the source is read-only.

func (*Staged) Remove

func (s *Staged) Remove() error

Remove deletes the entire disposable directory. It tolerates repeated calls.

type SwapJournal

type SwapJournal struct {
	Version           int       `json:"version"`
	Kind              SwapKind  `json:"kind"`
	Step              string    `json:"step"`
	New               string    `json:"new"`
	Target            string    `json:"target"`
	Aside             string    `json:"aside"`
	DeleteAside       bool      `json:"delete_aside"`
	OwnerTokenPending bool      `json:"owner_token_pending"`
	StartedAt         time.Time `json:"started_at"`
	Rollback          string    `json:"rollback"` // "", started, discarding, new-discarded, old-restored
	Discard           string    `json:"discard"`  // journaled before the installed file moves here
}

SwapJournal records durable progress. New must be a verified, fsynced, self-contained DELETE-mode database. Callers hold the instance lock throughout Swap, ResumeSwap and RollbackSwap, and keep all database connections closed.

func ReadJournal

func ReadJournal(path string) (*SwapJournal, error)

ReadJournal reads recovery metadata without modifying it.

type SwapKind

type SwapKind string

SwapKind identifies the offline operation replacing a database file set.

const (
	SwapRestore SwapKind = "restore"
	SwapImport  SwapKind = "import"
	SwapScrub   SwapKind = "scrub"
)

Supported journaled swap operations.

Jump to

Keyboard shortcuts

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