client

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package client holds the HTTP client generator and the runtime that its output calls, S13.

The declaration is an interface with comment directives. `avero generate` reads the directives one time and writes a plain implementation. The generated file imports no reflect, and no call path reads a struct tag. See design rule 2 and AN-2.

//avero:client base="https://api.example.com" auth="bearer"
type Example interface {
    //avero:GET /things/{id}
    GetThing(ctx context.Context, id string) (Thing, error)
}

The runtime carries the timeout, the retry with backoff, the circuit breaker and the OTel span of each call. A status outside the two hundreds becomes a StatusError, which keeps the response reachable through errors.As.

Index

Constants

View Source
const (
	// DefaultThreshold is the number of failures in a row that opens the
	// circuit.
	DefaultThreshold = 5
	// DefaultCooldown is the time that the circuit stays open.
	DefaultCooldown = 30 * time.Second
)

The defaults of the circuit breaker.

View Source
const (
	// DefaultTimeout bounds one attempt.
	DefaultTimeout = 10 * time.Second
	// DefaultAttempts is the number of attempts of one call, the first one
	// included.
	DefaultAttempts = 3
	// DefaultBackoff is the delay before the second attempt. Each further
	// delay doubles it.
	DefaultBackoff = 100 * time.Millisecond
	// MaxBackoff bounds one delay.
	MaxBackoff = 2 * time.Second
	// TracerName names the instrumentation of the client.
	TracerName = "github.com/alternayte/avero/codegen/client"
	// MaxErrorBody is the number of bytes of a failed response that a
	// StatusError keeps.
	MaxErrorBody = 1 << 20
)

The defaults of one client. An option replaces each one.

View Source
const (
	// ClientDirective declares an interface as a client.
	ClientDirective = "//avero:client"
	// MethodPrefix starts a method directive, such as //avero:GET.
	MethodPrefix = "//avero:"
)

The directive prefixes that the generator reads.

View Source
const GeneratedFile = "zz_generated_client.go"

GeneratedFile is the name that the generator writes in each package that declares a client.

Variables

View Source
var ErrBreakerOpen = errors.New("client: the circuit breaker is open")

ErrBreakerOpen states that the circuit is open, so the client sent no request. The call fails at once and the service gets time to recover.

Functions

func Bool

func Bool(v bool) string

Bool returns true or false.

func Check

func Check(dir string) error

Check reports a generated client that is not current. It writes nothing.

func Escape

func Escape(v string) string

Escape encodes one path parameter.

func Float

func Float(v float64) string

Float returns the shortest form of a floating point value.

func Generate

func Generate(dir string) ([]string, error)

Generate writes the client of each package under dir that declares one. It returns the paths that it wrote, in order. A package with no client interface gets no file.

func Int

func Int(v int64) string

Int returns the decimal form of a signed value.

func MustDuration

func MustDuration(v string) time.Duration

MustDuration parses a duration and panics on a fault. The generated code calls it with a value that the generator already proved, so it cannot panic at run time.

func NewHeader

func NewHeader() http.Header

NewHeader returns an empty header set. The generated code fills it, so the generated file imports no net/http.

func NewQuery

func NewQuery() url.Values

NewQuery returns an empty query. The generated code fills it, so the generated file imports no net/url.

func Uint

func Uint(v uint64) string

Uint returns the decimal form of an unsigned value.

Types

type Auth

type Auth string

Auth states the authentication that a client sends.

const (
	// AuthNone sends no credential.
	AuthNone Auth = "none"
	// AuthBearer sends the token in the Authorization header.
	AuthBearer Auth = "bearer"
	// AuthBasic sends the user and the password in the Authorization
	// header.
	AuthBasic Auth = "basic"
)

The authentication shapes that a directive names.

type Breaker

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

Breaker is the circuit breaker of one client.

The state machine holds three states. Closed passes every call and counts the failures in a row. The failure that reaches the threshold opens the circuit. Open fails every call with ErrBreakerOpen until the cooldown ends, and then it passes one probe as half-open. A probe that succeeds closes the circuit. A probe that fails opens it again for another cooldown.

func NewBreaker

func NewBreaker(cfg BreakerConfig) *Breaker

NewBreaker builds a circuit breaker.

func (*Breaker) Allow

func (b *Breaker) Allow() error

Allow reports whether a call can go out. It returns ErrBreakerOpen when the circuit is open, and it takes the probe of a half-open circuit.

func (*Breaker) Failure

func (b *Breaker) Failure()

Failure records a call that failed. The failure that reaches the threshold opens the circuit, and a failed probe opens it again.

func (*Breaker) State

func (b *Breaker) State() State

State returns the state of the circuit. It moves an open circuit to half-open when the cooldown ended.

func (*Breaker) Success

func (b *Breaker) Success()

Success records a call that reached an answer.

type BreakerConfig

type BreakerConfig struct {
	// Threshold is the number of failures in a row that opens the circuit.
	// A value below one takes the default.
	Threshold int
	// Cooldown is the time that the circuit stays open. A value below one
	// takes the default.
	Cooldown time.Duration
	// Now returns the time. A test replaces it.
	Now func() time.Time
}

BreakerConfig states one circuit breaker.

type Client

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

Client is the runtime of one generated client. The generated code holds it as a field and calls Do.

func New

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

New builds the runtime of one client. The generated constructor calls it.

func (*Client) Do

func (c *Client) Do(ctx context.Context, req Request, out any) error

Do sends the request, retries it under the policy of the client, and decodes the body into out. A nil out reads no body.

type Doer

type Doer interface {
	Do(req *http.Request) (*http.Response, error)
}

Doer sends one request. The standard http.Client satisfies it, and a test passes its own.

type Fault

