vault

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 36 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 vault scans, watches and writes vault directories (docs/design/vault.md).

Index

Constants

View Source
const (
	MaxSegment = 255
	MaxPath    = 4000
)

The longest a path's segment and a whole path may be, in bytes: what file systems hold (255 bytes a name, and well within PATH_MAX for the vault's own folder too).

View Source
const SettingsDir = ".frostnotes"

SettingsDir is the settings directory directly under a vault's root.

View Source
const SettingsFile = SettingsDir + "/vault.yaml"

SettingsFile is the settings file under SettingsDir.

View Source
const TypesFile = SettingsDir + "/types.yaml"

TypesFile is the property types file under SettingsDir.

Variables

View Source
var ErrChanged = errors.New("vault: the file is not as expected")

ErrChanged means a file is not in the state a change expected: it changed since, on disk or in the index. Sync pushes the local change first and applies the hub's answer (ADR-0017).

View Source
var ErrCrashed = errors.New("vault: crashed for the simulation")

ErrCrashed is what a change returns when Config.Crash stopped it after its rename and before its transaction, as a crash would: the simulation then restarts the notesd (ADR-0020).

View Source
var ErrPath = errors.New("not a vault path")

ErrPath is the error CheckPath wraps: a path the API may not name.

Functions

func Beside

func Beside(p, suffix string) string

Beside returns p with suffix put before its extension ("name 1.md", "name.sync-7.md"), the name's stem cut short, at a character, when the name would be longer than MaxSegment.

func CheckFolder

func CheckFolder(folder string) (string, error)

CheckFolder is CheckPath for a folder, where "", "/" and "." name the vault's root. It returns the folder without surrounding slashes.

func CheckPath

func CheckPath(p string) error

CheckPath reports whether p may name a file of a vault through the API (docs/design/vault.md): vault-relative and slash-separated, valid UTF-8, with no empty, "." or ".." segment, no NUL, and no segment starting with "." except a first segment of SettingsDir. It is lexical; checkFile refuses symlinks on disk.

func DailyPath

func DailyPath(s DailySettings, date time.Time) (string, error)

DailyPath is the path of date's daily note under s: the folder, then the date in s's format, which may name subfolders, then ".md".

func IsSettings

func IsSettings(p string) bool

IsSettings reports whether p lies in the vault's settings directory.

func LoadTypes

func LoadTypes(root string) (map[string]string, error)

LoadTypes reads the property types of the vault at root, by key lower-cased: Obsidian's built-in ones (aliases, cssclasses, tags) under .frostnotes/types.yaml, a mapping of key to type, or while that does not exist Obsidian's .obsidian/types.json. A types.yaml that cannot be read or decoded is an error; types.json only gives defaults, so one that cannot be decoded is skipped.

func Unholdable

func Unholdable(err error) bool

Unholdable reports whether err is a file system refusing a name: too long, or not in its character set.

func WithWriteGuard

func WithWriteGuard(ctx context.Context, guard func(path string) error) context.Context

WithWriteGuard returns ctx carrying guard, which the vault asks of each path it chooses to write.

Types

type Author

type Author struct {
	Source api.VersionSource // editor or agent
	Name   string            // the client's name; "" when unknown
	Push   *Push             // on a hub, the device's push this write is; nil otherwise
}

Author says who made a write, for its version.

type Config

type Config struct {
	DB    *store.DB
	Blobs *blobs.Store
	Log   *slog.Logger // [discard]
	// Publish delivers transient events (vault.scan); nil drops them.
	// Durable events go through the store as usual.
	Publish func([]api.EventEnvelope)
	// Now is the clock of daily notes and pruning [time.Now].
	Now func() time.Time
	// Debounce is how long a path must be quiet before the watcher's
	// events for it are handled [100ms].
	Debounce time.Duration
	// Rescan is the interval of rescans [5m]; NetworkRescan replaces it
	// for a vault on a network file system [10s].
	Rescan, NetworkRescan time.Duration
	// Batch is the most files one scan transaction indexes [200].
	Batch int
	// Keep is how long versions are kept [30 days]; PruneEvery is the
	// interval of the pass that prunes them [24h].
	Keep, PruneEvery time.Duration
	// Crash, when set, is asked at each point a crash could fall (only
	// "renamed": after a change's rename, before its transaction); true
	// stops the change there with ErrCrashed. The simulation sets it
	// (ADR-0020); notesd never does.
	Crash func(point string) bool
}

