transport

package
v3.0.0-dev.6 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 36 Imported by: 0

Documentation

Overview

Package transport is forgeapi's one request core: addressing, auth injection, retry, the SSRF hook, trust, decode bounds, pagination, budget, error mapping and the per-request log line.

It is under internal/ because its whole job is to hold the three dependency types the exported surface bans from a signature, so an importable spelling would put a dependency's next major on that surface. The path decides it mechanically: the surface generator skips any directory named internal.

A family package builds one Conn per connection and speaks to it in this package's own vocabulary. Nothing here reaches a consumer.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AfterRemovals

func AfterRemovals(err error, removed []string) error

AfterRemovals is err, a refusal a label removal met after it had removed the labels named in removed, with its Message naming them: those removals stay, and forgeapi.Labels.RemoveLabels says the refusal names them. A context sentinel carries no message and is returned as it is.

func AnswerFigures

func AnswerFigures(fe *forgeapi.Error, answer *Response, signal budgetSignal, pool budgetPool)

AnswerFigures sets fe's Remaining, Reset and Pool from answer's own budget signal and pool, as the governor reads them off every answer, raw, the pool's name quoted by answer's quoter: what a limit holds is the consumer's to read from them and Secondary.

func Call

func Call(ctx context.Context, op string) context.Context

Call opens one operation and returns the context its every request is issued on, so the published price is the CALL's and every request shares the deadline that starts here ([Conn.withDeadline]). A family calls it once per operation, because only the family knows where one begins: nothing beneath it can tell several requests of one operation from several operations. A request issued outside a Call is priced and bounded as a call of its own.

func CallWrite

func CallWrite(ctx context.Context, op string) context.Context

CallWrite is Call for a mutating operation whose call also reads: every read it makes is part of its write, so a read-only client refuses it with forgeapi.CodeMutationsDisabled before anything is sent, and the mutation reserve, held back for a write and its follow-up reads, admits it.

func ContextSentinel

func ContextSentinel(err error) error

ContextSentinel re-exports the context-sentinel test for a package that reads a transport failure before choosing its own answer.

func Decode

func Decode(body []byte, v any) error

Decode reads one response body under the decode bounds, which is what keeps an untrusted response's cost bounded before allocation scales with it.

func DistinctNames

func DistinctNames(names []string) []string

DistinctNames is names with every empty name and every repeat after the first dropped, in order, so a removal sends one request per label however often the caller named it. An empty name names no label, and on a route that takes the name as its last segment it would address the collection: GitHub's DELETE there removes every label the item carries.

func IsDeferred

func IsDeferred(err error) bool

IsDeferred reports whether an error is the governor's deferral rather than an answer an instance gave, which is what lets a list report the rows it did not fetch as partial instead of failing the call.

func IsRefused

func IsRefused(err error) bool

IsRefused reports whether an error is an attempt the attempt hook refused (forgeapi.CodeAttemptRefused). Nothing was sent, so it says nothing about the instance: a caller returns it unchanged rather than reading it as an answer.

func IsThrottled

func IsThrottled(err error) bool

IsThrottled reports whether an error is a throttle the INSTANCE answered rather than a deferral this library chose, which the status is what separates: a deferral sent nothing and so carries none. It is what lets a fold refused by a throttle mark its row with the reason the envelope assigns that refusal instead of failing the list around it.

func Local

func Local(code, message string) *forgeapi.Error

Local re-exports the local-refusal shape for a family's own pre-request checks.

func OperationExpired

func OperationExpired(ctx context.Context, err error) bool

OperationExpired reports whether err is the operation's own bound ([Conn.withDeadline]) running out while ctx, the context the operation was called with, is still live. It is what lets a list reading row by row mark the rows it did not reach forgeapi.PartialBudget rather than fail; the caller's own deadline or cancellation still fails it.

func ParseOriginAndPath

func ParseOriginAndPath(raw string) (*url.URL, bool)

ParseOriginAndPath parses raw when it is an origin and a path, the one form a base URL takes, and answers false for any other form or a URL that does not parse.

func PickRun

func PickRun[T any](
	ctx context.Context, c *Conn, op, noun string, size int, pinned bool,
	read func(page int) ([]T, *Response, error), pick func(*T) (onHead, rerunnable bool),
) (T, error)

PickRun walks a re-run's resolving read from page 1, each page read by read at size rows with the answer it came on, and answers the first row on which pick reports both that it carries the head and that it failed or was cancelled. A page shorter than size ends the walk, and so does page [maxRunPages]. With no such row it refuses on the last page's answer before any write: forgeapi.CodeRunPageTruncated after a full last page, else forgeapi.CodeStaleHead for a pin no row carried, else forgeapi.CodeRunNotFailed, each naming the row by noun.

