// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! One client, connected: who it is, what it offered and what it was //! granted, what it says of itself, and a queue of what is to be sent to //! it. //! //! Sending goes through the queue, and one task of the connection's own //! takes from it, seals and writes, so that a client slow to read holds up //! only its own queue, and the nonces go out in the order the frames do. //! A group streaming to many clients puts the same chunk in each one's //! queue and moves on. //! //! A connection is counted: whatever holds one beyond the call it was //! handed in -- a group sending to it -- `retain`s and `release`s it, and //! the last release frees it. const Connection = @This(); const std = @import("std"); const Io = std.Io; const sendspin = @import("sendspin"); const message = sendspin.message; const server_message = sendspin.server_message; const secure = sendspin.secure; const Session = sendspin.Session; const Server = @import("Server.zig"); const Group = @import("Group.zig"); const log = std.log.scoped(.sendspin_server); server: *Server, session: *Session, /// This server's own number for the connection, unique while it runs. id: u64, /// The sealed channel, on a sealed connection; the writer task seals with /// it and the reader opens with it, which is safe: each direction has its /// own cipher. channel: ?secure.Channel, /// Everything the client said in its hello, and its id: a sealed /// connection's is its key, an unsealed one's what the hello said. Lives /// in `arena` for the connection's life. hello: server_message.ClientHello, /// The hello itself, as the client sent it. hello_text: []const u8 = "", client_id: []const u8, /// Whether the handshake ended on a long-term PSK: the client is paired. paired: bool, /// The sealed handshake's hash, which pairing binds to. handshake_hash: [32]u8 = undefined, arena: std.heap.ArenaAllocator, /// The roles granted, from those offered; see `Server.Options.roles`. roles: Roles, /// What the client last said of itself; under the server's lock. state: State = .{}, /// Whether it has said anything of itself yet: a player is sent no audio /// until its first `client/state`, which carries the timing it needs. state_seen: std.atomic.Value(bool) = .init(false), /// Whether it is in a group and the program has been told of it: at once /// for most clients, and for a player at its first `client/state`. On the /// connection's task alone. joined: bool = false, /// The group it is in, under the server's lock; null only on the way out. group: ?*Group = null, refs: std.atomic.Value(u32) = .init(1), queue: Io.Queue(Out), queue_buf: [queue_len]Out = undefined, writer: ?Io.Future(void) = null, /// Set once the connection has failed or ended: nothing more is queued. closed: std.atomic.Value(bool) = .init(false), pub const Roles = struct { player: bool = false, metadata: bool = false, controller: bool = false, artwork: bool = false, pub fn names(r: Roles, buf: *[4][]const u8) []const []const u8 { var n: usize = 0; inline for (.{ .{ "player", message.player_role }, .{ "metadata", message.metadata_role }, .{ "controller", message.controller_role }, .{ "artwork", message.artwork_role } }) |role| { if (@field(r, role[0])) { buf[n] = role[1]; n += 1; } } return buf[0..n]; } }; /// What a client says of itself, as far as it has. pub const State = struct { available: bool = true, volume: u8 = 100, muted: bool = false, static_delay_ms: u32 = 0, required_lead_time_ms: u32 = 0, min_buffer_ms: u32 = 0, }; /// What goes out, owned by the connection until sent. A clock reply is /// kept apart so that its transmit time is taken as it goes, not as it was /// queued. pub const Out = union(enum) { text: []u8, binary: []u8, time: struct { client_transmitted: i64, server_received: i64 }, /// Close the connection, once everything before it has gone. close, }; /// Messages waiting to go. Audio is paced to a few seconds ahead, so a /// queue this long only fills if the client stops reading. const queue_len = 1024; pub fn retain(self: *Connection) void { _ = self.refs.fetchAdd(1, .monotonic); } pub fn release(self: *Connection) void { if (self.refs.fetchSub(1, .acq_rel) != 1) return; const gpa = self.server.gpa; // Whatever was queued and never sent -- taken into a slot of its own, // not the queue's storage it is read from. var one: [1]Out = undefined; while (self.queue.getUncancelable(self.server.io, &one, 0)) |n| { if (n == 0) break; freeOut(gpa, one[0]); } else |_| {} if (self.channel) |*ch| ch.deinit(); self.arena.deinit(); gpa.destroy(self); } fn freeOut(gpa: std.mem.Allocator, out: Out) void { switch (out) { .text => |t| gpa.free(t), .binary => |b| gpa.free(b), .time, .close => {}, } } /// End the connection once what is already queued has been sent: a /// WebSocket Close, and the socket shut, which ends the client's reading /// and so the connection's. pub fn disconnect(self: *Connection) void { self.put(.close) catch {}; } /// Queue a text message, copied. Fails only once the connection is closed, /// which the caller may ignore. pub fn send(self: *Connection, text: []const u8) !void { return self.put(.{ .text = try self.server.gpa.dupe(u8, text) }); } /// Queue a binary message -- its type byte first -- copied. pub fn sendBinary(self: *Connection, bytes: []const u8) !void { return self.put(.{ .binary = try self.server.gpa.dupe(u8, bytes) }); } /// Queue a binary message from a header and a body, copied into one. pub fn sendBinaryParts(self: *Connection, header: []const u8, body: []const u8) !void { const out = try self.server.gpa.alloc(u8, header.len + body.len); @memcpy(out[0..header.len], header); @memcpy(out[header.len..], body); return self.put(.{ .binary = out }); } /// Queue `out` if there is room, and say whether there was; never waits. /// For audio, which a client too far behind can miss. pub fn putNow(self: *Connection, out: Out) bool { if (self.closed.load(.acquire)) { freeOut(self.server.gpa, out); return false; } const n = self.queue.put(self.server.io, &.{out}, 0) catch 0; if (n == 0) freeOut(self.server.gpa, out); return n == 1; } pub fn put(self: *Connection, out: Out) !void { if (self.closed.load(.acquire)) { freeOut(self.server.gpa, out); return error.Closed; } self.queue.putOne(self.server.io, out) catch |err| { freeOut(self.server.gpa, out); return err; }; } /// The writer task: take from the queue, seal and write, until the queue is /// closed and drained, or a write fails. pub fn writeLoop(self: *Connection) void { const io = self.server.io; const gpa = self.server.gpa; while (true) { const out = self.queue.getOneUncancelable(io) catch return; defer freeOut(gpa, out); self.write(out) catch |err| { if (!self.closed.swap(true, .acq_rel)) log.info("could not write to {s}: {t}", .{ self.hello.name, err }); // Wake the reader: the connection is over. self.session.shutdown(io); // Drop what is left, so that no putter waits. self.queue.close(io); }; } } fn write(self: *Connection, out: Out) !void { switch (out) { .text => |t| try self.writeText(t), .binary => |b| { self.server.traceBinary(.outbound, self.channel != null, b); if (self.channel) |*ch| { try ch.sealBinary(b, Frames{ .session = self.session }); } else try self.session.sendBinary(b); }, .time => |t| { var buf: [160]u8 = undefined; var w: Io.Writer = .fixed(&buf); try server_message.writeTime(&w, .{ .client_transmitted = t.client_transmitted, .server_received = t.server_received, .server_transmitted = Server.now(), }); try self.writeText(w.buffered()); }, .close => { self.session.ws.close(.normal, "") catch {}; self.session.shutdown(self.server.io); }, } } /// Write a text message now, sealed on a sealed connection. For the /// writer task, and for the handshake before it starts. pub fn writeText(self: *Connection, text: []const u8) !void { self.server.traceText(.outbound, self.channel != null, text); if (self.channel) |*ch| { try ch.sealText(text, Frames{ .session = self.session }); } else try self.session.sendText(text); } const Frames = struct { session: *Session, pub fn frame(sink: @This(), bytes: []const u8) !void { try sink.session.sendBinary(bytes); } }; /// Stop sending: nothing more is queued, and the writer finishes what is. pub fn close(self: *Connection) void { _ = self.closed.swap(true, .acq_rel); self.queue.close(self.server.io); }