store

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 23 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 store is notesd's SQLite database: migrations, the single writer, the durable event log and the queries (docs/design/vault.md).

Reads go through DB methods and may run concurrently. Every write runs in DB.Tx, which serializes writers, records the events the transaction emits and hands them to OnCommit after commit, in commit order.

Index

Constants

View Source
const TimeFormat = "2006-01-02T15:04:05.000Z"

TimeFormat is how times are stored: UTC, fixed width, lexically sortable.

Variables

View Source
var (
	// ErrNotFound means the row does not exist.
	ErrNotFound = errors.New("store: not found")
	// ErrConflict means a uniqueness rule rejected the write.
	ErrConflict = errors.New("store: conflict")
)

Functions

func FileName

func FileName(p string) string

FileName is the key markdown.Resolve's files(name) looks up: the last segment of p, lower-cased by strings.ToLower. files.name holds it. Task card T-0014.

func FormatTime

func FormatTime(t time.Time) string

FormatTime renders t in TimeFormat.

func IsForeignKeyViolation

func IsForeignKeyViolation(err error) bool

IsForeignKeyViolation reports whether err is SQLite's foreign key constraint failure: a row names a parent that does not exist.

func IsUniqueViolation

func IsUniqueViolation(err error) bool

IsUniqueViolation reports whether err is a SQLite UNIQUE or PRIMARY KEY constraint failure; callers map it to ErrConflict.

func LinkName

func LinkName(target string) string

LinkName is links.name for a link's target: its last segment, lower-cased by strings.ToLower, without a final ".md"; "" for an empty target. A file whose FileName is n may resolve the links named strings.TrimSuffix(n, ".md"). Task card T-0015.

func ParseTime

func ParseTime(s string) (time.Time, error)

ParseTime parses a TimeFormat value.

func SearchQuery

func SearchQuery(text string) string

SearchQuery turns what a user typed into an FTS5 MATCH expression: each double-quoted phrase, and each other word with a letter or digit, is quoted as an FTS5 phrase, a word with "*" after it to match as a prefix, and all are required. It returns "" when nothing is left to match. Task card T-0016.

Types

type Agreed

type Agreed struct {
	VaultID    int64
	HubFile    int64
	FileID     int64 // the local files.id
	Seq        int64 // the latest revision of the file applied or answered
	Revision   int64 // the agreed head
	Path       string
	Hash       string
	Conflicted bool
}

Agreed is a sync_files row: what this device and the hub last agreed a file is.

type BacklinkSpan

type BacklinkSpan struct {
	Backlink   api.Backlink
	SourceHash string
	Start      int
	Stop       int
}

BacklinkSpan is a backlink with where it sits in its source: the byte offsets of the link in the content whose hash is SourceHash.

type Change

type Change struct {
	FileID  int64   // the local file
	Agreed  *Agreed // nil for a create
	Path    string  // the file's path now; for a delete, the agreed path
	Hash    string  // its hash now; "" for a delete
	Deleted bool
}

Change is a file with a change to push: the difference between the index and the agreed state.

type DB

type DB struct {

	// Now is the clock for stored timestamps; tests replace it.
	Now func() time.Time
	// OnCommit receives each committed transaction's events, in commit
	// order, while the write lock is held. It must not block.
	OnCommit func([]api.EventEnvelope)
	// contains filtered or unexported fields
}

DB is the notesd database.

func Open

func Open(ctx context.Context, path string) (*DB, error)

Open opens or creates the database at path and applies pending migrations. path must not live on a network or virtiofs share: WAL needs shared memory.

func (*DB) AgreedByFile

func (d *DB) AgreedByFile(ctx context.Context, fileID int64) (Agreed, error)

AgreedByFile returns the agreed row of local file fileID, or ErrNotFound. Task card T-0027.

func (*DB) AgreedByHubFile

func (d *DB) AgreedByHubFile(ctx context.Context, vaultID, hubFile int64) (Agreed, error)

AgreedByHubFile returns the agreed row of hub file hubFile in vault vaultID, or ErrNotFound. Task card T-0027.

func (*DB) AgreedRows

func (d *DB) AgreedRows(ctx context.Context, vaultID int64) ([]Agreed, error)

AgreedRows returns vault vaultID's agreed rows by path; a non-nil empty slice when none. Task card T-0027.

func (*DB) BacklinkSpans

func (d *DB) BacklinkSpans(ctx context.Context, fileID int64) ([]BacklinkSpan, error)

BacklinkSpans returns Backlinks' links with their spans, in the same order, for showing each link's line.

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

Backlinks returns the links that resolve to file fileID, by the linking note's path, then line, then position. Task card T-0017.

func (*DB) ChangesSince

func (d *DB) ChangesSince(ctx context.Context, seq int64) ([]api.EventEnvelope, error)

ChangesSince returns the retained durable events after seq, in order.

func (*DB) Close

func (d *DB) Close() error

Close closes the database.

func (*DB) Device

func (d *DB) Device(ctx context.Context, id int64) (HubDevice, error)