func RetryAfter

func RetryAfter(header http.Header) time.Duration

RetryAfter is the wait a response's Retry-After header asks for, uncapped, and zero where the header is absent or malformed.

func Retryable

func Retryable(kind forgeapi.ErrorKind, status int) bool

Retryable is the one rule behind forgeapi.Error.Retryable: another attempt may succeed after a transport failure or a throttle, and on a status httpclient.IsRetryableStatus accepts.

func WaitFits

func WaitFits(ctx context.Context, wait time.Duration) bool

WaitFits reports whether ctx's deadline, if any, is past a wait from now.

Types

type Conn

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

Conn is one connection's request core: one wire transport, two clients over it, and its governor.

There are two clients because a transport configuration is consumed once per round tripper and carries no per-request override, so the read path and the mutation path cannot share one: the read path retries non-idempotent requests and the mutation path takes exactly one attempt, because a replayed merge is a duplicate no interval undoes.

func Open

func Open(conn *forgeapi.Connection, set *forgeapi.Settings, opts *Options) (*Conn, error)

Open validates one connection and builds its request core. It performs no I/O: what it refuses is a client it could not run honestly, and each refusal carries its own code so a consumer names the remedy rather than showing a warning.

func OpenEndpoint

func OpenEndpoint(conn *forgeapi.Connection, set *forgeapi.Settings, family forgeapi.Family) (*Conn, error)

OpenEndpoint builds the request core for one connection's OAuth endpoints, which live under its web base, so its API root plays no part. It carries the connection's trust material, proxy, address policy, port allowlist and headers exactly as Open does, and no credential. Its one exchange is Conn.PostForm.

func (*Conn) APIBase

func (c *Conn) APIBase() *url.URL

APIBase is the connection's API root, the one the connection named or the one its family derived, which is where a document served BESIDE the REST routes lives.

func (*Conn) AdmitFold

func (c *Conn) AdmitFold(ctx context.Context, op string) (forgeapi.PartialReason, bool)

AdmitFold asks the governor whether one folded-status read may be issued inside the current rolling interval, and says why not when it may not. Under forgeapi.ActionReads with its bound not spent it holds the read only against a pool at zero, as [Conn.admitRead] does. Each read the fold issues spends one of the bound through Conn.Do, so a fold can take the bound's last read and leave its next read governed as any read.

func (*Conn) Bound

Bound is ctx under the deadline Conn.Do gives the operation ctx belongs to, for a caller that waits between that operation's requests.

func (*Conn) Budget

func (c *Conn) Budget() forgeapi.Budget

Budget is the resolved budget.

func (*Conn) BudgetState

func (c *Conn) BudgetState() forgeapi.BudgetState

BudgetState is the governor's state for this connection, read-only and never written from outside.

func (*Conn) Close

func (c *Conn) Close()

Close releases this connection's pool, the idle connections of the ssrf transport Open built, and empties its read cache. A substitute wire is its author's, so Close never reaches it.

func (*Conn) Counters

func (c *Conn) Counters() forgeapi.Counters

Counters is the consumer's counter set.

func (*Conn) Do

func (c *Conn) Do(ctx context.Context, req *Request) (*Response, error)

Do issues one request, maps its outcome and records what it cost. While the read cache is on, a REST GET outside CallWrite that names Request.Into, carries no no-store and is not changed by an observer (httpcache.Guard) is revalidated, and a 304 the cache vouches for is served from the held answer (httpcache.Read.Serve, docs/read-cache.md).

What the call spent is published on EVERY arm it leaves by, the two refusals that send nothing included: it is the last CALL's price, so one that sent nothing is 0.

func (*Conn) Fail

func (c *Conn) Fail(ctx context.Context, op string, ex Exchange, answer *Response, code string, kind forgeapi.ErrorKind, message string) *forgeapi.Error

Fail builds a failure the family reached after a request on ex, the exchange only the family knows it reached it on: it carries a diagnostic id, and the line that id names is recorded here. It carries answer's status and figures ([Conn.answered]), none where answer is nil because none arrived. message may hold the instance's words: [Conn.quoterOf] quotes it.

func (*Conn) FailBody

func (c *Conn) FailBody(ctx context.Context, op string, ex Exchange, answer *Response, cause error) *forgeapi.Error