Config is what every vault's actor shares. Zero fields take the defaults in brackets.

type DailySettings

type DailySettings struct {
	Folder   string // "" is the vault root
	Format   string // a moment.js format; "" is YYYY-MM-DD
	Template string // the template note's path, ".md" optional; "" for none
}

DailySettings say where daily notes go and what a new one holds.

type Entry

type Entry struct {
	Path    string // Slash-separated, relative to the root.
	Kind    Kind
	Size    int64
	ModTime time.Time // Unrounded FileInfo modification time.
}

Entry describes a regular file in a vault.

type Expect

type Expect struct {
	Path string
	Hash string
}

Expect is the local state a pulled head may replace: the file at Path whose content hashes to Hash, or, when Hash is "", no file at Path.

type FileSettings

type FileSettings struct {
	NewNoteLocation  api.NewNoteLocation // root
	NewNoteFolder    string              // with NewNoteLocationFolder; "" is the vault root
	AttachmentFolder string              // as Obsidian writes it; "/" is the vault root
	LinkFormat       api.LinkFormat      // shortest
	Wikilinks        bool                // true
	UpdateLinks      bool                // false
}

FileSettings say where new notes and files go and how new links are written: Obsidian's Files and links settings, with its defaults.

type Head struct {
	Path    string
	Hash    string
	Deleted bool
}

Head is the state Apply makes: the blob Hash at Path, or no file when Deleted.

type Ignore

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

Ignore holds validated, case-sensitive vault ignore patterns.

func NewIgnore

func NewIgnore(patterns []string) (*Ignore, error)

NewIgnore validates patterns in the supported subset of gitignore syntax.

func (*Ignore) Match

func (ig *Ignore) Match(name string, dir bool) bool

Match reports whether a path or any of its parent folders is ignored. A nil *Ignore matches nothing; dir indicates whether the path itself is a folder.

type Kind

type Kind int

Kind identifies a vault file's role.

const (
	// KindNote is a file whose name ends in the case-sensitive suffix ".md".
	KindNote Kind = iota + 1
	// KindAttachment is any other regular file outside the settings directory.
	KindAttachment
	// KindSettings is a regular file under SettingsDir.
	KindSettings
)

type Listing

type Listing struct {
	Files   []Entry
	Skipped []Skip
	// Dirs holds every folder walked, SettingsDir included and the root
	// left out: the folders a watcher watches.
	Dirs []string
	// Temps holds the temporary files of atomic writes a crash left
	// behind, which a scan removes.
	Temps []string
}

Listing contains a complete walk, with non-nil slices sorted by Path in byte order.

func Walk

func Walk(ctx context.Context, root string, ignore *Ignore) (Listing, error)

Walk lists a vault's files without following symlinks. Any error discards the listing.

type Manager

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

Manager runs one actor per registered vault, and the daily pass that prunes versions and blobs.

func NewManager

func NewManager(cfg Config) *Manager

NewManager returns a Manager; Start runs it.

func (*Manager) Prune

func (m *Manager) Prune(ctx context.Context) error

Prune deletes the versions older than Config.Keep, except each file's newest, thins a hub's log by ADR-0019, and removes the blobs that no version, file or kept revision names any more and that are a day old, with every vault's changes held off, and no vault starting, so none can name a blob it removes (docs/design/vault.md#versions); requests that only read the index go on. Temporary blobs older than an hour go too.

func (*Manager) Reload

func (m *Manager) Reload(ctx context.Context) error

Reload starts an actor for each registered vault without one and stops the actors of vaults that are gone: vault.add and vault.remove call it.

func (*Manager) Remove

func (m *Manager) Remove(ctx context.Context, id int64, forget func() error) error

Remove forgets vault id: forget deletes its row, and the vault's actor first finishes the changes it is making and refuses new ones, so none writes a file the index can no longer record.

func (*Manager) Start

func (m *Manager) Start(ctx context.Context) error

Start opens every registered vault, scanning and watching each, and runs the prune pass now and every Config.PruneEvery, until ctx ends.