Device returns device id, revoked or not, or ErrNotFound. Task card T-0026.

func (*DB) DeviceByToken

func (d *DB) DeviceByToken(ctx context.Context, tokenHash string) (HubDevice, error)

DeviceByToken returns the device whose token's SHA-256 is tokenHash, or ErrNotFound when none has it (revoked devices have none). Task card T-0026.

func (*DB) Devices

func (d *DB) Devices(ctx context.Context) ([]HubDevice, error)

Devices returns every device, revoked ones included, by ID; a non-nil empty slice when none. Task card T-0026.

func (*DB) FileByID

func (d *DB) FileByID(ctx context.Context, id int64) (File, error)

FileByID returns file id, or ErrNotFound.

func (*DB) FileByPath

func (d *DB) FileByPath(ctx context.Context, vaultID int64, path string) (File, error)

FileByPath returns vault's file at path, or ErrNotFound. Task card T-0014.

func (*DB) FileCounts

func (d *DB) FileCounts(ctx context.Context, vaultID int64) (notes, attachments int, err error)

FileCounts returns how many notes and attachments vault has. Task card T-0014.

func (*DB) Files

func (d *DB) Files(ctx context.Context, vaultID int64) ([]File, error)

Files returns every file of vault in byte order of path: what a scan compares with a walk. Task card T-0014.

func (*DB) FilesNamed

func (d *DB) FilesNamed(ctx context.Context, vaultID int64, name string) ([]string, error)

FilesNamed returns the paths of vault's files whose FileName is name: markdown.Resolve's files(name), outside a transaction.

func (*DB) GetVault

func (d *DB) GetVault(ctx context.Context, id int64) (Vault, error)

GetVault returns one vault, or ErrNotFound.

func (*DB) GetVersion

func (d *DB) GetVersion(ctx context.Context, id int64) (Version, error)

GetVersion returns version id, or ErrNotFound. Task card T-0018.

func (*DB) HasContent

func (d *DB) HasContent(ctx context.Context, hash string) (bool, error)

func (*DB) HasVersion

func (d *DB) HasVersion(ctx context.Context, fileID int64, hash string) (bool, error)

HasVersion reports whether file fileID has a version with content hash, a conflict version included, a deletion not: whether hash may be the base of a write.

func (*DB) History

func (d *DB) History(ctx context.Context, vaultID, fileID, before int64, limit int) ([]api.Revision, error)

History returns file fileID's revisions in vault vaultID, newest first, only those before seq before when before > 0, at most limit (50 when limit is 0 or less; more than 200 is 200), with their device's name, or "hub" when DeviceID is 0. A file the log does not have is ErrNotFound. Task card T-0025.

func (*DB) HubFile

func (d *DB) HubFile(ctx context.Context, vaultID, fileID int64) (HubFile, error)

HubFile returns file fileID's place in vault vaultID's log, or ErrNotFound. Task card T-0024.

func (*DB) HubIdentity

func (d *DB) HubIdentity(ctx context.Context) (string, error)

HubIdentity returns the hub ID, or "" when this notesd has never served a vault. Task card T-0024.

func (*DB) HubURL

func (d *DB) HubURL(ctx context.Context) (string, error)

HubURL returns the URL the hub records for its devices (hub.setURL), or "" when it records none.

func (*DB) HubVault

func (d *DB) HubVault(ctx context.Context, vaultID int64) (HubVault, error)

HubVault returns served vault vaultID, or ErrNotFound when it is not served. Task card T-0024.

func (*DB) HubVaultBySync

func (d *DB) HubVaultBySync(ctx context.Context, syncID string) (HubVault, error)

HubVaultBySync returns the served vault with sync ID syncID, or ErrNotFound. Task card T-0024.

func (*DB) HubVaults

func (d *DB) HubVaults(ctx context.Context) ([]HubVault, error)

HubVaults returns every served vault, by name, then vault ID; a non-nil empty slice when none. Task card T-0024.

func (*DB) IndexSnapshot

func (d *DB) IndexSnapshot(ctx context.Context, vaultID int64) ([]string, error)

IndexSnapshot returns everything vault's index holds as sorted text rows, by path rather than ID: an index after a crash and restart must equal a fresh rebuild of the same files row for row (plan 0003's kill -9 harness).

func (*DB) LastFileAt

func (d *DB) LastFileAt(ctx context.Context, vaultID int64, path string) (int64, error)

LastFileAt returns the ID of the file whose newest version was recorded at path in vault, the way to a deleted file's versions, or ErrNotFound. Task card T-0018.

func (*DB) LatestSeq

func (d *DB) LatestSeq(ctx context.Context) (int64, error)

LatestSeq is the highest durable sequence number ever assigned, or 0. It survives pruning because it reads AUTOINCREMENT's counter.

func (d *DB) Links(ctx context.Context, fileID int64) ([]api.Link, error)

Links returns note fileID's links in the order they are written, each with the path it resolves to. Task card T-0017.

