api

package
v0.11.2 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 63 Imported by: 0

Documentation

Overview

Package api is a platform module: a gRPC server and a REST gateway in front of it, with the interceptors every service needs and the OpenAPI description of the API.

The project writes proto files and handlers and registers its services from wireDomain; the module owns the servers, the interceptor chain, the gateway options, health, metrics, CORS and the documentation page.

Index

Constants

View Source
const (
	// ReasonExternalUnavailable is a provider that answered with an error the client
	// cannot fix: a 5xx, a refusal of the service's own credentials, an answer without
	// a result. The REST gateway answers 502 for it.
	ReasonExternalUnavailable = "EXTERNAL_UNAVAILABLE"
	// ReasonExternalTimeout is a provider that did not answer in time; DeadlineExceeded
	// is a 504.
	ReasonExternalTimeout = "EXTERNAL_TIMEOUT"
)

Reasons of the google.rpc.ErrorInfo the platform puts on a failure of an external provider, named as taply names them: a client and the gateway tell such a failure from the service's own by them.

View Source
const AllDocuments = "all"

AllDocuments names the whole description, /openapi.yaml and /docs, among the documents of API_DOCS_DOCUMENTS and to DocsAccess.

View Source
const ClientIPMetadataKey = "x-platform-client-ip"

ClientIPMetadataKey is the gRPC metadata key that carries the client address from the REST gateway to the gRPC server. The gateway sets it from the address the HTTP side resolved and drops an HTTP header of the same name, so a REST client cannot choose it. The gRPC server believes it only from a trusted peer: loopback, the address the server itself listens on, or the networks set in API_TRUSTED_PROXIES — a gRPC proxy there may set it too; the default of every private network does not count. From anyone else it is ignored and the peer address is the client.

x-forwarded-for metadata cannot serve this purpose: grpc-gateway appends the address of the HTTP peer to it, so its last entry is the proxy, the same for every client, and its first entries are whatever the client sent.

View Source
const ErrorDomain = "platform-go"

ErrorDomain is the domain of the ErrorInfo of ExternalUnavailable and ExternalTimeout.

View Source
const IdempotencyKeyHeader = "Idempotency-Key"

IdempotencyKeyHeader is the header a client sends to make a call safe to repeat.

Variables

View Source
var DefaultTrustedProxies = []netip.Prefix{
	netip.MustParsePrefix("127.0.0.0/8"),
	netip.MustParsePrefix("10.0.0.0/8"),
	netip.MustParsePrefix("172.16.0.0/12"),
	netip.MustParsePrefix("192.168.0.0/16"),
	netip.MustParsePrefix("::1/128"),
	netip.MustParsePrefix("fc00::/7"),
}

DefaultTrustedProxies are loopback and the private networks.

View Source
var ErrIdempotencyLeaseLost = errors.New("idempotency lease lost")

ErrIdempotencyLeaseLost is returned by Finish when the record was taken over by a repeat after the lease expired: the late outcome is not written.

Functions

func AddStreamInterceptor

func AddStreamInterceptor(app *platform.App, i grpc.StreamServerInterceptor)

AddStreamInterceptor adds a project stream interceptor in PhaseAuthenticate.

func AddStreamInterceptorAt added in v0.9.0

func AddStreamInterceptorAt(app *platform.App, p Phase, name string, i grpc.StreamServerInterceptor)

AddStreamInterceptorAt adds a project stream interceptor in the given phase.

func AddUnaryInterceptor

func AddUnaryInterceptor(app *platform.App, i grpc.UnaryServerInterceptor)

AddUnaryInterceptor adds a project interceptor, such as authentication, in PhaseAuthenticate: after recovery, metrics, logging, the rate limit by address and the translation of errors, and before the access check and request validation. AddUnaryInterceptorAt places one in another phase.

func AddUnaryInterceptorAt added in v0.9.0

func AddUnaryInterceptorAt(app *platform.App, p Phase, name string, i grpc.UnaryServerInterceptor)

AddUnaryInterceptorAt adds a project interceptor in the given phase. The name shows in Chain and in the log line of the chain at start; an empty one is taken from the function. A phase below PhaseRecover would run outside every recovery and panics; one above PhaseHandlerRecover runs inside the handler's recovery-free zone, covered by the outer recovery only.

api.AddUnaryInterceptorAt(app, api.PhaseGuard, "restaurant", restaurantGuard)

func Authorize added in v0.3.0

func Authorize(app *platform.App, unary grpc.UnaryServerInterceptor, stream grpc.StreamServerInterceptor)

