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
- Variables
- func Each(ctx context.Context, n, workers int, ...) error
- func Ordered[T any](ctx context.Context, n, workers int, ...) error
- func WithDeadline(conn Deadliner, d time.Duration, f func() error) error
- type Budget
- type Cache
- type Conn
- type Deadliner
- type FSLock
- type Gate
- type Order
- type Pool
- type Run
- type Slot
- type Span
Constants ¶
const DefaultBatch = 256 << 10
DefaultBatch is a reasonable bound for Conn.SetBatch: 256 KiB, eight 32 KiB SSH packets.
const DefaultGhostCap = 16384
DefaultGhostCap is how many evicted keys a Cache remembers (keys only).
const DefaultSeenCap = 16384
DefaultSeenCap is how many keys Cache.Seen remembers (keys only).
Variables ¶
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.
var ErrBadDeadline = errors.New("inflight: deadline must be positive")
ErrBadDeadline is returned by WithDeadline for a non-positive duration.
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.
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
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
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
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
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) Release ¶ added in v0.7.0
Release gives n bytes back. Releasing more than is held is a programming error and panics, rather than letting the accounting drift.
func (*Budget) TryAcquire ¶ added in v0.7.0
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]) 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
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.
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 ¶
Abandon gives back a slot from Conn.Begin whose request could not be read.
func (*Conn) Barrier ¶
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 ¶
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 ¶
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 ¶
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
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.
type Deadliner ¶ added in v0.7.0
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 ¶
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) 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 NewKeyGate ¶ added in v0.7.0
NewKeyGate makes a gate of max slots in all and at most perKey per key; both are raised to 1 when smaller.
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
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
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
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.
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 ¶
NewPool returns a pool that allows total requests in flight across all its connections. total must be at least 1.
type Run ¶
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 ¶
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 ¶
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 ¶
WriteRange is a request that writes n bytes of key from off.