Files
archie/internal/natsrpc/natsrpc.go
T

143 lines
4.0 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"`
}
// NewEnvelope builds an Envelope from err, leaving Error empty on nil.
func NewEnvelope(err error) Envelope {
if err == nil {
return Envelope{}
}
return Envelope{Error: err.Error()}
}
// Err converts a populated Error string back into an error, or nil.
func (e Envelope) Err() error {
if e.Error == "" {
return nil
}
return errors.New(e.Error)
}
// 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(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(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
}
func serve(h func(context.Context, *nats.Msg)) nats.MsgHandler {
return func(msg *nats.Msg) {
ctx, span := StartServer(context.Background(), 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)
}
}