FailBody is what a response body that decoded but is not an answer earns. cause is the non-nil sentinel naming the check that failed, which the line carries as its error; the returned message is [bodyFailure]'s whatever the check.

func (*Conn) FailDecode

func (c *Conn) FailDecode(ctx context.Context, op string, ex Exchange, resp *Response, cause error) *forgeapi.Error

FailDecode is what a response body that did not decode earns, resp being the answer whose body it is. The line carries the decode error through the exchange's quoter, since a decode error can quote an instance string whole, and the body's content type and length beside it, never the body.

func (*Conn) FailOn

func (c *Conn) FailOn(ctx context.Context, op string, ex Exchange, cause *forgeapi.Error, code string, kind forgeapi.ErrorKind, message string) *forgeapi.Error

FailOn is Conn.Fail for a failure the family reached on cause, an earlier failure of the same exchange: it carries cause's status and figures, which cause took from its own answer where one arrived.

func (*Conn) Logger

func (c *Conn) Logger() *slog.Logger

Logger is the injected logger, for the family's own lines.

func (*Conn) PageCall

func (c *Conn) PageCall(op string, repo forgeapi.RepoRef, set *forgeapi.ListSettings) PageCall

PageCall names the call one list operation is making on this connection. op is the operation as its role method spells it; repo is the repository the call addresses, the zero reference on a list no repository addresses. The repository and an owner fold as the derived repository identifier folds them, and the API base folds as [connectionOf] states, so two spellings of one call name one call.

func (*Conn) PoolOf

func (c *Conn) PoolOf(req *http.Request) string

PoolOf is the pool req's operation last drew on, by the name the product's answer gave it: empty before an answer named one, on a product whose figure is the whole service's, and for a request this library did not build.

func (*Conn) PostForm

func (c *Conn) PostForm(ctx context.Context, op, path string, form url.Values, secrets ...masked.Secret) (*Response, error)

PostForm sends one form-encoded POST to path under the web base and answers the response whatever its status: an OAuth endpoint answers its outcomes in the body, at 200 on one product and 400 on another. An unreadable body answers the status and headers beside the failure, since a token may have been issued; every other failure answers no response. It takes one attempt, since a lost answer spent the code or refresh token it carried, and meets neither the mutation gate nor the interval, which govern forge objects. Every text it answers is quoted without secrets, the form's values that are credentials; its other values are kept.

func (*Conn) Price

func (c *Conn) Price(cost int)

Price replaces what the governor reports as the last call's cost, for the one product that prices a call by a figure in its own RESPONSE rather than by the number of requests that left. A family calls it after Conn.Do, which published the wire count, returned. Measured: GitLab's GraphQL endpoint answers a complexity score beside the data, and the expectation table prices a document by that score and a REST request at one.

func (*Conn) Quote

func (c *Conn) Quote(text string) Quoted

Quote is text with no exchange in hand made safe to carry, as [Conn.ambient] quotes it: a family's value from an answer it no longer holds.

func (*Conn) Refuse

func (c *Conn) Refuse(ctx context.Context, op string, capability forgeapi.Capability, support forgeapi.Support, ev forgeapi.Evidence) *forgeapi.Error

Refuse is the capability refusal: no request, one dedicated code, and the operation, the capability and the evidence detection holds for the verdict. The message follows the support value, because a capability detected as absent and one detection could not establish (an instance with its document switched off) are different facts, and only the first says the forge lacks it.

func (*Conn) Rotate

func (c *Conn) Rotate(cursor forgeapi.RotationCursor)

Rotate records how far the rotation of those reads got, so the next interval starts after the row last served rather than at the first.

func (*Conn) SpendFold

func (c *Conn) SpendFold(d time.Duration)

SpendFold charges one folded-status read's measured wall clock to the current interval, which is what the wall-clock bound spends.

func (*Conn) UnderAPI

func (c *Conn) UnderAPI(address string) (string, bool)

UnderAPI is the escaped path an absolute address names beneath this connection's API root, and whether it names one: another origin, compared as the redirect policy compares origins, or a path outside the root names nothing on this connection.

func (*Conn) WebBase

func (c *Conn) WebBase() *url.URL

WebBase is the connection's web base URL, which is where a document served at the instance root rather than under the API root lives.

type Exchange

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

Exchange is what one exchange with an instance was: the method it used and the arm that carried it. The per-request record names both from here rather than assuming either, and a family that reaches a failure AFTER a response states the exchange it reached it on.

The ZERO value describes NO exchange, which is what a refusal reached before any request is. The record then carries neither attribute, because naming a method for an exchange that never happened is worse than naming none.

