Documentation
¶
Overview ¶
Package vault scans, watches and writes vault directories (docs/design/vault.md).
Index ¶
- Constants
- Variables
- func Beside(p, suffix string) string
- func CheckFolder(folder string) (string, error)
- func CheckPath(p string) error
- func DailyPath(s DailySettings, date time.Time) (string, error)
- func IsSettings(p string) bool
- func LoadTypes(root string) (map[string]string, error)
- func Unholdable(err error) bool
- func WithWriteGuard(ctx context.Context, guard func(path string) error) context.Context
- type Author
- type Config
- type DailySettings
- type Entry
- type Expect
- type FileSettings
- type Head
- type Ignore
- type Kind
- type Listing
- type Manager
- func (m *Manager) Prune(ctx context.Context) error
- func (m *Manager) Reload(ctx context.Context) error
- func (m *Manager) Remove(ctx context.Context, id int64, forget func() error) error
- func (m *Manager) Start(ctx context.Context) error
- func (m *Manager) Vault(id int64) (*Vault, error)
- func (m *Manager) Wait()
- type Push
- type PushChange
- type PushOutcome
- type Record
- type Settings
- type Skip
- type TemplateSettings
- type Vault
- func (v *Vault) AppendDaily(ctx context.Context, date time.Time, text string, who Author) (*api.DailyAppend, error)
- func (v *Vault) Apply(ctx context.Context, exp Expect, head Head, who Author, rec Record) (store.File, error)
- func (v *Vault) Backlinks(ctx context.Context, fileID int64) ([]api.Backlink, error)
- func (v *Vault) CheckSpelling(p string) error
- func (v *Vault) Configure(ctx context.Context, c *api.VaultConfigureParams) (Settings, error)
- func (v *Vault) Create(ctx context.Context, p string, content []byte, who Author) (*api.WriteResult, error)
- func (v *Vault) Daily(ctx context.Context, date time.Time, who Author) (*api.DailyNote, error)
- func (v *Vault) Delete(ctx context.Context, p, base string, who Author) error
- func (v *Vault) DeleteFolder(ctx context.Context, folder string, files []api.FileBase, who Author) (*api.FolderDeleteResult, error)
- func (v *Vault) Folders(ctx context.Context) ([]string, error)
- func (v *Vault) ID() int64
- func (v *Vault) Ignores(p string) bool
- func (v *Vault) Mkdir(ctx context.Context, p string) error
- func (v *Vault) Move(ctx context.Context, from, to string, updateLinks bool, who Author) (*api.MoveResult, error)
- func (v *Vault) MoveFolder(ctx context.Context, from, to string, updateLinks bool, who Author) (*api.FolderMoveResult, error)
- func (v *Vault) Park(ctx context.Context, c PushChange, who Author) (string, string, error)
- func (v *Vault) Push(ctx context.Context, c PushChange, who Author) (PushOutcome, error)
- func (v *Vault) PushOrder(ctx context.Context, cs []PushChange) ([]int, []int, error)
- func (v *Vault) Read(ctx context.Context, p string) (*api.Note, error)
- func (v *Vault) ReadVersion(ctx context.Context, id int64) (*api.VersionContent, error)
- func (v *Vault) Reindex(ctx context.Context) (api.ScanStatus, error)
- func (v *Vault) Render(ctx context.Context, p string, note []byte) (string, error)
- func (v *Vault) Resolve(ctx context.Context, fileID, seq int64, who Author) error
- func (v *Vault) Revert(ctx context.Context, p string, id int64, base string, who Author) (*api.WriteResult, error)
- func (v *Vault) Root() string
- func (v *Vault) Scanned(ctx context.Context) error
- func (v *Vault) Serve(ctx context.Context) (store.HubVault, error)
- func (v *Vault) Status(ctx context.Context) (api.ScanStatus, error)
- func (v *Vault) Template(ctx context.Context, p, title string, at time.Time) (string, error)
- func (v *Vault) Unpark(ctx context.Context, id int64, from, parked string, who Author) error
- func (v *Vault) Write(ctx context.Context, p, base string, text []byte, who Author) (*api.WriteResult, error)
Constants ¶
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).
const SettingsDir = ".frostnotes"
SettingsDir is the settings directory directly under a vault's root.
const SettingsFile = SettingsDir + "/vault.yaml"
SettingsFile is the settings file under SettingsDir.
const TypesFile = SettingsDir + "/types.yaml"
TypesFile is the property types file under SettingsDir.
Variables ¶
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).
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).
var ErrNotScanned = errors.New("no scan of the vault has succeeded since it opened")
ErrNotScanned is what Scanned returns while no scan of the vault has succeeded since it opened.
var ErrPath = errors.New("not a vault path")
ErrPath is the error CheckPath wraps: a path the API may not name.
Functions ¶
func Beside ¶
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 ¶
CheckFolder is CheckPath for a folder, where "", "/" and "." name the vault's root. It returns the folder without surrounding slashes.
func CheckPath ¶
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 ¶
IsSettings reports whether p lies in the vault's settings directory.
func LoadTypes ¶
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 ¶
Unholdable reports whether err is a file system refusing a name: too long, or not in its character set.
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
// ("renamed": after a change's rename, before its transaction;
// "applying": in Apply's delete, before the file is removed); true
// stops the change there with ErrCrashed. The simulation sets it
// (ADR-0020), and tests (ADR-0034); 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 ¶
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 Ignore ¶
type Ignore struct {
// contains filtered or unexported fields
}
Ignore holds validated, case-sensitive vault ignore patterns.
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.
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 (*Manager) Prune ¶
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 ¶
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 ¶
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 ¶
Start opens every registered vault, scanning and watching each, and runs the prune pass now and every Config.PruneEvery, until ctx ends.
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 ¶
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 ¶
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 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 (*Vault) Backlinks ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) Ignores ¶
Ignores reports whether the vault's settings leave p out: a device skips pulled heads at such paths.
func (*Vault) Mkdir ¶
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 ¶
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 ¶
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 ¶
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 ¶
ReadVersion returns one of the vault's versions and its content, as Read shows a file's.
func (*Vault) Reindex ¶
Reindex asks for a scan that reads every file again and rebuilds its index rows, and returns the status.
func (*Vault) Render ¶
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 ¶
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) Scanned ¶ added in v0.3.2
Scanned waits until the vault's first scan has finished. It returns nil once a scan has succeeded since the vault opened: the index then holds what the disk held when notesd started, a file a crash left behind or took away included. While none has (a scan fails as a whole, changing nothing, on a folder it cannot read or an empty folder of an indexed vault), it returns ErrNotScanned at once: the index may still hold rows of files that are gone. A later scan that succeeds, the next rescan among them, makes it return nil.
func (*Vault) Serve ¶
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) Template ¶
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 ¶
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).