← Back to Official Package Registry
Tier 2: Distributed & Wire Protocols • NATS & Kafka Wire Codecsv1.0.0 • 59 KB • Ed25519 Verified

mq_streams@1.0.0

Pure-Veko NATS Core/Headers wire protocol & wildcard subject matcher alongside Kafka RecordBatch v2 (CRC32C) & Produce/Fetch codecs.

use [mq_streams/kafka]use [mq_streams]use [mq_streams/nats]
veko pkg add mq_streams@1.0.0
Run in Browser PlaygroundDownload 1.0.0.vkpRaw demo.vk

mq_streams

Pure-Veko NATS / JetStream text-and-header wire protocol client, Apache Kafka / Redpanda KIP-98 binary wire codec (RecordBatch v2 + CRC-32C Castagnoli), and deterministic in-memory broker (mq_streams, mq_streams/nats, mq_streams/kafka).

Overview

mq_streams provides wire-level messaging codecs and io/Stream clients for event-driven microservices and log pipelines:

  • mq_streams/nats:
  • Complete NATS protocol encoder and streaming parser (INFO, CONNECT, PUB, HPUB, SUB, UNSUB, MSG, HMSG, PING, PONG, +OK, -ERR).
  • NATS/1.0 header serialization with JetStream status codes (100 FlowControl, 503 No Responders),hierarchical . subject wildcard matching (* single token and > tail match), and io/Stream client session (connect-stream, client-pub, client-hpub, client-sub, client-read-frame with automatic PING -> PONG keepalive).
  • mq_streams/kafka:
  • Reflected CRC-32C Castagnoli (0x82F63B78) checksum, 4-byte TCP packet framing, and RequestHeader v2 / ResponseHeader codecs built over codec/wire and big-endian wire intrinsics.
  • Full KIP-98 RecordBatch v2 (magic = 2) encoder and CRC-32C-verifying decoder supporting ZigZag signed-varint Record framing, per-record headers, nullable keys, producer IDs, and RFC 8878 Zstandard (attributes = 4) batch compression (compress/zstd).
  • ProduceRequest, FetchRequest, FetchResponse, and decode-fetch-records wire codecs compatible with Apache Kafka and Redpanda.
  • mq_streams:
  • Deterministic MemoryBroker combining NATS wildcard fan-out and queue-group round-robin load balancing with append-only CRC-32C-verified Kafka v2 partition logs for zero-network integration tests.

Installation

powershell
veko pkg add mq_streams@1.0.0

Import the modules in .vk source files:

rebol
use [
    mq    = mq_streams
    nats  = mq_streams/nats
    kafka = mq_streams/kafka
]

Wire Protocol & Architecture Notes

NATS HPUB / HMSG Header Framing

Header-carrying NATS frames prefix the payload with a NATS/1.0 header block terminated by \r\n\r\n and declare both #header_bytes and #total_bytes on the control line:

text
HPUB orders.42.eu _INBOX.1 45 60\r\n
NATS/1.0\r\n
Nats-Msg-Id: ord-42\r\n
\r\n
{"amount":2500}\r\n

Apache Kafka KIP-98 RecordBatch v2 Layout

Each RecordBatch v2 begins with a 61-byte big-endian header:

Byte OffsetFieldTypeNotes
0..8baseOffsetint64 BEFirst offset in batch
8..12batchLengthint32 BEByte length of bytes 12..end
12..16partitionLeaderEpochint32 BEBroker leader epoch
16magicint8Always 2 for KIP-98 v2
17..21crcuint32 BECRC-32C Castagnoli (0x82F63B78) over 21..end
21..23attributesint16 BEBits 0..2: 0 = none, 4 = Zstd
23..27lastOffsetDeltaint32 BE(len records) - 1
27..43baseTimestamp / maxTimestamp2 x int64 BEUnix millisecond timestamps
43..57producerId / epoch / seq8B + 2B + 4BIdempotent producer metadata (-1 if unset)
57..61recordsCountint32 BENumber of ZigZag-varint-framed Records

Complete API Reference

