XU XUv0.16.0

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

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

counts: 31 functions, 24 methods, 4 types, 0 constants, 0 method sets

Apache Kafka High-Performance Distributed Event Streaming Driver for Xu Features Pure native Kafka Wire Protocol implementation (TCP socket + Big-Endian framing). IEEE CRC32 message verification via standard library #hash/crc32. High-throughput Produce & Fetch operations with partition targeting. Heartbeat probe via ApiVersions & Metadata APIs. Connection pooling via reusable TCP socket channels. Full compatibility with Apache Kafka 2.x, 3.x, and 4.x (KRaft & ZooKeeper modes).

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.

33_standalone_kafka/main.xu

Required SDK: Xu 0.8.3 · Complete project · Download source

XuLocal SDK example
@main

kafka #github.com/xulang-org/packages/kafka
#errors

fn verify_kafka_ping() {
    println("--- 1. Testing Kafka Heartbeat & ApiVersions Ping ---")
    $client := kafka.open("127.0.0.1:9092") >>> (err) {
        println("   [FAIL] Connect error: " + err.msg())
        <<
    }
    is_ok := client.ping()
    if is_ok {
        println("   [PASS] Kafka ApiVersions heartbeat succeeded.")
    } else {
        println("   [FAIL] Kafka ping failed.")
    }
    client.close()
}

fn verify_kafka_produce_fetch() {
    println("\n--- 2. Testing Kafka Produce & Fetch Operations ---")
    $client := kafka.open("127.0.0.1:9092") >>> (err) {
        println("   [FAIL] Connect error: " + err.msg())
        <<
    }

    topic := "xu_test_topic"
    partition := 0

    // Ensure metadata / auto create topic
    client.metadata(topic + "")

    // 1. Produce message
    msg := "Antigravity event message from Xu language"
    println("   Producing message to topic '" + topic + "': " + msg)
    offset := client.produce_key_value(topic + "", partition, "event-key-1", msg + "") >>> (err) {
        println("   [FAIL] Produce failed: " + err.msg())
        client.close()
        <<
    }
    println("   [PASS] Message produced successfully at offset: " + str(offset))

    // 2. Fetch message back
    messages := client.fetch(topic + "", partition, offset) >>> (err) {
        println("   [FAIL] Fetch failed: " + err.msg())
        client.close()
        <<
    }
    println("   Fetched messages count: " + str(messages.len))
    $found := false
    $i := 0
    while i < messages.len {
        println("   Message[" + str(i) + "]: " + messages[i])
        if messages[i] == msg {
            found = true
        }
        i = i + 1
    }

    if found {
        println("   [PASS] Produced message was verified in fetch output!")
    } else {
        println("   [WARN] Message not matched in first fetch chunk (may require offset adjustment).")
    }

    client.close()
}

