inflight

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: BSD-3-Clause Imports: 8 Imported by: 6 modules, 9 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.

README

inflight

Bounded, optionally ordered concurrent request dispatch shared by the go-filesystems NFS, SMB and SFTP servers. It carries no protocol knowledge.

pool, _ := inflight.NewPool(256)                       // server-wide cap
conn, _ := pool.NewConn(w, inflight.InOrder, 64)       // per connection
for {
    br.Peek(1)                                          // idle holds nothing
    sl, err := conn.Begin()                             // bounds taken BEFORE the read
    // read the request into sl.In
    conn.Go(sl, inflight.ReadRange(key, off, n), run)   // runs beside others
    // or conn.Barrier(sl, run)                         // runs alone
}
conn.Wait()
  • Bounds (Pool, Conn.Begin): a per-connection slot and a server-wide token are taken before a request is read; a peer that does not read replies keeps them, as with OpenSSH sftp-server, knfsd and Samba.
  • Reply order: InOrder (SFTP, whose OpenSSH client refuses to resume on reordered replies) or AnyOrder (ONC RPC xid, SMB2 MessageId).
  • Batching (Conn.SetBatch, InOrder only, off by default): replies ready together at the head of the queue leave in one Write of at most the given bytes (DefaultBatch = 256 KiB). Slots are released only after the write, so the pool's budget is unchanged; the one extra buffer is at most the bound.
  • Ordering: two requests on one key with overlapping ranges, a write among them, run in arrival order, across every connection of the pool.
  • Barriers: wait for everything in flight, run alone.
  • Ordered (inflight.Ordered(ctx, n, workers, work, emit)): the batch counterpart for n independent items known up front (blocks, slides, files): work runs on at most workers goroutines, emit receives the results in index order from the caller's goroutine, at most workers results exist at once whatever n is, the first error in index order stops the run, and no goroutine outlives the call. Memory is bounded by the workers, not by n. workers goroutines are started once and nothing is allocated per item.
  • Each (inflight.Each(ctx, n, workers, work)): Ordered without the hand-off, for items that write their own output. No result is emitted, so no worker waits for the caller or for an earlier item: one atomic increment per item. Measured on go-compressions/edonr's SumNParallel (16 cores), Ordered's per-item wake-ups cost 14 % of throughput; Each is at parity with a private pool. The lowest-index error stops the run.
  • Cache (inflight.NewCache[K, V](start, max, size)): the bounded block cache that goes with Ordered when blocks are decoded ahead of the reader. FIFO, bounded in bytes, and it grows (by a sixteenth, up to max) only when a key it evicted is asked for again: a sequential pass never grows it, a random read of a file larger than the cache does at once. An entry larger than the bound is not stored. Extracted from go-filesystems/squashfs v0.9.0 (#61); zfs uses it for decoded records. Cache.Seen(key) is admission on second touch: false the first time a key is passed (only the key is remembered, at most 16384 of them), true the second time, so a caller that Puts only when it is true caches what is read twice and spends nothing on a stream read once.
  • Server limits (limits.go), for the part of a network server that runs before any request is bounded:
    • Budget (NewBudget(total), Acquire(ctx, n), TryAcquire(n), Release(n)): a byte budget, a weighted semaphore served in arrival order. n > total returns ErrExceedsBudget instead of waiting forever; a cancelled wait holds nothing; releasing more than held panics.
    • Gate (NewGate(max), TryEnter, Leave; NewKeyGate(max, perKey), TryEnterKey(key), LeaveKey(key)): a cap on slots held at once, for example connections not yet authenticated, optionally per source address. Never blocks: the caller refuses the connection.
    • WithDeadline(conn, d, f): sets the connection's deadline, runs f (an SSH NewServerConn, a TLS handshake), and clears the deadline after.
  • FSLock: the go-filesystems/interface concurrency contract as a lock.

Extracted from go-filesystems/sftp v0.9.0. 100% statement coverage, race detector on, every public entry point fuzzed with its corpus committed.

Documentation

Overview

Package inflight answers several requests of one connection at once, within bounds, and knows nothing of the protocol it serves.

It was extracted from go-filesystems/sftp v0.9.0 (PRs #32 and #34) so that the NFS, SMB and SFTP servers share one implementation of the part that is easy to get subtly wrong: the bounds, the ordering and the barriers.

Shape

A server makes one Pool, which holds what is shared by every connection: the server-wide cap on requests in flight and the set of byte ranges being worked on. Each connection makes a Conn from it, saying where replies go and in which Order they leave.

The connection's reader loop is

for {
	wait until the next request begins (a Peek, or a blocking read of its
	first byte): an idle connection holds nothing
	sl, err := c.Begin()        // bounds taken here, before any read
	read the request into sl.In
	c.Go(sl, span, run)         // runs beside others; or
	c.Barrier(sl, run)          // runs alone
}
c.Wait()

For items known up front rather than requests that arrive, Ordered gives the same two properties, bounded and ordered, to any caller: it is the fleet's shared way to run independent work on several cores and keep the output in order. When the items write their own output and nothing needs emitting, use Each: the same bound on goroutines without Ordered's per-item hand-off.

Bounds

Conn.Begin takes one of the connection's slots and then one token of the pool's budget, and blocks while either is unavailable. It is called before the request is read, so at a bound the reader stops reading and the peer waits in the transport's window: nothing has been allocated for a request that is refused. A slot and its token are given back when the request's reply has been written, so a peer that does not read its replies keeps its requests counted. That is the same property as OpenSSH's sftp-server, which stops reading input while its output queue cannot take a maximum-size message (sftp-server.c process_requests, lines 2064-2066 and 2121), and as knfsd's threads and Samba's aio threads, which a stalled peer also holds until the connection is closed.

Ordering

Requests are decoded one at a time by the reader, so a connection's requests are always STARTED in arrival order. Conn.Go then lets a request overlap others, except that two requests on the same key whose ranges overlap, with a write among them, run in arrival order (across every connection of the pool). Conn.Barrier waits until every earlier request is answered, runs alone and only then returns, so the reader does not look at the next one before it.

Replies leave in the order the requests arrived (InOrder: SFTP, whose OpenSSH client refuses to resume a transfer whose replies came back reordered) or in the order they finish (AnyOrder: ONC RPC matches a reply to its call by xid, SMB2 by MessageId).

Index

Constants

View Source
const DefaultBatch = 256 << 10

DefaultBatch is a reasonable bound for Conn.SetBatch: 256 KiB, eight 32 KiB SSH packets.

View Source
const DefaultGhostCap = 16384

DefaultGhostCap is how many evicted keys a Cache remembers (keys only).

View Source
const DefaultSeenCap = 16384

DefaultSeenCap is how many keys Cache.Seen remembers (keys only).

Variables

View Source
var (
	ErrLimit  = errors.New("inflight: a limit must be at least 1")
	ErrOrder  = errors.New("inflight: reply order must be InOrder or AnyOrder")
	ErrWriter = errors.New("inflight: nil reply writer")
)

Errors returned by NewPool and Pool.NewConn. A limit below one would make every request wait for ever, and a missing writer or an unnamed order would fail at the first reply; each is refused where it is made.

View Source
var ErrBadDeadline = errors.New("inflight: deadline must be positive")

ErrBadDeadline is returned by WithDeadline for a non-positive duration.

View Source
var ErrBounds = errors.New("inflight: Ordered needs n >= 0 and workers >= 1")

ErrBounds is returned by Ordered when n is negative or workers is below 1: a bound of zero would wait forever and a negative count has no meaning.

View Source
var ErrExceedsBudget = errors.New("inflight: request exceeds the whole budget")

ErrExceedsBudget is returned by Budget.Acquire and Budget.TryAcquire callers that ask for more than the whole budget: such a request could never be satisfied, so it is refused instead of waiting forever.

Functions

func Each added in v0.4.0

func Each(ctx context.Context, n, workers int, work func(ctx context.Context, i int) error) error

Each runs work(ctx, 0), …, work(ctx, n-1) on at most workers goroutines at once and returns when all have returned, or once the run has stopped on an error.

It is Ordered without the hand-off: for items that write their own output (a slot of a slice, a file), nothing is emitted, so no worker waits for the caller or for an earlier item, and there is no per-item synchronisation but one atomic increment. That is the difference between a bound on goroutines and a bound on results: Ordered pays one wake-up per item to keep results in order and bounded, Each pays none.

Errors

Items start in index order, so when item j fails every item below j has already started, and the error returned is the lowest-index one among the items that failed. That is the same on every run only when work does not itself fail on a cancelled context: such an item may return the run's own stop, which is ignored (below). The context given to work is then cancelled and no further item starts; an item that fails with context.Canceled after that cancellation is the run's own stop, not a failure, and is ignored. If ctx is done first, Each returns ctx's error. No goroutine outlives the call. n < 0 or workers < 1 returns ErrBounds.

func Ordered added in v0.3.0

func Ordered[T any](ctx context.Context, n, workers int, work func(ctx context.Context, i int) (T, error), emit func(i int, v T) error) error

Ordered runs work(ctx, 0), …, work(ctx, n-1) on at most workers goroutines at once and hands each result to emit in index order, from the calling goroutine, so a caller that writes what emit receives writes it in the same order whatever the workers' speeds.

It is the batch counterpart of Conn: the same two properties, bounded and ordered, for n independent items known up front (the blocks of a file, the slides of a deck, the files of a build) instead of requests arriving on a connection.

Bounds

A token is taken before item i starts and given back once emit has returned for it, so at most workers results exist at any time, being computed or waiting for their turn behind a slower earlier item. Memory is therefore bounded by workers results, not by n, and so is the bookkeeping: nothing is allocated per item beyond the item's own result. No goroutine outlives the call, whichever way it returns.

Errors

The first error in INDEX order, from work or from emit, stops the run and is returned: the context given to work is cancelled, no item after it starts, and Ordered returns once the items already running have returned. An error is thus the same on every run, not whichever worker failed first. A work whose items must not stop one another returns its failure inside T and nil. If ctx is done first, Ordered returns ctx's error. emit is never called concurrently and never after Ordered has returned.

func WithDeadline added in v0.7.0

func WithDeadline(conn Deadliner, d time.Duration, f func() error) error

WithDeadline sets conn's read and write deadline to d from now, runs f, and clears the deadline afterwards, so a handshake (for example ssh.NewServerConn) cannot be held open by a silent peer yet the established connection has no deadline left behind. It returns f's error, or the error of clearing the deadline when f succeeded. d must be positive.

Types

type Budget added in v0.7.0

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

Budget is a weighted semaphore over bytes: a server-wide cap on memory that requests hold while they are being served. Waiters are served in arrival order, so a large request is not starved by a stream of small ones.

func NewBudget added in v0.7.0

func NewBudget(total int64) *Budget

NewBudget makes a budget of total bytes. total must be positive; a non-positive total is raised to 1 so that the zero value is never usable by accident.

func (*Budget) Acquire added in v0.7.0

func (b *Budget) Acquire(ctx context.Context, n int64) error

Acquire takes n bytes, blocking until they are available or ctx is done. It returns ErrExceedsBudget when n is larger than the whole budget, a negative n as an error too, and ctx's error when the wait is abandoned; in every error case nothing is held.

func (*Budget) InUse added in v0.7.0

func (b *Budget) InUse() int64

InUse returns the bytes currently held.

func (*Budget) Release added in v0.7.0

func (b *Budget) Release(n int64)

Release gives n bytes back. Releasing more than is held is a programming error and panics, rather than letting the accounting drift.

func (*Budget) Total added in v0.7.0

func (b *Budget) Total() int64

Total returns the size of the budget.

func (*Budget) TryAcquire added in v0.7.0

func (b *Budget) TryAcquire(n int64) bool

TryAcquire takes n bytes if they are available now and nobody is waiting ahead, and reports whether it did. It never blocks; n out of range is false.

type Cache added in v0.5.0

type Cache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Cache is a bounded FIFO cache of decoded blocks that grows when it is too small and not otherwise. It was extracted from go-filesystems/squashfs v0.9.0 (its PR 61), where it holds decompressed data blocks, so that the read-only filesystems that decode blocks in parallel (see Ordered) share one implementation of the part that is easy to get subtly wrong: the bound, and the rule for when to exceed it.

The bound is in bytes, as reported by the size function given to NewCache, called once per Put and never under the cache's lock. It starts at the start argument (at least 1) and grows, by a sixteenth at a time (at least one entry), only when a key that was evicted is asked for again: a random read of a file larger than the cache does at once; one sequential pass never does, a second pass over a file larger than the cache does. It never passes max. A value larger than the current bound is not stored, so one huge value cannot empty the cache or exceed max; putting such a value under a key that is cached removes the old one.

The values are shared, not copied: callers must not modify what Get returns or what they Put. A Cache is safe for concurrent use. The zero value is not usable; a nil *Cache reports a miss and stores nothing, which is how a caller turns the cache off.

func NewCache added in v0.5.0

func NewCache[K comparable, V any](start, max int64, size func(V) int64) *Cache[K, V]

NewCache returns a Cache that starts at start bytes (at least 1) and may grow to max (at least start). size reports the cost of a value in bytes (a negative result counts as 0); it must not touch the cache.

func (*Cache[K, V]) Cap added in v0.5.0

func (c *Cache[K, V]) Cap() int64

Cap is the current bound in bytes.

func (*Cache[K, V]) Get added in v0.5.0

func (c *Cache[K, V]) Get(k K) (V, bool)

Get returns the cached value of k.

func (*Cache[K, V]) Len added in v0.5.0

func (c *Cache[K, V]) Len() int

Len is the number of entries held.

func (*Cache[K, V]) Put added in v0.5.0

func (c *Cache[K, V]) Put(k K, v V)

Put stores v under k as the newest entry, evicting the oldest while the cache is over its bound. A value already cached under k is dropped first.

func (*Cache[K, V]) Seen added in v0.6.0

func (c *Cache[K, V]) Seen(k K) bool

Seen is admission on second touch. It reports whether k was passed to Seen before (and not since forgotten), and remembers it if not: the first call for a key returns false, the next returns true and forgets the key, so a caller that Puts only when Seen is true caches what is read twice and never what is read once. A stream read once, however long, then costs no cache memory and no copy. Only keys are kept, at most DefaultSeenCap of them, the oldest forgotten first; a nil *Cache reports false and remembers nothing.

It is independent of the entries and of the keys of evicted entries that grow the bound: Seen neither reads nor changes them.

func (*Cache[K, V]) SetMax added in v0.5.0

func (c *Cache[K, V]) SetMax(max int64)

SetMax sets the most bytes the cache may grow to, never below its starting size. A cache already above it shrinks to it at once.

type Conn

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

Conn is the in-flight state of one connection. Make it with Pool.NewConn.

Begin, Go, Barrier, Abandon and Wait are called by ONE goroutine, the connection's reader.

func (*Conn) Abandon

func (c *Conn) Abandon(sl *Slot)

Abandon gives back a slot from Conn.Begin whose request could not be read.

func (*Conn) Barrier

func (c *Conn) Barrier(sl *Slot, run Run)

Barrier waits until every request before it has been answered, runs this one alone, and returns once it has run (its reply is written by the time the next Barrier or Wait returns).

func (*Conn) Begin

func (c *Conn) Begin() (*Slot, error)

Begin takes a slot of this connection and then a token of the pool, blocking while either is unavailable, and returns the slot to read the request into. Call it BEFORE reading the request: that is what makes a bound a bound (see the package documentation). If the connection has failed it returns the error instead, holding nothing.

Call it only once the next request has begun to arrive (a Peek of one byte is enough): an idle connection must hold nothing of the pool's budget.

func (*Conn) Err

func (c *Conn) Err() error

Err is why the connection can go no further, or nil: the first write error, or the first error a Run returned.

func (*Conn) Go

func (c *Conn) Go(sl *Slot, sp Span, run Run)

Go runs the request on a goroutine of its own, beside the others in flight, and returns as soon as the request may start: it blocks only while another request, of any connection of the pool, holds a conflicting span (see Span). With max 1 it runs on the caller's goroutine instead.

func (*Conn) SetBatch added in v0.2.0

func (c *Conn) SetBatch(max int)

SetBatch makes an InOrder connection coalesce replies: the replies that are ready together at the head of the queue leave in ONE Write of at most max bytes (a single reply larger than max still leaves alone, uncopied). A stream whose Write has a fixed cost (a syscall, an encrypted packet) pays it once per batch instead of once per reply. The default, 0, is one Write per reply.

Memory: the replies of a batch are still held by their slots, and a slot is released only after its reply is written, so the pool's budget is unchanged; the connection adds one buffer of at most max bytes, made when the first batch of several replies needs it.

Call it before the first Begin.

func (*Conn) Wait

func (c *Conn) Wait()

Wait blocks until every request handed to Go or Barrier has been answered (or has failed on a dead stream). Call it when the reader loop ends, before freeing anything a request might still use.

type Deadliner added in v0.7.0

type Deadliner interface {
	SetDeadline(t time.Time) error
}

Deadliner is what WithDeadline needs of a connection; every net.Conn is one. It is declared here, rather than taking a net.Conn, so that this package does not import net (govulncheck's SSA build of net panics on CI, and a package of bounds has no other use for it).

type FSLock

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

FSLock is the driver contract made executable, for a server whose backing store is a go-filesystems/interface Filesystem.

That module documents exactly two things as safe for concurrent use: File.ReadAt, and WritableFile.WriteAt on non-overlapping ranges (interface v0.5.0). It documents nothing about concurrent path-based calls, Truncate or Sync. So:

  • File.ReadAt and WritableFile.WriteAt hold the lock SHARED (LockIO): any number run together; keeping their ranges apart is Conn.Go's job.
  • Every other driver call holds it EXCLUSIVELY (Lock), and so never overlaps any File I/O or any other call.
  • Read-only path calls (Stat, ListDir, ReadFile, ReadLink) hold it shared too (LockPath), but only if the embedder asserted, with NewFSLock(true), that the driver allows it: right for a host directory, wrong for a driver with a shared cursor or cache.

func NewFSLock

func NewFSLock(pathOpsConcurrent bool) *FSLock

NewFSLock returns the lock; pathOpsConcurrent is the embedder's assertion that read-only path calls may run beside each other and beside File I/O.

func (*FSLock) Lock

func (l *FSLock) Lock()

Lock and Unlock bracket every driver call that is not File I/O or a read-only path call.

func (*FSLock) LockIO

func (l *FSLock) LockIO()

LockIO and UnlockIO bracket File.ReadAt and WritableFile.WriteAt.

func (*FSLock) LockPath

func (l *FSLock) LockPath()

LockPath and UnlockPath bracket a read-only path call: shared if the embedder asserted it, exclusive otherwise.

func (*FSLock) Unlock

func (l *FSLock) Unlock()

func (*FSLock) UnlockIO

func (l *FSLock) UnlockIO()

func (*FSLock) UnlockPath

func (l *FSLock) UnlockPath()

type Gate added in v0.7.0

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

Gate caps the number of slots held at once, for example connections that have not authenticated yet. It never blocks: a caller that cannot enter refuses the connection. A Gate made with NewKeyGate also caps the slots held per key (a source address).

func NewGate added in v0.7.0

func NewGate(slots int) *Gate

NewGate makes a gate of max slots; max below 1 is raised to 1.

func NewKeyGate added in v0.7.0

func NewKeyGate(slots, perKey int) *Gate

NewKeyGate makes a gate of max slots in all and at most perKey per key; both are raised to 1 when smaller.

func (*Gate) Held added in v0.7.0

func (g *Gate) Held() int

Held returns the slots currently held.

func (*Gate) Leave added in v0.7.0

func (g *Gate) Leave()

Leave gives a slot taken by TryEnter back. Leaving a gate that holds nothing panics.

func (*Gate) LeaveKey added in v0.7.0

func (g *Gate) LeaveKey(key string)

LeaveKey gives back a slot taken by TryEnterKey. The key's entry is removed at zero, so the map is bounded by the slots held, not by the keys seen.

func (*Gate) TryEnter added in v0.7.0

func (g *Gate) TryEnter() bool

TryEnter takes a slot if one is free and reports whether it did. Pair every true with one Gate.Leave.

func (*Gate) TryEnterKey added in v0.7.0

func (g *Gate) TryEnterKey(key string) bool

TryEnterKey takes a slot for key if both the gate and the key have room. On a gate made by NewGate there is no per-key cap and only the total applies. Pair every true with one Gate.LeaveKey of the same key.

type Order

type Order uint8

Order is the order in which a connection's replies leave. The zero value is not an order, so a connection cannot be made without choosing one.

const (
	// InOrder writes replies in the order the requests arrived, whatever order
	// the work finishes in. Work is concurrent, replies are sequential.
	InOrder Order = iota + 1
	// AnyOrder writes each reply as soon as it is ready.
	AnyOrder
)

type Pool

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

Pool is what every connection of one server shares: the cap on requests in flight across all of them, and the byte ranges being worked on, which is what makes two connections writing one file order exactly as two requests of one connection do.

A Pool is safe for concurrent use. Make one per server with NewPool.

func NewPool

func NewPool(total int) (*Pool, error)

NewPool returns a pool that allows total requests in flight across all its connections. total must be at least 1.

func (*Pool) NewConn

func (p *Pool) NewConn(w io.Writer, order Order, max int) (*Conn, error)

NewConn returns a connection that writes its replies to w in the given order and has at most max requests in flight, within the pool's budget. max must be at least 1; 1 is the sequential connection. w is never closed.

type Run

type Run func(*Slot) ([]byte, error)

Run is the work of one request. It returns the reply, framed and ready to write (it may alias the slot's buffers), or nil for a request that has none. A non-nil error ends the connection: the reply is not written and nothing after it is, the way a failed Write does.

type Slot

type Slot struct {
	In, Out, Data []byte
	// contains filtered or unexported fields
}

Slot is one request's working memory. A connection owns at most Max of them, made on demand and reused for its life, so steady-state traffic allocates nothing per request. The three buffers are the caller's to use as it likes (the request as read, the reply as framed, a scratch buffer); the package never looks inside them.

A Slot belongs to the caller from Conn.Begin until it is handed to Conn.Go, Conn.Barrier or Conn.Abandon, and to the Conn after that.

type Span

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

Span is the part of a file a request touches: a key naming the file (a path, a file handle: the caller decides what identifies "the same file" across handles), a half-open byte range, and whether the request writes it. Make one with ReadRange, WriteRange or WriteAll; the zero Span is the empty range of the empty key, which conflicts with nothing.

func ReadRange

func ReadRange(key string, off, n uint64) Span

ReadRange is a request that reads n bytes of key from off. The end saturates, so an offset straight off the wire cannot wrap.

func WriteAll

func WriteAll(key string) Span

WriteAll is a request that may rewrite the whole of key (a driver without positional writes): it orders against every other request on the key.

func WriteRange

func WriteRange(key string, off, n uint64) Span

WriteRange is a request that writes n bytes of key from off.

Jump to

Keyboard shortcuts

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