client

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 22 Imported by: 0 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.

Documentation

Overview

Package client is the fulfillmenttools API as the rest of fft sees it.

It wraps the generated client (which owns the paths, the models and — crucially — the per-parameter query encoding) with the five things every command needs and none should reimplement:

  • the error envelope decoded as the JSON *array* it actually is, mapped to an exit code and a hint (APIError, Check);
  • a retry that knows the difference between a request it may repeat and one it may not (Client.Do);
  • the reactive 401: refresh the token and retry, exactly once;
  • cursor pagination as one generic, because every /search endpoint in the API has the same shape (Search, SearchAll);
  • optimistic locking as one generic, because `version` travels in the body and every mutation is therefore a read-then-write (UpdateVersioned).

Why the retry is here and not in a RoundTripper

A RoundTripper is handed a request whose body is a one-shot io.ReadCloser. By the time a 401 or a 500 comes back the body has been consumed, and replaying it is impossible in the general case. A retry at that layer works in the specs, where the body is a bytes.Reader, and silently sends an empty POST in production. So the retry lives here, where a request is a Doer that can simply be called again.

Index

Constants

View Source
const (
	KeyFacilityRef      = "facilityRef"
	KeyTenantFacilityID = "tenantFacilityId"
)

The two names a facility goes by outside a path parameter: the platform's reference, and the tenant's own id (swagger:38576, 82981).

View Source
const (
	// MinSize and MaxSize bound `size`. The API rejects anything outside them with
	// an opaque 400, so fft rejects it first, with a sentence.
	MinSize = 1
	MaxSize = 250

	// DefaultSize is what the API uses when `size` is absent.
	DefaultSize = 20

	// PageSize is what [SearchAll] asks for. Well under the maximum, and 5× fewer
	// round trips than the API's own default across a tenant with a few thousand
	// entities.
	PageSize = 100

	// DefaultMaxItems is how far [SearchAll] will follow the cursor before it stops
	// and says so. A runaway cursor must not be able to hang a terminal.
	DefaultMaxItems = 10_000
)

The search API's numbers. The legacy GET list has a *different* default (25): the two are not unified into one --limit default, because a user who set --size 25 and got 20 would be right to file a bug.

View Source
const DefaultListSize = 25

DefaultListSize is what these endpoints use when `size` is absent.

It is 25, and DefaultSize — the cursor searches' default — is 20. They are deliberately not folded into one number: the defaults belong to the API, not to fft, and a user who passed --size 25 and quietly got 20 would be right to file a bug. See the same argument at the top of search.go.

Variables

This section is empty.

Functions

func Check

func Check(status int, body []byte) error

Check turns a non-2xx response into an *APIError, and returns nil for a 2xx.

func ExplainQueryTooComplex added in v0.11.0

func ExplainQueryTooComplex(op string, err error) error

ExplainQueryTooComplex turns the API's "Query too complex" 400 into a *QueryTooComplexError and passes every other error through untouched.

It matches the message, not the status alone: an unknown enum value gets the same 400, and hinting at a narrower filter for it would send the user the wrong way.

func FacilityRef

func FacilityRef(id string) string

FacilityRef turns whatever the user typed into something a facility path parameter accepts.

A platform UUID passes through. Anything else is taken to be the tenant's own id and wrapped as urn:fft:facility:tenantFacilityId:<id>, which every facility path parameter in the API also accepts. So `fft facility get BER-01` works, and the user never has to look up a UUID for an id they chose themselves.

A value that is already a URN passes through too, so that piping one command's output into another cannot double-wrap it.

func FacilitySelector

func FacilitySelector(id string) (key, value string)

FacilitySelector names a facility the way a request *body* and a search *query* want it: as one of two differently-spelled fields, rather than as the URN FacilityRef builds for a path.

The two are told apart the same way FacilityRef tells them apart — by shape, because there is no other signal. A platform UUID (or an already-built URN) is a facilityRef; anything else is the tenant's own id. key is "" for an empty id.