mq_streams/nats

  • Structs: NatsFrame, FrameDecodeStep, NatsClient
  • Wildcards & Wire Codecs:
  • subject-match? [pattern str, subject str] bool
  • encode-connect [opts map] bytes / encode-info [info map] bytes
  • encode-ping [] bytes / encode-pong [] bytes / encode-ok [] bytes / encode-err [reason str] bytes
  • encode-sub [subject str, sid str /queue qgroup str = ''] bytes
  • encode-unsub [sid str /max max_msgs i64 = 0] bytes
  • encode-pub [subject str, payload bytes /reply reply_to str = ''] bytes
  • encode-hpub [subject str, headers map[str], payload bytes /reply reply_to str = ''] bytes
  • encode-msg [subject str, sid str, payload bytes /reply reply_to str = ''] bytes
  • encode-hmsg [subject str, sid str, headers map[str], payload bytes /reply reply_to str = '' /status code i64 = 0 /reason text str = ''] bytes
  • decode-frame-at [wire bytes, off i64] FrameDecodeStep / decode-frames [wire bytes] block[NatsFrame]
  • Stream Client:
  • connect-stream [mut stream io/Stream, connect_opts map] NatsClient
  • client-pub [mut client NatsClient, subject str, payload bytes /reply reply_to str = ''] i64
  • client-hpub [mut client NatsClient, subject str, headers map[str], payload bytes /reply reply_to str = ''] i64
  • client-sub [mut client NatsClient, subject str /queue qgroup str = ''] str
  • client-read-frame [mut client NatsClient /auto-pong pong bool = true] NatsFrame

mq_streams/kafka

  • Constants (0-arg inline functions): API-PRODUCE, API-FETCH, API-LIST-OFFSETS, API-METADATA, API-API-VERSIONS
  • Structs: RecordHeader, KafkaRecord, RecordBatch, RequestHeaderV2, ResponseHeader
  • Functions:
  • crc32c [data bytes] i64
  • frame-packet [payload bytes] bytes / unframe-packet [framed bytes] bytes
  • encode-request-header-v2 [api_key i64, api_version i64, correlation_id i64, client_id str] bytes
  • decode-request-header-v2 [buf bytes, off i64] RequestHeaderV2
  • encode-response-header [correlation_id i64] bytes / decode-response-header [buf bytes, off i64] ResponseHeader
  • encode-record-batch [base_offset i64, base_timestamp i64, records block[KafkaRecord] /zstd use_zstd bool = false /producer-id pid i64 = -1] bytes
  • decode-record-batch [wire bytes] RecordBatch / decode-record-batch-at [wire bytes, off i64] map
  • encode-produce-request [correlation_id i64, client_id str, topic str, partition i64, record_batch bytes /acks req_acks i64 = -1 /timeout timeout_ms i64 = 5000] bytes
  • encode-fetch-request [correlation_id i64, client_id str, topic str, partition i64, fetch_offset i64 /max-wait max_wait_ms i64 = 500 /max-bytes max_bytes i64 = 1048576] bytes
  • encode-fetch-response [correlation_id i64, topic str, partition i64, high_watermark i64, batches_wire bytes] bytes
  • decode-fetch-records [framed_resp bytes] block[KafkaRecord]

mq_streams

  • new-broker [] MemoryBroker
  • subscribe [mut b MemoryBroker, pattern str /queue qgroup str = ''] str
  • unsubscribe [mut b MemoryBroker, sid str] bool
  • publish [mut b MemoryBroker, subject str, payload bytes /headers hdrs map[str] = {} /reply reply_to str = ''] i64
  • drain-sub [mut b MemoryBroker, sid str] block[BrokerMsg]
  • append-partition-batch [mut b MemoryBroker, topic str, partition i64, base_timestamp i64, records block[kafka/KafkaRecord] /zstd use_zstd bool = false] i64
  • fetch-partition [b MemoryBroker, topic str, partition i64, min_offset i64] block[kafka/KafkaRecord]

Idiomatic Veko Examples

NATS HPUB Framing & Subject Matching

rebol
use [nats = mq_streams/nats]

wire = nats/encode-hpub 'orders.42.eu' { 'Nats-Msg-Id' = 'id-42' } (bytes/from-str 'payload')
frames = nats/decode-frames wire
if nats/subject-match? 'orders.*.eu' frames[0].subject [
    print (map/get frames[0].headers 'Nats-Msg-Id')
]

Kafka v2 RecordBatch Encode, CRC-32C Verification & Decode

rebol
use [kafka = mq_streams/kafka]

