tripwire

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: BSD-3-Clause Imports: 17 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 tripwire watches one or more directory trees for changes and delivers debounced, deduplicated batches of caller-defined keys.

A Watcher subscribes to every directory under each of Config.Roots (up to Config.MaxDepth levels below each root), attaches new directories as they appear, and maps each filesystem event to a key with Config.Key. Event.Root and Event.Rel say which root an event belongs to. All roots share one subscription and one debounce window: keys collect in a single set until every root goes quiet for Config.Debounce, or until Config.MaxDelay passes under constant churn. Then they are handed to Config.OnBatch in a single Batch.

The key type picks the batching behaviour:

  • Watcher[string] with PathOf reports which paths changed.
  • Watcher[struct{}] with Signal collapses any burst into one call.

When events may have been lost (inotify queue overflow, a lost subscription, or a root being removed, renamed, or restored), the next batch has Batch.Resync set and the consumer should do a full reconcile. Losing one root does not interrupt the others; it is retried with Config.Backoff until it comes back.

tripwire uses os.* rather than acfs on purpose: it watches arbitrary user-configured paths and, with Config.FollowSymlinks, follows symlinked directories whose targets may live outside any confinement root.

Index

Constants

View Source
const (
	// Filesystem operations an [Event] can carry.
	Create = fsnotify.Create
	Write  = fsnotify.Write
	Remove = fsnotify.Remove
	Rename = fsnotify.Rename
	Chmod  = fsnotify.Chmod
)

Variables

View Source
var (
	// ErrNoKey is returned by [New] when [Config.Key] is nil.
	ErrNoKey = errors.New("tripwire: Config.Key is required")
	// ErrNoRoot is returned by [New] when [Config.Roots] is empty or holds an
	// empty path.
	ErrNoRoot = errors.New("tripwire: Config.Roots needs at least one non-empty path")
	// ErrNestedRoots is returned by [New], wrapped with both paths, when one
	// root lies inside another. The check is lexical; symlinks are not
	// resolved.
	ErrNestedRoots = errors.New("tripwire: roots must not be nested")
	// ErrStopped is returned by [Watcher.Start] after Stop or a failed Start.
	ErrStopped = errors.New("tripwire: watcher stopped")
)

Functions

func PathOf

func PathOf(e Event) (string, bool)

PathOf is a Config.Key for Watcher[string] that keys every event by its real path.

func Signal

func Signal[K comparable](Event) (K, bool)

Signal is a Config.Key that maps every event to K's zero value, so a burst of changes becomes a single key. Use it as Key: tripwire.Signal on a Watcher[struct{}]; the type argument is inferred from the field.

Types

type Backoff

type Backoff struct {
	// Initial is the delay before the first retry. Zero means 5s.
	Initial time.Duration
	// Max caps the delay. Zero means 5m.
	Max time.Duration
}

Backoff is an exponential retry delay.

type Batch

type Batch[K comparable] struct {
	// Keys holds the distinct keys collected since the last batch, in no
	// particular order.
	Keys []K
	// Resync reports that events may have been lost, so the consumer should
	// reconcile everything instead of trusting Keys alone.
	Resync bool
}

Batch is one debounced delivery to Config.OnBatch.

type Config

type Config[K comparable] struct {
	// Key maps an event to a batch key. Returning false drops the event.
	// Key runs on the watcher goroutine for every event, so keep it cheap.
	Key func(Event) (K, bool)
	// OnBatch receives debounced batches. Calls are serial: a slow OnBatch
	// delays the next batch, and keys keep merging while it runs. A panic is
	// recovered and logged. Nil discards batches.
	OnBatch func(context.Context, Batch[K])
	// SkipDir reports whether a directory with this base name should not be
	// watched or descended into. Nil watches everything.
	SkipDir func(name string) bool
	// Logger receives warnings about directories that could not be watched
	// and about lost roots and subscriptions. Nil uses slog.Default().
	Logger *slog.Logger
	// Roots are the directory trees to watch. Each is cleaned with
	// filepath.Clean; duplicates (equal once made absolute) are dropped,
	// keeping the first spelling. Roots must not be nested inside one
	// another. Order matters only for symlinks: when links under two roots
	// point at the same directory, events there are reported under the
	// earlier root.
	Roots []string
	// Backoff controls how fast a lost root or subscription is retried.
	Backoff Backoff
	// Debounce is how long every root must be quiet before a batch is
	// delivered. Zero means 2s.
	Debounce time.Duration
	// MaxDelay caps how long a batch can be held back by continuous changes.
	// Zero means 10*Debounce. Values below Debounce are raised to Debounce.
	MaxDelay time.Duration
	// MaxDepth limits how many directory levels below each root are watched.
	// Direct children of a root are depth 1. Zero or negative is unlimited.
	MaxDepth int
	// FollowSymlinks watches symlinked directories (and their targets). A
	// link whose target is a root, lies inside one, or contains one is not
	// followed, since that root already reports those directories under
	// its own path.
	FollowSymlinks bool
}

Config configures a Watcher. Roots and Key are required.

type Event

type Event struct {
	// Path is the real path reported by the OS. Inside a followed symlinked
	// directory this is the path under the symlink target.
	Path string
	// Logical is Path as seen from its root, with followed symlinked
	// directories mapped back to the link's location.
	Logical string
	// Root is the cleaned entry of [Config.Roots] that Logical lies under.
	Root string
	// Rel is Logical relative to Root, using the OS path separator. It is
	// "." for the root itself.
	Rel string
	// Op is the set of operations in this event. Entries discovered inside a
	// newly created directory are reported as [Create].
	Op Op
}

Event is one filesystem change under one of the watched roots.

type Op

type Op = fsnotify.Op

Op is a bitmask of filesystem operations.

type Watcher

type Watcher[K comparable] struct {
	// contains filtered or unexported fields
}

Watcher watches one or more directory trees through a single subscription and delivers debounced batches of keys. Changes under any root share one debounce window, so a burst spanning several roots arrives as one Batch. Create one with New. A Watcher runs once: after Stop it cannot restart.

Roots are lost and restored independently. When a root is removed or renamed its watches are dropped, a Resync batch is requested straight away (its contents vanished without per-file events), and the other roots keep delivering. Lost roots are retried together on one Config.Backoff schedule, which restarts at Backoff.Initial whenever another root is lost. A root that comes back is walked again and a second Resync batch is requested.

func New

func New[K comparable](cfg Config[K]) (*Watcher[K], error)

New returns a watcher for cfg.Roots. It validates the config but does not touch the filesystem until Watcher.Start.

func (*Watcher[K]) Start

func (w *Watcher[K]) Start(ctx context.Context) error

Start subscribes to every root and begins delivering batches. When Start returns nil, every root and every existing directory within the depth limit under each root is watched. If any root cannot be subscribed, Start returns the joined errors naming each failed root, releases the subscription, and the watcher is spent; calling Stop afterwards is safe but not required. The watcher runs until Stop is called or ctx is done. Start is a no-op on a running watcher and returns ErrStopped after Stop.

func (*Watcher[K]) Stop

func (w *Watcher[K]) Stop() error

Stop shuts the watcher down and waits for an in-flight OnBatch to return. Changes not yet delivered are dropped. Stop is idempotent, safe to call concurrently, and safe to call before Start.

Jump to

Keyboard shortcuts

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