connectnats

package module
v0.0.0-...-4237af8 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 26 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

connectnats

connectnats 是 connect-go v2 的 NATS 传输实现。它把每个 RPC 映射成一条由两个 NATS subject 组成的会话,使 connect 的生成代码、拦截器和 handler 可以直接跑在 NATS 之上,而不需要 net/http。

状态:v1.0.0 待发布(协议 v1,已冻结)

线协议只有一个版本 Connect-Protocol-Version: 1:一元调用是「一条请求、一条响应」的单消息形态,流式调用使用帧(open/ready/msg/end 等)。1.0.0 冻结第一版规范;不兼容变更留到 v2.x,1.x 不维护双版本、不做能力协商、不提供兼容矩阵。

已完成 M0–M8 与 1.0 收敛:wire 层(帧、header/元数据、subject、end-stream、压缩协商、序号/窗口/credit)、单消息一元、服务端与客户端传输、四种流型、流控与保活、运维与安全(Shutdown、Close、并发上限、size 与 header 预算、subject 防注入、ServerInfo/ClientInfo、日志与指标)、客户端响应池与服务端请求池(订阅足迹与并发无关)、与 connectinprocess 的契约测试,以及发布基准。发布门禁见 docs/v1.0-release-checklist.md。

2026-12-02 状态:仓库在 github.com/chenjpu/connectnats,ci 全绿(build / -race test / lint / vuln,run 46794608389)。nightly 的 cluster job 已在 run 46804079478 跑通(单机 3 个容器节点,有 route;不是跨机器),soak job 同 run 进行中。v1.0.0 尚未打 tag。route/leaf 拓扑与网络分区未验证。

为什么

connect-go v2 已经把 handler 与传输分离:

  • 客户端通过 connect.Transport.NewClientStream 获取 connect.ClientStream;
  • 服务端由传输层枚举 connect.Server.Specs() 安装路由,并在收到调用时执行 connect.Server.Call。

这意味着第三方可以新增传输而不改生成代码。NATS 是云原生场景里常见的事件/消息总线,具备 subject 路由、queue group 负载均衡、请求/响应和集群能力,很适合用来承载 RPC。本项目要解决的是 NATS 与 connect 流语义之间的差距:没有请求方向结束信号、没有端到端流控、at-most-once、单条消息默认受 max_payload 限制(服务端默认 1 MiB,可调)。

设计准则只有一条:以 connect 自身的语义为基准。协议里凡 connect 已经定义的(流生命周期、三组 header、错误模型、codec 与压缩协商、end-stream message),一律复用其语义与词汇;connect 没有的(ready、credit 窗口、序号、cancel、ping),才补充,并逐条说明「NATS 缺什么」。

设计要点

  • 一元是一条请求、一条响应:请求发布到方法 subject(参与 queue group),响应发布到请求方给定的 respInbox。没有 open/ready,也没有每调用的 reqInbox,happy path 2 条消息、1 个 RTT。
  • 流式每 RPC 两个 subject:reqInbox(C→S)与 respInbox(S→C),每个方向只有一个发布者,天然有序且流粘性稳定。两侧都池化订阅:客户端一条 *.<stream>.resp,服务端一条 *.<route>.req,订阅足迹与并发无关。
  • open 走 procedure subject:<prefix>.<service>.<method>,queue group 只在“选择实例”时生效。
  • 流式自建帧协议:open / ready / headers / msg / close-send / end / cancel / credit / ping。
  • 流式显式 ready 握手:服务端注册好请求路由,并在 ready 中返回自己分配的 reqInbox,客户端才向该 subject 发后续数据,消除 NATS 的“无订阅即丢弃”竞态;open 是 ready 之前唯一允许发布的帧。
  • 终止即 connect 的 end-stream message:流式的 end 与一元的错误响应共用 {"error": …, "metadata": …},状态码与 trailer 一次到达。
  • 双向 credit 窗口:端到端背压;窗口被违反时由 NATS 的慢消费者检测兜底并暴露为 DataLoss。
  • 两种形态、四种流型:一元走单消息,服务端流/客户端流/双向流走帧;bidi 自 v0.2 起不再标记 experimental。
  • 诚实的语义:core NATS 是 at-most-once,序号缺口会映射为 DataLoss,不做静默重试。

完整设计见 docs/design.md,线协议规范见 docs/protocol.md。

单消息一元

一元调用不是帧:客户端把一条消息发布到 <prefix>.<service>.<method>,服务端把一条响应发布到请求方给出的 respInbox。请求与响应都不带 Connect-Frame,版本 header 为 1;成功响应带 Connect-Res-* 与 Connect-Trailer-*,错误响应用 Connect-Error-Code / Connect-Error-Message,正文仍是 connect 的 end-stream message,因此 details 与 debug 不丢失。

判别是结构性的:没有 Connect-Frame 即单消息一元;声明为 unary 的帧式 open 以 Unimplemented 拒绝,流式方法收到单消息请求同样拒绝。两者不互相降级。

取消走服务级 subject <prefix>.<service>._cancel.<streamID>:客户端从自己的响应 inbox 派生 key,服务端每个服务一条常数订阅(不参与 queue group,未持有该调用的副本只做一次 map 查表后丢弃)。流式调用保留 reqInbox 上的 cancel 帧。

相对 v0.2 的帧式一元(历史数据,仅用于理解收益;来源 docs/decisions.md「Q3 实测结论」):

v0.2 帧式一元 v1 单消息一元
每调用消息数 5.00 2.00
顺序延迟 ≈126µs ≈96µs
饱和吞吐(96–384 goroutine) 基准 2.0–2.3×

以上是本机 CPU/loopback 成本,不是跨机器、跨网络或跨版本的性能承诺。

运维前提与边界:

  • 调用方需有 publish: <prefix>.<service>._cancel.> 权限;方法名不得以 _cancel/ 开头(Mount 以 InvalidArgument 拒绝),名字恰好是 _cancel 仍合法。
  • 取消不绑定调用者身份。有效边界是 NATS 账号与 ACL(一个应用一套账号,调用方 subscribe 仅限自己的 inbox),细节与残余风险见 docs/decisions.md「Q3 补充:取消的可信边界」。
  • 未验证。route/leaf 拓扑、网络分区、跨机器 RTT,以及网关是否限流 _cancel.> 均未测。

API