Authorize adds an access check in PhaseAuthorize. It runs after the project's authentication — so the caller's identity is already in the context — and before request validation. The rbac module registers itself here.

func BodyTooLarge added in v0.4.0

func BodyTooLarge(r *http.Request) bool

BodyTooLarge reports whether the request body is over API_MAX_RECV_SIZE: declared larger, or found larger while it was read. A project middleware that reads the body itself, such as a signature check, answers 413 when it is.

func CORSHeaders added in v0.9.0

func CORSHeaders(app *platform.App, names ...string)

CORSHeaders lets browsers send the request headers the API cannot work without, such as a tenant header, on top of the platform's: Authorization, Content-Type, Accept, X-Request-ID and Idempotency-Key. They belong in code rather than in the environment of every stand; API_CORS_HEADERS adds more. It takes effect where API_CORS_ORIGINS allows an origin.

api.CORSHeaders(app, "X-Restaurant-Id")

func Chain added in v0.9.0

func Chain(app *platform.App) []string

Chain lists the unary interceptors of the server from the outside in, as "phase/name", for tests of a project and for reading the order. It is filled when the module starts.

func ClientIP added in v0.3.0

func ClientIP(ctx context.Context) string

ClientIP returns the address of the client. For a REST call it is the address the HTTP side resolved: the last X-Forwarded-For hop when the connection comes from a trusted proxy — the address the proxy itself saw, which the client cannot forge — and the connection address otherwise. For a direct gRPC call it is the peer address, or ClientIPMetadataKey when the peer is trusted.

func DeprecatedReplacements added in v0.9.0

func DeprecatedReplacements(app *platform.App, replacements map[string]string)

DeprecatedReplacements names what replaces each deprecated method, for the replacement label of api_deprecated_calls_total and the log line of a call, as taply keeps them. A method listed here counts as deprecated even without `option deprecated = true`; an empty replacement means there is none. Without this call the metric keeps the method label only.

api.DeprecatedReplacements(app, map[string]string{
	"/shop.v1.OrdersService/GetOrderOld": "/shop.v1.OrdersService/GetOrder",
})

func DocsAccess added in v0.10.0

func DocsAccess(app *platform.App, wrap func(document string, next http.Handler) http.Handler)

DocsAccess guards the descriptions the module serves: wrap gets the name of a document, AllDocuments for the whole one, and the handler of its description or of its page, and returns the handler to serve instead — one that asks for a password, a token or a role, or the same handler for a public document. API_DOCS and API_DOCS_DOCUMENTS decide what is served at all. A later call replaces an earlier one.

api.DocsAccess(app, func(doc string, next http.Handler) http.Handler {
	if doc == "public" {
		return next
	}
	return staffOnly(next)
})

func ExternalTimeout added in v0.9.0

func ExternalTimeout(provider, message string) error

ExternalTimeout is the error of a call whose external provider did not answer in time: DeadlineExceeded, a 504 over REST, with an ErrorInfo of ReasonExternalTimeout.

func ExternalUnavailable added in v0.9.0

func ExternalUnavailable(provider, message string) error

ExternalUnavailable is the error of a call that failed because an external provider failed: Unavailable with an ErrorInfo of ReasonExternalUnavailable that names the provider. Over REST it answers 502 Bad Gateway instead of the 503 of a plain Unavailable: a proxy such as nginx takes a 503 for a dead replica and stops sending to it, while the replica is fine and the provider is not. Idempotency lets a repeat run again, and the i18n module leaves the message as it is.

The message is "provider: message" and goes to the client as it is: pass a short fixed text, never err.Error() or the body of the provider's answer, which can hold credentials or a whole HTML page — those belong in the log. An empty provider gives the message alone and an ErrorInfo without the provider.

return nil, api.ExternalUnavailable("kaspi", "payment service unavailable")

func HTTPErrorHandler added in v0.4.0

func HTTPErrorHandler(app *platform.App, h runtime.ErrorHandlerFunc)

HTTPErrorHandler replaces how the REST side writes an error, for an API whose contract has its own error body. It receives every error of the gateway: from the handlers, from request decoding and routing, and a body over the limit as a *runtime.HTTPStatusError with 413. A failure of an external provider comes as the handler returned it; IsExternalUnavailable tells it, for the 502 the platform's writer answers. A later call replaces an earlier one.

func HandleHTTP

func HandleHTTP(app *platform.App, pattern string, h http.Handler)

