shapebundle

package module
v0.0.0-...-050e57a Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 23 Imported by: 0 modules, 2 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

shapebundle

Go Reference Go

Fetches and loads traffic shaping bundles for zmux sessions: optional signature check, fetch and cache, load from a directory, and compose one or more bundles into the shaper factory, session budget, pool policy and handshake shaper zmux takes. Parsing and candidate selection are in zmux's shaping/bundle package.

go get github.com/djylb/shapebundle
f, _ := shapebundle.NewFetcher(shapebundle.FetcherConfig{URL: url, CacheDir: dir})
f.Load()
go f.Run(ctx)

p, _ := shapebundle.NewProfile(shapebundle.ProfileOptions{}, f.Current())
cfg.Shaper = p.Factory()

See the package documentation for details.

License

Apache-2.0

Documentation

Overview

Package shapebundle fetches and loads traffic shaping bundles for zmux sessions: it verifies their optional Ed25519 signatures, fetches them over HTTP into a local cache, loads them from a directory, and composes several of them into what zmux takes. Package github.com/zmuxio/zmux-go/shaping/bundle parses them.

Nothing here fetches on the path of a connection: a Profile and a Switch only read bundles already in memory, and a Fetcher fetches only when Refresh is called or while Run runs.

Index

Constants

View Source
const (
	DefaultCacheName = "bundle.json"
	DefaultTimeout   = 30 * time.Second
	DefaultRetryMin  = 30 * time.Second //nolint:revive // exported name; the Min/Max suffix pairs with the RetryMin and RetryMax fields
	DefaultRetryMax  = time.Hour
	DefaultMaxSkew   = time.Hour
)

Defaults of FetcherConfig fields left zero.

View Source
const SignatureHeader = "X-Bundle-Signature"

SignatureHeader is the response header that carries a bundle's signature: the Ed25519 signature of the raw response body, in hex.

Variables

View Source
var ErrFuture = errors.New("shapebundle: bundle from the future")

ErrFuture reports a bundle whose generated_at lies more than MaxSkew ahead of the clock; it is not taken.

View Source
var ErrNoBundle = errors.New("shapebundle: no bundle")

ErrNoBundle reports that a Fetcher has no bundle: none is cached and none was fetched.

View Source
var ErrOlder = errors.New("shapebundle: older bundle")

ErrOlder reports a fetched bundle generated before the current one; it is not taken.

View Source
var ErrSignature = errors.New("shapebundle: bad signature")

ErrSignature reports a missing or invalid signature.

Functions

func Bundles

func Bundles(d []DirBundle) []*bundle.Bundle

Bundles returns the bundles of d in order.

func ParseFile

func ParseFile(path string, o bundle.ParseOptions) (*bundle.Bundle, error)

ParseFile reads and parses the bundle at path.

func ParsePublicKey

func ParsePublicKey(s string) (ed25519.PublicKey, error)

ParsePublicKey decodes a hex Ed25519 public key.

func Verify

func Verify(pub ed25519.PublicKey, body []byte, sig string) error

Verify checks sig, the hex Ed25519 signature of body, against pub.

Types

type DirBundle

type DirBundle struct {
	Name   string // file name in the directory
	Bundle *bundle.Bundle
}

DirBundle is a bundle read by LoadDir.

func LoadDir

func LoadDir(dir string, o bundle.ParseOptions) ([]DirBundle, error)

LoadDir reads every bundle in dir: the regular files whose names end in ".json" and do not start with ".", in lexical order of their names. It fails on the first file that does not parse. Names starting with "." cover the temporary files a Fetcher leaves if it stops mid-write. A missing directory holds no bundles. The order is the caller's to use, for example as the layers of NewProfile.

type Fetcher

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

Fetcher fetches a bundle over HTTP and keeps it in a local cache. It is safe for concurrent use.

func NewFetcher

func NewFetcher(c FetcherConfig) (*Fetcher, error)

NewFetcher returns a Fetcher for c.

func (*Fetcher) Current

func (f *Fetcher) Current() *bundle.Bundle

Current returns the current bundle; nil before a Load or Refresh succeeds.

func (*Fetcher) Load

func (f *Fetcher) Load() (*bundle.Bundle, error)

Load reads the cached bundle and makes it current, under the same rules as Refresh: a cached bundle older than the current one (ErrOlder) or too far ahead of the clock (ErrFuture) is not taken, and the current one stays. The cache is trusted local state: its signature is not checked again, so a bundle cached under an earlier PublicKey still loads until the next Refresh replaces it. It fails with an error wrapping fs.ErrNotExist when nothing is cached, and with ErrNoBundle when there is no cache.