func (*Manager) Vault

func (m *Manager) Vault(id int64) (*Vault, error)

Vault returns vault id's actor, or notFound.

func (*Manager) Wait

func (m *Manager) Wait()

Wait blocks until every actor has stopped after Start's context ended.

type Push

type Push struct {
	DeviceID  int64
	ReplicaID int64
	PushID    int64
	Base      int64 // the revision the device based its change on
}

Push says which device's push a change is, for the hub's log (docs/specs/sync-protocol.md); it is nil for every other writer.

type PushChange

type PushChange struct {
	FileID   int64 // the hub's file ID; 0 for a create
	Base     int64 // the agreed revision; 0 for a create
	BaseHash string
	Path     string
	Hash     string // "" when Deleted
	Deleted  bool
	// Conflict: Hash lost conflicting hunks in a merge on the device; the
	// hub keeps it as a conflict revision of the file.
	Conflict bool
}

PushChange is one device's change to a file of a hub vault: the file's whole new state and the revision it was based on (log.push's PushItem).

type PushOutcome

type PushOutcome struct {
	Status     api.PushStatus
	Reason     api.RefuseReason // "" unless refused
	FileID     int64            // 0 for a refused create
	Conflicts  int64
	BasePruned bool
}

PushOutcome is what the hub did with a PushChange.

type Record

type Record func(ctx context.Context, tx *store.Tx, f store.File) error

Record runs in the transaction that records a change, after the change's own rows, with the file as it now is (a deleted file's last row): sync sets the file's agreed state there, so the two cannot disagree after a crash.

type Settings

type Settings struct {
	Daily     DailySettings
	Templates TemplateSettings
	Files     FileSettings
	// Ignore holds gitignore-style patterns of files the vault leaves out
	// (NewIgnore). Only vault.yaml sets them: Obsidian's Excluded files
	// hide files from its search and graph but keep them in the vault.
	Ignore []string
	// Sources says where each setting comes from, by its field's name in
	// api.VaultSettings.
	Sources map[string]api.SettingSource
	// contains filtered or unexported fields
}

Settings are a vault's settings (docs/design/vault.md#on-disk). Each one comes from .frostnotes/vault.yaml, or while that lacks it from Obsidian's .obsidian/daily-notes.json, templates.json or app.json, or is the default. Reading them never writes to the vault.

func LoadSettings

func LoadSettings(root string) (Settings, error)

LoadSettings reads the settings of the vault at root. A vault.yaml that cannot be read or decoded, or holds a value no setting takes, is an error; Obsidian's files are only defaults, so one that cannot be decoded, or a value in it that is not one, is skipped.

func (Settings) API

func (s Settings) API() api.VaultSettings

API is the settings as vault.settings returns them: each default spelled out.

type Skip

type Skip struct {
	Path   string
	Reason string // "symlink" or "not a regular file".
}

Skip records an entry that cannot be treated as a vault file.

type TemplateSettings

type TemplateSettings struct {
	Folder     string // where templates live; "" when unset
	DateFormat string // {{date}}'s moment.js format; "" is YYYY-MM-DD
	TimeFormat string // {{time}}'s moment.js format; "" is HH:mm
}

TemplateSettings are the defaults of template variables.

type Vault

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

Vault is one vault's actor. A goroutine scans and watches the vault's folder; mu serializes every change to the vault, whoever makes it: a write, a scan's batch, the watcher's paths. Reads of the index need no lock.

func (*Vault) AppendDaily

func (v *Vault) AppendDaily(ctx context.Context, date time.Time, text string, who Author) (*api.DailyAppend, error)

AppendDaily appends text at the end of date's daily note, after a line break when the note does not end in one, and ends it with one; it creates the note first as Daily does. The append is a write whose base is the note as read under the vault's lock, so it changes no text that is there (ADR-0028).

func (*Vault) Apply

func (v *Vault) Apply(ctx context.Context, exp Expect, head Head, who Author, rec Record) (store.File, error)

Apply makes the vault hold head where it holds exp, and nothing otherwise: a device applying what it pulled, which compares instead of merging (ADR-0017, docs/specs/sync-protocol.md). The file is compared with exp once more just before each rename; when it differs, nothing is written and Apply returns ErrChanged. Content streams from the blob store at any size. Every path passes the path guard, so a hub cannot write outside the vault or into its settings. rec, when not nil, runs in the transaction of the last change, or in one of its own when nothing needs to change. A folder the change leaves empty is removed.