The difference from the URN wrap is not cosmetic. A stock creation body carrying {"facilityRef": "BER-01"} is refused, because BER-01 is not a reference; a search query filtering facilityRef by "BER-01" is *accepted* and quietly matches nothing, which is worse. Same value, same intent, two spellings — not something each command should be left to work out for itself.

func Fetch

func Fetch[T any](ctx context.Context, c *Client, op string, do Doer) (T, error)

Fetch issues the request and decodes its JSON answer into T.

func ListAll added in v0.2.0

func ListAll[T any](ctx context.Context, c *Client, op ListOp[T], size int, opts ...AllOption) iter.Seq2[T, error]

ListAll yields every entity, walking the list one page at a time.

It is SearchAll for the id-keyed endpoints, and it keeps the same two promises: it stops at maxItems (DefaultMaxItems unless MaxItems says otherwise), and if that cut anything off it yields a *TruncatedError as its last element. A truncated list that does not say it was truncated is a wrong answer that looks like a right one.

func RawID added in v0.2.0

func RawID(raw json.RawMessage) (string, error)

RawID reads the id off an entity that has not been decoded into a model, which is what every list command actually holds — the table is built from a view struct and -o json prints the API's own bytes, so nothing in between needs the generated type.

func RequestError

func RequestError(op string, err error) error

RequestError reports a request that never got an answer.

http.Client wraps every transport failure in a *url.Error, which prints as `Get "https://…/api/…": <cause>`. When the cause is fft's own — a token it could not mint, a proxy's refusal — that prefix buries the one sentence the user needs ("sign in again") behind a URL they did not type. So an error that already knows its exit code is returned as it is, with its hint intact; a genuine network failure keeps the URL, because there the URL is the point, and is a TransportError.

The token source runs inside the round trip, so its failures arrive as a *url.Error too. One that is not itself a network failure — a locked keychain, a failed cache write — never left the machine, so it is wrapped without the URL and without claiming the upstream was at fault: a script retrying on 9 would loop on something a retry cannot fix. One that is (Google's token endpoint unreachable) is still a transport failure.

func SearchAll

func SearchAll[Q, S, T any](ctx context.Context, c *Client, op Op[T], payload SearchPayload[Q, S], opts ...AllOption) iter.Seq2[T, error]

SearchAll yields every match, following the cursor from page to page.

It stops at maxItems (DefaultMaxItems unless MaxItems says otherwise) and, if that cut anything off, yields a *TruncatedError as its last element: a truncated list that does not say it was truncated is a wrong answer that looks like a right one.

The iteration stops at the first error, which is also yielded. A caller that breaks out early simply stops fetching.

func UpdateVersioned

func UpdateVersioned[T any](ctx context.Context, get GetFn[T], put PutFn[T], mutate func(*T) error, expected *int) (T, error)

UpdateVersioned is the read-then-write that every mutation of a versioned entity has to be.

It reads the entity, applies mutate to it, and writes it back with the version it just read. If the server answers 409 — someone else wrote in between — it reads again, re-applies mutate to the *fresh* entity, and writes once more. A second 409 is not retried: at that point the entity is being written by something else faster than fft can read it, and the honest answer is to say so.

expected is the --if-version escape hatch. When it is set, the read is skipped and that version is sent as it stands: a CI job that already knows the version pays for one request instead of two, and gets a 409 rather than a silent overwrite if it was wrong. mutate is then applied to the zero value of T, so it must produce the complete entity — which is what `--file` gives it.

(The flag is --if-version, never --version: cobra owns --version on the root command, and a subcommand-local one would read as "print the version" to every user and every script.)

Types

type APIError

type APIError struct {
	// Status is the HTTP status code.
	Status int
	// Errors is the decoded envelope. It is empty when the body was not one — a
	// proxy's HTML 502, say.
	Errors []api.ErrorInner
	// Envelope is whether the body was a JSON array at all — the tenant's shape —
	// even an empty one, which leaves Errors empty. Intermediary keys on this and
	// not on len(Errors), so that a tenant's `[]` is not blamed on a proxy.
	Envelope bool
	// Body is the raw response, kept only when it could not be decoded, so that
	// the user is told *something* rather than "HTTP 502".
	Body string
}

APIError is a non-2xx answer from fulfillmenttools.

The error envelope is a JSON *array* of ErrorInner — [{"summary":"…"}] — and not an object. Decoding it into a struct succeeds and produces {} for every error, which is how an API turns "no facility matching request X was found" into silence.

func (*APIError) Conflict

func (e *APIError) Conflict() (sent, current int64, ok bool)

Conflict reports the two versions a 409 carries: the one the request sent and the one the server holds. ok is false for anything else — including a 409 whose envelope, for once, did not carry them.

This is the gift the array envelope brings: the server tells us exactly how stale we were, so the user is told too, instead of "409 Conflict".

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) ExitCode

