Standard library · Network

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 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.

net-nats-headers.salam
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")
end
Output
acme 3 true
true false

Subjects 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.

net-nats-guide-subjects.salam
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.>")
end
Output
orders.* orders.created true
orders.* orders.created.eu false
orders.> orders.created.eu true
orders.> orders false
*.created orders.created true
orders.created orders.created true
false false false
false false true

Request 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.

net-nats-guide-request.salam
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
end

Queue 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.

net-nats-guide-queue.salam
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
end

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.

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 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.

Types

JSResult

#
struct JSResult

The answer to a JetStream API call: ok is false when the call failed or the server said no.

NameTypeDescription
okbool = falseTrue when the call worked.
errstr = ""The error text from the server or the client, empty when the call worked.
codeint = 0The JetStream error code, for example 10059 for a stream that does not exist. Zero when there is none.
rawstr = ""The JSON the server answered with, for fields this package does not read.

StreamState

#
struct StreamState

What StreamInfo returns about a stream.

NameTypeDescription
okbool = falseTrue when the information was read.
errstr = ""The error text when it was not.
namestr = ""The name of the stream.
messagesint = 0The number of messages stored.
bytesint = 0The size of the stored messages in bytes.
first_seqint = 0The sequence number of the oldest stored message.
last_seqint = 0The sequence number of the newest stored message.
consumersint = 0How many consumers the stream has.

PubAck

#
struct PubAck

The server's receipt for a message published to a stream.

NameTypeDescription
okbool = falseTrue when the stream stored the message.
errstr = ""The error text when it did not; no responders means no stream listens on the subject.
streamstr = ""The name of the stream that stored the message.
seqint = 0The sequence number the message got in the stream.
duplicatebool = falseTrue when the server saw the same Nats-Msg-Id header recently and ignored the message.

Batch

#
struct Batch

The messages one Fetch call brought back.

NameTypeDescription
msgsVector<Msg>The messages, in order. Acknowledge each one.
errstr = ""Why the batch is empty: a timeout, or the server's status text. Empty when there are messages.

KVEntry

#
struct KVEntry

The result of reading a key from a key value bucket.

NameTypeDescription
okbool = falseTrue when the call itself worked, even if the key is not there.
foundbool = falseTrue when the key exists and holds a value.
deletedbool = falseTrue when the newest entry for the key is a delete marker.
keystr = ""The key that was asked for.
valuestr = ""The value, empty when the key was not found.
revisionint = 0The revision of the entry: its sequence number in the bucket's stream.
errstr = ""The error text, or key not found.

Header

#
struct Header

A list of message headers. A name can appear more than once, and names compare without regard to case.

NameTypeDescription
keysVector<str>The header names, in the order they were added.
valuesVector<str>The values, one for each name in keys.

Msg

#
struct Msg

A message received from the server, or the empty result of a call that failed.

NameTypeDescription
okbool = falseTrue for a real message. A timeout or an error gives a message with ok false and the reason in err.
errstr = ""The reason a call returned no message, such as timeout or no responders.
subjectstr = ""The subject the message was published to.
replystr = ""The subject to answer on, empty when the sender does not want an answer.
datastr = ""The payload as text. It stops at the first NUL byte.
headerHeaderThe headers of the message.
sidint = 0The subscription id the message arrived on.
statusint = 0The 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_textstr = ""The text that goes with status.

Subscription

#
struct Subscription

A handle for one subscription, used to read its messages and to cancel it.

NameTypeDescription
okbool = falseTrue when the subscription was made.
sidint = 0The id the server knows the subscription by.
subjectstr = ""The subject or pattern subscribed to.
queuestr = ""The queue group, empty for a plain subscription.

ServerInfo

#
struct ServerInfo

What the server said about itself in its INFO message when the connection opened.

NameTypeDescription
server_idstr = ""The unique id of the server.
server_namestr = ""The name of the server.
versionstr = ""The server's version.
hoststr = ""The host the server is listening on.
portint = 0The port the server is listening on.
protoint = 0The protocol version the server speaks.
client_idint = 0The id the server gave this connection.
max_payloadint = 1048576The largest message the server accepts, in bytes.
headersbool = falseTrue when the server supports headers.
tls_requiredbool = falseTrue when the server wants TLS.
auth_requiredbool = falseTrue when the server wants credentials.
jetstreambool = falseTrue when JetStream is turned on.
rawstr = ""The whole INFO JSON, for fields this package does not read.