func (v *Vault) Backlinks(ctx context.Context, fileID int64) ([]api.Backlink, error)

Backlinks returns the links to file fileID, as the store lists them, each with its line in the source (docs/specs/ui.md, Right sidebar panes): the index's spans index the content of the source's indexed hash, which the blob store holds.

func (*Vault) CheckSpelling

func (v *Vault) CheckSpelling(p string) error

CheckSpelling refuses a path that reaches a file or folder on disk by a name its folder does not list, up to case and Unicode normalization (api.SameName). A file system can answer to such a name: an 8.3 short name on a share, a trailing dot it trims, a letter it folds otherwise. An agent's scope judges paths by name, so it must not meet an alias of a folder it may not write (ADR-0028).

func (*Vault) Configure

func (v *Vault) Configure(ctx context.Context, c *api.VaultConfigureParams) (Settings, error)

Configure writes the settings c gives to vault.yaml, atomically, keeping its other keys and comments, emits vault.configured and returns the settings now in effect (ADR-0021). It is the only write notesd makes to SettingsDir.

func (*Vault) Create

func (v *Vault) Create(ctx context.Context, p string, content []byte, who Author) (*api.WriteResult, error)

Create makes a new file at p with content, and its missing folders. It fails with conflict when p exists (ADR-0006: only a create has no base).

func (*Vault) Daily

func (v *Vault) Daily(ctx context.Context, date time.Time, who Author) (*api.DailyNote, error)

