stream

package
v0.11.1 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 25 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 stream holds long-running inputs (a command's output or a tailed file) and fans their rows out to every connection that shows them.

A Hub owns one Buffer per input. Every row gets a hub-wide sequence number, and a merge buffer receives rows from its inputs under the same lock that assigns the number, so merged rows are always in seq order. Rows are immutable once published, so snapshots share them without copying.

Index

Constants

View Source
const (
	DefaultBufferSize = 2000
	DefaultBacklog    = 200
	MaxLineBytes      = 16 * 1024
	MaxLineMax        = 16 * 1024 * 1024 // the largest line_max

	// DefaultIdleStop is how long an input keeps running with no page
	// subscribed. Short tab closes keep history; an abandoned input (a page
	// closed for good, or a cmd edited under --watch) stops and frees its rows.
	DefaultIdleStop = 5 * time.Minute
)

Defaults for InputSpec fields left at their zero value.

View Source
const MaxCollected = 64 * 1024

MaxCollected caps the text a keyed row gathers in "collected"; the end is kept, since that is where a failure usually prints.

View Source
const MaxFolderFiles = 1000

MaxFolderFiles caps the files a folder source reads.

View Source
const MaxHTTPFill = 64 * 1024 * 1024

MaxHTTPFill caps the bytes one read of a .http file may fill in, across its variables and every request, so the values it keeps stay bounded.

View Source
const MaxReadFile = 4 * 1024 * 1024

MaxReadFile caps the bytes a file reader reads in one go: a file, or a folder's files together.

Variables

View Source
var Formats = []string{"auto", "json", "logfmt", "lines"}

Formats lists the accepted values of InputSpec.Format.

View Source
var ListRunTimeout = 30 * time.Second

ListRunTimeout stops a list input's run that hasn't exited, such as a command waiting on a lock, so the list goes on running and says why.

View Source
var WatchQuiet = 200 * time.Millisecond

WatchQuiet is how long a watch waits after the last file event before it reruns the hub's list inputs, so a burst, such as a commit writing dozens of files, starts one run.

Functions

func CompilePattern added in v0.11.0

func CompilePattern(p string) (*regexp.Regexp, error)

CompilePattern compiles a pattern: Go regex syntax (RE2, so it runs in linear time) with at least one named group, (?P<name>...).

func EntryID added in v0.10.0

func EntryID(source string, i int) string

EntryID names a row a file reader made: its source's name, "/", and its place from 1, so rows from two files differ and a click names one.

func FieldPath added in v0.6.0

func FieldPath(r Row, path string) interface{}

FieldPath reads a row field by path: NAME is a row field, and fields.NAME a field parsed from a JSON or logfmt line. It returns nil when absent.

func Fill added in v0.8.0

func Fill(s string, vars map[string]string) (string, error)

Fill replaces each {{name}} in s with vars[name], and each {{$processEnv NAME}} with the environment variable NAME, as the VS Code REST Client does. A plain {{name}} never reads the environment, so a file gets only the variables it asks for by name. A variable's value is filled too, so @token = {{$processEnv TOKEN}} works; an environment value is used as it is. Fill reports the first reference it couldn't fill.

Types

type Buffer

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

Buffer is a ring of the newest rows of one input or merge.

func (*Buffer) Err added in v0.8.0

func (b *Buffer) Err() string

Err returns the error b, or the first of a merge's inputs, reports in place of its rows, such as a file that doesn't parse; "" when there is none.

func (*Buffer) Running added in v0.8.0

func (b *Buffer) Running() bool

Running reports whether b's input, or any of a merge's inputs, is running its command or reading its file.

func (*Buffer) Snapshot

func (b *Buffer) Snapshot() []Row

Snapshot returns the buffered rows, oldest first. The slice and its rows are shared with other callers and must not be modified.

func (*Buffer) Subscribe

func (b *Buffer) Subscribe() *Subscription

Subscribe starts the input if it isn't running and returns a subscription whose channel holds at most one pending wake-up.

type HTTPRequest added in v0.8.0

type HTTPRequest struct {
	Name    string // from the ### line or # @name; "" when neither is set
	Method  string
	URL     string
	Headers string // one per line
	Body    string
}

HTTPRequest is one request in a .http file, as written.

func ParseHTTPFile added in v0.8.0

func ParseHTTPFile(text string) ([]HTTPRequest, map[string]string, error)

ParseHTTPFile reads the subset of the .http format the VS Code REST Client and JetBrains IDEs share: ### separates requests and may name the next one, # @name also names it, # and // start comments, @name = value defines a variable. A request is its request line, then headers up to the first blank line, then the body up to the next ###. It returns the requests and the variables, or the first line it can't read.

type Hub

type Hub struct {

	// IdleStop is how long an input runs after its last subscriber leaves.
	IdleStop time.Duration

	// WatchDir, when set before the first Subscribe, makes list inputs (see
	// InputSpec.Every) run again when a file under it changes, in place of
	// their timer.
	WatchDir string
	// contains filtered or unexported fields
}

Hub owns every Buffer of one server.

func NewHub

func NewHub() *Hub

NewHub returns an empty hub. Inputs start lazily on their first Subscribe.

func (*Hub) Close

func (h *Hub) Close() error

Close stops every input, kills their process groups and waits for them.

func (*Hub) Input

func (h *Hub) Input(spec InputSpec) (*Buffer, error)

Input returns the buffer for spec, creating it on first use. Two calls with equal specs share one buffer; any difference gets a buffer of its own.

func (*Hub) Merge

func (h *Hub) Merge(name string, inputs []*Buffer, size int, key KeySpec) (*Buffer, error)

Merge returns the buffer that interleaves inputs in seq order, creating it on first use and seeding it with the inputs' current rows. Subscribing to it starts every input. Inputs must be Input buffers, not other merges. A keyed merge (key.Paths set) keeps one row per key instead of every row.

func (*Hub) NewSubscription added in v0.7.0

func (h *Hub) NewSubscription() *Subscription

NewSubscription returns a subscription attached to no buffer. Attach adds buffers whose rows should wake it.

func (*Hub) Private added in v0.8.0

func (h *Hub) Private(r Row) (Private, bool)

Private returns what was published privately with r, by its seq. A keyed merge's copy of a row keeps the seq, so it finds the same values.

func (*Hub) RerunLists added in v0.11.0

func (h *Hub) RerunLists()

RerunLists starts the next run of every list input running now, without waiting for its timer or a file change, since a click's command may have changed what they print.

func (*Hub) Restart added in v0.8.0

func (h *Hub) Restart(b *Buffer)

Restart ends the runs of b's manual inputs (b's own, for an input), drops the rows they published, and starts each again. It is the only way a manual input starts, so a click runs its command exactly once.

