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
- Variables
- func AtomicWrite(path string, data []byte, perm fs.FileMode) error
- func CheckSchemaVersion(data []byte, supported int) error
- func DecodeYAML(data []byte, v any) error
- func EncodeJSON(v any) ([]byte, error)
- func EncodeYAML(v any) ([]byte, error)
- func HashBytes(data []byte) [sha256.Size]byte
- func LockFile(path string) (func() error, error)
- func MarshalJSONL(v any) ([]byte, error)
- func RepairTornTail(path string) (int64, error)
- func ScanJSONL(path string, fn func(line []byte) error) error
- func TxnStageHookForTest(hook func(stage string))
- func WriteFileSync(path string, data []byte, perm fs.FileMode) error
- type Diagnostics
- type Expect
- type Options
- type PendingOp
- type PendingTxn
- type PendingTxnError
- type Reader
- type RecoveryReport
- type Store
- func (s *Store) DevsysDir() string
- func (s *Store) Diagnose() (Diagnostics, error)
- func (s *Store) Inspect(ctx context.Context, fn func(r *Reader) error) error
- func (s *Store) InspectUnlocked(ctx context.Context, fn func(r *Reader) error) error
- func (s *Store) LocalDir() string
- func (s *Store) Read(ctx context.Context, fn func(r *Reader) error) error
- func (s *Store) Recover(ctx context.Context) (RecoveryReport, error)
- func (s *Store) Write(ctx context.Context, fn func(tx *Tx) error) error
- type TailStatus
- type Tx
- func (tx *Tx) AppendJSONL(rel string, record any) error
- func (tx *Tx) AppendJSONLRaw(rel string, payload []byte) error
- func (tx *Tx) Delete(rel string, expect Expect) error
- func (tx *Tx) Put(rel string, content []byte, expect Expect) error
- func (tx *Tx) PutYAML(rel string, v any, expect Expect) error
- func (tx *Tx) ReadForExpect(rel string) ([]byte, bool, error)
- func (tx *Tx) Staged(rel string) bool
Constants ¶
const DefaultLockTimeout = 5 * time.Second
DefaultLockTimeout bounds how long a blocked Read/Write waits before returning ErrLockTimeout.
const DevsysDirName = ".devsys"
DevsysDirName is the per-project state directory (方案 §14.3).
Variables ¶
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") )
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.
var ErrLocked = errors.New("lock is held by another process")
ErrLocked reports that another holder has the lock.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 LockFile ¶
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 ¶
MarshalJSONL renders one JSONL record: compact JSON plus a trailing LF.
func RepairTornTail ¶
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 ¶
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).
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 ExpectHash ¶
ExpectHash requires the target file to have exactly this content hash.
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 有效状态读取须与写入、恢复协调).
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 ¶
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) 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 ¶
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 ¶
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 ¶
LocalDir returns the local-only directory that holds locks and transaction material.
func (*Store) Read ¶
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: 中断后先按日志完成确定性恢复).
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 ¶
AppendJSONL stages record as one JSONL line appended to rel. Appends are serialized by the project lock, so they never conflict.
func (*Tx) AppendJSONLRaw ¶
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 ¶
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) ReadForExpect ¶
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.