# store/file

> Package filestore is a durable store.LogStore on a local filesystem: one append-only log file per session, plus a directory of each session's outputs and one of its checkpoint versions.

<!-- Generated from the Go source of github.com/barevoidco/zelk/core/store/file (cmd/zelk/internal/reference TestReferenceGoAPI). Don't edit: change the code, then run make reference. -->

```go
import filestore "github.com/barevoidco/zelk/core/store/file"
```

Package filestore is a durable [store.LogStore](/reference/go/store/#logstore) on a local filesystem: one append-only log file per session, plus a directory of each session's outputs and one of its checkpoint versions.

The record format, the write protocol and how crash damage is told apart from corruption are specified in docs/design/durability.md. In short: every append is one framed, checksummed record, acknowledged only after fsync; a crash can damage only the final, unacknowledged record, which is the only damage ever repaired; anything else is reported as corruption.

Inbox keeps observer occurrences outside the session log without requiring a lease. Pending durably seals payloads before returning them for admission; Trim follows log acknowledgment. Both bounds and immutability are enforced.

See docs/design/durability.md for the Windows NTFS process-crash contract.


## Constants

```go
const DefaultLockWait = 10 * time.Second
```

DefaultLockWait is how long an append waits for another store's append to release a session's writer lock, unless WithLockWait says otherwise.

```go
const DefaultOpenLogs = 64
```

DefaultOpenLogs is how many session logs a Store keeps open by default.


## Variables

```go
var (
	// ErrBroken is returned for a session whose writer failed to write or
	// sync, or to repair a torn tail. The failed batch may or may not be on
	// disk, and until the machine restarts the page cache can show it
	// either way, so the session is neither written nor read again: not by
	// this store, and, through a marker file, not by other stores or
	// processes either (docs/design/durability.md).
	ErrBroken = errors.New("session log writer broken by a failed write or sync")
	// ErrCorrupt is returned for a log or blob whose contents are damaged
	// in a way a crash can't explain. Nothing is repaired. A whole log
	// another generation of zelk wrote isn't damaged: reading it reports
	// event.ErrFormatBreak or event.ErrUnsupportedVersion alone, and
	// nothing in it is repaired, a torn tail included.
	ErrCorrupt = store.ErrCorrupt
	// ErrLocked is returned by Append when another writer, in this process
	// or another, holds the session log's lock.
	ErrLocked = errors.New("session log is locked by another writer")
)
```


## Option

```go
type Option func(*Store)
```

Option configures a [Store](/reference/go/store-file/#store).


### WithLockWait

```go
func WithLockWait(d time.Duration) Option
```

WithLockWait sets how long an append waits for another store's append to release the session's writer lock before failing with ErrLocked. Appends hold it only from write to sync; a writer that broke holds it until its process exits.


### WithLogger

```go
func WithLogger(l *slog.Logger) Option
```

WithLogger sets the logger the store reports torn-tail repairs to. The default discards everything.


### WithOpenLogs

```go
func WithOpenLogs(n int) Option
```

WithOpenLogs bounds how many session logs the store keeps open between appends; the least recently written is closed first, and reopened when next written. The default is DefaultOpenLogs. A broken session's log stays open regardless (see Close).


## Store

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

Store is a [store.LogStore](/reference/go/store/#logstore) that keeps each session's log in its own file under a directory, and each session's outputs and checkpoint versions in directories beside the logs. A Store is safe for concurrent use. Close it when done.

**Example**

```go
dir, err := os.MkdirTemp("", "zelk-example-*")
if err != nil {
	panic(err)
}
defer os.RemoveAll(dir)

ctx := context.Background()
s, err := filestore.New(ctx, dir)
if err != nil {
	panic(err)
}
defer s.Close()

tok := lease.Token{Session: "s1", Fence: 1}
now := time.Date(2026, 10, 15, 9, 0, 0, 0, time.UTC)
if err := s.Append(ctx, "s1", 0, tok, event.Event{Seq: 1, Time: now, Payload: event.Warning{Code: "hello"}}); err != nil {
	panic(err)
}
for ev, err := range s.Read(ctx, "s1", 0) {
	if err != nil {
		panic(err)
	}
	fmt.Println(ev.Seq, ev.Payload.(event.Warning).Code)
}
// Output:
// 1 hello
```

Output:

```text
1 hello
```


### New

```go
func New(ctx context.Context, dir string, opts ...Option) (*Store, error)
```

New opens the store in dir, which must be the absolute path of an existing directory. The host owns dir and its durability; the store creates its own subdirectories in it and makes them durable before returning. ctx is checked before each step; the file system calls themselves can't be interrupted.


### Store.Adopt

```go
func (s *Store) Adopt(ctx context.Context, session string, token lease.Token) (uint64, error)
```

Adopt makes everything the session's log holds durable, records token's fence, and returns the sequence number of the log's last event (docs/design/durability.md, L11). A new holder adopts a log before folding it, so it never decides anything from a batch another writer wrote but never synced. Adopting a session that was never written creates its empty log.


### Store.Append

```go
func (s *Store) Append(ctx context.Context, session string, expectSeq uint64, token lease.Token, evs ...event.Event) error
```

Append atomically adds evs to the session's log as one record, and returns only once the record is synced. It takes the log's writer lock for this append only (docs/design/durability.md, L9), waiting for another store's append if one holds it, and refreshes what it knows of the log under the lock, since another store may have written while it was free. ctx is honoured until the write starts; once started, the write and sync run to completion, because abandoning them would break the session.


### Store.Blobs

```go
func (s *Store) Blobs() store.BlobStore
```

Blobs returns the store of the sessions' outputs, kept per session under outputs/ (docs/design/retention.md).


### Store.Close

```go
func (s *Store) Close() error
```

Close closes the store's open log files, releasing their locks. Appends after Close fail; reads and blob operations keep working, and a session that broke stays refused.

A broken session's log is deliberately left open, holding its lock until the process exits: until then the page cache may show the uncertain batch, and the lock is the one guard that can't fail, so no other writer can adopt the batch even if the broken-session marker couldn't be written.


### Store.DropHistory

```go
func (s *Store) DropHistory(ctx context.Context, session string) error
```

DropHistory removes the session's version directory and everything in it.


### Store.Durable

```go
func (*Store) Durable() bool
```

Durable reports true: logs outlive the process, along with the fences that guard them, so the store needs a lease whose fences do too, such as lease/file.


### Store.GetVersion

```go
func (s *Store) GetVersion(ctx context.Context, session string, ref blob.Ref) ([]byte, error)
```

GetVersion returns a version of the session's history after checking it against its digest.


### Store.Inbox

```go
func (s *Store) Inbox() store.Inbox
```

Inbox returns the store's durable observer inbox. Operations take the existing session writer lock but require no lease token, and never append to the log.

**Example**

```go
dir, err := os.MkdirTemp("", "zelk-inbox-example-*")
if err != nil {
	panic(err)
}
defer os.RemoveAll(dir)
ctx := context.Background()
s, err := filestore.New(ctx, dir)
if err != nil {
	panic(err)
}
defer s.Close()
if err = s.Inbox().Append(ctx, "session", "build", store.Occurrence{Payload: event.OccurrencePayload{Text: "Build failed"}}); err != nil {
	panic(err)
}
pending, err := s.Inbox().Pending(ctx, "session", "build", 0)
if err != nil {
	panic(err)
}
fmt.Println(pending[0].Number, pending[0].Payload.Text)
// Output: 1 Build failed
```

Output:

```text
1 Build failed
```


### Store.Leftovers

```go
func (s *Store) Leftovers(ctx context.Context) iter.Seq2[string, error]
```

Leftovers yields the sessions the listing leaves out that still hold storage: logs that are empty or tombstoned, and outputs, file history or inboxes with no log.


### Store.PruneVersions

```go
func (s *Store) PruneVersions(ctx context.Context, session string, keep func(digest string) bool) error
```

PruneVersions removes the session's versions keep rejects, and any temporary file a crashed PutVersion left behind.


### Store.PutVersion

```go
func (s *Store) PutVersion(ctx context.Context, session string, data []byte) (blob.Ref, error)
```

PutVersion stores data in the session's history: written and synced under a temporary name, linked into place, and the directory synced, before it returns.


### Store.Read

```go
func (s *Store) Read(ctx context.Context, session string, fromSeq uint64) iter.Seq2[event.Event, error]
```

Read yields the session's events from fromSeq on. A torn tail, the unacknowledged remains of a crash, ends the log silently; corruption is reported as ErrCorrupt, after the whole records before it. Once the store has read or written a session, it reads only from the record holding fromSeq; records before that were verified when they were indexed.


### Store.RemoveSession

```go
func (s *Store) RemoveSession(ctx context.Context, session string, token lease.Token) error
```

RemoveSession removes the session's outputs, inbox, file history and then its log, under the log's writer lock (docs/design/retention.md). The log is not decoded or repaired, so unreadable logs can be removed. The fence file stays: a writer whose lease ended before the removal still holds the old log open, and the fence keeps refusing it. A broken log is refused with ErrBroken: it is evidence, and removing it is an operator's decision.


### Store.Sessions

```go
func (s *Store) Sessions(ctx context.Context) iter.Seq2[store.SessionInfo, error]
```

Sessions yields the sessions whose logs hold an event, most recently updated first. The store remembers how far it has summarized each log, so listing again reads only what was appended since. An unreadable log is yielded with its ID, error and file modification time in Updated; if stat fails, Updated is zero and the error includes that failure.
