moon_zmq

    Pure MoonBit implementation of ZeroMQ (ZMTP 3.1) messaging library with NULL/PLAIN security and full socket patterns.

    zeromq
    zmq
    zmtp
    messaging
    pubsub
    Download zip
    Author
    Version
    0.3.2
    License
    MIT
    Last updated
    18 hours ago
    Downloads
    35

    No dependencies

    #moon-zmq: 纯 MoonBit 实现的 ZeroMQ (ZMTP 3.1) 消息通信库

    CI Mooncakes Compiler: moonc >= 1.0.0-rc1 License: MIT Target: Native

    moon-zmq 是一个基于纯 MoonBit 语言实现的、工业级、通用的 ZeroMQ(ZMTP 3.1)网络通信库。它旨在为 MoonBit 生态提供高性能、全双工、跨语言互通的消息通信总线能力,能够直接与官方 C/C++ libzmq 以及各语言驱动(如 Python pyzmq、Rust zmq、Go pebbe/zmq4 等)进行原生无缝通信。


    #致谢与同类生态对比

    在 MoonBit 生态早期,Mr-Shi123/moonjupyter 项目开创性地为 Jupyter 内核协议内嵌了一小段基础的 ZMTP NULL 握手与单向帧编解码逻辑,为本项目的初期协议调研提供了非常有价值的参考与启发,在此特向 Mr-Shi123 及其贡献者致以崇高的敬意与诚挚的感谢!

    #与 moonjupyter 内置实现的本质区别:

    特性维度moonjupyter 内嵌实现moon-zmq (本项目)
    项目定位专为 Jupyter Kernel 协议定制的内嵌辅助代码独立、通用、可发布的现代 ZeroMQ 基础设施库
    Socket 模式支持仅满足 Jupyter 通信的基本收发,无标准模式状态机完整覆盖 10 种标准模式:REQ/REP、PUB/SUB、XPUB/XSUB、PUSH/PULL、DEALER/ROUTER、PAIR
    规范遵从度基础握手,无严格 RFC 状态机校验严格对标 RFC 23 / 24 / 28 / 29 / 30 / 31 / 47,具备信封包装与交替检查
    连接与高可用单次连接,无重连与流量控制多连接并发管理 (TransportHub)、指数退避自动重连、高水位 (HWM) 反压队列
    安全机制仅支持简易无认证的 NULL 机制支持 NULL 机制与 RFC 24 PLAIN 明文认证机制,支持自定义服务端 ZAP 校验回调
    双向跨语言互通未针对标准 libzmq 进行双向全面互通校验具备与官方 libzmq (pyzmq) 的全量双向端到端互通测试套件 (18/18 通过)


    #核心特性

    • 纯 MoonBit 原生构建:基于现代协作式协程库 moonbitlang/async 编写,无 CGO、无外部动态链接库依赖。
    • 高并发全异步 I/O:深度利用操作系统原生异步事件机制(Windows IOCP、Linux epoll、macOS kqueue),通过结构化并发 TaskGroup 保证连接与资源安全释放。
    • 双传输层引擎 (tcp:// & inproc://):
      • 原生支持跨进程高性能异步 tcp:// 网络传输;
      • 原生支持进程内零内核开销的 inproc:// 内存通道(具备 Context 命名空间隔离与 ZeroMQ 标志性的 先 connect 后 bind 能力)。
    • 全模式与扩展原语覆盖:
      • 10 种标准模式:REQ/REP、DEALER/ROUTER(含 ZMQ_ROUTER_MANDATORY)、PUB/SUB、XPUB/XSUB(含 ZMQ_XPUB_VERBOSE)、PUSH/PULL、PAIR;
      • Draft 精确分组模式 (RadioSocket / DishSocket):提供无前缀误匹配的精确群组发布订阅(join / leave);
      • 高可靠 RPC 与服务发现 (ReliableClient, MdpBroker):内置 Lazy Pirate 多端点故障转移客户端、RFC 7 Majordomo (MDP/0.2) 面向服务代理以及 RFC 8 mmi.service 服务发现在线查询。
    • 高级调度、缓存与并发原语:
      • RFC 43 可控消息代理 (proxy, proxy_steerable):支持全自动双向流量中继、旁路流量审计抓包(Capture)及控制通道动态暂停、恢复与终止(PAUSE / RESUME / TERMINATE);
      • 前缀字典树与最新值缓存 (SubscriptionTrie, LastValueCache, ConflateBuffer):O(|topic|) 多管道引用计数订阅树、LVC 晚加入重放代理(run_lvc_proxy)以及 ZMQ_CONFLATE 最新状态合并缓冲;
      • CZMQ 并发与配置模型 (ZActor, ZLoop, ZConfig):支持 RFC 4 ZPL 层级配置解析/序列化、inproc:// Actor 协程通信以及融合定时器与 Poller 的 ZLoop 事件反应器;
      • I/O 多路复用调度器 (Poller):在单协程内统一轮询多套接字,非阻塞探测 POLLIN / POLLOUT / POLLERR;
      • 可观测性、限流与熔断诊断 (SocketEvent, WireDissector, LatencyHistogram, RateLimiter, CircuitBreaker):捕获全生命周期连接事件,内置 ZMTP 报文解剖器、微秒级分位数直方图、双令牌桶流量整形与三态故障熔断器;
      • ZMTP 3.1 心跳检测 (set_heartbeat):支持定时 PING 探测、对端自动 PONG 响应与静默失活自动断连重连。
    • 完备的安全认证与编码体系:
      • 支持 RFC 23 NULL 机制与 RFC 24 PLAIN 机制;
      • 完整实现 RFC 27 ZAP 1.0 认证协议(inproc://zeromq.zap.01 异步鉴权服务、IPv4 CIDR 黑白名单、多域用户凭据库与审计日志);
      • 完整实现 RFC 32 Z85 二进制/文本编码器与 WireReader / WireWriter 网络字节序游标。


    #安装与引入

    在您的 MoonBit 项目根目录下的 moon.mod 或 moon.pkg 中添加依赖:

    import {
    "chgttyyr/moon_zmq",
    "moonbitlang/core/async",
    }

    或者使用 moon 包管理命令添加:

    moon add chgttyyr/moon_zmq

    环境与编译要求:需使用 moonc >= 1.0.0-rc1 工具链,并在 Native 目标下检查、构建与测试:

    moon check --target native moon build --target native moon test --target native


    #快速开始

    #1. 基础请求-应答模式 (REQ / REP)

    async fn run_req_rep() -> Unit {
    @async.with_task_group(async fn(group) {
    let ctx = @moon_zmq.Context::new()

    // 1. 服务端监听
    let rep = ctx.socket(@moon_zmq.Rep) catch { _ => return }
    let endpoint = rep.bind(group, "tcp://127.0.0.1:5555") catch { _ => return }

    // 2. 客户端连接
    let req = ctx.socket(@moon_zmq.Req) catch { _ => return }
    req.connect(group, endpoint)

    // 等待建立握手
    while rep.active_peer_count() < 1 { @async.sleep(10) }

    // 3. 客户端发送请求
    let _ = req.send(@moon_zmq.Message::from_string("ping")) catch { _ => return }

    // 4. 服务端接收并应答
    let request = rep.recv() catch { _ => return }
    println("Server received: \{request.first_string()}")
    let _ = rep.send(@moon_zmq.Message::from_string("pong")) catch { _ => return }

    // 5. 客户端获取响应
    let reply = req.recv() catch { _ => return }
    println("Client received: \{reply.first_string()}")

    req.close()
    rep.close()
    ctx.term()
    })
    }

    #2. 发布-订阅遥测与过滤 (PUB / SUB)

    async fn run_pub_sub() -> Unit {
    @async.with_task_group(async fn(group) {
    let ctx = @moon_zmq.Context::new()
    let pub_sock = ctx.socket(@moon_zmq.Pub) catch { _ => return }
    let endpoint = pub_sock.bind(group, "tcp://127.0.0.1:0") catch { _ => return }

    let sub_sock = ctx.socket(@moon_zmq.Sub) catch { _ => return }
    // 订阅指定主题前缀
    sub_sock.subscribe(b"market.quote")
    sub_sock.connect(group, endpoint)

    while pub_sock.active_peer_count() < 1 { @async.sleep(10) }
    @async.sleep(50)

    // 发布主题数据
    let _ = pub_sock.send(@moon_zmq.Message::from_string("market.quote symbol=MOON price=128.5")) catch { _ => () }
    let _ = pub_sock.send(@moon_zmq.Message::from_string("unrelated.topic ignored")) catch { _ => () }

    // 订阅端只会收到匹配订阅的主题
    let msg = sub_sock.recv() catch { _ => return }
    println("Received quote: \{msg.first_string()}")

    sub_sock.close()
    pub_sock.close()
    ctx.term()
    })
    }

    #3. PLAIN 用户名密码安全认证 (RFC 24)

    async fn run_secure_auth() -> Unit {
    @async.with_task_group(async fn(group) {
    let ctx = @moon_zmq.Context::new()

    // 1. 服务端配置 PLAIN 及认证回调
    let server = ctx.socket(@moon_zmq.Rep) catch { _ => return }
    server.set_plain_server(true, authenticator=Some(fn(user, pass) {
    user == "admin" && pass == "secret123"
    }))
    let endpoint = server.bind(group, "tcp://127.0.0.1:0") catch { _ => return }

    // 2. 客户端配置认证凭据
    let client = ctx.socket(@moon_zmq.Req) catch { _ => return }
    client.set_plain_credentials("admin", "secret123")
    client.connect(group, endpoint)

    while server.active_peer_count() < 1 { @async.sleep(10) }

    let _ = client.send(@moon_zmq.Message::from_string("secure rpc payload")) catch { _ => return }
    let req = server.recv() catch { _ => return }
    let _ = server.send(@moon_zmq.Message::from_string("auth confirmed ok")) catch { _ => return }
    let rep = client.recv() catch { _ => return }
    println("Secure Reply: \{rep.first_string()}")

    client.close()
    server.close()
    ctx.term()
    })
    }

    #4. RFC 43 可控消息代理与旁路抓包 (Proxy & Capture)

    async fn run_proxy_broker() -> Unit {
    @async.with_task_group(async fn(group) {
    let ctx = @moon_zmq.Context::new()

    // 1. 设置前端 ROUTER 与后端 DEALER
    let frontend = ctx.socket(@moon_zmq.Router) catch { _ => return }
    let f_ep = frontend.bind(group, "tcp://127.0.0.1:5559") catch { _ => return }

    let backend = ctx.socket(@moon_zmq.Dealer) catch { _ => return }
    let b_ep = backend.bind(group, "tcp://127.0.0.1:5560") catch { _ => return }

    // 2. 启动代理转发任务(自动双向转发并输出审计日志)
    let stats = @moon_zmq.ProxyStats::new()
    group.spawn(no_wait=true, allow_failure=true, async fn() {
    let _ = @moon_zmq.proxy_steerable(frontend, backend, stats~) catch { _ => () }
    })

    // 客户端连接 frontend (5559),Worker 连接 backend (5560),实现解耦路由
    })
    }

    #5. I/O 多路复用调度 (Poller Multiplexing)

    async fn run_poller_multiplex() -> Unit {
    @async.with_task_group(async fn(group) {
    let ctx = @moon_zmq.Context::new()
    let sock1 = ctx.socket(@moon_zmq.Pull) catch { _ => return }
    let sock2 = ctx.socket(@moon_zmq.Pair) catch { _ => return }

    // 注册到 Poller
    let poller = @moon_zmq.Poller::new()
    poller.add(sock1, @moon_zmq.POLLIN)
    poller.add(sock2, @moon_zmq.POLLIN)

    // 非阻塞超时轮询
    let ready_count = poller.poll(timeout_ms=50) catch { _ => 0 }
    if poller.has_in(sock1) {
    let msg = sock1.recv() catch { _ => return }
    println("Channel 1 event: \{msg.first_string()}")
    }
    })
    }


    #规范覆盖表

    moon-zmq 严格对齐 ZeroMQ RFC 官方标准:

    规范描述状态详细说明
    RFC 4ZPL 属性配置语言100% 完成4 空格层级解析、序列化及 SocketOptions 双向映射 (ZConfig)
    RFC 7 / 8Majordomo MDP/0.2 与 MMI100% 完成面向服务代理 (MdpBroker)、LRU 调度与 mmi.service 服务发现
    RFC 23ZMTP 3.1 协议核心规范100% 完成支持短帧、长帧、MORE 标志、命令帧、版本协商与 NULL 握手
    RFC 24PLAIN 安全机制100% 完成完整覆盖 HELLO/WELCOME/INITIATE 交互流与 ZAP 认证回调
    RFC 25CURVE 安全机制暂未实现详细技术评估参见 docs/spec-coverage.md(等待生态标准库)
    RFC 27ZAP 1.0 认证协议100% 完成inproc://zeromq.zap.01 鉴权服务、IPv4 CIDR 策略与审计日志
    RFC 28REQ / REP 套接字规范100% 完成状态机交替校验、空帧信封封装解包及 ReliableClient 故障转移
    RFC 29PUB / SUB 套接字规范100% 完成SubscriptionTrie 前缀树过滤、多连接广播与 ConflateBuffer
    RFC 30PIPELINE (PUSH / PULL) 规范100% 完成公平轮询(Round-Robin)分发与公平排队(Fair-Queuing)汇聚
    RFC 31ROUTER / DEALER 异步路由规范100% 完成异步多路复用、Identity 信封路由与全双工轮询收发
    RFC 32Z85 二进制文本编码规范100% 完成85 字符集编解码、溢出保护及任意长度填充扩展 (z85_encode)
    RFC 37ZMTP 心跳保活机制100% 完成周期 PING 探测、对端自动应答 PONG 与失活超时自动重连
    RFC 43ZeroMQ 可控代理与转发中介100% 完成双向流量中继、流量统计、旁路抓包与 PAUSE/RESUME/TERMINATE 管控
    RFC 47XPUB / XSUB 与 LVC 缓存代理100% 完成下游订阅透传与最新值缓存重放代理 (LastValueCache / run_lvc_proxy)
    Draft / CZMQinproc://、Radio/Dish、ZActor/ZLoop100% 完成零拷贝进程内通道(含先 connect 后 bind)、精确群组订阅与反应器

    完整逐条规范对标说明与技术分析,请参见面向开发者的正式文档:docs/spec-coverage.md。


    #跨实现互通测试结果

    本项目通过 Python 官方 pyzmq(底层驱动为官方 libzmq 4.3.5)进行了高标准的全量双向端到端互通测试(集成测试源码位于 tests/interop/test_interop.py),并在 GitHub Actions CI 中自动化运行:

    test_big_message_moonbit_server (MoonBit REP 服务端接收 Python 512KB 大消息) ... ok test_big_message_python_server (Python REP 服务端接收 MoonBit 512KB 大消息) ... ok test_multipart_moonbit_server (MoonBit 接收 Python 多帧消息并倒序回复) ... ok test_multipart_python_server (Python 接收 MoonBit 多帧消息并倒序回复) ... ok test_pair_moonbit_server (MoonBit PAIR 服务端 <-> Python PAIR 客户端) ... ok test_pair_python_server (Python PAIR 服务端 <-> MoonBit PAIR 客户端) ... ok test_plain_auth_moonbit_server (MoonBit PLAIN 服务端验证 Python 认证凭据) ... ok test_plain_auth_python_server (Python ThreadAuthenticator 服务端验证 MoonBit 凭据) ... ok test_pub_sub_moonbit_server (MoonBit PUB 广播 <-> Python SUB 过滤订阅) ... ok test_pub_sub_python_server (Python PUB 广播 <-> MoonBit SUB 过滤订阅) ... ok test_pull_server_moonbit (MoonBit PULL 汇聚 <-> Python PUSH 生产) ... ok test_push_pull_moonbit_server (MoonBit PUSH 分发 <-> Python PULL 接收) ... ok test_push_pull_python_server (Python PUSH 分发 <-> MoonBit PULL 接收) ... ok test_reconnection_moonbit_client (服务端崩溃重启后 MoonBit 客户端自动重连并恢复通信) ... ok test_req_rep_moonbit_server (MoonBit REP 服务端 <-> Python REQ 客户端) ... ok test_req_rep_python_server (Python REP 服务端 <-> MoonBit REQ 客户端) ... ok test_router_dealer_moonbit_server (MoonBit ROUTER 代理 <-> Python DEALER 客户端) ... ok test_router_dealer_python_server (Python ROUTER 服务端 <-> MoonBit DEALER 客户端) ... ok ---------------------------------------------------------------------- Ran 18 tests in 6.678s OK (18 passed, 0 failed)

    • MoonBit 单元/状态机/属性/企业特性/边界测试:54/54 测试通过。
    • 官方 libzmq 双向互通与基准测试:20/20 测试通过。


    #真实基准性能测试数据 (Benchmarks)

    在本地原生 TCP 回环环境(Windows x86_64,Intel Core 处理器)下对 moon-zmq 开展系统性基准性能压测,涵盖小包至超大包(64B ~ 1MB)的单向流水线吞吐量与双向 RPC 往返延迟分位数统计:

    #1. PUSH / PULL 单向流水线吞吐量

    消息载荷规格传输批次耗时消息吞吐率 (msg/s)带宽吞吐率 (MB/s)
    64 Bytes2,000 帧80 ms25,000 msg/s1.53 MB/s
    1 KByte1,000 帧67 ms14,925 msg/s14.58 MB/s
    64 KBytes100 帧357 ms280 msg/s17.51 MB/s
    1 MByte (超大帧)10 帧539 ms18 msg/s18.55 MB/s

    注:在跨语言互通基准测试中(Python pyzmq 生产 -> MoonBit PULL 接收),64B 小包吞吐率达到 37,679 ~ 47,965 msg/s,64KB 吞吐带宽达到 24.67 ~ 27.20 MB/s,1MB 超大帧带宽达到 31.26 MB/s。

    #2. REQ / REP 双向往返延迟 (Round-Trip Latency Percentiles)

    消息载荷规格采样次数 (n)Minp50 (中位数)p95p99Max平均延迟 (Avg)
    64 Bytes500 次0 ms0 ms1 ms1 ms8 ms0.29 ms
    1 KByte200 次0 ms0 ms1 ms2 ms50 ms0.58 ms
    64 KBytes50 次5 ms7 ms25 ms86 ms86 ms10.08 ms
    1 MByte10 次69 ms101 ms124 ms124 ms124 ms95.6 ms

    注:在官方 libzmq(pyzmq)与 MoonBit 互通延迟测试中,64B 小包 RPC 往返延迟 p50 仅为 0.10 ms(100 微秒),p99 为 0.20 ms;1KB 包往返延迟 p50 仅为 0.12 ms。


    #运行示例工程

    仓库的 examples/ 目录提供了 8 个开箱即用的完整独立示例工程:

    # 1. 运行请求应答示例 (REQ / REP) moon -C examples/req_rep run . --target native # 2. 运行发布订阅遥测示例 (PUB / SUB) moon -C examples/pub_sub run . --target native # 3. 运行流水线任务分发示例 (PUSH / PULL) moon -C examples/pipeline run . --target native # 4. 运行路由代理中介示例 (ROUTER / DEALER) moon -C examples/router_broker run . --target native # 5. 运行 RFC 43 可控消息代理与旁路抓包示例 (Proxy Broker) moon -C examples/proxy_broker run . --target native # 6. 运行 Poller 多路事件复用轮询示例 (Poller Multiplex) moon -C examples/poller_multiplex run . --target native # 7. 运行套接字生命周期监听与流量度量示例 (Socket Monitor) moon -C examples/socket_monitor run . --target native # 8. 运行进程内零拷贝通信、ZActor、RFC 4 配置与 Radio/Dish 示例 (Inproc Actor) moon -C examples/inproc_actor run . --target native


    #版本路线 (Roadmap)

    • v0.1.0 (已完成发布):
    • v0.2.0 (已完成发布):
    • v0.3.0 (当前重大架构升级版本):
    • v1.0.0 (长期演进):


    #开源许可证与合规声明

    本项目采用 OSI(开放源代码促进会)正式认可的 MIT 许可证 开源(Copyright (c) 2026 chgttyyr)。

    • 本项目全部代码均为依据 ZeroMQ 官方公开 RFC 规范 独立编写的 100% 纯 MoonBit 原创实现,未拷贝或移植任何第三方 GPL/LGPL 受限代码;
    • 早期协议调研阶段曾参考社区开源项目 Mr-Shi123/moonjupyter(MIT 许可证)的设计思路,已在文档首部予以公开致谢,完全符合原项目及 OSI 开源合规要求。

    ZmqError

    pub(all) suberror ZmqError {
    ProtocolError(String)
    FrameTooLarge(Int)
    InvalidSocketPair(String, String)
    AuthFailed(String)
    InvalidState(String)
    InvalidEndpoint(String)
    Unroutable(Bytes)
    HighWaterMarkReached
    Closed
    IoError(String)
    } derive(Eq,
    Debug
    )

    ZMTP 3.1 error types covering protocol violations, security failures, socket state errors, routing issues, and transport errors.
    impl Show for ZmqError

    ZmqError::equal

    fn ZmqError::equal(ZmqError, ZmqError) -> Bool
    automatically derived

    ZmqError::not_equal

    fn ZmqError::not_equal(x : ZmqError, y : ZmqError) -> Bool
    automatically derived

    ZmqError::output

    fn ZmqError::output(self : ZmqError, logger : &Logger) -> Unit

    ZmqError::to_repr

    automatically derived

    ZmqError::to_string

    fn ZmqError::to_string(self : ZmqError) -> String

    Default implementation for Show::to_string, uses a StringBuilder

    CircuitBreaker

    pub struct CircuitBreaker {
    failure_threshold : Int
    success_threshold : Int
    cooldown_ms : Int64
    trip_count : Int64
    rejected_calls : Int64
    // private fields
    }

    Three-state endpoint CircuitBreaker (CircuitClosed / CircuitOpen / CircuitHalfOpen) protecting distributed ZeroMQ RPC pipelines against cascading peer stalls.

    CircuitBreaker::allow_request

    fn CircuitBreaker::allow_request(self : CircuitBreaker, now_ms : Int64) -> Bool

    Check whether an outbound call is allowed at now_ms. Automatically transitions CircuitOpen to CircuitHalfOpen once cooldown_ms expires.

    CircuitBreaker::current_state

    fn CircuitBreaker::current_state(self : CircuitBreaker, now_ms? : Int64) -> CircuitState

    Inspect the current CircuitState (advancing CircuitOpen -> CircuitHalfOpen if cooldown_ms has elapsed as of now_ms).

    CircuitBreaker::new

    fn CircuitBreaker::new(failure_threshold? : Int, success_threshold? : Int, cooldown_ms? : Int64) -> CircuitBreaker

    Create a new CircuitBreaker starting in CircuitClosed.

    CircuitBreaker::record_failure

    fn CircuitBreaker::record_failure(self : CircuitBreaker, now_ms : Int64) -> Unit

    Record a downstream timeout or error at now_ms, tripping the breaker to CircuitOpen when failure_threshold is reached (or immediately if CircuitHalfOpen).

    CircuitBreaker::record_success

    fn CircuitBreaker::record_success(self : CircuitBreaker) -> Unit

    Record a successful downstream operation, resetting failure streaks or advancing CircuitHalfOpen toward CircuitClosed.

    CircuitBreaker::reset

    fn CircuitBreaker::reset(self : CircuitBreaker) -> Unit

    Forcefully reset this CircuitBreaker back to CircuitClosed.

    CircuitState

    pub(all) enum CircuitState {
    CircuitClosed
    CircuitOpen
    CircuitHalfOpen
    } derive(Eq,
    Debug
    )

    Operational state of an endpoint CircuitBreaker.

    CircuitState::equal

    automatically derived

    CircuitState::not_equal

    fn CircuitState::not_equal(x : CircuitState, y : CircuitState) -> Bool
    automatically derived

    CircuitState::to_repr

    automatically derived

    ConflateBuffer

    pub struct ConflateBuffer {
    by_topic : Bool
    single_latest : Message?
    topic_slots : Array[(Bytes, Message)]
    pushed_total : Int64
    overwritten_total : Int64
    notify :
    Queue
    [Int]
    }

    Conflating message buffer implementing ZeroMQ ZMQ_CONFLATE behavior.

    Instead of queueing unbounded historical messages during producer bursts, ConflateBuffer overwrites stale unread messages so consumers always read the freshest state (either globally when by_topic=false or per topic frame when by_topic=true).

    ConflateBuffer::has_message

    fn ConflateBuffer::has_message(self : ConflateBuffer) -> Bool

    Whether at least one conflated message is ready to pop without blocking.

    ConflateBuffer::new

    fn ConflateBuffer::new(by_topic? : Bool) -> ConflateBuffer

    Create a new ConflateBuffer.
    • by_topic=false: classic ZMQ_CONFLATE single-slot buffer keeping only the last message.
    • by_topic=true: multi-topic conflation keeping the latest message per first-frame topic.

    ConflateBuffer::overwritten_count

    fn ConflateBuffer::overwritten_count(self : ConflateBuffer) -> Int64

    Total number of stale unread messages coalesced/overwritten before consumption.

    ConflateBuffer::pop

    async fn ConflateBuffer::pop(self : ConflateBuffer) -> Message raise ZmqError

    Asynchronously wait for and pop the latest conflated message.

    ConflateBuffer::push

    fn ConflateBuffer::push(self : ConflateBuffer, msg : Message) -> Unit

    Push a new Message into the conflating buffer, replacing any unread stale value.

    ConflateBuffer::pushed_count

    fn ConflateBuffer::pushed_count(self : ConflateBuffer) -> Int64

    Total number of messages pushed into this ConflateBuffer.

    ConflateBuffer::try_pop

    fn ConflateBuffer::try_pop(self : ConflateBuffer) -> Message?

    Non-blockingly pop the latest message (or earliest-queued dirty topic in by_topic mode).

    Context

    pub struct Context {
    sockets : Array[Socket]
    inproc : InprocRegistry
    closed : Bool
    }

    ZeroMQ Context managing the lifecycle of all created Socket instances and providing an isolated inproc:// transport namespace.

    Context::inproc_registry

    fn Context::inproc_registry(self : Context) -> InprocRegistry

    Return the InprocRegistry isolated within this Context.

    Context::new

    fn Context::new() -> Context

    Create a new ZeroMQ Context.

    Context::socket

    fn Context::socket(self : Context, socket_type : SocketType, options? : SocketOptions) -> Socket raise ZmqError

    Create a new Socket of the given SocketType within this Context.

    Context::term

    fn Context::term(self : Context) -> Unit

    Terminate the Context and close all associated sockets and inproc:// endpoints.

    DecodedItem

    pub(all) enum DecodedItem {
    CommandFrame(Bytes)
    DataMessage(Message)
    } derive(Eq,
    Debug
    )

    Output items decoded from the ZMTP frame stream.

    DecodedItem::equal

    fn DecodedItem::equal(DecodedItem, DecodedItem) -> Bool
    automatically derived

    DecodedItem::not_equal

    fn DecodedItem::not_equal(x : DecodedItem, y : DecodedItem) -> Bool
    automatically derived

    DecodedItem::to_repr

    automatically derived

    DishSocket

    pub struct DishSocket {
    socket : Socket
    // private fields
    }

    ZeroMQ Draft DISH subscriber receiving messages only from explicitly joined groups.

    DishSocket::bind

    async fn DishSocket::bind(self : DishSocket, group :
    TaskGroup
    , endpoint : String) -> String raise ZmqError

    Bind this DishSocket to a tcp:// or inproc:// endpoint.

    DishSocket::close

    fn DishSocket::close(self : DishSocket) -> Unit

    Close the underlying subscriber socket.

    DishSocket::connect

    fn DishSocket::connect(self : DishSocket, group :
    TaskGroup
    , endpoint : String) -> Unit raise ZmqError

    Connect this DishSocket to a tcp:// or inproc:// endpoint.

    DishSocket::groups

    fn DishSocket::groups(self : DishSocket) -> Array[String]

    Return a snapshot of all group names currently joined by this DishSocket.

    DishSocket::is_joined

    fn DishSocket::is_joined(self : DishSocket, group_name : String) -> Bool

    Check whether this DishSocket is currently a member of group_name.

    DishSocket::join

    async fn DishSocket::join(self : DishSocket, group_name : String) -> Unit raise ZmqError

    Join exact group_name (1..255 characters). Idempotent if already joined.

    DishSocket::leave

    async fn DishSocket::leave(self : DishSocket, group_name : String) -> Bool raise ZmqError

    Leave exact group_name. Returns true if previously joined.

    DishSocket::new

    fn DishSocket::new(ctx : Context, options? : SocketOptions) -> DishSocket raise ZmqError

    Create a new DishSocket inside ctx.

    DishSocket::recv_group

    async fn DishSocket::recv_group(self : DishSocket) -> (String, Message) raise ZmqError

    Receive the next group publication as (group_name, payload_message).

    DishSocket::standalone

    fn DishSocket::standalone(options? : SocketOptions) -> DishSocket

    Create a standalone DishSocket outside an explicit Context.

    DissectedPacket

    pub struct DissectedPacket {
    offset : Int
    wire_len : Int
    kind : DissectedPacketKind
    } derive(Eq,
    Debug
    )

    Annotated ZMTP wire record produced by dissect_zmtp_wire.

    DissectedPacket::equal

    automatically derived

    DissectedPacket::not_equal

    fn DissectedPacket::not_equal(x : DissectedPacket, y : DissectedPacket) -> Bool
    automatically derived

    DissectedPacket::to_repr

    automatically derived

    DissectedPacketKind

    pub(all) enum DissectedPacketKind {
    GreetingPacket(String, Int, Int, Bool)
    CommandPacket(String, String)
    DataFramePacket(Bool, Bool, Int, String)
    MalformedPacket(Int, String)
    } derive(Eq,
    Debug
    )

    High-level classification of a dissected ZMTP 3.1 wire unit.

    DissectedPacketKind::equal

    automatically derived

    DissectedPacketKind::not_equal

    automatically derived

    DissectedPacketKind::to_repr

    automatically derived

    Endpoint

    pub(all) enum Endpoint {
    Tcp(String, Int)
    Inproc(String)
    } derive(Eq,
    Debug
    )

    Parsed ZeroMQ transport endpoint URI.
    impl Show for Endpoint

    Endpoint::equal

    fn Endpoint::equal(Endpoint, Endpoint) -> Bool
    automatically derived

    Endpoint::not_equal

    fn Endpoint::not_equal(x : Endpoint, y : Endpoint) -> Bool
    automatically derived

    Endpoint::output

    fn Endpoint::output(self : Endpoint, logger : &Logger) -> Unit

    Endpoint::parse

    fn Endpoint::parse(endpoint : String, for_bind? : Bool) -> Endpoint raise ZmqError

    Parse any supported ZeroMQ endpoint string (tcp://... or inproc://...) into a structured Endpoint value.

    Endpoint::to_repr

    automatically derived

    Endpoint::to_string

    fn Endpoint::to_string(self : Endpoint) -> String

    Default implementation for Show::to_string, uses a StringBuilder

    Frame

    pub struct Frame {
    more : Bool
    is_command : Bool
    data : Bytes
    } derive(Eq,
    Debug
    )

    A single ZMTP 3.1 wire frame (either a message data frame or a command frame).

    Frame::command_frame

    fn Frame::command_frame(data : Bytes) -> Frame

    Create a command frame (COMMAND flag set, MORE flag cleared).

    Frame::data_frame

    fn Frame::data_frame(data : Bytes, more? : Bool) -> Frame

    Create a data frame with an optional more indicator.

    Frame::encode

    fn Frame::encode(self : Frame) -> Bytes

    Encode a single ZMTP 3.1 frame into wire bytes. Uses short framing (1-byte size) for payloads <= 255 bytes and long framing (8-byte big-endian size) for payloads > 255 bytes.

    Frame::equal

    fn Frame::equal(Frame, Frame) -> Bool
    automatically derived

    Frame::not_equal

    fn Frame::not_equal(x : Frame, y : Frame) -> Bool
    automatically derived

    Frame::to_repr

    automatically derived

    FrameDecoder

    pub struct FrameDecoder {
    max_frame_size : Int
    buf : Array[Byte]
    pos : Int
    pending_frames : Array[Bytes]
    failed : Bool
    }

    Streaming ZMTP 3.1 frame and multipart message decoder. Handles arbitrary TCP fragmentation (partial headers/bodies) and coalescing.

    FrameDecoder::feed

    fn FrameDecoder::feed(self : FrameDecoder, chunk : Bytes) -> Array[DecodedItem] raise ZmqError

    Feed raw bytes into the streaming decoder and return all completed frames/messages.

    FrameDecoder::new

    fn FrameDecoder::new(max_frame_size? : Int) -> FrameDecoder

    Create a new streaming frame decoder with an optional maximum frame size cap.

    Greeting

    pub struct Greeting {
    version_major : Int
    version_minor : Int
    mechanism : String
    as_server : Bool
    } derive(Eq,
    Debug
    )

    64-byte ZMTP 3.1 Greeting exchanged at the beginning of a connection (RFC 23 Section 3.2).

    Greeting::decode

    fn Greeting::decode(raw : Bytes) -> Greeting raise ZmqError

    Decode and validate a 64-byte ZMTP Greeting.

    Greeting::encode

    fn Greeting::encode(self : Greeting) -> Bytes

    Encode the 64-byte ZMTP Greeting into wire bytes.

    Greeting::equal

    fn Greeting::equal(Greeting, Greeting) -> Bool
    automatically derived

    Greeting::new

    fn Greeting::new(mechanism? : String, as_server? : Bool, version_major? : Int, version_minor? : Int) -> Greeting

    Construct a ZMTP 3.1 Greeting.

    Greeting::not_equal

    fn Greeting::not_equal(x : Greeting, y : Greeting) -> Bool
    automatically derived

    Greeting::to_repr

    automatically derived

    HwmPolicy

    pub(all) enum HwmPolicy {
    BlockOnFull
    DropOnFull
    ErrorOnFull
    } derive(Eq,
    Debug
    )

    High-water mark (HWM) overflow behavior when a pipe's outbound queue is full.

    HwmPolicy::equal

    fn HwmPolicy::equal(HwmPolicy, HwmPolicy) -> Bool
    automatically derived

    HwmPolicy::not_equal

    fn HwmPolicy::not_equal(x : HwmPolicy, y : HwmPolicy) -> Bool
    automatically derived

    HwmPolicy::to_repr

    automatically derived

    InprocRegistry

    pub struct InprocRegistry {
    // private fields
    }

    Registry coordinating inproc:// listeners and connectors within a Context (or across standalone sockets via the default global registry).

    InprocRegistry::bound_endpoints

    fn InprocRegistry::bound_endpoints(self : InprocRegistry) -> Array[String]

    Return all currently active "inproc://<name>" endpoints in this registry.

    InprocRegistry::close_all

    fn InprocRegistry::close_all(self : InprocRegistry) -> Unit

    Shut down all registered inproc:// listeners and wake all pending waiters.

    InprocRegistry::is_bound

    fn InprocRegistry::is_bound(self : InprocRegistry, name : String) -> Bool

    Check whether name (without "inproc://" prefix) is currently bound in this registry.

    InprocRegistry::new

    Create a new isolated InprocRegistry.

    InprocRegistry::unbind

    fn InprocRegistry::unbind(self : InprocRegistry, name : String) -> Bool

    Unbind an inproc:// endpoint name from this registry. Returns true if removed.

    InprocStream

    pub struct InprocStream {
    rx :
    Queue
    [Bytes?]
    tx :
    Queue
    [Bytes?]
    bytes_written : Int64
    bytes_read : Int64
    closed : Bool
    }

    Full-duplex in-memory byte stream backing one side of an inproc:// connection.

    InprocStream::close

    fn InprocStream::close(self : InprocStream) -> Unit

    Close this InprocStream and signal EOF to the remote peer without destroying unread chunks still queued in transit.

    InprocStream::read

    async fn InprocStream::read(self : InprocStream) -> Bytes? raise ZmqError

    Read the next wire byte chunk from the inbound half of this InprocStream, returning None on clean EOF.

    InprocStream::write

    async fn InprocStream::write(self : InprocStream, data : Bytes) -> Unit raise ZmqError

    Write wire bytes into the outbound half of this InprocStream.

    Ipv4Cidr

    pub struct Ipv4Cidr {
    network : Int64
    mask : Int64
    prefix_len : Int
    text : String
    } derive(Eq,
    Debug
    )

    Parsed IPv4 CIDR network rule (e.g. "127.0.0.1/32" or "10.0.0.0/8").

    Ipv4Cidr::contains

    fn Ipv4Cidr::contains(self : Ipv4Cidr, ip_str : String) -> Bool

    Test whether ip_str falls within this Ipv4Cidr subnet.

    Ipv4Cidr::equal

    fn Ipv4Cidr::equal(Ipv4Cidr, Ipv4Cidr) -> Bool
    automatically derived

    Ipv4Cidr::not_equal

    fn Ipv4Cidr::not_equal(x : Ipv4Cidr, y : Ipv4Cidr) -> Bool
    automatically derived

    Ipv4Cidr::parse

    fn Ipv4Cidr::parse(cidr : String) -> Ipv4Cidr raise ZmqError

    Parse an IPv4 address or CIDR block ("10.20.0.0/16" or "127.0.0.1").

    Ipv4Cidr::to_repr

    automatically derived

    LastValueCache

    pub struct LastValueCache {
    max_topics : Int
    ttl_ms : Int64
    entries : Array[LvcEntry]
    next_seq : Int64
    cache_hits : Int64
    cache_updates : Int64
    evictions : Int64
    }

    Last-Value Cache (LVC) engine for ZeroMQ PUB/SUB & XPUB/XSUB brokers (ZeroMQ Guide Chapter 5 "Last Value Caching").

    Retains the most recent Message published for each topic, supports optional TTL expiration and bounded capacity eviction, and replays matching cached messages whenever a late-joining subscriber subscribes to a topic prefix.

    LastValueCache::clear

    fn LastValueCache::clear(self : LastValueCache) -> Unit

    Clear all cached topic entries.

    LastValueCache::evictions_count

    fn LastValueCache::evictions_count(self : LastValueCache) -> Int64

    Total number of entries evicted due to capacity limits or TTL expiration.

    LastValueCache::get_exact

    fn LastValueCache::get_exact(self : LastValueCache, topic : Bytes, now_ms? : Int64) -> Message?

    Retrieve the cached message for exact topic, if present and not expired.

    LastValueCache::hits_count

    fn LastValueCache::hits_count(self : LastValueCache) -> Int64

    Total number of prefix/exact replay hits served from the cache.

    LastValueCache::new

    fn LastValueCache::new(max_topics? : Int, ttl_ms? : Int64) -> LastValueCache

    Create a new LastValueCache with bounded max_topics and optional ttl_ms (0L disables time-based expiration).

    LastValueCache::purge_expired

    fn LastValueCache::purge_expired(self : LastValueCache, now_ms : Int64) -> Int

    Remove all expired entries as of now_ms and return the count of purged entries.

    LastValueCache::query_prefix

    fn LastValueCache::query_prefix(self : LastValueCache, prefix : Bytes, now_ms? : Int64) -> Array[Message]

    Query all non-expired cached messages whose topic starts with prefix. Used by an XPUB LVC broker to immediately replay cached values to new subscribers.

    LastValueCache::size

    fn LastValueCache::size(self : LastValueCache) -> Int

    Number of topics currently stored in the cache.

    LastValueCache::store

    fn LastValueCache::store(self : LastValueCache, topic : Bytes, message : Message, now_ms? : Int64) -> Unit

    Store or overwrite the latest message for topic at timestamp now_ms. If max_topics is exceeded, evicts the oldest updated topic.

    LastValueCache::store_auto_topic

    fn LastValueCache::store_auto_topic(self : LastValueCache, msg : Message, delimiter? : Byte?, now_ms? : Int64) -> Bytes

    Store a message using its first frame as the canonical topic key (or full single-frame prefix up to delimiter byte if single-frame "topic payload" style is used).

    LastValueCache::updates_count

    fn LastValueCache::updates_count(self : LastValueCache) -> Int64

    Total number of topic updates recorded in the cache.

    LatencyHistogram

    pub struct LatencyHistogram {
    window_capacity : Int
    buckets : FixedArray[Int64]
    total_samples : Int64
    sum_us : Int64
    min_us : Int64
    max_us : Int64
    // private fields
    }

    Sliding-window microsecond latency histogram with fixed latency buckets: [<50us, <100us, <250us, <500us, <1ms, <5ms, <10ms, <50ms, >=50ms].

    LatencyHistogram::new

    fn LatencyHistogram::new(window_capacity? : Int) -> LatencyHistogram

    Create a new LatencyHistogram retaining the latest window_capacity samples for exact percentile calculation alongside lifetime cumulative buckets.

    LatencyHistogram::record_ms

    fn LatencyHistogram::record_ms(self : LatencyHistogram, latency_ms : Int64) -> Unit

    Record a latency observation given in milliseconds.

    LatencyHistogram::record_us

    fn LatencyHistogram::record_us(self : LatencyHistogram, latency_us : Int64) -> Unit

    Record a single latency observation in microseconds (>= 0).

    LatencyHistogram::reset

    fn LatencyHistogram::reset(self : LatencyHistogram) -> Unit

    Reset all recorded observations and bucket counters in this LatencyHistogram.

    LatencyHistogram::summarize

    Compute a LatencySummary containing lifetime min/max/mean and sliding-window p50, p90, p95, and p99 percentiles in microseconds.

    LatencySummary

    pub struct LatencySummary {
    samples : Int64
    min_us : Int64
    max_us : Int64
    mean_us : Int64
    p50_us : Int64
    p90_us : Int64
    p95_us : Int64
    p99_us : Int64
    } derive(Eq,
    Debug
    )

    Latency distribution snapshot with microsecond percentiles and fixed bucket counts.

    LatencySummary::equal

    automatically derived

    LatencySummary::not_equal

    fn LatencySummary::not_equal(x : LatencySummary, y : LatencySummary) -> Bool
    automatically derived

    LatencySummary::to_repr

    automatically derived

    LvcEntry

    pub struct LvcEntry {
    topic : Bytes
    message : Message
    updated_at_ms : Int64
    sequence : Int64
    } derive(Eq,
    Debug
    )

    Cached topic snapshot stored inside a LastValueCache.

    LvcEntry::equal

    fn LvcEntry::equal(LvcEntry, LvcEntry) -> Bool
    automatically derived

    LvcEntry::not_equal

    fn LvcEntry::not_equal(x : LvcEntry, y : LvcEntry) -> Bool
    automatically derived

    LvcEntry::to_repr

    automatically derived

    MdpBroker

    pub struct MdpBroker {
    heartbeat_liveness_ms : Int64
    total_client_requests : Int64
    total_worker_replies : Int64
    total_mmi_queries : Int64
    // private fields
    }

    ZeroMQ RFC 7 Majordomo (MDP/0.2) & RFC 8 (MMI) Service-Oriented Broker state machine.

    Manages worker registration, Least-Recently-Used (LRU) dispatch, request queueing when all workers are busy, worker liveness expiry, and built-in "mmi.service" discovery.

    MdpBroker::build_worker_heartbeats

    fn MdpBroker::build_worker_heartbeats(self : MdpBroker) -> Array[Message]

    Build HEARTBEAT router messages for all currently registered workers.

    MdpBroker::handle_router_message

    fn MdpBroker::handle_router_message(self : MdpBroker, raw : Message, now_ms? : Int64) -> Array[Message] raise ZmqError

    Process a single inbound ROUTER message (either MDPC02 from a client or MDPW02 from a worker) at now_ms, returning zero or more outbound ROUTER messages.

    MdpBroker::new

    fn MdpBroker::new(heartbeat_liveness_ms? : Int64) -> MdpBroker

    Create a new MdpBroker with configurable worker heartbeat_liveness_ms.

    MdpBroker::purge_expired_workers

    fn MdpBroker::purge_expired_workers(self : MdpBroker, now_ms : Int64) -> Array[Message]

    Purge workers whose expires_at_ms has elapsed as of now_ms, returning optional DISCONNECT notifications to send over the ROUTER socket.

    MdpBroker::service_count

    fn MdpBroker::service_count(self : MdpBroker) -> Int

    Number of distinct service queues created on the broker.

    MdpBroker::worker_count

    fn MdpBroker::worker_count(self : MdpBroker) -> Int

    Number of registered workers (both idle and busy) currently tracked by the broker.

    MdpWorkerCommand

    pub(all) enum MdpWorkerCommand {
    Ready
    Request
    Reply
    Heartbeat
    Disconnect
    } derive(Eq,
    Debug
    )

    Command tags for Majordomo Worker Protocol (MDP/0.2, RFC 7 Section 2.2).

    MdpWorkerCommand::equal

    automatically derived

    MdpWorkerCommand::from_byte

    fn MdpWorkerCommand::from_byte(b : Byte) -> MdpWorkerCommand?

    Parse a single-byte RFC 7 wire tag into MdpWorkerCommand.

    MdpWorkerCommand::not_equal

    fn MdpWorkerCommand::not_equal(x : MdpWorkerCommand, y : MdpWorkerCommand) -> Bool
    automatically derived

    MdpWorkerCommand::to_byte

    fn MdpWorkerCommand::to_byte(self : MdpWorkerCommand) -> Byte

    Convert an MdpWorkerCommand to its single-byte RFC 7 wire tag.

    MdpWorkerCommand::to_repr

    automatically derived

    Message

    pub struct Message {
    frames : Array[Bytes]
    } derive(Eq,
    Debug
    )

    A ZeroMQ multipart message consisting of one or more contiguous data frames.

    Message::add_frame

    fn Message::add_frame(self : Message, frame : Bytes) -> Message

    Create a new Message with an additional frame appended at the end.

    Message::add_string

    fn Message::add_string(self : Message, str : String) -> Message

    Create a new Message with an additional UTF-8 string frame appended at the end.

    Message::encode

    fn Message::encode(self : Message) -> Bytes

    Encode a multipart message into ZMTP 3.1 wire bytes, setting MORE=1 on all frames except the final frame.

    Message::equal

    fn Message::equal(Message, Message) -> Bool
    automatically derived

    Message::first_bytes

    fn Message::first_bytes(self : Message) -> Bytes

    Return the first frame's bytes (or empty bytes if none).

    Message::first_string

    fn Message::first_string(self : Message) -> String

    Return the first frame decoded as a UTF-8 string.

    Message::frame_at

    fn Message::frame_at(self : Message, index : Int) -> Bytes?

    Get the frame payload at index (0-based), or None if out of bounds.

    Message::frame_count

    fn Message::frame_count(self : Message) -> Int

    Number of frames in this message.

    Message::frame_string_at

    fn Message::frame_string_at(self : Message, index : Int) -> String?

    Get the UTF-8 string representation of the frame at index, or None if out of bounds.

    Message::from_bytes

    fn Message::from_bytes(payload : Bytes) -> Message

    Construct a single-frame message from raw bytes.

    Message::from_string

    fn Message::from_string(s : String) -> Message

    Construct a single-frame message from a UTF-8 string.

    Message::from_strings

    fn Message::from_strings(strings : Array[String]) -> Message

    Construct a multipart message from an array of UTF-8 string frames.

    Message::is_empty

    fn Message::is_empty(self : Message) -> Bool

    Whether this message has no payload frames.

    Message::len

    fn Message::len(self : Message) -> Int

    Number of frames in the multipart message.

    Message::multipart

    fn Message::multipart(frames : Array[Bytes]) -> Message

    Construct a multipart message from an array of frame byte payloads. If an empty array is passed, a single empty frame [b""] is used per ZMTP rules.

    Message::not_equal

    fn Message::not_equal(x : Message, y : Message) -> Bool
    automatically derived

    Message::to_repr

    automatically derived

    Message::to_string_array

    fn Message::to_string_array(self : Message) -> Array[String]

    Convert all frames into an array of UTF-8 strings.

    Message::total_bytes

    fn Message::total_bytes(self : Message) -> Int

    Total payload byte count across all frames.

    Metadata

    pub struct Metadata {
    socket_type : String
    identity : Bytes?
    properties : Array[(String, Bytes)]
    } derive(Eq,
    Debug
    )

    ZMTP 3.1 handshake metadata properties (Socket-Type, Identity, and custom keys).

    Metadata::decode

    fn Metadata::decode(raw : Bytes) -> Metadata raise ZmqError

    Parse ZMTP metadata wire bytes into Metadata. Property names are matched case-insensitively per RFC 23 Section 3.3.

    Metadata::encode

    fn Metadata::encode(self : Metadata) -> Bytes

    Serialize metadata into ZMTP property key-value wire format.

    Metadata::equal

    fn Metadata::equal(Metadata, Metadata) -> Bool
    automatically derived

    Metadata::get

    fn Metadata::get(self : Metadata, key : String) -> Bytes?

    Look up a metadata property value by case-insensitive key name.

    Metadata::new

    fn Metadata::new(socket_type : String, identity? : Bytes?, properties? : Array[(String, Bytes)]) -> Metadata

    Construct handshake metadata.

    Metadata::not_equal

    fn Metadata::not_equal(x : Metadata, y : Metadata) -> Bool
    automatically derived

    Metadata::to_repr

    automatically derived

    NullSession

    pub struct NullSession {
    local_type : SocketType
    local_identity : Bytes?
    state : NullSessionState
    greet_buf : Array[Byte]
    decoder : FrameDecoder
    peer_metadata : Metadata?
    }

    Streaming ZMTP 3.1 session state machine for the NULL security mechanism. Handles arbitrary byte chunking across greeting, READY handshake, PING/PONG, ERROR frames, and multipart data messages.

    NullSession::feed

    fn NullSession::feed(self : NullSession, chunk : Bytes) -> Array[SessionEvent]

    Feed raw wire bytes into the NullSession and return resulting session events.

    NullSession::initial_greeting

    fn NullSession::initial_greeting(_self : NullSession) -> Bytes

    Produce the initial outbound greeting bytes for a NULL session.

    NullSession::local_ready_frame

    fn NullSession::local_ready_frame(self : NullSession) -> Bytes

    Produce the outbound READY command frame for this session.

    NullSession::new

    fn NullSession::new(local_type : SocketType, local_identity? : Bytes?, max_frame_size? : Int) -> NullSession

    Create a new NullSession for the given local socket type and optional identity.

    NullSession::peer_metadata

    fn NullSession::peer_metadata(self : NullSession) -> Metadata?

    Return the negotiated peer metadata once the handshake is complete.

    NullSessionState

    type NullSessionState derive(Eq)

    NullSessionState::equal

    automatically derived

    NullSessionState::not_equal

    fn NullSessionState::not_equal(x : NullSessionState, y : NullSessionState) -> Bool
    automatically derived

    Pipe

    pub struct Pipe {
    id : Int
    peer_identity : Bytes
    peer_metadata : Metadata
    sndhwm : Int
    rcvhwm : Int
    snd_queue :
    Queue
    [Bytes]
    rcv_queue :
    Queue
    [Message]
    snd_count : Int
    rcv_count : Int
    subscriptions : Array[Bytes]
    active : Bool
    closed : Bool
    }

    Bidirectional message pipe representing a single active ZMTP peer connection. Enforces send/receive High-Water Marks (sndhwm, rcvhwm) and tracks per-peer routing identity and PUB/XPUB topic subscriptions.

    Pipe::add_subscription

    fn Pipe::add_subscription(self : Pipe, topic : Bytes) -> Bool

    Add a topic subscription prefix to this pipe. Returns true if this prefix was not already subscribed on this pipe.

    Pipe::can_send

    fn Pipe::can_send(self : Pipe) -> Bool

    Whether the outbound queue is below the send high-water mark (sndhwm).

    Pipe::check_and_clear_activity

    fn Pipe::check_and_clear_activity(self : Pipe) -> Bool

    Check whether activity occurred since last check, and reset the activity flag to false.

    Pipe::close

    fn Pipe::close(self : Pipe) -> Unit

    Close the pipe and both of its underlying queues.

    Pipe::dequeue_outbound

    async fn Pipe::dequeue_outbound(self : Pipe) -> Bytes?

    Dequeue the next outbound wire frame from snd_queue (used by the TCP writer task).

    Pipe::has_inbound

    fn Pipe::has_inbound(self : Pipe) -> Bool

    Whether the inbound queue currently has at least one message ready to read.

    Pipe::is_open

    fn Pipe::is_open(self : Pipe) -> Bool

    Whether the pipe is still open.

    Pipe::matches_subscription

    fn Pipe::matches_subscription(self : Pipe, msg : Message) -> Bool

    Check if a message's first frame matches any subscription prefix registered on this pipe.

    Pipe::new

    fn Pipe::new(id : Int, peer_metadata : Metadata, sndhwm? : Int, rcvhwm? : Int) -> Pipe

    Create a new Pipe for an established peer session.

    Pipe::push_inbound

    async fn Pipe::push_inbound(self : Pipe, msg : Message, drop_on_full? : Bool) -> Bool

    Push a decoded inbound Message from the TCP reader task into rcv_queue. Respects rcvhwm: if drop_on_full is true, drops when full; otherwise blocks.

    Pipe::recv_message

    async fn Pipe::recv_message(self : Pipe) -> Message raise ZmqError

    Asynchronously wait for and pop an inbound Message from this pipe.

    Pipe::remove_subscription

    fn Pipe::remove_subscription(self : Pipe, topic : Bytes) -> Bool

    Remove a topic subscription prefix from this pipe. Returns true if removed.

    Pipe::send_message

    async fn Pipe::send_message(self : Pipe, msg : Message, policy? : HwmPolicy) -> Bool raise ZmqError

    Enqueue a Message onto this pipe using the given HwmPolicy.

    Pipe::send_wire

    async fn Pipe::send_wire(self : Pipe, wire : Bytes, policy? : HwmPolicy) -> Bool raise ZmqError

    Enqueue raw wire bytes (an encoded Message or ZmtpCommand) for transmission according to the specified HwmPolicy. Returns true if enqueued, false if dropped.

    Pipe::touch_activity

    fn Pipe::touch_activity(self : Pipe) -> Unit

    Mark this pipe as having received activity (data or command) from peer.

    Pipe::try_recv_message

    fn Pipe::try_recv_message(self : Pipe) -> Message?

    Non-blocking attempt to pop an inbound Message from this pipe.

    Pipe::try_send_message

    fn Pipe::try_send_message(self : Pipe, msg : Message) -> Bool raise ZmqError

    Non-blocking attempt to enqueue an encoded Message onto this pipe.

    PollItem

    pub struct PollItem {
    socket : Socket
    events : Int
    revents : Int
    }

    An item registered within a Poller tracking a specific Socket and interest bitmask.

    Poller

    pub struct Poller {
    items : Array[PollItem]
    }

    Multiplexer monitoring multiple Socket instances for I/O readiness.

    Poller::add

    fn Poller::add(self : Poller, socket : Socket, events : Int) -> Unit

    Register a Socket to monitor for the specified events bitmask. If already registered, updates the monitored event bitmask.

    Poller::clear

    fn Poller::clear(self : Poller) -> Unit

    Clear all registered sockets from this Poller.

    Poller::has_err

    fn Poller::has_err(self : Poller, socket : Socket) -> Bool

    Check whether POLLERR was signaled for socket in the last poll call.

    Poller::has_in

    fn Poller::has_in(self : Poller, socket : Socket) -> Bool

    Check whether POLLIN was signaled for socket in the last poll call.

    Poller::has_out

    fn Poller::has_out(self : Poller, socket : Socket) -> Bool

    Check whether POLLOUT was signaled for socket in the last poll call.

    Poller::length

    fn Poller::length(self : Poller) -> Int

    Number of sockets currently monitored by this Poller.

    Poller::modify

    fn Poller::modify(self : Poller, socket : Socket, events : Int) -> Bool

    Modify the interest bitmask for an already registered Socket. Returns true if modified, false if the socket was not registered.

    Poller::new

    fn Poller::new() -> Poller

    Create a new empty Poller.

    Poller::poll

    async fn Poller::poll(self : Poller, timeout_ms? : Int) -> Int

    Wait asynchronously for events on any registered Socket.
    • timeout_ms = 0: Non-blocking immediate check.
    • timeout_ms < 0: Wait indefinitely until at least one event is ready.
    • timeout_ms > 0: Wait up to timeout_ms milliseconds. Returns the number of ready sockets.

    Poller::remove

    fn Poller::remove(self : Poller, socket : Socket) -> Bool

    Unregister a Socket from this Poller. Returns true if found and removed, false otherwise.

    Poller::revents_for

    fn Poller::revents_for(self : Poller, socket : Socket) -> Int

    Get the ready events bitmask (revents) computed during the last poll call for socket.

    ProxyState

    pub(all) enum ProxyState {
    Active
    Paused
    Terminated
    } derive(Eq,
    Debug
    )

    Runtime operational state of a proxy forwarder.

    ProxyState::equal

    fn ProxyState::equal(ProxyState, ProxyState) -> Bool
    automatically derived

    ProxyState::not_equal

    fn ProxyState::not_equal(x : ProxyState, y : ProxyState) -> Bool
    automatically derived

    ProxyState::to_repr

    automatically derived

    ProxyStats

    pub struct ProxyStats {
    frontend_messages : Int64
    backend_messages : Int64
    captured_messages : Int64
    }

    Performance and message counters tracked by a proxy instance.

    ProxyStats::new

    fn ProxyStats::new() -> ProxyStats

    Create a new ProxyStats counter initialized to zero.

    RadioSocket

    pub struct RadioSocket {
    socket : Socket
    }

    ZeroMQ Draft RADIO publisher broadcasting exact-group messages to DISH peers.

    RadioSocket::bind

    async fn RadioSocket::bind(self : RadioSocket, group :
    TaskGroup
    , endpoint : String) -> String raise ZmqError

    Bind this RadioSocket to a tcp:// or inproc:// endpoint.

    RadioSocket::close

    fn RadioSocket::close(self : RadioSocket) -> Unit

    Close the underlying publisher socket.

    RadioSocket::connect

    fn RadioSocket::connect(self : RadioSocket, group :
    TaskGroup
    , endpoint : String) -> Unit raise ZmqError

    Connect this RadioSocket to a tcp:// or inproc:// endpoint.

    RadioSocket::new

    fn RadioSocket::new(ctx : Context, options? : SocketOptions) -> RadioSocket raise ZmqError

    Create a new RadioSocket inside ctx (or standalone via RadioSocket::standalone).

    RadioSocket::send_group

    async fn RadioSocket::send_group(self : RadioSocket, group_name : String, payload : Message) -> Unit raise ZmqError

    Publish a Message exclusively to DishSocket peers that have joined exact group_name.

    RadioSocket::send_group_string

    async fn RadioSocket::send_group_string(self : RadioSocket, group_name : String, text : String) -> Unit raise ZmqError

    Convenience helper publishing a UTF-8/ASCII string message to exact group_name.

    RadioSocket::standalone

    fn RadioSocket::standalone(options? : SocketOptions) -> RadioSocket

    Create a standalone RadioSocket outside an explicit Context.

    RateLimiter

    pub struct RateLimiter {
    msgs_per_sec : Int64
    burst_msgs : Int64
    bytes_per_sec : Int64
    burst_bytes : Int64
    accepted_msgs : Int64
    rejected_msgs : Int64
    // private fields
    }

    Dual token-bucket rate limiter shaping both message rate (msgs_per_sec) and byte bandwidth (bytes_per_sec, 0L = unlimited byte rate).

    Uses millisecond token refill with 1000x internal scaling to avoid floating-point drift.

    RateLimiter::new

    fn RateLimiter::new(msgs_per_sec? : Int64, burst_msgs? : Int64, bytes_per_sec? : Int64, burst_bytes? : Int64, initial_now_ms? : Int64) -> RateLimiter

    Create a new RateLimiter.
    • msgs_per_sec: sustained message rate (<= 0L disables message rate limiting).
    • burst_msgs: maximum message burst bucket size.
    • bytes_per_sec: sustained payload byte rate (<= 0L disables bandwidth limiting).
    • burst_bytes: maximum byte burst bucket size.

    RateLimiter::send_paced

    async fn RateLimiter::send_paced(self : RateLimiter, socket : Socket, msg : Message, policy? : HwmPolicy) -> Unit raise ZmqError

    Asynchronously wait until tokens become available and send msg on socket.

    RateLimiter::try_acquire

    fn RateLimiter::try_acquire(self : RateLimiter, payload_bytes : Int, now_ms : Int64) -> Bool

    Attempt to consume quota for 1 message of payload_bytes at now_ms. Returns true if permitted, or false (leaving tokens intact) if rate-limited.

    RateLimiter::wait_time_ms

    fn RateLimiter::wait_time_ms(self : RateLimiter, payload_bytes : Int, now_ms : Int64) -> Int

    Estimate how many milliseconds a caller must wait from now_ms until a message of payload_bytes will be permitted. Returns 0 if immediately allowed.

    ReliableClient

    pub struct ReliableClient {
    ctx : Context
    endpoints : Array[String]
    endpoint_index : Int
    timeout_ms : Int
    max_retries : Int
    active_socket : Socket?
    requests_sent : Int64
    retries_count : Int64
    failovers_count : Int64
    }

    Reliable Request-Reply client implementing the ZeroMQ Guide Chapter 4 "Lazy Pirate" + multi-endpoint failover pattern.

    Unlike raw REQ (which blocks forever if a single REP peer crashes mid-call), ReliableClient enforces per-attempt timeout_ms, retries up to max_retries, recreates the underlying socket on timeout to clear poisoned state, and rotates across all configured endpoints.

    ReliableClient::close

    fn ReliableClient::close(self : ReliableClient) -> Unit

    Close the underlying socket held by this ReliableClient.

    ReliableClient::failovers

    fn ReliableClient::failovers(self : ReliableClient) -> Int64

    Total number of endpoint failover rotations performed by this ReliableClient.

    ReliableClient::new

    fn ReliableClient::new(ctx : Context, endpoints : Array[String], timeout_ms? : Int, max_retries? : Int) -> ReliableClient raise ZmqError

    Create a ReliableClient configured with one or more server endpoints, per-try timeout_ms, and max_retries.

    ReliableClient::request

    Send request and wait for a REP response within timeout_ms, automatically retrying and rotating endpoints up to max_retries times before raising IoError.

    ReliableClient::retries

    fn ReliableClient::retries(self : ReliableClient) -> Int64

    Total number of retries triggered by timeouts on this ReliableClient.

    SessionEvent

    pub(all) enum SessionEvent {
    HandshakeReady(Metadata)
    MessageReceived(Message)
    CommandReceived(ZmtpCommand)
    SendBytes(Bytes)
    ProtocolFailure(String)
    } derive(Eq,
    Debug
    )

    High-level events produced by a ZMTP 3.1 peer session state machine.

    SessionEvent::equal

    automatically derived

    SessionEvent::not_equal

    fn SessionEvent::not_equal(x : SessionEvent, y : SessionEvent) -> Bool
    automatically derived

    SessionEvent::to_repr

    automatically derived

    Socket

    pub struct Socket {
    id : Int
    socket_type : SocketType
    options : SocketOptions
    hub : TransportHub
    inproc_registry : InprocRegistry
    closed : Bool
    // private fields
    }

    High-level ZeroMQ Socket implementing ZMTP 3.1 messaging patterns.
    impl Eq for Socket

    Socket::active_peer_count

    fn Socket::active_peer_count(self : Socket) -> Int

    Number of currently active peer connections on this socket.

    Socket::active_peer_ids

    fn Socket::active_peer_ids(self : Socket) -> Array[Int]

    List of IDs of all currently active peer connections.

    Socket::bind

    async fn Socket::bind(self : Socket, group :
    TaskGroup
    , endpoint : String) -> String raise ZmqError

    Bind a local "tcp://host:port" or "inproc://name" endpoint and begin accepting peers in group. Returns the resolved endpoint string (e.g. "tcp://127.0.0.1:54321" or "inproc://workers").

    Socket::bytes_received

    fn Socket::bytes_received(self : Socket) -> Int64

    Total payload bytes received by this socket.

    Socket::bytes_sent

    fn Socket::bytes_sent(self : Socket) -> Int64

    Total payload bytes sent by this socket.

    Socket::can_recv

    fn Socket::can_recv(self : Socket) -> Bool

    Whether this Socket can perform a non-blocking receive operation.

    Socket::can_send

    fn Socket::can_send(self : Socket) -> Bool

    Whether this Socket can perform a non-blocking send operation.

    Socket::close

    fn Socket::close(self : Socket) -> Unit

    Close the socket and release all underlying transport resources.

    Socket::connect

    fn Socket::connect(self : Socket, group :
    TaskGroup
    , endpoint : String) -> Unit raise ZmqError

    Connect to a remote "tcp://host:port" or "inproc://name" endpoint in group with automatic reconnection and early-connect support.

    Socket::equal

    fn Socket::equal(self : Socket, other : Socket) -> Bool

    Socket::has_events

    fn Socket::has_events(self : Socket, events : Int) -> Int

    Evaluate which events among requested events (POLLIN, POLLOUT, POLLERR) are currently ready.

    Socket::id

    fn Socket::id(self : Socket) -> Int

    Unique numeric identifier of this Socket.

    Socket::is_closed

    fn Socket::is_closed(self : Socket) -> Bool

    Whether this Socket has been closed.

    Socket::messages_received

    fn Socket::messages_received(self : Socket) -> Int64

    Total number of messages received by this socket.

    Socket::messages_sent

    fn Socket::messages_sent(self : Socket) -> Int64

    Total number of messages sent by this socket.

    Socket::monitor_events

    fn Socket::monitor_events(self : Socket, capacity? : Int) ->
    Queue
    [SocketEvent]

    Create an asynchronous queue that receives all SocketEvent occurrences for this socket.

    Socket::new

    fn Socket::new(socket_type : SocketType, options? : SocketOptions) -> Socket

    Create a standalone Socket with the specified SocketType and SocketOptions.

    Socket::new_with_inproc

    fn Socket::new_with_inproc(socket_type : SocketType, inproc_registry : InprocRegistry, options? : SocketOptions) -> Socket

    Create a Socket bound to a specific InprocRegistry namespace.

    Socket::not_equal

    fn Socket::not_equal(x : Socket, y : Socket) -> Bool

    Socket::on_event

    fn Socket::on_event(self : Socket, handler : (SocketEvent) -> Unit) -> Unit

    Register a callback to receive SocketEvent lifecycle notifications.

    Socket::peer_metadata_by_identity

    fn Socket::peer_metadata_by_identity(self : Socket, routing_id : Bytes) -> Metadata?

    Look up the negotiated ZMTP Metadata (including ZAP-injected User-Id and custom attributes) for an active peer identified by routing_id or pipe_id.

    Socket::recv

    async fn Socket::recv(self : Socket) -> Message raise ZmqError

    Receive a Message according to this socket's pattern semantics.

    Socket::recv_batch

    async fn Socket::recv_batch(self : Socket, max_count? : Int) -> Array[Message] raise ZmqError

    Receive up to max_count available messages in a single batch operation. Asynchronously waits for at least the first message, then non-blockingly drains any ready messages.

    Socket::recv_string

    async fn Socket::recv_string(self : Socket) -> String raise ZmqError

    Convenience helper to receive a message and return its first frame as a String.

    Socket::recv_timeout

    async fn Socket::recv_timeout(self : Socket, timeout_ms? : Int) -> Message? raise ZmqError

    Receive a Message waiting up to timeout_ms (falls back to options.rcvtimeo_ms when timeout_ms < -1). Returns None on timeout expiry.

    Socket::send

    async fn Socket::send(self : Socket, msg : Message, policy? : HwmPolicy) -> Unit raise ZmqError

    Send a Message according to this socket's pattern semantics.

    Socket::send_batch

    async fn Socket::send_batch(self : Socket, messages : Array[Message], policy? : HwmPolicy) -> Int raise ZmqError

    Send an array of messages sequentially in a single batch operation.

    Socket::send_bytes

    async fn Socket::send_bytes(self : Socket, b : Bytes, policy? : HwmPolicy) -> Unit raise ZmqError

    Convenience helper to send a single-frame binary message.

    Socket::send_string

    async fn Socket::send_string(self : Socket, s : String, policy? : HwmPolicy) -> Unit raise ZmqError

    Convenience helper to send a single-frame UTF-8/ASCII string message.

    Socket::send_timeout

    async fn Socket::send_timeout(self : Socket, msg : Message, timeout_ms? : Int) -> Bool raise ZmqError

    Send a Message waiting up to timeout_ms for writability (falls back to options.sndtimeo_ms when timeout_ms < -1). Returns false on timeout expiry.

    Socket::set_conflate

    fn Socket::set_conflate(self : Socket, enabled : Bool, by_topic? : Bool) -> Unit

    Enable or disable ZMQ_CONFLATE inbound message coalescing (by_topic=false keeps the single freshest message overall; by_topic=true keeps the freshest per topic).

    Socket::set_heartbeat

    fn Socket::set_heartbeat(self : Socket, ivl_ms~ : Int, timeout_ms? : Int, ttl_ms? : Int) -> Unit

    Configure ZMTP 3.1 heartbeat ping-pong interval and activity timeout in milliseconds.

    Socket::set_hwm

    fn Socket::set_hwm(self : Socket, sndhwm? : Int, rcvhwm? : Int) -> Unit

    Set the outbound and inbound High-Water Marks (sndhwm, rcvhwm).

    Socket::set_identity

    fn Socket::set_identity(self : Socket, identity : Bytes) -> Unit

    Set the ZMTP Identity (Routing-Id) of this socket before binding or connecting.

    Socket::set_plain_credentials

    fn Socket::set_plain_credentials(self : Socket, username : String, password : String) -> Unit

    Configure client-side PLAIN authentication credentials (username, password).

    Socket::set_plain_server

    fn Socket::set_plain_server(self : Socket, enabled : Bool, authenticator? : (String, String) -> Bool?) -> Unit

    Configure server-side PLAIN authentication and optional ZAP verification callback.

    Socket::set_rcvtimeo

    fn Socket::set_rcvtimeo(self : Socket, timeout_ms : Int) -> Unit

    Configure ZMQ_RCVTIMEO default receive timeout in milliseconds (-1 = infinite).

    Socket::set_reconnect_interval

    fn Socket::set_reconnect_interval(self : Socket, ivl_ms : Int, max_ms? : Int) -> Unit

    Configure automatic reconnect initial interval and maximum exponential backoff in milliseconds.

    Socket::set_req_relaxed

    fn Socket::set_req_relaxed(self : Socket, relaxed : Bool) -> Unit

    Enable or disable ZMQ_REQ_RELAXED on a REQ socket so a new send() cancels an unanswered request instead of raising InvalidState.

    Socket::set_router_handover

    fn Socket::set_router_handover(self : Socket, handover : Bool) -> Unit

    Enable or disable ZMQ_ROUTER_HANDOVER on a ROUTER socket.

    Socket::set_router_mandatory

    fn Socket::set_router_mandatory(self : Socket, mandatory : Bool) -> Unit

    Configure ZMQ_ROUTER_MANDATORY on a ROUTER socket.

    Socket::set_sndtimeo

    fn Socket::set_sndtimeo(self : Socket, timeout_ms : Int) -> Unit

    Configure ZMQ_SNDTIMEO default send timeout in milliseconds (-1 = infinite).

    Socket::set_xpub_verbose

    fn Socket::set_xpub_verbose(self : Socket, verbose : Bool) -> Unit

    Configure ZMQ_XPUB_VERBOSE on an XPUB socket.

    Socket::set_zap_engine

    fn Socket::set_zap_engine(self : Socket, engine : ZapPolicyEngine?, domain? : String) -> Unit

    Attach an RFC 27 ZapPolicyEngine for IP/CIDR filtering, credential verification, and authenticated User-Id / metadata injection onto incoming peer pipes.

    Socket::subscribe

    async fn Socket::subscribe(self : Socket, topic : Bytes) -> Unit raise ZmqError

    Add a topic prefix subscription to a SUB or XSUB socket.

    If already connected, immediately sends a subscription frame (0x01 + topic) across all active peer pipes.

    Socket::subscribe_string

    async fn Socket::subscribe_string(self : Socket, topic : String) -> Unit raise ZmqError

    Convenience helper to subscribe to a UTF-8 string topic prefix.

    Socket::try_recv

    async fn Socket::try_recv(self : Socket) -> Message? raise ZmqError

    Non-blocking receive (ZMQ_DONTWAIT): returns Some(msg) if a message is immediately available without waiting, or None if no message is ready.

    Socket::try_send

    async fn Socket::try_send(self : Socket, msg : Message) -> Bool raise ZmqError

    Non-blocking send (ZMQ_DONTWAIT): sends msg immediately if writable without blocking, returning true if sent or false if no writable peer / HWM reached.

    Socket::unsubscribe

    async fn Socket::unsubscribe(self : Socket, topic : Bytes) -> Unit raise ZmqError

    Remove a topic prefix subscription from a SUB or XSUB socket.

    Sends an unsubscription frame (0x00 + topic) across all active peer pipes.

    Socket::unsubscribe_string

    async fn Socket::unsubscribe_string(self : Socket, topic : String) -> Unit raise ZmqError

    Convenience helper to unsubscribe from a UTF-8 string topic prefix.

    SocketEvent

    pub(all) enum SocketEvent {
    Listening(String)
    Accepted(Int)
    Connected(Int)
    Disconnected(Int)
    HandshakeSucceeded(String, Bytes)
    HandshakeFailed(String)
    Closed
    } derive(Eq,
    Debug
    )

    Lifecycle events emitted by a ZeroMQ socket for observability and monitoring.

    SocketEvent::equal

    fn SocketEvent::equal(SocketEvent, SocketEvent) -> Bool
    automatically derived

    SocketEvent::not_equal

    fn SocketEvent::not_equal(x : SocketEvent, y : SocketEvent) -> Bool
    automatically derived

    SocketEvent::to_repr

    automatically derived

    SocketOptions

    pub struct SocketOptions {
    identity : Bytes?
    sndhwm : Int
    rcvhwm : Int
    reconnect_ivl_ms : Int
    reconnect_ivl_max_ms : Int
    handshake_timeout_ms : Int
    max_frame_size : Int
    router_mandatory : Bool
    router_handover : Bool
    req_relaxed : Bool
    xpub_verbose : Bool
    conflate : Bool
    conflate_by_topic : Bool
    rcvtimeo_ms : Int
    sndtimeo_ms : Int
    send_subscribe_commands : Bool
    plain_credentials : (String, String)?
    plain_server : Bool
    zap_authenticator : (String, String) -> Bool?
    zap_engine : ZapPolicyEngine?
    zap_domain : String
    heartbeat_ivl_ms : Int
    heartbeat_timeout_ms : Int
    heartbeat_ttl_ms : Int
    event_handlers : Array[(SocketEvent) -> Unit]
    }

    Configurable options for a ZeroMQ socket and its underlying ZMTP transport.

    SocketOptions::new

    Construct default SocketOptions.

    SocketOptions::on_event

    fn SocketOptions::on_event(self : SocketOptions, handler : (SocketEvent) -> Unit) -> Unit

    Register a callback to receive SocketEvent lifecycle notifications.

    SocketOptions::set_conflate

    fn SocketOptions::set_conflate(self : SocketOptions, enabled : Bool, by_topic? : Bool) -> Unit

    Enable or disable ZMQ_CONFLATE latest-message coalescing on inbound queues.

    SocketOptions::set_handshake_timeout

    fn SocketOptions::set_handshake_timeout(self : SocketOptions, timeout_ms : Int) -> Unit

    Set the handshake timeout in milliseconds (handshake_timeout_ms).

    SocketOptions::set_heartbeat

    fn SocketOptions::set_heartbeat(self : SocketOptions, ivl_ms~ : Int, timeout_ms? : Int, ttl_ms? : Int) -> Unit

    Configure ZMTP 3.1 heartbeat ping-pong interval and timeout in milliseconds.

    SocketOptions::set_identity

    fn SocketOptions::set_identity(self : SocketOptions, id : Bytes?) -> Unit

    Set the ZMTP Identity (Routing-Id) on SocketOptions.

    SocketOptions::set_max_frame_size

    fn SocketOptions::set_max_frame_size(self : SocketOptions, max_bytes : Int) -> Unit

    Set the maximum allowed single frame size in bytes (max_frame_size).

    SocketOptions::set_plain_credentials

    fn SocketOptions::set_plain_credentials(self : SocketOptions, username : String, password : String) -> Unit

    Configure client-side PLAIN credentials (username, password).

    SocketOptions::set_plain_server

    fn SocketOptions::set_plain_server(self : SocketOptions, enabled : Bool, authenticator? : (String, String) -> Bool?) -> Unit

    Configure server-side PLAIN authentication with an optional ZAP callback.

    SocketOptions::set_rcvhwm

    fn SocketOptions::set_rcvhwm(self : SocketOptions, hwm : Int) -> Unit

    Set the inbound High-Water Mark (rcvhwm) on SocketOptions.

    SocketOptions::set_rcvtimeo

    fn SocketOptions::set_rcvtimeo(self : SocketOptions, timeout_ms : Int) -> Unit

    Set default receive timeout in milliseconds (-1 = infinite, 0 = immediate).

    SocketOptions::set_reconnect_interval

    fn SocketOptions::set_reconnect_interval(self : SocketOptions, ivl_ms : Int, max_ms? : Int) -> Unit

    Set the reconnect initial interval (reconnect_ivl_ms) and max backoff (reconnect_ivl_max_ms).

    SocketOptions::set_req_relaxed

    fn SocketOptions::set_req_relaxed(self : SocketOptions, relaxed : Bool) -> Unit

    Enable or disable ZMQ_REQ_RELAXED on a REQ socket.

    SocketOptions::set_router_handover

    fn SocketOptions::set_router_handover(self : SocketOptions, handover : Bool) -> Unit

    Enable or disable ZMQ_ROUTER_HANDOVER on a ROUTER socket.

    SocketOptions::set_router_mandatory

    fn SocketOptions::set_router_mandatory(self : SocketOptions, mandatory : Bool) -> Unit

    Enable or disable ZMQ_ROUTER_MANDATORY behavior on a ROUTER socket.

    SocketOptions::set_send_subscribe_commands

    fn SocketOptions::set_send_subscribe_commands(self : SocketOptions, enabled : Bool) -> Unit

    Configure whether SUB/XSUB also emit ZMTP 3.1 SUBSCRIBE/CANCEL commands.

    SocketOptions::set_sndhwm

    fn SocketOptions::set_sndhwm(self : SocketOptions, hwm : Int) -> Unit

    Set the outbound High-Water Mark (sndhwm) on SocketOptions.

    SocketOptions::set_sndtimeo

    fn SocketOptions::set_sndtimeo(self : SocketOptions, timeout_ms : Int) -> Unit

    Set default send timeout in milliseconds (-1 = infinite, 0 = immediate).

    SocketOptions::set_xpub_verbose

    fn SocketOptions::set_xpub_verbose(self : SocketOptions, verbose : Bool) -> Unit

    Enable or disable ZMQ_XPUB_VERBOSE behavior on an XPUB socket.

    SocketOptions::set_zap_engine

    fn SocketOptions::set_zap_engine(self : SocketOptions, engine : ZapPolicyEngine?, domain? : String) -> Unit

    Attach an RFC 27 ZapPolicyEngine and domain for server-side IP/credential enforcement and User-Id / metadata injection on incoming connections.

    SocketType

    pub(all) enum SocketType {
    Req
    Rep
    Dealer
    Router
    Pub
    Sub
    XPub
    XSub
    Push
    Pull
    Pair
    } derive(Eq,
    Debug
    )

    Standard ZeroMQ socket types defined across RFC 28, 29, 30, and 31.

    SocketType::equal

    fn SocketType::equal(SocketType, SocketType) -> Bool
    automatically derived

    SocketType::from_zmtp_name

    fn SocketType::from_zmtp_name(name : String) -> SocketType?

    Parse a ZMTP Socket-Type name into a SocketType.

    SocketType::is_compatible_with

    fn SocketType::is_compatible_with(self : SocketType, peer : SocketType) -> Bool

    Check whether two socket types are valid peers according to ZeroMQ RFC 28/29/30/31.

    SocketType::not_equal

    fn SocketType::not_equal(x : SocketType, y : SocketType) -> Bool
    automatically derived

    SocketType::to_repr

    automatically derived

    SocketType::to_zmtp_name

    fn SocketType::to_zmtp_name(self : SocketType) -> String

    Return the canonical ZMTP 3.1 Socket-Type string for this socket type.

    SubscriptionTrie

    pub struct SubscriptionTrie {
    // private fields
    }

    Multi-pipe prefix subscription trie matching official libzmq mtrie_t semantics.

    Tracks per-pipe reference counts on each byte-prefix topic so that:
    • add returns true only when the first subscriber registers for topic (0 -> 1).
    • rm returns true only when the last subscriber unregisters from topic (1 -> 0).
    • match_pipes resolves all matching subscriber pipe_ids in O(|payload|) prefix walk.

    SubscriptionTrie::add

    fn SubscriptionTrie::add(self : SubscriptionTrie, topic : Bytes, pipe_id : Int) -> Bool

    Register a subscription to topic for pipe_id.

    Returns true if topic transitioned from 0 subscribers to 1 subscriber (indicating an XPUB / SUB socket should forward \x01<topic> upstream).

    SubscriptionTrie::all_topics

    fn SubscriptionTrie::all_topics(self : SubscriptionTrie) -> Array[Bytes]

    List all currently active subscription topics in this trie.

    SubscriptionTrie::clear

    fn SubscriptionTrie::clear(self : SubscriptionTrie) -> Unit

    Clear all subscriptions from the trie.

    SubscriptionTrie::match_pipes

    fn SubscriptionTrie::match_pipes(self : SubscriptionTrie, payload : Bytes) -> Array[Int]

    Return all unique pipe_ids whose subscribed prefix matches payload.

    Runs in O(|payload|) trie depth steps without scanning unrelated topic branches.

    SubscriptionTrie::matches_any

    fn SubscriptionTrie::matches_any(self : SubscriptionTrie, payload : Bytes) -> Bool

    Fast boolean check returning true if at least one registered prefix matches payload.

    SubscriptionTrie::new

    Create a new empty SubscriptionTrie.

    SubscriptionTrie::remove_pipe

    fn SubscriptionTrie::remove_pipe(self : SubscriptionTrie, pipe_id : Int) -> Array[Bytes]

    Remove all subscriptions owned by pipe_id (used when a peer disconnects). Returns an array of all topics whose total subscriber count dropped to 0.

    SubscriptionTrie::rm

    fn SubscriptionTrie::rm(self : SubscriptionTrie, topic : Bytes, pipe_id : Int) -> Bool

    Unregister one subscription to topic for pipe_id.

    Returns true if topic transitioned from 1 subscriber down to 0 subscribers (indicating an XPUB / SUB socket should forward \x00<topic> upstream).

    SubscriptionTrie::subscriber_count

    fn SubscriptionTrie::subscriber_count(self : SubscriptionTrie, topic : Bytes) -> Int

    Return the number of distinct pipes currently subscribed to exact topic.

    SubscriptionTrie::topics_for_pipe

    fn SubscriptionTrie::topics_for_pipe(self : SubscriptionTrie, pipe_id : Int) -> Array[Bytes]

    List all active topics subscribed by a specific pipe_id.

    SubscriptionTrie::total_registrations

    fn SubscriptionTrie::total_registrations(self : SubscriptionTrie) -> Int

    Total active subscription registrations across all pipes and topics.

    SubscriptionTrie::unique_topic_count

    fn SubscriptionTrie::unique_topic_count(self : SubscriptionTrie) -> Int

    Number of distinct topics that currently have at least one subscribed pipe.

    TransportHub

    pub struct TransportHub {
    socket_type : SocketType
    options : SocketOptions
    pipes : Array[Pipe]
    tasks : Array[
    Task
    [Unit]]
    next_pipe_id : Int
    rr_index : Int
    fq_index : Int
    inbound_notify :
    Queue
    [Int]
    pipe_ready_notify :
    Queue
    [Int]
    sub_events :
    Queue
    [Message]
    pending_sub_events : Int
    local_subscriptions : Array[Bytes]
    pub_trie : SubscriptionTrie
    sub_trie : SubscriptionTrie
    conflate_buf : ConflateBuffer?
    reconnect_attempts : Int
    handshake_failures : Int
    last_auth_error : String?
    messages_sent : Int64
    messages_received : Int64
    bytes_sent : Int64
    bytes_received : Int64
    closed : Bool
    }

    Multi-connection transport hub managing TCP listeners (bind), outbound connectors (connect) with exponential-backoff reconnection, and active Pipes.

    TransportHub::active_peer_count

    fn TransportHub::active_peer_count(self : TransportHub) -> Int

    Number of currently active (handshake-completed) peer connections.

    TransportHub::active_peer_ids

    fn TransportHub::active_peer_ids(self : TransportHub) -> Array[Int]

    Array of all currently active peer pipe IDs.

    TransportHub::bind

    async fn TransportHub::bind(self : TransportHub, group :
    TaskGroup
    , endpoint : String) -> String raise ZmqError

    Bind a local "tcp://host:port" endpoint and start accepting peer connections in the background within group. Returns the resolved bound endpoint (e.g. "tcp://127.0.0.1:54321" when bound to port 0).

    TransportHub::bind_inproc

    fn TransportHub::bind_inproc(self : TransportHub, group :
    TaskGroup
    , endpoint : String, registry? : InprocRegistry) -> String raise ZmqError

    Bind an "inproc://<name>" endpoint inside registry and accept in-memory peer sessions.

    TransportHub::bytes_received

    fn TransportHub::bytes_received(self : TransportHub) -> Int64

    Total payload bytes received through this transport hub.

    TransportHub::bytes_sent

    fn TransportHub::bytes_sent(self : TransportHub) -> Int64

    Total payload bytes sent through this transport hub.

    TransportHub::can_recv

    fn TransportHub::can_recv(self : TransportHub) -> Bool

    Check whether any connected pipe has an inbound message ready to read without blocking.

    TransportHub::can_send

    fn TransportHub::can_send(self : TransportHub) -> Bool

    Check whether any connected pipe is capable of accepting an outbound message without blocking.

    TransportHub::close

    fn TransportHub::close(self : TransportHub) -> Unit

    Close all listeners, active connections, pipes, and background tasks.

    TransportHub::connect

    fn TransportHub::connect(self : TransportHub, group :
    TaskGroup
    , endpoint : String) -> Unit raise ZmqError

    Connect to a remote "tcp://host:port" endpoint in the background within group. Automatically reconnects on disconnect or failure using configurable initial interval (reconnect_ivl_ms) and exponential backoff (reconnect_ivl_max_ms).

    TransportHub::connect_inproc

    fn TransportHub::connect_inproc(self : TransportHub, group :
    TaskGroup
    , endpoint : String, registry? : InprocRegistry) -> Unit raise ZmqError

    Connect to an "inproc://<name>" endpoint inside registry. Supports connecting before the peer calls bind("inproc://<name>") as well as automatic reconnection if the bound listener restarts.

    TransportHub::matches_local_subscription

    fn TransportHub::matches_local_subscription(self : TransportHub, msg : Message) -> Bool

    Check whether msg matches any local subscription prefix on a SUB socket using O(|topic|) prefix lookup in sub_trie.

    TransportHub::messages_received

    fn TransportHub::messages_received(self : TransportHub) -> Int64

    Total number of data messages received through this transport hub.

    TransportHub::messages_sent

    fn TransportHub::messages_sent(self : TransportHub) -> Int64

    Total number of data messages sent through this transport hub.

    TransportHub::new

    fn TransportHub::new(socket_type : SocketType, options? : SocketOptions) -> TransportHub

    Create a new TransportHub for the given SocketType and SocketOptions.

    TransportHub::reconnect_count

    fn TransportHub::reconnect_count(self : TransportHub) -> Int

    Total number of automatic reconnection attempts made by connect endpoints.

    TransportHub::record_recv

    fn TransportHub::record_recv(self : TransportHub, msg : Message) -> Unit

    Record a received message and update metric counters.

    TransportHub::record_send

    fn TransportHub::record_send(self : TransportHub, msg : Message) -> Unit

    Record a sent message and update metric counters.

    TransportHub::recv_fair_queue

    async fn TransportHub::recv_fair_queue(self : TransportHub) -> (Pipe, Message) raise ZmqError

    Receive a message using Fair-Queueing across all active peer pipes. Returns both the source Pipe and the Message.

    TransportHub::send_round_robin

    async fn TransportHub::send_round_robin(self : TransportHub, msg : Message, policy? : HwmPolicy) -> Unit raise ZmqError

    Send a message using Round-Robin selection across all active peer pipes. Used by REQ, DEALER, PUSH, and PAIR.

    TransportHub::wait_for_writable_pipe

    async fn TransportHub::wait_for_writable_pipe(self : TransportHub) -> Unit raise ZmqError

    Wait until at least one active peer pipe is connected and can accept outbound messages.

    WireReader

    pub struct WireReader {
    data : Bytes
    pos : Int
    }

    Zero-copy binary deserialization cursor over an immutable Bytes buffer.

    WireReader::is_eof

    fn WireReader::is_eof(self : WireReader) -> Bool

    Whether the reader has consumed all bytes in the buffer.

    WireReader::new

    fn WireReader::new(data : Bytes) -> WireReader

    Create a new WireReader positioned at offset 0 of data.

    WireReader::position

    fn WireReader::position(self : WireReader) -> Int

    Current byte offset of the reader cursor.

    WireReader::read_chunk

    fn WireReader::read_chunk(self : WireReader) -> Bytes raise ZmqError

    Read a length-prefixed binary chunk (4-byte big-endian length + raw bytes).

    WireReader::read_i32_be

    fn WireReader::read_i32_be(self : WireReader) -> Int raise ZmqError

    Read a signed 32-bit integer in big-endian byte order.

    WireReader::read_i32_le

    fn WireReader::read_i32_le(self : WireReader) -> Int raise ZmqError

    Read a signed 32-bit integer in little-endian byte order.

    WireReader::read_i64_be

    fn WireReader::read_i64_be(self : WireReader) -> Int64 raise ZmqError

    Read a signed 64-bit integer in big-endian byte order.

    WireReader::read_i64_le

    fn WireReader::read_i64_le(self : WireReader) -> Int64 raise ZmqError

    Read a signed 64-bit integer in little-endian byte order.

    WireReader::read_long_string

    fn WireReader::read_long_string(self : WireReader) -> String raise ZmqError

    Read a ZMTP long string (4-byte big-endian length + UTF-8 string bytes).

    WireReader::read_raw_bytes

    fn WireReader::read_raw_bytes(self : WireReader, len : Int) -> Bytes raise ZmqError

    Read an exact slice of len bytes from the current position.

    WireReader::read_short_string

    fn WireReader::read_short_string(self : WireReader) -> String raise ZmqError

    Read a ZMTP short string (1-byte length + UTF-8 string bytes).

    WireReader::read_string_map

    fn WireReader::read_string_map(self : WireReader) -> Map[String, String] raise ZmqError

    Read a string dictionary encoded by WireWriter::write_string_map.

    WireReader::read_u16_be

    fn WireReader::read_u16_be(self : WireReader) -> Int raise ZmqError

    Read an unsigned 16-bit integer in big-endian byte order (0..65535).

    WireReader::read_u16_le

    fn WireReader::read_u16_le(self : WireReader) -> Int raise ZmqError

    Read an unsigned 16-bit integer in little-endian byte order (0..65535).

    WireReader::read_u8

    fn WireReader::read_u8(self : WireReader) -> Int raise ZmqError

    Read an unsigned 8-bit integer (0..255).

    WireReader::remaining

    fn WireReader::remaining(self : WireReader) -> Int

    Number of unread bytes remaining in the buffer.

    WireWriter

    pub struct WireWriter {
    buf : Array[Byte]
    }

    Binary serialization buffer supporting network byte order (big-endian), little-endian integers, ZMTP short strings (OCTET length), ZMTP long strings (4-OCTET length), length-prefixed byte chunks, and key-value property tables.

    WireWriter::clear

    fn WireWriter::clear(self : WireWriter) -> Unit

    Reset and clear the internal buffer of this WireWriter.

    WireWriter::length

    fn WireWriter::length(self : WireWriter) -> Int

    Current byte length written to this WireWriter.

    WireWriter::new

    fn WireWriter::new(capacity? : Int) -> WireWriter

    Create a new WireWriter with optional pre-allocated byte capacity.

    WireWriter::to_bytes

    fn WireWriter::to_bytes(self : WireWriter) -> Bytes

    Finalize and return an immutable Bytes snapshot of the written payload.

    WireWriter::to_message

    fn WireWriter::to_message(self : WireWriter) -> Message

    Finalize and wrap the written payload as a single-frame Message.

    WireWriter::write_chunk

    fn WireWriter::write_chunk(self : WireWriter, chunk : Bytes) -> Unit

    Write a length-prefixed binary chunk (4-byte big-endian length + raw bytes).

    WireWriter::write_i32_be

    fn WireWriter::write_i32_be(self : WireWriter, val : Int) -> Unit

    Write a 32-bit integer in big-endian (network) byte order.

    WireWriter::write_i32_le

    fn WireWriter::write_i32_le(self : WireWriter, val : Int) -> Unit

    Write a 32-bit integer in little-endian byte order.

    WireWriter::write_i64_be

    fn WireWriter::write_i64_be(self : WireWriter, val : Int64) -> Unit

    Write a 64-bit integer in big-endian (network) byte order.

    WireWriter::write_i64_le

    fn WireWriter::write_i64_le(self : WireWriter, val : Int64) -> Unit

    Write a 64-bit integer in little-endian byte order.

    WireWriter::write_long_string

    fn WireWriter::write_long_string(self : WireWriter, s : String) -> Unit

    Write a ZMTP long string (4-byte big-endian length + UTF-8 string bytes).

    WireWriter::write_raw_bytes

    fn WireWriter::write_raw_bytes(self : WireWriter, bytes : Bytes) -> Unit

    Append raw bytes without any length prefix.

    WireWriter::write_short_string

    fn WireWriter::write_short_string(self : WireWriter, s : String) -> Unit raise ZmqError

    Write a ZMTP short string (1-byte length + up to 255 UTF-8 bytes). Raises ProtocolError if UTF-8 byte length exceeds 255 bytes.

    WireWriter::write_string_map

    fn WireWriter::write_string_map(self : WireWriter, entries : Map[String, String]) -> Unit raise ZmqError

    Write a key-value dictionary in ZMTP metadata format (1-byte key len + key + 4-byte big-endian val len + val), preceded by a 4-byte entry count.

    WireWriter::write_u16_be

    fn WireWriter::write_u16_be(self : WireWriter, val : Int) -> Unit

    Write a 16-bit integer in big-endian (network) byte order.

    WireWriter::write_u16_le

    fn WireWriter::write_u16_le(self : WireWriter, val : Int) -> Unit

    Write a 16-bit integer in little-endian byte order.

    WireWriter::write_u8

    fn WireWriter::write_u8(self : WireWriter, val : Int) -> Unit

    Write a single unsigned 8-bit integer (0..255).

    ZActor

    pub struct ZActor {
    id : Int
    pipe : Socket
    stopped : Bool
    // private fields
    }

    CZMQ-style ZActor wrapping a background coroutine connected to its owner through a dedicated inproc:// PAIR control pipe.

    ZActor::recv

    async fn ZActor::recv(self : ZActor) -> Message raise ZmqError

    Receive the next Message emitted by the running actor.

    ZActor::recv_string

    async fn ZActor::recv_string(self : ZActor) -> String raise ZmqError

    Receive the next single-frame String emitted by the running actor.

    ZActor::send

    async fn ZActor::send(self : ZActor, msg : Message) -> Unit raise ZmqError

    Send a control or data Message to the running actor.

    ZActor::send_string

    async fn ZActor::send_string(self : ZActor, cmd : String) -> Unit raise ZmqError

    Send a single-frame command string to the running actor.

    ZActor::socket

    fn ZActor::socket(self : ZActor) -> Socket

    Return the parent PAIR control Socket of this ZActor (compatible with Poller & ZLoop).

    ZActor::spawn

    async fn ZActor::spawn(group :
    TaskGroup
    , ctx : Context, actor_fn : async (Socket) -> Unit) -> ZActor raise ZmqError

    Spawn a new ZActor inside group and ctx.

    Automatically binds an exclusive inproc://zactor-<id> PAIR endpoint, connects the actor body's pipe, waits for the initial readiness signal from the actor coroutine, and returns the parent ZActor handle.

    ZActor::stop

    async fn ZActor::stop(self : ZActor) -> Unit

    Gracefully request actor termination by sending "$TERM", waiting briefly for the actor coroutine to exit, and closing the parent pipe.

    ZConfig

    pub struct ZConfig {
    name : String
    value : String
    children : Array[ZConfig]
    } derive(Eq,
    Debug
    )

    Hierarchical configuration node implementing ZeroMQ RFC 4 (ZPL).

    ZConfig::equal

    fn ZConfig::equal(ZConfig, ZConfig) -> Bool
    automatically derived

    ZConfig::get

    fn ZConfig::get(self : ZConfig, path : String, default? : String) -> String

    Resolve a string value at path, returning default if the path does not exist.

    ZConfig::get_bool

    fn ZConfig::get_bool(self : ZConfig, path : String, default? : Bool) -> Bool

    Resolve a boolean value ("1", "true", "yes", "on") at path.

    ZConfig::get_int

    fn ZConfig::get_int(self : ZConfig, path : String, default? : Int) -> Int

    Resolve an Int32 value at path, returning default if missing or invalid.

    ZConfig::locate

    fn ZConfig::locate(self : ZConfig, path : String) -> ZConfig?

    Locate a descendant ZConfig node by slash-separated path (e.g. "context/iothreads").

    ZConfig::new

    fn ZConfig::new(name : String, value? : String) -> ZConfig

    Create a new ZConfig node with name and optional string value.

    ZConfig::not_equal

    fn ZConfig::not_equal(x : ZConfig, y : ZConfig) -> Bool
    automatically derived

    ZConfig::parse

    fn ZConfig::parse(text : String) -> ZConfig raise ZmqError

    Parse a ZeroMQ RFC 4 ZPL configuration document into a ZConfig tree.

    Indentation uses 4 spaces per hierarchy level (level = leading_spaces / 4). Comments start with # outside quotes, and properties take the form name or name = value.

    ZConfig::put

    fn ZConfig::put(self : ZConfig, path : String, value : String) -> Unit

    Insert or update the value at slash-separated path, creating intermediate section nodes as needed.

    ZConfig::root

    fn ZConfig::root() -> ZConfig

    Create an unnamed root ZConfig container node.

    ZConfig::to_repr

    automatically derived

    ZConfig::to_zpl

    fn ZConfig::to_zpl(self : ZConfig) -> String

    Serialize this ZConfig hierarchy into canonical RFC 4 ZPL text.

    ZLoop

    pub struct ZLoop {
    tick_count : Int64
    halted : Bool
    // private fields
    }

    CZMQ-style ZLoop reactor multiplexing readable Socket handlers with millisecond-precision one-shot and repeating timers.

    Returning false from any timer or reader callback cleanly halts the reactor loop.

    ZLoop::add_reader

    fn ZLoop::add_reader(self : ZLoop, socket : Socket, handler : async (Socket) -> Bool) -> Unit

    Register an asynchronous POLLIN reader callback for socket. If handler(socket) returns false, the ZLoop halts cleanly.

    ZLoop::add_timer

    fn ZLoop::add_timer(self : ZLoop, delay_ms : Int, times? : Int, now_ms? : Int64, handler : (Int) -> Bool) -> Int

    Register a timer firing every delay_ms milliseconds.
    • times = 0: repeats indefinitely until cancelled or reactor stops.
    • times > 0: fires at most times times and auto-removes itself. If handler(timer_id) returns false, the ZLoop halts cleanly.

    ZLoop::cancel_timer

    fn ZLoop::cancel_timer(self : ZLoop, timer_id : Int) -> Bool

    Cancel a registered timer by timer_id. Returns true if removed.

    ZLoop::new

    fn ZLoop::new() -> ZLoop

    Create a new ZLoop event reactor.

    ZLoop::remove_reader

    fn ZLoop::remove_reader(self : ZLoop, socket : Socket) -> Bool

    Remove a previously registered socket reader from this ZLoop.

    ZLoop::run

    async fn ZLoop::run(self : ZLoop) -> Unit

    Run the ZLoop reactor until halted by stop(), a callback returning false, or until both timers and readers become empty.

    ZLoop::stop

    fn ZLoop::stop(self : ZLoop) -> Unit

    Signal this ZLoop to stop at the end of the current reactor iteration.

    ZapAuditEntry

    pub struct ZapAuditEntry {
    timestamp_ms : Int64
    domain : String
    address : String
    mechanism : String
    principal : String
    status_code : ZapStatusCode
    reason : String
    } derive(Eq,
    Debug
    )

    Structured audit log record emitted for each evaluated ZAP request.

    ZapAuditEntry::equal

    automatically derived

    ZapAuditEntry::not_equal

    fn ZapAuditEntry::not_equal(x : ZapAuditEntry, y : ZapAuditEntry) -> Bool
    automatically derived

    ZapAuditEntry::to_repr

    automatically derived

    ZapPolicyEngine

    pub struct ZapPolicyEngine {
    allowlist : Array[Ipv4Cidr]
    blocklist : Array[Ipv4Cidr]
    curve_allow_any : Bool
    max_audit_entries : Int
    audit_log : Array[ZapAuditEntry]
    // private fields
    }

    Configurable RFC 27 ZAP policy engine supporting IPv4 CIDR allowlists/blocklists, domain-scoped PLAIN user accounts with custom ZMTP metadata injection, CURVE Z85 public-key whitelists, and a bounded authentication audit log.

    ZapPolicyEngine::allow_ip

    fn ZapPolicyEngine::allow_ip(self : ZapPolicyEngine, cidr : String) -> Unit raise ZmqError

    Add an IPv4 address or CIDR subnet to the allowlist (matched before credentials).

    ZapPolicyEngine::as_plain_authenticator

    fn ZapPolicyEngine::as_plain_authenticator(self : ZapPolicyEngine, domain? : String, address? : String) -> ((String, String) -> Bool)

    Convert this ZapPolicyEngine into a Socket::set_plain_server authenticator closure scoped to domain and optional peer address.

    ZapPolicyEngine::authorize_curve_z85

    fn ZapPolicyEngine::authorize_curve_z85(self : ZapPolicyEngine, label : String, z85_public_key : String) -> Unit raise ZmqError

    Authorize a 40-character Z85-encoded CURVE 32-byte client public key and bind it to a principal label.

    ZapPolicyEngine::block_ip

    fn ZapPolicyEngine::block_ip(self : ZapPolicyEngine, cidr : String) -> Unit raise ZmqError

    Add an IPv4 address or CIDR subnet to the blocklist.

    ZapPolicyEngine::evaluate

    fn ZapPolicyEngine::evaluate(self : ZapPolicyEngine, req : ZapRequest, now_ms? : Int64) -> ZapReply

    Evaluate a ZapRequest against IP policies and mechanism credentials, returning an RFC 27 ZapReply and appending an entry to audit_log.

    ZapPolicyEngine::new

    fn ZapPolicyEngine::new(max_audit_entries? : Int) -> ZapPolicyEngine

    Create a new ZapPolicyEngine with optional max_audit_entries ring capacity.

    ZapPolicyEngine::remove_plain_user

    fn ZapPolicyEngine::remove_plain_user(self : ZapPolicyEngine, username : String, domain? : String) -> Bool

    Remove a PLAIN user from domain. Returns true if removed.

    ZapPolicyEngine::set_curve_allow_any

    fn ZapPolicyEngine::set_curve_allow_any(self : ZapPolicyEngine, allow_any : Bool) -> Unit

    Configure whether any syntactically valid 32-byte CURVE key is permitted (CURVE_ALLOW_ANY).

    ZapPolicyEngine::spawn_inproc_server

    async fn ZapPolicyEngine::spawn_inproc_server(self : ZapPolicyEngine, group :
    TaskGroup
    , ctx : Context, endpoint? : String) -> Socket raise ZmqError

    Spawn an asynchronous RFC 27 ZAP REP server inside ctx bound to endpoint (defaults to "inproc://zeromq.zap.01"), returning the server Socket so the caller or ctx.term() can stop it cleanly.

    ZapPolicyEngine::upsert_plain_user

    fn ZapPolicyEngine::upsert_plain_user(self : ZapPolicyEngine, username : String, password : String, domain? : String, properties? : Array[(String, String)]) -> Unit

    Register or update a PLAIN user credential in domain ("*" matches all domains), optionally attaching custom ZMTP metadata properties returned on 200 OK.

    ZapReply

    pub struct ZapReply {
    version : String
    request_id : Bytes
    status_code : ZapStatusCode
    status_text : String
    user_id : String
    metadata : Bytes
    } derive(Eq,
    Debug
    )

    RFC 27 ZAP 1.0 authentication reply message structure (6 frames).

    ZapReply::equal

    fn ZapReply::equal(ZapReply, ZapReply) -> Bool
    automatically derived

    ZapReply::from_message

    fn ZapReply::from_message(msg : Message) -> ZapReply raise ZmqError

    Parse a 6-frame RFC 27 multipart Message into a ZapReply.

    ZapReply::is_authenticated

    fn ZapReply::is_authenticated(self : ZapReply) -> Bool

    Whether this ZapReply indicates successful authentication (status_code == Ok200).

    ZapReply::not_equal

    fn ZapReply::not_equal(x : ZapReply, y : ZapReply) -> Bool
    automatically derived

    ZapReply::ok

    fn ZapReply::ok(request_id : Bytes, user_id? : String, status_text? : String, metadata? : Bytes) -> ZapReply

    Construct a 200 OK ZapReply.

    ZapReply::reject

    fn ZapReply::reject(request_id : Bytes, status_code? : ZapStatusCode, status_text? : String) -> ZapReply

    Construct a non-200 failure ZapReply.

    ZapReply::to_message

    fn ZapReply::to_message(self : ZapReply) -> Message

    Serialize a ZapReply into an exact 6-frame RFC 27 multipart Message.

    ZapReply::to_repr

    automatically derived

    ZapRequest

    pub struct ZapRequest {
    version : String
    request_id : Bytes
    domain : String
    address : String
    identity : Bytes
    mechanism : String
    credentials : Array[Bytes]
    } derive(Eq,
    Debug
    )

    RFC 27 ZAP 1.0 authentication request message structure.

    ZapRequest::equal

    fn ZapRequest::equal(ZapRequest, ZapRequest) -> Bool
    automatically derived

    ZapRequest::from_message

    fn ZapRequest::from_message(msg : Message) -> ZapRequest raise ZmqError

    Parse an RFC 27 multipart Message into a ZapRequest.

    ZapRequest::new_curve

    fn ZapRequest::new_curve(request_id : Bytes, address : String, client_public_key : Bytes, domain? : String, identity? : Bytes) -> ZapRequest

    Construct a ZapRequest for the CURVE mechanism carrying a 32-byte client public key.

    ZapRequest::new_null

    fn ZapRequest::new_null(request_id : Bytes, address : String, domain? : String, identity? : Bytes) -> ZapRequest

    Construct a ZapRequest for the NULL mechanism (IP/domain check only).

    ZapRequest::new_plain

    fn ZapRequest::new_plain(request_id : Bytes, address : String, username : String, password : String, domain? : String, identity? : Bytes) -> ZapRequest

    Construct a ZapRequest for the PLAIN mechanism carrying [username, password].

    ZapRequest::not_equal

    fn ZapRequest::not_equal(x : ZapRequest, y : ZapRequest) -> Bool
    automatically derived

    ZapRequest::to_message

    fn ZapRequest::to_message(self : ZapRequest) -> Message

    Serialize a ZapRequest into an RFC 27 multipart Message (6 + N frames).

    ZapRequest::to_repr

    automatically derived

    ZapStatusCode

    pub(all) enum ZapStatusCode {
    Ok200
    TemporaryError300
    Rejected400
    InternalError500
    } derive(Eq,
    Debug
    )

    Status codes returned in frame 2 of a ZAP 1.0 reply (RFC 27 Section 2.2).

    ZapStatusCode::equal

    automatically derived

    ZapStatusCode::from_code_string

    fn ZapStatusCode::from_code_string(code : String) -> ZapStatusCode?

    Parse a 3-character RFC 27 status string into ZapStatusCode.

    ZapStatusCode::not_equal

    fn ZapStatusCode::not_equal(x : ZapStatusCode, y : ZapStatusCode) -> Bool
    automatically derived

    ZapStatusCode::to_code_string

    fn ZapStatusCode::to_code_string(self : ZapStatusCode) -> String

    Convert a ZapStatusCode to its canonical 3-character RFC 27 status string.

    ZapStatusCode::to_repr

    automatically derived

    ZmtpCommand

    pub(all) enum ZmtpCommand {
    Ready(Metadata)
    ErrorCmd(String)
    Ping(Int, Bytes)
    Pong(Bytes)
    Subscribe(Bytes)
    Cancel(Bytes)
    Hello(String, String)
    Welcome
    Initiate(Metadata)
    Unknown(String, Bytes)
    } derive(Eq,
    Debug
    )

    ZMTP 3.1 and PLAIN (RFC 24) command frames.

    ZmtpCommand::decode_body

    fn ZmtpCommand::decode_body(body : Bytes) -> ZmtpCommand raise ZmqError

    Decode a command frame payload into a typed ZmtpCommand.

    ZmtpCommand::encode_frame

    fn ZmtpCommand::encode_frame(self : ZmtpCommand) -> Bytes

    Encode a ZmtpCommand into a complete ZMTP command wire frame.

    ZmtpCommand::equal

    fn ZmtpCommand::equal(ZmtpCommand, ZmtpCommand) -> Bool
    automatically derived

    ZmtpCommand::not_equal

    fn ZmtpCommand::not_equal(x : ZmtpCommand, y : ZmtpCommand) -> Bool
    automatically derived

    ZmtpCommand::to_repr

    automatically derived

    DEFAULT_HWM

    let DEFAULT_HWM : Int

    Default send/receive high-water mark (1000 messages, matching libzmq default).

    DEFAULT_MAX_FRAME_SIZE

    let DEFAULT_MAX_FRAME_SIZE : Int

    Default maximum allowed single frame payload size (64 MiB).

    FLAG_COMMAND

    let FLAG_COMMAND : Int

    FLAG_LONG

    let FLAG_LONG : Int

    FLAG_MORE

    let FLAG_MORE : Int

    Frame flag bits defined by ZMTP 3.1 (RFC 23 Section 3.1).

    FLAG_RESERVED_MASK

    let FLAG_RESERVED_MASK : Int

    Bits 3..7 of the frame flags octet are reserved and MUST be zero.

    MDP_CLIENT_HEADER

    let MDP_CLIENT_HEADER : String

    Canonical Majordomo Client Protocol v0.2 header (ZeroMQ RFC 7).

    MDP_WORKER_HEADER

    let MDP_WORKER_HEADER : String

    Canonical Majordomo Worker Protocol v0.2 header (ZeroMQ RFC 7).

    POLLERR

    let POLLERR : Int

    Event flag indicating that an error condition occurred on the socket.

    POLLIN

    let POLLIN : Int

    Event flag indicating that a message is ready to be received without blocking.

    POLLOUT

    let POLLOUT : Int

    Event flag indicating that a message can be sent without blocking.

    ZACTOR_TERM_CMD

    let ZACTOR_TERM_CMD : String

    Canonical termination command string used by CZMQ zactor_t.

    ZAP_DEFAULT_ENDPOINT

    let ZAP_DEFAULT_ENDPOINT : String

    Standard in-process endpoint URI used by ZeroMQ ZAP authenticators (RFC 27).

    ZAP_VERSION

    let ZAP_VERSION : String

    Canonical ZAP protocol version string defined by ZeroMQ RFC 27.

    apply_zconfig_to_socket_options

    fn apply_zconfig_to_socket_options(cfg : ZConfig, opts : SocketOptions) -> Unit

    Apply a ZConfig subtree (socket/... or root properties) onto a SocketOptions instance.

    ascii_bytes_to_string

    fn ascii_bytes_to_string(b : Bytes) -> String

    Convert raw ASCII/Latin-1 bytes into a String.

    ascii_to_upper

    fn ascii_to_upper(s : String) -> String

    Convert an ASCII string to uppercase.

    attach_rep_envelope

    fn attach_rep_envelope(envelope : Array[Bytes], reply : Message) -> Message

    Re-attach a saved REP routing envelope stack (including the empty delimiter) to an application reply Message.

    bytes_starts_with

    fn bytes_starts_with(haystack : Bytes, prefix : Bytes) -> Bool

    Check whether haystack starts with prefix.

    bytes_to_hex

    fn bytes_to_hex(data : Bytes, uppercase? : Bool) -> String

    Encode binary data as a hexadecimal string (lowercase by default).

    concat_bytes

    fn concat_bytes(parts : Array[Bytes]) -> Bytes

    Concatenate an array of Bytes into a single Bytes.

    constant_time_bytes_eq

    fn constant_time_bytes_eq(a : Bytes, b : Bytes) -> Bool

    Constant-time byte comparison to prevent timing side-channels when verifying credentials, tokens, or message authentication tags.

    create_inproc_stream_pair

    fn create_inproc_stream_pair(queue_capacity? : Int) -> (InprocStream, InprocStream)

    Create a connected pair (client_stream, server_stream) of in-memory full-duplex streams.

    decode_group_topic_header

    fn decode_group_topic_header(header : Bytes) -> String raise ZmqError

    Decode the exact-match group header from frame 0 of a Radio / Dish packet.

    decode_mdp_client_reply

    fn decode_mdp_client_reply(msg : Message) -> (String, Array[Bytes]) raise ZmqError

    Decode an MDPC02 reply received on a DEALER client socket ([b"", "MDPC02", service, ...body]), returning (service_name, reply_frames).

    decode_plain_hello

    fn decode_plain_hello(body : Bytes) -> (String, String) raise ZmqError

    Decode a PLAIN HELLO command body into (username, password) (RFC 24 Section 3.1).

    decode_plain_initiate

    fn decode_plain_initiate(body : Bytes) -> Metadata raise ZmqError

    Decode a PLAIN INITIATE command body into Metadata.

    decode_subscription_frame

    fn decode_subscription_frame(msg : Message) -> (Bool, Bytes)?

    Parse a ZMTP 3.0 subscription data frame (\x01topic or \x00topic). Returns Some((true, topic)) for subscribe, Some((false, topic)) for cancel, or None if the message is not a subscription frame.

    decode_zap_metadata_blob

    fn decode_zap_metadata_blob(blob : Bytes) -> Array[(String, String)] raise ZmqError

    Decode an RFC 23/27 binary metadata blob from a ZapReply into (key, value) string pairs.

    default_routing_id

    fn default_routing_id(pipe_id : Int) -> Bytes

    Generate a deterministic 5-byte routing identity (\x00 + 4-byte big-endian id) when a peer does not supply an explicit Identity property in its handshake metadata.

    dissect_zmtp_wire

    fn dissect_zmtp_wire(stream : Bytes, expect_greeting? : Bool) -> Array[DissectedPacket]

    Dissect a raw ZMTP 3.1 byte stream (optionally starting with a 64-byte Greeting) into an ordered array of DissectedPacket descriptors without raising on malformed tails.

    encode_group_topic_header

    fn encode_group_topic_header(group_name : String) -> Bytes raise ZmqError

    Build the exact-match subscription frame header [b'G', b'R', len:u8, ...group] used by Radio / Dish so group "alerts" never prefix-matches "alerts.eu".

    encode_mdp_client_request

    fn encode_mdp_client_request(service : String, body : Array[Bytes]) -> Message raise ZmqError

    Encode an MDPC02 client request addressed to service ([b"", "MDPC02", service, ...body] when sent over DEALER to a ROUTER Majordomo broker).

    encode_mdp_worker_control

    fn encode_mdp_worker_control(cmd : MdpWorkerCommand) -> Message

    Encode an MDPW02 HEARTBEAT or DISCONNECT control packet.

    encode_mdp_worker_ready

    fn encode_mdp_worker_ready(service : String) -> Message raise ZmqError

    Encode an MDPW02 worker READY packet ([b"", "MDPW02", 0x01, service]).

    encode_mdp_worker_reply

    fn encode_mdp_worker_reply(client_id : Bytes, body : Array[Bytes]) -> Message

    Encode an MDPW02 worker REPLY packet ([b"", "MDPW02", 0x03, client_id, b"", ...body]).

    encode_plain_hello

    fn encode_plain_hello(username : String, password : String) -> Bytes

    Encode a PLAIN HELLO command body (RFC 24 Section 3.1). Format: \x05HELLO + [username_len: 1B] + username + [password_len: 1B] + password

    encode_plain_initiate

    fn encode_plain_initiate(meta : Metadata) -> Bytes

    Encode a PLAIN INITIATE command frame carrying client metadata (RFC 24 Section 3.3).

    encode_plain_welcome

    fn encode_plain_welcome() -> Bytes

    Encode a PLAIN WELCOME command frame (RFC 24 Section 3.2).

    encode_subscription_frame

    fn encode_subscription_frame(subscribe : Bool, topic : Bytes) -> Message

    Encode a ZMTP 3.0 compatible subscription data message (\x01 + topic or \x00 + topic).

    encode_zap_metadata_blob

    fn encode_zap_metadata_blob(properties : Array[(String, String)]) -> Bytes raise ZmqError

    Encode a list of (key, value) properties into an RFC 23/27 ZAP metadata blob ([1-byte key_len][key][4-byte big-endian val_len][val]...).

    format_dissected_trace

    fn format_dissected_trace(packets : Array[DissectedPacket]) -> String

    Format an array of DissectedPacket records into a multi-line human-readable trace.

    format_wire_hexdump

    fn format_wire_hexdump(data : Bytes, max_bytes? : Int) -> String

    Format raw data into a side-by-side 16-byte hexadecimal + printable ASCII dump (matching hexdump -C / Wireshark packet inspection layout).

    hex_to_bytes

    fn hex_to_bytes(hex : String) -> Bytes raise ZmqError

    Decode a hexadecimal string (ignoring spaces, colons, and hyphens) into Bytes. Raises ProtocolError on odd nibble counts or invalid characters.

    is_plain_welcome

    fn is_plain_welcome(body : Bytes) -> Bool

    Check if a decoded command body is a PLAIN WELCOME command.

    is_valid_z85

    fn is_valid_z85(s : String) -> Bool

    Check whether a string is a valid canonical RFC 32 Z85 string.

    merge_zap_reply_metadata

    fn merge_zap_reply_metadata(meta : Metadata, reply : ZapReply) -> Metadata

    Enrich a peer's ZMTP Metadata with User-Id and custom properties returned inside an authenticated 200 OK ZapReply (RFC 27 Section 2.2).

    next_reconnect_delay_ms

    fn next_reconnect_delay_ms(current_ms : Int, initial_ms : Int, max_ms : Int) -> Int

    Compute the next reconnect delay in milliseconds using exponential backoff, capped at max_ms. If max_ms <= initial_ms, a fixed interval initial_ms is used.

    pack_multipart_blob

    fn pack_multipart_blob(msg : Message) -> Bytes

    Pack an arbitrary multipart Message into a single self-contained binary blob (4-byte magic "ZMSG" + 4-byte frame count + length-prefixed frames) suitable for persistence, caching (LVC), or tunneling over single-frame transports.

    parse_inproc_endpoint

    fn parse_inproc_endpoint(endpoint : String) -> String raise ZmqError

    Validate and extract <name> from an "inproc://<name>" endpoint string. Per ZeroMQ specification, inproc names must be non-empty, at most 255 bytes, and must not contain NUL (\x00) characters.

    parse_ipv4_u32

    fn parse_ipv4_u32(addr_str : String) -> Int64 raise ZmqError

    Parse a dotted-quad IPv4 address (e.g. "192.168.1.10") into an unsigned 32-bit value stored in Int64. Strips optional :port suffix if present.

    parse_tcp_endpoint

    fn parse_tcp_endpoint(endpoint : String, for_bind? : Bool) ->
    Addr
    raise ZmqError

    Parse a ZeroMQ "tcp://host:port" endpoint string into a @socket.Addr. Supports wildcard "*" (mapped to 0.0.0.0 on bind or 127.0.0.1 on connect) and "localhost" (mapped to 127.0.0.1).

    proxy

    async fn proxy(frontend : Socket, backend : Socket, capture? : Socket?) -> Unit

    High-level ZeroMQ proxy connecting frontend and backend sockets with optional capture. Forwards messages from frontend to backend and vice versa until one of the sockets is closed.

    proxy_steerable

    async fn proxy_steerable(frontend : Socket, backend : Socket, capture? : Socket?, control? : Socket?, stats? : ProxyStats) -> Unit

    RFC 43 Steerable Proxy supporting runtime control commands via control socket. Recognized control commands:
    • "PAUSE": Suspends message forwarding between frontend and backend.
    • "RESUME": Resumes message forwarding.
    • "TERMINATE": Gracefully terminates the proxy forwarder.

    run_lvc_proxy

    async fn run_lvc_proxy(frontend : Socket, backend : Socket, cache : LastValueCache, control? : Socket?, topic_delimiter? : Byte?) -> Int64 raise ZmqError

    Run an asynchronous Last-Value Caching (LVC) broker bridging an XSub frontend (connected to upstream publishers) and an XPub backend (serving downstream subscribers), controlled by an optional steerable control socket ("TERMINATE" stops the loop).

    slice_bytes

    fn slice_bytes(b : Bytes, start : Int, end : Int) -> Bytes

    Slice a sub-range [start, end) from Bytes.

    socket_options_to_zconfig

    fn socket_options_to_zconfig(opts : SocketOptions) -> ZConfig

    Export a SocketOptions configuration into a ZConfig RFC 4 tree under "socket".

    split_rep_envelope

    fn split_rep_envelope(raw : Message) -> (Array[Bytes], Message)?

    Split an inbound REP message into (envelope_stack, payload_message) at the first empty delimiter frame (b""), preserving any upstream routing frames prepended by ROUTER intermediaries (RFC 28 Section 2.3).

    string_to_ascii_bytes

    fn string_to_ascii_bytes(s : String) -> Bytes

    Convert an ASCII string into raw bytes (1 byte per character, low 8 bits).

    string_to_utf8_bytes

    fn string_to_utf8_bytes(s : String) -> Bytes

    Encode a MoonBit String (UTF-16 code units, including surrogate pairs) into canonical RFC 3629 UTF-8 Bytes. Pure ASCII strings encode byte-identically.

    unpack_multipart_blob

    fn unpack_multipart_blob(blob : Bytes) -> Message raise ZmqError

    Unpack a binary blob created by pack_multipart_blob back into a multipart Message.

    unwrap_req_envelope

    fn unwrap_req_envelope(raw : Message) -> Message?

    Strip the leading empty delimiter frame (b"") from an inbound REQ reply. Returns Some(payload_msg) if the first frame is empty and at least one payload frame follows, or None if malformed per RFC 28 Section 2.1.

    utf8_bytes_to_string

    fn utf8_bytes_to_string(b : Bytes) -> String

    Decode UTF-8 Bytes into a MoonBit String per RFC 3629, falling back to Latin-1 byte mapping on standalone invalid continuation bytes so arbitrary binary routing frames remain inspectable without raising.

    wrap_req_envelope

    fn wrap_req_envelope(msg : Message) -> Message

    Prepend an empty delimiter frame (b"") to an application Message as required by REQ when sending a request (RFC 28 Section 2.1).

    z85_decode

    fn z85_decode(encoded : String) -> Bytes raise ZmqError

    Decode a ZeroMQ RFC 32 Z85 string back into raw binary Bytes.

    Per RFC 32, the input string length MUST be divisible by 5 (len % 5 == 0), all characters must belong to the Z85 alphabet, and each 5-character group must decode to a 32-bit unsigned value (<= 0xFFFFFFFF).

    z85_decode_padded

    fn z85_decode_padded(encoded : String) -> Bytes raise ZmqError

    Decode a padded Z85 string produced by z85_encode_padded back into exact-length Bytes.

    z85_encode

    fn z85_encode(data : Bytes) -> String raise ZmqError

    Encode raw binary data into a ZeroMQ RFC 32 Z85 string.

    Per RFC 32, the input byte length MUST be divisible by 4 (len % 4 == 0). Every 4-byte big-endian binary frame is encoded into 5 printable ASCII characters. Raises ProtocolError if data.length() % 4 != 0.

    z85_encode_padded

    fn z85_encode_padded(data : Bytes) -> String raise ZmqError

    Encode arbitrary-length binary data using Z85 with a 1-character padding header.

    Prepends the PKCS-style pad count (0..3 encoded as '0'..'3') and pads data with trailing zero bytes to a multiple of 4 before Z85 encoding.

    zap_authenticate_over_socket

    async fn zap_authenticate_over_socket(req_socket : Socket, request : ZapRequest) -> ZapReply raise ZmqError

    Client helper sending a ZapRequest over a REQ socket connected to a ZAP server (such as "inproc://zeromq.zap.01") and decoding the ZapReply.