Options

#
struct Options

Settings for ConnectWith. Start from DefaultOptions and change what you need.

NameTypeDescription
namestr = ""A name for this client, shown in the server's connection list.
userstr = ""The user name. A user:password@ part in the URL does the same.
passwordstr = ""The password for user.
tokenstr = ""An authentication token. A URL of the form nats://token@host sets it too.
no_echobool = falseWhen true the server does not send this connection the messages it publishes itself.
verbosebool = falseAsk the server to answer every command with +OK. Rarely useful.
pedanticbool = falseAsk the server to check subjects strictly.
securebool = falseUse TLS even when the server does not require it. A tls:// URL does the same.
insecure_skip_verifybool = falseDo not check the server's certificate. For testing only.
timeout_msint = 5000How long connecting may take, in milliseconds. Zero means 5000.
ping_interval_msint = 120000How long the line may be silent before the client sends a PING. Zero turns the check off.
max_pings_outint = 2How many PINGs may go unanswered before the connection counts as stale.
inbox_prefixstr = "_INBOX"The start of the private subjects used for replies. Change it when your permissions only allow a certain prefix.
serversVector<str>More servers to try. The URL given to ConnectWith comes first, then these in order.
max_reconnectsint = 0How many failed attempts in a row end the reconnecting: 0 turns reconnecting off, a negative number never gives up.
reconnect_wait_msint = 2000How long to wait between attempts in milliseconds.
reconnect_bufferint = 8388608How many bytes of publishes are held while the link is down. Over the limit, Publish returns false.

Stats

#
struct Stats

Counters for one connection.

NameTypeDescription
in_msgsi64 = 0Messages received.
out_msgsi64 = 0Messages published.
in_bytesi64 = 0Payload bytes received.
out_bytesi64 = 0Payload bytes published.

Conn

#
struct Conn

One connection to a NATS server. Make it with Connect and pass it by reference to every call.

NameTypeDescription
okbool = falseTrue while the connection is up.
closedbool = falseTrue once the connection is closed for good.
drainingbool = falseTrue while Drain is running.
errstr = ""The last error text.
urlstr = ""The URL of the server the connection is on now.
infoServerInfoWhat the server said about itself.
optsOptionsThe options the connection was made with.
statsStatsThe message counters.

Functions

JSRequest

#
func JSRequest(nc &: Conn, api: str, body: str, timeout_ms: int): JSResult

Calls any JetStream API subject, given without the $JS.API. start, with a JSON body.

net-nats-JetStream.salam
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
end

AddStream

#
func AddStream(nc &: Conn, name: str, subjects: Vector<str>, timeout_ms: int): JSResult

Creates a file-backed stream that stores messages published to the given subjects.

The example for this item is shown with the ones above: net-nats-JetStream.salam

DeleteStream

#
func DeleteStream(nc &: Conn, name: str, timeout_ms: int): JSResult

Deletes a stream and its messages.

The example for this item is shown with the ones above: net-nats-JetStream.salam

PurgeStream

#
func PurgeStream(nc &: Conn, name: str, timeout_ms: int): JSResult

Removes every message from a stream and keeps the stream.

The example for this item is shown with the ones above: net-nats-JetStream.salam

StreamInfo

#
func StreamInfo(nc &: Conn, name: str, timeout_ms: int): StreamState

Reads a stream's message counts and consumer count.

The 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): PubAck

Publishes to a stream and waits for the receipt.

The 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): PubAck

Publishes with headers. A Nats-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): JSResult

Creates a durable pull consumer with explicit acknowledgements. An empty filter takes every subject of the stream.

The 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): JSResult

Deletes a durable consumer.

The 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): Batch

Asks a pull consumer for up to batch 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): bool

Tells the server the message is done.

The example for this item is shown with the ones above: net-nats-JetStream.salam

Nak

