// SPDX-FileCopyrightText: © 2012 Salvatore Sanfilippo // SPDX-FileCopyrightText: © 2014-2021 Oliver Jowett // SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: GPL-2.0-or-later //! Handing messages on to whatever is listening. //! //! A receiver is rarely the end of the line. What it decodes goes to an //! aggregator, a map, a multilateration server, another copy of this program //! — usually several at once, each wanting a different format. So each output //! is a *service*: a port to listen on, a way of writing a message, and //! however many connections happen to be attached. //! //! Upstream does all of this in one thread, driven by `select`, because it //! has to interleave with the demodulator. Here each connection is a task: //! the decoder appends bytes to a connection's buffer and the connection's //! own task drains it to the socket. That means a slow reader blocks nothing //! but itself — and when its buffer fills, it is disconnected rather than //! allowed to stall the receiver, which is the one thing a receiver must //! never do. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const datetime = @import("datetime"); const adept_client = @import("adept.zig"); const log_mod = @import("log.zig"); const fifo = @import("fifo.zig"); const input = @import("input.zig"); const message = @import("message.zig"); const mode_s = @import("mode_s.zig"); const output = @import("output.zig"); const output_fatsv = @import("fatsv.zig"); const track = @import("track.zig"); const Message = message.Message; /// What a service speaks. pub const Protocol = enum { /// AVR text: a line of hex per frame. raw, /// Beast binary, with the frame as received and no filtering. beast_verbatim, /// Beast binary, with the frame as received, but only for frames this /// receiver heard itself. beast_verbatim_local, /// Beast binary, with corrections applied and doubtful frames held back. beast_cooked, /// The same, thinned: at most one message per aircraft per interval. beast_reduce, /// BaseStation comma-separated text. sbs, /// Stratux JSON, one object per message. stratux, /// FlightAware's tab-separated change feed. fatsv, /// How many there are, for the "render each one at most once" table. pub const count = @typeInfo(Protocol).@"enum".fields.len; /// Whether a reader on this protocol may send settings commands back. pub fn isBeast(self: Protocol) bool { return switch (self) { .beast_verbatim, .beast_verbatim_local, .beast_cooked, .beast_reduce => true, .raw, .sbs, .stratux, .fatsv => false, }; } /// The name shown when a connection is made or lost. pub fn description(self: Protocol) []const u8 { return switch (self) { .raw => "Raw TCP output", .beast_verbatim => "Beast TCP output (verbatim)", .beast_verbatim_local => "Beast TCP output (verbatim+local)", .beast_cooked => "Beast TCP output", .beast_reduce => "BeastReduce TCP output", .sbs => "BaseStation TCP output", .stratux => "Stratux TCP output", .fatsv => "FATSV TCP output", }; } /// What to send when nothing else has been sent for a while, so that a /// reader can tell a quiet receiver from a dead one. pub fn heartbeat(self: Protocol) []const u8 { return switch (self) { .raw => output.raw.heartbeat, .beast_verbatim, .beast_verbatim_local, .beast_cooked, .beast_reduce => &output.beast.heartbeat, .sbs => output.sbs.heartbeat, .stratux => output.stratux.heartbeat, // The format has no keepalive, and a consumer parsing lines // would have to be taught to ignore one. .fatsv => "", }; } }; /// How long a connection may go without anything to say before a heartbeat /// is sent, and how long output may sit in a buffer before it is written. pub const default_heartbeat_interval_ms = 60_000; pub const default_flush_interval_ms = 500; pub const default_flush_size = 1300; /// The most output that may be held back waiting for the buffer to fill. /// Upstream's own limit, and what `--net-ro-size` is clamped to. pub const max_flush_size = 16 * 1024 - 256; /// ...and the longest it may be held. Upstream's ceiling on /// `--net-ro-interval`. pub const max_flush_interval_ms = 60_000; /// How long shutdown waits for the attached readers to be sent whatever was /// still buffered for them. pub const drain_timeout_ms = 2_000; /// How much unwritten output a connection may accumulate before it is /// dropped. /// /// This is a backstop against a reader that has stopped reading altogether, /// not a rate limit: a single pass of the decoder can hand over every /// message in a block at once, and the Stratux format turns each of those /// into a few hundred bytes, so a bound of a few kilobytes would disconnect /// a perfectly healthy reader on the first busy second. Upstream has no /// equivalent because it writes from the decoding thread and drops a client /// the moment one write comes up short; here the writing is somebody else's /// task, and the buffer between them is what has to be bounded. pub const max_pending_bytes = 1 << 20; /// How long a reduced Beast feed waits before forwarding an aircraft again. /// /// readsb's default, and what the aggregators expecting this format are /// tuned for. pub const default_reduce_interval_ms = 125; /// Somewhere to push output to, rather than wait to be asked for it. /// /// The aggregators that do not ship a client of their own expect a receiver /// to dial *them* and push a Beast stream. Upstream cannot do this at all — /// its one outward-dialling function is used only by `faup1090` and /// `view1090`, never by `dump1090` — so this is the first place the port /// goes beyond what it was ported from. pub const Connector = struct { /// The host to dial. Borrowed; it must outlive the server. host: []const u8, port: u16, /// What to send once connected. protocol: Protocol, /// The identifier some aggregators use to recognise a feed, sent once on /// connecting. Only `beast_reduce_plus_out` carries one, which is the /// whole difference between it and `beast_reduce_out`. uuid: ?[]const u8 = null, /// How long to wait before dialling again, and the ceiling that backoff /// climbs to. A feed that is refused should not hammer the far end, and /// one that drops should come back quickly. pub const retry_initial_ms = 5_000; pub const retry_max_ms = 60_000; }; /// Milliseconds on the monotonic clock, which is what the output pacing is /// measured against: a wall clock that steps sideways must not turn into a /// flurry of heartbeats or an hour without one. fn millis(io: Io) u64 { const now = Io.Timestamp.now(io, .awake); return @intCast(@divTrunc(now.nanoseconds, std.time.ns_per_ms)); } /// What an input protocol speaks. pub const InputProtocol = enum { /// AVR text, a line per frame. raw, /// Beast binary. beast, pub fn description(self: InputProtocol) []const u8 { return switch (self) { .raw => "Raw TCP input", .beast => "Beast TCP input", }; } }; /// Something that arrived over the network and has yet to be decoded. pub const Inbound = union(enum) { /// A frame somebody else received. frame: struct { frame: input.Frame, /// When it reached us, which is the best arrival time we have: the /// sender's clock is its own and means nothing here. arrived_ms: u64, }, /// A Radarcape saying where it is. receiver_position: input.beast.Position, }; /// Frames waiting for the decoding task to pick them up. /// /// The decoder and the tracker belong to one task, so network readers cannot /// call into them; they leave frames here instead, and the decoding task /// drains the queue between blocks of samples. Bounded, because a peer that /// floods should be dropped rather than allowed to exhaust memory. pub const InboundQueue = struct { gpa: Allocator, mutex: Io.Mutex = .init, items: std.ArrayList(Inbound) = .empty, /// How many frames were dropped for want of room, for the statistics. dropped: u64 = 0, /// About a second's worth of a very busy feed. pub const capacity = 4096; pub fn deinit(self: *InboundQueue) void { self.items.deinit(self.gpa); } pub fn push(self: *InboundQueue, io: Io, item: Inbound) void { self.mutex.lockUncancelable(io); defer self.mutex.unlock(io); if (self.items.items.len >= capacity) { self.dropped += 1; return; } self.items.append(self.gpa, item) catch { self.dropped += 1; }; } /// Hand the queued items to `into`, emptying the queue. pub fn drain(self: *InboundQueue, io: Io, into: *std.ArrayList(Inbound)) void { self.mutex.lockUncancelable(io); defer self.mutex.unlock(io); std.mem.swap(std.ArrayList(Inbound), into, &self.items); } }; /// One input: a port, a protocol, and the readers attached to it. pub const InputService = struct { gpa: Allocator, protocol: InputProtocol, server: *Server, listener: Io.net.Server, port: u16, }; /// One attached reader. pub const Connection = struct { gpa: Allocator, stream: Io.net.Stream, service: *Service, /// Guards `pending` and `state`. mutex: Io.Mutex = .init, /// Bumped whenever there is something new to write, or the connection is /// being closed. epoch: std.atomic.Value(u32) = .init(0), /// Bytes waiting to go out. pending: std.ArrayList(u8) = .empty, /// Set when the connection should stop. closing: bool = false, /// Set when the reader could not keep up and was dropped for it. overflowed: bool = false, /// What this reader is currently being sent, as a `Protocol` tag. /// /// It belongs to the connection rather than to the service because a /// Beast reader can change its mind at any time by sending a settings /// command back up the connection. wants: std.atomic.Value(u8), /// Whether this reader asked for frames as received rather than as /// corrected, and whether it asked for only what this receiver heard /// itself. Touched only by the connection's own command task. verbatim_requested: bool = false, local_requested: bool = false, /// Whether it asked for Mode A/C. Read across connections when the /// global setting is recomputed, so it is atomic. modeac_requested: std.atomic.Value(bool) = .init(false), /// How many tasks are still using this connection. A Beast reader has /// two — one writing to it, one listening for its settings commands — /// and the last one out closes the socket and frees the connection. tasks: std.atomic.Value(u8) = .init(1), /// What this reader is currently being sent. pub fn protocol(self: *const Connection) Protocol { return @enumFromInt(self.wants.load(.acquire)); } fn setProtocol(self: *Connection, wanted: Protocol) void { self.wants.store(@intFromEnum(wanted), .release); } /// Note that one of this connection's tasks has finished, and clean up /// once they all have. fn release(self: *Connection, io: Io) void { if (self.tasks.fetchSub(1, .acq_rel) != 1) return; const service = self.service; service.detach(io, self); // The connection is gone now, so what it was asking for no longer // counts towards whether Mode A/C is decoded. service.server.autosetModeAc(io); } /// Append bytes to be written. Called from the decoding task. /// /// Silently drops the connection if it has fallen too far behind: the /// alternative is to block the receiver on a reader that has stopped /// reading, and samples do not wait. fn append(self: *Connection, io: Io, bytes: []const u8) void { self.mutex.lockUncancelable(io); defer self.mutex.unlock(io); if (self.closing) return; if (self.pending.items.len + bytes.len > max_pending_bytes) { self.overflowed = true; self.closing = true; self.wake(io); return; } self.pending.appendSlice(self.gpa, bytes) catch { self.closing = true; self.wake(io); return; }; self.wake(io); } fn wake(self: *Connection, io: Io) void { _ = self.epoch.fetchAdd(1, .release); io.futexWake(u32, &self.epoch.raw, std.math.maxInt(u32)); } /// Ask the connection to finish and go away. pub fn close(self: *Connection, io: Io) void { self.mutex.lockUncancelable(io); self.closing = true; self.mutex.unlock(io); self.wake(io); } /// The connection's own task: gather bytes, write them, repeat. /// /// Output is batched rather than written a message at a time, because a /// busy receiver decodes hundreds a second and a packet each would be /// absurd. A batch goes out as soon as it reaches `flush_size`, and in /// any case within `flush_interval_ms`; when nothing at all has been /// written for `heartbeat_interval_ms`, a heartbeat goes instead, so /// that a reader can tell a quiet receiver from a dead one. fn run(self: *Connection, io: Io) void { var buffer: [8192]u8 = undefined; var writer = self.stream.writer(io, &buffer); const options = self.service.server.options; var chunk: std.ArrayList(u8) = .empty; defer chunk.deinit(self.gpa); var batch: std.ArrayList(u8) = .empty; defer batch.deinit(self.gpa); var last_write_ms = millis(io); while (true) { const seen = self.epoch.load(.acquire); self.mutex.lockUncancelable(io); const closing = self.closing; std.mem.swap(std.ArrayList(u8), &chunk, &self.pending); self.mutex.unlock(io); if (chunk.items.len > 0) { batch.appendSlice(self.gpa, chunk.items) catch { self.overflowed = true; break; }; chunk.clearRetainingCapacity(); } const now = millis(io); const full = batch.items.len >= options.flush_size; const overdue = now -| last_write_ms >= options.flush_interval_ms; if (batch.items.len > 0 and (full or overdue or closing)) { writer.interface.writeAll(batch.items) catch break; writer.interface.flush() catch break; batch.clearRetainingCapacity(); last_write_ms = now; } if (closing) break; // Sleep until the next thing is due: either the batch's flush // deadline, or the heartbeat's. Whichever is nearer. const wait_ms = deadline: { var soonest: u64 = std.math.maxInt(u64); if (batch.items.len > 0) { soonest = @min(soonest, (last_write_ms + options.flush_interval_ms) -| now); } if (options.heartbeat_interval_ms != 0) { soonest = @min(soonest, (last_write_ms + options.heartbeat_interval_ms) -| now); } // Nothing buffered and no heartbeats: wait to be poked. if (soonest == std.math.maxInt(u64)) break :deadline max_flush_interval_ms; break :deadline @max(soonest, 1); }; io.futexWaitTimeout(u32, &self.epoch.raw, seen, .{ .duration = .{ .raw = .fromMilliseconds(@intCast(@min(wait_ms, std.math.maxInt(i64)))), .clock = .awake, } }) catch {}; // A heartbeat is due when nothing has been written for long // enough, whatever woke us. if (options.heartbeat_interval_ms != 0 and batch.items.len == 0) { const then = millis(io); if (then -| last_write_ms >= options.heartbeat_interval_ms) { writer.interface.writeAll(self.service.protocol.heartbeat()) catch break; writer.interface.flush() catch break; last_write_ms = then; } } } // Wake the command task, if there is one, by making its read end. _ = self.stream.shutdown(io, .both) catch {}; self.release(io); } /// A Beast reader's other task: listen for the settings commands it may /// send back up the connection. /// /// This is how a reader asks for Mode A/C, or for frames as received /// rather than as corrected, without reconnecting to a different port. fn commandLoop(self: *Connection, io: Io) void { var socket_buffer: [256]u8 = undefined; var reader = self.stream.reader(io, &socket_buffer); while (true) { const consumed = self.consumeCommands(io, reader.interface.buffered()); if (consumed > 0) { reader.interface.toss(consumed); continue; } reader.interface.fillMore() catch break; } self.release(io); } /// Take whole Beast settings commands from the front of `bytes`, /// returning how many bytes were used. /// /// A command is `0x1a`, `'1'`, and a letter. Anything else is skipped a /// byte at a time, which is what upstream does with the garbage a /// confused client sends. fn consumeCommands(self: *Connection, io: Io, bytes: []const u8) usize { var offset: usize = 0; while (std.mem.indexOfScalarPos(u8, bytes, offset, 0x1a)) |start| { if (start + 2 >= bytes.len) { // The rest of the command has yet to arrive. Anything before // the escape is garbage and can go. return start; } if (bytes[start + 1] != '1') { offset = start + 1; continue; } self.handleCommand(io, bytes[start + 2]); offset = start + 3; } // Whatever is left holds no escape, so it is garbage too. return bytes.len; } fn handleCommand(self: *Connection, io: Io, command: u8) void { switch (command) { 'j', 'J' => { self.modeac_requested.store(command == 'J', .release); self.service.server.autosetModeAc(io); }, 'v', 'V' => { self.verbatim_requested = command == 'V'; self.applySettings(); }, 'l', 'L' => { self.local_requested = command == 'L'; self.applySettings(); }, // Upstream recognises no others and ignores them. else => {}, } } fn applySettings(self: *Connection) void { self.setProtocol(if (self.local_requested) .beast_verbatim_local else if (self.verbatim_requested) .beast_verbatim else .beast_cooked); } }; /// One output: a protocol, whatever is listening on it, and whoever is /// attached. pub const Service = struct { gpa: Allocator, protocol: Protocol, server: *Server, /// The listening socket, if this service listens at all. It lives here, /// in an allocation that does not move, rather than in a list on the /// server: the accept task holds a pointer to it for as long as it runs. /// /// Null for a connector, which dials out instead of being dialled. listener: ?Io.net.Server = null, /// The port it ended up on, which is only interesting when the caller /// asked for port zero and let the kernel choose. port: u16 = 0, /// Where to dial, for a service that connects outward. connector: ?Connector = null, /// Guards `connections`. mutex: Io.Mutex = .init, connections: std.ArrayList(*Connection) = .empty, /// Whether anything is listening, so that formatting can be skipped when /// nothing would read it. pub fn hasConnections(self: *Service, io: Io) bool { self.mutex.lockUncancelable(io); defer self.mutex.unlock(io); return self.connections.items.len > 0; } fn attach(self: *Service, io: Io, connection: *Connection) Allocator.Error!void { self.mutex.lockUncancelable(io); defer self.mutex.unlock(io); try self.connections.append(self.gpa, connection); } fn detach(self: *Service, io: Io, connection: *Connection) void { self.mutex.lockUncancelable(io); for (self.connections.items, 0..) |candidate, i| { if (candidate == connection) { _ = self.connections.orderedRemove(i); break; } } self.mutex.unlock(io); connection.stream.close(io); connection.pending.deinit(connection.gpa); self.gpa.destroy(connection); } }; /// Where to listen, for each protocol that was asked for. pub const Options = struct { /// The address to bind to. Null binds to every interface. bind_address: ?[]const u8 = null, raw_port: ?u16 = null, beast_port: ?u16 = null, beast_verbatim_port: ?u16 = null, sbs_port: ?u16 = null, stratux_port: ?u16 = null, fatsv_port: ?u16 = null, /// Feeds to push output to, rather than wait to be asked for it. connectors: []const Connector = &.{}, /// How long a reduced Beast feed waits before forwarding an aircraft /// again. reduce_interval_ms: u64 = default_reduce_interval_ms, /// Ports to accept frames on. raw_input_port: ?u16 = null, beast_input_port: ?u16 = null, /// Whether Mode A/C is decoded to begin with. mode_ac: bool = false, /// Whether attached Beast readers get to decide that instead, by asking /// for Mode A/C or not asking for it. mode_ac_auto: bool = true, /// Whether Beast output defaults to passing frames on unaltered. verbatim: bool = false, /// Whether to pass multilateration results on to Beast readers. forward_mlat: bool = false, /// Whether raw output carries the receiver's clock. mlat_timestamps: bool = false, /// BaseStation formatting options. sbs: output.sbs.Options = .{}, /// FATSV formatting options. fatsv: output_fatsv.Options = .{}, /// How long a connection may be silent before a heartbeat is sent, or /// zero for no heartbeats at all. heartbeat_interval_ms: u64 = default_heartbeat_interval_ms, /// How long output may wait for company before it is written. Batching /// is what keeps a busy receiver from sending one packet per message. flush_interval_ms: u64 = default_flush_interval_ms, /// ...and how much output is enough to write without waiting. flush_size: usize = default_flush_size, }; /// All the output services, and the tasks running them. pub const Server = struct { gpa: Allocator, options: Options, /// The local timezone the BaseStation output stamps its lines with, or /// null to stamp them in UTC. zone: ?datetime.TimeZone, /// Where to say what the feeds are doing. A feeder that cannot say /// whether it is connected is very hard to trust. /// /// Shared with the decoding loop and the uplink, so it is a `Log` rather /// than a bare writer: several tasks report through it at once. log: ?*log_mod.Log = null, /// The FlightAware uplink, if one is configured. It is fed the same /// FATSV lines the `fatsv` port serves, because they are the same bytes: /// a track line is already an adept message. adept: ?*adept_client.Client = null, /// The gain the tuner is at, in decibels, which the Stratux output /// reports. Written by the decoding task, which is the only one that /// reads it. gain_db: f64 = 0, /// Whether Mode A/C is being decoded. It starts as `--modeac` said and /// is then recomputed from what the attached Beast readers ask for, /// unless `--no-modeac-auto` was given. mode_ac: std.atomic.Value(bool), services: std.ArrayList(*Service) = .empty, input_services: std.ArrayList(*InputService) = .empty, /// Frames that arrived over the network, waiting to be decoded. inbound: InboundQueue, group: Io.Group = .init, running: std.atomic.Value(bool) = .init(true), /// A scratch buffer for formatting one message, reused between calls. /// Only the decoding task uses it. scratch: [Protocol.count][output.stratux.max_packet_size]u8 = undefined, pub fn init(gpa: Allocator, options: Options, zone: ?datetime.TimeZone) Server { return .{ .gpa = gpa, .options = options, .zone = zone, .mode_ac = .init(options.mode_ac), .inbound = .{ .gpa = gpa }, }; } /// Start listening on every port that was configured. pub fn start(self: *Server, io: Io) !void { try self.listen(io, .raw, self.options.raw_port); try self.listen(io, if (self.options.verbatim) .beast_verbatim else .beast_cooked, self.options.beast_port); try self.listen(io, .beast_verbatim, self.options.beast_verbatim_port); try self.listen(io, .sbs, self.options.sbs_port); try self.listen(io, .stratux, self.options.stratux_port); try self.listen(io, .fatsv, self.options.fatsv_port); try self.listenInput(io, .raw, self.options.raw_input_port); try self.listenInput(io, .beast, self.options.beast_input_port); for (self.options.connectors) |connector| try self.connect(io, connector); } fn listen(self: *Server, io: Io, protocol: Protocol, port: ?u16) !void { const wanted = port orelse return; const listener = try self.bind(io, wanted); const service = try self.gpa.create(Service); service.* = .{ .gpa = self.gpa, .protocol = protocol, .server = self, .listener = listener, .port = boundPort(listener), }; try self.services.append(self.gpa, service); try self.group.concurrent(io, acceptLoop, .{ self, io, service }); } fn listenInput(self: *Server, io: Io, protocol: InputProtocol, port: ?u16) !void { const wanted = port orelse return; const listener = try self.bind(io, wanted); const service = try self.gpa.create(InputService); service.* = .{ .gpa = self.gpa, .protocol = protocol, .server = self, .listener = listener, .port = boundPort(listener), }; try self.input_services.append(self.gpa, service); try self.group.concurrent(io, inputAcceptLoop, .{ self, io, service }); } fn inputAcceptLoop(self: *Server, io: Io, service: *InputService) void { while (self.running.load(.acquire)) { const stream = service.listener.accept(io) catch break; self.group.concurrent(io, readLoop, .{ self, io, service.protocol, stream }) catch { stream.close(io); continue; }; } } /// One reader's task: pull bytes off the socket and turn them into /// frames. /// /// The reader's own buffer does the reassembly: a frame that arrives in /// two pieces simply stays buffered until `fillMore` brings the rest. /// The buffer is far larger than the longest frame either format can /// produce, so nothing can be stuck for want of room. fn readLoop(self: *Server, io: Io, protocol: InputProtocol, stream: Io.net.Stream) void { defer stream.close(io); var socket_buffer: [8192]u8 = undefined; var reader = stream.reader(io, &socket_buffer); while (self.running.load(.acquire)) { const available = reader.interface.buffered(); const consumed = switch (protocol) { .beast => self.consumeBeast(io, available), .raw => self.consumeLines(io, available), }; if (consumed > 0) { reader.interface.toss(consumed); continue; } // Nothing complete yet. Wait for more, and give up when the peer // goes away. reader.interface.fillMore() catch break; } } /// Take whole Beast frames from the front of `bytes`, returning how many /// bytes were used. fn consumeBeast(self: *Server, io: Io, bytes: []const u8) usize { var offset: usize = 0; while (offset < bytes.len) { const parsed = input.beast.parse(bytes[offset..], self.mode_ac.load(.acquire)); if (parsed.consumed == 0) break; // wait for more offset += parsed.consumed; if (parsed.frame) |frame| self.inbound.push(io, .{ .frame = .{ .frame = frame, .arrived_ms = nowMillis(io), } }); if (parsed.position) |position| self.inbound.push(io, .{ .receiver_position = position }); } return offset; } /// Take whole lines from the front of `bytes`, returning how many bytes /// were used. fn consumeLines(self: *Server, io: Io, bytes: []const u8) usize { var offset: usize = 0; while (std.mem.indexOfScalarPos(u8, bytes, offset, '\n')) |end| { const line = bytes[offset..end]; offset = end + 1; if (input.avr.parse(line, self.mode_ac.load(.acquire))) |frame| { self.inbound.push(io, .{ .frame = .{ .frame = frame, .arrived_ms = nowMillis(io), } }); } } return offset; } fn bind(self: *Server, io: Io, port: u16) !Io.net.Server { const address: Io.net.IpAddress = if (self.options.bind_address) |text| try .parse(text, port) else .{ .ip4 = .unspecified(port) }; return Io.net.IpAddress.listen(&address, io, .{ .reuse_address = true }); } /// Add a service that dials out rather than waiting to be dialled. fn connect(self: *Server, io: Io, connector: Connector) !void { const service = try self.gpa.create(Service); service.* = .{ .gpa = self.gpa, .protocol = connector.protocol, .server = self, .connector = connector, }; try self.services.append(self.gpa, service); try self.group.concurrent(io, connectLoop, .{ self, io, service }); } /// One connector's task: dial, push until the far end goes away, wait, /// dial again. /// /// The connection this makes is an ordinary `Connection`, so everything /// that renders and paces output treats a feed exactly like a reader that /// happened to connect to us. The difference is only in who dialled, and /// that this task is also the connection's writing task rather than /// spawning one. fn connectLoop(self: *Server, io: Io, service: *Service) void { const connector = service.connector.?; var backoff: u64 = Connector.retry_initial_ms; // So that an unreachable feed says so once rather than every retry. var complained = false; while (self.running.load(.acquire)) { if (self.dialOnce(io, service, connector, &complained)) { // It connected and later dropped; come back quickly. backoff = Connector.retry_initial_ms; } else { backoff = @min(backoff * 2, Connector.retry_max_ms); } if (!self.running.load(.acquire)) break; Io.Timeout.sleep(fifo.millis(backoff), io) catch break; } } /// Connect to a connector's host, whether it is written as an address or /// as a name. fn dial(io: Io, connector: Connector) !Io.net.Stream { if (Io.net.IpAddress.parse(connector.host, connector.port)) |address| { return Io.net.IpAddress.connect(&address, io, .{ .mode = .stream }); } else |_| {} const name = try Io.net.HostName.init(connector.host); return name.connect(io, connector.port, .{ .mode = .stream }); } fn note(self: *Server, comptime format: []const u8, args: anytype) void { const l = self.log orelse return; l.print(format ++ "\n", args); } /// One attempt. Returns whether the connection was ever established. fn dialOnce(self: *Server, io: Io, service: *Service, connector: Connector, complained: *bool) bool { // A literal address is used as it stands; anything else is a name to // look up. `HostName.connect` resolves and dials in one, trying every // address the name has and taking the first that answers, which is // what a feed behind several servers needs. var stream = dial(io, connector) catch |err| { if (!complained.*) { self.note("feed {s}:{d}: {t}", .{ connector.host, connector.port, err }); complained.* = true; } return false; }; complained.* = false; self.note("feed {s}:{d}: connected, sending {s}", .{ connector.host, connector.port, @tagName(connector.protocol), }); const connection = self.gpa.create(Connection) catch { stream.close(io); return false; }; connection.* = .{ .gpa = self.gpa, .stream = stream, .service = service, .wants = .init(@intFromEnum(connector.protocol)), }; service.attach(io, connection) catch { stream.close(io); self.gpa.destroy(connection); return false; }; // Some aggregators identify a feed by an identifier sent once, before // any messages. It goes out ahead of everything else so that the far // end knows whose stream this is from the first frame. if (connector.uuid) |uuid| { var buffer: [64]u8 = undefined; var writer: Io.Writer = .fixed(&buffer); if (output.beast.writeUuid(&writer, uuid)) |_| { connection.append(io, writer.buffered()); } else |_| {} } // Runs until the far end goes away, then detaches and frees the // connection. Connection.run(connection, io); self.note("feed {s}:{d}: disconnected", .{ connector.host, connector.port }); return true; } fn acceptLoop(self: *Server, io: Io, service: *Service) void { // A connector has no listener; it is driven by `connectLoop` instead. const listener = if (service.listener) |*l| l else return; while (self.running.load(.acquire)) { const stream = listener.accept(io) catch break; const connection = self.gpa.create(Connection) catch { stream.close(io); continue; }; connection.* = .{ .gpa = self.gpa, .stream = stream, .service = service, .wants = .init(@intFromEnum(service.protocol)), // A reader that connected to a verbatim port has asked for // verbatim frames by doing so, and can still change its mind. .verbatim_requested = service.protocol == .beast_verbatim or service.protocol == .beast_verbatim_local, .local_requested = service.protocol == .beast_verbatim_local, }; service.attach(io, connection) catch { stream.close(io); self.gpa.destroy(connection); continue; }; // A Beast reader may talk back, so it gets a second task to // listen with. Count it before it starts: the writing task can // finish first, and must not free the connection underneath it. const listens = service.protocol.isBeast(); if (listens) _ = connection.tasks.fetchAdd(1, .acq_rel); self.group.concurrent(io, Connection.run, .{ connection, io }) catch { if (listens) _ = connection.tasks.fetchSub(1, .acq_rel); service.detach(io, connection); continue; }; if (listens) { self.group.concurrent(io, Connection.commandLoop, .{ connection, io }) catch { // The writing task has it now; just give the count back. connection.release(io); }; } } } /// Stop listening and disconnect everything. pub fn stop(self: *Server, io: Io) void { self.running.store(false, .release); // Closing the listening socket makes the accept in each task fail, // which is how it learns to stop. for (self.services.items) |service| { if (service.listener) |*listener| listener.deinit(io); } for (self.input_services.items) |service| service.listener.deinit(io); for (self.services.items) |service| { service.mutex.lockUncancelable(io); const attached = self.gpa.dupe(*Connection, service.connections.items) catch &.{}; service.mutex.unlock(io); defer if (attached.len > 0) self.gpa.free(attached); for (attached) |connection| connection.close(io); } // Wait for those connections to write what they were still holding // and detach. Output is batched, so at any moment up to half a // second of messages is sitting in a buffer, and cancelling the // tasks outright would throw the end of every run away. const deadline = millis(io) + drain_timeout_ms; while (millis(io) < deadline) { var draining = false; for (self.services.items) |service| { if (service.hasConnections(io)) { draining = true; break; } } if (!draining) break; Io.Timeout.sleep(fifo.millis(5), io) catch break; } self.group.cancel(io); } pub fn deinit(self: *Server, io: Io) void { for (self.services.items) |service| { service.connections.deinit(self.gpa); self.gpa.destroy(service); } self.services.deinit(self.gpa); for (self.input_services.items) |service| self.gpa.destroy(service); self.input_services.deinit(self.gpa); self.inbound.deinit(); _ = io; self.* = undefined; } /// Recompute whether Mode A/C is decoded from what the attached readers /// have asked for. /// /// Upstream does this when a client disconnects and when one sends a /// Mode A/C command, but not when one connects — so `--modeac` on its /// own survives only until the first reader comes and goes. That is odd /// enough to be worth saying out loud, and faithful. fn autosetModeAc(self: *Server, io: Io) void { if (!self.options.mode_ac_auto) return; var wanted = false; for (self.services.items) |service| { service.mutex.lockUncancelable(io); for (service.connections.items) |connection| { if (connection.modeac_requested.load(.acquire)) { wanted = true; break; } } service.mutex.unlock(io); if (wanted) break; } self.mode_ac.store(wanted, .release); } /// Hand a decoded message to every service that wants it. /// /// Called from the decoding task, once per message. pub fn queue(self: *Server, io: Io, mm: *const Message, aircraft: ?*track.Aircraft, now_ms: u64) void { const reliable = if (aircraft) |a| a.reliable else null; // Decided once for the message, not once per reader: the rate limit // belongs to the aircraft, not to whoever happens to be listening. const reduce = self.reduceForward(mm, aircraft); // Each format is rendered at most once, and only if somebody is // actually attached who wants it. Null means "not looked at yet"; // an empty slice means "looked at, and this message is not for it". var rendered: [Protocol.count]?[]const u8 = @splat(null); for (self.services.items) |service| { service.mutex.lockUncancelable(io); defer service.mutex.unlock(io); for (service.connections.items) |connection| { const protocol = connection.protocol(); const index = @intFromEnum(protocol); if (rendered[index] == null) { rendered[index] = self.render(protocol, mm, aircraft, reliable, now_ms, reduce); } const bytes = rendered[index].?; if (bytes.len > 0) connection.append(io, bytes); } } } /// Send whatever the FATSV output has to say about this message. /// /// Separate from `queue` because the format is a change feed: most of /// what it says comes from `writeFatsv` walking the tracker, and only /// the capability and resolution-advisory reports are forwarded as they /// arrive. pub fn queueFatsvEvent( self: *Server, io: Io, mm: *const Message, aircraft: ?*track.Aircraft, ) void { if (!self.wantsFatsv()) return; const a = aircraft orelse return; var buffer: [output_fatsv.max_line]u8 = undefined; var writer: Io.Writer = .fixed(&buffer); const wrote = output_fatsv.writeEvent(&writer, mm, a, self.options.fatsv) catch return; if (wrote) self.emitFatsv(io, writer.buffered()); } /// Walk the tracker and send a line for every aircraft that is due one. /// /// Called about once a second; each aircraft decides for itself whether /// enough has changed and enough time has passed. pub fn writeFatsv(self: *Server, io: Io, tracker: *track.Tracker, now_ms: u64) void { if (!self.wantsFatsv()) return; var iterator = tracker.aircraft.iterator(); while (iterator.next()) |entry| { var buffer: [output_fatsv.max_line]u8 = undefined; var writer: Io.Writer = .fixed(&buffer); const wrote = output_fatsv.writeAircraft(&writer, entry.value_ptr.*, now_ms, self.options.fatsv) catch continue; if (wrote) self.emitFatsv(io, writer.buffered()); } } /// Tell the FATSV readers where this receiver is, which is the one thing /// the format says about the receiver rather than an aircraft. pub fn queueFatsvPosition( self: *Server, io: Io, latitude: f32, longitude: f32, altitude: f32, now_ms: u64, ) void { if (!self.wantsFatsv()) return; var buffer: [output_fatsv.max_line]u8 = undefined; var writer: Io.Writer = .fixed(&buffer); output_fatsv.writePositionUpdate(&writer, latitude, longitude, altitude, now_ms) catch return; self.emitFatsv(io, writer.buffered()); } fn fatsvService(self: *Server) ?*Service { for (self.services.items) |service| { if (service.protocol == .fatsv) return service; } return null; } /// Whether anything is listening for tracks, over a port or over the /// uplink. Generating them is not free, so it is not done for nobody. fn wantsFatsv(self: *Server) bool { return self.adept != null or self.fatsvService() != null; } /// Hand one track line to everything that wants it. fn emitFatsv(self: *Server, io: Io, bytes: []const u8) void { if (self.fatsvService()) |service| self.broadcast(io, service, bytes); if (self.adept) |client| client.submit(io, bytes); } /// Give every reader on one service the same bytes. fn broadcast(self: *Server, io: Io, service: *Service, bytes: []const u8) void { _ = self; if (bytes.len == 0) return; service.mutex.lockUncancelable(io); defer service.mutex.unlock(io); for (service.connections.items) |connection| connection.append(io, bytes); } /// Whether a message carries something about where the aircraft is or /// what it is doing, as against who it is or what it can do. /// /// The distinction is the reduced feed's: state is worth sending often, /// everything else rarely. fn carriesState(mm: *const Message) bool { return mm.cpr != null or mm.altitude_baro != null or mm.altitude_geom != null or mm.gs != null or mm.ias != null or mm.tas != null or mm.heading != null or mm.baro_rate != null or mm.geom_rate != null; } /// Whether this message should go out on the reduced Beast feed. /// /// One timer per aircraft: a message goes out if that aircraft has not /// been forwarded within the interval, and a message carrying nothing /// about the aircraft's state has to wait four times as long. /// /// This is the contract readsb documents, rather than a port of what /// readsb does — its own version keeps a timer per *field* and sorts /// fields into how often each deserves forwarding, threaded through an /// accept-data path this port has no equivalent of. The output is /// ordinary Beast either way, so the difference a consumer can observe /// is how much of it arrives, not what it looks like. fn reduceForward(self: *Server, mm: *const Message, aircraft: ?*track.Aircraft) bool { // Without a track there is nothing to rate-limit against, and a // message about no known aircraft is not worth a feed's bandwidth. const a = aircraft orelse return false; // Timed by when the message was received rather than by when this // runs. For a live receiver the two are the same; for a recording // played faster than real time they are not, and the clock would // throw away almost everything. const heard = mm.system_timestamp_ms; if (heard < a.reduce_next_forward_ms) return false; const interval = self.options.reduce_interval_ms; a.reduce_next_forward_ms = heard + if (carriesState(mm)) interval else interval * 4; return true; } /// Write one message in one format, or return nothing if that format /// does not want this message. fn render( self: *Server, protocol: Protocol, mm: *const Message, aircraft: ?*const track.Aircraft, reliable: ?bool, now_ms: u64, reduce: bool, ) []const u8 { var writer: Io.Writer = .fixed(&self.scratch[@intFromEnum(protocol)]); const wanted = switch (protocol) { .raw => blk: { if (!output.raw.shouldSend(mm, reliable)) break :blk false; output.raw.write(&writer, mm, self.options.mlat_timestamps) catch break :blk false; break :blk true; }, .beast_verbatim => blk: { if (!output.beast.shouldSendVerbatim(mm, self.options.forward_mlat)) break :blk false; output.beast.write(&writer, mm.timestamp_12mhz, mm.signal_level, mm.verbatimBytes()) catch break :blk false; break :blk true; }, .beast_verbatim_local => blk: { // Never anything somebody else heard. if (mm.remote) break :blk false; output.beast.write(&writer, mm.timestamp_12mhz, mm.signal_level, mm.verbatimBytes()) catch break :blk false; break :blk true; }, .beast_cooked, .beast_reduce => blk: { if (!output.beast.shouldSendCooked(mm, reliable, self.options.forward_mlat)) break :blk false; // The reduced feed sends the same bytes, just fewer of them. if (protocol == .beast_reduce and !reduce) break :blk false; output.beast.write(&writer, mm.timestamp_12mhz, mm.signal_level, mm.bytes()) catch break :blk false; break :blk true; }, .sbs => blk: { if (!output.sbs.shouldSend(mm, aircraft)) break :blk false; output.sbs.write(&writer, mm, aircraft.?, self.zone, now_ms, self.options.sbs) catch break :blk false; break :blk true; }, .stratux => blk: { if (!output.stratux.shouldSend(mm, aircraft)) break :blk false; output.stratux.write(&writer, mm, aircraft.?, self.gain_db) catch break :blk false; break :blk true; }, // Not a per-message format: its lines come from `writeFatsv`, // which walks the tracker, and from `queueFatsvEvent` for the // handful of messages it forwards whole. .fatsv => false, }; return if (wanted) writer.buffered() else &.{}; } }; const testing = std.testing; test "a reduced feed forwards an aircraft at most once an interval" { var server: Server = .init(testing.allocator, .{}, null); defer server.deinit(undefined); var a: track.Aircraft = .{ .address = 0x4840d6, .address_type = .adsb_icao }; var mm: Message = .empty; mm.format = .{ .mode_s = 17 }; // A position message: something worth sending often. mm.cpr = .{ .frame = .even, .type = .airborne, .encoded = .{ .latitude = 1, .longitude = 2 } }; mm.system_timestamp_ms = 1_000_000; try testing.expect(server.reduceForward(&mm, &a)); // Anything inside the interval is held back... mm.system_timestamp_ms = 1_000_050; try testing.expect(!server.reduceForward(&mm, &a)); mm.system_timestamp_ms = 1_000_124; try testing.expect(!server.reduceForward(&mm, &a)); // ...and the next one after it goes. mm.system_timestamp_ms = 1_000_125; try testing.expect(server.reduceForward(&mm, &a)); } test "a message saying nothing about the aircraft's state waits four times as long" { var server: Server = .init(testing.allocator, .{}, null); defer server.deinit(undefined); var a: track.Aircraft = .{ .address = 0x4840d6, .address_type = .adsb_icao }; var mm: Message = .empty; mm.format = .{ .mode_s = 17 }; // A callsign carries nothing about where the aircraft is or what it is // doing, so it is worth sending rarely. mm.callsign = "KLM1023 ".*; mm.system_timestamp_ms = 1_000_000; try testing.expect(server.reduceForward(&mm, &a)); mm.system_timestamp_ms = 1_000_499; try testing.expect(!server.reduceForward(&mm, &a)); mm.system_timestamp_ms = 1_000_500; try testing.expect(server.reduceForward(&mm, &a)); } test "one aircraft's rate limit does not hold back another" { var server: Server = .init(testing.allocator, .{}, null); defer server.deinit(undefined); var one: track.Aircraft = .{ .address = 0x111111, .address_type = .adsb_icao }; var two: track.Aircraft = .{ .address = 0x222222, .address_type = .adsb_icao }; var mm: Message = .empty; mm.format = .{ .mode_s = 17 }; mm.altitude_baro = .{ .value = 35000, .unit = .feet }; mm.system_timestamp_ms = 1_000_000; try testing.expect(server.reduceForward(&mm, &one)); try testing.expect(server.reduceForward(&mm, &two)); try testing.expect(!server.reduceForward(&mm, &one)); } test "a message about no known aircraft is not worth a feed's bandwidth" { var server: Server = .init(testing.allocator, .{}, null); defer server.deinit(undefined); var mm: Message = .empty; mm.format = .mode_ac; mm.system_timestamp_ms = 1_000_000; try testing.expect(!server.reduceForward(&mm, null)); } test "protocol descriptions and heartbeats" { try testing.expectEqualStrings("*0000;\n", Protocol.raw.heartbeat()); try testing.expectEqualStrings("\r\n", Protocol.sbs.heartbeat()); try testing.expectEqual(@as(usize, 11), Protocol.beast_cooked.heartbeat().len); try testing.expectEqualStrings("Raw TCP output", Protocol.raw.description()); } test "a server with nothing configured listens on nothing" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var server: Server = .init(testing.allocator, .{}, null); defer server.deinit(io); try server.start(io); try testing.expectEqual(@as(usize, 0), server.services.items.len); server.stop(io); } test "a message goes out to a connected reader" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var server: Server = .init(testing.allocator, .{ .raw_port = 0, .bind_address = "127.0.0.1" }, null); defer server.deinit(io); defer server.stop(io); try server.start(io); try testing.expectEqual(@as(usize, 1), server.services.items.len); // Port 0 means the kernel chose one; the service records which. const address: Io.net.IpAddress = try .parse("127.0.0.1", server.services.items[0].port); var stream = try Io.net.IpAddress.connect(&address, io, .{ .mode = .stream }); defer stream.close(io); // Wait for the accept loop to notice. var waited: usize = 0; while (!server.services.items[0].hasConnections(io) and waited < 500) : (waited += 1) { (Io.Timeout{ .duration = .{ .raw = .fromMilliseconds(10), .clock = .awake } }).sleep(io) catch {}; } try testing.expect(server.services.items[0].hasConnections(io)); var mm: Message = .empty; const frame = [_]u8{ 0x8d, 0x48, 0x40, 0xd6, 0x20, 0x2c, 0xc3, 0x71, 0xc3, 0x2c, 0xe0, 0x57, 0x60, 0x98 }; @memcpy(mm.msg[0..frame.len], &frame); mm.len = frame.len; mm.format = .{ .mode_s = 17 }; mm.reliable = true; server.queue(io, &mm, null, 0); var buffer: [128]u8 = undefined; var reader = stream.reader(io, &buffer); const line = try reader.interface.takeDelimiterInclusive('\n'); try testing.expectEqualStrings("*8D4840D6202CC371C32CE0576098;\n", line); } /// Wait for `condition` to come true, up to five seconds. Returns whether it /// did, so that a test can say what it was waiting for. fn waitFor(io: Io, context: anytype, condition: fn (@TypeOf(context)) bool) bool { var waited: usize = 0; while (waited < 500) : (waited += 1) { if (condition(context)) return true; (Io.Timeout{ .duration = .{ .raw = .fromMilliseconds(10), .clock = .awake } }).sleep(io) catch {}; } return condition(context); } test "a Beast reader can ask for Mode A/C, and change its mind" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var server: Server = .init(testing.allocator, .{ .beast_port = 0, .bind_address = "127.0.0.1" }, null); defer server.deinit(io); defer server.stop(io); try server.start(io); const service = server.services.items[0]; const address: Io.net.IpAddress = try .parse("127.0.0.1", service.port); var stream = try Io.net.IpAddress.connect(&address, io, .{ .mode = .stream }); defer stream.close(io); try testing.expect(waitFor(io, service, struct { fn f(s: *Service) bool { return s.connections.items.len > 0; } }.f)); try testing.expect(!server.mode_ac.load(.acquire)); var buffer: [64]u8 = undefined; var writer = stream.writer(io, &buffer); try writer.interface.writeAll(&.{ 0x1a, '1', 'J' }); try writer.interface.flush(); try testing.expect(waitFor(io, &server, struct { fn f(sv: *Server) bool { return sv.mode_ac.load(.acquire); } }.f)); try writer.interface.writeAll(&.{ 0x1a, '1', 'j' }); try writer.interface.flush(); try testing.expect(waitFor(io, &server, struct { fn f(sv: *Server) bool { return !sv.mode_ac.load(.acquire); } }.f)); } test "a Beast reader can switch itself to verbatim and back" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var server: Server = .init(testing.allocator, .{ .beast_port = 0, .bind_address = "127.0.0.1" }, null); defer server.deinit(io); defer server.stop(io); try server.start(io); const service = server.services.items[0]; try testing.expectEqual(Protocol.beast_cooked, service.protocol); const address: Io.net.IpAddress = try .parse("127.0.0.1", service.port); var stream = try Io.net.IpAddress.connect(&address, io, .{ .mode = .stream }); defer stream.close(io); try testing.expect(waitFor(io, service, struct { fn f(s: *Service) bool { return s.connections.items.len > 0; } }.f)); const connection = service.connections.items[0]; try testing.expectEqual(Protocol.beast_cooked, connection.protocol()); var buffer: [64]u8 = undefined; var writer = stream.writer(io, &buffer); // Verbatim, then verbatim and local, then all the way back. try writer.interface.writeAll(&.{ 0x1a, '1', 'V' }); try writer.interface.flush(); try testing.expect(waitFor(io, connection, struct { fn f(c: *Connection) bool { return c.protocol() == .beast_verbatim; } }.f)); try writer.interface.writeAll(&.{ 0x1a, '1', 'L' }); try writer.interface.flush(); try testing.expect(waitFor(io, connection, struct { fn f(c: *Connection) bool { return c.protocol() == .beast_verbatim_local; } }.f)); try writer.interface.writeAll(&.{ 0x1a, '1', 'l', 0x1a, '1', 'v' }); try writer.interface.flush(); try testing.expect(waitFor(io, connection, struct { fn f(c: *Connection) bool { return c.protocol() == .beast_cooked; } }.f)); } /// Wall-clock milliseconds, which is what a frame's arrival is recorded in. fn nowMillis(io: Io) u64 { const now = Io.Timestamp.now(io, .real); return @intCast(@divTrunc(now.nanoseconds, std.time.ns_per_ms)); } /// One frame's worth of the port number a service ended up on. fn boundPort(listener: Io.net.Server) u16 { return switch (listener.socket.address) { .ip4 => |ip4| ip4.port, .ip6 => |ip6| ip6.port, }; } test "frames sent to an input port come back out of the queue" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var server: Server = .init(testing.allocator, .{ .beast_input_port = 0, .bind_address = "127.0.0.1", }, null); defer server.deinit(io); defer server.stop(io); try server.start(io); try testing.expectEqual(@as(usize, 1), server.input_services.items.len); const address: Io.net.IpAddress = try .parse("127.0.0.1", server.input_services.items[0].port); var stream = try Io.net.IpAddress.connect(&address, io, .{ .mode = .stream }); // Two frames, written the way the output side writes them. var buf: [256]u8 = undefined; var w: Io.Writer = .fixed(&buf); const frame = [_]u8{ 0x8d, 0x48, 0x40, 0xd6, 0x20, 0x2c, 0xc3, 0x71, 0xc3, 0x2c, 0xe0, 0x57, 0x60, 0x98 }; try output.beast.write(&w, 1000, 0.5, &frame); try output.beast.write(&w, 2000, 0.5, &frame); var socket_buffer: [256]u8 = undefined; var stream_writer = stream.writer(io, &socket_buffer); try stream_writer.interface.writeAll(w.buffered()); try stream_writer.interface.flush(); var received: std.ArrayList(Inbound) = .empty; defer received.deinit(testing.allocator); var waited: usize = 0; while (received.items.len < 2 and waited < 500) : (waited += 1) { (Io.Timeout{ .duration = .{ .raw = .fromMilliseconds(10), .clock = .awake } }).sleep(io) catch {}; var drained: std.ArrayList(Inbound) = .empty; defer drained.deinit(testing.allocator); server.inbound.drain(io, &drained); try received.appendSlice(testing.allocator, drained.items); } stream.close(io); try testing.expectEqual(@as(usize, 2), received.items.len); try testing.expectEqualSlices(u8, &frame, received.items[0].frame.frame.bytes()); try testing.expectEqual(@as(u64, 1000), received.items[0].frame.frame.timestamp); try testing.expectEqual(@as(u64, 2000), received.items[1].frame.frame.timestamp); } test "the inbound queue drops rather than growing without bound" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var queue: InboundQueue = .{ .gpa = testing.allocator }; defer queue.deinit(); const item: Inbound = .{ .frame = .{ .frame = .{ .data = @splat(0), .len = 14, .timestamp = 0, .signal_level = 0 }, .arrived_ms = 0, } }; for (0..InboundQueue.capacity + 100) |_| queue.push(io, item); try testing.expectEqual(InboundQueue.capacity, queue.items.items.len); try testing.expectEqual(@as(u64, 100), queue.dropped); var drained: std.ArrayList(Inbound) = .empty; defer drained.deinit(testing.allocator); queue.drain(io, &drained); try testing.expectEqual(InboundQueue.capacity, drained.items.len); try testing.expectEqual(@as(usize, 0), queue.items.items.len); } /// An aircraft settled enough that the FATSV writer will emit a line for it. fn fatsvTestAircraft(now: u64) track.Aircraft { var a: track.Aircraft = .{ .address = 0x4840d6, .address_type = .adsb_icao, .reliable = true, .seen = now, .fatsv = .{ .last_emitted = now, .last_force_emit = now }, }; _ = a.altitude_baro.set(now, .adsb, 35000); _ = a.position.set(now, .adsb, .{ .position = .{ .latitude = 51.9, .longitude = 4.4 }, .nic = 8, .rc = 186, }); return a; } test "tracks reach the FlightAware uplink with no FATSV port configured" { // The wiring that makes `.flightaware` usable on its own. Generating // these lines used to be gated on a `fatsv` service existing, so a // receiver configured for the uplink and nothing else would have decoded // happily and sent nothing at all. var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var uplink: adept_client.Client = .{ .gpa = testing.allocator, .options = .{ .mac = "001122334455", .version = "test" }, }; defer uplink.deinit(); uplink.logged_in.store(true, .release); var server: Server = .init(testing.allocator, .{}, null); defer server.deinit(io); server.adept = &uplink; var tracker: track.Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); const now: u64 = 1_000_000; // Owned by the tracker, which destroys what it holds. const aircraft = try testing.allocator.create(track.Aircraft); aircraft.* = fatsvTestAircraft(now); try tracker.aircraft.put(testing.allocator, aircraft.address, aircraft); server.writeFatsv(io, &tracker, now + 10_000); try testing.expect(uplink.pending.items.len > 0); // What arrives is a FATSV line, unconverted, because that is already an // adept message. try testing.expect(std.mem.startsWith(u8, uplink.pending.items, "_v\t9E\tclock\t")); try testing.expect(std.mem.indexOf(u8, uplink.pending.items, "hexid\t4840D6\t") != null); } test "with nothing listening for tracks, none are generated" { // The other half of the gate: walking the tracker and rendering a line // per aircraft is not free, and a receiver feeding neither a FATSV port // nor FlightAware should not be paying for it. var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var server: Server = .init(testing.allocator, .{}, null); defer server.deinit(io); try testing.expect(!server.wantsFatsv()); var tracker: track.Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); const now: u64 = 1_000_000; const aircraft = try testing.allocator.create(track.Aircraft); aircraft.* = fatsvTestAircraft(now); try tracker.aircraft.put(testing.allocator, aircraft.address, aircraft); // The aircraft's own record of what was last said about it is untouched, // which is the observable proof nothing was rendered. const before = aircraft.fatsv.last_emitted; server.writeFatsv(io, &tracker, now + 10_000); try testing.expectEqual(before, aircraft.fatsv.last_emitted); } test "a decoded aircraft becomes a message FlightAware can parse" { // The two halves of the track path joined: real frames through the // decoder, into the tracker, out as FATSV, and into the uplink's queue as // something FlightAware's server can parse. Each half is tested on its // own — above, and in adept.zig — which is exactly why the join is worth // pinning: the seam between them is one field on `Server` that nothing // else would notice going stale. var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var decoder: mode_s.Decoder = try .init(testing.allocator, .{ .fix_bits = .one }); defer decoder.deinit(testing.allocator); var tracker: track.Tracker = .init(testing.allocator, .{}); defer tracker.deinit(); // The worked-example pair from aircraft 40:62:1D: one even and one odd // airborne position, which is the least that resolves a position and so // the least that gives FATSV something worth saying. const frames = [_][14]u8{ .{ 0x8d, 0x40, 0x62, 0x1d, 0x58, 0xc3, 0x82, 0xd6, 0x90, 0xc8, 0xac, 0x28, 0x63, 0xa7 }, .{ 0x8d, 0x40, 0x62, 0x1d, 0x58, 0xc3, 0x86, 0x43, 0x5c, 0xc4, 0x12, 0x69, 0x2a, 0xd6 }, }; const start: u64 = 1_000_000; for (frames, 0..) |frame, i| { var mm: Message = .empty; try mode_s.decode(&decoder, &mm, &frame); mm.system_timestamp_ms = start + i * 1_000; mm.reliable = true; _ = try tracker.update(&mm); } // It decoded as the aircraft it should have, and got a position out of // the pair — without which there would be nothing to forward. const aircraft = tracker.find(0x40621d).?; try testing.expect(aircraft.position.isValid(start + 1_000)); var uplink: adept_client.Client = .{ .gpa = testing.allocator, .options = .{ .mac = "001122334455", .version = "test" }, }; defer uplink.deinit(); uplink.logged_in.store(true, .release); var server: Server = .init(testing.allocator, .{}, null); defer server.deinit(io); server.adept = &uplink; // Far enough past the aircraft's first message that its turn has come. server.writeFatsv(io, &tracker, start + 60_000); // Parsed rather than searched: what is queued has to be a well-formed // adept message, which is a stronger claim than containing the right // substrings and is the one the far end actually depends on. try testing.expect(uplink.pending.items.len > 0); const line = std.mem.trimEnd(u8, uplink.pending.items, "\n"); var fields: [adept_client.max_fields]adept_client.Field = undefined; const parsed = try adept_client.parseLine(line, &fields); try testing.expectEqualStrings("9E", adept_client.find(parsed, "_v").?); try testing.expectEqualStrings("40621D", adept_client.find(parsed, "hexid").?); try testing.expect(adept_client.find(parsed, "clock") != null); // The position the two frames resolved to, carried through unchanged. const position = adept_client.find(parsed, "position").?; try testing.expect(std.mem.startsWith(u8, position, "{52.2")); }