import (
    "connectrpc.com/connect/v2"
    "github.com/chenjpu/connectnats"
    "github.com/nats-io/nats.go"
)

// 客户端
conn, err := nats.Connect(nats.DefaultURL)
transport, err := connectnats.NewTransport(conn)
defer transport.Close() // 结束在飞调用并释放订阅;不关闭 conn
client := pingv1connect.NewPingServiceClient(connect.NewClient(transport))

// 服务端
server := connect.NewServer()
pingv1connect.RegisterPingServiceHandler(server, pingServer{})
service, err := connectnats.Mount(conn, server, connectnats.WithQueueGroup("ping"))
defer service.Shutdown(ctx)

可用选项:

WithSubjectPrefix("connect.rpc")
WithInboxPrefix("_INBOX")
WithQueueGroup("connect")
WithCodecs(...)
WithCompressors(...)
WithSendCodec("proto")
WithSendCompression("identity")
WithCompressMinBytes(1024)
WithReadMaxBytes(4 << 20)
WithSendMaxBytes(0)
WithHeaderMaxBytes(64 << 10) // 0 = 关闭
WithStreamMaxBytes(0)        // 0 = 关闭;WithWindow(0) 时必须显式设置
WithWindow(16)
WithReadBuffer(1024)     // 仅当 WithWindow(0) 时生效
WithKeepalive(30*time.Second, 90*time.Second)
WithMaxConcurrentCalls(1024) // 服务端与客户端通用;0 = 不限
WithSendStallTimeout(0) // 0 = 关闭
WithLogger(nil)         // nil = 不输出日志
WithMetrics(Metrics{})  // 零值 = 不回调
WithMicroDiscovery(MicroConfig{Version: "1.0.0"}) // NATS micro ($SRV) 发现,默认关闭

WithMicroDiscovery 让 nats micro ls|info|stats 等工具看到 Mount 挂载的服务:每个 Service 新增一条 $SRV.> 订阅,按 nats.go/micro 的 JSON 协议应答 PING、INFO、STATS。它不改变 v1 线协议;统计复用 WithMetrics 的 StreamEnded(一条流 = 一次请求,只统计服务端),与用户回调组合而不是替换。服务端需要 subscribe: $SRV.> 与应答发布权限(publish: _INBOX.> 或 allow_responses),version 必须显式配置。发布名默认是 service token 按点换横线(common.v1.AttachmentService → common-v1-AttachmentService),生成代码无需额外配置;需要缩短或消歧时用 MicroConfig.Services[token].Name 覆写。详见 docs/micro-adapter.md。

example_test.go 中的 ExampleNewTransport、ExampleMount 与 ExampleWithMetrics 展示客户端、服务端与指标接线,go test 会编译它们(示例假定 nats.DefaultURL 上有可用的 NATS)。

需要一个可直接运行、覆盖四种 RPC 形状的端到端示例(含 .proto、生成代码与 server/client 两个命令)时,见 example/。

Mount 在调用时快照 connect.Server.Specs() 并安装路由,因此 Register 必须发生在 Mount 之前;Mount 之后新增的方法不会被路由,调用会落到 unknown handler(Unimplemented)。这与 connecthttp 里「先注册后启动 mux」的顺序一致,但更容易被忽略,因为 NATS 没有显式的 Serve。

与 connect-http 的差异

connectnats 与 connecthttp 共用 connect 的流契约、拦截器和同一份 protoc-gen-connect-go 生成代码,但不是同一条线协议:HTTP 客户端不能直连 NATS 挂载的服务,反之亦然。

维度 connecthttp connectnats
互操作 Connect / gRPC / gRPC-Web 客户端 只有 connectnats 客户端;跨网关需翻译 subject 与 Connect-Req-* / Connect-Res-* 前缀
负载均衡 连接粘性,或在前面挂 per-request LB 一元逐次经 queue group;流一旦 open 就粘在接单实例
背压 HTTP/2 字节窗口 自建 credit 窗口,v1 按消息条数(默认 16)
可靠性 连接错误可重试 core NATS at-most-once;序号缺口报 DataLoss,传输层不重试
Connect GET 支持幂等 GET 不支持,全部经 open 建立
并发闸门 无内置上限 WithMaxConcurrentCalls 默认 1024,超限立即 ResourceExhausted,不排队
无订阅者 连接拒绝 / HTTP 5xx nats-server 的 Status: 503 映射为 Unavailable
CallInfo.Protocol connect / grpc / grpcweb nats(connectnats.ProtocolName)
CallInfo.PeerAddr 对端地址 空字符串;NATS 没有 HTTP 连接的对端概念
CallInfo.TransportInfo connecthttp.* *connectnats.ClientInfo / *connectnats.ServerInfo
metadata 形状 裸 HTTP header 请求 Connect-Req-*、响应 Connect-Res-*、trailer Connect-Trailer-*
一元响应基数 客户端发现 0/多条 → Unimplemented 0 条由服务端报 Unimplemented;多条时首条已发布,第二条 Send 返回 io.EOF

按 CallInfo.Protocol、PeerAddr 或 TransportInfo 分支的拦截器、指标和追踪必须显式处理上表的后三行,不能假设 HTTP 传输的字段形状。两端的共同契约仍然是:Send 成功不代表对端已处理;Receive 读到 io.EOF 才释放资源;失败统一以 *connect.Error 暴露。

仓库结构