func (e *APIError) ExitCode() int

ExitCode implements the interface exitcode.FromError looks for, so a script can tell "you are not permitted" from "it does not exist" without parsing text.

func (*APIError) Hint

func (e *APIError) Hint() string

Hint names the command that would fix the failure, where there is one.

func (*APIError) Intermediary added in v0.11.0

func (e *APIError) Intermediary() bool

Intermediary reports an auth-class refusal (401, 403, 407) that did not come from the tenant: a corporate egress proxy, firewall or gateway answered instead.

The tenant's errors always carry the JSON-array envelope, so a body that is not a JSON array is the tell — an empty array still is one. An empty body is deliberately not counted — the tenant has been seen to answer bare, and blaming a proxy for a real permission failure would send the user off to the wrong team. 407 is the exception: only a proxy sends it.

type AllOption

type AllOption func(*allOptions)

AllOption configures SearchAll.

func MaxItems

func MaxItems(n int) AllOption

MaxItems caps how many items SearchAll yields. A value below 1 is ignored.

type Client

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

Client is one tenant, authenticated.

The generated client underneath is reachable through Client.API for the calls that need no retry — `fft ping` against /api/status, say. Everything else goes through Client.Do, which is what turns a generated call into one that retries safely, refreshes on a 401, and fails with a message the user can act on.

func New

func New(baseURL string, opts ...Option) (*Client, error)

New returns the client for the tenant at baseURL.

func (*Client) API

func (c *Client) API() *api.ClientWithResponses

API is the generated client, for a call that does not go through Client.Do.

func (*Client) Do

func (c *Client) Do(ctx context.Context, op string, do Doer) (*Result, error)

Do issues the request, retrying it where that is safe, and turns the answer into a *Result or an error a user can act on.

op names the operation in errors ("list the facilities"), so that a failure reads as a sentence rather than as a URL.

func (*Client) DoRaw

func (c *Client) DoRaw(ctx context.Context, op string, req RawRequest) (*Result, error)

DoRaw issues a request built from spec metadata, through the same Client.Do as everything else: the same retry rules, the same 401 refresh, the same error envelope.

op names the operation in errors, as it does everywhere else in this package.

type Doer

type Doer func(ctx context.Context) (*http.Response, error)

Doer issues one attempt of a request.

It must build a *fresh* request every time it is called, because Client.Do calls it again to retry and an http.Request body is a one-shot reader. Every generated api.ClientInterface method satisfies this: each call marshals the body anew. A Doer that closes over an io.Reader does not, and would retry by sending an empty body.

type FacilitySearchPayload

type FacilitySearchPayload = SearchPayload[api.FacilitySearchQuery, api.FacilitySort]

FacilitySearchPayload is the body of POST /api/facilities/search.

type GetFn

type GetFn[T any] func(ctx context.Context) (entity T, version int, err error)

GetFn reads the entity to be updated, and the version the server currently holds for it.

The version comes back separately rather than being read off the entity, because T is a type parameter and Go cannot reach a field through one. The call site knows the field — it is one line — and this way UpdateVersioned works for every versioned entity in the API without an interface the generated models would have to implement.

type ListOp added in v0.2.0