func (*DB) ListNotes

func (d *DB) ListNotes(ctx context.Context, vaultID int64, f NoteFilter) ([]api.NoteEntry, error)

ListNotes returns vault's notes that match f, by path. Task card T-0017.

func (*DB) ListVaults

func (d *DB) ListVaults(ctx context.Context) ([]Vault, error)

ListVaults returns every vault ordered by name, then ID; none is an empty slice.

func (*DB) LogFile

func (d *DB) LogFile(ctx context.Context, vaultID, fileID int64) (api.LogFile, error)

LogFile returns file fileID as log.pull shows it: its hub_files row with its head revision's path, hash, size, author and device name ("hub" for the hub's own writers), and Deleted when the head is a delete. ErrNotFound when the log does not have the file. Task card T-0024.

func (*DB) Match

func (d *DB) Match(ctx context.Context, vaultID int64, qs []api.MatchQuery) ([]api.LogMatch, error)

Match answers log.match for vault vaultID, in the order of qs: for each query, File is the file last at q.Path (the file of the newest revision whose path is q.Path, other than a conflict or resolve), and Revision is the revision a copy with hash q.Hash at q.Path is agreed at: that file's newest create, put or move at q.Path no later than its newest create, put or move with hash q.Hash, or that one when the file was not at q.Path before it; RevisionHash is that revision's content. So a copy that has a later revision's content but not its path is a put from the revision before the file left the path, and the hub's answer brings it the head's path. Either is nil when there is none. Task card T-0025.

func (*DB) NamedRevision

func (d *DB) NamedRevision(ctx context.Context, vaultID, seq int64) (api.Revision, error)

NamedRevision returns revision seq of vault vaultID as History gives revisions, with its device's name, or ErrNotFound.

func (*DB) NoteInfo

func (d *DB) NoteInfo(ctx context.Context, fileID int64) (NoteInfo, error)

NoteInfo returns what the index holds for note fileID, or ErrNotFound. Task card T-0017.

func (*DB) OldestSeq

func (d *DB) OldestSeq(ctx context.Context) (int64, error)

OldestSeq is the lowest retained sequence number, or 0 when the log is empty.

func (*DB) Pending

func (d *DB) Pending(ctx context.Context, vaultID int64) ([]Change, error)

Pending returns vault vaultID's changes to push, comparing its files rows with its agreed rows (docs/specs/sync-protocol.md, Pending changes): a file without an agreed row is a create, a file whose path or hash differs from its agreed row a put, an agreed row whose file is gone a delete. A change whose file, path and hash (or deletion) are those of the file's newest push, when that push was refused, is left out. The order is deletes, then puts, then creates, each by path. Task card T-0027.

func (*DB) PendingConflicts

func (d *DB) PendingConflicts(ctx context.Context, vaultID int64) ([]LostLocally, error)

PendingConflicts returns vault vaultID's local conflict versions of files it agrees with the hub on, that no push has carried, by version. The device pushes each as a conflict item, so the hub's log keeps it and flags the file (docs/specs/sync-protocol.md, Pending changes).

func (*DB) PropertyCounts

func (d *DB) PropertyCounts(ctx context.Context, vaultID int64, types map[string]string) ([]api.PropertyCount, error)

PropertyCounts returns every frontmatter key of vault's notes and how many notes have it, one entry per key ignoring case as strings.ToLower folds it, ordered by the lower-cased key in byte order. A key's spelling is the one that sorts first in byte order among its notes' spellings; a key counts even when its value is null or an empty list. types maps lower-cased keys to the vault's property types; a key without one has type "". Task card T-0043.

func (*DB) PruneChanges

func (d *DB) PruneChanges(ctx context.Context, keep int) error

PruneChanges keeps the newest keep durable events.

func (*DB) Pull

func (d *DB) Pull(ctx context.Context, vaultID, after int64, limit int) (api.LogPage, error)

Pull returns the files of vault vaultID whose hub_files.seq is after after, by that seq, at most limit of them (500 when limit is 0 or less; more than 1,000 is 1,000), each as LogFile returns it. Next is the last file's seq, or after when there are none; More is whether a file after Next remains. Files is non-nil. Task card T-0024.

func (*DB) PushRecords

func (d *DB) PushRecords(ctx context.Context, vaultID, replicaID int64, pushes []int64) ([]api.PushRecord, error)

PushRecords returns, for each push ID in pushes, in that order, the revisions of vault vaultID that replica replicaID's push made, by seq, with their device's name; Revisions is a non-nil empty slice when there are none. Task card T-0025.

func (*DB) Pushes

func (d *DB) Pushes(ctx context.Context, vaultID int64) ([]LocalPush, error)

Pushes returns vault vaultID's answered pushes, by push ID; a non-nil empty slice when none. Task card T-0027.

func (*DB) Remote

func (d *DB) Remote(ctx context.Context, vaultID int64) (Remote, error)

Remote returns vault vaultID's remote, or ErrNotFound. Task card T-0027.

func (*DB) Remotes