connectnats-go/
├── connectnats.go      # Option、默认值与校验
├── transport.go        # connect.Transport 实现:一元走单消息,流式走帧
├── unary.go            # 单消息一元的 header 与错误常量
├── unary_client.go     # 单消息一元客户端:请求/响应各一条消息
├── unary_server.go     # 单消息一元服务端:校验、取消、Shutdown
├── client_stream.go    # 流式客户端:open、reader、Send/Receive/Close
├── message.go          # 收发消息的编解码与压缩(客户端/服务端共用)
├── server.go           # Mount、Service、Shutdown
├── server_dispatch.go  # 单消息/帧分派、open 校验、并发信号量
├── server_stream.go    # 流式服务端:ready、Receive/Send、finalize
├── wire.go             # 帧编解码与校验
├── header.go           # header 常量、canonicalize、错误构造
├── metadata.go         # 用户 metadata ↔ Connect-Req-/Connect-Res-
├── subject.go          # procedure ↔ subject 映射与 inbox 校验
├── status.go           # end-stream message(error + metadata)
├── compression.go      # 编码协商
├── flow.go             # 序号与窗口/credit 的纯逻辑
├── keepalive.go        # 共享保活循环:最小堆 + 单 ticker,每 Transport/Service 一个
├── stall.go            # WithSendStallTimeout:等待 credit 的超时状态
├── log.go              # WithLogger:协议异常/panic 的日志记录
├── metrics.go          # WithMetrics:成对起止、终止码与 credit 阻塞回调
├── micro.go            # WithMicroDiscovery:$SRV 发现选项、身份与 endpoint 计划
├── micro_server.go     # $SRV.> 订阅、PING/INFO/STATS 应答与内部计数
├── errors.go           # 错误映射与 scrub
├── observability.go    # CallInfo 辅助:ServerInfo / ClientInfo
├── doc.go
├── stream_test.go      # 流式服务端/客户端的集成测试
├── unary_test.go       # 单消息一元:往返、错误、取消、Shutdown、指标
├── singlemessage_test.go # 手写单消息的测试驱动(rawUnaryCall)
├── bidi_test.go        # 双向流集成测试
├── flow_test.go        # 窗口/credit、超窗、慢消费者、丢帧检测
├── stall_test.go       # WithSendStallTimeout 的客户端/服务端停滞
├── keepalive_test.go   # 共享保活循环与 activityClock 的单元测试
├── keepalive_integration_test.go # 双侧保活超时
├── deadline_test.go    # deadline 发 end 与 Close/取消传播
├── reconnect_test.go   # NATS 重启后流以 Unavailable 终止
├── fault_test.go       # ready 前服务端消失、业务提交后实例失联
├── soak_test.go        # 夜间长稳(CONNECTNATS_SOAK_DURATION 开启)
├── shutdown_test.go    # Shutdown 排空:等在途 handler、并发调用、滚动重启重试
├── size_test.go        # WithReadMaxBytes/WithSendMaxBytes、header 预算与 max_payload 预检
├── security_test.go    # subject 注入防护:通配符 / 系统 subject / 错误前缀不建订阅
├── observability_test.go # ServerInfo/ClientInfo 字段、脱敏与查找语义
├── log_test.go         # WithLogger 的协议异常、丢帧与 panic 记录
├── metrics_test.go     # WithMetrics 的起止配对、终止码与 credit 阻塞
├── micro_test.go       # $SRV 应答、计数、错误口径与订阅足迹
├── conformance_test.go # 与 connectinprocess 对跑的行为一致性用例
├── example_test.go     # NewTransport / Mount / WithMetrics 的可编译示例
├── example/            # 可运行示例:.proto + server/client 两个命令(见 example/README.md)
├── transport_bench_test.go # 发布基线:unary、bidi ping-pong、服务端流吞吐
├── cluster_test.go     # 双实例 queue group:unary 分摊、bidi 粘性
├── compression_test.go # 编码协商、控制帧明文与 compressMinBytes 两侧阈值
├── internal/natstest/  # 进程内 NATS 测试辅助
├── CHANGELOG.md        # 版本变更与已知限制
└── docs/
    ├── design.md             # 总体设计(含双向流)
    ├── protocol.md           # 线协议规范(规范性)
    ├── development-plan.md   # 里程碑与详细开发清单
    └── decisions.md          # 设计决策记录

M0–M8 已落地,1.0.0 的发版收尾项见 docs/development-plan.md §19。

已知限制与非目标(1.0)

  • at-most-once:core NATS 不重传,序号缺口报 DataLoss;需要可靠投递时用 JetStream 或应用层确认,不做断点续传。
  • 单条消息 ≤ max_payload:超出映射为 ResourceExhausted,v1 不做分块(chunk)。end 超限时先丢 details,再去 metadata 与 message、保留原 code;完整错误只留在服务端日志。
  • 一元是单消息形态:handler 不 Send 时服务端报 Unimplemented;Send 第二条会被丢弃并返回 io.EOF,客户端看到的是第一条成功响应。connecthttp 在客户端发现多条响应时才报 Unimplemented,单消息形态无法回写这个判定。
  • 不做传输层自动重试;是否重试由调用方按 connect.Code 与 Spec.IdempotencyLevel 决定。
  • 不实现 NATS micro 的服务注册与端点模型(micro.AddService);只提供默认关闭的 $SRV 发现与统计适配器(WithMicroDiscovery),不替代 NATS 自身的鉴权、TLS、账号体系。
  • 若账号 ACL 使用 allow_responses,默认每个请求只允许 1 个响应;服务端流/双向流需放宽 max。流式调用的请求 inbox 由服务端分配,客户端还需要显式 publish: <inboxPrefix>.>(或收窄到 *.req 子树),因为后续帧不再是对 open 的响应。一元调用不需要这两项。
尺寸与内存预算(1.0 默认值)

两个上限不是同一个旋钮,默认部署里先撞到的是服务端那个:

上限 默认值 由谁决定 超出时
max_payload 1 MiB NATS 服务端配置 发送方在发布前被 nats.go 拒绝,ResourceExhausted
WithReadMaxBytes 4 MiB 本库 解压后超过即 ResourceExhausted

因此有效接收上限 = min(WithReadMaxBytes, conn.MaxPayload())。默认组合(4 MiB / 1 MiB)的实际上限是 1 MiB;要收 4 MiB 的消息,必须先调大服务端的 max_payload。NewTransport/Mount 在 WithReadMaxBytes 大于 conn.MaxPayload() 且设置了 WithLogger 时打一条 WARN,但不失败——服务端设置可能正要调整,静默截断比一行日志更意外。

每流未消费字节上界 = min(WithWindow × 有效接收上限, WithStreamMaxBytes);WithStreamMaxBytes 默认 0,表示只受窗口约束。默认窗口 16,因此每流约 16 MiB(服务端仍是默认 max_payload 时);把 max_payload 提到 4 MiB 后是 64 MiB。服务端总量上界 ≈ WithMaxConcurrentCalls × 每流上界,默认 1024 时这个数字很大,是上界而不是常态:实际占用由发送与消费速率决定。内存敏感部署应显式收窄 WithMaxConcurrentCalls 或设置 WithStreamMaxBytes,不要依赖默认值。

结果不确定性与重试

core NATS 是 at-most-once,传输层无法判断业务是否已执行。调用方只能按「客户端可观察的结果」推断:

阶段 客户端可观察 业务是否可能已执行 建议
请求未派发(入参/配置错误、无订阅) InvalidArgument/Unavailable 否 可按幂等性重试
已发布请求但未收到响应(流式为 open 未等到 ready,一元为请求已发出) Unavailable/超时 可能 仅幂等操作可重试
服务端已接收、handler 未执行 客户端不可区分 否 不假设
handler 执行中 客户端不可区分 部分 不假设
业务已提交、响应丢失 Unavailable/Canceled/DataLoss 是 用业务幂等键去重
客户端主动取消/断连 Canceled/Unavailable 可能 同上一行

规则:

  1. 传输层不自动重试,也不提供「可安全重试」标志;没有协议信号能证明业务未执行。
  2. 有副作用的调用必须携带业务幂等键(请求 ID / 去重键)。StreamID 只用于日志关联,跨重试不稳定。
  3. DataLoss 表示消息缺失,不能推断「服务端未执行」。
  4. 是否重试由调用方或拦截器根据 connect.Code 与 Spec.IdempotencyLevel 决定。
  5. 一元调用必须带 deadline。帧形态的流有保活可以判定服务端消失,单消息形态没有可往返的帧:响应一旦丢失,Receive 只会等响应或 ctx,没有 deadline 就永久阻塞(TestUnaryWithoutDeadlineBlocks)。这不是缺陷,是 at-most-once 传输的边界,v1 不加看门狗——它无法区分「慢」与「丢」,还会把隐藏超时强加给已经设置 deadline 的调用方。

本地开发

本仓库与 connect-go 默认按模块依赖编译:

require (
    connectrpc.com/connect/v2 v2.0.0
    github.com/nats-io/nats.go v1.56.0
)

若要与本地 connect-go 联调,可临时追加:

replace connectrpc.com/connect/v2 => ../connect-go

提交前移除 replace。

提交前门禁(顺序与 Windows 细节见 docs/dev-environment.md):

gofmt -l .
go vet ./...
golangci-lint run ./...
go test ./...

CI 另外跑 go test -race -count=1 -timeout=20m ./...。-race 需要 cgo:Windows 本机没有可用的 gcc 时跑不了,用 WSL 执行(命令见 dev-environment.md §5),不要在提交信息里把「本机 go test 通过」当作 -race 证据。

文档

文档 内容
docs/design.md 总体架构、客户端/服务端、双向流、流控、错误、安全
docs/protocol.md 唯一的 v1 线协议:单消息一元、流式帧、header、状态载荷、序号与 credit
docs/development-plan.md M0–M8 里程碑、任务 ID、验收标准、测试矩阵、CI 门禁
docs/decisions.md 关键取舍与备选方案
docs/v0.2-gap-analysis.md v0.2 差异分析、协议状态表与 P0 实施计划
docs/v1.0-release-checklist.md 1.0.0 发布门禁清单
docs/micro-adapter.md $SRV 发现适配器(1.0.0,opt-in,默认关闭)的设计与取舍
docs/dev-environment.md 本机工具链、提交前门禁、Windows 坑与 WSL -race 路径
CHANGELOG.md 版本变更与 1.0.0 发布说明

许可证

Apache License 2.0,见 LICENSE。

Documentation

Overview

Package connectnats provides a NATS transport for connect-go v2.

The package implements version 1 of the Connect-over-NATS wire protocol, the only version 1.x speaks. The architecture is described in docs/design.md, the normative wire protocol in docs/protocol.md, and the implementation plan in docs/development-plan.md. The wire layer (frame parsing, header handling, subject mapping, end-stream messages, flow-control arithmetic), the server transport, and the client transport support unary, server-streaming, client-streaming, and bidirectional-streaming calls end to end. Unary calls are one request message and one response message; streaming calls use frames. A bidirectional stream allows one Send and one Receive to run concurrently, and CloseSend closes only the request direction: the handler may keep sending. Streaming calls of every shape use the same session, credit, and termination path. Trailing metadata travels in the end frame for streams and in the response header for unary calls, so no separate trailer frame exists.

In short, the transport has two forms. A unary RPC publishes one request on a per-procedure subject, so queue groups can balance calls across service instances, and the server answers with one message on the caller's reply inbox; there is no open/ready handshake and no per-call request inbox. A streaming RPC is a session made of two NATS subjects: one for client-to-server frames and one for server-to-client frames. Its open frame is published on the per-procedure subject, and after that all frames stay on the two per-RPC subjects, which keeps a stream pinned to the instance that accepted it. Neither side subscribes per call for either form: the client pools every response inbox under one wildcard subscription per Transport, and the server pools every request inbox under one per Service, so the subscription footprint does not grow with concurrency. Unary calls reuse the streaming message codec, compression, deadline, and cancellation rules but terminate with a single response. Keepalive is shared: one loop covers every stream of a Transport or Service, so idle streams do not each own a timer goroutine. Termination of a stream uses connect's own end-stream message shape, carrying the error verdict and the response trailer in a single frame.

Logging is opt-in: the transport is silent unless WithLogger supplies a logger, and then it records only protocol violations and handler panics.

Discovery for NATS micro tooling is also opt-in: WithMicroDiscovery publishes every mounted service on $SRV.PING, $SRV.INFO, and $SRV.STATS with the io.nats.micro.v1 schema, under the service token with "." replaced by "-" ("/acme.ping.v1.PingService/Ping" becomes "acme-ping-v1-PingService"). It adds one $SRV.> subscription per Service, derives its request, error, and timing counters from the same Metrics stream lifecycle, and leaves the wire protocol unchanged. It is a server-side capability; a Transport ignores the option.

Delivery is at-most-once: core NATS does not retransmit, so a gap in the per-direction sequence is reported as connect.CodeDataLoss, and a lost end frame leaves the caller unable to tell whether the handler ran. The transport never retries on its own and exposes no "safe to retry" signal; callers that need at-least-once delivery must use JetStream or their own idempotency keys. A unary call is one request and one response on the wire, so it has no keepalive frame to prove the server is still there: always pass a context with a deadline. Without one, a response lost after the request was published blocks Receive until the connection dies.