type ListOp[T any] struct {
	// Name names the operation in errors ("list the facility's connections").
	Name string

	// Items is the response field holding the entities: "interFacilityConnections".
	// Empty means the response *is* the array of entities, which is what a few
	// endpoints answer — and then there is no envelope, so no total to cross-check.
	Items string

	// Do issues one page. Every parameter but the paging pair — the facility whose
	// connections these are, a filter, a locale — is closed over by the constructor,
	// exactly as [Op.Do] closes over nothing but the body.
	Do func(ctx context.Context, raw api.ClientInterface, after string, size int) (*http.Response, error)

	// ID reads an entity's id, which *is* the cursor: the next page is the one that
	// starts after the last id of this one.
	//
	// So a list fft cannot page is one whose entities it cannot identify, and that is
	// a failure worth naming rather than a loop worth entering. [RawID] is the
	// implementation every caller wants.
	ID func(T) (string, error)

	// Unpageable is set for an endpoint that hands out ids it will not take back as
	// startAfterId, so no second page can be addressed. [ListAll] then reads one page
	// (as large as fft allows: [MaxSize], the one --size bound every list command
	// shares, which may be below what the endpoint's own schema declares) and reports
	// the rest as an [*UnpageableError] instead of asking for a page that can only fail.
	Unpageable bool
}

ListOp binds the id-keyed pagination to one endpoint. It is Op for the GET lists, and it is used the same way.

func FacilityConnections added in v0.2.0

func FacilityConnections(facilityID, target string) ListOp[json.RawMessage]

FacilityConnections is GET /api/facilities/{facilityId}/connections, decoding each connection into json.RawMessage.

It is a ListOp and not an Op because the connections have no /search: they page by startAfterId. See the top of list.go.

facilityID goes in the path, so it may be a URN — FacilityRef is enough. target goes in a *query* filter, and query filters do not resolve URNs: it must already be a platform id, or the API answers a cheerful, empty 200. See resolveFacilityID in cmd/fft/facility.go, which is what the caller uses to get one.

func Orders added in v0.3.0

func Orders(tenantOrderID, consumerID string) ListOp[json.RawMessage]

Orders is GET /api/orders, decoding each order into json.RawMessage.

It is a ListOp and not an Op because the GET list pages by startAfterId, not by a cursor — POST /api/orders/search is the cursor search (see OrderSearch).

tenantOrderID and consumerID are the only two filters the GET list offers, both exact-match query params; they are closed over here the way FacilityConnections closes over its target. Anything richer (status, date range) is search-only.

func RawListOp added in v0.11.0

func RawListOp(c *Client, name, items string, base RawRequest) ListOp[json.RawMessage]

RawListOp is a ListOp for an operation known only from the spec: base is the request without its paging pair, and every page re-adds `size` and, after the first, `startAfterId`. It is what lets a generated (Tier-2) list command page through ListAll with the guarantees the curated ones have.

base.Query must not already carry either parameter; the caller strips them.

func RoutingCategories added in v0.6.0

func RoutingCategories() ListOp[json.RawMessage]

RoutingCategories is GET /api/routing/nodeconfigcategories, decoding each node config category into json.RawMessage. Its envelope array is routingStrategyNodeConfigCategories.

func RoutingDecisionLogs added in v0.6.0

func RoutingDecisionLogs(filter RoutingDecisionLogsFilter) ListOp[json.RawMessage]

RoutingDecisionLogs is GET /api/routing/decisionlogs, decoding each decision log into json.RawMessage. Its envelope array is decisionLogs.

The endpoint offers only exact-match id filters — closed over here the way FacilityConnections closes over its target — and cannot be paged: see Unpageable.

func RoutingStrategies added in v0.6.0

func RoutingStrategies() ListOp[json.RawMessage]

RoutingStrategies is GET /api/routing/strategies, decoding each strategy into json.RawMessage.

It is a ListOp and not an Op because the strategies have no /search: they page by startAfterId, and their envelope is {routingStrategies, total}. See the top of list.go.

type ListPage added in v0.2.0

type ListPage[T any] struct {
	// Items are the entities on this page.
	Items []T

	// Total is the number of matches. Unlike [Page.Total] it is not a pointer: this
	// envelope always carries a total, so there is no "the API did not count" to tell
	// apart from a count of zero.
	Total int
}

ListPage is one page of a GET list.

func List added in v0.2.0

