Debian Codegraph @

CLAUDE.md

raw
1 # CLAUDE.md
2
3 This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
5 ## Project Overview
6
7 Official Go client library for the NATS messaging system. Provides core pub/sub, request/reply, JetStream (streams, consumers, KV, object store), and a micro services framework. Module path: `github.com/nats-io/nats.go`.
8
9 ## Build and Test Commands
10
11 This project uses a **dual module** setup: `go.mod` for production (minimal deps) and `go_test.mod` for testing (protobuf encoder + jwt + nkeys + nuid + the ntf tester). Always use `-modfile=go_test.mod` when running tests.
12
13 `go_test.mod` declares `go 1.26.0` while `go.mod` stays at `1.25.0`, because `github.com/synadia-io/orbit.go/ntf` requires 1.26 and that raises the floor for the whole test module. `go get`/`go mod tidy` will rewrite this line; leave it at 1.26.0. TESTING.md has the full derivation.
14
15 Integration tests (everything in `./test/`, `./jetstream/test/`, `./micro/test/`) run against real servers spawned by a **tester** service, driven through `github.com/synadia-io/orbit.go/ntf-client`. There are two ways to run it:
16
17 - **In-process, no docker (the default)** — a `TestMain` in each of the three test packages starts `github.com/synadia-io/orbit.go/ntf` inside the test binary. No build tag; this is what a plain `go test` does.
18 - **Docker** (`synadia/ntf-server`, tag pinned in `.github/workflows/ci.yaml`) — located via `TESTER_NATS_URL`. This is what CI uses.
19
20 `TESTER_NATS_URL` takes precedence: when set, it is used instead of starting an in-process tester. The two are **not** necessarily equivalent — in-process links whatever nats-server `orbit.go/ntf` depends on, the container ships its own — so `TestMain` hard-fails when `GITHUB_ACTIONS` is set without `TESTER_NATS_URL`, rather than silently changing what CI tests against. (`GITHUB_ACTIONS`, not `CI`: devcontainers and other runners set that one too.)
21
22 ```bash
23 # Default local workflow: no docker, nothing to start or tear down.
24 make test # full race-enabled suite
25 make test T=TestName PKG=./test/... # single test, verbose
26 make test-norace # NoRace suite
27
28 # Equivalent raw command:
29 go test -modfile=go_test.mod -tags=internal_testing -race -p=1 ./... --failfast -vet=off
30
31 # Docker workflow (host-side mode publishes the tester's ports so `go test`
32 # from your terminal can reach the spawned NATS servers via localhost).
33 # Use the test-docker targets: plain `make test` ignores the container.
34 make tester-up-host
35 make test-docker T=TestName PKG=./test/...
36
37 # Run all tests against the tester (single command, covers both white-box
38 # tests at the repo root and integration tests in ./test/, ./jetstream/test/,
39 # ./micro/test/).
40 TESTER_NATS_URL=nats://localhost:4222 \
41 go test -modfile=go_test.mod -race -v -p=1 ./... --failfast -vet=off -tags=internal_testing
42
43 # Run NoRace tests (must be run separately, without -race flag)
44 TESTER_NATS_URL=nats://localhost:4222 \
45 go test -modfile=go_test.mod -v -run=TestNoRace -p=1 ./... --failfast -vet=off
46
47 # Run a specific test
48 TESTER_NATS_URL=nats://localhost:4222 \
49 go test -modfile=go_test.mod -race -tags=internal_testing -run TestName ./...
50
51 # Run tests for a specific package
52 TESTER_NATS_URL=nats://localhost:4222 go test -modfile=go_test.mod -race ./jetstream/test/... --failfast
53 TESTER_NATS_URL=nats://localhost:4222 go test -modfile=go_test.mod -race ./micro/test/... --failfast
54
55 # Makefile wrappers for the docker path (TESTER_NATS_URL defaults to nats://localhost:4222)
56 make test-docker # full race-enabled suite with internal_testing tag
57 make test-docker T=TestName PKG=./test/... # single test, verbose
58
59 # Test against a different nats-server (branch/tag/commit/local checkout).
60 # Adds a replace directive to go_test.mod — never commit it. Do NOT use
61 # `go get ...@main`, which can drop ntf from the module graph (why: TESTING.md).
62 make server-replace V=main
63 make server-replace-drop
64
65 # Stop the tester
66 make tester-down
67
68 # Alternative: run the full suite inside an alpine sibling container (matches CI).
69 # Doesn't need TESTER_NATS_URL or tester-up-host — the Makefile target handles it.
70 make test-tester
71
72 # Build
73 go build ./...
74
75 # Formatting
76 go fmt -modfile=go_test.mod ./...
77
78 # Vet
79 go vet -modfile=go_test.mod ./...
80
81 # Static analysis (as CI does it; staticcheck has no -modfile flag, so it goes
82 # through GOFLAGS)
83 GOFLAGS="-mod=mod -modfile=go_test.mod" staticcheck ./...
84
85 # Linting (golangci-lint runs only on jetstream/; the modfile GOFLAGS lets it
86 # typecheck jetstream/test, whose deps live in go_test.mod only)
87 GOFLAGS="-mod=mod -modfile=go_test.mod" golangci-lint run --timeout 5m0s ./jetstream/...
88
89 # Spell check
90 find . -type f -name "*.go" | xargs misspell -error -locale US
91
92 # Update test dependencies (never change go.mod for test deps)
93 go mod tidy -modfile=go_test.mod
94 ```
95
96 A plain `go test -modfile=go_test.mod ./...` now runs the integration suites too, since `TestMain` starts a tester on its own. It takes minutes rather than seconds — that is expected, not a hang.
97
98 ## Important Build Tags
99
100 - **`internal_testing`** -- Exposes internal test helpers (e.g., `AddMsgFilter`, `CloseTCPConn`) from `testing_internal.go`. Required for some tests in `./test/`.
101 - **`!race && !skip_no_race_tests`** -- NoRace tests in `test/norace_test.go` only run when the race detector is OFF.
102 - **`compat`** -- Compatibility tests in `test/compat_test.go` (connect to an external NATS server via `NATS_URL`).
103 - **`go1.23`** -- Iterator-based tests in `test/nats_iter_test.go` and `nats_iter.go`.
104
105 ## CI Pipeline (ci.yaml)
106
107 1. **lint** -- `go fmt`, `go vet`, `staticcheck`, `misspell` (all packages), `golangci-lint` (jetstream only).
108 2. **test** -- Matrix of Go 1.26 and 1.27; 1.26 is the floor because `go_test.mod` declares it (a lower row would silently fetch 1.26 via `GOTOOLCHAIN=auto`). The 1.27 row runs coverage. Runs inside an `alpine` container on the same docker network as the `synadia/ntf-server` service, which is started with `command: serve --advertise nats` (the integration tests dial the spawned NATS servers by service name). CI sets `TESTER_NATS_URL` at job level so it uses the docker tester rather than the in-process default; `TestMain` fails the run if that variable ever goes missing under `GITHUB_ACTIONS`. Two steps: NoRace tests (without `-race`), then full race-enabled tests with `-tags=internal_testing` (`scripts/cov.sh` runs for coverage instead of the plain race run).
109
110 ## Project Structure
111
112 ```
113 nats.go # Core connection, pub/sub, request/reply (~6500 lines)
114 parser.go # Client-side protocol parser
115 ws.go # WebSocket transport support
116 js.go # Legacy JetStream API (deprecated, see jetstream/)
117 jsm.go # Legacy JetStream management
118 kv.go # Legacy KeyValue API
119 object.go # Legacy Object Store API
120 enc.go # EncodedConn (deprecated)
121 netchan.go # Go channel bindings
122 timer.go # Internal timer utilities
123 context.go # Context-aware request methods
124 nats_iter.go # Go 1.23+ iterator support (go:build go1.23)
125 testing_internal.go # Internal test hooks (go:build internal_testing)
126
127 jetstream/ # New JetStream API (preferred over legacy)
128 jetstream.go # Top-level JetStream interface
129 stream.go # Stream management
130 stream_config.go # Stream configuration types
131 consumer.go # Consumer management
132 consumer_config.go # Consumer configuration types
133 pull.go # Pull consumer implementation
134 push.go # Push consumer (deprecated)
135 ordered.go # Ordered consumer
136 publish.go # JetStream publish methods
137 kv.go # KeyValue store
138 object.go # Object store
139 message.go # JetStream message types
140 errors.go # JetStream error types
141 test/ # Integration tests (package test, uses testservice)
142
143 micro/ # Micro services framework
144 service.go # Service interface and implementation
145 request.go # Request handling
146 test/ # Integration tests
147
148 internal/
149 parser/ # NATS protocol parser (used by core client)
150 syncx/ # Concurrent map utility
151
152 encoders/
153 builtin/ # Default encoders (JSON, GOB, string)
154 protobuf/ # Protocol Buffers encoder
155
156 test/ # Integration tests for core package (package test)
157 testservice_helper_test.go # withServer / withServerInstance / newTester / dialInstance helpers
158 main_test.go # TestMain: starts the tester (in-process by default)
159 helper_test.go # Shared utility helpers (Wait, checkFor, getStableNumGoroutine, ...)
160 norace_test.go # Tests that cannot run with -race (build tag guarded)
161 js_internal_test.go # Tests requiring internal_testing tag
162 configs/certs/ # CA/server/key PEMs loaded by TLS tests (the *.conf files are unused)
163
164 bench/ # Benchmarking utilities
165 examples/ # Example command-line tools (nats-pub, nats-sub, etc.)
166 scripts/cov.sh # Coverage collection script (run by the CI coverage matrix row)
167 ```
168
169 The tester client is an external test-only dependency: `github.com/synadia-io/orbit.go/ntf-client`
170 (package `ntf`, imported under the alias `testservice`). It lives in `go_test.mod` only.
171
172 ## Test Architecture
173
174 - **Root `nats_test.go`** (package `nats`) -- White-box unit tests with access to unexported internals.
175 - **`test/`** (package `test`) -- Black-box integration tests. Tests bring up a NATS server via the testservice helpers (`withServer`, `withJSServer`, `withJSCluster`, ...) which talk to the tester over NATS — either the in-process one started by `TestMain` (the default) or the `synadia/ntf-server` docker service via `TESTER_NATS_URL`. Use the `testerURL` package var; never read `TESTER_NATS_URL` directly, or the test will bypass the in-process tester (this exact bug hit `headers_test.go`).
176 - **`jetstream/test/`** (package `test`) -- Integration tests for the new JetStream API, same testservice harness.
177 - **`micro/test/`** (package `micro_test`) -- Integration tests for the micro services framework, same testservice harness.
178 - **NoRace tests** -- Prefixed `TestNoRace*`, guarded by `//go:build !race && !skip_no_race_tests`. Must be run separately without `-race`.
179 - Tests always run with `-p=1` (no parallel packages) because the tester serializes some bookkeeping that doesn't tolerate concurrent CreateServer calls from independent test binaries.
180
181 ## Code Conventions
182
183 - **License header** -- Every `.go` file starts with the Apache 2.0 license header (Copyright year range).
184 - **Error variables** -- Exported errors defined as `var Err... = errors.New("nats: ...")` in `nats.go`. JetStream errors in `jetstream/errors.go` follow the same pattern.
185 - **Options pattern** -- Connection options use functional options: `nats.Connect(url, nats.Name("myapp"), nats.MaxReconnects(5))`. JetStream and micro use similar patterns.
186 - **No external dependencies in production** -- Only `klauspost/compress`, `nkeys`, `nuid` in `go.mod`. Test deps (protobuf, jwt, etc.) are isolated in `go_test.mod`. PRs adding dependencies are scrutinized heavily.
187 - **Commits require sign-off** -- Use `git commit -s` (DCO: `Signed-off-by`).
188 - **US English spelling** -- Enforced by `misspell -locale US` in CI.
189 - **Interface-driven design** -- JetStream and micro packages define interfaces (`JetStream`, `Stream`, `Consumer`, `Service`) with concrete unexported implementations.
190
191 ## Key Types
192
193 - `nats.Conn` -- Core connection, handles all NATS protocol operations.
194 - `nats.Msg` -- Message type for pub/sub and request/reply.
195 - `nats.Subscription` -- Represents a subscription (sync, async, or channel-based).
196 - `jetstream.JetStream` -- Entry point for new JetStream API (created via `jetstream.New(nc)`).
197 - `jetstream.Stream`, `jetstream.Consumer` -- Stream and consumer management.
198 - `micro.Service` -- Micro service instance (created via `micro.AddService(nc, config)`).