fn verify_kafka_pool() {
    println("\n--- 3. Testing Kafka Connection Pool ---")
    $p := kafka.open_pool("127.0.0.1:9092", "xu-pool-tester", 5)

    // 1. Connection Reuse Test
    $c1 := p.get() >>> (err) {
        println("   [FAIL] Failed to get c1: " + err.msg())
        <<
    }
    fd1 := c1.fd
    println("   Borrow 1 fd: " + str(fd1))
    p.put(c1)

    $c2 := p.get() >>> (err) {
        println("   [FAIL] Failed to get c2: " + err.msg())
        <<
    }
    fd2 := c2.fd
    println("   Borrow 2 (after return) fd: " + str(fd2))
    if fd1 == fd2 {
        println("   [PASS] Connection reused successfully (fd " + str(fd1) + " == " + str(fd2) + ")")
    } else {
        println("   [WARN] Different fd allocated: " + str(fd1) + " vs " + str(fd2))
    }

    // 2. Multi-connection concurrent borrow
    $c3 := p.get() >>> (err) {
        println("   [FAIL] Failed to get c3: " + err.msg())
        <<
    }
    fd3 := c3.fd
    println("   Borrow 3 (concurrently) fd: " + str(fd3))
    if fd2 != fd3 {
        println("   [PASS] Concurrently allocated distinct fds (" + str(fd2) + " != " + str(fd3) + ")")
    } else {
        println("   [FAIL] Expected distinct fds for concurrent connections!")
    }
    p.put(c2)
    p.put(c3)

    // 3. Delegated Produce & Fetch via Pool
    println("   Testing delegated operations via pool...")
    pool_topic := "xu_pool_topic"
    pool_msg := "pool message payload test"

    offset := p.produce_key_value(pool_topic + "", 0, "pk1", pool_msg + "") >>> (err) {
        println("   [FAIL] Pool produce failed: " + err.msg())
        <<
    }
    println("   [PASS] Message produced via pool at offset: " + str(offset))

    msgs := p.fetch(pool_topic + "", 0, offset) >>> (err) {
        println("   [FAIL] Pool fetch failed: " + err.msg())
        <<
    }
    println("   Fetched messages via pool count: " + str(msgs.len))
    $found := false
    $i := 0
    while i < msgs.len {
        if msgs[i] == pool_msg {
            found = true
        }
        i = i + 1
    }
    if found {
        println("   [PASS] Pool produce & fetch roundtrip verified successfully!")
    } else {
        println("   [WARN] Pool message not in immediate chunk.")
    }

    p.close()
    println("   [PASS] Kafka Pool closed cleanly.")
}

fn main() {
    println("=== Xu Apache Kafka Distributed Event Streaming Driver Verification ===\n")
    verify_kafka_ping()
    verify_kafka_produce_fetch()
    verify_kafka_pool()
    println("\n[KAFKA VERIFICATION 100% COMPLETED]")
}

API declarations

open

XuAPI
pub fn open(broker string) Client

Purpose

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

Parameters

broker string
broker (string)

Returns

Client — a value of this type

See usage example

open_client

XuAPI
pub fn open_client(broker string, client_id string) Client

Purpose

Open client. Throws on failure; handle the error or propagate it to the caller.

Parameters

broker string
broker (string)
client_id string
client_id (string)

Returns

Client — a value of this type

open_pool_client

XuAPI
pub fn open_pool_client(broker string, client_id string, max_idle int) Pool

Purpose

Open pool client.

Parameters

broker string
broker (string)
client_id string
client_id (string)
max_idle int
max_idle (int)

Returns

Pool — a value of this type

struct Client

XuAPI
pub struct Client {
    pub fd int
    pub broker string
    pub client_id string
    pub next_correlation_id int
}

Purpose

Kafka Client session maintaining connection and operations.

Public fields

fd int
file descriptor
broker string
field (string)
client_id string
field (string)
next_correlation_id int
field (int)

($&Client) write_exact

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

Purpose

Operation on $&Client: write exact. 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

($&Client) read_exact

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

Purpose

Operation on $&Client: read exact. 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) round_trip

XuAPI
pub fn (c $&Client) round_trip(req_bytes string) string

Purpose

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

Parameters

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

Returns

string — result string

connect

XuAPI
pub fn connect(broker string, client_id string) Client

Purpose

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

Parameters

broker string
broker (string)
client_id string
client_id (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.

Parameters

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

Returns

bool — true or false

($&Client) metadata

XuAPI
pub fn (c $&Client) metadata(topic string) bool

Purpose

Execute metadata on $&Client.

Parameters

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

Returns

bool — true or false

($&Client) produce

XuAPI
pub fn (c $&Client) produce(topic string, partition int, message string) int

Purpose

Execute produce on $&Client.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
topic string
topic (string)
partition int
partition (int)
message string
message (string)

Returns

int — a value of this type

($&Client) produce_key_value

XuAPI
pub fn (c $&Client) produce_key_value(topic string, partition int, key string, val string) int

Purpose

Operation on $&Client: produce key value. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
topic string
topic (string)
partition int
partition (int)
key string
key (string)
val string
value (string)

Returns

int — a value of this type

($&Client) fetch

XuAPI
pub fn (c $&Client) fetch(topic string, partition int, offset int) []string

Purpose

Execute fetch 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).
topic string
topic (string)
partition int
partition (int)
offset int
offset (int)

