open
pub fn open(broker string) ClientPurpose
Open resource or establish connection. Throws on failure; handle the error or propagate it to the caller.
Parameters
brokerstring- broker (string)
Returns
Client — a value of this type
#github.com/xulang-org/packages/kafkaApache 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
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@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]")
}openpub fn open(broker string) ClientOpen resource or establish connection. Throws on failure; handle the error or propagate it to the caller.
broker stringClient — a value of this type
open_clientpub fn open_client(broker string, client_id string) ClientOpen client. Throws on failure; handle the error or propagate it to the caller.
broker stringclient_id stringClient — a value of this type
open_pool_clientpub fn open_pool_client(broker string, client_id string, max_idle int) PoolOpen pool client.
broker stringclient_id stringmax_idle intPool — a value of this type
struct Clientpub struct Client {
pub fd int
pub broker string
pub client_id string
pub next_correlation_id int
}Kafka Client session maintaining connection and operations.
fd intbroker stringclient_id stringnext_correlation_id int($&Client) write_exactpub fn (c $&Client) write_exact(data string) intOperation on $&Client: write exact. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).data stringint — a value of this type
($&Client) read_exactpub fn (c $&Client) read_exact(n int) stringOperation on $&Client: read exact. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).n intstring — result string
($&Client) round_trippub fn (c $&Client) round_trip(req_bytes string) stringOperation on $&Client: round trip. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).req_bytes stringstring — result string
connectpub fn connect(broker string, client_id string) ClientExecute connect. Throws on failure; handle the error or propagate it to the caller.
broker stringclient_id stringClient — a value of this type
($&Client) pingpub fn (c $&Client) ping() boolSend a ping heartbeat request to verify connection liveness.
c $&ClientClient instance used by this call (exclusive borrow).bool — true or false
($&Client) metadatapub fn (c $&Client) metadata(topic string) boolExecute metadata on $&Client.
c $&ClientClient instance used by this call (exclusive borrow).topic stringbool — true or false
($&Client) producepub fn (c $&Client) produce(topic string, partition int, message string) intExecute produce on $&Client.
c $&ClientClient instance used by this call (exclusive borrow).topic stringpartition intmessage stringint — a value of this type
($&Client) produce_key_valuepub fn (c $&Client) produce_key_value(topic string, partition int, key string, val string) intOperation on $&Client: produce key value. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).topic stringpartition intkey stringval stringint — a value of this type
($&Client) fetchpub fn (c $&Client) fetch(topic string, partition int, offset int) []stringExecute fetch on $&Client. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).topic stringpartition intoffset int[]string — slice result
($&Client) closepub fn (c $&Client) close()Operation on $&Client: close the resource.
c $&ClientClient instance used by this call (exclusive borrow).This call does not return a value.
struct Poolpub struct Pool {
pub broker string
pub client_id string
pub idle chan int
pub max_idle int
}Connection Pool for Apache Kafka. Manages reusable TCP socket connections via a scalar channel.
broker stringclient_id stringidle chan intmax_idle intnew_poolpub fn new_pool(broker string, client_id string, max_idle int) PoolConstruct pool.
broker stringclient_id stringmax_idle intPool — a value of this type
open_poolpub fn open_pool(broker string, client_id string, max_idle int) PoolOpen pool.
broker stringclient_id stringmax_idle intPool — a value of this type
(&Pool) getpub fn (p &Pool) get() ClientExecute get on &Pool. Throws on failure; handle the error or propagate it to the caller.
p &PoolPool instance used by this call (borrow).Client — a value of this type
(&Pool) pingpub fn (p &Pool) ping() boolSend a ping heartbeat request to verify connection liveness.
p &PoolPool instance used by this call (borrow).bool — true or false
(&Pool) producepub fn (p &Pool) produce(topic string, partition int, message string) intExecute produce on &Pool. Throws on failure; handle the error or propagate it to the caller.
p &PoolPool instance used by this call (borrow).topic stringpartition intmessage stringint — a value of this type
(&Pool) produce_key_valuepub fn (p &Pool) produce_key_value(topic string, partition int, key string, val string) intOperation on &Pool: produce key value. Throws on failure; handle the error or propagate it to the caller.
p &PoolPool instance used by this call (borrow).topic stringpartition intkey stringval stringint — a value of this type
(&Pool) fetchpub fn (p &Pool) fetch(topic string, partition int, offset int) []stringExecute fetch on &Pool. Throws on failure; handle the error or propagate it to the caller.
p &PoolPool instance used by this call (borrow).topic stringpartition intoffset int[]string — slice result
(&Pool) put_connpub fn (p &Pool) put_conn(fd int)Operation on &Pool: put connection.
p &PoolPool instance used by this call (borrow).fd intThis call does not return a value.
(&Pool) putpub fn (p &Pool) put(c Client)Store or update the value associated with the specified key.
p &PoolPool instance used by this call (borrow).c ClientThis call does not return a value.
(&Pool) closepub fn (p &Pool) close()Operation on &Pool: close the resource.
p &PoolPool instance used by this call (borrow).This call does not return a value.
encode_i8pub fn encode_i8(v int) stringEncode i8 data.
v intstring — result string
encode_i16pub fn encode_i16(v int) stringEncode i16 data.
v intstring — result string
encode_i32pub fn encode_i32(v int) stringEncode i32 data.
v intstring — result string
encode_i64pub fn encode_i64(v int) stringEncode i64 data.
v intstring — result string
encode_stringpub fn encode_string(s string) stringEncode string data.
s stringstring — result string
encode_null_stringpub fn encode_null_string() stringEncode null string data.
No arguments are required.
string — result string
encode_bytespub fn encode_bytes(b string) stringEncode bytes data.
b stringstring — result string
encode_null_bytespub fn encode_null_bytes() stringEncode null bytes data.
No arguments are required.
string — result string
encode_zigzag_i32pub fn encode_zigzag_i32(n int) stringZigzag + Varint encoder for Kafka Record v2
n intstring — result string
encode_zigzag_i64pub fn encode_zigzag_i64(n int) stringEncode zigzag i64 data.
n intstring — result string
struct VarintResultpub struct VarintResult {
pub value int
pub bytes_read int
}Structure encapsulating value, bytes_read.
value intbytes_read intdecode_varintpub fn decode_varint(s &string, off int) VarintResultDecode varint data.
s &stringoff intVarintResult — a value of this type
decode_zigzagpub fn decode_zigzag(s &string, off int) VarintResultDecode zigzag data.
s &stringoff intVarintResult — a value of this type
decode_i16pub fn decode_i16(s &string, off int) intDecode i16 data.
s &stringoff intint — a value of this type
decode_i32pub fn decode_i32(s &string, off int) intDecode i32 data.
s &stringoff intint — a value of this type
decode_i64pub fn decode_i64(s &string, off int) intDecode i64 data.
s &stringoff intint — a value of this type
build_requestpub fn build_request(api_key int, api_version int, correlation_id int, client_id string, body string) stringRequest Framer: [Length (INT32)] [Header (ApiKey, ApiVersion, CorrelationID, ClientID)] [Body]
api_key intapi_version intcorrelation_id intclient_id stringbody stringstring — result string
build_record_batchpub fn build_record_batch(key string, val string) stringBuild RecordBatch (Magic = 2) for Kafka 0.11+ / 2.x / 3.x / 4.x
key stringval stringstring — result string
build_produce_requestpub fn build_produce_request(correlation_id int, client_id string, topic string, partition int, key string, val string) stringProduce Request (ApiKey 0, Version 3)
correlation_id intclient_id stringtopic stringpartition intkey stringval stringstring — result string
build_fetch_requestpub fn build_fetch_request(correlation_id int, client_id string, topic string, partition int, offset int) stringFetch Request (ApiKey 1, Version 4)
correlation_id intclient_id stringtopic stringpartition intoffset intstring — result string
build_metadata_requestpub fn build_metadata_request(correlation_id int, client_id string, topic string) stringMetadata Request (ApiKey 3, Version 0)
correlation_id intclient_id stringtopic stringstring — result string
build_apiversions_requestpub fn build_apiversions_request(correlation_id int, client_id string) stringApiVersions Request (ApiKey 18, Version 0)
correlation_id intclient_id stringstring — result string
parse_produce_responsepub fn parse_produce_response(resp string) intParse Produce Response v3 Throws on failure; handle the error or propagate it to the caller.
resp stringint — a value of this type
parse_fetch_responsepub fn parse_fetch_response(resp string) []stringParse Fetch Response v4 Throws on failure; handle the error or propagate it to the caller.
resp string[]string — slice result
struct TlsClientpub struct TlsClient {
pub conn transport.Conn
pub host string
pub port int
}Kafka Client session maintaining connection and operations.
conn transport.Connhost stringport inttls_connectpub fn tls_connect(endpoint string, default_port int) TlsClientTls connect. Throws on failure; handle the error or propagate it to the caller.
endpoint stringdefault_port intTlsClient — a value of this type
tls_connect_configpub fn tls_connect_config(endpoint string, default_port int, cfg tls.Config) TlsClientTls connect config. Throws on failure; handle the error or propagate it to the caller.
endpoint stringdefault_port intcfg tls.ConfigTlsClient — a value of this type
($&TlsClient) write_allpub fn (c $&TlsClient) write_all(data string) intOperation on $&TlsClient: write all. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).data stringint — a value of this type
($&TlsClient) readpub fn (c $&TlsClient) read(max int) stringOperation on $&TlsClient: read up to max bytes. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).max intstring — result string
($&TlsClient) read_exactpub fn (c $&TlsClient) read_exact(need int) stringOperation on $&TlsClient: read exact. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).need intstring — result string
($&TlsClient) closepub fn (c $&TlsClient) close() intOperation on $&TlsClient: close the resource. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).int — a value of this type
($&TlsClient) set_deadlinepub fn (c $&TlsClient) set_deadline(t_ns int) intOperation on $&TlsClient: set deadline. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).t_ns intint — a value of this type
($&TlsClient) set_read_deadlinepub fn (c $&TlsClient) set_read_deadline(t_ns int) intOperation on $&TlsClient: set read deadline. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).t_ns intint — a value of this type
($&TlsClient) set_write_deadlinepub fn (c $&TlsClient) set_write_deadline(t_ns int) intOperation on $&TlsClient: set write deadline. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).t_ns intint — a value of this type