index

package
v0.200.3 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: BSD-2-Clause Imports: 24 Imported by: 1 module, 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 index keeps the metadata of each vault folder's pages in memory so a list read can be answered without opening a vault file. It never holds a page body: listed pages carry empty Content, each entry carries its pre-parsed Open Questions, and a body is read from disk on request only.

See docs/page-index.md for the full contract.

Index

Constants

View Source
const (
	ReadReasonBuild  = "build"
	ReadReasonEvent  = "event"
	ReadReasonWrite  = "write"
	ReadReasonRescan = "rescan"
	ReadReasonReload = "reload"
)

The reasons a single-file read happens, reported through Metrics.FileRead.

View Source
const (
	UnboundedUnknownKey                   = "unknown_key"
	UnboundedRevisionAhead                = "revision_ahead"
	UnboundedWindowNotRetained            = "window_not_retained"
	UnboundedForcedReload                 = "forced_reload"
	UnboundedFirstPublication             = "first_publication"
	UnboundedFolderMarkExplicit           = "folder_mark_explicit"
	UnboundedFolderMarkWidenedName        = "folder_mark_widened_name_not_in_snapshot"
	UnboundedFolderMarkWidenedFile        = "folder_mark_widened_file_absent"
	UnboundedFolderMarkWidenedNameInvalid = "folder_mark_widened_invalid_name"
	UnboundedFolderMarkWidenedKey         = "folder_mark_widened_key_unpublished"
)

The reasons a changed set cannot be bounded, reported through Metrics.ChangedPagesUnbounded.

View Source
const RescanInterval = 50 * time.Second

RescanInterval is the time between stat-diff rescans of every known key. It is deliberately below the 60 s ceiling so that interval + rescanPollInterval + one read stays inside it.

View Source
const StoreFormatVersion = 2

StoreFormatVersion is the on-disk layout version. Version 2 records carry no page body. A store written under a different version is discarded, never converted.

Variables

ReadReasons is every reason Metrics.FileRead can be called with.

UnboundedReasons is every reason Metrics.ChangedPagesUnbounded can be called with.

Functions

func DefaultStorePath

func DefaultStorePath(app string) (string, error)

DefaultStorePath returns <user cache directory>/<app>/page-index.bolt. It is a pure path helper and creates nothing.

It has no context parameter by contract, so the single stdlib lookup's error is returned unwrapped.

func SetWarnf

func SetWarnf(idx PageIndex, warnf func(format string, args ...any))

SetWarnf redirects the index's warnings to warnf. It must be called before the index reads anything; a nil warnf or an index not built by this package is ignored.

Types

type DirectoryLister

type DirectoryLister interface {
	ListFiles(ctx context.Context, vaultPath string, pagesDir string) ([]FileEntry, error)
}

DirectoryLister lists one folder's page-file entries with their current fingerprints, in os.ReadDir order (filename ascending).

func NewDirectoryLister

func NewDirectoryLister() DirectoryLister

NewDirectoryLister returns the production directory lister.

type Entry

type Entry struct {
	Page          *domain.Page
	OpenQuestions []domain.OpenQuestion
}

Entry is one indexed page: the metadata-only page (Content always empty) plus its pre-parsed Open Questions. OpenQuestions is never nil, and every Text is a copy that shares no memory with the file body.

A published Entry and its Page are read-only for every consumer.

type FileEntry

type FileEntry struct {
	Name        string
	Fingerprint FileFingerprint
}

FileEntry is one directory entry with its current fingerprint.

type FileFingerprint

type FileFingerprint struct {
	Size             int64
	ModTime          time.Time
	StatusChangeTime time.Time
}

FileFingerprint is the pre-read stat of one page file. Size, ModTime and StatusChangeTime come from a single stat that follows symlinks.

type Key

type Key struct {
	VaultPath string
	PagesDir  string
}

Key identifies one indexed folder: a vault root plus a vault-relative pages dir.

func NewKey

func NewKey(vaultPath, pagesDir string) Key

NewKey builds a Key, applying filepath.Clean to both parts so the read side and the event side derive identical keys from equivalent paths.

type Metrics

type Metrics interface {
	// FileRead counts one single-file page read by reason.
	FileRead(reason string)
	// ChangedPagesUnbounded counts one refused changed-set bound by reason.
	ChangedPagesUnbounded(reason string)
}

Metrics receives the index's counters. A consumer adapts it to its own metrics stack; the package itself imports none.

func NewNoopMetrics

func NewNoopMetrics() Metrics

NewNoopMetrics returns a Metrics that records nothing.

type PageIndex