Returns

[]string — slice result

($&Client) close

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

Purpose

Operation on $&Client: close the resource.

Parameters

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

Returns

This call does not return a value.

struct Pool

XuAPI
pub struct Pool {
    pub broker string
    pub client_id string
    pub idle chan int
    pub max_idle int
}

Purpose

Connection Pool for Apache Kafka. Manages reusable TCP socket connections via a scalar channel.

Public fields

broker string
field (string)
client_id string
field (string)
idle chan int
field (channel; type chan int)
max_idle int
field (int)

new_pool

XuAPI
pub fn new_pool(broker string, client_id string, max_idle int) Pool

Purpose

Construct pool.

Parameters

broker string
broker (string)
client_id string
client_id (string)
max_idle int
max_idle (int)

Returns

Pool — a value of this type

open_pool

XuAPI
pub fn open_pool(broker string, client_id string, max_idle int) Pool

Purpose

Open pool.

Parameters

broker string
broker (string)
client_id string
client_id (string)
max_idle int
max_idle (int)

Returns

Pool — a value of this type

See usage example

(&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) ping

XuAPI
pub fn (p &Pool) ping() bool

Purpose

Send a ping heartbeat request to verify connection liveness.

Parameters

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

Returns

bool — true or false

(&Pool) produce

XuAPI
pub fn (p &Pool) produce(topic string, partition int, message string) int

Purpose

Execute produce 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).
topic string
topic (string)
partition int
partition (int)
message string
message (string)

Returns

int — a value of this type

(&Pool) produce_key_value

XuAPI
pub fn (p &Pool) produce_key_value(topic string, partition int, key string, val string) int

Purpose

Operation on &Pool: produce key value. Throws on failure; handle the error or propagate it to the caller.

Parameters

p &Pool
The Pool instance used by this call (borrow).
topic string
topic (string)
partition int
partition (int)
key string
key (string)
val string
value (string)

Returns

int — a value of this type

(&Pool) fetch

XuAPI
pub fn (p &Pool) fetch(topic string, partition int, offset int) []string

Purpose

Execute fetch 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).
topic string
topic (string)
partition int
partition (int)
offset int
offset (int)

Returns

[]string — slice result

(&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) 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.

encode_i8

XuAPI
pub fn encode_i8(v int) string

Purpose

Encode i8 data.

Parameters

v int
value (int)

Returns

string — result string

encode_i16

XuAPI
pub fn encode_i16(v int) string

Purpose

Encode i16 data.

Parameters

v int
value (int)

Returns

string — result string

encode_i32

XuAPI
pub fn encode_i32(v int) string

Purpose

Encode i32 data.

Parameters

v int
value (int)

Returns

string — result string

encode_i64

XuAPI
pub fn encode_i64(v int) string

Purpose

Encode i64 data.

Parameters

v int
value (int)

Returns

string — result string

encode_string

XuAPI
pub fn encode_string(s string) string

Purpose

Encode string data.

Parameters

s string
source string (string)

Returns

string — result string

encode_null_string

XuAPI
pub fn encode_null_string() string

Purpose

Encode null string data.

Parameters

No arguments are required.

Returns

string — result string

encode_bytes

XuAPI
pub fn encode_bytes(b string) string

Purpose

Encode bytes data.

Parameters

b string
b (string)

Returns

string — result string

encode_null_bytes

XuAPI
pub fn encode_null_bytes() string

Purpose

Encode null bytes data.

Parameters

No arguments are required.

Returns

string — result string

encode_zigzag_i32

XuAPI
pub fn encode_zigzag_i32(n int) string

Purpose

Zigzag + Varint encoder for Kafka Record v2

Parameters

n int
count, length, or limit (int)

Returns

string — result string

encode_zigzag_i64

XuAPI
pub fn encode_zigzag_i64(n int) string

Purpose

Encode zigzag i64 data.

Parameters

n int
count, length, or limit (int)

Returns

string — result string

struct VarintResult

XuAPI
pub struct VarintResult {
    pub value int
    pub bytes_read int
}

