XU XUv0.16.0

#github.com/xulang-org/packages/nats

import: nats #github.com/xulang-org/packages/nats

counts: 10 functions, 24 methods, 5 types, 0 constants, 0 method sets

NATS high-performance cloud-native messaging driver for Xu. Features Standard NATS text protocol implementation in 100% pure Xu. High-throughput publish/subscribe (PUB/SUB). Queue Groups (distributed load-balanced worker queues). Request-Reply RPC pattern with dynamic inbox routing. Automatic PING/PONG heartbeat management.

github.com/xulang-org/packages · 1.17.2 · Install and use

Examples · API declarations

Examples

These sources come from the official examples repository and can be copied or downloaded. Run them with a local Xu SDK in the complete project; network, database, and desktop examples require the corresponding services or assets.

24_standalone_nats/main.xu

Required SDK: Xu 0.8.3 · Complete project · Download source

XuLocal SDK example
@main

nats #github.com/xulang-org/packages/nats
#os

fn main() int {
    println("=== NATS Cloud-Native Messaging Standalone Integration Test ===")
    addr := "127.0.0.1:4222"
    println("Connecting to NATS at " + addr + "...")

    $nc := nats.connect(addr + "") >>> (err) {
        println("Connection to NATS failed: " + err.msg())
        << 1
    }

    ping_ok := nc.ping() >>> (err) {
        println("Ping failed: " + err.msg())
        << 1
    }
    println("1. NATS Ping response: " + str(ping_ok))

    // 2. Subscribe to subject
    topic := "xu.events"
    sub := nc.subscribe(topic + "") >>> (err) {
        println("Subscribe failed: " + err.msg())
        << 1
    }
    println("2. Subscribed to subject: " + sub.subject + " (sid=" + sub.sid + ")")

    // 3. Publish a message
    payload := "Hello NATS from Xu Programming Language!"
    nc.publish(topic + "", payload + "") >>> (err) {
        println("Publish failed: " + err.msg())
        << 1
    }
    println("3. Published payload: " + payload)

    // 4. Receive the message
    msg := nc.next_msg() >>> (err) {
        println("Receive failed: " + err.msg())
        << 1
    }
    println("4. Successfully received message:")
    println("   - Subject: " + msg.subject)
    println("   - Sid: " + msg.sid)
    println("   - Data: " + msg.data)

    // 5. Test Queue Group (load-balanced worker queue)
    q_sub := nc.queue_subscribe("xu.tasks", "workers") >>> (err) {
        println("Queue subscribe failed: " + err.msg())
        << 1
    }
    println("5. Queue Group subscribed: xu.tasks -> workers (sid=" + q_sub.sid + ")")

    nc.publish("xu.tasks", "task_payload_123") >>> (err) {
        << 1
    }
    q_msg := nc.next_msg() >>> (err) {
        << 1
    }
    println("6. Queue Group received task: " + q_msg.data)

    nc.unsubscribe(sub) >>> (err) {
        << 1
    }
    nc.unsubscribe(q_sub) >>> (err) {
        << 1
    }
    nc.close()

    // 7. NATS Connection Pool Deep Verification
    println("7. Testing NATS Connection Pool with Reuse & Concurrency...")
    pool := nats.open_pool("127.0.0.1:4222", 5)
    $c1 := pool.get() >>> (err) {
        println("Pool get c1 failed: " + err.msg())
        << 1
    }
    fd_first := c1.fd
    c1_ok := c1.ping() >>> (err) {
        << 1
    }
    println("   Pool c1 ping: " + str(c1_ok) + " (fd=" + str(fd_first) + ")")
    pool.put(c1)

    // Verify Pool Connection REUSE
    $c2 := pool.get() >>> (err) {
        println("Pool get c2 failed: " + err.msg())
        << 1
    }
    fd_second := c2.fd
    if fd_first == fd_second {
        println("   [PASS] NATS Pool Connection REUSE verified! (fd1 == fd2: " + str(fd_first) + ")")
    } else {
        println("   [WARN] fd1 != fd2 (fd1=" + str(fd_first) + ", fd2=" + str(fd_second) + ")")
    }

    // Concurrent borrow another connection
    $c3 := pool.get() >>> (err) {
        println("Pool get c3 failed: " + err.msg())
        << 1
    }
    fd_third := c3.fd
    if fd_second != fd_third {
        println("   [PASS] NATS Pool Multi-connection concurrency verified! (fd2=" + str(fd_second) + " != fd3=" + str(fd_third) + ")")
    }

    // Pool Direct Publish
    pool.publish("pool.notify", "notification from nats pool") >>> (err) {
        << 1
    }
    println("   [PASS] NATS Pool direct publish succeeded.")

    pool.put(c2)
    pool.put(c3)
    pool.close()
    println("   [PASS] NATS Pool closed cleanly.")

    println("=== NATS Tests Completed Successfully! ===")
    << 0
}

API declarations

open

XuAPI
pub fn open(addr string) Client

Purpose

Open resource or establish connection. Throws on failure; handle the error or propagate it to the caller.

