multipath

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT Imports: 15 Imported by: ? 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.

README

MultiPath — Go client

The same line management as ../ts, for connectors and CLIs: read the registry, rank the lines, race reads, replay a failed write over the next line under the same idempotency key.

No package registry is involved — Go does not need one. Consume it by repository path and tag:

go get github.com/micro-teams/multipath/go@v0.1.6

Use

client := multipath.New(multipath.Options{Registry: registry})

client.Probe(ctx, "/mt/probe")            // measure; nothing is measured until you ask
response, err := client.Get(ctx, "/mt/x") // hedged read
response, err := client.Write(ctx, http.MethodPost, "/mt/x", body, key) // one line, then failover

Or as a transport, for a consumer whose HTTP is already a stack of round trippers — which is how a connector integrates without any of its call sites learning that more than one line exists:

http.Client{Transport: authenticate(client.RoundTripper())}

And, for a process that stays up, a measurement loop rather than a single Probe:

go client.Prober(multipath.ProberOptions{ProbePath: "/mt/probe"}).Run(ctx)

Reads are hedged: the best line first, and only if it has not answered within HedgeAfter are the others asked. Writes are never raced — one line, and only a transport failure moves the write to the next, carrying the same idempotency key so the server recognises the second arrival as one attempt rather than two writes. An error status is an answer rather than something to route around; only silence leaves it unknown whether anything happened.

Status

Everything the design specifies for a connector is implemented: the registry, health table and ranking, the measurement loop with its backoff and its idle-gated throughput probe, hedged reads, write failover, stream line selection, and the http.RoundTripper adapter. Each is held to the same test cases as the TypeScript package — the connector and the browser have to mean the same thing by "a line", and a behaviour only one of them checks is one they will eventually disagree about.

The TypeScript package leads and this one follows, deliberately. The registry JSON is the shared contract — see ../ts/src/registry.ts.

Documentation

Overview

Package multipath manages redundant network paths to one origin: rank the lines, race reads, and replay a failed write over the next line under the same idempotency key.

The implementation is MP-3/MP-4 and follows the TypeScript package deliberately, so that the two cannot drift into two different meanings of "a line". The shared contract is the registry JSON.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoLine = errors.New("multipath: no line available to serve the request")

ErrNoLine is returned when the registry has nothing to send over.

Functions

func StreamURL

func StreamURL(line Line, path string) string

StreamURL upgrades a line's scheme: ws:// for http://, wss:// for https://. A same-origin line yields the bare path, leaving the scheme to whatever the caller is already using.

Types

type Client

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

Client sends requests over whichever line is currently best.

func New

func New(opts Options) *Client

New builds a client. Nothing is measured until Probe is called: a library that starts making network requests the moment it is constructed is one that surprises people.

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string) (*http.Response, error)

Get performs a hedged read.

The best line is asked first; if it has not answered within HedgeAfter the rest are asked too and the first response wins, the others being cancelled. On a healthy line that budget is never spent and no second request is ever sent — which is what makes hedging affordable, where always fanning out would multiply every request by the number of lines to buy an improvement that only exists on the slow tail.

func (*Client) Health

func (c *Client) Health() *HealthTable

Health exposes what has been measured, for a connector's own diagnostics.

func (*Client) Lines

func (c *Client) Lines() []Line

Lines returns the registry's lines in their configured order.

func (*Client) Probe

func (c *Client) Probe(ctx context.Context, probePath string)

Probe measures every line once and updates the ranking.

func (*Client) Prober

func (c *Client) Prober(opts ProberOptions) *Prober

Prober builds the measurement loop for this client, and wires it up to notice real traffic so the throughput probe can tell quiet from busy.

func (*Client) Ranked

func (c *Client) Ranked() []Line

Ranked returns the lines best-first.

func (*Client) RoundTripper

func (c *Client) RoundTripper() http.RoundTripper

RoundTripper returns the client as an http.RoundTripper: reads are hedged across lines, writes go to one line and fail over under a single idempotency key.

The transport it returns is safe for concurrent use and holds no per-request state.

func (*Client) SetRegistry

func (c *Client) SetRegistry(registry Registry)

SetRegistry swaps the lines at runtime, forgetting health for lines that have gone.