type PageIndex interface {
	storage.PageStorage
	// ListEntries returns the key's snapshot as entries: the same pages, in the
	// same order and with the same pointers as ListPages, each with its Open
	// Questions.
	ListEntries(ctx context.Context, vaultPath string, pagesDir string) ([]*Entry, error)
	// Build warms the given keys, discarding the pages.
	Build(ctx context.Context, keys []Key) error
	// Refresh re-reads the key's files whose size, modification time or
	// status-change time changed since they were last read, and blocks until a
	// listing that started after this call has been applied. It reads nothing
	// when nothing changed and publishes a new snapshot only when something
	// did. A key with no snapshot yet is built in full.
	Refresh(ctx context.Context, key Key) error
	// RefreshFile re-reads one file of the key's folder and publishes a new
	// snapshot with the result spliced in. It blocks until a snapshot
	// containing a read that started after this call has been published. The
	// file's current on-disk state decides the outcome, not the caller's reason
	// for calling: present and readable replaces or inserts the page at its
	// filename-ordered position, absent or unreadable removes it. The filename
	// is a single plain base name including ".md"; a filename that is empty,
	// contains a path separator, contains "..", or does not end in ".md" is
	// rejected with an error and nothing is read.
	RefreshFile(ctx context.Context, key Key, filename string) error
	// MarkDirty marks the named keys stale at folder level, so the next read of
	// each compares the folder's fingerprints and re-reads only what changed.
	MarkDirty(keys ...Key)
	// MarkFileDirty marks one file of the key stale so the next read re-reads it
	// before serving. The name is the item id; it is applied only when the
	// exactness rule holds, otherwise the whole key is marked folder-level.
	MarkFileDirty(key Key, name string)
	// ForceReload marks every known key so the next read of each re-reads every
	// file, whatever the fingerprints say. It is the only path that ignores
	// fingerprints.
	ForceReload()
	// Revision reports a per-key value that advances whenever the key's page
	// snapshot is published or marked stale. A derived snapshot reads it to
	// detect that its page input changed. An unknown key reports 0.
	Revision(key Key) uint64
	// ChangedPagesSince returns the names of the pages whose parsed form changed
	// in key's publications and marks after revision. Each name is a base
	// filename WITH its ".md" suffix, matching the page index's write-mark and
	// snapshot naming.
	//
	// ok is false when the key cannot bound the set. That is any of: an unknown
	// key; a revision ahead of the key's current one, which the key has never
	// reached; a revision so far behind that the retained change window no longer
	// covers it; a folder-level mark; a forced reload; or the key's first
	// publication, which publishes the whole snapshot whatever the build's kind.
	// A revision the key has advanced past while the advance is still retained is
	// the normal bounded case.
	ChangedPagesSince(key Key, revision uint64) (names []string, ok bool)
	// Rescan refreshes every known key once per RescanInterval until ctx is done.
	Rescan(ctx context.Context) error
}

PageIndex serves vault page lists from immutable in-memory snapshots that hold page metadata only. ListPages returns pages with empty Content; ReadPage always reads the full page from disk and never caches it.

func NewPageIndex

func NewPageIndex(
	reader PageReader,
	lister DirectoryLister,
	currentDateTimeGetter libtime.CurrentDateTimeGetter,
	waiter libtime.WaiterDuration,
	metrics Metrics,
) PageIndex

NewPageIndex creates an empty page index over the given reader and lister, with no store. A nil metrics records nothing.

func NewPageIndexWithStore

func NewPageIndexWithStore(
	reader PageReader,
	lister DirectoryLister,
	currentDateTimeGetter libtime.CurrentDateTimeGetter,
	waiter libtime.WaiterDuration,
	metrics Metrics,
	store Store,
) PageIndex

NewPageIndexWithStore creates an empty page index that hydrates each key from store before its first stat-diff and writes each publication through to it. A nil metrics records nothing; a nil store disables persistence.

type PageReader

type PageReader interface {
	// ReadEntry reads one page file and returns its metadata-only entry and
	// pre-read fingerprint. The filename is the file's base name including the
	// ".md" suffix. A non-nil error means the file is excluded (absent,
	// unreadable, unparsable, or a symlink out of the vault) and the returned
	// fingerprint is still the best available (zero when the stat failed).
	ReadEntry(
		ctx context.Context,
		vaultPath string,
		pagesDir string,
		filename string,
	) (*Entry, FileFingerprint, error)
	// ReadPage reads the full page, body included, by its bare base name
	// (without ".md"). The result is never cached.
	ReadPage(
		ctx context.Context,
		vaultPath string,
		pagesDir string,
		name string,
	) (*domain.Page, error)
}

PageReader reads page files from a folder.

func NewPageReader

func NewPageReader(pages storage.PageStorage) PageReader

NewPageReader returns the production reader over vault-cli's page storage.

type Store

type Store interface {
	// Load returns the key's stored entries. ok is false when there is nothing
	// usable to load for the key, which is the full-parse path. err is non-nil
	// only when ctx was cancelled.
	Load(ctx context.Context, key Key) (entries []StoredEntry, ok bool, err error)
	// Write applies one publication's delta for the key in a single
	// transaction: puts replaces or inserts entries keyed by Filename, deletes
	// removes them.
	Write(ctx context.Context, key Key, puts []StoredEntry, deletes []string) error
	// Path returns the store file path, for logging and warnings.
	Path() string
	// Close releases the store file.
	Close() error
}

Store persists the parsed page index on local disk. It is a cache: a Load that cannot supply entries never fails the caller, it reports them absent.

func NewBoltStore

func NewBoltStore(
	ctx context.Context,
	path string,
	identity WriterIdentity,
	warnf func(format string, args ...any),
	vlogf func(format string, args ...any),
) Store

NewBoltStore opens the embedded-Bolt store at path under the given writer identity. It never returns nil and never fails.

type StoredEntry

type StoredEntry struct {
	Filename    string
	Entry       *Entry
	Fingerprint FileFingerprint
}

storeDelta is one publication's change: the entries it re-read and the names it dropped. It is computed under the index mutex and written to the store after the build is released, so no reader waits on store I/O. StoredEntry is one indexed file's record: the metadata-only entry, or nil when the file was excluded, plus the pre-read fingerprint. It never holds a body.

type WriterIdentity

type WriterIdentity struct {
	StoreFormat   int
	ParserVersion string
}

WriterIdentity identifies the process that wrote the store: the store-format version plus the vault-cli parser version this process was built against.

func CurrentWriterIdentity

func CurrentWriterIdentity(ctx context.Context) WriterIdentity

CurrentWriterIdentity returns this process's writer identity.

Jump to

Keyboard shortcuts

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