HandleHTTP serves a plain HTTP route next to the gateway: webhooks, file downloads, anything that is not a gRPC call.

func IdempotencyMessages added in v0.11.0

func IdempotencyMessages(app *platform.App, texts IdempotencyKeyMessages)

IdempotencyMessages replaces the texts of the errors about the Idempotency-Key, for a project whose clients know other ones — taply's "Idempotency-Key is required in header" and "Idempotency-Key is too long".

func IdempotencyMethods added in v0.9.0

func IdempotencyMethods(app *platform.App, methods ...string)

IdempotencyMethods lists the methods whose Idempotency-Key counts, on top of those of RequireIdempotency; a key on any other method is ignored. Without the call the keys count on every method that changes something: one whose HTTP binding is not a GET and whose idempotency_level is not NO_SIDE_EFFECTS. The list wins over that default, as taply keeps its own.

func IdempotencyUser added in v0.3.0

func IdempotencyUser(app *platform.App, user func(ctx context.Context) string)

IdempotencyUser scopes idempotency keys to the caller: two users may use the same key. The project's authentication supplies the user. A key counts only for a caller this names: without the call, or for an empty user — an anonymous caller — the key is ignored, since anonymous callers would share one space of keys and could get each other's answers.

func IsExternalUnavailable added in v0.9.0

func IsExternalUnavailable(err error) bool

IsExternalUnavailable reports whether an error is Unavailable with an ErrorInfo of ReasonExternalUnavailable, whatever its domain: a status a project builds itself, as taply does, counts too; another code with that reason does not. For an api.HTTPErrorHandler that maps it like the platform.

func MaskLogBodies added in v0.9.0

func MaskLogBodies(app *platform.App, pathParts ...string)

MaskLogBodies keeps the bodies of requests whose path contains one of the given parts out of the access log: a failed request there is logged with [REDACTED] instead. For endpoints that take secrets, such as a certificate upload. API_LOG_BODIES_MASK_PATHS adds more per stand.

func MaxRecvSize added in v0.11.0

func MaxRecvSize(app *platform.App, bytes int)

MaxRecvSize sets the largest request message, in bytes, from code: a project that keeps the limit of uploads in its own settings reads them in wireDomain and passes it here. It wins over API_MAX_RECV_MB and caps HTTP bodies as that does; zero or less keeps the environment's. A change needs a restart, as the variable does.

func Methods added in v0.3.0

func Methods(app *platform.App) []string

Methods returns the full names of every registered gRPC method, such as /shop.v1.OrdersService/CreateOrder. It is filled when the module starts.

func Normalize added in v0.9.0

func Normalize(app *platform.App, fn func(proto.Message))

Normalize changes every request message before validation, after the project's authentication and guards: trimming strings, Unicode normalisation, as taply's strutil does. It runs in PhaseTransform+50, after the other transforms of the phase — the base fields the i18n module takes from translations are normalised too — and the functions run in the order they were added.

api.Normalize(app, strutil.Normalize)

func PublicMethods added in v0.3.0

func PublicMethods(app *platform.App, public func(method string) bool)

PublicMethods tells the API which methods are public, for their separate rate limit. The rbac module sets it from its policy.

func RateLimitKey added in v0.9.0

func RateLimitKey(app *platform.App, key func(ctx context.Context) string)

RateLimitKey names the principal of a call — a user, an API client, a device — for the second rate limit, API_PRINCIPAL_RATE_RPS per principal. It runs after the project's interceptors, so the authentication has put the principal into the context; an empty key, an anonymous call, is left to the limit by address. The limit by address still applies to every call.

func Register

func Register(app *platform.App, s Service)

Register adds a gRPC service and its gateway.

func RequestID added in v0.3.0

func RequestID(ctx context.Context) string

RequestID returns the id of the request: the X-Request-ID the client sent, or one generated for it. It works for HTTP handlers and for gRPC handlers behind the gateway.

func RequireIdempotency added in v0.3.0

func RequireIdempotency(app *platform.App, methods ...string)

RequireIdempotency makes the methods refuse a call without an Idempotency-Key header, as taply does for every method that creates something.

func StreamChain added in v0.9.0

func StreamChain(app *platform.App) []string

StreamChain lists the stream interceptors the same way.

func UseHTTP

func UseHTTP(app *platform.App, mw func(http.Handler) http.Handler)

UseHTTP wraps the whole REST side in a middleware.

Types

type Config