batch_bytes = kafka/encode-record-batch/zstd 100 1730000000000 [
    kafka/KafkaRecord {
        timestamp_ms = 1730000000050
        key          = bytes/from-str 'k1'
        value        = bytes/from-str 'v1'
        headers      = [ kafka/RecordHeader { key = 'source', value = (bytes/from-str 'edge') } ]
    }
] true

batch = kafka/decode-record-batch batch_bytes
print batch.records[0].offset
packages/mq_streams/examples/demo.vkSelf-contained runnable example & assertion suite
Raw .vk
// packages/mq_streams/examples/demo.vk
// Self-contained verification suite & runnable example for `mq_streams`, `mq_streams/nats`, and `mq_streams/kafka`.

use [
	mq    = mq_streams
	nats  = mq_streams/nats
	kafka = mq_streams/kafka
	io
]

assert-true = fn [cond bool, label str] enum [
	if not cond [
		println (str/join ['[FAIL] ' label] '')
		os/exit 1
	]
	print (str/join ['[PASS] ' label] '')
	.ok
]

// --- 1. NATS Subject Wildcard Matching (`*` and `>`) ---
wc_ok_1 = (nats/subject-match? 'orders.*.eu' 'orders.8841.eu') and (not (nats/subject-match? 'orders.*.eu' 'orders.8841.us')) and (not (nats/subject-match? 'orders.*.eu' 'orders.8841.west.eu'))
wc_ok_2 = (nats/subject-match? 'events.>' 'events.auth') and (nats/subject-match? 'events.>' 'events.auth.login.mfa') and (not (nats/subject-match? 'events.>' 'events'))
_ = assert-true (wc_ok_1 and wc_ok_2) 'NATS wildcard subject matcher (* single token and > multi-token tail)'

// --- 2. NATS `HPUB` / `HMSG` / `CONNECT` / `SUB` Wire Codec & `io/mem-stream` Session ---
hpub_wire = nats/encode-hpub/reply 'orders.99.eu' { 'Nats-Msg-Id' = 'msg-0099', 'Trace-Parent' = '00-4bf92f' } (bytes/from-str '{"amount":2500}') '_INBOX.reply.1'
hmsg_wire = nats/encode-hmsg/reply/status/reason 'orders.99.eu' '7' { 'Nats-Stream' = 'ORDERS', 'Nats-Sequence' = '42' } (bytes/from-str '{"amount":2500}') '_INBOX.reply.1' 100 'FlowControl'

mut mixed_wire = bytes/with-cap 512
_ = bytes/push-all mut mixed_wire hpub_wire
_ = bytes/push-all mut mixed_wire hmsg_wire
_ = bytes/push-all mut mixed_wire (nats/encode-sub/queue 'orders.*.eu' '7' 'workers')
_ = bytes/push-all mut mixed_wire (nats/encode-ok)
_ = bytes/push-all mut mixed_wire (nats/encode-err 'Authorization Violation')

parsed_frames = nats/decode-frames mixed_wire
f_hpub = parsed_frames[0]
f_hmsg = parsed_frames[1]
f_sub  = parsed_frames[2]
f_ok   = parsed_frames[3]
f_err  = parsed_frames[4]

nats_wire_ok_1 = (len parsed_frames) == 5 and f_hpub.kind == .hpub and f_hpub.subject == 'orders.99.eu' and f_hpub.reply_to == '_INBOX.reply.1'
nats_wire_ok_2 = (map/get f_hpub.headers 'Nats-Msg-Id') == 'msg-0099' and (bytes/to-str f_hpub.payload) == '{"amount":2500}'
nats_wire_ok_3 = f_hmsg.kind == .hmsg and f_hmsg.sid == '7' and f_hmsg.status_code == 100 and (map/get f_hmsg.headers 'Nats-Stream') == 'ORDERS'
nats_wire_ok_4 = f_sub.kind == .sub and f_sub.queue_group == 'workers' and f_ok.kind == .ok_ack and f_err.error_text == 'Authorization Violation'
_ = assert-true (nats_wire_ok_1 and nats_wire_ok_2 and nats_wire_ok_3 and nats_wire_ok_4) 'NATS HPUB, HMSG, SUB, +OK, and -ERR wire protocol roundtrip'

