storage

package
v0.1.8 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: MIT Imports: 19 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 storage implements the text state primitives required by 方案 §15.2: atomic single-file replacement, JSONL appends with torn-tail detection, stable-key YAML/JSON serialization, a project-level short write lock, optimistic version checks and a recoverable multi-file transaction log.

Facts this package does *not* claim: file-system crash consistency under power loss. It provides single-file atomicity (temp file + rename), process interruption recovery (journal replay), and best-effort fsync. Power-loss durability is out of scope until separately verified.

Index

Constants

View Source
const DefaultLockTimeout = 5 * time.Second

DefaultLockTimeout bounds how long a blocked Read/Write waits before returning ErrLockTimeout.

View Source
const DevsysDirName = ".devsys"

DevsysDirName is the per-project state directory (方案 §14.3).

Variables

View Source
var (
	// ErrConflict reports that a staged update expected an older version of a
	// managed file than the one currently on disk (方案 §15.2 乐观并发控制).
	ErrConflict = errors.New("storage: version conflict")

	// ErrLockTimeout reports that the project lock stayed busy for the whole
	// LockTimeout window.
	ErrLockTimeout = errors.New("storage: project lock timeout")

	// ErrRecoveryFailed reports that an interrupted transaction could not be
	// recovered deterministically. Valid-state reads and writes are refused
	// until it is resolved; diagnostics remain available.
	ErrRecoveryFailed = errors.New("storage: transaction recovery failed")

	// ErrIncompleteTail reports a JSONL file whose last line has no line
	// terminator (a torn append).
	ErrIncompleteTail = errors.New("storage: jsonl incomplete tail")

	// ErrUnsafePath reports a managed path that would leave the .devsys tree
	// or collide with storage-internal material.
	ErrUnsafePath = errors.New("storage: unsafe managed path")

	// ErrSchemaVersion reports a missing or unsupported schema_version.
	ErrSchemaVersion = errors.New("storage: schema_version rejected")

	// ErrNotInitialized reports a project root without a .devsys directory.
	ErrNotInitialized = errors.New("storage: project not initialized")
)
View Source
var ErrLockUnavailable = errors.New("storage: project lock unavailable (no .devsys/local/lock)")

ErrLockUnavailable reports that the project lock file does not exist, so a read-only command cannot take the shared lock without creating state. Callers should report "inspection unavailable" rather than fabricating a "no activity" claim.

View Source
var ErrLocked = errors.New("lock is held by another process")

ErrLocked reports that another holder has the lock.

View Source
var ErrPendingTxn = errors.New("storage: pending transactions block inspection")

ErrPendingTxn reports that Inspect refuses to run while pending transactions exist on disk. Callers must surface the pending IDs and refuse to render business facts (方案 §15.4 待恢复事务不作为有效业务状态返回).

Functions

func AtomicWrite

func AtomicWrite(path string, data []byte, perm fs.FileMode) error

AtomicWrite replaces path with data by writing a temporary file in the same directory, fsyncing it and renaming it over the destination. Readers observe either the old or the new content, never a partial file (方案 §15.2 单文件 原子写). Existing permissions are preserved when the file already exists, otherwise perm is used. The parent directory is fsynced on POSIX on a best-effort basis; that error is not propagated, and no power-loss guarantee is claimed.

func CheckSchemaVersion

func CheckSchemaVersion(data []byte, supported int) error

CheckSchemaVersion validates the top-level schema_version field of a managed file against the version this build understands (方案 §14.1: 读到未知版本时 拒绝写入). Unlike DecodeYAML it ignores unknown keys on purpose, because it runs before the strict per-file decoding introduced in M0.4.

func DecodeYAML

func DecodeYAML(data []byte, v any) error

DecodeYAML decodes exactly one YAML document into v with unknown keys rejected, so typos and half-written files fail loudly instead of being silently ignored. Field errors carry line numbers from the parser.

func EncodeJSON

func EncodeJSON(v any) ([]byte, error)

EncodeJSON renders v as compact deterministic JSON. Struct fields keep their declaration order and map keys are sorted; HTML escaping is off so state files stay readable and diffable.

func EncodeYAML

func EncodeYAML(v any) ([]byte, error)

EncodeYAML renders v deterministically so that repeated writes of the same value produce identical bytes (方案 §14.1 文本优先/可 diff): key order follows struct field order (maps sort by key), indentation is two spaces and the output always ends in exactly one LF. State files must be produced through an encoder like this one rather than by hand-rolling YAML.

func HashBytes

func HashBytes(data []byte) [sha256.Size]byte

HashBytes returns the version tag used for content.

func LockFile

func LockFile(path string) (func() error, error)

LockFile takes a non-blocking exclusive advisory lock on path, creating the file when needed, and returns the release function. It is the same primitive the store uses for project-level write locks (方案 §15.2): the OS releases it when the process dies, so an interrupted run never leaves the file locked.