func Document

func Document(method string) Exchange

Document names one exchange on the GraphQL document arm, which is the two reads one product answers from a document and nothing else.

func REST

func REST(method string) Exchange

REST names one exchange on the REST arm, which is every route of every family.

type Member

type Member struct {
	Error string
	Scope string
	Class string
}

Member is the machine-readable part of a refusal's body: RFC 6750's error code and the scope it names, each empty where the body carries none, and Class, the family's name for the message member as Options.MessageClass answers it.

type Options

type Options struct {
	Mapper errorMapper
	// Limit is asked before Mapper, which never sees a limit it reads; nil
	// leaves every limit to Mapper.
	Limit         limitReader
	Signal        budgetSignal
	Pool          budgetPool
	PoolParent    budgetParent
	DeriveAPIBase func(web *url.URL) string
	Clock         func() time.Time
	// MessageClass names the class of a refusal's message member, trimmed of
	// space, that its mapper reads in [Member.Class], empty for a message it does
	// not read; no other message text reaches the mapper. Nil reads none.
	MessageClass func(message string) string
	Family       forgeapi.Family
	// FreeNotModified says the product bills nothing for a not-modified answer to
	// an authorized conditional request, as its spec.Revalidations row states.
	FreeNotModified bool
}

Options is what a family hands Open: the connection, the resolved settings, the family this client serves, the API base to use when the connection names none, and the two per-family functions this package cannot own.

Clock is the time source the governor's rolling interval and a reported reset are measured on, time.Now where it is nil. Only a test sets it, to move a bound no caller can advance; no exported surface carries it, so a consumer cannot replace the pacing this governor exists to do.

type PageCall

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

PageCall is one list call as every continuation it mints names it: the family, the connection, the operation, the repository, the resolved state filter, the scope and any since bound, folded into a fixed-length digest, and the page bound. A continuation that names another call names no position in this one, so both resume methods refuse it before any request.

func (PageCall) Mint

func (p PageCall) Mint(prefix string, position ...int) forgeapi.Cursor

Mint is the page-numbered continuation resuming this call at position: prefix, then the position's numbers in order, the page bound and the call's digest, separated.

func (PageCall) MintPosition

func (p PageCall) MintPosition(prefix string, position ...string) forgeapi.Cursor

MintPosition is the continuation resuming this call at an upstream connection's own position: prefix, then the position's fields in order and the call's digest, separated. Each field is the family's own encoding and carries no separator. It carries no page bound, since a connection position resumes at the row after the last one served whatever page size the next call asks.

func (PageCall) MintWide

func (p PageCall) MintWide(prefix string, position ...int64) forgeapi.Cursor

MintWide is PageCall.Mint over 64-bit numbers, for a position naming a value an int may not hold, such as a run id.

func (PageCall) Resume

func (p PageCall) Resume(c forgeapi.Cursor, prefix string, count int) ([]int, error)

Resume reads the count numbers of the position a continuation this call minted under prefix names. It refuses, with forgeapi.CodeCursorInvalid, another encoding, another call's continuation, and one minted at another page bound, whose message names the bound the walk began at, since that bound alone resumes it. Whether each number is one the family mints is the family's to judge.

func (PageCall) ResumePosition

func (p PageCall) ResumePosition(c forgeapi.Cursor, prefix string, count int) ([]string, error)

ResumePosition reads the count fields of the position a continuation this call minted with PageCall.MintPosition under prefix names, refusing another encoding and another call's continuation with forgeapi.CodeCursorInvalid. Whether each field is one the family mints is the family's to judge.

func (PageCall) ResumeWide

func (p PageCall) ResumeWide(c forgeapi.Cursor, prefix string, count int) ([]int64, error)

ResumeWide is PageCall.Resume over 64-bit numbers, reading what PageCall.MintWide minted.

type Quoted

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

Quoted is text an instance, a proxy, the network or a credential source supplied, made safe to carry on an error or a log line. Only [quoter.quote] mints one, so a sink that takes a Quoted cannot be handed text no quoter saw.

func (Quoted) LogValue

func (q Quoted) LogValue() slog.Value

LogValue is the quoted text, which a line carries as a string.

func (Quoted) String

func (q Quoted) String() string

String is the quoted text.

type Request