func List[T any](ctx context.Context, c *Client, op ListOp[T], after string, size int) (ListPage[T], error)

List fetches one page. after is the id to start after — empty for the first page.

type ListingSearchPayload

type ListingSearchPayload = SearchPayload[api.ListingSearchQuery, api.ListingSort]

ListingSearchPayload is the body of POST /api/listings/search.

type Op

type Op[T any] struct {
	// Name names the operation in errors ("search the facilities").
	Name string

	// ID is the spec's operationId ("searchFacility"). It is what lets [Search] retry
	// a page that hit a 502: a POST is retried only when this id names an operation
	// the spec classifies as a read. Empty means "not known to be a read", and the
	// page is then sent once, like any other POST.
	ID string

	// Items is the response field holding the entities: "facilities", "stocks",
	// "listings". It is the one part of the response shape that is not uniform.
	Items string

	// Do issues one page.
	Do func(ctx context.Context, raw api.ClientInterface, body []byte) (*http.Response, error)
}

Op binds the generic search to one entity's endpoint.

Do is the generated client's method, so the path and the encoding stay in the generated code. It takes the body as bytes rather than as an io.Reader because Client.Do may call it twice: a Reader would be empty the second time.

func FacilitySearch

func FacilitySearch[T any]() Op[T]

FacilitySearch is POST /api/facilities/search, decoding each facility into T.

func ListingSearch

func ListingSearch[T any]() Op[T]

ListingSearch is POST /api/listings/search, decoding each listing into T.

func OrderSearch added in v0.3.0

func OrderSearch[T any]() Op[T]

OrderSearch is POST /api/orders/search, decoding each order into T.

func RawSearchOp added in v0.11.0

func RawSearchOp(c *Client, id, name, items, path string) Op[json.RawMessage]

RawSearchOp is an Op for a cursor search known only from the spec: one whose tag has no generated client, so there is no typed method to call. path is the search's path, with no placeholders.

id must be the spec's operationId, exactly as for Op.ID: it is what lets a page that hit a 502 be retried, and an id the spec does not classify as a read gets no retry.

func StockSearch

func StockSearch[T any]() Op[T]

StockSearch is POST /api/stocks/search, decoding each stock into T.

type Option

type Option func(*options)

Option configures the client.

func WithDebug

func WithDebug(w io.Writer) Option

WithDebug logs every request and response to w, redacted. This is --debug.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient replaces the underlying HTTP client.

func WithObserver added in v0.8.0

func WithObserver(observe func(status int)) Option

WithObserver reports the HTTP status of every response the tenant sends back.

It sees each attempt, not each call: a 401 answered by a refresh and a retry is two reports, the last of which is what the call finally got. A request that never received a response — refused, timed out, cancelled — is not reported at all, because there is no status to report and inventing one (0, say) would be a lie a history view would faithfully repeat.

observe runs on the goroutine that sent the request and must not block.

func WithRetry

func WithRetry(r Retry) Option

WithRetry replaces the retry policy. Fields left zero keep their default.

func WithTokenSource

func WithTokenSource(src auth.TokenSource) Option

WithTokenSource authenticates every request with src.

Without it the client is unauthenticated, which is exactly what `fft ping` wants: /api/status is the one endpoint that answers without a token, so it can prove connectivity even when the credentials are the thing that is broken.

type OrderSearchPayload added in v0.3.0

type OrderSearchPayload = SearchPayload[api.OrderSearchQuery, api.OrderSort]

OrderSearchPayload is the body of POST /api/orders/search.

type Page

type Page[T any] struct {
	// Items are the entities on this page.
	Items []T

	// PageInfo carries the cursor to the next page, and whether there is one.
	PageInfo api.PageInfo

	// Total is the number of matches — *absent* unless the search asked for it with
	// options.withTotal. A pointer, because "the API did not count" and "the API
	// counted zero" are different answers and a command that renders `Total: 0` for
	// the first one is lying.
	Total *int
}

Page is one page of search results.

func Search[Q, S, T any](ctx context.Context, c *Client, op Op[T], payload SearchPayload[Q, S]) (Page[T], error)

Search fetches one page.