Contention is reported as ErrLocked rather than waited out: a caller that wants to wait can retry, and a caller that must not run twice (a long refresh) gets a straight answer.

func MarshalJSONL

func MarshalJSONL(v any) ([]byte, error)

MarshalJSONL renders one JSONL record: compact JSON plus a trailing LF.

func RepairTornTail

func RepairTornTail(path string) (int64, error)

RepairTornTail truncates a JSONL file back to its last complete line and reports how many bytes were dropped (0 when the file is missing or already ends on a line boundary). A torn tail is a record that was never completed, so dropping it loses no record; callers are expected to note the repair in the stream itself. Append-only evidence streams (方案 §14.2 运行事件流) use this so a crash cannot leave a file that refuses every later append.

func ScanJSONL

func ScanJSONL(path string, fn func(line []byte) error) error

ScanJSONL calls fn for every complete line of a JSONL file, without the line terminator (a trailing CR is also stripped). A missing file scans as empty. A file whose last line has no terminator fails with ErrIncompleteTail before that line is handed to fn, so callers never observe a torn record.

func TxnStageHookForTest

func TxnStageHookForTest(hook func(stage string))

TxnStageHookForTest installs a test-only hook that fires after each durable transaction stage. Production code must not call it; it exists so other packages can simulate a real process interruption at an exact stage (the internal hook itself is unexported).

func WriteFileSync

func WriteFileSync(path string, data []byte, perm fs.FileMode) error

WriteFileSync writes data to path, creating it if needed, and fsyncs it. It is the primitive for new files (journal, payload) that are not replacing an existing version.

Types

type Diagnostics

type Diagnostics struct {
	// TxnDir is the transaction material directory.
	TxnDir string
	// Lock is the best-effort holder description of the last exclusive holder.
	Lock string
	// Pending lists transaction directories still on disk.
	Pending []PendingTxn
}

Diagnostics is the read-only recovery view. It never fails on damaged transaction material: describing the damage is its purpose.

type Expect

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

Expect is an optimistic version guard for a managed file (方案 §15.2 乐观并发控制/版本号): a Put only applies while the file still matches it.

func ExpectAbsent

func ExpectAbsent() Expect

ExpectAbsent requires the target file to be missing.

func ExpectAny

func ExpectAny() Expect

ExpectAny stages a Put without a version check.

func ExpectHash

func ExpectHash(h [sha256.Size]byte) Expect

ExpectHash requires the target file to have exactly this content hash.

func (Expect) String

func (e Expect) String() string

type Options

type Options struct {
	// LockTimeout is how long Read/Write wait for the project lock.
	LockTimeout time.Duration
	// Now supplies the current time; tests override it.
	Now func() time.Time
}

Options tunes a Store; zero values are valid.

type PendingOp

type PendingOp struct {
	Rel string
	// Status is "applied" (the new content is already in place), "pending"
	// (recovery would apply it), "conflict" (the target matches neither the
	// expected old nor the committed new content) or "unknown".
	Status string
	Detail string
}

PendingOp is the on-disk status of one staged operation.

type PendingTxn

type PendingTxn struct {
	ID string
	// State is "uncommitted" (discardable), "committed" (replayable) or
	// "unreadable" (needs a human).
	State string
	// Detail explains what recovery would do, or what is wrong.
	Detail string
	// Ops describes, per staged operation, what recovery would find on disk.
	Ops []PendingOp
}

PendingTxn describes one transaction directory found by Diagnose.

type PendingTxnError

type PendingTxnError struct {
	IDs []string
}

PendingTxnError wraps the pending transaction IDs alongside ErrPendingTxn so callers can render them without re-scanning the directory.

func (*PendingTxnError) Error

func (e *PendingTxnError) Error() string

func (*PendingTxnError) Unwrap

func (e *PendingTxnError) Unwrap() error

type Reader

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

Reader exposes consistent reads: it runs under the shared project lock, and Read/Write recover interrupted transactions first, so callers never observe a half-applied multi-file change (方案 §15.2 有效状态读取须与写入、恢复协调).

func (*Reader) Expect

func (r *Reader) Expect(rel string) (Expect, error)

Expect reads rel and returns the version guard that makes a later Put fail if anyone else changed the file in between (optimistic concurrency).

func (*Reader) Read

func (r *Reader) Read(rel string) ([]byte, bool, error)

Read returns the content of a managed file; a missing file yields exists false rather than an error.

type RecoveryReport

type RecoveryReport struct {
	// Discarded counts transactions that never reached the commit point and
	// were removed (their targets were verified untouched).
	Discarded int
	// Replayed counts committed transactions whose changes were re-applied.
	Replayed int
	// Skipped counts committed operations already present on disk (the
	// idempotent part of the replay).
	Skipped int
}

RecoveryReport summarizes one recovery pass.

func (RecoveryReport) Empty

