litefs

package
v1.31.0 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: BSD-3-Clause Imports: 17 Imported by: 0

Documentation

Overview

Package litefs provides utilities for detecting the role of the current node in a LiteFS cluster (primary vs replica) and for reading the replication position of a database.

Index

Constants

View Source
const PrimaryFile = "/litefs/.primary"

PrimaryFile is the standard LiteFS lease file path. This file exists ONLY on replica nodes and contains the primary's hostname. Its ABSENCE means this node IS the primary.

The semantics are inverted from what the filename suggests:

  • .primary file EXISTS -> this node is a REPLICA (file contains the primary's address)
  • .primary file ABSENT -> this node IS the PRIMARY (we hold the lease)

See: https://fly.io/docs/litefs/primary/

Variables

This section is empty.

Functions

func IsPrimaryAt

func IsPrimaryAt(path string) bool

IsPrimaryAt reports whether this node is the LiteFS primary by checking the given path for the lease file. Returns true when the file does NOT exist (absence = primary), false when it does exist (presence = replica).

This is a low-level primitive with no fallback handling; it is exported so the package's external test can exercise the lease-file semantics against arbitrary paths. Production code calls IsPrimaryWithFallback, which adds the fail-safe-to-replica path for ambiguous stat errors and the no-LiteFS env-var fallback.

func IsPrimaryWithFallback

func IsPrimaryWithFallback(path string, envKey string) bool

IsPrimaryWithFallback detects primary status with a fallback for environments where LiteFS is not running (e.g., local development).

Detection order:

  1. If the primary file at path exists, this is a replica (return false).
  2. If stat fails with anything other than "does not exist" (e.g. a flaky LiteFS FUSE mount returning EIO/EACCES/ENOTDIR), fail SAFE toward replica (return false) and log a WARN. A misclassified replica that declines primary duties is harmless; a misclassified primary runs destructive Schema.Create DDL (WithDropColumn/WithDropIndex).
  3. If the file is genuinely absent and the parent directory of path exists (LiteFS is mounted), this is the primary (return true).
  4. If neither exists (no LiteFS), fall back to the environment variable identified by envKey parsed as a boolean. Defaults to true if the env var is unset, matching the common local-dev expectation (single node = primary).

func PosPath added in v1.28.3

func PosPath(dbPath string) string

PosPath returns the path of the LiteFS position file for the database at dbPath. LiteFS exposes one "<db>-pos" file next to each database in the FUSE mount.

func ReadPos added in v1.28.3

func ReadPos(path string) (string, error)

ReadPos returns the replication position of a LiteFS database, read from its "-pos" file at path. The position changes on every committed transaction that LiteFS applies to the database, on the primary and on each replica.

LiteFS v0.5 renders the file in fuse/pos_node.go as TXID and PostApplyChecksum separated by "/", each formatted %016x, with a trailing newline. ReadPos requires exactly that shape and returns it without the newline. Each call opens and reads the file again, because LiteFS generates the content on each read.

A missing file returns an error that matches fs.ErrNotExist.

func ValidateEnvFallback added in v1.23.0

func ValidateEnvFallback(envKey string) error

ValidateEnvFallback checks that the environment fallback variable, if set, parses as a boolean. Call once at startup so an operator typo in PDBPLUS_IS_PRIMARY fails fast with a clear message instead of being silently coerced into a role at every scheduler tick. Unset is valid (the documented "default primary" local-dev behaviour).

Types

type Metrics added in v1.29.0

type Metrics struct {
	// TXID is the current transaction ID of the database
	// (litefs_db_txid).
	TXID int64
	// Commits is the number of database commits on this node since
	// LiteFS started (litefs_db_commit_count). LiteFS creates the series
	// at the first commit, so it is 0 until then. A replica applies LTX
	// files and does not commit, so the value does not grow while the
	// node is a replica. A node that LiteFS demoted keeps its count.
	Commits int64
	// LTXBytes is litefs_db_ltx_bytes. Each retention pass (once a
	// minute by default) sets it to the size of the LTX files on disk.
	// A commit sets it to the size of the new LTX file, until the next
	// retention pass. LiteFS keeps each LTX file for its retention
	// period, so a large commit shows in both values.
	LTXBytes *int64
	// LTXFiles is the number of LTX files on disk (litefs_db_ltx_count).
	LTXFiles *int64
	// LTXLagSeconds is the time from the creation of the last LTX file
	// that this node applied to its apply (litefs_db_lag_seconds). A
	// commit on the primary sets it to 0.
	LTXLagSeconds *float64
	// LagSeconds is the time since this node last received a frame
	// (LTX file or heartbeat) from the primary (litefs_lag_seconds). It
	// is 0 on the primary.
	LagSeconds float64
	// Subscribers is the number of replicas connected to this node
	// (litefs_subscriber_count).
	Subscribers int64
}

Metrics holds the LiteFS values that the app exports, from one scrape of the LiteFS Prometheus endpoint (http.addr, :20202 by default). The db-labelled values are for one database.

LiteFS creates some db-labelled series only when it first sets them: at the first commit, LTX apply or retention pass after it starts. A pointer field is nil while its series is absent.

func ParseMetrics added in v1.29.0

func ParseMetrics(r io.Reader, db string) (Metrics, error)

ParseMetrics reads a Prometheus text exposition from r and returns the LiteFS values for the database named db (the base name of the database file, the value of the "db" label). It ignores lines it cannot parse and metrics it does not use. It returns an error when a metric in metricSamples that is not lazy has no sample, or when a sample value is not finite or a count is not an int64. A wrong URL, a wrong database name or a changed LiteFS exposition then gives an error, not zero values.

type MetricsScraper added in v1.29.0

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

MetricsScraper reads the LiteFS metrics endpoint for one database.

func NewMetricsScraper added in v1.29.0

func NewMetricsScraper(endpoint, db string, logger *slog.Logger) *MetricsScraper

NewMetricsScraper returns a scraper for the LiteFS metrics at endpoint (for example http://localhost:20202/metrics) and the database named db (the base name of the database file).

func (*MetricsScraper) Scrape added in v1.29.0

func (s *MetricsScraper) Scrape(ctx context.Context) (Metrics, error)

Scrape fetches and parses the LiteFS metrics. The first failure after a success (or at start) logs a WARN, later failures log at DEBUG, and the first success after a failure logs at INFO.

Jump to

Keyboard shortcuts

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