// Test `connect-stream` over `io/mem-stream` with server INFO + auto-PONG + HMSG delivery
mut server_feed = bytes/with-cap 256
_ = bytes/push-all mut server_feed (nats/encode-info { server_id = 'NATS-VEKO-1', max_payload = 1048576, headers = true })
_ = bytes/push-all mut server_feed (nats/encode-ping)
_ = bytes/push-all mut server_feed (nats/encode-hmsg 'events.billing.paid' '1' { 'X-Source' = 'stripe' } (bytes/from-str 'inv_771'))

mut mem_st = io/mem-stream server_feed
mut nc = nats/connect-stream mut mem_st { name = 'demo-worker' }
sid1 = nats/client-sub mut nc 'events.>'
_ = nats/client-hpub mut nc 'events.billing.paid' { 'X-Source' = 'stripe' } (bytes/from-str 'inv_771')
delivered_frm = nats/client-read-frame mut nc
_ = assert-true (sid1 == '1' and (map/get nc.server_info 'server_id') == 'NATS-VEKO-1' and delivered_frm.kind == .hmsg and (bytes/to-str delivered_frm.payload) == 'inv_771') 'NATS io/Stream client handshake, auto-PONG, and HMSG stream read'

// --- 3. Kafka CRC-32C Castagnoli & Multi-Record KIP-98 RecordBatch v2 ---
crc_vec = kafka/crc32c (bytes/from-str '123456789')
_ = assert-true (crc_vec == 0xe3069283) 'CRC-32C Castagnoli (0x82F63B78) matches RFC 3720 check vector 0xE3069283'

recs_in = [
	kafka/KafkaRecord {
		timestamp_ms = 1730000000100
		key          = bytes/from-str 'acct-10'
		value        = bytes/from-str '{"ev":"credit","cents":5000}'
		headers      = [ kafka/RecordHeader { key = 'trace-id', value = (bytes/from-str 'tr-aaa') } ]
	}
	kafka/KafkaRecord {
		timestamp_ms = 1730000000250
		key          = bytes/from-str 'acct-20'
		value        = bytes/from-str '{"ev":"debit","cents":1200}'
		headers      = [
			kafka/RecordHeader { key = 'trace-id', value = (bytes/from-str 'tr-bbb') }
			kafka/RecordHeader { key = 'region',   value = (bytes/from-str 'eu-central') }
		]
	}
	kafka/KafkaRecord {
		timestamp_ms = 1730000000400
		key          = bytes/with-cap 0
		has_key      = false
		value        = bytes/from-str '{"ev":"heartbeat"}'
		headers      = []
	}
]

batch_wire = kafka/encode-record-batch/zstd/producer-id 500 1730000000100 recs_in true 9001
dec_batch = kafka/decode-record-batch batch_wire
kb_ok_1 = dec_batch.magic == 2 and dec_batch.base_offset == 500 and dec_batch.producer_id == 9001 and (dec_batch.attributes & 7) == 4
kb_ok_2 = (len dec_batch.records) == 3 and dec_batch.records[0].offset == 500 and dec_batch.records[1].offset == 501 and dec_batch.records[2].offset == 502
kb_ok_3 = dec_batch.records[1].timestamp_ms == 1730000000250 and (bytes/to-str dec_batch.records[1].key) == 'acct-20' and dec_batch.records[1].headers[1].key == 'region'
kb_ok_4 = (not dec_batch.records[2].has_key) and (bytes/to-str dec_batch.records[2].value) == '{"ev":"heartbeat"}'
_ = assert-true (kb_ok_1 and kb_ok_2 and kb_ok_3 and kb_ok_4) 'Kafka RecordBatch v2 (magic=2, Zstd, headers, null-key) encode + CRC32C-verify + decode'

// Corrupt 1 byte inside the batch payload and confirm CRC-32C catches corruption
mut corrupted = bytes/with-cap (len batch_wire)
_ = bytes/push-all mut corrupted batch_wire
last_b = (len corrupted) - 1
_ = bytes/set mut corrupted last_b (corrupted[last_b] ^ 0xff)
tampered_ok = err? (kafka/decode-record-batch/or corrupted [e -> e])
_ = assert-true tampered_ok 'Kafka RecordBatch v2 rejects bit-flipped payload on CRC-32C mismatch'

