nats
| Kind | ffi-zig |
|---|---|
| Capabilities | ffi net |
| Categories | messaging networking ffi |
| Keywords | nats messaging pubsub queue streaming |
NATS client for Kit using native Zig FFI
Files
| File | Description |
|---|---|
.editorconfig | Editor formatting configuration |
.gitignore | Git ignore rules for build artifacts and dependencies |
.tool-versions | asdf tool versions (Zig, Kit) |
LICENSE | MIT license file |
README.md | This file |
docs/api.md | API reference notes |
examples/basic.kit | Basic connection, ping, publish, subscribe, and flush example |
examples/pubsub.kit | Publish/subscribe example |
examples/queue-groups.kit | Queue group worker and producer example |
examples/request-reply.kit | Request/reply responder and requester example |
kit.toml | Package manifest with metadata, capabilities, and tasks |
src/nats.kit | Public Kit API and typed error definitions |
tests/nats.test.kit | Tests for exported error types and module import behavior |
zig/kit_ffi.zig | Kit FFI helper definitions used by the Zig implementation |
zig/nats.zig | Native Zig implementation of the NATS protocol client |
Dependencies
No Kit package dependencies.
This package requires Kit capabilities for FFI and networking:
[capabilities]
requires = ["ffi", "net"]Live examples require a NATS server listening on localhost:4222.
brew install nats-server
nats-serverInstallation
kit add gitlab.com/kit-lang/packages/kit-nats.gitUsage
import Kit.Nats as NATS
print-error = fn(prefix: String, e: NatsError) =>
match e
| NatsConnectionError {message} -> println "${prefix}: ${message}"
| NatsCommandError {message} -> println "${prefix}: ${message}"
main = fn() =>
match NATS.connect "localhost" 4222
| Ok conn ->
defer NATS.close conn
match NATS.ping conn
| Ok response -> println "Ping: ${response}"
| Err e -> print-error "Ping failed" e
match NATS.publish conn "greet.joe" "Hello Joe!"
| Ok _ -> println "Published message"
| Err e -> print-error "Publish failed" e
match NATS.subscribe conn "greet.*"
| Ok sid ->
println "Subscribed with sid: ${Int.to-string sid}"
NATS.unsubscribe conn sid
| Err e -> print-error "Subscribe failed" e
NATS.flush conn
| Err e ->
print-error "Connection failed" e
mainRequest/Reply
import Kit.Nats as NATS
match NATS.connect "localhost" 4222
| Ok conn ->
defer NATS.close conn
match NATS.request conn "echo" "Hello NATS!" 5000
| Ok response -> println "Received response: ${response}"
| Err e -> println "Request failed: ${NatsError.show e}"
| Err e -> println "Connection failed: ${NatsError.show e}"Queue Groups
import Kit.Nats as NATS
match NATS.connect "localhost" 4222
| Ok conn ->
defer NATS.close conn
match NATS.subscribe-queue conn "jobs" "workers"
| Ok sid ->
println "Worker subscribed with sid: ${Int.to-string sid}"
match NATS.next-msg conn
| Ok msg -> println "Job payload: ${msg.payload}"
| Err e -> println "Receive failed: ${NatsError.show e}"
| Err e -> println "Subscribe failed: ${NatsError.show e}"
| Err e -> println "Connection failed: ${NatsError.show e}"API Overview
| Function | Description |
|---|---|
NATS.connect host port | Connect to a NATS server by host and port |
NATS.connect-url url | Connect using a nats://host:port style URL |
NATS.close conn | Close a connection and release native resources |
NATS.ping conn | Send PING and wait for PONG |
NATS.flush conn | Ensure previously sent commands have reached the server |
NATS.publish conn subject payload | Publish a payload to a subject |
NATS.publish-reply conn subject reply-to payload | Publish with an explicit reply subject |
NATS.subscribe conn subject | Subscribe to a subject or wildcard subject |
NATS.subscribe-queue conn subject queue | Subscribe as part of a queue group |
NATS.unsubscribe conn sid | Unsubscribe by subscription id |
NATS.unsubscribe-after conn sid max-msgs | Auto-unsubscribe after max-msgs messages |
NATS.next-msg conn | Block until the next subscribed message is received |
NATS.request conn subject payload timeout | Send a request and wait for a reply |
All operations return Result values using NatsError:
export type NatsError =
| NatsConnectionError {message: String}
| NatsCommandError {message: String}Connections are native resources. Use defer NATS.close conn immediately after a successful connection.
Architecture
Pub/Sub Pattern
Request/Reply Pattern
FFI Structure
Development
Running Examples
Run the basic example with the interpreter:
kit run examples/basic.kitCompile the basic example to a native binary:
kit build examples/basic.kit -o basic && ./basicRun the pub/sub example:
kit run examples/pubsub.kitThe examples import ../src/nats.kit so they exercise the local working tree during package development.
Running Tests
Run the test suite:
kit testRun the test suite with coverage:
kit test --coverageRunning kit dev
Run the standard development workflow (format, check, and test):
kit devThis will:
- Format and check source files
- Type check examples
- Run tests in
tests/with coverage
Running Parity
Run interpreter/compiler parity checks for all examples:
kit parity --no-spinner --failures-onlyParity builds and runs each example through both execution paths, then compares outputs. A local NATS server is optional for examples/basic.kit, but recommended for exercising the successful connection paths in the other examples.
Generating Documentation
Generate API documentation from doc comments:
kit docNote: Kit sources with doc comments (##) will generate HTML documents in docs/*.html.
Cleaning Build Artifacts
Remove generated files, caches, coverage data, parity results, and build artifacts:
kit task cleanNote: Defined in kit.toml.
Local Installation
To install this package locally for development:
kit installThis installs the package to ~/.kit/packages/@kit/nats/, making it available for import as Kit.Nats in other projects.
Implementation Notes
zig/nats.zigimplements the NATS text protocol directly over TCP sockets.@defer-required("NATS.close")on connection functions helps Kit warn when a connection is not closed in scope.connect-urlsupportsnats://host:port,user:pass@host:port, and barehost:portforms.- TLS URLs (
tls://) are rejected because TLS transport is not implemented yet. next-msgblocks until a message arrives on any subscription for the connection.requestcreates an inbox subscription, publishes withreply-to, waits for one response, and resets the receive timeout.
License
This package is released under the MIT License - see LICENSE for details.
Exported Functions & Types
NatsError
NATS error type for typed error handling. Variants distinguish between connection and command errors.
Variants
NatsConnectionError {message}NatsCommandError {message}