type Fault struct {
	// Message states the fault.
	Message string `json:"message"`
	// Repair states what to do. It is one sentence.
	Repair string `json:"repair"`
}

Fault is one client fault that no server caused, such as a body that does not encode. It states the repair in one sentence. See DX-7.

func (*Fault) Error

func (f *Fault) Error() string

Error returns the message and the repair.

type GenFault

type GenFault struct {
	// File is the file that holds the fault.
	File string `json:"file"`
	// Line is the line of the directive or of the method.
	Line int `json:"line"`
	// Column is the column of the directive or of the method.
	Column int `json:"column"`
	// Message states the fault.
	Message string `json:"message"`
	// Repair states what to do. It is one sentence.
	Repair string `json:"repair"`
}

GenFault is one generation fault. It names a file, a line and a column in code that the person wrote, and it states the repair in one sentence. It never points into a generated file or into Avero. See DX-6 and DX-7.

func (*GenFault) Error

func (f *GenFault) Error() string

Error prints the position, the message and the repair.

type GenFaults

type GenFaults struct {
	Faults []*GenFault `json:"faults"`
}

GenFaults holds every fault of one run. The generator reports every fault, not only the first.

func (*GenFaults) Error

func (l *GenFaults) Error() string

Error returns a count and one entry for each fault.

func (*GenFaults) Unwrap

func (l *GenFaults) Unwrap() []error

Unwrap returns each fault so that errors.As reaches a single one.

type Option

type Option func(*Client)

Option configures a client.

func WithAttempts

func WithAttempts(n int) Option

WithAttempts sets the number of attempts of one call, the first one included. A value below one keeps the default.

func WithAuth

func WithAuth(a Auth) Option

WithAuth states the authentication shape. The generated constructor passes the shape of the directive.

func WithBackoff

func WithBackoff(d time.Duration) Option

WithBackoff sets the delay before the second attempt. Each further delay doubles it, up to MaxBackoff.

func WithBaseURL

func WithBaseURL(raw string) Option

WithBaseURL sets the address that every path joins. The generated constructor passes the address of the directive, and an option after it replaces the address, so a test points the client at httptest.

func WithBasicAuth

func WithBasicAuth(user, password string) Option

WithBasicAuth sets the user and the password.

func WithBreaker

func WithBreaker(b *Breaker) Option

WithBreaker sets the circuit breaker. A nil breaker opens no circuit.

func WithHTTPClient

func WithHTTPClient(d Doer) Option

WithHTTPClient sets the sender. A test passes its own.

func WithHeader

func WithHeader(name, value string) Option

WithHeader adds a header to every request.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout bounds one attempt. A zero value keeps the default.

func WithToken

func WithToken(token string) Option

WithToken sets the bearer token.

func WithTracer

func WithTracer(t trace.Tracer) Option

WithTracer sets the tracer. The default reads the global provider.

type Request

type Request struct {
	// Op names the method of the interface, such as Example.GetThing. The
	// span carries it.
	Op string
	// Method is the HTTP method.
	Method string
	// Path is the path of the call, with every parameter already in place.
	Path string
	// Query holds the query parameters.
	Query url.Values
	// Header holds the headers of this call.
	Header http.Header
	// Body becomes the JSON body. A nil value sends no body.
	Body any
	// Idempotent states that a retry is safe. The generated code sets it
	// from the HTTP method, and a directive can state it for a POST.
	Idempotent bool
}

Request states one call. The generated code fills it.

type StaleFault

type StaleFault struct {
	// Path is the generated file.
	Path string `json:"path"`
	// Reason states what is wrong.
	Reason string `json:"reason"`
}

StaleFault reports a generated file that a run of the generator would change.

func (*StaleFault) Error

func (f *StaleFault) Error() string

Error states the fault and the repair.

type State

type State string

State is one state of the circuit breaker.

const (
	// StateClosed passes every call.
	StateClosed State = "closed"
	// StateOpen fails every call at once.
	StateOpen State = "open"
	// StateHalfOpen passes one probe.
	StateHalfOpen State = "half-open"
)

The states of the circuit breaker.

type StatusError

type StatusError struct {
	// Op names the method of the interface.
	Op string `json:"op"`
	// Method is the HTTP method of the call.
	Method string `json:"method"`
	// URL is the address of the call.
	URL string `json:"url"`
	// Status is the status code of the answer.
	Status int `json:"status"`
	// Body holds the answer, up to MaxErrorBody bytes.
	Body []byte `json:"body"`
	// Response is the answer. Its body is already read, and it reads again
	// from the bytes of Body, so a caller can read it one more time.
	Response *http.Response `json:"-"`
}

StatusError states an answer with a status outside the two hundreds.

It keeps the response, so errors.As reaches the header and the body:

var status *client.StatusError
if errors.As(err, &status) && status.Status == http.StatusNotFound {
    log.Info("absent", "body", string(status.Body))
}

func (*StatusError) Error

func (e *StatusError) Error() string

Error states the call and the status.

func (*StatusError) RetryAfter

func (e *StatusError) RetryAfter() time.Duration

RetryAfter returns the delay that the server asked for, or zero.

type TransportError

type TransportError struct {
	// Op names the method of the interface.
	Op string `json:"op"`
	// URL is the address of the call.
	URL string `json:"url"`
	// Err is the fault of the transport.
	Err error `json:"-"`
}

TransportError states that the request never reached an answer. A retry can help, so the policy of the client retries it for an idempotent method.

func (*TransportError) Error

func (e *TransportError) Error() string

Error states the call and the fault.

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

Unwrap returns the fault of the transport, so errors.Is reaches context.DeadlineExceeded.

Directories

Path Synopsis
internal
example
Package example holds the client that the tests of the generator drive.
Package example holds the client that the tests of the generator drive.

Jump to

Keyboard shortcuts

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