type Config struct {
	GRPCAddr    string   // gRPC listen address
	HTTPAddr    string   // REST gateway listen address
	MaxRecvSize int      // largest request message, bytes
	MaxSendSize int      // largest response message, bytes
	CORSOrigins []string // origins allowed to call the REST API from a browser; "*" allows any
	Docs        bool     // serve /openapi.yaml and the /docs page
	// DocsDocuments are the descriptions served when Docs is on: the documents of
	// api.openapi.documents by name, and AllDocuments for the whole one. Empty serves
	// all of them.
	DocsDocuments []string
	Reflection    bool // gRPC server reflection, for grpcurl and similar tools

	// CORS beyond the allowed origins. CORSHeaders are request headers a browser may
	// send on top of the platform's and those of api.CORSHeaders; CORSExpose are
	// response headers a page may read on top of X-Request-ID. CORSNoCredentials drops
	// Access-Control-Allow-Credentials, and with "*" among the origins the answer is a
	// literal "*" instead of the caller's origin. CORSMaxAge is how long a browser may
	// cache a preflight, in seconds; zero means a day.
	CORSHeaders       []string
	CORSExpose        []string
	CORSNoCredentials bool
	CORSMaxAge        int
	// CORSPreflightNoContent answers every OPTIONS request that gets no CORS answer — a
	// foreign origin, no origin, no API_CORS_ORIGINS — with 204 and no CORS headers, as
	// taply does, instead of passing it to the API, whose gateway answers 404 or 405
	// with a body.
	CORSPreflightNoContent bool

	// RateLimit per client address, and per principal; zero rates turn it off.
	RateLimit RateLimit

	// Idempotency: how long a finished call is remembered, and the lease a running one
	// holds its key with. The lease is extended while the handler runs, so it only
	// decides how soon a repeat may take over the key of a call that died.
	IdempotencyRetention time.Duration
	IdempotencyLease     time.Duration
	// Deprecated: IdempotencyLock is the old name of IdempotencyLease, used when the
	// lease is not set.
	IdempotencyLock time.Duration

	AccessLog       bool // log every HTTP request, as taply does
	LogBodies       bool // put the bodies of failed requests into the access log
	SecurityHeaders bool // taply's security response headers

	// LogBodiesMaskPaths keep bodies out of the access log: a failed request whose path
	// contains one of them is logged with [REDACTED] instead of its bodies, as taply does
	// for certificate uploads. api.MaskLogBodies adds paths in code.
	LogBodiesMaskPaths []string

	// MetricsTenantHeader names the request header whose value labels the call metrics
	// as tenant_name, "unknown" without it, as taply's do. Empty, the default, leaves the
	// metrics without the label. Every distinct value is a new series, so the header must
	// carry one of a bounded set of tenants.
	MetricsTenantHeader string

	// TrustedProxies are the networks whose X-Forwarded-For is believed. A request from
	// anywhere else is identified by its connection address, so a client reaching the
	// service directly cannot pose as another address. Empty means the private networks
	// and loopback, where a reverse proxy normally runs. On the gRPC side the networks
	// set here, never the default, may name the client with ClientIPMetadataKey;
	// loopback and the server's own address always may, since the gateway of this
	// process connects from them.
	TrustedProxies []netip.Prefix

	// Shutdown budgets, as in taply. HTTPStopTimeout is how long running REST calls may
	// finish once the server stops taking new ones; GRPCStopTimeout is how long running
	// gRPC calls may finish before their connections are cut. Zero waits as long as the
	// shutdown timeout allows.
	HTTPStopTimeout time.Duration
	GRPCStopTimeout time.Duration
}

Config holds module settings. Load fills it from the environment; the platform generator writes the Load call into the project's config.gen.go.

func Load

func Load(l *confx.Loader) Config

Load reads the module settings from environment variables.

type IdempotencyKeyMessages added in v0.11.0

type IdempotencyKeyMessages struct {
	Required     string // "Idempotency-Key is required in the header"
	TooLong      string // "Idempotency-Key is longer than 255 characters"
	NotPrintable string // "Idempotency-Key must be printable ASCII"
}

IdempotencyKeyMessages are the texts of the InvalidArgument a call gets for a bad Idempotency-Key. An empty one keeps the platform's.

type IdempotencyLeaseExtender added in v0.9.0

type IdempotencyLeaseExtender interface {
	// ExtendLease moves the expiry of an in_progress record from lease to until, and
	// reports false when the record no longer has that lease: it was taken over.
	ExtendLease(ctx context.Context, id int64, lease, until time.Time) (bool, error)
}