func (d *DB) Remotes(ctx context.Context) ([]Remote, error)

Remotes returns every remote by vault ID; a non-nil empty slice when none. Task card T-0027.

func (*DB) Replica

func (d *DB) Replica(ctx context.Context, id int64) (Replica, error)

Replica returns replica id, or ErrNotFound. Task card T-0025.

func (*DB) Revision

func (d *DB) Revision(ctx context.Context, vaultID, seq int64) (Revision, error)

Revision returns revision seq of vault vaultID, or ErrNotFound. Task card T-0024.

func (*DB) SchemaVersion

func (d *DB) SchemaVersion(ctx context.Context) (int, error)

SchemaVersion is the highest applied migration.

func (*DB) Search

func (d *DB) Search(ctx context.Context, vaultID int64, query string, limit int) ([]api.SearchHit, error)

Search returns vault's notes that match query, an expression from SearchQuery, best first, at most limit of them, each with a snippet around its best match. Task card T-0016.

func (*DB) SearchNotes

func (d *DB) SearchNotes(ctx context.Context, vaultID int64, q Query, limit int) ([]api.SearchHit, error)

SearchNotes returns vault's notes that match q, at most limit of them. With Match, it ranks and snippets as Search does, keeping only notes the filters admit; with filters alone it lists the notes they admit by path, each without a snippet; with neither it returns none. Task card T-0044.

func (*DB) SyncHub

func (d *DB) SyncHub(ctx context.Context, id int64) (SyncHub, error)

SyncHub returns sync_hubs row id, or ErrNotFound. Task card T-0027.

func (*DB) SyncHubByURL

func (d *DB) SyncHubByURL(ctx context.Context, url string) (SyncHub, error)

SyncHubByURL returns the hub paired at exactly url, or ErrNotFound. Task card T-0027.

func (*DB) SyncHubs

func (d *DB) SyncHubs(ctx context.Context) ([]SyncHub, error)

SyncHubs returns the paired hubs by ID; a non-nil empty slice when none. Task card T-0027.

func (*DB) TagCounts

func (d *DB) TagCounts(ctx context.Context, vaultID int64) ([]api.TagCount, error)

TagCounts returns every tag of vault's notes and how many notes have it, one entry per tag ignoring case (tags.folded), ordered by that folded name. A tag's spelling is the one that sorts first in byte order among its notes' spellings. Nested tags are counted whole: a note tagged a/b counts for a/b, not for a. Task card T-0043.

func (*DB) Tx

func (d *DB) Tx(ctx context.Context, fn func(*Tx) error) error

Tx runs fn in a write transaction: committed if fn returns nil, rolled back otherwise. Writers are serialized.

func (*DB) Unanswered

func (d *DB) Unanswered(ctx context.Context, vaultID int64) ([]LocalPush, error)

Unanswered returns vault vaultID's pushes without an answer, by push ID: a retry sends them again with the same IDs. Task card T-0027.

func (*DB) UsedHashes

func (d *DB) UsedHashes(ctx context.Context) (map[string]bool, error)

UsedHashes returns every hash a version, a file or a hub revision whose content is kept (a create, put, move or conflict not yet pruned) names, in every vault: the blobs that must stay.

func (*DB) VaultHasContent

func (d *DB) VaultHasContent(ctx context.Context, vaultID int64, hash string) (bool, error)

HasContent reports whether a create, put, move or conflict revision of a served vault that is not pruned names hash: the blobs /sync/blobs hands out. A delete or resolve revision holds no content of its own. Task card T-0024. VaultHasContent reports whether hub vault vaultID's log names content hash and keeps it: what a device of that vault may take as present without uploading it.

func (*DB) Versions

func (d *DB) Versions(ctx context.Context, fileID int64, limit int) ([]Version, error)

Versions returns file fileID's versions, newest first, at most limit of them (50 when limit is 0 or less). Task card T-0018.

type File

type File struct {
	ID      int64
	VaultID int64
	Path    string    // vault-relative and slash-separated, as on disk
	Size    int64     // in bytes
	ModTime time.Time // stored as Unix nanoseconds, so a scan compares it exactly
	Hash    string    // the lowercase hex SHA-256 of the content: its blob ID
}

File is a files row: one file of a vault.

func (File) Kind

func (f File) Kind() FileKind

Kind is FileNote when f's name ends in ".md", FileAttachment otherwise. Task card T-0014.

type FileKind

type FileKind string

FileKind is what a file is to the index.

const (
	FileNote       FileKind = "note"       // a name ending in ".md", exactly
	FileAttachment FileKind = "attachment" // any other file
)

