net.nats
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
strstops 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.
import net.nats
func main:
mut h := nats.NewHeader()
nats.HeaderAdd(h, "Trace", "a1")
nats.HeaderAdd(h, "Trace", "b2")
nats.HeaderSet(h, "Tenant", "acme")
println nats.HeaderGet(h, "Tenant"), nats.HeaderCount(h), nats.HeaderHas(h, "Trace")
println nats.ValidSubject("orders.created"), nats.ValidSubject("bad subject")
endSubjects and wildcards
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.
import net.nats
func show(pattern: str, subject: str):
println pattern, subject, nats.SubjectMatches(pattern, subject)
end
func main:
show("orders.*", "orders.created")
show("orders.*", "orders.created.eu")
show("orders.>", "orders.created.eu")
show("orders.>", "orders")
show("*.created", "orders.created")
show("orders.created", "orders.created")
println nats.ValidSubject("orders..created"), nats.ValidSubject(".orders"), nats.ValidSubject("orders.")
println nats.ValidSubject(""), nats.ValidSubject("a b"), nats.ValidSubject("orders.>")
endRequest and reply
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.
import net.nats
func main:
mut nc := nats.Connect("nats://127.0.0.1:4222")
if not nats.IsConnected(nc):
println "cannot connect:", nats.LastError(nc)
ret 1
end
_s := nats.SubscribeReplier(nc, "svc.shout", "", (m: nats.Msg): ret m.data + "!" end)
r := nats.Request(nc, "svc.shout", "hello", 1000)
if r.ok:
println "reply:", r.data
else:
println "failed:", r.err
end
gone := nats.Request(nc, "svc.nobody", "x", 1000)
println gone.ok, gone.err
slow := nats.Request(nc, "svc.silent", "x", 150)
println slow.ok, slow.err
nats.Close(nc)
ret 0
endQueue groups and a clean exit
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.
import net.nats
func main:
mut nc := nats.Connect("nats://127.0.0.1:4222")
if not nats.IsConnected(nc):
println "cannot connect:", nats.LastError(nc)
ret 1
end
a := nats.QueueSubscribe(nc, "jobs", "workers")
b := nats.QueueSubscribe(nc, "jobs", "workers")
_ok := nats.AutoUnsubscribe(nc, a, 10)
repeat 6 in i:
_sent := nats.Publish(nc, "jobs", "job " + i)
end
_flushed := nats.Flush(nc, 1000)
mut handled := 0
repeat 2 in k:
s := k == 0 ? a : b
mut m := nats.NextMsg(nc, s, 200)
until m.ok:
handled++
m = nats.NextMsg(nc, s, 200)
end
end
println "handled", handled, "subscriptions", nats.SubscriptionCount(nc)
println "drained", nats.Drain(nc, 1000)
ret 0
endReconnecting
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.
mut opts := nats.DefaultOptions()
opts.servers.push("nats://10.0.0.2:4222")
opts.max_reconnects = 20
opts.reconnect_wait_ms = 500
JetStream
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
Pumpor 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 enabledorno responders.
Types
JSResult
struct JSResultok is false when the call failed or the server said no.| Name | Type | Description |
|---|---|---|
ok | bool = false | True when the call worked. |
err | str = "" | The error text from the server or the client, empty when the call worked. |
code | int = 0 | The JetStream error code, for example 10059 for a stream that does not exist. Zero when there is none. |
raw | str = "" | The JSON the server answered with, for fields this package does not read. |
StreamState
struct StreamStateStreamInfo returns about a stream.| Name | Type | Description |
|---|---|---|
ok | bool = false | True when the information was read. |
err | str = "" | The error text when it was not. |
name | str = "" | The name of the stream. |
messages | int = 0 | The number of messages stored. |
bytes | int = 0 | The size of the stored messages in bytes. |
first_seq | int = 0 | The sequence number of the oldest stored message. |
last_seq | int = 0 | The sequence number of the newest stored message. |
consumers | int = 0 | How many consumers the stream has. |
PubAck
struct PubAck| Name | Type | Description |
|---|---|---|
ok | bool = false | True when the stream stored the message. |
err | str = "" | The error text when it did not; no responders means no stream listens on the subject. |
stream | str = "" | The name of the stream that stored the message. |
seq | int = 0 | The sequence number the message got in the stream. |
duplicate | bool = false | True when the server saw the same Nats-Msg-Id header recently and ignored the message. |
Batch
struct BatchFetch call brought back.| Name | Type | Description |
|---|---|---|
msgs | Vector | The messages, in order. Acknowledge each one. |
err | str = "" | Why the batch is empty: a timeout, or the server's status text. Empty when there are messages. |
KVEntry
struct KVEntry| Name | Type | Description |
|---|---|---|
ok | bool = false | True when the call itself worked, even if the key is not there. |
found | bool = false | True when the key exists and holds a value. |
deleted | bool = false | True when the newest entry for the key is a delete marker. |
key | str = "" | The key that was asked for. |
value | str = "" | The value, empty when the key was not found. |
revision | int = 0 | The revision of the entry: its sequence number in the bucket's stream. |
err | str = "" | The error text, or key not found. |
Header
struct Header| Name | Type | Description |
|---|---|---|
keys | Vector | The header names, in the order they were added. |
values | Vector | The values, one for each name in keys. |
Msg
struct Msg| Name | Type | Description |
|---|---|---|
ok | bool = false | True for a real message. A timeout or an error gives a message with ok false and the reason in err. |
err | str = "" | The reason a call returned no message, such as timeout or no responders. |
subject | str = "" | The subject the message was published to. |
reply | str = "" | The subject to answer on, empty when the sender does not want an answer. |
data | str = "" | The payload as text. It stops at the first NUL byte. |
header | Header | The headers of the message. |
sid | int = 0 | The subscription id the message arrived on. |
status | int = 0 | The status code of a message sent by the server itself, such as 503 for no responders or 100 for a heartbeat. Zero for an ordinary message. |
status_text | str = "" | The text that goes with status. |
Subscription
struct Subscription| Name | Type | Description |
|---|---|---|
ok | bool = false | True when the subscription was made. |
sid | int = 0 | The id the server knows the subscription by. |
subject | str = "" | The subject or pattern subscribed to. |
queue | str = "" | The queue group, empty for a plain subscription. |
ServerInfo
struct ServerInfo| Name | Type | Description |
|---|---|---|
server_id | str = "" | The unique id of the server. |
server_name | str = "" | The name of the server. |
version | str = "" | The server's version. |
host | str = "" | The host the server is listening on. |
port | int = 0 | The port the server is listening on. |
proto | int = 0 | The protocol version the server speaks. |
client_id | int = 0 | The id the server gave this connection. |
max_payload | int = 1048576 | The largest message the server accepts, in bytes. |
headers | bool = false | True when the server supports headers. |
tls_required | bool = false | True when the server wants TLS. |
auth_required | bool = false | True when the server wants credentials. |
jetstream | bool = false | True when JetStream is turned on. |
raw | str = "" | The whole INFO JSON, for fields this package does not read. |
Options
struct OptionsConnectWith. Start from DefaultOptions and change what you need.| Name | Type | Description |
|---|---|---|
name | str = "" | A name for this client, shown in the server's connection list. |
user | str = "" | The user name. A user:password@ part in the URL does the same. |
password | str = "" | The password for user. |
token | str = "" | An authentication token. A URL of the form nats://token@host sets it too. |
no_echo | bool = false | When true the server does not send this connection the messages it publishes itself. |
verbose | bool = false | Ask the server to answer every command with +OK. Rarely useful. |
pedantic | bool = false | Ask the server to check subjects strictly. |
secure | bool = false | Use TLS even when the server does not require it. A tls:// URL does the same. |
insecure_skip_verify | bool = false | Do not check the server's certificate. For testing only. |
timeout_ms | int = 5000 | How long connecting may take, in milliseconds. Zero means 5000. |
ping_interval_ms | int = 120000 | How long the line may be silent before the client sends a PING. Zero turns the check off. |
max_pings_out | int = 2 | How many PINGs may go unanswered before the connection counts as stale. |
inbox_prefix | str = "_INBOX" | The start of the private subjects used for replies. Change it when your permissions only allow a certain prefix. |
servers | Vector | More servers to try. The URL given to ConnectWith comes first, then these in order. |
max_reconnects | int = 0 | How many failed attempts in a row end the reconnecting: 0 turns reconnecting off, a negative number never gives up. |
reconnect_wait_ms | int = 2000 | How long to wait between attempts in milliseconds. |
reconnect_buffer | int = 8388608 | How many bytes of publishes are held while the link is down. Over the limit, Publish returns false. |
Stats
struct Stats| Name | Type | Description |
|---|---|---|
in_msgs | i64 = 0 | Messages received. |
out_msgs | i64 = 0 | Messages published. |
in_bytes | i64 = 0 | Payload bytes received. |
out_bytes | i64 = 0 | Payload bytes published. |
Conn
struct ConnConnect and pass it by reference to every call.| Name | Type | Description |
|---|---|---|
ok | bool = false | True while the connection is up. |
closed | bool = false | True once the connection is closed for good. |
draining | bool = false | True while Drain is running. |
err | str = "" | The last error text. |
url | str = "" | The URL of the server the connection is on now. |
info | ServerInfo | What the server said about itself. |
opts | Options | The options the connection was made with. |
stats | Stats | The message counters. |
Functions
JSRequest
func JSRequest(nc &: Conn, api: str, body: str, timeout_ms: int): JSResult$JS.API. start, with a JSON body.import net.nats
func main(): int:
mut nc := nats.Connect("nats://127.0.0.1:4222")
if not nats.IsConnected(nc):
println "cannot connect:", nats.LastError(nc)
ret 1
end
mut subjects := Vector {} as Vector<str>
defer subjects.Free()
subjects.Push("orders.*")
made := nats.AddStream(nc, "ORDERS", subjects, 2000)
println "stream:", made.ok, made.err
ack := nats.JSPublish(nc, "orders.new", "order 1", 2000)
println "stored at", ack.stream, ack.seq
mut h := nats.NewHeader()
nats.HeaderAdd(h, "Nats-Msg-Id", "order-2")
again := nats.JSPublishHeaders(nc, "orders.new", h, "order 2", 2000)
println again.ok, again.duplicate
info := nats.StreamInfo(nc, "ORDERS", 2000)
println info.messages, info.first_seq, info.last_seq, info.consumers
raw := nats.JSRequest(nc, "STREAM.NAMES", "", 2000)
println raw.ok
nats.AddConsumer(nc, "ORDERS", "worker", "orders.*", 2000)
batch := nats.Fetch(nc, "ORDERS", "worker", 10, 1000)
each m in batch.msgs:
println m.data, "number", nats.MsgSequence(m)
if m.data == "order 1":
nats.Ack(nc, m)
else m.data == "order 2":
nats.Nak(nc, m)
else:
nats.Term(nc, m)
end
end
if batch.msgs.Len() > 0:
nats.InProgress(nc, batch.msgs.Get(0))
end
nats.DeleteConsumer(nc, "ORDERS", "worker", 2000)
nats.PurgeStream(nc, "ORDERS", 2000)
nats.DeleteStream(nc, "ORDERS", 2000)
nats.Close(nc)
ret 0
endAddStream
func AddStream(nc &: Conn, name: str, subjects: Vector<str>, timeout_ms: int): JSResultThe example for this item is shown with the ones above: net-nats-JetStream.salam
DeleteStream
func DeleteStream(nc &: Conn, name: str, timeout_ms: int): JSResultThe example for this item is shown with the ones above: net-nats-JetStream.salam
PurgeStream
func PurgeStream(nc &: Conn, name: str, timeout_ms: int): JSResultThe example for this item is shown with the ones above: net-nats-JetStream.salam
StreamInfo
func StreamInfo(nc &: Conn, name: str, timeout_ms: int): StreamStateThe example for this item is shown with the ones above: net-nats-JetStream.salam
JSPublish
func JSPublish(nc &: Conn, subject: str, data: str, timeout_ms: int): PubAckThe example for this item is shown with the ones above: net-nats-JetStream.salam
JSPublishHeaders
func JSPublishHeaders(nc &: Conn, subject: str, h: Header, data: str, timeout_ms: int): PubAckNats-Msg-Id header lets the server drop duplicates.The example for this item is shown with the ones above: net-nats-JetStream.salam
AddConsumer
func AddConsumer(nc &: Conn, stream: str, durable: str, filter: str, timeout_ms: int): JSResultThe example for this item is shown with the ones above: net-nats-JetStream.salam
DeleteConsumer
func DeleteConsumer(nc &: Conn, stream: str, durable: str, timeout_ms: int): JSResultThe example for this item is shown with the ones above: net-nats-JetStream.salam
Fetch
func Fetch(nc &: Conn, stream: str, durable: str, batch: int, timeout_ms: int): Batchbatch messages and waits up to the timeout for them. Heartbeats are skipped.The example for this item is shown with the ones above: net-nats-JetStream.salam
Ack
func Ack(nc &: Conn, m: Msg): boolThe example for this item is shown with the ones above: net-nats-JetStream.salam
Nak
func Nak(nc &: Conn, m: Msg): boolThe example for this item is shown with the ones above: net-nats-JetStream.salam
Term
func Term(nc &: Conn, m: Msg): boolThe example for this item is shown with the ones above: net-nats-JetStream.salam
InProgress
func InProgress(nc &: Conn, m: Msg): boolThe example for this item is shown with the ones above: net-nats-JetStream.salam
MsgSequence
func MsgSequence(m: Msg): intThe example for this item is shown with the ones above: net-nats-JetStream.salam
AddPushConsumer
func AddPushConsumer(nc &: Conn, stream: str, durable: str, filter: str, deliver: str, queue: str, timeout_ms: int): JSResultdeliver subject. Subscribe to that subject first. With an empty queue flow control and heartbeats are turned on.import net.nats
func main(): int:
mut nc := nats.Connect("nats://127.0.0.1:4222")
if not nats.IsConnected(nc):
println "cannot connect:", nats.LastError(nc)
ret 1
end
sub := nats.Subscribe(nc, "deliver.orders")
made := nats.AddPushConsumer(nc, "ORDERS", "pusher", "orders.*", "deliver.orders", "", 2000)
if not made.ok:
println "consumer:", made.err
ret 1
end
until true:
m := nats.NextPush(nc, sub, 2000)
if not m.ok:
break
end
println m.data, nats.MsgSequence(m)
nats.Ack(nc, m)
end
nats.Close(nc)
ret 0
endNextPush
func NextPush(nc &: Conn, s: Subscription, timeout_ms: int): MsgNextMsg for a push consumer's subscription, but it answers flow control requests and skips idle heartbeats by itself.The example for this item is shown with the ones above: net-nats-Push.salam
KVCreate
func KVCreate(nc &: Conn, bucket: str, history: int, timeout_ms: int): JSResultKV_bucket. history is how many revisions of a key are kept.import net.nats
func main(): int:
mut nc := nats.Connect("nats://127.0.0.1:4222")
if not nats.IsConnected(nc):
println "cannot connect:", nats.LastError(nc)
ret 1
end
made := nats.KVCreate(nc, "config", 5, 2000)
println "bucket:", made.ok
put := nats.KVPut(nc, "config", "theme", "dark", 2000)
println "revision", put.seq
got := nats.KVGet(nc, "config", "theme", 2000)
if got.found:
println got.key, got.value, got.revision
end
nats.KVDelete(nc, "config", "theme", 2000)
gone := nats.KVGet(nc, "config", "theme", 2000)
println gone.found, gone.deleted
nats.KVDeleteBucket(nc, "config", 2000)
nats.Close(nc)
ret 0
endKVDeleteBucket
func KVDeleteBucket(nc &: Conn, bucket: str, timeout_ms: int): JSResultThe example for this item is shown with the ones above: net-nats-KV.salam
KVPut
func KVPut(nc &: Conn, bucket: str, key: str, value: str, timeout_ms: int): PubAckseq is the new revision. Keys follow subject rules, so no spaces or wildcards.The example for this item is shown with the ones above: net-nats-KV.salam
KVGet
func KVGet(nc &: Conn, bucket: str, key: str, timeout_ms: int): KVEntryfound false.The example for this item is shown with the ones above: net-nats-KV.salam
KVDelete
func KVDelete(nc &: Conn, bucket: str, key: str, timeout_ms: int): PubAckThe example for this item is shown with the ones above: net-nats-KV.salam
DefaultOptions
func DefaultOptions(): Optionsimport net.nats
func main(): int:
mut opts := nats.DefaultOptions()
opts.name = "billing"
opts.timeout_ms = 3000
mut nc := nats.ConnectWith("nats://127.0.0.1:4222", opts)
if not nats.IsConnected(nc):
println "cannot connect:", nats.LastError(nc)
ret 1
end
println "connected, largest payload", nats.MaxPayload(nc)
nats.Close(nc)
println nats.IsClosed(nc)
ret 0
endNewHeader
func NewHeader(): Headerimport net.nats
import str
func main:
mut h := nats.NewHeader()
nats.HeaderAdd(h, "Trace-Id", "abc")
nats.HeaderAdd(h, "Tag", "one")
nats.HeaderAdd(h, "Tag", "two")
println nats.HeaderGet(h, "trace-id"), nats.HeaderValues(h, "TAG").Len(), nats.HeaderHas(h, "nope")
nats.HeaderSet(h, "Tag", "only")
nats.HeaderDel(h, "Trace-Id")
println nats.HeaderCount(h)
println str.Replace(nats.HeaderEncode(h), "\r\n", "|")
mut code := 0
mut text := ""
back := nats.HeaderParse("NATS/1.0 503 No Responders\r\nA: 1\r\n\r\n", code, text)
println code, text, nats.HeaderGet(back, "a")
endHeaderAdd
func HeaderAdd(h &: Header, key: str, value: str)The example for this item is shown with the ones above: net-nats-Headers.salam
HeaderDel
func HeaderDel(h &: Header, key: str)The example for this item is shown with the ones above: net-nats-Headers.salam
HeaderSet
func HeaderSet(h &: Header, key: str, value: str)The example for this item is shown with the ones above: net-nats-Headers.salam
HeaderGet
func HeaderGet(h: Header, key: str): strThe example for this item is shown with the ones above: net-nats-Headers.salam
HeaderValues
func HeaderValues(h: Header, key: str): Vector<str>The example for this item is shown with the ones above: net-nats-Headers.salam
HeaderHas
func HeaderHas(h: Header, key: str): boolThe example for this item is shown with the ones above: net-nats-Headers.salam
HeaderCount
func HeaderCount(h: Header): intThe example for this item is shown with the ones above: net-nats-Headers.salam
HeaderEncode
func HeaderEncode(h: Header): strNATS/1.0 followed by one line for each header.The example for this item is shown with the ones above: net-nats-Headers.salam
HeaderParse
func HeaderParse(block: str, status &: int, status_text &: str): Header503 No Responders, come back through the two reference parameters.The example for this item is shown with the ones above: net-nats-Headers.salam
NewInbox
func NewInbox(nc: Conn): strinbox_prefix and random text.import net.nats
func main(): int:
mut nc := nats.Connect("nats://127.0.0.1:4222")
if not nats.IsConnected(nc):
println "cannot connect:", nats.LastError(nc)
ret 1
end
r := nats.Request(nc, "time.now", "", 1000)
if r.ok:
println "answer:", r.data
else:
println "no answer:", r.err
end
mut h := nats.NewHeader()
nats.HeaderAdd(h, "Trace-Id", "abc-123")
r2 := nats.RequestMsg(nc, "svc.echo", h, "ping", 1000)
println r2.ok, r2.data
inbox := nats.NewInbox(nc)
nats.PublishRequest(nc, "svc.echo", inbox, "fire")
reply := nats.Subscribe(nc, inbox)
println nats.NextMsg(nc, reply, 500).ok
println "drained:", nats.Drain(nc, 1000)
ret 0
endValidSubject
func ValidSubject(subject: str): boolimport net.nats
func main:
println nats.ValidSubject("orders.eu.new"), nats.ValidSubject("orders..new"), nats.ValidSubject("a b")
println nats.SubjectMatches("orders.*", "orders.new"), nats.SubjectMatches("orders.*", "orders.eu.new")
println nats.SubjectMatches("orders.>", "orders.eu.new"), nats.SubjectMatches("orders.>", "orders")
endSubjectMatches
func SubjectMatches(pattern: str, subject: str): bool* stands for one token and a final > for one or more.The example for this item is shown with the ones above: net-nats-Subjects.salam
Pump
func Pump(nc &: Conn, timeout_ms: int): intimport net.nats
mut seen := 0
func note(m: nats.Msg):
seen++
println "event", m.subject, m.data
end
func shout(m: nats.Msg): str:
ret "HELLO " + m.data
end
func main(): int:
mut nc := nats.Connect("nats://127.0.0.1:4222")
if not nats.IsConnected(nc):
println "cannot connect:", nats.LastError(nc)
ret 1
end
nats.SubscribeHandler(nc, "events.>", "", (m: nats.Msg): note(m) end)
nats.SubscribeReplier(nc, "greet", "", (m: nats.Msg): ret shout(m) end)
nats.Publish(nc, "events.a.b", "started")
mut fwd := nats.Msg {}
fwd.subject = "events.copy"
fwd.data = "forwarded"
nats.PublishMsg(nc, fwd)
repeat 20:
nats.Pump(nc, 100)
end
println "handled", seen
nats.Close(nc)
ret 0
endConnect
func Connect(url: str): ConnIsConnected; a failed connection has the reason in err.The example for this item is shown with the ones above: net-nats-Connect.salam
ConnectWith
func ConnectWith(url: str, opts: Options): Connservers once and keeps the first that answers.The example for this item is shown with the ones above: net-nats-Connect.salam
IsConnected
func IsConnected(nc: Conn): boolThe example for this item is shown with the ones above: net-nats-Connect.salam
IsClosed
func IsClosed(nc: Conn): boolThe example for this item is shown with the ones above: net-nats-Connect.salam
LastError
func LastError(nc: Conn): strThe example for this item is shown with the ones above: net-nats-Connect.salam
Close
func Close(nc &: Conn)Drain to finish cleanly.The example for this item is shown with the ones above: net-nats-Connect.salam
Publish
func Publish(nc &: Conn, subject: str, data: str): boolimport net.nats
func main(): int:
mut nc := nats.Connect("nats://127.0.0.1:4222")
if not nats.IsConnected(nc):
println "cannot connect:", nats.LastError(nc)
ret 1
end
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)
ret 0
endPublishRequest
func PublishRequest(nc &: Conn, subject: str, reply: str, data: str): boolThe example for this item is shown with the ones above: net-nats-Request.salam
PublishHeaders
func PublishHeaders(nc &: Conn, subject: str, h: Header, data: str): boolThe example for this item is shown with the ones above: net-nats-Headers.salam
PublishMsg
func PublishMsg(nc &: Conn, m: Msg): boolThe example for this item is shown with the ones above: net-nats-Handlers.salam
Respond
func Respond(nc &: Conn, m: Msg, data: str): boolThe example for this item is shown with the ones above: net-nats-Handlers.salam
Subscribe
func Subscribe(nc &: Conn, subject: str): SubscriptionNextMsg.The example for this item is shown with the ones above: net-nats-PubSub.salam
QueueSubscribe
func QueueSubscribe(nc &: Conn, subject: str, queue: str): SubscriptionThe example for this item is shown with the ones above: net-nats-PubSub.salam
SubscribeHandler
func SubscribeHandler(nc &: Conn, subject: str, queue: str, handler: func(Msg)): SubscriptionPump, NextMsg, Flush or Request.The example for this item is shown with the ones above: net-nats-Handlers.salam
SubscribeReplier
func SubscribeReplier(nc &: Conn, subject: str, queue: str, handler: func(Msg): str): SubscriptionThe example for this item is shown with the ones above: net-nats-Handlers.salam
Unsubscribe
func Unsubscribe(nc &: Conn, s: Subscription): boolThe example for this item is shown with the ones above: net-nats-PubSub.salam
AutoUnsubscribe
func AutoUnsubscribe(nc &: Conn, s: Subscription, max: int): boolThe example for this item is shown with the ones above: net-nats-PubSub.salam
IsValidSubscription
func IsValidSubscription(nc: Conn, s: Subscription): boolThe example for this item is shown with the ones above: net-nats-PubSub.salam
Delivered
func Delivered(nc: Conn, s: Subscription): intThe example for this item is shown with the ones above: net-nats-PubSub.salam
Pending
func Pending(nc: Conn, s: Subscription): intNextMsg.The example for this item is shown with the ones above: net-nats-PubSub.salam
NextMsg
func NextMsg(nc &: Conn, s: Subscription, timeout_ms: int): Msgok false and err timeout.The example for this item is shown with the ones above: net-nats-PubSub.salam
Flush
func Flush(nc &: Conn, timeout_ms: int): boolThe example for this item is shown with the ones above: net-nats-PubSub.salam
Request
func Request(nc &: Conn, subject: str, data: str, timeout_ms: int): Msgno responders.The example for this item is shown with the ones above: net-nats-Request.salam
RequestMsg
func RequestMsg(nc &: Conn, subject: str, h: Header, data: str, timeout_ms: int): MsgRequest but with headers.The example for this item is shown with the ones above: net-nats-Request.salam
Drain
func Drain(nc &: Conn, timeout_ms: int): boolThe example for this item is shown with the ones above: net-nats-Request.salam
MaxPayload
func MaxPayload(nc: Conn): intThe example for this item is shown with the ones above: net-nats-Connect.salam
SubscriptionCount
func SubscriptionCount(nc: Conn): intThe example for this item is shown with the ones above: net-nats-PubSub.salam
IsReconnecting
func IsReconnecting(nc: Conn): boolimport net.nats
func main(): int:
mut opts := nats.DefaultOptions()
opts.servers.Push("nats://10.0.0.2:4222")
opts.servers.Push("nats://10.0.0.3:4222")
opts.max_reconnects = 20
opts.reconnect_wait_ms = 500
opts.reconnect_buffer = 1048576
mut nc := nats.ConnectWith("nats://10.0.0.1:4222", opts)
if not nats.IsConnected(nc):
println "cannot connect:", nats.LastError(nc)
ret 1
end
sub := nats.Subscribe(nc, "metrics.>")
until not nats.IsClosed(nc):
m := nats.NextMsg(nc, sub, 1000)
if m.ok:
println m.subject, m.data
end
if nats.IsReconnecting(nc):
println "link is down, buffered", nats.BufferedBytes(nc), "bytes"
nats.Publish(nc, "audit", "waiting for the server")
end
if nats.IsClosed(nc):
break
end
end
println "reconnected", nats.Reconnects(nc), "times"
nats.Close(nc)
ret 0
endReconnects
func Reconnects(nc: Conn): intThe example for this item is shown with the ones above: net-nats-Reconnect.salam
BufferedBytes
func BufferedBytes(nc: Conn): intThe example for this item is shown with the ones above: net-nats-Reconnect.salam