IdempotencyLeaseExtender is a store that extends the lease of a running call, so a handler that runs longer than the lease keeps its key. The memory and postgres stores implement it; with a store that does not, the lease is not extended.

type IdempotencyRecord added in v0.3.0

type IdempotencyRecord struct {
	ID          int64
	User        string
	Method      string
	Key         string
	Fingerprint string
	Status      string
	Code        int32
	Message     string
	// Response is the response message for a success and the google.rpc.Status the
	// client got for a failure, both in the binary proto format. Records written before
	// the status was kept have none for a failure, and are replayed from Code and
	// Message.
	Response  []byte
	ExpiresAt time.Time
	// Lease is the expires_at of the in_progress record the running call holds: the
	// token Finish checks, so a call whose key was taken over does not overwrite the
	// outcome of the one that took it. Zero means no check.
	Lease time.Time
}

IdempotencyRecord is one remembered call.

type IdempotencyStore added in v0.3.0

type IdempotencyStore interface {
	// Begin inserts an in_progress record, or returns the existing one with created false.
	Begin(ctx context.Context, rec IdempotencyRecord) (IdempotencyRecord, bool, error)
	// Retake moves a retry record, an in_progress one whose lock expired or a completed
	// one past its expiry back to in_progress until lockUntil. It reports false when
	// another call took it first.
	Retake(ctx context.Context, id int64, lockUntil time.Time) (bool, error)
	// Finish stores the outcome. With rec.Lease set it writes only while the record is
	// still in_progress with that expiry, and returns ErrIdempotencyLeaseLost otherwise.
	Finish(ctx context.Context, rec IdempotencyRecord) error
	// DeleteExpired removes records past their expiry.
	DeleteExpired(ctx context.Context, now time.Time) (int, error)
}

IdempotencyStore keeps the records. The postgres store is used when the postgres module is enabled; tests use the memory one.

func NewPostgresIdempotencyStore added in v0.3.0

func NewPostgresIdempotencyStore(ctx context.Context, pool *pgxpool.Pool) (IdempotencyStore, error)

NewPostgresIdempotencyStore creates the table if needed and returns the store the module uses with the postgres module.

type MemoryIdempotencyStore added in v0.3.0

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

MemoryIdempotencyStore keeps records in memory. It does not survive a restart and is not shared between instances: it is for tests.

func NewMemoryIdempotencyStore added in v0.3.0

func NewMemoryIdempotencyStore() *MemoryIdempotencyStore

NewMemoryIdempotencyStore creates an empty store.

func (*MemoryIdempotencyStore) Begin added in v0.3.0

func (*MemoryIdempotencyStore) DeleteExpired added in v0.3.0

func (s *MemoryIdempotencyStore) DeleteExpired(_ context.Context, now time.Time) (int, error)

func (*MemoryIdempotencyStore) ExtendLease added in v0.9.0

func (s *MemoryIdempotencyStore) ExtendLease(_ context.Context, id int64, lease, until time.Time) (bool, error)

ExtendLease implements IdempotencyLeaseExtender.

func (*MemoryIdempotencyStore) Finish added in v0.3.0

func (*MemoryIdempotencyStore) Retake added in v0.3.0

func (s *MemoryIdempotencyStore) Retake(_ context.Context, id int64, lockUntil time.Time) (bool, error)

type Module

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

Module implements platform.Module.

func New

func New(cfg Config, opts ...Option) *Module

New creates the module from ready settings.

func (*Module) GRPCAddr

func (m *Module) GRPCAddr() string

GRPCAddr is the address the gRPC server listens on.

func (*Module) HTTPAddr

func (m *Module) HTTPAddr() string

HTTPAddr is the address the REST gateway listens on.

func (*Module) Health

func (m *Module) Health(context.Context) error

Health reports whether both servers are serving.

func (*Module) Init

func (m *Module) Init(_ context.Context, app *platform.App) error

Init puts the registry into the container, so wireDomain can register services.

func (*Module) Name

func (m *Module) Name() string

func (*Module) Start

func (m *Module) Start(ctx context.Context) error

Start builds the servers from what the project registered and starts serving.

func (*Module) Stop

func (m *Module) Stop(ctx context.Context) error

Stop stops taking requests and lets the running ones finish within the shutdown timeout and the budgets of HTTP and gRPC; what is still running after it is cut off.

func (*Module) StopPhases added in v0.9.0

func (m *Module) StopPhases() []platform.StopPhase

StopPhases lets a phased shutdown stop the REST gateway first and gRPC last, with the job queue draining in between while gRPC clients are still served.