The kinds of file (docs/specs/markdown.md#notes-and-files).

type HubDevice

type HubDevice struct {
	ID        int64
	Name      string
	TokenHash string // "" once revoked
	PairedAt  time.Time
	SeenAt    time.Time // zero until its first request
	RevokedAt time.Time // zero unless revoked
}

HubDevice is a hub_devices row: a paired device (ADR-0016).

func (HubDevice) API

func (h HubDevice) API(connected bool) api.HubDevice

API converts d to its wire form; connected says whether it is connected now, which only the hub's listener knows. Task card T-0026.

type HubFile

type HubFile struct {
	VaultID    int64
	FileID     int64
	Seq        int64 // its latest revision of any kind
	Revision   int64 // its head: the latest create, put, move or delete
	Conflicted bool
}

HubFile is a hub_files row: a file's place in its vault's log.

type HubVault

type HubVault struct {
	VaultID  int64
	SyncID   string // 32 lowercase hex digits
	Name     string // the vault's name
	Seq      int64  // the log's latest sequence number; 0 before any revision
	ServedAt time.Time
}

HubVault is a hub_vaults row, with its vault's name.

func (HubVault) API

func (v HubVault) API() api.HubVault

API converts v to the hub domain's form. Task card T-0024.

func (HubVault) Log

func (v HubVault) Log() api.LogVault

Log converts v to the log domain's form. Task card T-0024.

type LocalPush

type LocalPush struct {
	VaultID  int64
	PushID   int64
	FileID   int64
	HubFile  int64 // 0 for a create
	Base     int64
	Path     string
	Hash     string // "" for a delete
	At       time.Time
	Status   api.PushStatus   // "" until answered
	Reason   api.RefuseReason // "" unless refused
	Conflict bool             // a local conflict version, for the hub's log
	// BaseHash is the content hash of revision Base, for a conflict item
	// whose file has no agreed row when it is sent (DropAgreed); "" when
	// the agreed row gives it.
	BaseHash string
}

LocalPush is a sync_pushes row: a push this device made.

type LostLocally

type LostLocally struct {
	FileID int64
	Agreed Agreed
	Path   string
	Hash   string
}

LostLocally is a conflict version of a synced file that no push has carried to the hub yet: content a writer with a stale base lost in a merge on this device.

type NoteFilter

type NoteFilter struct {
	Folder   string // a vault-relative folder: notes in it or below it; "/" is the whole vault
	Tag      string // a tag, or the parent of nested tags, without '#'; case is ignored
	Property string // a frontmatter key the note has
	Value    string // with Property: the key's value, or an item of its list; case is ignored
}

NoteFilter selects notes for ListNotes. A zero field selects every note; a note must match every field that is set.

type NoteInfo

type NoteInfo struct {
	Title     string
	Props     jsontext.Value // the frontmatter as a JSON object
	PropError string         // "" without one
	Aliases   []string
	Tags      []string // as first spelled, in Doc order
	Words     int
}

NoteInfo is what the index holds for one note beyond its file.

type PushAnswer

type PushAnswer struct {
	ReplicaID  int64
	PushID     int64
	FileID     int64 // 0 for a refused create
	Status     api.PushStatus
	Reason     api.RefuseReason // "" unless refused
	Conflicts  int64
	BasePruned bool
	At         time.Time
}

PushAnswer is a hub_pushes row: what the hub answered one push.

type Query

type Query struct {
	// Match is an FTS5 MATCH expression, as SearchQuery makes it from the
	// words and phrases that are not filters; "" when there are none.
	Match string
	// Paths hold path:TEXT filters: a note's path must contain each,
	// ignoring case.
	Paths []string
	// Files hold file:TEXT filters: a note's file name, its last path
	// segment, must contain each, ignoring case.
	Files []string
	// Tags hold tag:#TAG filters, without '#' and lower-cased: a note must
	// have each tag or one nested under it.
	Tags []string
}

Query is a search as note.search takes it: words and phrases to match, and filters (schema/rpc/note.yaml, note.search).

func ParseQuery

func ParseQuery(text string) Query

ParseQuery splits what a user typed into a Query. A filter is a word that starts with path:, file: or tag: (case ignored) followed by its value, which may be a double-quoted phrase; an empty value is no filter. Everything else goes to SearchQuery. Task card T-0044.

type Remote

type Remote struct {
	VaultID   int64
	Hub       int64 // the sync_hubs row
	SyncID    string
	Name      string // the hub vault's name
	ReplicaID int64
	Cursor    int64
	HubSeq    int64
	JoinedAt  time.Time
	SyncedAt  time.Time // zero until the device was first in step
}

Remote is a remotes row: a local vault synced with a hub vault.

type Replica

type Replica struct {
	ID       int64
	DeviceID int64
	VaultID  int64
	JoinedAt time.Time
}

Replica is a hub_replicas row: one device's join of one vault.

type Revision

type Revision struct {
	VaultID   int64
	Seq       int64
	FileID    int64 // the hub's files.id
	Op        api.RevisionOp
	Path      string // the file's path after this revision
	Hash      string // the content; "" for a delete
	Size      int64
	Base      int64 // the revision it was based on; 0 for a create
	DeviceID  int64 // 0 for the hub's own writers
	ReplicaID int64 // 0 unless a push made it
	PushID    int64 // 0 unless a push made it
	Source    api.VersionSource
	Author    string
	At        time.Time
	LostTo    int64 // a conflict revision's winner; 0 otherwise
	Pruned    bool  // its content is no longer kept (ADR-0019)
}

Revision is a revisions row (ADR-0017).

func (Revision) API

func (r Revision) API(deviceName string) api.Revision

API converts r to its wire form, with deviceName its device's name ("hub" for the hub's own writers). Task card T-0025.