The default receive limit is 4 MiB, but the effective limit is min(WithReadMaxBytes, the server's max_payload), and NATS defaults max_payload to 1 MiB. NewTransport and Mount log one warning when the configured limit cannot be reached.

Index

Examples

Constants

View Source
const ProtocolName = "nats"

ProtocolName is the value this transport reports in connect.CallInfo.Protocol. It is distinct from the HTTP transport protocol names (connect, grpc, grpcweb), so interceptors and metrics that branch on the protocol need a case for it.

Variables

This section is empty.

Functions

This section is empty.

Types

type ClientInfo

type ClientInfo struct {
	// StreamID is the token this transport generated for the call. A streaming
	// client shares it with the server in the open frame; a single-message
	// unary client encodes it in the response inbox.
	StreamID string
	// RequestSubject is the subject the client publishes requests on. A
	// single-message unary call publishes to the method subject; a streaming
	// call publishes to the server-assigned inbox returned in ready.
	RequestSubject string
	// ResponseSubject is the inbox the client subscribes to for responses.
	ResponseSubject string
	// ServerURL is the URL of the NATS server this transport was connected to
	// when the stream opened, with any password redacted. It is a snapshot:
	// after a reconnect it may name a server the call no longer uses.
	ServerURL string
}

ClientInfo is the transport-specific information attached to a client-side connect.CallInfo.TransportInfo. The transport fills it when it opens the stream, before the first request is published, and it never changes afterwards.

func ClientInfoForContext

func ClientInfoForContext(ctx context.Context) (*ClientInfo, bool)

ClientInfoForContext returns the ClientInfo of the current client-side call. It reports false outside a call opened by a Transport, including in server handlers and in client interceptors that run before the transport opens the stream.

To read the info after a call returns, attach the CallInfo to the context with connect.NewClientContext first, exactly as with connecthttp.ClientInfoForContext.

type Metrics

type Metrics struct {
	// StreamStarted runs once a stream is accepted by a service or created by
	// a transport. Every StreamStarted is followed by exactly one StreamEnded.
	StreamStarted func(StreamMetrics)
	// StreamReady runs once when the ready handshake completes: the client
	// accepted the server's ready frame, or the server published its own. The
	// latency is the same value StreamEnded later reports as OpenLatency. A
	// stream that ends before ready has no StreamReady callback.
	StreamReady func(StreamMetrics, time.Duration)
	// StreamEnded runs once when the stream releases its resources. The error
	// is nil for a clean completion and the terminal error otherwise; use
	// connect.CodeOf to bucket failures.
	StreamEnded func(StreamMetrics, *connect.Error)
	// CreditBlocked runs each time Send has to wait because the peer's receive
	// window is full. A Send that only waits for the handshake does not count.
	CreditBlocked func(StreamMetrics)
}

Metrics observes stream lifecycle counters. Every field is optional: a nil callback is skipped, and the zero value disables metrics.

Callbacks are invoked from stream goroutines, possibly concurrently, but never while the transport holds a stream lock. They must be fast and must not block: a callback runs before the operation that reported it returns, so blocking it stalls that operation. Calling Close or Send on the reporting stream is safe; calling a method that waits for the same stream to make progress (Receive, for example) deadlocks the caller. An active-stream gauge can be derived by pairing StreamStarted with StreamEnded.

type MicroConfig

type MicroConfig struct {
	// Version is the SemVer-compatible version reported for every service.
	// nats micro tooling expects SemVer, but the adapter only requires a
	// non-empty value. Mount returns CodeInvalidArgument when it is empty.
	Version string
	// Description is the human-readable description reported by $SRV.INFO.
	// Empty is allowed.
	Description string
	// Metadata annotates every service. The map is copied; nil is reported as
	// the empty object, matching nats.go/micro.
	Metadata map[string]string
	// Services overrides Version, Description, Metadata, and the published name
	// for individual services, keyed by the service token from the procedure. A
	// zero field inherits the value above; a non-nil Metadata map replaces the
	// global one. A key that does not name a registered service is rejected by
	// Mount.
	Services map[string]MicroServiceInfo
}

MicroConfig configures the NATS micro discovery adapter for one Mount.

The adapter answers the read-only control verbs defined by nats.go/micro: $SRV.PING, $SRV.INFO, and $SRV.STATS, in the io.nats.micro.v1 response schema. Every service registered on the connect.Server passed to Mount is published; Services only overrides the identity of individual services.

Discovery is metadata, not a data path. Enabling it adds one $SRV.> subscription per Mount, leaves the v1 wire protocol untouched, and does not take part in dispatch. A deployment that also runs nats.go/micro services must not reuse a service name: both implementations would answer the same control subjects.

type MicroServiceInfo

type MicroServiceInfo struct {
	// Name replaces the published service name. The default is the service
	// token from the procedure with every "." replaced by "-", so
	// "/acme.ping.v1.PingService/Ping" publishes as "acme-ping-v1-PingService"
	// and needs no configuration. That derived name is a single NATS token and
	// is usually what a monitor already shows for the equivalent nats.go/micro
	// service.
	//
	// Set Name only to shorten the label or to disambiguate a collision, since
	// control subjects are $SRV.<verb>.<name>: the published name must be a
	// single token (no ".", wildcard, or whitespace) and must be unique within
	// the Mount.
	Name string
	// Version overrides MicroConfig.Version when non-empty.
	Version string
	// Description overrides MicroConfig.Description when non-empty.
	Description string
	// Metadata replaces MicroConfig.Metadata when non-nil. An empty non-nil
	// map reports an empty object rather than the global metadata.
	Metadata map[string]string
}

MicroServiceInfo overrides the discovery identity of one service. Zero values inherit the corresponding MicroConfig field.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures a client transport or a mounted service. Options that only apply to one side are ignored by the other.

func WithCodecs

func WithCodecs(codecs ...connect.Codec) Option

WithCodecs replaces the supported codecs. The first is preferred when a client does not express a choice. Defaults to protobuf binary and JSON.

func WithCompressMinBytes

func WithCompressMinBytes(size int) Option

WithCompressMinBytes sets the smallest payload worth compressing. Payloads below it are sent uncompressed even when an encoding is negotiated, which mirrors connect's compressMinBytes. Default 1024.

func WithCompressors

func WithCompressors(compressors ...connect.Compressor) Option

WithCompressors replaces the supported compression algorithms. Compression is disabled when called with no arguments. Default gzip.

func WithHeaderMaxBytes

func WithHeaderMaxBytes(size int) Option

WithHeaderMaxBytes bounds the total size of one received frame's headers: the sum of its keys and values, across every value. A frame over the limit fails the call with CodeResourceExhausted: on the server when it arrives in the open frame, on the client when it arrives in any response frame. Zero means no limit; Default 64 KiB, which bounds request and response metadata without being reached by normal RPCs.

Trailers are not affected: they travel in the end frame's payload, not in headers.

func WithInboxPrefix

func WithInboxPrefix(prefix string) Option

WithInboxPrefix sets the root of the per-RPC inbox space. It must match the prefix the NATS server uses for client inboxes, which is "_INBOX" unless custom_inbox_prefix is configured server-side. Default "_INBOX".

func WithKeepalive

func WithKeepalive(interval, timeout time.Duration) Option

WithKeepalive sets how often an idle stream sends a ping and how long it waits before declaring the peer dead. Default 30s/90s.

WithKeepalive(0, 0) disables keepalive; a peer that dies silently is then detected only by the call's context or by the NATS connection closing. The keepalive state is shared per Transport and per Service: one heap and at most one goroutine cover every stream.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the logger used for protocol violations and handler panics. A nil logger, the default, disables logging: the transport is silent on the happy path and does not log expected outcomes such as cancellation, an expired deadline, or a peer that closed its connection.

Protocol records carry stream (Connect-Stream), procedure, subject (the open subject), code, and error. Panic records carry the panic value and stack instead of code. The logger must be safe for concurrent use, as the standard library's loggers are.

func WithMaxConcurrentCalls

func WithMaxConcurrentCalls(limit int) Option

WithMaxConcurrentCalls bounds how many RPCs one mounted service handles at once and how many streams one Transport keeps open. Excess calls fail immediately with CodeResourceExhausted rather than queueing. Default 1024; zero disables the limit.

func WithMetrics

func WithMetrics(metrics Metrics) Option

WithMetrics installs stream lifecycle callbacks. The zero Metrics value, the default, disables them. The callbacks report started and ended streams, the terminal code of each, and every Send that had to wait for the peer's receive window.

Example

ExampleWithMetrics wires the optional stream callbacks. The zero Metrics value disables them, so the transport stays silent by default.

package main

import (
	"connectrpc.com/connect/v2"
	"github.com/chenjpu/connectnats"
)

func main() {
	metrics := connectnats.Metrics{
		StreamStarted: func(info connectnats.StreamMetrics) {
			_ = info // count active streams by pairing with StreamEnded
		},
		StreamEnded: func(info connectnats.StreamMetrics, err *connect.Error) {
			_ = info
			_ = err // nil is a clean end; connect.CodeOf(err) buckets failures
		},
		CreditBlocked: func(info connectnats.StreamMetrics) {
			_ = info // Send had to wait for the peer's receive window
		},
	}
	_ = connectnats.WithMetrics(metrics)
}

func WithMicroDiscovery

func WithMicroDiscovery(config MicroConfig) Option

WithMicroDiscovery publishes every mounted service on the NATS micro control subjects $SRV.PING, $SRV.INFO, and $SRV.STATS.

The adapter is disabled by default: when it is not enabled, Mount creates no $SRV subscription and no counters. Enabling it requires Version to be non-empty; Mount otherwise returns CodeInvalidArgument.

Each service is published under its service token with "." replaced by "-", so a generated "/acme.ping.v1.PingService/Ping" becomes "acme-ping-v1-PingService". MicroServiceInfo.Name overrides the label, and Mount rejects two services that would publish under one name because $SRV.PING.<name> must have one answer.

The adapter needs subscribe permission on "$SRV.>" to receive the control requests, plus publish permission for the reply subject it answers on: the monitor's inbox (usually "_INBOX.>") unless the user configures allow_responses. Answering is a plain msg.Respond publish, so subscribe permission alone leaves $SRV.PING unanswered. It is a server-side capability: a Transport ignores this option.

Statistics follow the Metrics contract: one stream is one request, whether it is unary or streaming, and only server-side streams are counted. The reported processing time is StreamMetrics.Duration, which includes queueing and transport time rather than handler CPU time alone. num_errors counts ends whose code is not Canceled, DeadlineExceeded, Unavailable, or DataLoss; Internal is counted as a business error because the transport cannot tell a handler-authored Internal from a local protocol violation. See docs/micro-adapter.md for the full mapping.

func WithQueueGroup

func WithQueueGroup(group string) Option

WithQueueGroup sets the NATS queue group used by mounted services. Instances in the same group share the call load; instances in different groups each receive a copy of every open frame. Default "connectnats".

func WithReadBuffer

func WithReadBuffer(size int) Option

WithReadBuffer sets the NATS subscription capacity used when the window is unlimited. Ignored otherwise. Default 1024.

func WithReadMaxBytes

func WithReadMaxBytes(size int) Option

WithReadMaxBytes limits the decompressed size of a received message. Zero means no limit. Default 4 MiB, matching connect's HTTP transports.

The effective receive limit is min(this, conn.MaxPayload()): nats.go rejects a message larger than the server's max_payload before the peer publishes it, so a larger value here cannot be reached. NewTransport and Mount log one warning when that happens and a logger is configured; they do not fail, because the server setting may be about to change.

func WithSendCodec

func WithSendCodec(name string) Option

WithSendCodec sets the codec used by a client for its first request. The server's codec comes from the wire, so it ignores this option.

func WithSendCompression

func WithSendCompression(name string) Option

WithSendCompression sets the compression a client applies to its request payloads. Default "identity"; the response coding follows the request.

func WithSendMaxBytes

func WithSendMaxBytes(size int) Option

WithSendMaxBytes limits the uncompressed size of a sent message. Zero means no limit.

func WithSendStallTimeout

func WithSendStallTimeout(timeout time.Duration) Option

WithSendStallTimeout bounds how long a Send may wait for the peer's receive window to open. When the window stays full for the whole timeout, Send returns CodeResourceExhausted instead of blocking until the peer consumes a message or the call context ends. Zero, the default, waits indefinitely.

The limit applies to both client and server Send. It is a per-stream error, not a protocol failure: the stream stays open, and the caller decides whether to abandon it with Close or the call's context.

func WithStreamMaxBytes

func WithStreamMaxBytes(size int) Option

WithStreamMaxBytes bounds the payload bytes one stream may buffer before the application consumes them: responses waiting in a client's Receive queue and requests waiting in a server's Receive queue. Bytes are counted as they arrived on the wire, so a compressed message counts compressed and headers are not counted. A stream that would exceed the limit fails with CodeResourceExhausted and stops reading; other streams are unaffected.

The check is off by default. With the default WithWindow(16) and the default 4 MiB WithReadMaxBytes, the message-count window already caps a stream at about 64 MiB; a smaller byte budget would fail streams that connect's HTTP transports serve, because HTTP applies backpressure instead of failing. Set this option for a tighter bound, or when the count window is disabled.

With WithWindow(0) it is required: without a count window the byte budget is the only bound on pending messages.

func WithSubjectPrefix

func WithSubjectPrefix(prefix string) Option

WithSubjectPrefix sets the root of the open-subject space. Default "connect.rpc".

func WithWindow

func WithWindow(size int) Option

WithWindow sets how many un-consumed messages this side is willing to buffer for one stream. Zero disables the count window and is intended for benchmark experiments; it requires WithStreamMaxBytes. Default 16.

type ServerInfo

type ServerInfo struct {
	// Subject is the method subject the call arrived on, such as
	// "connect.rpc.acme.ping.v1.PingService.Ping".
	Subject string
	// RequestSubject is the server-assigned inbox that a streaming client
	// publishes later request frames on, sent back in the ready frame
	// (Connect-Request-Subject). It is empty for a single-message unary call,
	// which carries its only request in the initial message.
	RequestSubject string
	// ResponseSubject is the inbox the service publishes responses on, taken
	// from the request's reply subject.
	ResponseSubject string
	// StreamID identifies the call. A streaming client supplies it in
	// Connect-Stream; for a single-message unary call it is derived from the
	// response inbox. It is advisory: the transport does not trust it for
	// routing, but it is the natural correlation key for server logs and
	// traces.
	StreamID string
	// QueueGroup is the queue group the mounted service uses for this call,
	// or empty when the service does not load-balance.
	QueueGroup string
}

ServerInfo is the transport-specific information attached to a server-side connect.CallInfo.TransportInfo. It is a snapshot of the request: the service fixes it before the handler runs, and it never changes afterwards, so handlers may read it without synchronization.

The transport fills it from whichever wire form carried the call: the single message used by unary RPCs, or the open frame used by streaming RPCs.

NATS does not expose the publisher's address or identity, so there is no peer address here; the stream ID is the handle that correlates logs across both sides (protocol.md §3).

func ServerInfoForContext

func ServerInfoForContext(ctx context.Context) (*ServerInfo, bool)

ServerInfoForContext returns the ServerInfo of the current server-side call. It reports false outside a call dispatched by a mounted Service, including in client interceptors and on the client side of an RPC.

type Service

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

Service is a running set of NATS subscriptions that dispatch RPCs to a connect.Server.

Mount creates one subscription per registered service, on the service's subject wildcard. Every instance sharing the queue group receives one copy of each open frame, so they split the call load; instances in different groups each receive every frame and would answer it independently.

With WithMicroDiscovery, Mount also creates one $SRV.> subscription that answers the NATS micro control verbs for every mounted service.

A Service never closes the NATS connection it was given: connections are owned by the caller and may be shared with other users.

func Mount

func Mount(conn *nats.Conn, server *connect.Server, options ...Option) (*Service, error)

Mount subscribes to every service registered on server and returns the running Service. The subscriptions are flushed before Mount returns, so a client may issue calls immediately.

Mount is setup-time work: server.Register must not run concurrently with it. If any subscription fails, the subscriptions already created are removed and Mount returns the error, leaving no partially mounted service behind.

Example

ExampleMount builds the server half: register handlers on a connect.Server, then mount it on a NATS connection. Every instance sharing the same queue group load-balances opens of the same procedure.

package main

import (
	"context"
	"log"
	"time"

	"connectrpc.com/connect/v2"
	"github.com/chenjpu/connectnats"
	"github.com/nats-io/nats.go"
)

func main() {
	conn, err := nats.Connect(nats.DefaultURL)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	server := connect.NewServer()
	// pingv1connect.RegisterPingServiceHandler(server, pingServer{})
	service, err := connectnats.Mount(conn, server, connectnats.WithQueueGroup("ping"))
	if err != nil {
		log.Print(err)
		return
	}
	defer func() {
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		_ = service.Shutdown(ctx)
	}()
}

func (*Service) Shutdown

func (s *Service) Shutdown(ctx context.Context) error

Shutdown stops accepting new RPCs and ends the ones in flight.

It removes every service subscription first, so an open frame published afterwards reaches no subscriber and the client observes NATS's no-responders status message, which maps to CodeUnavailable. Each active call is then ended with an end frame carrying CodeUnavailable, and its handler context is canceled. The end frames are flushed before Shutdown waits, so a caller that closes the connection right after it returns cannot discard them.

Shutdown waits for the handlers to return or for ctx to expire, whichever comes first. It is idempotent and safe to call concurrently: every caller waits for the same completion. It never closes the NATS connection.

Shutdown publishes no drain or goaway broadcast (ADR-020): NATS has no connection-level RPC channel, and queue groups already choose the instance, so Unavailable is the only shutdown signal a client can act on.

func (*Service) SubscriptionCount

func (s *Service) SubscriptionCount() int

SubscriptionCount returns the number of NATS subscriptions this service owns: one request-inbox pool, plus one method subscription and one cancellation subscription per registered service. When micro discovery is enabled it also includes the single $SRV.> subscription. It is zero after Shutdown. The connection may carry subscriptions created by other users; only the ones Mount created are counted.

type StreamMetrics

type StreamMetrics struct {
	// StreamID is the Connect-Stream token.
	StreamID string
	// Procedure is the RPC procedure.
	Procedure string
	// StreamType is the declared stream type of the call.
	StreamType connect.StreamType
	// Server reports which side ran the callback: true for a mounted service,
	// false for a Transport.
	Server bool
	// Subscriptions is the number of NATS subscriptions the reporting side owns
	// when the callback runs: one response pool on a Transport, and one request
	// pool plus one per service on a Service. It is not the process-wide
	// connection count.
	Subscriptions int
	// StartedAt is when the stream was created (client) or accepted (server).
	// It is set in StreamStarted and repeated in StreamEnded.
	StartedAt time.Time
	// Duration is the wall-clock time from StartedAt to StreamEnded. It is zero
	// in StreamStarted.
	Duration time.Duration
	// OpenLatency is the time from StartedAt to the ready handshake: ready
	// received on a client, ready published on a server. It is zero in
	// StreamStarted and zero in StreamEnded when ready never completed.
	OpenLatency time.Duration
	// SendWait is the total time Send spent waiting for the peer's receive
	// window. Waiting for ready is excluded. It is zero in StreamStarted.
	SendWait time.Duration
	// DroppedMessages is the number of frames this stream's bounded queue
	// dropped. Pool-level drops cannot be attributed to a stream and are not
	// included; the terminal error is CodeDataLoss in that case. It is zero in
	// StreamStarted.
	DroppedMessages int
	// ProtocolErrors reports a local frame, header, or state violation that
	// terminated the stream. DataLoss is excluded because it is reported
	// through DroppedMessages and the terminal code; handler errors,
	// cancellation, deadlines, and connection loss are also excluded. It is
	// zero in StreamStarted.
	ProtocolErrors int
	// ReconnectFailure reports that the stream ended with CodeUnavailable while
	// the NATS connection was still reconnecting. It counts failed calls, not
	// reconnect attempts: a call that fails after a reconnect completed is not
	// counted. It is false in StreamStarted.
	ReconnectFailure bool
	// PendingMessages and PendingBytes report what was still buffered and never
	// consumed by the application when the stream ended. They are zero in
	// StreamStarted, and zero in StreamEnded when the application drained the
	// queue. PendingBytes counts payload as it arrived on the wire: compressed
	// when the message was compressed, and without frame headers.
	PendingMessages int
	PendingBytes    int
}

StreamMetrics identifies one stream in Metrics callbacks. It is an immutable snapshot taken by the transport.

type Transport

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

Transport is a connect.Transport that sends RPCs over NATS.

A Transport owns one response-inbox subscription for all of its calls: NewTransport subscribes to <inboxPrefix>.<transportToken>.*.resp and flushes it once, and every call publishes to its own token under that tree. Messages are demultiplexed by subject token, so the subscription footprint is constant in the number of concurrent calls. A Transport owns no NATS connection: the caller passes one in and keeps ownership of it, so Close and Shutdown never close the connection. A single Transport is safe for concurrent use.

A Transport does own its streams. Close ends every in-flight call and releases the pool subscription; Shutdown does the same and waits for the calls to unwind, bounded by its context. Calls ended this way report CodeCanceled, which connect's retry policy does not retry. After Close or Shutdown, NewClientStream fails with CodeCanceled until the Transport is rebuilt.

func NewTransport

func NewTransport(conn *nats.Conn, options ...Option) (*Transport, error)

NewTransport returns a Transport that publishes calls over conn. The options configure codecs, compression, the receive window, size limits, and the cap on concurrently open streams; the server-only options (queue group) are ignored.

NewTransport subscribes to the response-inbox pool and flushes it before returning, so the first call cannot race the subscription. A rejected subscription is reported immediately as CodePermissionDenied (ACL) or CodeResourceExhausted (max_subscriptions) instead of surfacing later as a call that never completes.

Example

ExampleNewTransport builds the client half: wrap an existing NATS connection in a Transport, then pass connect.NewClient to generated code.

package main

import (
	"log"
	"time"

	"connectrpc.com/connect/v2"
	"github.com/chenjpu/connectnats"
	"github.com/nats-io/nats.go"
)

func main() {
	conn, err := nats.Connect(nats.DefaultURL)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	transport, err := connectnats.NewTransport(
		conn,
		connectnats.WithWindow(16),
		connectnats.WithKeepalive(30*time.Second, 90*time.Second),
	)
	if err != nil {
		log.Print(err)
		return
	}
	client := connect.NewClient(transport)
	_ = client // pingv1connect.NewPingServiceClient(client)
}

func (*Transport) Close

func (t *Transport) Close() error

Close ends every in-flight call and waits for their resources to be released. The NATS connection stays open and owned by the caller.

In-flight calls see CodeCanceled from Receive; a client-streaming call sees the same error from every later Receive. The pool subscription and the shared keepalive loop are released before Close returns, so the connection's subscription count falls back to its pre-call value. Close stops opening new calls but does not close the connection, which lets the caller reuse it for other transports.

Close is idempotent and safe to call concurrently; every caller waits for the same completion.

func (*Transport) NewClientStream

func (t *Transport) NewClientStream(ctx context.Context, spec connect.Spec) (connect.ClientStream, error)

NewClientStream opens a client stream for spec.

The response inbox is covered by the pool subscription NewTransport already flushed, so a call only registers a token before the open frame is published. A transport already running WithMaxConcurrentCalls streams reports CodeResourceExhausted; a closed transport or a closed connection reports CodeCanceled or CodeUnavailable.

func (*Transport) Shutdown

func (t *Transport) Shutdown(ctx context.Context) error

Shutdown stops opening new calls, ends the ones in flight, and waits for them to unwind or for ctx to expire, whichever comes first.

It differs from Close only in the wait: Shutdown honors ctx, so a caller that cannot block (for example a process shutdown with a fixed budget) can bound the drain. The handlers behind the ended calls are told to stop by the cancel frames, exactly as with Close; the NATS connection is never closed.

Shutdown is idempotent and safe to call concurrently. A completion that finishes at the same moment ctx expires is reported as success.

func (*Transport) SubscriptionCount

func (t *Transport) SubscriptionCount() int

SubscriptionCount returns the number of NATS subscriptions this transport owns: one response pool while it is open, and zero after Close or Shutdown. The connection may carry subscriptions created by other users; only the ones this transport created are counted.

Directories

Path Synopsis
Package example is the parent of the example's client and server commands.
Package example is the parent of the example's client and server commands.
client command
Command client calls the example PingService over NATS.
Command client calls the example PingService over NATS.
ping/v1/pingv1connect
The example package mirrors connect-go's internal example so the two can be compared side by side: one unary, one client-streaming, one server-streaming, and one bidirectional RPC.
The example package mirrors connect-go's internal example so the two can be compared side by side: one unary, one client-streaming, one server-streaming, and one bidirectional RPC.
server command
Command server serves the example PingService over NATS.
Command server serves the example PingService over NATS.
internal
natstest
Package natstest starts in-process NATS servers for tests.
Package natstest starts in-process NATS servers for tests.

Jump to

Keyboard shortcuts

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