type ProxyRefusedError added in v0.11.0

type ProxyRefusedError struct {
	// Status is the CONNECT response's status code (403, 407, …).
	Status int
	// Proxy is the proxy's host, without credentials.
	Proxy string
}

ProxyRefusedError is an explicit proxy (HTTPS_PROXY) declining to open the tunnel to the tenant. net/http never hands such a refusal back as a response — it turns any non-200 CONNECT reply into a bare transport error, `Get "…": Forbidden` — so APIError.Check never sees it. This is the typed error that reaches the user instead, with the same hint an in-tunnel intermediary gets.

func (*ProxyRefusedError) Error added in v0.11.0

func (e *ProxyRefusedError) Error() string

func (*ProxyRefusedError) ExitCode added in v0.11.0

func (e *ProxyRefusedError) ExitCode() int

ExitCode says whether trying again can help. The request never reached the tenant, so neither 4 (auth) nor 5 (permission) is true of it. A 5xx is the proxy being down or overloaded, which passes, so a script should back off (9). Anything else — 403, 407 — is the proxy's policy or its credentials for us, which a retry will not change, so it stays a plain failure.

func (*ProxyRefusedError) Hint added in v0.11.0

func (e *ProxyRefusedError) Hint() string

Hint implements the same hint interface APIError does.

type PutFn

type PutFn[T any] func(ctx context.Context, entity T, version int) (T, error)

PutFn writes the entity back, carrying version in the *body*.

There is no ETag and no If-Match anywhere in the API: optimistic locking is a required `version` field in the request body. That is why the version is a parameter here and not a header somewhere below.

type QueryParam

type QueryParam struct {
	// Name is the parameter's name as the API spells it.
	Name string

	// Values are the values to send. One for a scalar; any number for an array.
	Values []string

	// Explode chooses the encoding, and it must come from the *parameter's* own
	// `explode` in the spec — never from a policy applied to all of them.
	//
	//	true  repeats the name:     status=OPEN&status=CLOSED
	//	false joins with a comma:   status=OPEN%2CCLOSED
	//
	// The comma really does go over the wire percent-encoded: the values become one
	// string, and url.Values.Encode escapes the separator along with everything else.
	// It is what oapi-codegen's runtime already sends for the eight tags it covers, and
	// it was confirmed against the live tenant on 2026-07-13 — getStockSummaries
	// filtered by facilityStatus=ONLINE%2COFFLINE answers 384,279 of 383,484 rows,
	// which is the union of the two statuses and emphatically not the zero an
	// unrecognised filter would have returned.
	//
	// The API does not reject the wrong *choice*, though, and that is the danger. It
	// answers 200 and filters on something else — a comma-joined value sent to an
	// exploded parameter is matched as the literal string "ONLINE,OFFLINE", which no
	// row has, and the user is told there are none. 17 of the spec's 77 array query
	// parameters want the joined form and 60 want the repeated one, which is why this
	// is a field and not a constant.
	Explode bool
}

QueryParam is one query parameter, encoded the way its own spec entry says.

type QueryTooComplexError added in v0.11.0

type QueryTooComplexError struct {
	// Op names the operation, as everywhere else in this package.
	Op string
	// Err is the API's answer, kept whole.
	Err *APIError

	// Walk is set when the refusal cut an --all walk short; Pages and Items are how
	// far it got. Without them a page-two refusal reads as if the very first request
	// failed, and the user cannot tell a bad query from a collection that got too
	// big part-way through.
	Walk         bool
	Pages, Items int
}

QueryTooComplexError is the API's 400 "Query too complex", with the way out the API's own message gets wrong.

The message advises reducing the result set size, and that is the one thing that does not work: the cost is in the filter or sort over the whole collection, not in the page, so a smaller --size fails the same way. Every POST /{entity}/search is the same cursor search over the same kind of backend, so this is recognised once, here, rather than by each command that sends a search.

It wraps rather than replaces the APIError, so the message stays the API's own words and the exit code stays the one the status maps to: there is no exit code of its own, and none is wanted.

func (*QueryTooComplexError) Error added in v0.11.0

func (e *QueryTooComplexError) Error() string