type InputSpec

type InputSpec struct {
	Name string            `json:"name"` // source name, copied into each row's "source"
	Cmd  string            `json:"cmd"`  // run with /bin/sh -c
	Dir  string            `json:"dir"`  // working directory for Cmd
	Env  map[string]string `json:"env"`  // extra environment for Cmd
	File string            `json:"file"` // absolute path to tail
	HTTP string            `json:"http"` // absolute path of a .http file, re-read whole on change
	SQL  string            `json:"sql"`  // absolute path of a .sql file or a folder of them, re-read on change
	// Manual makes a Cmd start only when Restart is called, never when a page
	// attaches, and run once. A command that changes something (sends a
	// request) must not run again because a page reloaded.
	Manual bool `json:"manual"`
	// LineMax caps a line's length in bytes; 0 means MaxLineBytes.
	LineMax int    `json:"line_max"`
	Format  string `json:"format"`
	Buffer  int    `json:"buffer"`  // rows kept
	Backlog int    `json:"backlog"` // lines read from the end of File on start
	Restart string `json:"restart"` // on-exit or never
	// IdleStop, when set, replaces the hub's IdleStop for this input.
	IdleStop time.Duration `json:"idle_stop"`
	// Every makes a Cmd a list: each run's stdout replaces the rows the last
	// run printed, and the next run starts Every after it exits, or with the
	// hub's WatchDir when a file there changes. RerunLists starts it sooner.
	Every time.Duration `json:"every"`
	// Pattern, a regex with named groups, gives a line that matches it the
	// groups as its fields.
	Pattern string `json:"pattern"`
	// contains filtered or unexported fields
}

