A NATS client: publish and subscribe, request and reply, queue groups, automatic reconnection, JetStream and a key value helper.
import net.nats
NATS is a small, fast message bus. Programs publish messages to subjects such as orders.eu.new, other programs subscribe to subjects or patterns, and the server delivers. This package is a client for the core protocol, request and reply, queue groups, headers, JetStream streams and consumers, and a simple key value helper. It speaks the text protocol over TCP or TLS and needs nothing but the standard library.
The model: Connect opens a connection and you pass it by reference to every call. Nothing runs in the background. Messages are read, handlers are called and PINGs are answered only while you call Pump, NextMsg, Flush, Request or Fetch, so a program that stops calling them stops answering the server. Failures are values: a call returns false, or a message whose ok is false with the reason in err.
•
Subjects are tokens joined by dots. * matches one token and a final > matches the rest, in subscriptions only.
•
Queue groups split a subject among workers: each message goes to one member.
•
Payloads are text. A str stops at its first NUL byte, so send binary data encoded, for example with Base64.
Connecting
Connect takes a URL such as nats://127.0.0.1:4222; tls:// turns TLS on, and nats://user:password@host or nats://token@host carries credentials. ConnectWith takes an Options value for the rest. A failed connection is a connection with ok false, so check IsConnected and read LastError.
mut nc := nats.Connect("nats://127.0.0.1:4222")
if not nats.IsConnected(nc):
println nats.LastError(nc)
end
Publishing and subscribing
Subscribe returns a handle; NextMsg waits for its next message. Or give SubscribeHandler a function and let Pump call it. Flush sends a PING and waits for the PONG, which proves the server has received everything you published before it.
sub := nats.Subscribe(nc, "greet.*")
nats.Publish(nc, "greet.bob", "hello")
m := nats.NextMsg(nc, sub, 1000)
println m.subject, m.data
Headers
A Header carries key and value pairs next to the payload. NewHeader makes one, HeaderAdd appends a value, HeaderSet replaces the values of a key, HeaderGet and HeaderValues read them, and HeaderEncode and HeaderParse turn a header to and from its wire form.
A subscription may use two wildcards: * stands for exactly one word and > for one or more words at the end. So orders.* matches orders.created but not orders.created.eu, and orders.> matches both but not orders alone. SubjectMatches applies the same rule locally, which makes it handy in tests. ValidSubject rejects an empty name, spaces and control characters, a leading or trailing dot and an empty word between two dots. Neither call needs a server.
Request sends a message with a private reply subject and waits for one answer. It returns a Msg, so check ok before reading data. When nothing is subscribed to the subject the server says so and err is no responders; when somebody is subscribed but does not answer in time it is timeout. SubscribeReplier takes a function from a message to the reply text. Nothing runs in the background: handlers run while the connection is being pumped, which Request, NextMsg, Flush and Pump all do. To answer by hand, subscribe with Subscribe and call Respond with the incoming message.
Subscriptions that share a queue name are one group, and the server delivers each message to just one of them, which is how several workers split a stream of jobs. Which member gets which message is up to the server, so count what was handled, not who handled it. NextMsg waits up to the given milliseconds and returns a message with ok false and err set to timeout when nothing arrives. AutoUnsubscribe removes a subscription after that many deliveries. Drain stops the subscriptions, flushes what is pending and closes the connection, so it is the right last call.
net-nats-guide-queue.salam
import net.nats
funcmain:
mut nc := nats.Connect("nats://127.0.0.1:4222")
ifnot nats.IsConnected(nc):
println"cannot connect:", nats.LastError(nc)
ret1end
a := nats.QueueSubscribe(nc, "jobs", "workers")
b := nats.QueueSubscribe(nc, "jobs", "workers")
_ok := nats.AutoUnsubscribe(nc, a, 10)
repeat6in i:
_sent := nats.Publish(nc, "jobs", "job " + i)
end
_flushed := nats.Flush(nc, 1000)
mut handled := 0repeat2in k:
s := k == 0 ? a : b
mut m := nats.NextMsg(nc, s, 200)
until m.ok:
handled++
m = nats.NextMsg(nc, s, 200)
endendprintln"handled", handled, "subscriptions", nats.SubscriptionCount(nc)
println"drained", nats.Drain(nc, 1000)
ret0end
Reconnecting
By default a lost connection is closed for good. Set max_reconnects to a positive number, or a negative one to never give up, and the client reconnects by itself. It walks the list made of the URL and servers, waits reconnect_wait_ms between attempts, sends all subscriptions again (an AutoUnsubscribe limit counts only what is left) and then sends the publishes that were held while the link was down, up to reconnect_buffer bytes. Reconnecting happens inside Pump, NextMsg, Flush and Request, since nothing runs in the background. A request that was already on its way when the link broke gets no answer and times out. Errors such as a refused login close the connection instead of retrying.
JetStream stores messages in streams and hands them to consumers. AddStream makes a stream for some subjects, JSPublish publishes and returns the receipt with the stored sequence number, and a pull consumer made with AddConsumer is read with Fetch. Acknowledge every message with Ack; Nak asks for a redelivery and Term gives up on a message.
A push consumer made with AddPushConsumer has the server send messages to a subject you subscribed to. Read them with NextPush, which also answers flow control and skips heartbeats. Any other JetStream call is available through JSRequest.
Key value buckets
A bucket is a stream called KV_ followed by its name, with one subject for each key. KVCreate, KVPut, KVGet and KVDelete cover the common cases. A delete writes a marker, so KVGet then reports found false and deleted true. Watching keys, compare-and-set updates and purging are not provided; use JSRequest or the stream calls for those.
What to know
•
Nothing runs in the background. Call Pump or a waiting function regularly, or the server drops you as a slow consumer or a stale connection.
•
A connection is not safe to use from two threads at once.
•
Payloads stop at the first NUL byte. Binary data needs encoding.
•
The default is no reconnecting. Turn it on with max_reconnects.
•
Authentication is user and password or a token. NKeys, JWT credentials and client certificates are not supported.
•
JetStream calls need a server started with JetStream. Without it they return jetstream not enabled or no responders.
Creates a durable push consumer: the server sends its messages to the deliver subject. Subscribe to that subject first. With an empty queue flow control and heartbeats are turned on.
net-nats-Push.salam
import net.nats
funcmain(): int:
mut nc := nats.Connect("nats://127.0.0.1:4222")
ifnot nats.IsConnected(nc):
println"cannot connect:", nats.LastError(nc)
ret1end
sub := nats.Subscribe(nc, "deliver.orders")
made := nats.AddPushConsumer(nc, "ORDERS", "pusher", "orders.*", "deliver.orders", "", 2000)
ifnot made.ok:
println"consumer:", made.err
ret1enduntiltrue:
m := nats.NextPush(nc, sub, 2000)
ifnot m.ok:
breakendprintln m.data, nats.MsgSequence(m)
nats.Ack(nc, m)
end
nats.Close(nc)
ret0end
Waits up to the timeout for data, handles everything that arrived (calling handlers, answering PINGs, queueing messages) and returns how many messages it dealt with. While the link is down it runs reconnect attempts instead.
Sends a message to a subject. Returns false when the subject is invalid, the payload is over the server's limit, the connection is closed or the reconnect buffer is full. While reconnecting, the message is held and sent after the link is back.
net-nats-PubSub.salam
import net.nats
funcmain(): int:
mut nc := nats.Connect("nats://127.0.0.1:4222")
ifnot nats.IsConnected(nc):
println"cannot connect:", nats.LastError(nc)
ret1end
all := nats.Subscribe(nc, "orders.*")
first := nats.QueueSubscribe(nc, "jobs", "workers")
once := nats.Subscribe(nc, "ping")
nats.AutoUnsubscribe(nc, once, 1)
println"subscriptions:", nats.SubscriptionCount(nc)
nats.Publish(nc, "orders.new", "order 1")
nats.Publish(nc, "jobs", "job 1")
nats.Publish(nc, "ping", "hello")
nats.Flush(nc, 1000)
println"waiting:", nats.Pending(nc, all), nats.Pending(nc, first)
m := nats.NextMsg(nc, all, 1000)
if m.ok:
println m.subject, m.data
end
p := nats.NextMsg(nc, once, 1000)
println p.data, nats.Delivered(nc, once), nats.IsValidSubscription(nc, once)
nats.Unsubscribe(nc, all)
nats.Close(nc)
ret0end