type Option

type Option func(*Module)

Option configures the module.

func WithIdempotencyStore added in v0.3.0

func WithIdempotencyStore(store IdempotencyStore) Option

WithIdempotencyStore sets where idempotency records are kept. Without it the module uses the database of the postgres module; tests pass a memory store.

func WithOpenAPI

func WithOpenAPI(fsys fs.FS) Option

WithOpenAPI gives the module the generated OpenAPI description: a directory holding openapi.bundle.yaml, the description in one file, or openapi.yaml, and the documents for one audience each, openapi.<name>.bundle.yaml. The generated wiring passes the embedded api/openapi directory.

type Phase added in v0.9.0

type Phase int

Phase places an interceptor in the chain of the gRPC server. The chain runs the phases from the outside in, in the order of their values; inside a phase the platform's interceptors come first, then the project's in the order they were added. The phases are a hundred apart, so a project that needs a place between two of them uses an offset, such as PhaseGuard+10.

The order is taply's: recovery, metrics and logging, the rate limit by address, the project's authentication, access checks and guards, request transforms, validation, idempotency, and a second recovery around the handler.

const (
	// PhaseRecover is the outer recovery: a panic in any interceptor becomes Internal.
	PhaseRecover Phase = iota * 100
	// PhaseObserve settles the client address, then metrics, logging and hiding errors
	// without a status behind a plain Internal.
	PhaseObserve
	// PhaseLimit is the rate limit by address and the count of deprecated methods.
	PhaseLimit
	// PhaseErrorsI18n translates error messages; it is outside authentication, so the
	// refusals of the project's authentication are translated too.
	PhaseErrorsI18n
	// PhaseAuthenticate is the project's authentication: it puts the caller into the
	// context, for rbac with rbac.WithRoles. AddUnaryInterceptor and
	// AddStreamInterceptor add here.
	PhaseAuthenticate
	// PhaseAuthorize is the access check; Authorize adds here, and the rbac module
	// through it.
	PhaseAuthorize
	// PhaseGuard is for checks that need the caller, such as the tenant a caller may
	// act for; the rate limit per principal runs here.
	PhaseGuard
	// PhaseTransform changes the request and the response with the caller known: the
	// translation of response fields, string normalisation.
	PhaseTransform
	// PhaseValidate checks the request against its protovalidate rules.
	PhaseValidate
	// PhaseAfterValidate sees a request that passed validation.
	PhaseAfterValidate
	// PhaseIdempotency remembers the outcome of a call with an Idempotency-Key.
	PhaseIdempotency
	// PhaseHandlerRecover is the inner recovery: a panic of the handler becomes Internal
	// before idempotency, which remembers it instead of holding the key.
	PhaseHandlerRecover
)

func (Phase) String added in v0.9.0

func (p Phase) String() string

String names the phase; an offset from a named phase reads as "guard+10".

type RateLimit added in v0.3.0

type RateLimit struct {
	RPS, PublicRPS     float64
	Burst, PublicBurst int

	// PrincipalRPS and PrincipalBurst limit each principal the project names with
	// RateLimitKey, whatever address the calls come from. Zero turns it off.
	PrincipalRPS   float64
	PrincipalBurst int

	// IPv6Prefix is how many leading bits of an IPv6 address make one client: 64 by
	// default, the block one subscriber normally gets, so a client cannot take a new
	// bucket with every address of its block. 128 limits every address on its own.
	IPv6Prefix int
}

RateLimit is a token bucket per client address, with separate limits for public methods, as in taply, and a second bucket per principal for authenticated calls.

type Registry

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

Registry holds what the project adds to the API. It lives in the container and is filled from wireDomain, before the module starts.

type RetryableError added in v0.3.0

type RetryableError interface{ IsRetryable() bool }

RetryableError marks an error after which a repeated call must run again instead of getting the cached failure — or, returning false, a failure to remember although its code would let a repeat run.

type Service

type Service struct {
	GRPC    func(*grpc.Server)
	Gateway func(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error
}

Service is a gRPC service of the project and, optionally, its REST gateway. Both functions are generated: RegisterXServer from protoc-gen-go-grpc and RegisterXHandler from protoc-gen-grpc-gateway.

api.Register(app, api.Service{
	GRPC:    func(s *grpc.Server) { ordersv1.RegisterOrdersServiceServer(s, handler) },
	Gateway: ordersv1.RegisterOrdersServiceHandler,
})

Jump to

Keyboard shortcuts

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