func (r RecoveryReport) Empty() bool

Empty reports that nothing needed recovery.

type Store

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

Store gives coordinated access to the managed state under <root>/.devsys.

func Open

func Open(root string, opts Options) (*Store, error)

Open binds a project root (the directory that contains .devsys) to the storage primitives. The .devsys directory must already exist (devsys init); nothing is created here.

func (*Store) DevsysDir

func (s *Store) DevsysDir() string

DevsysDir returns the managed state directory.

func (*Store) Diagnose

func (s *Store) Diagnose() (Diagnostics, error)

Diagnose reports the pending transaction material and lock state without changing anything. It does not take the project lock: its output is informational, not a consistency claim.

func (*Store) Inspect

func (s *Store) Inspect(ctx context.Context, fn func(r *Reader) error) error

Inspect runs fn under the shared project lock without auto-recovery and without creating the lock file. See package doc for the contract.

func (*Store) InspectUnlocked

func (s *Store) InspectUnlocked(ctx context.Context, fn func(r *Reader) error) error

InspectUnlocked runs fn without the project lock. It is the conservative fallback for read-only diagnostics when no lock file exists yet (no writer ever ran): every file read is still a single atomic-replace target, so readers observe whole files. A concurrent first write can still race; callers must treat the snapshot as advisory and re-check critical evidence under a real transaction (方案 §15.4: 只读诊断不得误判).

func (*Store) LocalDir

func (s *Store) LocalDir() string

LocalDir returns the local-only directory that holds locks and transaction material.

func (*Store) Read

func (s *Store) Read(ctx context.Context, fn func(r *Reader) error) error

Read runs fn under the shared project lock. When an interrupted transaction needs recovery it upgrades to the exclusive lock, recovers deterministically and retries; a failed recovery is reported instead of reading partial state.

func (*Store) Recover

func (s *Store) Recover(ctx context.Context) (RecoveryReport, error)

Recover performs the deterministic recovery of interrupted transactions under the exclusive project lock (方案 §15.2: 中断后先按日志完成确定性恢复).

func (*Store) Write

func (s *Store) Write(ctx context.Context, fn func(tx *Tx) error) error

Write runs fn under the exclusive project lock and applies the collected changes as one recoverable transaction. fn errors abort the whole transaction: nothing reaches the managed files. An empty transaction is a no-op.

type TailStatus

type TailStatus struct {
	// Size is the current file size in bytes (0 when the file is missing).
	Size int64
	// Complete is true when the file is empty or ends with a line terminator.
	// A false value marks a torn append left by an interrupted writer.
	Complete bool
}

TailStatus describes whether a JSONL file can be appended to.

func InspectJSONL

func InspectJSONL(path string) (TailStatus, error)

InspectJSONL reports the size and tail state of a JSONL file. A missing file is treated as a complete empty file.

type Tx

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

Tx collects the changes of a single transaction. Ops are validated and applied under the project lock by Store.Write.

func (*Tx) AppendJSONL

func (tx *Tx) AppendJSONL(rel string, record any) error

AppendJSONL stages record as one JSONL line appended to rel. Appends are serialized by the project lock, so they never conflict.

func (*Tx) AppendJSONLRaw

func (tx *Tx) AppendJSONLRaw(rel string, payload []byte) error

AppendJSONLRaw stages a raw JSONL payload — one or more complete lines, each terminated by LF — as one append to rel. It exists for callers that must keep the one-append-per-file rule while batching records that share a shard (events.AppendBatchTx). Empty lines, CR bytes (records are LF-only, compact JSON never contains them raw) and a missing final terminator are rejected before staging.

func (*Tx) Delete

func (tx *Tx) Delete(rel string, expect Expect) error

Delete stages the removal of rel, guarded by expect. The delete participates in the same recoverable transaction as Put/AppendJSONL: precondition, journal and commit marker are recorded together, and a crash mid-commit is recovered by replaying the journal idempotently.

func (*Tx) Put

func (tx *Tx) Put(rel string, content []byte, expect Expect) error

Put stages a replacement of rel with content, guarded by expect.

func (*Tx) PutYAML

func (tx *Tx) PutYAML(rel string, v any, expect Expect) error

PutYAML serializes v with EncodeYAML and stages it as a replacement of rel.

func (*Tx) ReadForExpect

func (tx *Tx) ReadForExpect(rel string) ([]byte, bool, error)

ReadForExpect returns the current bytes of rel inside an open transaction so callers can decode the exact content their ExpectHash guard will replace. It performs no locking: Store.Write already holds the exclusive project lock.

func (*Tx) Staged

func (tx *Tx) Staged(rel string) bool

Staged reports whether rel has already been staged in this transaction. In-transaction reads see the on-disk state, so a second writer (e.g. an invalidation pass after a Guard already rewrote the same file) must use this check to avoid staging the same path twice.

Jump to

Keyboard shortcuts

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