InputSpec describes one stream input. Exactly one of Cmd, File, HTTP or SQL is set.

func (InputSpec) Normalize

func (s InputSpec) Normalize() (InputSpec, error)

Normalize fills defaults and rejects invalid specs. Input calls it, and config validation can call it to report errors before serving.

type KeySpec added in v0.6.0

type KeySpec struct {
	Paths   []string
	Collect string
	// Reset starts a key's collected text over when a row matches, such as a
	// test's next run.
	Reset Match
	// Drop removes a key's row when a row matches, such as a removed
	// container. The matching row is not stored.
	Drop Match
	// Sort orders the rows by a field instead of first-seen order.
	Sort Order
}

KeySpec makes a merge keyed: one row per distinct value of Paths, updated in place. Collect names a field whose text is gathered across a key's rows.

type Match added in v0.7.0

type Match struct {
	Path   string
	Values []string
}

Match is a PATH=VALUE condition on a row, where VALUE may list alternatives as a|b. The zero Match matches nothing. It is deliberately smaller than the filter language tabs use: one field, exact string values.

func ParseMatch added in v0.7.0

func ParseMatch(s string) (Match, bool)

ParseMatch reads PATH=VALUE. It reports false when "=" is missing, PATH is empty, or an alternative is empty (a||b); the caller checks that Path is a field path. "|" can't be escaped.

func (Match) Matches added in v0.7.0

func (m Match) Matches(r Row) bool

Matches reports whether r's field at m.Path is one of m.Values. A number is compared as it prints, so 0 matches the value "0".

func (Match) String added in v0.7.0

func (m Match) String() string

type Order added in v0.7.2

type Order struct {
	Path string
	Desc bool
}

Order sorts a keyed merge's rows by the field at Path, descending with Desc; see compare for how values order.

func ParseOrder added in v0.7.2

func ParseOrder(s string) (Order, bool)

ParseOrder parses PATH, or -PATH for descending.

func (Order) String added in v0.7.2

func (o Order) String() string

type Private added in v0.8.0

type Private struct {
	Values map[string]string
	Err    string
}

Private is what an input published alongside a row without putting it in the row: Values, or Err saying why it has none.

type Row

type Row = map[string]interface{}

Row is one published log row. It must not be modified after publish.

type SQLQuery added in v0.10.0

type SQLQuery struct {
	Name string
	SQL  string // trimmed
	Line int    // the header's line number, or 1 for a file with no header
}

SQLQuery is one query in a .sql file, as written.

func ParseSQLFile added in v0.10.0

func ParseSQLFile(text, name string) []SQLQuery

ParseSQLFile reads the queries in a .sql file. A query starts at a header line and runs to the next one; text before the first header, and a header with no SQL under it, are skipped. A file with no header is one query, named name, as in the classic layout of one query per file. A name keeps no trailing operator characters (^ $ ! < * #), which aiosql and yesql use to say what a query returns.

type Subscription

type Subscription struct {
	C <-chan struct{}
	// contains filtered or unexported fields
}

Subscription delivers a wake-up on C whenever its buffer gains rows.

func (*Subscription) Attach added in v0.7.0

func (s *Subscription) Attach(b *Buffer)

Attach makes b's new rows wake s, and holds b, starting its input if it is stopped. Attaching a buffer twice, or after Close, does nothing.

func (*Subscription) Close

func (s *Subscription) Close()

Close stops wake-ups. The inputs keep running for other subscribers, and for their idle time after the last one leaves. Close is idempotent.

func (*Subscription) Detach added in v0.7.0

func (s *Subscription) Detach(b *Buffer)

Detach stops b waking s and releases it; the input stops after its idle time if nothing else holds it. Detaching a buffer not attached does nothing.

Jump to

Keyboard shortcuts

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