Daily returns date's daily note, creating it from the vault's daily-note template when it is missing (docs/design/vault.md#daily-notes).

func (*Vault) Delete

func (v *Vault) Delete(ctx context.Context, p, base string, who Author) error

Delete removes p. base must be its current hash: a file changed since is not deleted, because an edit beats a delete (ADR-0005). Its versions stay, and a deletion version is added.

func (*Vault) DeleteFolder

func (v *Vault) DeleteFolder(ctx context.Context, folder string, files []api.FileBase, who Author) (*api.FolderDeleteResult, error)

DeleteFolder deletes the files of folder that files lists, each as Delete does with its base, then every folder left empty, the folder itself included. A file changed since its base, or not listed, is kept: an edit beats a delete (ADR-0005).

func (*Vault) Folders

func (v *Vault) Folders(ctx context.Context) ([]string, error)

Folders returns every folder below the vault's root that a scan walks, empty ones included, by path: hidden folders, the settings directory and ignored folders are left out. Unlike Walk it reads no file's information, so on a network share it costs one listing per folder.

func (*Vault) ID

func (v *Vault) ID() int64

ID is the vault's ID.

func (*Vault) Ignores

func (v *Vault) Ignores(p string) bool

Ignores reports whether the vault's settings leave p out: a device skips pulled heads at such paths.

func (*Vault) Mkdir

func (v *Vault) Mkdir(ctx context.Context, p string) error

Mkdir creates folder p and its missing parents; an existing folder is not an error. Folders have no events: a client lists note.files again.

func (*Vault) Move

func (v *Vault) Move(ctx context.Context, from, to string, updateLinks bool, who Author) (*api.MoveResult, error)

Move renames from to to, which must not exist, creating missing folders; the file keeps its ID and versions. With updateLinks, every link to it from a note, and every link of a moved note that the move would point elsewhere, is rewritten to the shortest target that resolves to the same file, as Obsidian's "Automatically update internal links" does; each note's rewrite is an ordinary write with a base (docs/design/vault.md#writes).

func (*Vault) MoveFolder

func (v *Vault) MoveFolder(ctx context.Context, from, to string, updateLinks bool, who Author) (*api.FolderMoveResult, error)

MoveFolder renames or moves folder from, with everything in it, to to, which must not exist, creating missing folders: one rename, after which each file the index has under it keeps its ID and versions, as Move's does, and with updateLinks the links Move would rewrite for each are rewritten.

func (*Vault) Park

func (v *Vault) Park(ctx context.Context, c PushChange, who Author) (string, string, error)

Park moves the file change c moves aside, beside where it is, as the first step of a ring of moves: the change itself then moves it on. The move appends its revision as part of c's push. It returns where the file was and where it went.

func (*Vault) Push

func (v *Vault) Push(ctx context.Context, c PushChange, who Author) (PushOutcome, error)

Push applies a device's change to this hub vault, as docs/specs/sync-protocol.md ("A push, on the hub") says: it checks the change, then creates, merges, moves, deletes or refuses, through the vault's write path, so every change appends its revision in the same transaction as its version; who carries the push's device, replica and push ID. The repeat of a push ID is the caller's to answer. A refusal is an outcome, not an error; errors are failures of the hub itself.

func (*Vault) PushOrder

func (v *Vault) PushOrder(ctx context.Context, cs []PushChange) ([]int, []int, error)

PushOrder orders a batch of pushed changes to this hub vault (docs/specs/sync-protocol.md, A push, on the hub). A change that moves a file onto a path another change of the batch moves a file away from goes after that change, so a batch that renames a chain of files takes no numbers. In a ring of such moves, a swap the simplest, one change is parked first: Park moves its file aside, and the ring then applies in order. It returns the order of cs's indexes, and the indexes to park.

func (*Vault) Read

func (v *Vault) Read(ctx context.Context, p string) (*api.Note, error)

Read returns a note or attachment as the API shows it, after bringing its index rows up to date with the file, so its hash is always a base a write can name.

func (*Vault) ReadVersion

func (v *Vault) ReadVersion(ctx context.Context, id int64) (*api.VersionContent, error)

ReadVersion returns one of the vault's versions and its content, as Read shows a file's.

func (*Vault) Reindex

func (v *Vault) Reindex(ctx context.Context) (api.ScanStatus, error)

Reindex asks for a scan that reads every file again and rebuilds its index rows, and returns the status.

func (*Vault) Render

func (v *Vault) Render(ctx context.Context, p string, note []byte) (string, error)

Render renders note, the content of the note at p or what an editor holds for it, to sanitized HTML (docs/specs/render.md). Links resolve over the index, and embedded notes and files are what the index holds.

func (*Vault) Resolve

func (v *Vault) Resolve(ctx context.Context, fileID, seq int64, who Author) error

Resolve clears file fileID's conflict flag with a resolve revision (log.resolve). seq is the newest conflict revision the user has seen: a newer one is api.Conflict, so a conflict that arrived since is not dismissed unseen. A file that is not flagged needs nothing.

func (*Vault) Revert

func (v *Vault) Revert(ctx context.Context, p string, id int64, base string, who Author) (*api.WriteResult, error)

Revert makes p's content that of version id, as a write with base; a deleted file comes back at p, its last path, with its ID.

func (*Vault) Root

func (v *Vault) Root() string

Root is the vault's folder.

func (*Vault) Serve

func (v *Vault) Serve(ctx context.Context) (store.HubVault, error)

Serve makes the vault a hub vault (hub.serve): it gets a sync ID, and each of its files, by path, a create revision, all in one transaction under the vault's lock, so no change slips between the files listed and the log begun.

func (*Vault) Status

func (v *Vault) Status(ctx context.Context) (api.ScanStatus, error)

Status is the state of the vault's index and scans.

func (*Vault) Template

func (v *Vault) Template(ctx context.Context, p, title string, at time.Time) (string, error)

Template returns the template note at p with its variables expanded (docs/design/vault.md#daily-notes): {{title}} is title, and {{date}} and {{time}} give at, in the template settings' formats.

func (*Vault) Unpark

func (v *Vault) Unpark(ctx context.Context, id int64, from, parked string, who Author) error

Unpark moves file id back from parked to from, when its change did not move it on (Push refused it) and from is still free.

func (*Vault) Write

func (v *Vault) Write(ctx context.Context, p, base string, text []byte, who Author) (*api.WriteResult, error)

Write replaces p's content with text, which the writer made from the content whose hash is base (ADR-0006). When the file changed since base, the write merges into it (docs/design/vault.md#writes); a conflicting hunk keeps the file's side, and text is kept as a conflict version. Bytes of the file that are not UTF-8 survive where text leaves them be (restore).

Jump to

Keyboard shortcuts

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