Files

182 lines
5.4 KiB
Go

// Package natsrpc is shared core NATS request/reply plumbing: client calls,
// server registration and a JSON error envelope.
package natsrpc
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"time"
"github.com/nats-io/nats.go"
"go.opentelemetry.io/otel/codes"
)
// Envelope is the error half of an RPC response. Embed it in a
// response type (it flattens into the same JSON object via
// encoding/json's anonymous-field promotion) to get Err/NewEnvelope for
// free instead of hand-rolling an `Error string` field and its checks.
type Envelope struct {
Error string `json:"error,omitempty"`
// Code names a sentinel from the table both ends pass to NewEnvelopeWith
// and ErrWith, so the receiver can match it with errors.Is.
Code string `json:"code,omitempty"`
}
// NewEnvelope builds an Envelope from err, leaving Error empty on nil.
func NewEnvelope(err error) Envelope {
return NewEnvelopeWith(err, nil)
}
// NewEnvelopeWith is NewEnvelope that also sets Code when err wraps one of the
// sentinels in codes (code name to sentinel).
func NewEnvelopeWith(err error, codes map[string]error) Envelope {
if err == nil {
return Envelope{}
}
env := Envelope{Error: err.Error()}
for code, sentinel := range codes {
if errors.Is(err, sentinel) {
env.Code = code
break
}
}
return env
}
// Err converts a populated Error string back into an error, or nil.
func (e Envelope) Err() error {
return e.ErrWith(nil)
}
// ErrWith is Err that rebuilds the sentinel named by Code from codes, so
// errors.Is matches it. The text is the sender's, unchanged.
func (e Envelope) ErrWith(codes map[string]error) error {
if e.Error == "" {
return nil
}
sentinel, ok := codes[e.Code]
if e.Code == "" || !ok {
return errors.New(e.Error)
}
return codedError{msg: e.Error, sentinel: sentinel}
}
// codedError keeps the sender's message and unwraps to the sentinel. It is not
// fmt.Errorf("%s: %w"), which would repeat the sentinel's text in the message.
type codedError struct {
msg string
sentinel error
}
func (e codedError) Error() string { return e.msg }
func (e codedError) Unwrap() error { return e.sentinel }
// Client sends timeout-bounded NATS request/reply calls.
type Client struct {
Conn *nats.Conn
// Timeout bounds each call when ctx has no deadline of its own.
Timeout time.Duration
}
// Request sends data to subject and returns the reply payload.
func (c *Client) Request(ctx context.Context, subject string, data []byte) ([]byte, error) {
if _, hasDeadline := ctx.Deadline(); !hasDeadline && c.Timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, c.Timeout)
defer cancel()
}
ctx, span := StartClient(ctx, subject)
defer span.End()
reply, err := c.Conn.RequestMsgWithContext(ctx, NewMsg(ctx, subject, data))
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
return nil, fmt.Errorf("%s: %w", subject, err)
}
return reply.Data, nil
}
// Call marshals req, sends it to subject, and unmarshals the reply
// into a Resp. It does not inspect Resp's error envelope -- callers
// that embed Envelope should check Err() themselves, since natsrpc
// has no way to know a bare Resp type embeds one.
func Call[Resp any](ctx context.Context, c *Client, subject string, req any) (Resp, error) {
var zero Resp
data, err := json.Marshal(req)
if err != nil {
return zero, fmt.Errorf("encode %s request: %w", subject, err)
}
reply, err := c.Request(ctx, subject, data)
if err != nil {
return zero, err
}
var resp Resp
if err := json.Unmarshal(reply, &resp); err != nil {
return zero, fmt.Errorf("%s: decode response: %w", subject, err)
}
return resp, nil
}
// Registration pairs a subject with its handler for RegisterAll.
type Registration struct {
Subject string
// Handler receives a context carrying the caller's trace and a SERVER
// span that ends when it returns.
Handler func(ctx context.Context, msg *nats.Msg)
}
// RegisterAll subscribes every registration and flushes, unsubscribing all
// of them on any failure. The returned func unsubscribes all.
func RegisterAll(ctx context.Context, nc *nats.Conn, regs []Registration) (unsubscribe func(), err error) {
subs := make([]*nats.Subscription, 0, len(regs))
unsubscribeAll := func() {
for _, s := range subs {
_ = s.Unsubscribe()
}
}
for _, r := range regs {
sub, subErr := nc.Subscribe(r.Subject, serve(ctx, r.Handler))
if subErr != nil {
unsubscribeAll()
return nil, fmt.Errorf("subscribe %s: %w", r.Subject, subErr)
}
subs = append(subs, sub)
}
if err := nc.Flush(); err != nil {
unsubscribeAll()
return nil, fmt.Errorf("flush subscriptions: %w", err)
}
return unsubscribeAll, nil
}
// serve roots each request in base without its cancellation, so a handler
// keeps the registering service's values but outlives the call that registered it.
func serve(base context.Context, h func(context.Context, *nats.Msg)) nats.MsgHandler {
base = context.WithoutCancel(base)
return func(msg *nats.Msg) {
ctx, span := StartServer(base, msg)
defer span.End()
h(ctx, msg)
}
}
// Respond marshals v and replies to msg, logging any failure.
func Respond(msg *nats.Msg, log *slog.Logger, pkg string, v any) {
data, err := json.Marshal(v)
if err != nil {
if log != nil {
log.Error(pkg+": encode response failed", "err", err)
}
return
}
if err := msg.RespondMsg(&nats.Msg{Data: data}); err != nil && log != nil {
log.Error(pkg+": respond failed", "err", err)
}
}