mirror of
https://github.com/luxfi/netrunner.git
synced 2026-07-27 00:04:23 +00:00
Per the project rule 'ZAP internal, ZIP edge': netrunner's 26-method
ControlService + PingService move off google.golang.org/grpc and
grpc-gateway onto a luxfi/zap envelope. Default builds now have ZERO
google.golang.org/grpc transitive deps.
New package: netrunner/zaprpc/
- protocol.go: MsgType (uint8 range, encoded in ZAP flags upper byte).
One stable wire ID per method. Append-only.
- dispatch.go: typed Bind[Req, Resp](d, msg, handler) — register a
'func(ctx, *Req) (*Resp, error)' handler. JSON encode/decode +
envelope framing happen here, handlers stay business-logic-only.
- server.go: thin wrapper around zap.Node hosting a Dispatcher.
- client.go: typed Call[Req, Resp](ctx, c, msg, req) — same DX as the
old gRPC client but transport is ZAP. Includes connect-retry around
the boot race.
server/bind.go: one-shot registration of all 26 RPC methods onto a
Dispatcher. The canonical map of 'what this server exposes'.
server/server.go: gRPC server + grpc-gateway HTTP bridge are gone.
Run() now starts the ZAP server and waits for rootCtx.Done. The
'soldier-on' isClientCanceled helper goes with the gRPC stream code.
client/client.go: full rewrite. Same Client interface (28 methods),
implementation is now one-line zaprpc.Call per method. StreamStatus
becomes a client-driven Status() poll on the requested interval —
ZAP has no native server-streaming, but the observable contract
(channel of ClusterInfo) is unchanged.
Deleted:
- rpcpb/rpc_grpc.pb.go (gRPC service stubs)
- rpcpb/rpc.pb.gw.go (grpc-gateway HTTP bridge)
The rpcpb message types (rpc.pb.go) stay — they're plain Go structs
with json: tags, used as the JSON payload format inside ZAP envelopes.
A future cleanup pass can replace them with hand-written structs to
drop google.golang.org/protobuf from the dep tree too.
go.mod cleanup: drop github.com/grpc-ecosystem/grpc-gateway/v2,
google.golang.org/grpc, google.golang.org/genproto/googleapis/api.
Pin luxfi/proto v1.0.0 (was luxfi/protocol v0.0.4 — stale rename
artifact). Add luxfi/zap v0.2.0.
Tests: zaprpc/zaprpc_test.go round-trips request/response and proves
the error path propagates through the envelope.
No backwards compat — forwards perfection per the project rule.
158 lines
4.1 KiB
Go
158 lines
4.1 KiB
Go
// Copyright (C) 2021-2026, Lux Industries Inc. All rights reserved.
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
|
|
|
package zaprpc
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/luxfi/zap"
|
|
)
|
|
|
|
// ClientConfig configures a netrunner ZAP client.
|
|
type ClientConfig struct {
|
|
// NodeID is this client's identifier (sent during handshake).
|
|
NodeID string
|
|
// ServerAddr is "host:port" of the netrunner ZAP server.
|
|
ServerAddr string
|
|
// DialTimeout bounds the initial TCP+handshake.
|
|
DialTimeout time.Duration
|
|
Logger *slog.Logger
|
|
}
|
|
|
|
// Client is a typed RPC client against a netrunner ZAP server.
|
|
//
|
|
// Wire layer only — domain-specific methods live in netrunner/client.
|
|
type Client struct {
|
|
node *zap.Node
|
|
serverID string
|
|
closed chan struct{}
|
|
closeOnce sync.Once
|
|
dialedOnce sync.Once
|
|
}
|
|
|
|
// NewClient connects to the netrunner ZAP server at cfg.ServerAddr.
|
|
func NewClient(cfg ClientConfig) (*Client, error) {
|
|
if cfg.NodeID == "" {
|
|
cfg.NodeID = "netrunner-client"
|
|
}
|
|
if cfg.DialTimeout == 0 {
|
|
cfg.DialTimeout = 10 * time.Second
|
|
}
|
|
if cfg.Logger == nil {
|
|
cfg.Logger = slog.Default()
|
|
}
|
|
|
|
node := zap.NewNode(zap.NodeConfig{
|
|
NodeID: cfg.NodeID,
|
|
ServiceType: "_netrunner._tcp",
|
|
Port: 0,
|
|
Logger: cfg.Logger,
|
|
NoDiscovery: true,
|
|
})
|
|
if err := node.Start(); err != nil {
|
|
return nil, fmt.Errorf("zaprpc client start: %w", err)
|
|
}
|
|
|
|
dialCtx, cancel := context.WithTimeout(context.Background(), cfg.DialTimeout)
|
|
defer cancel()
|
|
if err := connectWithDeadline(dialCtx, node, cfg.ServerAddr); err != nil {
|
|
node.Stop()
|
|
return nil, err
|
|
}
|
|
|
|
// One netrunner client talks to exactly one server — pick that peer's
|
|
// node ID once. ConnectDirect handshake learned it.
|
|
peers := node.Peers()
|
|
if len(peers) == 0 {
|
|
node.Stop()
|
|
return nil, fmt.Errorf("zaprpc client: no peer after connecting to %s", cfg.ServerAddr)
|
|
}
|
|
|
|
return &Client{
|
|
node: node,
|
|
serverID: peers[0],
|
|
closed: make(chan struct{}),
|
|
}, nil
|
|
}
|
|
|
|
// Call sends a typed request and waits for the typed response. ctx bounds
|
|
// the round trip. JSON encode/decode + ZAP framing happen inside.
|
|
func Call[Req, Resp any](ctx context.Context, c *Client, msgType MsgType, req *Req) (*Resp, error) {
|
|
raw, err := Encode(msgType, req, "")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
msg, err := zap.Parse(raw)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("zaprpc call: parse outgoing: %w", err)
|
|
}
|
|
|
|
respMsg, err := c.node.Call(ctx, c.serverID, msg)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var resp Resp
|
|
if err := Decode(respMsg, &resp); err != nil {
|
|
return nil, err
|
|
}
|
|
return &resp, nil
|
|
}
|
|
|
|
// CallVoid is Call's sibling for methods whose request struct is empty —
|
|
// avoids forcing the caller to type `&rpcpb.HealthRequest{}` for every ping.
|
|
func CallVoid[Resp any](ctx context.Context, c *Client, msgType MsgType) (*Resp, error) {
|
|
type empty struct{}
|
|
return Call[empty, Resp](ctx, c, msgType, &empty{})
|
|
}
|
|
|
|
// Close stops the underlying ZAP node.
|
|
func (c *Client) Close() error {
|
|
c.closeOnce.Do(func() {
|
|
close(c.closed)
|
|
c.node.Stop()
|
|
})
|
|
return nil
|
|
}
|
|
|
|
// Done returns a channel closed when the client is shut down.
|
|
func (c *Client) Done() <-chan struct{} {
|
|
return c.closed
|
|
}
|
|
|
|
// Node returns the underlying ZAP node — used by streaming subscriptions
|
|
// that need to install a server-push handler before issuing the subscribe call.
|
|
func (c *Client) Node() *zap.Node {
|
|
return c.node
|
|
}
|
|
|
|
// ServerID returns the connected server's node ID. Useful for explicit
|
|
// targeting in custom ZAP messages.
|
|
func (c *Client) ServerID() string {
|
|
return c.serverID
|
|
}
|
|
|
|
// connectWithDeadline retries ConnectDirect until the context expires.
|
|
// First-boot races are common — the server's listener may not be up yet
|
|
// even though the client has been told to dial.
|
|
func connectWithDeadline(ctx context.Context, n *zap.Node, addr string) error {
|
|
var lastErr error
|
|
for {
|
|
if err := n.ConnectDirect(addr); err == nil {
|
|
return nil
|
|
} else {
|
|
lastErr = err
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return fmt.Errorf("zaprpc client: dial %s timed out: %w", addr, lastErr)
|
|
case <-time.After(100 * time.Millisecond):
|
|
}
|
|
}
|
|
}
|