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
- Variables
- func Bool(v bool) string
- func Check(dir string) error
- func Escape(v string) string
- func Float(v float64) string
- func Generate(dir string) ([]string, error)
- func Int(v int64) string
- func MustDuration(v string) time.Duration
- func NewHeader() http.Header
- func NewQuery() url.Values
- func Uint(v uint64) string
- type Auth
- type Breaker
- type BreakerConfig
- type Client
- type Doer
- type Fault
- type GenFault
- type GenFaults
- type Option
- func WithAttempts(n int) Option
- func WithAuth(a Auth) Option
- func WithBackoff(d time.Duration) Option
- func WithBaseURL(raw string) Option
- func WithBasicAuth(user, password string) Option
- func WithBreaker(b *Breaker) Option
- func WithHTTPClient(d Doer) Option
- func WithHeader(name, value string) Option
- func WithTimeout(d time.Duration) Option
- func WithToken(token string) Option
- func WithTracer(t trace.Tracer) Option
- type Request
- type StaleFault
- type State
- type StatusError
- type TransportError
Constants ¶
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.
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.
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.
const GeneratedFile = "zz_generated_client.go"
GeneratedFile is the name that the generator writes in each package that declares a client.
Variables ¶
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 Generate ¶
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 MustDuration ¶
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 ¶
NewHeader returns an empty header set. The generated code fills it, so the generated file imports no net/http.
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 (*Breaker) Allow ¶
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.
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.
type Doer ¶
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.
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.
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.
type Option ¶
type Option func(*Client)
Option configures a client.
func WithAttempts ¶
WithAttempts sets the number of attempts of one call, the first one included. A value below one keeps the default.
func WithAuth ¶
WithAuth states the authentication shape. The generated constructor passes the shape of the directive.
func WithBackoff ¶
WithBackoff sets the delay before the second attempt. Each further delay doubles it, up to MaxBackoff.
func WithBaseURL ¶
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 ¶
WithBasicAuth sets the user and the password.
func WithBreaker ¶
WithBreaker sets the circuit breaker. A nil breaker opens no circuit.
func WithHTTPClient ¶
WithHTTPClient sets the sender. A test passes its own.
func WithHeader ¶
WithHeader adds a header to every request.
func WithTimeout ¶
WithTimeout bounds one attempt. A zero value keeps the default.
func WithTracer ¶
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 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.