type SyncHub

type SyncHub struct {
	ID       int64
	HubID    string
	URL      string
	DeviceID int64 // this device's ID on the hub
	PairedAt time.Time
}

SyncHub is a sync_hubs row. The device token is in the secret store.

func (SyncHub) API

func (h SyncHub) API() api.SyncHub

API converts h to its wire form. Task card T-0027.

type Tx

type Tx struct {
	*sql.Tx
	// contains filtered or unexported fields
}

Tx is a write transaction. Emit records events delivered after commit.

func (*Tx) AddDevice

func (t *Tx) AddDevice(ctx context.Context, name, tokenHash string) (HubDevice, error)

AddDevice records a paired device with paired_at = t.Now(). A token hash another device has is ErrConflict. Task card T-0026.

func (*Tx) AddPush

func (t *Tx) AddPush(ctx context.Context, p LocalPush) (LocalPush, error)

AddPush records p with PushID the vault's highest + 1 (from 1), At = t.Now() and no answer (p.PushID, p.At, p.Status and p.Reason are ignored), and returns it. Task card T-0027.

func (*Tx) AddRemote

func (t *Tx) AddRemote(ctx context.Context, r Remote) (Remote, error)

AddRemote records r with joined_at = t.Now(), cursor and hub_seq as given, and synced_at null. A vault that is already synced is ErrConflict; a vault or hub that does not exist, ErrNotFound. Task card T-0027.

func (*Tx) AddReplica

func (t *Tx) AddReplica(ctx context.Context, deviceID, vaultID int64) (Replica, error)

AddReplica records a new replica of vault vaultID for device deviceID, with joined_at = t.Now(). ErrNotFound when the vault is not served or the device does not exist. Task card T-0025.

func (*Tx) AddVersion

func (t *Tx) AddVersion(ctx context.Context, v Version) (Version, error)

AddVersion appends v with At = t.Now(), to the millisecond, and returns it with its ID; v.ID and v.At are ignored. Task card T-0018.

func (*Tx) AgreedByFileTx

func (t *Tx) AgreedByFileTx(ctx context.Context, fileID int64) (Agreed, error)

AgreedByFileTx is AgreedByFile as this transaction sees it.

func (*Tx) AgreedByHubFileTx

func (t *Tx) AgreedByHubFileTx(ctx context.Context, vaultID, hubFile int64) (Agreed, error)

AgreedByHubFileTx is AgreedByHubFile as this transaction sees it.

func (*Tx) AnswerPush

func (t *Tx) AnswerPush(ctx context.Context, vaultID, pushID int64, status api.PushStatus, reason api.RefuseReason) error

AnswerPush records the answer to push pushID of vault vaultID; a push that does not exist is ErrNotFound. Task card T-0027.

func (*Tx) AppendRevision

func (t *Tx) AppendRevision(ctx context.Context, r Revision) (Revision, error)

AppendRevision appends r to the log of vault r.VaultID and returns it as stored: Seq is the vault's seq + 1 and At is t.Now() to the millisecond (r.Seq and r.At are ignored). In the same transaction it sets hub_vaults.seq, and the file's hub_files row: seq always; revision for a create, put, move or delete; conflicted to 1 for a conflict and to 0 for a resolve. It emits api.LogAppended{Vault: the sync ID, Seq}. A vault that is not served is ErrNotFound. A create of a file the log already has, any other op for a file it does not have, and a delete, conflict or resolve whose Hash disagrees with its op (a delete has "", the others a hash) are errors, and nothing is appended. Task card T-0024.

func (*Tx) DeleteAgreed

func (t *Tx) DeleteAgreed(ctx context.Context, vaultID, hubFile int64) error

DeleteAgreed removes the agreed row of hub file hubFile in vault vaultID; a missing row is not an error. Task card T-0027.

func (*Tx) DeleteFile

func (t *Tx) DeleteFile(ctx context.Context, id int64) error

DeleteFile removes file id and its index rows, or returns ErrNotFound. The links that resolved to it are re-resolved: another file may now match. Its versions stay. Task card T-0014.

func (*Tx) DeleteRemote

func (t *Tx) DeleteRemote(ctx context.Context, vaultID int64) error

DeleteRemote removes vault vaultID's remote with its agreed rows and pushes; a vault without one is ErrNotFound. Task card T-0027.

func (*Tx) DeleteUnseenDevice added in v0.2.0

func (t *Tx) DeleteUnseenDevice(ctx context.Context, id int64) (bool, error)

DeleteUnseenDevice deletes device id when no request has touched it and it is not revoked, and reports whether it deleted it: a pairing the device could not keep its token for. A device that made a request stays, since the hub's revisions may name it.