// ProduceRequest / FetchRequest / FetchResponse wire roundtrip
prod_pkt = kafka/encode-produce-request 42 'veko-ingestor' 'ledger.events' 0 batch_wire
fetch_pkt = kafka/encode-fetch-request 43 'veko-consumer' 'ledger.events' 0 500
prod_unframed = kafka/unframe-packet prod_pkt
prod_hdr = kafka/decode-request-header-v2 prod_unframed 0
fetch_resp_pkt = kafka/encode-fetch-response 43 'ledger.events' 0 503 batch_wire
fetched_recs = kafka/decode-fetch-records fetch_resp_pkt
_ = assert-true (prod_hdr.api_key == (kafka/API-PRODUCE) and prod_hdr.correlation_id == 42 and (len (kafka/unframe-packet fetch_pkt)) > 20 and (len fetched_recs) == 3 and fetched_recs[0].offset == 500) 'Kafka ProduceRequest, FetchRequest, and FetchResponse wire roundtrip'

// --- 4. Unified `MemoryBroker` Wildcard Pub/Sub (Queue Groups) & Partition Log ---
mut broker = mq/new-broker
audit_sid = mq/subscribe mut broker 'orders.>'
q_sid_a   = mq/subscribe/queue mut broker 'orders.*.eu' 'eu-fulfillment'
q_sid_b   = mq/subscribe/queue mut broker 'orders.*.eu' 'eu-fulfillment'

_ = mq/publish/headers mut broker 'orders.101.eu' (bytes/from-str 'ord-101') { 'Idemp-Key' = 'k1' }
_ = mq/publish/headers mut broker 'orders.102.eu' (bytes/from-str 'ord-102') { 'Idemp-Key' = 'k2' }
_ = mq/publish mut broker 'orders.103.us' (bytes/from-str 'ord-103')

audit_msgs = mq/drain-sub mut broker audit_sid
qa_msgs    = mq/drain-sub mut broker q_sid_a
qb_msgs    = mq/drain-sub mut broker q_sid_b

hwm = mq/append-partition-batch mut broker 'orders-log' 0 1730000000100 recs_in
tail_recs = mq/fetch-partition broker 'orders-log' 0 1
_ = assert-true ((len audit_msgs) == 3 and (len qa_msgs) == 1 and (len qb_msgs) == 1 and hwm == 3 and (len tail_recs) == 2 and tail_recs[0].offset == 1) 'MemoryBroker wildcard fan-out, queue-group round-robin, and partition log offset fetch'

print 'mq_streams: all verification checks passed'
Cryptographic Provenance

Ed25519 Signature & Merkle Integrity

Registry URL: https://veko-lang.org/pkg/mq_streams/1.0.0.vkp
Archive SHA-256: 013cee8cb3d7f7d1480ef8cd63115848facd02d37065e81d9291aa3e9ad1a4eb
Merkle Root: fb0f19baf8b32719a31d171e7727d7ee4e1223165e2523ca91268a0b059e6a09
Signer Trust Key: ed25519:27406074d8681da1d4e6420f5d887cac15c313334c249ac047ba9d4e2df72b70
Embedded VKP1 Manifest

manifest.json

{"name":"mq_streams","version":"1.0.0","tier":2.0,"tier_label":"Tier 2: Distributed & Wire Protocols","category":"NATS & Kafka Wire Codecs","description":"Pure-Veko NATS Core/Headers wire protocol & wildcard subject matcher alongside Kafka RecordBatch v2 (CRC32C) & Produce/Fetch codecs.","modules":["mq_streams/kafka","mq_streams","mq_streams/nats"],"homepage":"https://veko-lang.org/packages/mq_streams"}
Bundle Entry PathSizeLeaf SHA-256 Digest
README.md7 KBc62465266fcb012269e762cf967fb35405167a2262fed77bb1a91ae92eb50f8f
examples/demo.vk7 KBdf1eeadbba0297e5cca19b73c03cd8ac7415174e19023aa93530b6de7e4f5e37
kafka.vk19 KB33cd5c50f813ab6e5079d77571c21de16c88c50ca6c3b36b3b58e9dcbebd4364
mod.vk5 KBbec5422756574b1f45840e355f55268b04bcc07bad010633f8c89319888c9b8d
nats.vk18 KBf3acf2d76e95c0366a3a61694540c145b82449c337095fa90252fb3cabd7e4f3