type Request struct {
	Body any
	// Into is the value [Conn.Do] decodes a successful answer's body into, inside
	// the operation's deadline; an undecodable body is the call's error. On a GET,
	// [Conn.Do] states which reads are revalidated; Into's type is part of the key,
	// because the cache keeps the decoded projection rather than the body.
	Into any
	// Headers are the FAMILY's own request headers for this request, written
	// after the credential and before the consumer's. They are per request
	// because one family's API-version pin waits for a response proving the
	// version; each name is on the reserved list, so no consumer entry collides.
	Headers http.Header
	Query   url.Values
	Op      string
	Method  string
	Path    string
	// EscapedPath is this request's path ALREADY percent-encoded, taken in place
	// of Path where it is set: GitLab takes a namespace path as ONE segment with
	// its separators encoded, and Path, the DECODED path, sends it as %252F or
	// as extra segments, both of which gitlab.com answers 404.
	EscapedPath string
	AbsoluteURL string
	// Answers are the non-2xx statuses this request reads as an ANSWER rather than
	// a refusal: [Conn.Do] returns such a response with its body and no error, and
	// the family decodes the outcome from it. A 304 is never one: the read cache
	// settles every 304.
	Answers  []int
	MaxBytes int64
	// OwnerStatus is the status this request's route answers for an owner
	// [forgeapi.WithOwner] named and the instance does not resolve, zero on a
	// request no owner scopes. [Conn] maps exactly that status to
	// [forgeapi.CodeOwnerUnresolved] before the family's [Mapper] is asked.
	OwnerStatus int
	// Page is which page of a paged read this request asks for, so the
	// per-request record carries it. One where the read is not paged.
	Page int
	// Document says this request carries a GraphQL document rather than a REST
	// route, which the per-request record's transport attribute names: one family
	// degrades from the document arm to REST at runtime, and the line recording
	// the refusal that degraded it must name the document arm. A document request
	// is a read whatever verb carries it, unless Mutation says otherwise
	// ([Request.mutates]).
	Document bool
	// Mutation says this document is a GraphQL mutation, which travels as the
	// same POST a query does and changes the instance, so only the document's
	// own kind tells the two apart.
	Mutation bool
	// Credential says this request is a credential source's own, a token mint
	// or the lookup it needs, which changes no forge object: it meets neither
	// the mutation gate, nor the write mark of the call that asked for the
	// token, nor the interval. It takes one attempt: its source owns every
	// retry, since only the source can read a malformed 2xx as worth another.
	Credential bool
}

Request is one call this package makes for a family.

type RerunResolver

type RerunResolver func(ctx context.Context, op string, repo forgeapi.RepoRef, pr forgeapi.PRRef, pin string) (RunTarget, error)

RerunResolver is choosing which run a re-run targets, the one signature every family implements for forgeapi.PullRequests.RerunFailedChecks: the run the forge itself links to the pull request's checks verdict on its current head, the head pinned where pin is not empty, or a refusal sent before any write.

type Response

type Response struct {
	Header http.Header

	Ended string
	// Refused is the address of a hop the redirect policy refused, with the status
	// and headers that asked for it: a write's hop is refused, so a family reads
	// the successor here without sending the write again.
	Refused    string
	Body       []byte
	Status     int
	Redirected bool
	// Revalidated says the held answer served this call after a 304: a held field
	// ([familyFields]) the 304 omitted is the held value, which it did not confirm.
	Revalidated bool
	// contains filtered or unexported fields
}

Response is what one call answered: the status, the headers, the decoded-ready bytes, and whether a redirect was followed to get them.

Redirected records that THIS request took a hop, the rename witness: one product answers a renamed repository with a 301, and the final path cannot be the witness, because the same product answers a repo-addressed list with an id-addressed link header on repositories never renamed. Ended, where the last request went, is no second witness: it resolves the successor once a hop is recorded.

func (*Response) Quote

func (r *Response) Quote(text string) Quoted

Quote is text the instance answered in this exchange made safe to carry on an error a family builds from it, as Conn.Do makes a refusal's text safe: every secret the exchange carried redacted out of it ([quoter]), on one line, and bounded. A Response no exchange built holds no secret to redact.

type RunTarget

type RunTarget struct {
	ID      int64
	Project int64
}

RunTarget is the run or pipeline a re-run of a pull request's failed checks retries: its id, and the id of the project holding it where that is not the addressed repository, 0 where it is.

type Verdict

type Verdict struct {
	Code      string
	Needs     string
	Kind      forgeapi.ErrorKind
	Secondary bool
}

Verdict is a family's reading of one refusal: the code and kind the caller branches on, what the forge says the call needs, which becomes forgeapi.Error.Needs, and whether a rate limit is GitHub's secondary one, which becomes forgeapi.Error.Secondary.

Jump to

Keyboard shortcuts

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