func (*Fetcher) Refresh

func (f *Fetcher) Refresh(ctx context.Context) (*bundle.Bundle, error)

Refresh fetches the bundle, verifies and validates it, writes it to the cache and makes it current. A bundle whose generated_at is before the current one's, or with none current before the cached one's, fails with ErrOlder; one more than MaxSkew ahead of the clock fails with ErrFuture. A future bundle is never taken, so it cannot block later ones; a cache from the future is ignored as a base and refused by Load, and is replaced by the next successful Refresh. On any failure the current and cached bundles stay as they were. The outcome is recorded in Status.

func (*Fetcher) Run

func (f *Fetcher) Run(ctx context.Context) error

Run fetches in the background until ctx ends, then returns ctx's error. It fetches at once when there is no current bundle, otherwise at the current bundle's next_change (at once if it has passed), or Interval after the last fetch when the bundle has none; each fetch is delayed by up to Jitter. A failed fetch keeps the current bundle and is retried with backoff. A Load or Refresh by the caller reschedules Run. Run starts no goroutine of its own besides the clock's timers, which it stops before it returns. Status reports when it fetches next.

func (*Fetcher) Status

func (f *Fetcher) Status() Status

Status returns a snapshot of f's fetches. It does not wait for a fetch in progress.

type FetcherConfig

type FetcherConfig struct {
	// URL is fetched with POST.
	URL string
	// Body is the JSON request body, passed on as it is; nil: empty.
	Body []byte
	// Token, if set, is sent as "Authorization: Bearer <Token>".
	Token string
	// PublicKey, if set, must verify the SignatureHeader of each response.
	// The cache holds only bundles that passed.
	PublicKey ed25519.PublicKey
	// CacheDir holds the cached bundle; "": no cache. It is created 0700
	// if missing.
	CacheDir string
	// CacheName is the cache file's name in CacheDir; "": DefaultCacheName.
	CacheName string
	// Client sends the requests; nil: a client that follows no redirect.
	Client *http.Client
	// Timeout bounds each fetch; 0: DefaultTimeout, negative: none
	// besides the caller's context.
	Timeout time.Duration
	// Parse bounds the bundles, response bodies included.
	Parse bundle.ParseOptions
	// Clock times Run; nil: the system clock.
	Clock timeshim.Clock
	// Jitter is the upper bound of a random delay Run adds to each
	// scheduled fetch, so that many fetchers do not fetch at once; 0:
	// none.
	Jitter time.Duration
	// Interval is the time Run waits after a fetch whose bundle has no
	// next_change; 0: Run fetches again only on a failure.
	Interval time.Duration
	// MinInterval is the least time Run leaves between the start of a
	// successful fetch and its next scheduled fetch, whatever next_change
	// says; 0: none. Retries of failed fetches are not bound by it.
	MinInterval time.Duration
	// MaxSkew is how far a bundle's generated_at may lie ahead of Clock's
	// now; a bundle further ahead is refused (ErrFuture), so that one
	// bundle with a wrong clock cannot make every later bundle older. 0:
	// DefaultMaxSkew; negative: no bound.
	MaxSkew time.Duration
	// RetryMin and RetryMax bound the delay before Run retries a failed
	// fetch, doubling from RetryMin to RetryMax with jitter; 0:
	// DefaultRetryMin, DefaultRetryMax. Run also waits RetryMin when a
	// fetched bundle's next_change has already passed.
	RetryMin, RetryMax time.Duration
	// OnUpdate, if set, is called with each bundle that Load or Refresh
	// makes current, in order, before they return. It must not call Load
	// or Refresh.
	OnUpdate func(*bundle.Bundle)
	// OnError, if set, is called with each failed fetch of Run.
	OnError func(error)
}

FetcherConfig configures a Fetcher. URL is required.

type Order

type Order uint8

Order is how a Profile resolves a carrier kind over several bundles, the first bundle given taking precedence.

const (
	// ByLayer takes each bundle as a whole: a kind resolves to the first
	// bundle that lists it or bundle.DefaultKind, and to that bundle's entry for
	// it, falling back to its bundle.DefaultKind entry.
	ByLayer Order = iota
	// ByKind prefers a listed kind over DefaultKind: a kind resolves to
	// the first bundle that lists it, otherwise to the first bundle.DefaultKind
	// entry.
	ByKind
)

type Profile

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

Profile is the entry of each carrier kind, resolved over one or more bundles, with the shapers of each entry made. It is immutable and safe for concurrent use.

func NewProfile

