Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445//! XRPC server for AT Protocol labeler//!//! serves two endpoints://! - com.atproto.label.subscribeLabels (WebSocket, CBOR-framed event stream)//! - com.atproto.label.queryLabels (HTTP GET, JSON response)
const std = @import("std");const websocket = @import("websocket");const zat = @import("zat");const label_stream = zat.labels;const store_mod = @import("store.zig");
const Io = std.Io;const Allocator = std.mem.Allocator;const log = std.log.scoped(.server);
// module state — initialized via init(), not from a globalvar io: Io = undefined;
pub fn init(app_io: Io) void { io = app_io;}
pub const Server = struct { allocator: Allocator, store: *store_mod.Store, subscribers: std.ArrayList(*Subscriber), mutex: Io.Mutex = .init,
pub fn init(allocator: Allocator, store: *store_mod.Store) Server { return .{ .allocator = allocator, .store = store, .subscribers = .empty, }; }
pub fn deinit(self: *Server) void { self.subscribers.deinit(self.allocator); }
/// broadcast a new label to all connected subscribers. /// called after a label is stored. pub fn broadcast(self: *Server, seq: i64, label: zat.Label) void { const frame = label_stream.encodeFrame(self.allocator, .{ .labels = .{ .seq = seq, .labels = &.{label} } }) catch |err| { log.err("failed to build frame: {s}", .{@errorName(err)}); return; }; defer self.allocator.free(frame);
self.mutex.lockUncancelable(io); defer self.mutex.unlock(io);
var i: usize = 0; while (i < self.subscribers.items.len) { const sub = self.subscribers.items[i]; // its replay already carried this label if (seq <= sub.sent) { i += 1; continue; } sub.conn.writeBin(frame) catch { // subscriber disconnected, remove log.info("subscriber disconnected, removing", .{}); self.allocator.destroy(sub); _ = self.subscribers.swapRemove(i); continue; }; sub.sent = seq; i += 1; } }
/// add a subscriber connection. /// replay and registration share the lock broadcast takes, so a label /// stored meanwhile is either in the replay or broadcast after it, never /// lost between them; `sent` keeps broadcast from repeating the replay. pub fn addSubscriber(self: *Server, conn: *websocket.Conn, cursor: ?i64) void { const sub = self.allocator.create(Subscriber) catch return;
self.mutex.lockUncancelable(io); defer self.mutex.unlock(io); // without a cursor a subscriber starts at the live head sub.* = .{ .conn = conn, .sent = self.store.latestSeq() }; if (cursor) |cur| { sub.sent = self.backfill(conn, cur) catch |err| blk: { log.err("backfill failed: {s}", .{@errorName(err)}); break :blk cur; }; } self.subscribers.append(self.allocator, sub) catch { self.allocator.destroy(sub); }; }
/// remove a subscriber connection. pub fn removeSubscriber(self: *Server, conn: *websocket.Conn) void { self.mutex.lockUncancelable(io); defer self.mutex.unlock(io);
for (self.subscribers.items, 0..) |sub, i| { if (sub.conn == conn) { self.allocator.destroy(sub); _ = self.subscribers.swapRemove(i); return; } } }
/// sends every stored label after `cursor`; returns the last seq sent fn backfill(self: *Server, conn: *websocket.Conn, cursor: i64) !i64 { const latest = self.store.latestSeq();
// check if cursor is in the future if (cursor > latest) { const frame = try label_stream.encodeFrame(self.allocator, .{ .err = .{ .name = "FutureCursor", .message = "cursor is in the future" } }); defer self.allocator.free(frame); conn.writeBin(frame) catch {}; return cursor; }
// send stored labels in batches var cur = cursor; while (true) { const page = self.store.queryByCursor(self.allocator, cur, 100) catch return cur; defer { for (page) |item| { self.allocator.free(item.label.src); self.allocator.free(item.label.uri); self.allocator.free(item.label.val); self.allocator.free(item.label.cts); self.allocator.free(item.encoded); if (item.label.sig) |s| self.allocator.free(s); if (item.label.cid) |ci| self.allocator.free(ci); if (item.label.exp) |e| self.allocator.free(e); } self.allocator.free(page); }
if (page.len == 0) break;
for (page) |stored| { const frame = label_stream.encodeFrame(self.allocator, .{ .labels = .{ .seq = stored.seq, .labels = &.{stored.label} } }) catch continue; defer self.allocator.free(frame); conn.writeBin(frame) catch return cur; cur = stored.seq; } } return cur; }
/// handle an HTTP request (non-WebSocket). pub fn handleHttp( self: *Server, conn: *websocket.Conn, method: []const u8, url: []const u8, ) void { // split path and query const qmark = std.mem.indexOfScalar(u8, url, '?'); const path = url[0..(qmark orelse url.len)]; const query = if (qmark) |q| url[q + 1 ..] else "";
if (std.mem.eql(u8, method, "GET") and std.mem.eql(u8, path, "/xrpc/com.atproto.label.queryLabels")) { self.handleQueryLabels(conn, query); } else if (std.mem.eql(u8, method, "GET") and std.mem.eql(u8, path, "/health")) { httpRespond(conn, "200 OK", "application/json", "{\"status\":\"ok\"}"); } else { httpRespond(conn, "404 Not Found", "application/json", \\{"error":"NotFound","message":"endpoint not found"} ); } }
fn handleQueryLabels(self: *Server, conn: *websocket.Conn, query: []const u8) void { // parse uriPatterns param const uri = queryParam(query, "uriPatterns") orelse { httpRespond(conn, "400 Bad Request", "application/json", \\{"error":"InvalidRequest","message":"uriPatterns parameter required"} ); return; };
const labels = self.store.queryBySubject(self.allocator, uri) catch { httpRespond(conn, "500 Internal Server Error", "application/json", \\{"error":"InternalError","message":"database query failed"} ); return; }; defer { for (labels) |item| { self.allocator.free(item.label.src); self.allocator.free(item.label.uri); self.allocator.free(item.label.val); self.allocator.free(item.label.cts); self.allocator.free(item.encoded); if (item.label.sig) |s| self.allocator.free(s); if (item.label.cid) |ci| self.allocator.free(ci); if (item.label.exp) |e| self.allocator.free(e); } self.allocator.free(labels); }
// build JSON response var aw: std.Io.Writer.Allocating = .init(self.allocator); defer aw.deinit(); const w = &aw.writer;
w.writeAll("{\"labels\":[") catch return;
for (labels, 0..) |stored, i| { if (i > 0) w.writeByte(',') catch return; writeJsonLabel(w, &stored) catch return; }
w.writeAll("]}") catch return;
httpRespond(conn, "200 OK", "application/json", w.buffered()); }};
const Subscriber = struct { conn: *websocket.Conn, /// the last seq this subscriber was sent sent: i64,};
/// websocket handler for subscribeLabelspub fn Handler(comptime ServerT: type) type { return struct { server: *ServerT, conn: *websocket.Conn, cursor: ?i64 = null,
const Self = @This();
pub fn init(handshake: *const websocket.Handshake, conn: *websocket.Conn, ctx: *ServerT) !Self { return .{ .server = ctx, .conn = conn, .cursor = cursorParam(handshake.url), }; }
pub fn afterInit(self: *Self, _: *ServerT) !void { self.server.addSubscriber(self.conn, self.cursor); }
pub fn clientMessage(_: *Self, _: []const u8) !void { // labeler is write-only to subscribers }
pub fn close(self: *Self) void { self.server.removeSubscriber(self.conn); }
pub fn httpFallback(conn: *websocket.Conn, method: []const u8, url: []const u8, _: []const u8, _: *const websocket.Handshake.KeyValue, ctx_ptr: ?*anyopaque) void { const ctx: *ServerT = @ptrCast(@alignCast(ctx_ptr.?)); ctx.handleHttp(conn, method, url); } };}
// === HTTP helpers ===
fn httpRespond(conn: *websocket.Conn, status: []const u8, content_type: []const u8, body: []const u8) void { var buf: [512]u8 = undefined; const header = std.fmt.bufPrint(&buf, "HTTP/1.1 {s}\r\nContent-Type: {s}\r\nContent-Length: {d}\r\nAccess-Control-Allow-Origin: *\r\n\r\n", .{ status, content_type, body.len, }) catch return; conn.writeFramed(header) catch return; if (body.len > 0) conn.writeFramed(body) catch return;}
/// `?cursor=N` on the subscribeLabels URL: replay everything after seq Nfn cursorParam(url: []const u8) ?i64 { const q = std.mem.indexOfScalar(u8, url, '?') orelse return null; const raw = queryParam(url[q + 1 ..], "cursor") orelse return null; return std.fmt.parseInt(i64, raw, 10) catch null;}
fn queryParam(query: []const u8, name: []const u8) ?[]const u8 { var it = std.mem.splitScalar(u8, query, '&'); while (it.next()) |pair| { const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; if (std.mem.eql(u8, pair[0..eq], name)) { return pair[eq + 1 ..]; } } return null;}
fn writeJsonLabel(w: anytype, stored: *const store_mod.StoredLabel) !void { const lbl = &stored.label; try w.writeAll("{"); try w.print("\"ver\":{d}", .{lbl.ver}); try w.writeAll(",\"src\":\""); try w.writeAll(lbl.src); try w.writeAll("\",\"uri\":\""); try w.writeAll(lbl.uri); try w.writeByte('"');
if (lbl.cid) |cid| { try w.writeAll(",\"cid\":\""); try w.writeAll(cid); try w.writeByte('"'); }
try w.writeAll(",\"val\":\""); try w.writeAll(lbl.val); try w.writeAll("\",\"cts\":\""); try w.writeAll(lbl.cts); try w.writeByte('"');
if (lbl.neg) try w.writeAll(",\"neg\":true"); if (lbl.exp) |exp| { try w.writeAll(",\"exp\":\""); try w.writeAll(exp); try w.writeByte('"'); }
// sig as base64 if (lbl.sig) |sig| { try w.writeAll(",\"sig\":\""); const encoder = std.base64.standard.Encoder; var b64_buf: [88]u8 = undefined; // 64 bytes → 88 chars const b64_len = encoder.calcSize(sig.len); const b64 = encoder.encode(b64_buf[0..b64_len], sig); try w.writeAll(b64); try w.writeByte('"'); }
try w.writeByte('}');}
// === tests ===
test "query param parsing" { try std.testing.expectEqualStrings("hello", queryParam("foo=hello&bar=world", "foo").?); try std.testing.expectEqualStrings("world", queryParam("foo=hello&bar=world", "bar").?); try std.testing.expect(queryParam("foo=hello", "bar") == null); try std.testing.expect(queryParam("", "foo") == null);}
test "cursor is read from the subscribe URL" { try std.testing.expectEqual(@as(?i64, 42), cursorParam("/xrpc/com.atproto.label.subscribeLabels?cursor=42")); try std.testing.expectEqual(@as(?i64, null), cursorParam("/xrpc/com.atproto.label.subscribeLabels")); try std.testing.expectEqual(@as(?i64, null), cursorParam("/xrpc/com.atproto.label.subscribeLabels?cursor=abc"));}
test "zat's LabelClient replays from its cursor after a reconnect" { const store_mod_ = @import("store.zig"); const alloc = std.testing.allocator; var threaded: Io.Threaded = .init(alloc, .{}); defer threaded.deinit(); const test_io = threaded.io(); init(test_io);
const kp = try zat.Keypair.fromSecretKey(.secp256k1, @splat(0x42)); const did_key = try kp.did(alloc); defer alloc.free(did_key);
var store = try store_mod_.Store.init(":memory:"); defer store.deinit(); const vals = [_][]const u8{ "spam", "!hide", "porn", "!takedown" }; var signed: [vals.len]zat.Label = undefined; var sigs: [vals.len][64]u8 = undefined; for (vals, &signed, &sigs) |val, *label, *sig| { label.* = .{ .src = "did:plc:labelz", .uri = "did:plc:subject", .val = val, .cts = "2026-11-01T00:00:00.000Z" }; sig.* = (try label.sign(alloc, &kp)).bytes; label.sig = sig; } // the first three are stored before anyone connects; the fourth goes out live for (signed[0..3]) |*label| { const encoded = try label.encode(alloc); defer alloc.free(encoded); _ = try store.insert(label, encoded); }
var server = Server.init(alloc, &store); defer server.deinit(); var ws_server = try websocket.Server(Handler(Server)).init(alloc, test_io, .{ .port = 47391, .address = "127.0.0.1" }); defer ws_server.deinit(); const thread = try ws_server.listenInNewThread(&server); defer { ws_server.stop(); thread.join(); }
const Collector = struct { alloc: Allocator, key: []const u8, stop_at: i64, seqs: [8]i64 = undefined, n: usize = 0, verified: usize = 0, failed: bool = false, pub fn onEvent(self: *@This(), event: zat.LabelEvent) void { const batch = switch (event) { .labels => |b| b, else => return, }; for (batch.labels) |label| { if (label.verify(self.alloc, self.key)) |_| self.verified += 1 else |_| {} } self.seqs[self.n] = batch.seq; self.n += 1; } pub fn onError(self: *@This(), _: anyerror) void { self.failed = true; } pub fn shouldStop(self: *@This()) bool { return self.failed or (self.n > 0 and self.seqs[self.n - 1] >= self.stop_at); } };
var client = zat.LabelClient.init(test_io, alloc, .{ .hosts = &.{"ws://127.0.0.1:47391"}, .idle_timeout_ms = 5000 }); defer client.deinit();
// first connection, no cursor: the stored backlog from the start client.last_seq = 0; var first: Collector = .{ .alloc = alloc, .key = did_key, .stop_at = 2 }; try client.subscribe(&first); try std.testing.expectEqualSlices(i64, &.{ 1, 2 }, first.seqs[0..first.n]); try std.testing.expectEqual(@as(?i64, 2), client.last_seq);
// while the consumer is away the labeler emits a fourth label: stored, // then broadcast to whoever is connected { const encoded = try signed[3].encode(alloc); defer alloc.free(encoded); const seq = try store.insert(&signed[3], encoded); server.broadcast(seq, signed[3]); }
// reconnect: the server replays everything after seq 2 var second: Collector = .{ .alloc = alloc, .key = did_key, .stop_at = 4 }; try client.subscribe(&second); try std.testing.expect(!first.failed and !second.failed); try std.testing.expectEqualSlices(i64, &.{ 3, 4 }, second.seqs[0..second.n]); try std.testing.expectEqual(@as(usize, 2), second.verified);}