func (*Client) Write

func (c *Client) Write(
	ctx context.Context,
	method, path string,
	body []byte,
	idempotencyKey string,
) (*http.Response, error)

Write sends a non-idempotent request over one line, moving to the next only on a transport failure — never in parallel, and always under the same idempotency key so the server can recognise a second arrival as one attempt rather than two writes.

type HealthOptions

type HealthOptions struct {
	// Smoothing is the weight of each new sample, between 0 and 1.
	//
	// 0.3 keeps roughly the last handful of probes in view: quick enough to notice a line going
	// bad within seconds, slow enough that one unlucky sample does not reorder the ranking for
	// long. A ranking that flaps is worse than a slightly stale one, because every flap moves
	// traffic.
	Smoothing float64
	// FailuresBeforeDown is how many consecutive failures stop being noise and become a fact.
	FailuresBeforeDown int
	// DegradedFactor marks a line answering this many times slower than the best as degraded.
	DegradedFactor float64
}

HealthOptions tunes the table. Zero values take the defaults.

type HealthTable

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

HealthTable holds what is known about each line. Safe for concurrent use: the prober writes to it from its own goroutine while requests read it.

func NewHealthTable

func NewHealthTable(opts HealthOptions) *HealthTable

NewHealthTable builds a table, filling in any option left at its zero value.

func (*HealthTable) All

func (h *HealthTable) All() []LineHealth

All returns every line the table has heard of.

func (*HealthTable) Get

func (h *HealthTable) Get(lineID string) LineHealth

Get returns what is known about a line. A line nobody has measured is up, not down: optimism is the safe default, since a client with no measurements still has to send requests somewhere.

func (*HealthTable) Rank

func (h *HealthTable) Rank(lines []Line) []Line

Rank orders lines best-first.

Down lines go last rather than being dropped: if every line is down the caller still has to send the request somewhere. Among usable lines, measured latency decides, throughput breaks ties because two lines that answer equally fast are distinguished by how much they can carry, and configured weight decides only when nothing has been measured at all — a hand-set number goes stale, a measurement does not.

func (*HealthTable) ReconcileDegraded

func (h *HealthTable) ReconcileDegraded()

ReconcileDegraded labels lines answering far slower than the best. Purely a label, for diagnosis.

func (*HealthTable) RecordFailure

func (h *HealthTable) RecordFailure(lineID string, err error, at time.Time)

RecordFailure counts a failure, demoting the line only once the run is long enough to be a fact.

func (*HealthTable) RecordSuccess

func (h *HealthTable) RecordSuccess(lineID string, latency time.Duration, at time.Time)

RecordSuccess folds a round-trip time into the average and clears any failure run.

func (*HealthTable) RecordThroughput

func (h *HealthTable) RecordThroughput(lineID string, bytesPerSecond float64)

RecordThroughput folds a delivery rate into the average.

func (*HealthTable) Retain

func (h *HealthTable) Retain(lineIDs []string)

Retain forgets lines that have left the registry, so a re-added id cannot inherit the reputation of whatever used to be called that.

type Line

type Line struct {
	// Stable, human-readable identifier — "cf", "ipv6-1", "frp-2".
	ID string `json:"id"`
	// Absolute origin for this line, or "" meaning "same origin as the caller's default".
	URL string `json:"url"`
	// Free-form transport label, for diagnosis only.
	Transport string `json:"transport,omitempty"`
	// Static preference, higher is better. Only breaks ties between indistinguishable latencies;
	// measurement outranks it, because a hand-set weight goes stale and an EWMA does not.
	Weight int `json:"weight,omitempty"`
	// True when the browser or client does not see this line under our own domain — a free proxy
	// that cannot be CNAME'd, and therefore a fallback with reduced capability.
	ForeignOrigin bool `json:"foreignOrigin,omitempty"`
}

Line is one network path to the origin.

func (Line) Resolve

func (l Line) Resolve(path string) (string, error)

Resolve returns the URL for path over this line.

A same-origin line returns the path unchanged, so a single-line deployment issues exactly the requests it issued before MultiPath existed.

type LineHealth