func (*QueryTooComplexError) Hint added in v0.11.0

func (e *QueryTooComplexError) Hint() string

Hint is true for every entity. A command with a better narrow filter than "an id" replaces it with its own.

func (*QueryTooComplexError) Unwrap added in v0.11.0

func (e *QueryTooComplexError) Unwrap() error

type RawRequest

type RawRequest struct {
	// Method is the HTTP method, upper-case.
	Method string

	// Path is the path template, placeholders and all: /api/pickjobs/{pickJobId}.
	// [RawRequest.URL] fills them from PathParams, so that the escaping happens in
	// one place instead of at every call site.
	Path string

	// PathParams fills the template's placeholders.
	PathParams map[string]string

	// Query is the query string, each parameter carrying its own encoding.
	Query []QueryParam

	// Header adds request headers. Content-Type, Accept and Authorization are set by
	// the client and should not be given here.
	Header map[string]string

	// Body is the request body, or nil for none.
	Body []byte
}

RawRequest is a request described by spec metadata rather than by a typed method.

func (RawRequest) URL

func (r RawRequest) URL(base string) (string, error)

URL resolves the request against a base URL.

Every placeholder must have a value and no value may be empty: an unfilled {pickJobId} would be sent literally and a blank one would collapse the path to /api/pickjobs/, which is a different endpoint that answers 200. Both are refused here rather than sent.

type Result

type Result struct {
	Status int
	Header http.Header
	Body   []byte
}

Result is a 2xx answer: everything a caller could want from it, with the body already read and the connection already returned to the pool.

type Retry

type Retry struct {
	// MaxAttempts is how many requests may be sent in total, the first included.
	MaxAttempts int

	// Base is the first backoff interval; it doubles from there.
	Base time.Duration

	// Max caps one backoff interval.
	Max time.Duration

	// MaxWait is the longest Retry-After fft will honour. A rate limit measured in
	// minutes is not something a CLI should sit and wait out — it is something the
	// user should be told about.
	MaxWait time.Duration

	// Sleep waits, or returns the context's error if the wait is cancelled. It is a
	// seam: nil means a real sleep, and specs replace it so that a spec exercising
	// a Retry-After of one second does not take one second.
	Sleep func(ctx context.Context, d time.Duration) error
}

Retry is the retry policy. A zero Retry means the defaults.

The idempotency rule

A 429 is retried for every method: the request provably did not happen. A 5xx or a dropped connection is retried only for GET, PUT and DELETE — a POST that answered 500 may still have created the facility, and re-sending it would create a second one. There is no way to tell from the outside, so fft does not guess: it surfaces the error and lets the user look.

The exception is a POST the spec says changes nothing — a cursor search, which posts its query because a query string cannot hold one. Re-sending a search creates nothing, so Search retries it as it would a GET. That is decided by operationId through api.Operation.Mutates, never by the method or the path, so a POST nobody has classified stays unretried.

type RoutingDecisionLogsFilter added in v0.6.0

type RoutingDecisionLogsFilter struct {
	OrderRef           string
	RoutingPlanRef     string
	ProcessRef         string
	TenantOrderID      string
	SourcingOptionRef  string
	SourcingOptionsRef string
}

RoutingDecisionLogsFilter is the exact-match filter set of GET /api/routing/decisionlogs. Every field is an id the API compares literally; an empty one is simply not sent, exactly as the two order filters behave on Orders.

type SearchPayload

type SearchPayload[Q, S any] struct {
	// Query is the entity's filter. Its zero value marshals to {}, which the API
	// accepts and reads as "everything" — confirmed against the live tenant.
	Query Q `json:"query"`

	// After is the cursor from the previous page's pageInfo.endCursor. [SearchAll]
	// drives it; a caller paging by hand sets it.
	After *string `json:"after,omitempty"`

	// Size is how many items to return: 1–250, 20 if absent.
	Size *int `json:"size,omitempty"`

	// Sort holds *exactly one* element, or is nil. The API's schema says
	// minItems: 1, maxItems: 1, and an empty array comes back as an opaque 400 —
	// so an empty (but non-nil) Sort is refused here, before the request is sent.
	Sort []S `json:"sort,omitempty"`

	// Options asks for the total. Without withTotal:true the response has no
	// `total` field at all — which is why [Page.Total] is a pointer.
	Options *api.SearchOptions `json:"options,omitempty"`
}