Parameters

addr string
address (string)

Returns

Client — a value of this type

open_pool

XuAPI
pub fn open_pool(addr string, max_idle int) Pool

Purpose

Open pool.

Parameters

addr string
address (string)
max_idle int
max_idle (int)

Returns

Pool — a value of this type

See usage example

struct Client

XuAPI
pub struct Client {
    pub fd int
    pub buf string
    pub addr string
    pub next_sid int
    pub server_info string
}

Purpose

Nats Client session maintaining connection and operations.

Public fields

fd int
file descriptor
buf string
buffer
addr string
address
next_sid int
field (int)
server_info string
field (string)

($&Client) read_line

XuAPI
pub fn (c $&Client) read_line() string

Purpose

Operation on $&Client: read line. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).

Returns

string — result string

($&Client) read_bytes

XuAPI
pub fn (c $&Client) read_bytes(n int) string

Purpose

Operation on $&Client: read through delim (inclusive). Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
n int
count, length, or limit (int)

Returns

string — result string

($&Client) write_raw

XuAPI
pub fn (c $&Client) write_raw(data string) int

Purpose

Operation on $&Client: write raw. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
data string
data (string)

Returns

int — a value of this type

connect

XuAPI
pub fn connect(addr string) Client

Purpose

Execute connect.

Parameters

addr string
address (string)

Returns

Client — a value of this type

See usage example

connect_auth

XuAPI
pub fn connect_auth(addr string, user string, pass string) Client

Purpose

Connect auth. Throws on failure; handle the error or propagate it to the caller.

Parameters

addr string
address (string)
user string
user (string)
pass string
pass (string)

Returns

Client — a value of this type

($&Client) ping

XuAPI
pub fn (c $&Client) ping() bool

Purpose

Send a ping heartbeat request to verify connection liveness. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).

Returns

bool — true or false

($&Client) publish

XuAPI
pub fn (c $&Client) publish(subject string, data string) int

Purpose

Publish message data to the given topic or channel. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
subject string
subject (string)
data string
data (string)

Returns

int — a value of this type

($&Client) publish_request

XuAPI
pub fn (c $&Client) publish_request(subject string, reply_to string, data string) int

Purpose

Operation on $&Client: publish request. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
subject string
subject (string)
reply_to string
reply_to (string)
data string
data (string)

Returns

int — a value of this type

($&Client) subscribe

XuAPI
pub fn (c $&Client) subscribe(subject string) Subscription

Purpose

Execute subscribe on $&Client. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
subject string
subject (string)

Returns

Subscription — a value of this type

($&Client) queue_subscribe

XuAPI
pub fn (c $&Client) queue_subscribe(subject string, queue_group string) Subscription

Purpose

Operation on $&Client: queue subscribe. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
subject string
subject (string)
queue_group string
queue_group (string)

Returns

Subscription — a value of this type

($&Client) unsubscribe

XuAPI
pub fn (c $&Client) unsubscribe(sub Subscription) int

Purpose

Execute unsubscribe on $&Client. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
sub Subscription
substring (Subscription)

Returns

int — a value of this type

($&Client) next_msg

XuAPI
pub fn (c $&Client) next_msg() Message

Purpose

Operation on $&Client: next msg. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).

Returns

Message — a value of this type

($&Client) request

XuAPI
pub fn (c $&Client) request(subject string, data string) Message

Purpose

Execute request on $&Client. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
subject string
subject (string)
data string
data (string)

Returns

Message — a value of this type

($&Client) close

XuAPI
pub fn (c $&Client) close() int

Purpose

Operation on $&Client: close the resource.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).

Returns

int — a value of this type

struct Message

XuAPI
pub struct Message {
    pub subject string
    pub sid string
    pub reply_to string
    pub data string
}

Purpose

Structure encapsulating subject, sid, reply_to, data.

Public fields

subject string
field (string)
sid string
field (string)
reply_to string
field (string)
data string
data

new_msg

XuAPI
pub fn new_msg(subject string, sid string, reply_to string, data string) Message

Purpose

Construct msg.

Parameters

subject string
subject (string)
sid string
sid (string)
reply_to string
reply_to (string)
data string
data (string)

Returns

Message — a value of this type

struct Pool

XuAPI
pub struct Pool {
    pub url string
    pub auth_user string
    pub auth_pass string
    pub idle chan int
    pub max_idle int
}

Purpose

Connection Pool for NATS messaging system. Uses channel of socket file descriptors for lightweight and high-throughput pooling.

Public fields

url string
field (string)
auth_user string
field (string)
auth_pass string
field (string)
idle chan int
field (channel; type chan int)
max_idle int
field (int)

new_pool

XuAPI
pub fn new_pool(url string, max_idle int) Pool

Purpose

Construct pool.

Parameters

url string
url (string)
max_idle int
max_idle (int)

Returns

Pool — a value of this type

new_pool_auth

XuAPI
pub fn new_pool_auth(url string, user string, pass string, max_idle int) Pool

Purpose

Construct pool auth.

Parameters