func NewProfile(o ProfileOptions, layers ...*bundle.Bundle) (*Profile, error)

NewProfile resolves every carrier kind over layers, the first taking precedence (nil layers are skipped), and compiles the candidate of each entry once, with a source of its own.

func (*Profile) Budget

func (p *Profile) Budget(k zmux.CarrierKind) func() shaping.Budget

Budget returns the budget function resolved for k (zmux.Config.ShapingBudget); nil when its entry has no budget.

func (*Profile) Entry

func (p *Profile) Entry(k zmux.CarrierKind) *bundle.Entry

Entry returns the entry resolved for k; nil if no bundle has one.

func (*Profile) Factory

func (p *Profile) Factory() zmux.ShaperFactory

Factory returns p.Shaper as a zmux.ShaperFactory, for zmux.Config.Shaper or SetShaper.

func (*Profile) Handshake

func (p *Profile) Handshake() shaping.HandshakeShaper

Handshake returns the handshake shaper of the Profile, for zmux.Config.HandshakeShaper and the seal configurations: it picks the entry by HandshakeView.Kind; an empty kind or one without an entry takes bundle.DefaultKind.

func (*Profile) PoolPolicy

func (p *Profile) PoolPolicy(k zmux.CarrierKind) zmux.PoolPolicy

PoolPolicy returns a new pool policy for k, nil when its entry has none (the pool's own logic). Each pool needs its own: a policy keeps per-member draws.

func (*Profile) SessionBudget

func (p *Profile) SessionBudget() func() shaping.Budget

SessionBudget returns the budget function of a session whose pipes may be of any kind, such as every session of one listener configuration or a multipath session mixing kinds: field by field the widest over the kinds that are shaped (whose entry has a definition), so that no kind is cut by another's budget. A shaped kind without a budget leaves it nil, as does no shaped kind; a shaped kind without an account or a bound on one wait leaves that part unset.

func (*Profile) Shaper

func (p *Profile) Shaper(sp zmux.ShapedPipe) shaping.Shaper

Shaper returns the Shaper of a pipe by its carrier kind; nil when the kind's entry has no definition.

type ProfileOptions

type ProfileOptions struct {
	// Order resolves kinds over the bundles.
	Order Order
	// NewSource is machine.Options.NewSource of every candidate.
	NewSource func() rand.Source
}

ProfileOptions configure a Profile. The zero value is valid.

type Status

type Status struct {
	// LastSuccess is when the last successful Refresh ended; zero: none.
	// Interval and MinInterval count from it.
	LastSuccess time.Time
	// LastErrorAt is when the last failed Refresh ended; zero: none since
	// the last success.
	LastErrorAt time.Time
	// LastError is the error of that Refresh; nil: none since the last
	// success. A Refresh whose ctx has ended by the time it returns is not
	// recorded; one that runs out of Timeout is.
	LastError error
	// Next is when Run fetches next, a retry or a refresh, jitter
	// included; zero: Run is not running or has no fetch scheduled. It
	// may lie in the past while that fetch is in progress, and Run sets
	// it anew after a Load or Refresh by the caller. With more than one
	// Run at a time it is that of whichever scheduled last.
	Next time.Time
}

Status is a snapshot of a Fetcher's fetches by Refresh and Run, for display. Load does not change it.

type StatusError

type StatusError struct{ Code int }

StatusError reports a fetch answered with a status other than 200.

func (*StatusError) Error

func (e *StatusError) Error() string

type Switch

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

Switch holds the current Profile, so that sessions and pools made once follow a Profile replaced later. Its zero value holds none. It is safe for concurrent use.

func (*Switch) Factory

func (s *Switch) Factory() zmux.ShaperFactory

Factory returns a zmux.ShaperFactory that shapes each pipe by the Profile current when the pipe's first record is made. A pipe keeps its Shaper when the Profile is replaced later: to move the pipes of an open session over, call its SetShaper again after Store (zmux then makes a new Shaper for each pipe at its next record), with the new Profile's budget; the session's account carries over.

func (*Switch) Load

func (s *Switch) Load() *Profile

Load returns the current Profile; nil if none.

func (*Switch) PoolPolicy

func (s *Switch) PoolPolicy(k zmux.CarrierKind) zmux.PoolPolicy

PoolPolicy returns a pool policy for k that decides by the policy of the current Profile, made anew for this pool when the Profile is replaced; with no Profile or no policy for k, it leaves the decision to the pool.

func (*Switch) Store

func (s *Switch) Store(p *Profile)

Store makes p the current Profile; nil: none.

Jump to

Keyboard shortcuts

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