SearchPayload is the body of every POST /{entity}/search in the API.

This is the leverage point: the shape is identical for facilities, listings, stocks, pickjobs and orders — only the query and the sort differ, and those are the two type parameters. One generic therefore carries cursor pagination for the whole API, and a new entity costs an Op and a type alias.

func (SearchPayload[Q, S]) WithTotal

func (p SearchPayload[Q, S]) WithTotal() SearchPayload[Q, S]

WithTotal asks the API to count the matches, and returns the payload so it can be set inline.

type StockSearchPayload

type StockSearchPayload = SearchPayload[api.StockSearchQuery, api.StockSort]

StockSearchPayload is the body of POST /api/stocks/search.

type TransportError added in v0.11.0

type TransportError struct {
	// Op names the operation in a sentence ("list the facilities").
	Op string
	// Err is what the HTTP client returned. It is a *url.Error, so the message keeps
	// the URL, which is the point of a network failure.
	Err error
}

TransportError is a request that never got an answer: the connection was refused or reset, the name did not resolve, the TLS handshake failed, a proxy would not open the tunnel. The upstream is unreachable, which a script should treat as transient and retry later, so it exits 9 rather than the 1 of an unclassified failure.

A cancellation is the exception: it is the user pressing ^C, not the network, and exitcode.FromError checks for it before it asks the error, so it still exits 130.

func (*TransportError) Error added in v0.11.0

func (e *TransportError) Error() string

func (*TransportError) ExitCode added in v0.11.0

func (e *TransportError) ExitCode() int

ExitCode is Unavailable: upstream did not answer.

func (*TransportError) Unwrap added in v0.11.0

func (e *TransportError) Unwrap() error

type TruncatedError

type TruncatedError struct {
	MaxItems int
	Op       string
}

TruncatedError says that a search matched more than SearchAll was allowed to yield. It is not a failure of the request — the items already yielded are real — it is the reason there are no more.

func (*TruncatedError) Error

func (e *TruncatedError) Error() string

func (*TruncatedError) Hint

func (e *TruncatedError) Hint() string

Hint tells the user how to see the rest.

type UnpageableError added in v0.11.0

type UnpageableError struct {
	Op      string
	Fetched int
	Total   int
}

UnpageableError says that a list has more entries than one page, on an endpoint that cannot be paged (ListOp.Unpageable). Like TruncatedError it is not a failure of the request: everything yielded before it is real.

func (*UnpageableError) Error added in v0.11.0

func (e *UnpageableError) Error() string

func (*UnpageableError) Hint added in v0.11.0

func (e *UnpageableError) Hint() string

Hint tells the user how to see the rest.

type WalkTimeoutError added in v0.11.0

type WalkTimeoutError struct {
	Op    string
	Pages int
	Items int
	// Err is what the walk's request returned, kept so the cause is never thrown
	// away. It is the walk context's own error, so it matches DeadlineExceeded.
	Err error
}

WalkTimeoutError says the whole-command --timeout expired part-way through an --all walk. --timeout bounds the walk, not one request, so a large tenant can run out of time long after every individual page was answering promptly — and a bare "context deadline exceeded" names neither the flag nor how far it got.

Nothing already fetched is lost to the caller of the iterator, but an --all command does not print half a list as if it were the list, so the command fails. It unwraps to context.DeadlineExceeded, so it exits 9 like any other timeout: the hint is for the person, the code for the script.

func (*WalkTimeoutError) Error added in v0.11.0

func (e *WalkTimeoutError) Error() string

func (*WalkTimeoutError) Hint added in v0.11.0

func (e *WalkTimeoutError) Hint() string

Hint tells the user how to finish the walk.

func (*WalkTimeoutError) Unwrap added in v0.11.0

func (e *WalkTimeoutError) Unwrap() error

Jump to

Keyboard shortcuts

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