Documentation
¶
Overview ¶
Package meshclient is the HTTP client for calls to sibling fleet services on the private mesh: a base URL, a timeout, a bounded and strictly decoded JSON body, and one explicit answer to the question every such call has to settle: if the sibling is down, does the caller go on without it, or stop?
ledger, err := meshclient.New(meshclient.Config{
Name: "ledger",
BaseURL: os.Getenv("LEDGER_SERVICE_URL"),
Mode: meshclient.FailOpen, // or FailClosed: there is no default
})
var out struct{ Balance int64 `json:"balance"` }
err = ledger.Do(ctx, meshclient.Request{Path: "/v1/balance"}, &out)
if meshclient.IsUnavailable(err) {
// carry on without it; "ledger-down" is already in the request's degraded list
}
Why not safehttp ¶
safehttp is for the public internet and refuses private addresses by design, so a mesh call through it fails at once with ErrBlocked. Every service that needed a sibling therefore wrote its own net/http client, with its own timeout, body cap, decoding and failure handling. This is that client, written once.
Failing open or closed ¶
Mode is required. When the sibling is unavailable (the connection fails or times out, it answers 5xx or 429, its reply is unreadable, or the resilience policy refuses the call), Do returns an *UnavailableError, which satisfies errors.Is(err, ErrUnavailable). In FailOpen mode it also appends "<name>-down" (or -timeout, -rate_limited, -degraded) to the degraded.Sink in the context, so the response envelope tells the caller's client what is missing. In FailClosed mode it does not: the request is going to fail, there is nothing partial to report. A 4xx answer is never "unavailable": it is a *StatusError, the sibling's reply to a request that was wrong.
Never use FailOpen for a check that protects something (credentials, charging, authorisation): carrying on without the answer would be the bypass.
What it does not do ¶
No redirects are followed. The request body is JSON. For retries, circuit breaking and load shedding pass a resilience.Policy in Config.
Index ¶
Examples ¶
Constants ¶
const ( DefaultTimeout = 3 * time.Second DefaultMaxBodyBytes = 1 << 20 DefaultUserAgent = "go-common/meshclient" )
Defaults.
Variables ¶
ErrUnavailable is what errors.Is matches for every failure that means the sibling is not usable right now. See UnavailableError.
Functions ¶
func IsUnavailable ¶
IsUnavailable reports whether err means the sibling is not usable right now.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client talks to one sibling service. It is safe for concurrent use.
func (*Client) Do ¶
Do makes the request and, on a 2xx answer, decodes the JSON body into out (nil to ignore it). See the package comment for how failures are reported.
Example (FailOpen) ¶
A fail-open client: when the sibling is down the caller carries on without its answer, and the request's degraded list says what is missing.
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/baditaflorin/go-common/degraded"
"github.com/baditaflorin/go-common/meshclient"
)
func main() {
sibling := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable)
}))
defer sibling.Close()
enrich, _ := meshclient.New(meshclient.Config{Name: "geo", BaseURL: sibling.URL, Mode: meshclient.FailOpen, Timeout: time.Second})
sink := degraded.New() // one per request; its Slice() goes in the response envelope
ctx := degraded.NewContext(context.Background(), sink)
var out struct {
Country string `json:"country"`
}
err := enrich.Get(ctx, "/v1/lookup", &out)
if meshclient.IsUnavailable(err) {
fmt.Println("carrying on without geo")
}
fmt.Println("degraded:", sink.Slice())
}
Output: carrying on without geo degraded: [geo-down]
type Config ¶
type Config struct {
// Name is the sibling's slug ("ledger"). It labels errors and becomes the
// prefix of degraded tokens ("ledger-down"), so it is lower case with digits,
// '-' and '_' only.
Name string
// BaseURL is the sibling's address, http or https, without credentials, query
// or fragment.
BaseURL string
// Mode is required: FailOpen or FailClosed.
Mode Mode
// Timeout bounds each attempt. Default DefaultTimeout.
Timeout time.Duration
// MaxBodyBytes caps how much of a reply is read. Default DefaultMaxBodyBytes.
MaxBodyBytes int64
// UserAgent defaults to DefaultUserAgent.
UserAgent string
// RejectUnknownFields makes decoding fail on a JSON field that out does not
// have. Off by default so a sibling can add fields without breaking callers.
RejectUnknownFields bool
// Policy adds retries (with a budget), a circuit breaker and load shedding.
// Nil makes exactly one attempt.
Policy *resilience.Policy
// Transport replaces the default (direct connections, tuned timeouts, trace
// propagation and fleet-graph events). Tests pass httptest's.
Transport http.RoundTripper
}
Config describes one sibling service.
type Mode ¶
type Mode int
Mode says what a caller does when the sibling is unavailable. It has no default on purpose: a client that quietly fails open is an authorisation bypass waiting to happen, and one that quietly fails closed is an outage amplifier.
const ( // FailOpen: the caller carries on without the answer. Unavailability is // reported in the context's degraded.Sink. FailOpen Mode // FailClosed: the caller stops. Unavailability is only an error. FailClosed )
type Request ¶
type Request struct {
// Method defaults to GET.
Method string
// Path is appended to the base URL's path and must start with "/".
Path string
Query url.Values
// Header is added to the request (credentials, idempotency keys).
Header http.Header
// Body is sent as JSON: a []byte or json.RawMessage as is, anything else
// marshalled. Nil sends no body.
Body any
}
Request is one call.
type StatusError ¶
StatusError is the sibling's answer when it was not a success. The body is the first MaxBodyBytes of the reply; it is not included in Error, because it may carry data that should not reach a log.
Example ¶
A fail-closed client, and the difference between the sibling being unavailable and the sibling saying no: a 402 is an answer, with its body.
package main
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"time"
"github.com/baditaflorin/go-common/meshclient"
)
func main() {
sibling := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusPaymentRequired)
_, _ = io.WriteString(w, `{"required":5,"balance":2}`)
}))
defer sibling.Close()
ledger, _ := meshclient.New(meshclient.Config{Name: "ledger", BaseURL: sibling.URL, Mode: meshclient.FailClosed, Timeout: time.Second})
err := ledger.PostJSON(context.Background(), "/v1/charge", map[string]int{"amount": 5}, nil)
var status *meshclient.StatusError
if errors.As(err, &status) {
fmt.Println(status.Status, string(status.Body))
}
fmt.Println("unavailable:", meshclient.IsUnavailable(err))
}
Output: 402 {"required":5,"balance":2} unavailable: false
func (*StatusError) Error ¶
func (e *StatusError) Error() string
func (*StatusError) Retryable ¶
func (e *StatusError) Retryable() bool
Retryable reports whether the status is one a later attempt may fix.
type UnavailableError ¶
type UnavailableError struct {
}
UnavailableError wraps a failure that means the sibling cannot be used right now. Class is the degraded-token suffix: "down", "timeout", "rate_limited" or "degraded". Cause is the underlying error (a *StatusError for a 5xx or 429).
func (*UnavailableError) Error ¶
func (e *UnavailableError) Error() string
func (*UnavailableError) Is ¶
func (e *UnavailableError) Is(target error) bool
Is makes errors.Is(err, ErrUnavailable) true.
func (*UnavailableError) Retryable ¶
func (e *UnavailableError) Retryable() bool
Retryable reports whether the cause is worth retrying, for callers that wrap this client in a policy of their own.
func (*UnavailableError) Unwrap ¶
func (e *UnavailableError) Unwrap() error