type LineHealth struct {
	LineID string
	State  LineState
	// Latency is the smoothed round-trip time; zero with Measured false means nothing is known.
	Latency  time.Duration
	Measured bool
	// ThroughputBps is the smoothed delivery rate, zero when never measured.
	ThroughputBps       float64
	ConsecutiveFailures int
	LastError           string
	LastProbedAt        time.Time
}

LineHealth is everything measured about one line.

type LineState

type LineState string

LineState is how usable a line looks right now.

const (
	// StateUp means the line is answering.
	StateUp LineState = "up"
	// StateDegraded means it answers, but slowly or with recent errors: usable, ranked last.
	StateDegraded LineState = "degraded"
	// StateDown means it is not answering, and is skipped until a probe says otherwise.
	StateDown LineState = "down"
)

type Options

type Options struct {
	Registry Registry
	// HTTP is the transport actually used. Injected so tests need no network, and so a connector
	// can supply its own timeouts and proxy settings.
	HTTP *http.Client
	// HedgeAfter is how long the best line gets alone before the rest are asked, for reads.
	HedgeAfter time.Duration
	// WriteTimeout bounds one write attempt before the next line is tried.
	WriteTimeout time.Duration
	// MaxWriteAttempts caps how many lines a write may be sent to. A client that fails over
	// forever hammers a struggling origin from every direction at once.
	MaxWriteAttempts int
	Health           HealthOptions
	// IdempotencyHeader must match the server filter's.
	IdempotencyHeader string
	// BaseURL is what a same-origin line (url "") means to this client.
	//
	// The browser has an origin already; a connector does not, so the registry entry that reads
	// "same origin as the caller" has to be told what that is. Left empty, RoundTrip infers it from
	// the request it is given, which is what makes the transport drop-in.
	BaseURL string
	// Now is injected in tests.
	Now func() time.Time
}

Options configures a Client. Zero values take the defaults.

type Prober

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

Prober keeps a client's health table current.

Deliberately not started by New: probing costs real requests, and a library that begins making them the moment it is constructed is one that surprises people. The caller says when.

func (*Prober) NoteTraffic

func (p *Prober) NoteTraffic()

NoteTraffic records that the application just made a real request. Called by the client itself; exported because a consumer whose traffic does not go through this client (a WebSocket carrying the bulk of it, say) knows about activity this package cannot see.

func (*Prober) ProbeAll

func (p *Prober) ProbeAll(ctx context.Context)

ProbeAll measures every line now, ignoring backoff. The diagnostic lever, and every test's.

func (*Prober) Run

func (p *Prober) Run(ctx context.Context)

Run measures until ctx is cancelled, then returns.

Blocking rather than start/stop: a goroutine the caller owns is easier to reason about than one a library hid, and it makes the lifetime of the loop exactly the lifetime of a context that something else already manages.

type ProberOptions

type ProberOptions struct {
	// ProbePath is the unauthenticated liveness endpoint.
	ProbePath string
	// Interval is the gap between probes of a healthy line.
	Interval time.Duration
	// Timeout is when a probe that has not answered counts as a failure.
	Timeout time.Duration
	// MaxBackoff caps the wait for a line that keeps failing.
	MaxBackoff time.Duration

	// BandwidthPath is a download used to measure throughput. Empty disables throughput probing
	// entirely, which is the right default: it costs real bytes, and a consumer that has not
	// deployed such an endpoint should not be guessing at one.
	BandwidthPath string
	// BandwidthInterval is the minimum gap between throughput measurements of the same line.
	BandwidthInterval time.Duration
	// IdleBeforeBandwidth is how long the application must have been quiet before one may run.
	IdleBeforeBandwidth time.Duration

	// Now is injected in tests.
	Now func() time.Time
}

ProberOptions tunes the loop. Zero values take the defaults.

type Registry

type Registry struct {
	Lines []Line `json:"lines"`
}

Registry is the document served by GET /mt/lines.

func ParseRegistry

func ParseRegistry(data []byte) (Registry, error)

ParseRegistry validates an untrusted registry document and returns it.

It arrives over the network, so every assumption the client later makes is checked here — the only place the mistake is still cheap to read.

type Stream

type Stream[Conn any] struct {
	// contains filtered or unexported fields
}