#
func Nak(nc &: Conn, m: Msg): bool

Tells the server the message failed so it will send it again.

The example for this item is shown with the ones above: net-nats-JetStream.salam

Term

#
func Term(nc &: Conn, m: Msg): bool

Tells the server never to send this message again.

The example for this item is shown with the ones above: net-nats-JetStream.salam

InProgress

#
func InProgress(nc &: Conn, m: Msg): bool

Tells the server work is still going on, which resets its acknowledgement timer.

The example for this item is shown with the ones above: net-nats-JetStream.salam

MsgSequence

#
func MsgSequence(m: Msg): int

Reads the stream sequence number out of the reply subject of a JetStream message. Zero when the message is not from JetStream.

The 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): JSResult

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

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
end

NextPush

#
func NextPush(nc &: Conn, s: Subscription, timeout_ms: int): Msg

Like NextMsg 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): JSResult

Creates a key value bucket, which is a stream named KV_bucket. history is how many revisions of a key are kept.

net-nats-KV.salam
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
end

KVDeleteBucket

#
func KVDeleteBucket(nc &: Conn, bucket: str, timeout_ms: int): JSResult

Deletes a bucket with all its keys.

The 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): PubAck

Writes a value and returns the receipt; its seq 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): KVEntry

Reads the latest value of a key. A missing or deleted key gives found 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): PubAck

Marks a key deleted by writing a delete marker. Older revisions stay in the history.

The example for this item is shown with the ones above: net-nats-KV.salam

DefaultOptions

#
func DefaultOptions(): Options

Returns the default options: five seconds to connect, a ping every two minutes and no reconnecting.

net-nats-Connect.salam
import 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
end

NewHeader

#
func NewHeader(): Header

Returns an empty header list.

net-nats-Headers.salam
import 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")
end
Output
abc 2 false
1
NATS/1.0|Tag: only||
503 No Responders 1

HeaderAdd

#
func HeaderAdd(h &: Header, key: str, value: str)

Adds a header. Adding a name again keeps both values.

The example for this item is shown with the ones above: net-nats-Headers.salam

HeaderDel

#
func HeaderDel(h &: Header, key: str)

Removes every header with this name.

The example for this item is shown with the ones above: net-nats-Headers.salam

HeaderSet

#
func HeaderSet(h &: Header, key: str, value: str)

Replaces every header with this name by a single one.

The example for this item is shown with the ones above: net-nats-Headers.salam

HeaderGet

#
func HeaderGet(h: Header, key: str): str

Returns the first value of a header, or an empty text. The name is compared without regard to case.

The example for this item is shown with the ones above: net-nats-Headers.salam

HeaderValues

#
func HeaderValues(h: Header, key: str): Vector<str>

Returns every value of a header. Free the vector.

The example for this item is shown with the ones above: net-nats-Headers.salam

HeaderHas

#
func HeaderHas(h: Header, key: str): bool

True when a header with this name exists.

The example for this item is shown with the ones above: net-nats-Headers.salam

HeaderCount

#
func HeaderCount(h: Header): int

The number of header lines.

The example for this item is shown with the ones above: net-nats-Headers.salam

HeaderEncode

#
func HeaderEncode(h: Header): str

Writes the headers in the wire form, NATS/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): Header

Reads a wire header block. The status code and text on the first line, such as 503 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): str

Returns a fresh private subject to receive an answer on, built from inbox_prefix and random text.

net-nats-Request.salam
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
end

ValidSubject

#
func ValidSubject(subject: str): bool

True when the text is a legal subject to publish to: tokens separated by dots, no empty token, no spaces and no wildcards.

net-nats-Subjects.salam
import 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")
end
Output
true false false
true false
true false

SubjectMatches

#
func SubjectMatches(pattern: str, subject: str): bool

True when a subject matches a pattern. * 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): int

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.

net-nats-Handlers.salam
import 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
end

Connect

#
func Connect(url: str): Conn

Connects to a server with the default options. Check IsConnected; 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): Conn

Connects with the given options. It tries the URL and then each entry of servers 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): bool

True when the connection is up. It is false while reconnecting.

The example for this item is shown with the ones above: net-nats-Connect.salam