func (*Tx) DeleteVault

func (t *Tx) DeleteVault(ctx context.Context, id int64) error

DeleteVault forgets vault id and emits api.VaultRemoved. A missing vault returns ErrNotFound.

func (*Tx) DropAgreed added in v0.3.1

func (t *Tx) DropAgreed(ctx context.Context, vaultID, hubFile int64) error

DropAgreed removes the agreed row of hub file hubFile in vault vaultID, for a delete that applied, as DeleteAgreed does. Its local file's conflict versions that no push has carried, which PendingConflicts finds only through the row, are recorded first as unanswered conflict pushes from the row (hub file, revision and its hash, path), and its unanswered conflict pushes take the row as their base: the device sends them as it sends every unanswered push, and the hub keeps them as conflict revisions of the file, live or deleted (docs/specs/sync-protocol.md, Pending changes). A missing row is not an error.

func (*Tx) Emit

func (t *Tx) Emit(ctx context.Context, ev api.Event) error

Emit records ev. A durable event is appended to the changes log in this transaction and gets its sequence number; every event is delivered to OnCommit only if the transaction commits.

func (*Tx) FileByPath

func (t *Tx) FileByPath(ctx context.Context, vaultID int64, path string) (File, error)

FileByPath returns vault's file at path as this transaction sees it, or ErrNotFound. Task card T-0014.

func (*Tx) HubFile

func (t *Tx) HubFile(ctx context.Context, vaultID, fileID int64) (HubFile, error)

HubFile returns file fileID's place in the log as this transaction sees it, or ErrNotFound. Task card T-0024.

func (*Tx) HubID

func (t *Tx) HubID(ctx context.Context) (string, error)

HubID returns this notesd's hub ID, making it on first use: 32 lowercase hex digits from crypto/rand, stored with created_at = t.Now(). Task card T-0024.

func (*Tx) HubVault

func (t *Tx) HubVault(ctx context.Context, vaultID int64) (HubVault, error)

HubVault returns served vault vaultID as this transaction sees it, or ErrNotFound. Task card T-0024.

func (*Tx) IndexNote

func (t *Tx) IndexNote(ctx context.Context, f File, content []byte, doc markdown.Doc) error

IndexNote replaces the index rows of note f (notes, props, tags, links, headings, blocks, tasks and its notes_fts row) with doc, which markdown.Parse returned for content. Each link is resolved with ResolveLink. f must be a note in the files table. Task card T-0015.

func (*Tx) InsertVault

func (t *Tx) InsertVault(ctx context.Context, name, path string) (Vault, error)

InsertVault registers a vault with CreatedAt = tx.Now() and emits api.VaultAdded. A path already registered returns ErrConflict.

func (*Tx) MarkSynced

func (t *Tx) MarkSynced(ctx context.Context, vaultID int64) error

MarkSynced sets vault vaultID's synced_at to t.Now(); ErrNotFound without a remote. Task card T-0027.

func (*Tx) MoveFile

func (t *Tx) MoveFile(ctx context.Context, id int64, to string) (File, error)

MoveFile gives file id the path to, keeping its ID, its index rows and its versions. It returns ErrNotFound when there is no file id and ErrConflict when to is taken. The links that could name the file by its old or new name, and a moved note's own links, are re-resolved, and a renamed note's title follows its name. Task card T-0014.

func (*Tx) Now

func (t *Tx) Now() time.Time

Now is the database clock, for rows written in this transaction.

func (*Tx) PruneRevisions

func (t *Tx) PruneRevisions(ctx context.Context, now time.Time, loc *time.Location) ([]string, error)

PruneRevisions applies ADR-0019 to every served vault as of now, with days and months in loc: it sets pruned on each revision with content (a create, put, move or conflict) that is no longer kept, and returns, sorted, the hashes it pruned that no kept create, put, move or conflict revision, no files row and no versions row names any more: the blobs that may go. A revision is kept when it is less than 30 days old (at > now - 30 days); when it is its file's head; when it is a conflict revision after its file's last resolve while the file is flagged; when it is a create, put or move less than 365 days old and its file's last create, put or move of its day; or when it is a create, put or move and its file's last of its month. A pruned revision stays pruned. Task card T-0028.

func (*Tx) PruneVersions

func (t *Tx) PruneVersions(ctx context.Context, before time.Time) ([]string, error)

PruneVersions deletes the versions made before before, except the newest version of each file that still exists and the versions holding a file's current content (a conflict version can be newer), and returns, sorted, the hashes that no version, no file and no hub revision whose content is kept names any more: the blobs that may go. Task card T-0018.

func (*Tx) PushAnswer

func (t *Tx) PushAnswer(ctx context.Context, replicaID, pushID int64) (PushAnswer, error)

PushAnswer returns the answer to push pushID of replica replicaID as this transaction sees it, or ErrNotFound. Task card T-0025.

func (*Tx) PutAgreed

