Something went wrong. Try again.
Sendspin in Zig, both sides: a player client for Music Assistant, and a server streaming to players in sync
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the conformance harness's two adapters here share: its command//! line, its registry and summary files, the identities and PSK it pairs//! both sides with, and the protocol evidence -- the same assertions read//! off a trace from either side of the connection.
const std = @import("std");const Io = std.Io;const sendspin = @import("sendspin");const uri = @import("uri");
const Sha256 = std.crypto.hash.sha2.Sha256;const Format = sendspin.message.Format;
/// The revision of the Sendspin specification the harness's protocol/// assertions are pinned to; evidence for another is refused.pub const spec_revision = "8c9577ea8719ad082d051ec13cc73ef15ed68948";
/// Parse `--name value` pairs into `T`'s fields, `-` for `_`: strings as/// they are, floats parsed. Flags `T` has no field for are accepted and/// ignored, since each scenario adds its own.pub fn parseArgs(comptime T: type, it: *std.process.Args.Iterator) !T { var args: T = .{}; while (it.next()) |flag| { if (!std.mem.startsWith(u8, flag, "--")) return error.Usage; const value = it.next() orelse return error.Usage; const name = flag[2..]; const info = @typeInfo(T).@"struct"; inline for (info.field_names, info.field_types) |field_name, field_type| { if (dashedEql(field_name, name)) { @field(args, field_name) = switch (field_type) { []const u8 => value, f64 => try std.fmt.parseFloat(f64, value), else => comptime unreachable, }; } } } return args;}
fn dashedEql(field: []const u8, flag: []const u8) bool { if (field.len != flag.len) return false; for (field, flag) |a, b| if (a != (if (b == '-') '_' else b)) return false; return true;}
/// SHA-256 over `label`, `a` and `b`, run together, as the harness derives/// its identities and PSKs.pub fn derive(label: []const u8, a: []const u8, b: []const u8) [32]u8 { var out: [32]u8 = undefined; var h = Sha256.init(.{}); h.update(label); h.update(a); if (b.len > 0) { h.update(":"); h.update(b); } h.final(&out); return out;}
/// The key pair the harness gives a side: `role` is "client" or "server",/// `id` its `--client-id` or `--server-id`.pub fn identity(comptime role: []const u8, id: []const u8) ![32]u8 { return derive("sendspin-conformance-identity:" ++ role ++ ":", id, "");}
/// The long-term PSK the harness pairs the two with.pub fn psk(server_id: []const u8, client_id: []const u8) [32]u8 { return derive("sendspin-conformance-psk:", server_id, client_id);}
/// Where a `ws://host:port/path` URL points.pub fn addressOf(arena: std.mem.Allocator, url: []const u8) !sendspin.Session.Address { const u = try uri.Uri.parse(arena, url); const scheme = u.scheme orelse return error.BadUrl; const secure = if (std.ascii.eqlIgnoreCase(scheme, "wss")) true else if (std.ascii.eqlIgnoreCase(scheme, "ws")) false else return error.BadUrl; const host = (u.host orelse return error.BadUrl).text(); var resource: Io.Writer.Allocating = .init(arena); for (u.path) |segment| { if (segment.len == 0 and u.path.len == 1) break; try resource.writer.print("/{s}", .{segment}); } return .{ .hostname = host, .port = u.port orelse if (secure) 443 else 80, .secure = secure, .resource = if (resource.written().len == 0) "/" else resource.written(), };}
/// Wait for the other side to register its URL under `name`.pub fn lookup(io: Io, arena: std.mem.Allocator, path: []const u8, name: []const u8, deadline: Io.Clock.Timestamp) ![]const u8 { while (true) { if (Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 20))) |text| { if (std.json.parseFromSliceLeaky(std.json.Value, arena, text, .{})) |registry| { if (registry == .object) if (registry.object.get(name)) |entry| { if (entry == .object) if (entry.object.get("url")) |u| if (u == .string) return u.string; }; } else |_| {} // Being written: try again. } else |err| if (err != error.FileNotFound) return err; if (deadline.durationFromNow(io).raw.nanoseconds <= 0) return error.TimedOutWaitingForRegistry; try io.sleep(.fromMilliseconds(100), .awake); }}
/// Put `url` under `name` in the registry, keeping whatever else is there.pub fn register(io: Io, arena: std.mem.Allocator, path: []const u8, name: []const u8, url: []const u8) !void { var registry: std.json.ObjectMap = .empty; if (Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 20))) |text| { const v = try std.json.parseFromSliceLeaky(std.json.Value, arena, text, .{}); if (v == .object) registry = v.object; } else |err| if (err != error.FileNotFound) return err; var entry: std.json.ObjectMap = .empty; try entry.put(arena, "url", .{ .string = url }); try registry.put(arena, name, .{ .object = entry }); try writeJson(io, path, std.json.Value{ .object = registry });}
pub fn writeJson(io: Io, path: []const u8, value: anytype) !void { var buf: [4096]u8 = undefined; var file = try Io.Dir.cwd().createFile(io, path, .{}); defer file.close(io); var w = file.writer(io, &buf); try std.json.Stringify.value(value, .{ .whitespace = .indent_2, .emit_null_optional_fields = false }, &w.interface); try w.interface.writeByte('\n'); try w.interface.flush();}
/// Write `value` to stdout as one line, as the harness also shows it.pub fn print(io: Io, value: anytype) !void { var buf: [4096]u8 = undefined; var stdout = Io.File.stdout().writer(io, &buf); try std.json.Stringify.value(value, .{ .emit_null_optional_fields = false }, &stdout.interface); try stdout.interface.writeByte('\n'); try stdout.interface.flush();}
/// The metadata as the harness compares it: the fields it sends, each/// present, null where unknown.pub const MetadataSnapshot = struct { title: ?[]const u8, artist: ?[]const u8, album_artist: ?[]const u8, album: ?[]const u8, artwork_url: ?[]const u8, year: ?i64, track: ?i64, progress: ?sendspin.message.Progress,};
pub fn snapshotOf(metadata: ?sendspin.message.Metadata) ?MetadataSnapshot { const m = metadata orelse return null; return .{ .title = m.title, .artist = m.artist, .album_artist = m.album_artist, .album = m.album, .artwork_url = m.artwork_url, .year = m.year, .track = m.track, .progress = m.progress, };}
/// A command the harness names, which takes nothing more.pub fn commandOf(name: []const u8) !sendspin.message.ControllerCommand { const Tag = std.meta.Tag(sendspin.message.ControllerCommand); const tag = std.meta.stringToEnum(Tag, name) orelse return error.UnknownCommand; const info = @typeInfo(sendspin.message.ControllerCommand).@"union"; inline for (info.field_names, info.field_types) |field_name, field_type| { if (field_type == void and std.mem.eql(u8, field_name, @tagName(tag))) return @unionInit(sendspin.message.ControllerCommand, field_name, {}); } return error.CommandTakesAnArgument;}
// --- protocol evidence -------------------------------------------------------
/// One message from the trace, as a side saw it go by.pub const Event = struct { direction: sendspin.Client.Direction, frame: []const u8, sealed: bool, type: []const u8, binary_type: ?u8, timestamp_us: ?i64 = null,
/// Copied into `a`, from `Client.Options.trace` or the server's. pub fn of(a: std.mem.Allocator, e: sendspin.Client.TraceEvent) !Event { return .{ .direction = e.direction, .frame = @tagName(e.frame), .sealed = e.sealed, .type = try a.dupe(u8, e.type), .binary_type = e.binary_type, .timestamp_us = e.timestamp_us, }; }};
pub const Side = enum { client, server };
pub const Protocol = struct { spec_revision: []const u8 = spec_revision, assertions: struct { @"CORE-001": Assertion, @"CORE-002": Assertion, @"CORE-003": Assertion, @"CORE-004": Assertion, @"PLAYER-001": Assertion, },};
pub const Assertion = struct { status: []const u8, detail: []const u8, events: []const TraceRecord,};
/// One entry of an assertion's trace, as the harness's contract has it: the/// event, and only what establishes the assertion.pub const TraceRecord = struct { event: []const u8, index: ?usize = null, direction: ?[]const u8 = null, message_type: ?[]const u8 = null, frame: ?[]const u8 = null, sealed: ?bool = null, binary_type: ?u8 = null, roles: ?[]const []const u8 = null, offered_roles: ?[]const []const u8 = null, negotiated_format: ?Format = null, advertised_formats: ?[]const Format = null, chunk_count: ?u64 = null, first_timestamp_us: ?i64 = null, last_timestamp_us: ?i64 = null,
fn message(i: usize, e: Event) TraceRecord { return .{ .event = "message", .index = i, .direction = @tagName(e.direction), .message_type = if (e.type.len > 0) e.type else null, .frame = e.frame, .sealed = e.sealed, .binary_type = e.binary_type, }; }};
/// Everything the assertions are judged on.pub const Observed = struct { side: Side, events: []const Event, /// Whether the trace holds the whole session, or was cut short. complete: bool, /// Each activation's roles, in order. activations: []const []const []const u8, /// The roles the client's hello offered. offered_roles: []const []const u8, /// The player's stream's format, and the formats the hello offered. stream: ?Format, advertised: []const Format,};
/// A message's direction as `side` sees it, from who sends it.fn from(side: Side, sender: Side) sendspin.Client.Direction { return if (side == sender) .outbound else .inbound;}
const Expected = struct { sender: Side, frame: []const u8, type: []const u8 };
/// The handshake, message by message, as the specification orders it:/// Noise in text frames, then the hellos sealed in binary ones.const sealed_handshake = [_]Expected{ .{ .sender = .client, .frame = "text", .type = "client/init" }, .{ .sender = .server, .frame = "text", .type = "server/init" }, .{ .sender = .server, .frame = "text", .type = "noise/handshake" }, .{ .sender = .client, .frame = "text", .type = "noise/handshake" }, .{ .sender = .server, .frame = "binary", .type = "server/hello" }, .{ .sender = .client, .frame = "binary", .type = "client/hello" },};
const handshake_types = [_][]const u8{ "client/init", "server/init", "noise/handshake", "server/hello", "client/hello" };
/// The five baseline assertions, judged on what `o` saw.pub fn evidence(a: std.mem.Allocator, o: Observed) !Protocol { const events = o.events;
// CORE-001: the handshake's messages, in order, each in its frame. const core_001: Assertion = blk: { var records: std.ArrayList(TraceRecord) = .empty; for (events[0..@min(events.len, sealed_handshake.len)], 0..) |e, i| try records.append(a, .message(i, e)); for (sealed_handshake, 0..) |want, i| { if (i >= events.len) break :blk failed(a, records.items, "the trace ends before the handshake does", .{}); const e = events[i]; const dir = from(o.side, want.sender); if (e.direction != dir or !std.mem.eql(u8, e.frame, want.frame) or !std.mem.eql(u8, e.type, want.type)) { break :blk failed(a, records.items, "message {d} was {t} {s} in a {s} frame, where {t} {s} in a {s} frame was due", .{ i, e.direction, e.type, e.frame, dir, want.type, want.frame }); } } break :blk passed(records.items, "client/init, server/init, both Noise messages in text frames; then the hellos, sealed, in binary frames"); };
const activate_dir = from(o.side, .server); const activate_index = for (events, 0..) |e, i| { if (e.direction == activate_dir and std.mem.eql(u8, e.type, "server/activate")) break i; } else null;
// CORE-002: nothing but the handshake before the first activation. const core_002: Assertion = blk: { const first = activate_index orelse break :blk failed(a, &.{}, "no server/activate was traced", .{}); var records: std.ArrayList(TraceRecord) = .empty; for (events[0 .. first + 1], 0..) |e, i| try records.append(a, .message(i, e)); for (events[0..first], 0..) |e, i| { const allowed = for (handshake_types) |t| { if (std.mem.eql(u8, e.type, t)) break true; } else false; if (!allowed) break :blk failed(a, records.items, "message {d}, {t} {s}, came before the first server/activate", .{ i, e.direction, if (e.type.len > 0) e.type else "binary" }); } break :blk passed(records.items, "only the handshake and the hellos went either way before the first server/activate"); };
// CORE-003: every role activated is one the hello offered. const core_003: Assertion = blk: { if (o.activations.len == 0) break :blk failed(a, &.{}, "no server/activate was traced", .{}); var records: std.ArrayList(TraceRecord) = .empty; for (o.activations) |roles| { try records.append(a, .{ .event = "server_activate", .roles = roles, .offered_roles = o.offered_roles }); for (roles) |role| { const offered = for (o.offered_roles) |r| { if (std.mem.eql(u8, r, role)) break true; } else false; if (!offered) break :blk failed(a, records.items, "{s} was activated, which the hello did not offer", .{role}); } } break :blk passed(records.items, "every role activated was among those the hello offered"); };
// CORE-004: the client's first client/state after the first activation, // and before the first binary message of any role. const core_004: Assertion = blk: { const first = activate_index orelse break :blk failed(a, &.{}, "no server/activate was traced", .{}); const state_dir = from(o.side, .client); const state = for (events, 0..) |e, i| { if (e.direction == state_dir and std.mem.eql(u8, e.type, "client/state")) break i; } else break :blk failed(a, &.{}, "no client/state was traced", .{}); const binary_dir = from(o.side, .server); const binary = for (events, 0..) |e, i| { if (e.direction == binary_dir and e.binary_type != null) break i; } else null; var records: std.ArrayList(TraceRecord) = .empty; try records.append(a, .message(first, events[first])); try records.append(a, .message(state, events[state])); if (binary) |b| try records.append(a, .message(b, events[b])); if (state < first) break :blk failed(a, records.items, "client/state went before the first server/activate", .{}); if (binary) |b| if (b < state) break :blk failed(a, records.items, "binary data went before the first client/state", .{}); if (!o.complete) break :blk failed(a, records.items, "the session outgrew the trace", .{}); break :blk passed(records.items, "the first client/state went after the activation and before any binary data"); };
// PLAYER-001: the stream is in a format offered, and its chunks are // stamped in order. const player_001: Assertion = blk: { const negotiated = o.stream orelse break :blk failed(a, &.{}, "no stream/start with a player object was traced", .{}); var records: std.ArrayList(TraceRecord) = .empty; try records.append(a, .{ .event = "stream_start_observed", .negotiated_format = negotiated, .advertised_formats = o.advertised }); const offered = for (o.advertised) |f| { if (std.meta.eql(f, negotiated)) break true; } else false; if (!offered) break :blk failed(a, records.items, "the stream's format was not among those offered", .{}); const audio_dir = from(o.side, .server); var chunks: u64 = 0; var first_ts: ?i64 = null; var last_ts: ?i64 = null; var out_of_order: u64 = 0; for (events) |e| { if (e.direction != audio_dir or e.binary_type != @backingInt(sendspin.message.BinaryType.audio)) continue; const ts = e.timestamp_us orelse continue; chunks += 1; if (first_ts == null) first_ts = ts; if (last_ts) |l| if (ts < l) { out_of_order += 1; }; last_ts = ts; } try records.append(a, .{ .event = "audio_chunks_observed", .chunk_count = chunks, .first_timestamp_us = first_ts, .last_timestamp_us = last_ts }); if (chunks == 0) break :blk failed(a, records.items, "no audio chunks went after stream/start", .{}); if (out_of_order > 0) break :blk failed(a, records.items, "{d} chunks were stamped earlier than the one before", .{out_of_order}); break :blk passed(records.items, "the stream was in a format offered, and every chunk was stamped in order"); };
return .{ .assertions = .{ .@"CORE-001" = core_001, .@"CORE-002" = core_002, .@"CORE-003" = core_003, .@"CORE-004" = core_004, .@"PLAYER-001" = player_001, } };}
fn passed(records: []const TraceRecord, detail: []const u8) Assertion { return .{ .status = "passed", .detail = detail, .events = records };}
fn failed(a: std.mem.Allocator, records: []const TraceRecord, comptime fmt: []const u8, args: anytype) Assertion { return .{ .status = "failed", .detail = std.fmt.allocPrint(a, fmt, args) catch fmt, .events = records };}
test "the harness's identity and PSK derivations" { var want: [32]u8 = undefined; Sha256.hash("sendspin-conformance-psk:s:c", &want, .{}); try std.testing.expectEqualSlices(u8, &want, &psk("s", "c")); Sha256.hash("sendspin-conformance-identity:client:c", &want, .{}); try std.testing.expectEqualSlices(u8, &want, &try identity("client", "c"));}
test "URLs" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = try addressOf(arena.allocator(), "ws://127.0.0.1:9100/sendspin"); try std.testing.expectEqualStrings("127.0.0.1", a.hostname); try std.testing.expectEqual(@as(?u16, 9100), a.port); try std.testing.expectEqualStrings("/sendspin", a.resource); try std.testing.expect(!a.secure); const b = try addressOf(arena.allocator(), "ws://localhost:8927/"); try std.testing.expectEqualStrings("/", b.resource); try std.testing.expectError(error.BadUrl, addressOf(arena.allocator(), "http://localhost/"));}
test "commands the harness names" { try std.testing.expectEqual(sendspin.message.ControllerCommand.next, try commandOf("next")); try std.testing.expectError(error.CommandTakesAnArgument, commandOf("volume")); try std.testing.expectError(error.UnknownCommand, commandOf("dance"));}
test "the handshake judged from either side" { // The same session as each side traced it: every direction swapped. const client_view = [_]Event{ .{ .direction = .outbound, .frame = "text", .sealed = false, .type = "client/init", .binary_type = null }, .{ .direction = .inbound, .frame = "text", .sealed = false, .type = "server/init", .binary_type = null }, .{ .direction = .inbound, .frame = "text", .sealed = false, .type = "noise/handshake", .binary_type = null }, .{ .direction = .outbound, .frame = "text", .sealed = false, .type = "noise/handshake", .binary_type = null }, .{ .direction = .inbound, .frame = "binary", .sealed = true, .type = "server/hello", .binary_type = null }, .{ .direction = .outbound, .frame = "binary", .sealed = true, .type = "client/hello", .binary_type = null }, .{ .direction = .inbound, .frame = "binary", .sealed = true, .type = "server/activate", .binary_type = null }, .{ .direction = .outbound, .frame = "binary", .sealed = true, .type = "client/state", .binary_type = null }, .{ .direction = .inbound, .frame = "binary", .sealed = true, .type = "", .binary_type = 4, .timestamp_us = 10 }, .{ .direction = .inbound, .frame = "binary", .sealed = true, .type = "", .binary_type = 4, .timestamp_us = 20 }, }; var server_view: [client_view.len]Event = undefined; for (&server_view, client_view) |*s, c| { s.* = c; s.direction = if (c.direction == .inbound) .outbound else .inbound; } var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const format: Format = .{ .codec = .pcm, .channels = 1, .sample_rate = 8000, .bit_depth = 16 }; const roles: []const []const u8 = &.{sendspin.message.player_role}; inline for (.{ .{ Side.client, &client_view }, .{ Side.server, &server_view } }) |c| { const p = try evidence(arena.allocator(), .{ .side = c[0], .events = c[1], .complete = true, .activations = &.{roles}, .offered_roles = roles, .stream = format, .advertised = &.{format}, }); inline for (.{ "CORE-001", "CORE-002", "CORE-003", "CORE-004", "PLAYER-001" }) |name| { try std.testing.expectEqualStrings("passed", @field(p.assertions, name).status); } }}