url string
url (string)
user string
user (string)
pass string
pass (string)
max_idle int
max_idle (int)

Returns

Pool — a value of this type

(&Pool) get

XuAPI
pub fn (p &Pool) get() Client

Purpose

Execute get on &Pool. Throws on failure; handle the error or propagate it to the caller.

Parameters

p &Pool
The Pool instance used by this call (borrow).

Returns

Client — a value of this type

(&Pool) put_conn

XuAPI
pub fn (p &Pool) put_conn(fd int)

Purpose

Operation on &Pool: put connection.

Parameters

p &Pool
The Pool instance used by this call (borrow).
fd int
file descriptor (int)

Returns

This call does not return a value.

(&Pool) put

XuAPI
pub fn (p &Pool) put(c Client)

Purpose

Store or update the value associated with the specified key.

Parameters

p &Pool
The Pool instance used by this call (borrow).
c Client
byte or character code (Client)

Returns

This call does not return a value.

(&Pool) publish

XuAPI
pub fn (p &Pool) publish(subject string, data string) int

Purpose

Publish message data to the given topic or channel. Throws on failure; handle the error or propagate it to the caller.

Parameters

p &Pool
The Pool instance used by this call (borrow).
subject string
subject (string)
data string
data (string)

Returns

int — a value of this type

(&Pool) close

XuAPI
pub fn (p &Pool) close()

Purpose

Operation on &Pool: close the resource.

Parameters

p &Pool
The Pool instance used by this call (borrow).

Returns

This call does not return a value.

struct Subscription

XuAPI
pub struct Subscription {
    pub sid string
    pub subject string
    pub queue_group string
}

Purpose

Structure encapsulating sid, subject, queue_group.

Public fields

sid string
field (string)
subject string
field (string)
queue_group string
field (string)

new_sub

XuAPI
pub fn new_sub(sid string, subject string, queue_group string) Subscription

Purpose

Construct sub.

Parameters

sid string
sid (string)
subject string
subject (string)
queue_group string
queue_group (string)

Returns

Subscription — a value of this type

struct TlsClient

XuAPI
pub struct TlsClient {
    pub conn transport.Conn
    pub host string
    pub port int
}

Purpose

Nats Client session maintaining connection and operations.

Public fields

conn transport.Conn
field (transport.Conn)
host string
host
port int
port

tls_connect

XuAPI
pub fn tls_connect(endpoint string, default_port int) TlsClient

Purpose

Tls connect. Throws on failure; handle the error or propagate it to the caller.

Parameters

endpoint string
endpoint (string)
default_port int
default_port (int)

Returns

TlsClient — a value of this type

tls_connect_config

XuAPI
pub fn tls_connect_config(endpoint string, default_port int, cfg tls.Config) TlsClient

Purpose

Tls connect config. Throws on failure; handle the error or propagate it to the caller.

Parameters

endpoint string
endpoint (string)
default_port int
default_port (int)
cfg tls.Config
cfg (tls.Config)

Returns

TlsClient — a value of this type

($&TlsClient) write_all

XuAPI
pub fn (c $&TlsClient) write_all(data string) int

Purpose

Operation on $&TlsClient: write all. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&TlsClient
The TlsClient instance used by this call (exclusive borrow).
data string
data (string)

Returns

int — a value of this type

($&TlsClient) read

XuAPI
pub fn (c $&TlsClient) read(max int) string

Purpose

Operation on $&TlsClient: read up to max bytes. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&TlsClient
The TlsClient instance used by this call (exclusive borrow).
max int
maximum (int)

Returns

string — result string

($&TlsClient) read_exact

XuAPI
pub fn (c $&TlsClient) read_exact(need int) string

Purpose

Operation on $&TlsClient: read exact. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&TlsClient
The TlsClient instance used by this call (exclusive borrow).
need int
need (int)

Returns

string — result string

($&TlsClient) close

XuAPI
pub fn (c $&TlsClient) close() int

Purpose

Operation on $&TlsClient: close the resource. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&TlsClient
The TlsClient instance used by this call (exclusive borrow).

Returns

int — a value of this type

($&TlsClient) set_deadline

XuAPI
pub fn (c $&TlsClient) set_deadline(t_ns int) int

Purpose

Operation on $&TlsClient: set deadline. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&TlsClient
The TlsClient instance used by this call (exclusive borrow).
t_ns int
t_ns (int)

Returns

int — a value of this type

($&TlsClient) set_read_deadline

XuAPI
pub fn (c $&TlsClient) set_read_deadline(t_ns int) int

Purpose

Operation on $&TlsClient: set read deadline. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&TlsClient
The TlsClient instance used by this call (exclusive borrow).
t_ns int
t_ns (int)

Returns

int — a value of this type

($&TlsClient) set_write_deadline

XuAPI
pub fn (c $&TlsClient) set_write_deadline(t_ns int) int

Purpose

Operation on $&TlsClient: set write deadline. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&TlsClient
The TlsClient instance used by this call (exclusive borrow).
t_ns int
t_ns (int)

Returns

int — a value of this type