Documentation
¶
Overview ¶
Package natsapi carries a service's HTTP API over NATS request/reply.
A caller that knows only the NATS controller and its own credentials can make the same calls it would make over HTTPS: the same verbs, paths, headers, payloads, and status codes. On the service side the request is turned into an *http.Request and dispatched through the service's normal router, so the ID middleware and every Bearer/RequireAdmin wrapper run unchanged and permissions cannot drift from the REST API.
Wire format ¶
Each request is one NATS message on
api.{service}.{METHOD}.{resource}
where resource is the first path segment after /api/v1/ (see ResourceToken). The headers carry the HTTP headers plus X-Path, the full request path and query, which is authoritative; the resource token exists only so a user JWT can restrict a caller to, say, api.admin_service.GET.>. The service rejects a request whose token does not match its path.
Bodies and responses stream in chunks so they are not bounded by the NATS max payload. A response is a sequence of messages on the reply inbox: the first carries X-Status and the response headers, every message carries X-Seq, and the last carries X-End. A request body larger than one chunk is pulled by the service: the caller publishes the first message with X-Body-Stream naming a subject it serves, and the service requests successive chunks from it until one arrives with X-End.
Service discovery uses the nats micro protocol: every served account answers $SRV.PING, $SRV.INFO and $SRV.STATS with the service name and one endpoint per verb.
Index ¶
- Constants
- Variables
- func EndpointSubject(service, method string) string
- func NewClient(nc *nats.Conn) *http.Client
- func NewRequest(ctx context.Context, method, service, path string, body io.Reader) (*http.Request, error)
- func ResourceToken(path string) string
- func Subject(service, method, path string) (string, error)
- func URL(service, path string) string
- func ValidService(name string) bool
- type Options
- type Service
- type Transport
Constants ¶
const ( // SubjectPrefix is the first token of every API subject. SubjectPrefix = "api" // HeaderPath carries the request path and query (authoritative). HeaderPath = "X-Path" // HeaderStatus carries the HTTP status code on the first reply message. HeaderStatus = "X-Status" // HeaderSeq numbers the messages of a chunked body from zero. HeaderSeq = "X-Seq" // HeaderEnd marks the last message of a chunked body. HeaderEnd = "X-End" // HeaderBodyStream names the subject a service pulls request body // chunks from when the body does not fit in the request message. HeaderBodyStream = "X-Body-Stream" // HeaderTransport is set on every bridged request so handlers and logs // can tell a NATS call from an HTTPS call. HeaderTransport = "X-Transport" // HeaderAccountID is the account header the ID middleware reads. HeaderAccountID = "X-Blackbox-AccountID" // TransportNATS is the value of HeaderTransport. TransportNATS = "nats" // DefaultQueueGroup is the queue group instances of a service share. DefaultQueueGroup = "api" // DefaultTimeout bounds the wait for each message of a chunked body. DefaultTimeout = 30 * time.Second // DefaultChunkSize is the body chunk size unless the connection's max // payload forces a smaller one. DefaultChunkSize = 256 << 10 // DefaultVersion is the micro service version when none is given. DefaultVersion = "1.0.0" )
Variables ¶
var ( // ErrNoService is returned when no instance of the service answered. ErrNoService = errors.New("natsapi: no service responded") // ErrBadURL is returned for a request URL that is not nats://{service}/path. ErrBadURL = errors.New("natsapi: request URL must be nats://{service}/api/...") // ErrNotConnected is returned when the transport has no connection. ErrNotConnected = errors.New("natsapi: not connected") )
var Methods = []string{"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"}
Methods lists the HTTP methods served over NATS; each is a micro endpoint.
Functions ¶
func EndpointSubject ¶
EndpointSubject is the wildcard subject a service subscribes to for one method.
func NewRequest ¶
func NewRequest(ctx context.Context, method, service, path string, body io.Reader) (*http.Request, error)
NewRequest builds a request for the Transport: method, service, and the path and query under /api/.
func ResourceToken ¶
ResourceToken returns the subject token for a request path: the first segment after the /api/{version}/ prefix, with characters that cannot appear in a subject token replaced by "_", or "_" when there is none. The query string is ignored.
func ValidService ¶
ValidService reports whether name can be a service token and micro name.
Types ¶
type Options ¶
type Options struct {
// Service is the subject token and micro service name, for example
// "admin_service". Required.
Service string
// Handler receives every bridged request, normally the service's
// router with all of its middleware. Required.
Handler http.Handler
// Version is the micro service version (semver). Default "1.0.0".
Version string
// Description is published in the micro service info.
Description string
// QueueGroup is shared by every instance of the service so that each
// request reaches exactly one of them. Default "api".
QueueGroup string
// ChunkSize bounds each body message; the connection's max payload
// lowers it when needed. Default 256 KiB.
ChunkSize int
// Timeout bounds the wait for each request body chunk pulled from the
// caller. Default 30s.
Timeout time.Duration
// Logger receives one line per request. Default: a new platform logger.
Logger *logger.Logger
}
Options configures a Service.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service bridges NATS requests to an http.Handler. One Service can serve any number of NATS connections, one per account, so a multi-tenant deployment serves every tenant with the same handler.
func New ¶
New validates the options and returns a Service that serves nothing until Serve is called.
func (*Service) Serve ¶
Serve starts answering requests on nc. accountID is the NATS account the connection belongs to; every request on it is pinned to that account (a mismatching X-Blackbox-AccountID is refused with 403) and the ID middleware sees it as the account header. Pass "" to skip the pin. Serving the same account twice is a no-op.
type Transport ¶
type Transport struct {
// Conn is the NATS connection. Required.
Conn *nats.Conn
// Timeout bounds the wait for each response message. Default 30s.
Timeout time.Duration
// ChunkSize bounds each request body message; the connection's max
// payload lowers it when needed. Default 256 KiB.
ChunkSize int
}
Transport is an http.RoundTripper that sends requests over NATS. Request URLs have the form nats://{service}/api/v1/..., so any code written against *http.Client works unchanged:
client := natsapi.NewClient(nc)
resp, err := client.Get(natsapi.URL("admin_service", "/api/v1/users"))
Authentication is the same as over HTTPS: set the Authorization bearer and, optionally, X-Blackbox-AccountID on the request.