Something went wrong. Try again.
An MQTT 5.0 and 3.1.1 client for Zig: a sans-I/O core, TCP, TLS, WebSocket and wss transports, SASL authentication, and reconnection
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
const std = @import("std");
pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{});
// Two modules, split along the one line that matters: whether a thing // touches I/O. // // `mqtt` is the wire format and the session state machine, and names no // transport, no clock and no thread. `mqtt_client` carries its bytes along // a `std.Io.Reader` and a `std.Io.Writer` and reconnects when one breaks. // A program with an event loop of its own -- which is most of the reason to // want a sans-I/O core at all -- depends on the first and never compiles a // line of the second. const mod = b.addModule("mqtt", .{ .root_source_file = b.path("src/root.zig"), .target = target, });
// TLS comes from tls.zig, not from `std.crypto.tls`. The standard // library's client has no client certificates and no ALPN, and it requires // the optional TLS 1.3 middlebox-compatibility record that some servers // leave out. `build.zig.zon` says which fork and which branch, and why. // // No options, as zig-http and zig-quic instantiate it: the dependency // cache is keyed on them, and a second set would make a second module // over the same files, which Zig refuses. The module ignores target and // optimize in any case. const tls_dep = b.dependency("tls", .{});
// MQTT over WebSocket, which is what a broker on port 443 behind an HTTP // proxy serves. Only the `websocket` module: zig-websocket keeps the // server half of the opening handshake in a second module, because that // half is written against an HTTP server library and a client has no use // for one. const ws_dep = b.dependency("websocket", .{ .target = target, .optimize = optimize });
// Extended authentication is a SASL exchange carried in MQTT packets, so // this takes the interface and not a mechanism: which mechanism to speak // is the caller's choice, and a library that picked one would be wrong for // everybody else. zig-sasl has no dependencies of its own. const sasl_dep = b.dependency("sasl", .{ .target = target, .optimize = optimize });
const client_mod = b.addModule("mqtt_client", .{ .root_source_file = b.path("src/client/root.zig"), .target = target, .imports = &.{ .{ .name = "mqtt", .module = mod }, .{ .name = "tls", .module = tls_dep.module("tls") }, .{ .name = "websocket", .module = ws_dep.module("websocket") }, .{ .name = "sasl", .module = sasl_dep.module("sasl") }, }, });
const exe = b.addExecutable(.{ .name = "zig-mqtt", .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "mqtt", .module = mod }, .{ .name = "mqtt_client", .module = client_mod }, }, }), }); b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe); run_cmd.step.dependOn(b.getInstallStep()); run_cmd.stdio = .inherit; run_cmd.addPassthruArgs(); const run_step = b.step("run", "Run the demo client against a broker"); run_step.dependOn(&run_cmd.step);
// A test executable covers one module, so each needs its own. Missing one // out would not fail: its tests would simply never run. const test_step = b.step("test", "Run tests"); for ([_]*std.Build.Module{ mod, client_mod, exe.root_module }) |m| { test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); }
// The end-to-end tests drive a real client against a real broker over a // real socket, which is the only way to prove that what the state machine // believes it is sending is what comes out of the other end. They are a // module of their own so that `zig build test` runs them while a consumer // of the library never compiles them. const e2e_mod = b.createModule(.{ .root_source_file = b.path("tests/e2e.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "mqtt", .module = mod }, .{ .name = "mqtt_client", .module = client_mod }, // For the broker's side of the WebSocket tests, which lays the // framing over its end of the socket by hand. .{ .name = "websocket", .module = ws_dep.module("websocket") }, // And for its side of the authentication exchanges, which run a // real mechanism's server half against the client's. .{ .name = "sasl", .module = sasl_dep.module("sasl") }, }, }); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = e2e_mod })).step);
// The fuzz targets: what the packet decoders and the connection must do // with input nobody wrote. They are ordinary tests as well as fuzz tests, // so `zig build test` exercises the same properties on the seeds checked in // beside them. const fuzz_mod = b.createModule(.{ .root_source_file = b.path("tests/fuzz.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "mqtt", .module = mod }, .{ .name = "mqtt_client", .module = client_mod }, }, }); // Zig's fuzzer takes one test at a time and keeps a coverage file per test, // so naming a target is what you want when a finding is being chased: // `zig build fuzz --fuzz -Dfuzz-filter=packet`. const fuzz_filter = b.option( []const u8, "fuzz-filter", "Fuzz or test only the targets whose name contains this", ); const fuzz_tests = b.addTest(.{ .root_module = fuzz_mod, .filters = if (fuzz_filter) |f| &.{f} else &.{}, // LLVM rather than the self-hosted backend Debug uses by default, // which emits no coverage instrumentation: under it `--fuzz` has no // program counters to steer by and ends with "pcs_len was zero". .use_llvm = true, }); test_step.dependOn(&b.addRunArtifact(fuzz_tests).step);
// A step of its own for `zig build fuzz --fuzz`, which needs a run step // holding nothing else: the fuzzer takes over the terminal and runs until // it is stopped, so it must not be reached by `zig build test`. const fuzz_step = b.step("fuzz", "The fuzz targets: add --fuzz to fuzz them"); fuzz_step.dependOn(&b.addRunArtifact(fuzz_tests).step);
// The loop that drives those same targets without Zig's fuzzer: seeded // and bounded, from an ordinary executable, which is what CI wants and // what reproduces a run exactly. Optimised, because a // fuzzer's whole job is how many inputs it gets through, and ReleaseSafe // keeps every check that makes a failure a failure. const fuzz_run = b.addExecutable(.{ .name = "zig-mqtt-fuzz", .root_module = b.createModule(.{ .root_source_file = b.path("tools/fuzz.zig"), .target = b.graph.host, .optimize = .ReleaseSafe, .imports = &.{.{ .name = "fuzz_targets", .module = fuzz_mod }}, }), }); const run_fuzz = b.addRunArtifact(fuzz_run); run_fuzz.stdio = .inherit; run_fuzz.addPassthruArgs(); const fuzz_run_step = b.step("fuzz-run", "Fuzz the targets with a loop of our own"); fuzz_run_step.dependOn(&run_fuzz.step);
// Nothing else builds it, so without this it could stop compiling and // `zig build test` would not notice. const check_step = b.step("check", "Compile everything without running it"); check_step.dependOn(&fuzz_run.step);
// -- documentation ------------------------------------------------------- // // Zig emits the API documentation as a side effect of compiling, so the // module is built as a library purely to get at it. What comes out is not a // page but a program: a WebAssembly viewer, its javascript, and a tar of // the sources it reads from. // `getEmittedDocs` covers one module, so two modules need two bundles and // an index saying which is which -- and, more usefully, what depending on // each one costs. const documented = [_]struct { name: []const u8, module: *std.Build.Module, needs: []const u8, what: []const u8, }{ .{ .name = "mqtt", .module = mod, .needs = "nothing", .what = "The wire format and the session state machine. No I/O of any kind: " ++ "bytes in, bytes out, and the caller says what time it is.", }, .{ .name = "mqtt_client", .module = client_mod, .needs = "<code>mqtt</code>", .what = "Carries those bytes along a <code>std.Io.Reader</code> and a " ++ "<code>std.Io.Writer</code>, and reconnects when one breaks.", }, };
// The bundles and the index are gathered into one generated directory, // which is both what is installed and what `docs-serve` serves: the server // cannot be handed the install path, since that is not known while the // build is being configured. const docs_dir = b.addWriteFiles();
var index: std.ArrayList(u8) = .empty; index.appendSlice(b.allocator, \\<!doctype html> \\<html lang="en"> \\<meta charset="utf-8"> \\<title>zig-mqtt API documentation</title> \\<style> \\body { font-family: system-ui, sans-serif; max-width: 44rem; \\ margin: 4rem auto; padding: 0 1rem; line-height: 1.5 } \\td, th { text-align: left; padding: 0.3rem 1.5rem 0.3rem 0; vertical-align: top } \\code { background: #eee; padding: 0 0.2rem } \\</style> \\<h1>zig-mqtt</h1> \\<p>An MQTT 5.0 and 3.1.1 client for Zig, with the protocol and the \\transport in separate modules so that a program driving its own event \\loop carries neither the reader nor the writer. \\<table> \\<tr><th>Module<th>Depends on<th> \\ ) catch @panic("OOM"); for (documented) |d| { const library = b.addLibrary(.{ .name = d.name, .root_module = d.module }); _ = docs_dir.addCopyDirectory(library.getEmittedDocs(), d.name, .{}); index.print(b.allocator, "<tr><td><a href=\"{s}/\"><code>{s}</code></a><td>{s}<td>{s}\n", .{ d.name, d.name, d.needs, d.what, }) catch @panic("OOM"); } index.appendSlice(b.allocator, "</table>\n") catch @panic("OOM");
_ = docs_dir.add("index.html", index.items);
const install_docs = b.addInstallDirectory(.{ .source_dir = docs_dir.getDirectory(), .install_dir = .prefix, .install_subdir = "docs", }); const docs_step = b.step("docs", "Build the API documentation into zig-out/docs"); docs_step.dependOn(&install_docs.step);
// That viewer fetches `sources.tar` and `main.wasm` at runtime, which a // browser refuses to do from a `file://` page, so reading the docs locally // means serving them. It is the same reason `zig std` runs a server rather // than opening a file. const docs_port = b.option(u16, "docs-port", "Port for `zig build docs-serve` (default 8000)") orelse 8000;
const docs_server = b.addExecutable(.{ .name = "docs-server", .root_module = b.createModule(.{ .root_source_file = b.path("tools/docs_server.zig"), // Always built for the machine running the build, never for // whatever -Dtarget the library is being built for. .target = b.graph.host, .optimize = .Debug, }), });
const run_docs_server = b.addRunArtifact(docs_server); run_docs_server.addDirectoryArg(docs_dir.getDirectory()); run_docs_server.addArg(b.fmt("{d}", .{docs_port})); // The server runs until interrupted, so its output has to reach the // terminal rather than being captured by the build runner. run_docs_server.stdio = .inherit;
const docs_serve_step = b.step("docs-serve", "Serve the API documentation over HTTP"); docs_serve_step.dependOn(&run_docs_server.step);
// The server has tests of its own; without this they would never run. test_step.dependOn(&b.addRunArtifact( b.addTest(.{ .root_module = docs_server.root_module }), ).step); check_step.dependOn(&docs_server.step);}