IsClosed

#
func IsClosed(nc: Conn): bool

True once the connection is closed for good.

The example for this item is shown with the ones above: net-nats-Connect.salam

LastError

#
func LastError(nc: Conn): str

The text of the last error.

The example for this item is shown with the ones above: net-nats-Connect.salam

Close

#
func Close(nc &: Conn)

Closes the connection at once. Anything not yet sent is lost; use 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): bool

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

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
end

PublishRequest

#
func PublishRequest(nc &: Conn, subject: str, reply: str, data: str): bool

Publishes with a reply subject, so that the receiver can answer on it.

The 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): bool

Publishes with headers. The server must support headers.

The example for this item is shown with the ones above: net-nats-Headers.salam

PublishMsg

#
func PublishMsg(nc &: Conn, m: Msg): bool

Publishes a whole message: its subject, reply, headers and data.

The example for this item is shown with the ones above: net-nats-Handlers.salam

Respond

#
func Respond(nc &: Conn, m: Msg, data: str): bool

Answers a message on its reply subject. Returns false when the message has none.

The example for this item is shown with the ones above: net-nats-Handlers.salam

Subscribe

#
func Subscribe(nc &: Conn, subject: str): Subscription

Subscribes to a subject or a pattern. Read the messages with NextMsg.

The example for this item is shown with the ones above: net-nats-PubSub.salam

QueueSubscribe

#
func QueueSubscribe(nc &: Conn, subject: str, queue: str): Subscription

Subscribes as part of a queue group: each message goes to only one member of the group.

The 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)): Subscription

Subscribes and calls the handler for every message. The handler runs while you call Pump, 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): Subscription

Subscribes and sends whatever the handler returns back to the message's reply subject.

The example for this item is shown with the ones above: net-nats-Handlers.salam

Unsubscribe

#
func Unsubscribe(nc &: Conn, s: Subscription): bool

Cancels a subscription and drops its waiting messages.

The example for this item is shown with the ones above: net-nats-PubSub.salam

AutoUnsubscribe

#
func AutoUnsubscribe(nc &: Conn, s: Subscription, max: int): bool

Cancels the subscription by itself after this many messages in total. The limit survives a reconnect.

The example for this item is shown with the ones above: net-nats-PubSub.salam

IsValidSubscription

#
func IsValidSubscription(nc: Conn, s: Subscription): bool

True while the subscription is active.

The example for this item is shown with the ones above: net-nats-PubSub.salam

Delivered

#
func Delivered(nc: Conn, s: Subscription): int

How many messages the subscription has received.

The example for this item is shown with the ones above: net-nats-PubSub.salam

Pending

#
func Pending(nc: Conn, s: Subscription): int

How many received messages are waiting to be read with NextMsg.

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): Msg

Returns the next message of a subscription, waiting up to the timeout. On a timeout the result has ok 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): bool

Sends a PING and waits for the PONG, which proves the server has everything sent so far. It waits through a reconnect too.

The 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): Msg

Sends a message and waits for one answer. A request nobody listens to ends at once with no 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): Msg

Like Request 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): bool

Stops the subscriptions, handles what is already on its way, flushes and closes. Returns false if the flush timed out.

The example for this item is shown with the ones above: net-nats-Request.salam

MaxPayload

#
func MaxPayload(nc: Conn): int

The largest payload the server accepts, in bytes.

The example for this item is shown with the ones above: net-nats-Connect.salam

SubscriptionCount

#
func SubscriptionCount(nc: Conn): int

The number of active subscriptions.

The example for this item is shown with the ones above: net-nats-PubSub.salam

IsReconnecting

#
func IsReconnecting(nc: Conn): bool

True while the link is down and the client is trying to get it back.

net-nats-Reconnect.salam
import 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
end

Reconnects

#
func Reconnects(nc: Conn): int

How many times the connection has been re-established.

The example for this item is shown with the ones above: net-nats-Reconnect.salam

BufferedBytes

#
func BufferedBytes(nc: Conn): int

How many bytes of publishes are waiting for the link to come back.

The example for this item is shown with the ones above: net-nats-Reconnect.salam