Purpose

Structure encapsulating value, bytes_read.

Public fields

value int
field (int)
bytes_read int
field (int)

decode_varint

XuAPI
pub fn decode_varint(s &string, off int) VarintResult

Purpose

Decode varint data.

Parameters

s &string
source string (read-only borrow; caller keeps the original; type &string)
off int
offset (int)

Returns

VarintResult — a value of this type

decode_zigzag

XuAPI
pub fn decode_zigzag(s &string, off int) VarintResult

Purpose

Decode zigzag data.

Parameters

s &string
source string (read-only borrow; caller keeps the original; type &string)
off int
offset (int)

Returns

VarintResult — a value of this type

decode_i16

XuAPI
pub fn decode_i16(s &string, off int) int

Purpose

Decode i16 data.

Parameters

s &string
source string (read-only borrow; caller keeps the original; type &string)
off int
offset (int)

Returns

int — a value of this type

decode_i32

XuAPI
pub fn decode_i32(s &string, off int) int

Purpose

Decode i32 data.

Parameters

s &string
source string (read-only borrow; caller keeps the original; type &string)
off int
offset (int)

Returns

int — a value of this type

decode_i64

XuAPI
pub fn decode_i64(s &string, off int) int

Purpose

Decode i64 data.

Parameters

s &string
source string (read-only borrow; caller keeps the original; type &string)
off int
offset (int)

Returns

int — a value of this type

build_request

XuAPI
pub fn build_request(api_key int, api_version int, correlation_id int, client_id string, body string) string

Purpose

Request Framer: [Length (INT32)] [Header (ApiKey, ApiVersion, CorrelationID, ClientID)] [Body]

Parameters

api_key int
api_key (int)
api_version int
api_version (int)
correlation_id int
correlation_id (int)
client_id string
client_id (string)
body string
body (string)

Returns

string — result string

build_record_batch

XuAPI
pub fn build_record_batch(key string, val string) string

Purpose

Build RecordBatch (Magic = 2) for Kafka 0.11+ / 2.x / 3.x / 4.x

Parameters

key string
key (string)
val string
value (string)

Returns

string — result string

build_produce_request

XuAPI
pub fn build_produce_request(correlation_id int, client_id string, topic string, partition int, key string, val string) string

Purpose

Produce Request (ApiKey 0, Version 3)

Parameters

correlation_id int
correlation_id (int)
client_id string
client_id (string)
topic string
topic (string)
partition int
partition (int)
key string
key (string)
val string
value (string)

Returns

string — result string

build_fetch_request

XuAPI
pub fn build_fetch_request(correlation_id int, client_id string, topic string, partition int, offset int) string

Purpose

Fetch Request (ApiKey 1, Version 4)

Parameters

correlation_id int
correlation_id (int)
client_id string
client_id (string)
topic string
topic (string)
partition int
partition (int)
offset int
offset (int)

Returns

string — result string

build_metadata_request

XuAPI
pub fn build_metadata_request(correlation_id int, client_id string, topic string) string

Purpose

Metadata Request (ApiKey 3, Version 0)

Parameters

correlation_id int
correlation_id (int)
client_id string
client_id (string)
topic string
topic (string)

Returns

string — result string

build_apiversions_request

XuAPI
pub fn build_apiversions_request(correlation_id int, client_id string) string

Purpose

ApiVersions Request (ApiKey 18, Version 0)

Parameters

correlation_id int
correlation_id (int)
client_id string
client_id (string)

Returns

string — result string

parse_produce_response

XuAPI
pub fn parse_produce_response(resp string) int

Purpose

Parse Produce Response v3 Throws on failure; handle the error or propagate it to the caller.

Parameters

resp string
resp (string)

Returns

int — a value of this type

parse_fetch_response

XuAPI
pub fn parse_fetch_response(resp string) []string

Purpose

Parse Fetch Response v4 Throws on failure; handle the error or propagate it to the caller.

Parameters

resp string
resp (string)

Returns

[]string — slice result

struct TlsClient

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

Purpose

Kafka 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