Stream keeps a connection up, over whichever line can hold one.

func NewStream

func NewStream[Conn any](opts StreamOptions[Conn]) *Stream[Conn]

NewStream prepares a stream. Nothing is dialled until Run is called.

func (*Stream[Conn]) Current

func (s *Stream[Conn]) Current() *Line

Current reports which line is carrying the stream, or nil between attempts.

func (*Stream[Conn]) Penalties

func (s *Stream[Conn]) Penalties() map[string]time.Time

Penalties reports lines recently unable to hold a stream, and until when.

func (*Stream[Conn]) Run

func (s *Stream[Conn]) Run(ctx context.Context) error

Run keeps the stream connected until the context is cancelled.

Reconnection is not optional politeness: every line here is expected to be less reliable than one well-chosen line, and the whole bet is that several beat one. That only pays if breaking is routine and recovering is automatic.

func (*Stream[Conn]) Selector added in v0.1.3

func (s *Stream[Conn]) Selector() *StreamSelector

Selector exposes the policy, for a caller that wants to read it.

type StreamOptions

type StreamOptions[Conn any] struct {
	// Lines in preference order, read afresh before every attempt so a re-ranking takes effect.
	Lines func() []Line
	// Path is joined to each line's origin.
	Path string
	// Dial opens the connection. Bring your own library.
	Dial func(ctx context.Context, url string) (Conn, error)
	// Serve runs the conversation and returns when it ends. Its error, if any, is why.
	Serve func(ctx context.Context, conn Conn) error
	// StableAfter is how long a connection must last before it counts as working.
	//
	// Without it, a line that accepts the handshake and drops it immediately looks like a success
	// every time and the client reconnects in a tight loop forever.
	StableAfter time.Duration
	// RetryDelay is the first reconnect delay; it doubles per consecutive failure up to MaxDelay.
	RetryDelay time.Duration
	MaxDelay   time.Duration
	// Penalty is how long a line is skipped for streams after failing to hold one.
	Penalty time.Duration
	// OnOpen and OnClose are for diagnostics.
	OnOpen  func(Line)
	OnClose func(Line, error)
	Now     func() time.Time
}

StreamOptions configures a stream. Zero values take the defaults.

type StreamSelector added in v0.1.3

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

StreamSelector is the line policy on its own, for a consumer that already owns its reconnect loop.

Some do, and they are not doing anything wrong: a transport that has to speak a handshake, send heartbeats and decide what a drop means has a loop whose shape belongs to that protocol. What it still needs is this — which line to dial next, and somewhere to say how the last attempt went — and reimplementing it there would duplicate the judgement calls that are the whole content of this file: that a connection must last before it counts, that an ordinary disconnection is not the line's fault, and that a client with no connection is worse than one on a flaky line.

Stream is this plus a loop.

func NewStreamSelector added in v0.1.3

func NewStreamSelector(lines func() []Line, stableAfter, penalty time.Duration, now func() time.Time) *StreamSelector

NewStreamSelector builds the policy. Zero values take the same defaults as Stream.

func (*StreamSelector) Closed added in v0.1.3

func (s *StreamSelector) Closed(line Line, held time.Duration)

Closed records how an attempt ended, and is where a line earns a penalty.

held is how long the connection lasted — zero if it never opened. A connection that did not last is evidence about this line's ability to carry a stream, which is a different question from whether it answers requests quickly. One that lasted and then dropped is an ordinary disconnection and is not held against it, or every line would slowly be penalised for the network being a network.

func (*StreamSelector) Current added in v0.1.3

func (s *StreamSelector) Current() *Line

Current reports which line is carrying the stream, or nil between attempts.

func (*StreamSelector) Next added in v0.1.3

func (s *StreamSelector) Next() (Line, bool)

Next returns the line to dial, and false when there is nothing to dial yet.

func (*StreamSelector) Opened added in v0.1.3

func (s *StreamSelector) Opened(line Line)

Opened records that a connection to line is now up.

func (*StreamSelector) Penalties added in v0.1.3

func (s *StreamSelector) Penalties() map[string]time.Time

Penalties reports lines recently unable to hold a stream, and until when.

Jump to

Keyboard shortcuts

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