func (t *Tx) PutAgreed(ctx context.Context, a Agreed) error

PutAgreed inserts a, or replaces the row with its vault and hub file. A local file that is agreed with another hub file is ErrConflict. Task card T-0027.

func (*Tx) PutFile

func (t *Tx) PutFile(ctx context.Context, f File) (File, error)

PutFile records f in vault f.VaultID: it inserts a row when the vault has no file at f.Path, and otherwise updates that row's size, time and hash. It returns the row; f.ID is ignored. Inserting a file re-resolves the vault's links that could name it. Task card T-0014.

func (*Tx) PutSyncHub

func (t *Tx) PutSyncHub(ctx context.Context, h SyncHub) (SyncHub, error)

PutSyncHub records a pairing with h.PairedAt = t.Now(): a new row, or, for a hub ID the device has paired with before, that row with its URL, device ID and paired_at replaced. It returns the row. Task card T-0027.

func (*Tx) RecordPush

func (t *Tx) RecordPush(ctx context.Context, a PushAnswer) error

RecordPush stores a's answer with at = t.Now() (a.At is ignored). A push ID the replica has an answer for is ErrConflict. Task card T-0025.

func (t *Tx) ResolveLink(ctx context.Context, vaultID int64, source, target string) (File, bool, error)

ResolveLink returns the file that a link from note source to target names, by markdown.Resolve over vault's files as this transaction sees them, and false when the link is unresolved. Task card T-0014.

func (*Tx) RestoreFile

func (t *Tx) RestoreFile(ctx context.Context, f File) (File, error)

RestoreFile records f, which DeleteFile removed, again with its ID, so its versions name it once more: note.revert bringing a deleted file back. It returns ErrConflict when vault f.VaultID has a file at f.Path or a file with f.ID. Like PutFile's insert, it re-resolves the vault's links that could name it.

func (*Tx) Revision

func (t *Tx) Revision(ctx context.Context, vaultID, seq int64) (Revision, error)

Revision returns revision seq as this transaction sees it, or ErrNotFound. Task card T-0024.

func (*Tx) RevokeDevice

func (t *Tx) RevokeDevice(ctx context.Context, id int64) error

RevokeDevice clears device id's token hash and sets revoked_at = t.Now(), once: revoking a revoked device changes nothing. ErrNotFound for a device that does not exist. Task card T-0026.

func (*Tx) ServeVault

func (t *Tx) ServeVault(ctx context.Context, vaultID int64) (HubVault, error)

ServeVault makes vault vaultID a hub vault, with a new sync ID (32 lowercase hex digits from crypto/rand), seq 0 and served_at = t.Now(), making the hub ID too if it is missing. A vault that is already served is ErrConflict; a vault that does not exist, ErrNotFound. Task card T-0024.

func (*Tx) SetCursor

func (t *Tx) SetCursor(ctx context.Context, vaultID, cursor, hubSeq int64) error

SetCursor sets vault vaultID's cursor, and its hub_seq to the larger of the stored one and hubSeq; ErrNotFound without a remote. Task card T-0027.

func (*Tx) SetHubURL

func (t *Tx) SetHubURL(ctx context.Context, url string) error

SetHubURL records url ("" forgets it) as the URL the hub's devices should use, making the hub ID first if it is missing.

func (*Tx) SetReplica

func (t *Tx) SetReplica(ctx context.Context, vaultID, replicaID int64) error

SetReplica records replicaID as vault vaultID's replica on its hub: a device that paired again joins anew, keeping its agreed state and cursor. ErrNotFound without a remote.

func (*Tx) SetSyncHubURL

func (t *Tx) SetSyncHubURL(ctx context.Context, id int64, url string) (SyncHub, error)

SetSyncHubURL moves sync_hubs row id to url, keeping its hub ID, device ID and every vault synced with it (log.hub, sync.relocate). A row that does not exist is ErrNotFound; a URL another row has, ErrConflict.

func (*Tx) TouchDevice

func (t *Tx) TouchDevice(ctx context.Context, id int64, at time.Time) (bool, error)

TouchDevice sets device id's seen_at to at, unless seen_at is less than a minute before at, and reports whether it changed it. Task card T-0026.

type Vault

type Vault struct {
	ID        int64
	Name      string
	Path      string
	CreatedAt time.Time
}

Vault is a vaults row.

func (Vault) API

func (v Vault) API() api.Vault

API converts v to its wire form.

type Version

type Version struct {
	ID       int64
	VaultID  int64
	FileID   int64  // kept after the file is deleted; file IDs are never reused
	Path     string // the file's path when this version was made
	Hash     string // the content's blob ID; "" records a deletion
	Size     int64
	At       time.Time
	Source   api.VersionSource
	Author   string // "" for an outside edit
	Conflict bool   // a writer's content that lost a conflicting hunk in a merge
}

Version is a versions row: one version of a file, or its deletion.

func (Version) API

func (v Version) API() api.Version

API converts v to its wire form. Task card T-0018.

Jump to

Keyboard shortcuts

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