Commit Graph
100 Commits
Author SHA1 Message Date
Audric f1d4afd032 fix(twin): deliver mirrored trunk audio to monitor-only twin clients
TwinLink::handleMsgPeerAudio and handleMsgPeerFlush broadcast to local
clients with a selected-only TgFilter, whereas the sibling receive paths
(TrunkLink, SatelliteLink, SatelliteClient) use the composite
selected-OR-(passive-observer monitor) filter. TwinLink was the lone
outlier — the bare filter was copied in when the trunk->twin mirror was
added (6a6cfad) without the monitor arbitration the other paths already had.

When a PAIRED external peer that OWNS a TG fans audio into a twin pair it
picks a single sticky socket, so the non-sticky twin only receives that
audio via the trunk->twin mirror. A monitor-only listener on the non-sticky
twin was silently dropped, while a selecting listener there (and any
listener on the sticky twin, which gets the direct trunk path) heard fine.
Reported in the field on a 255/256 twin+single deployment: clients
monitoring the single peer's TG were silent on one twin and fine on the other.

- TwinLink::handleMsgPeerAudio / handleMsgPeerFlush: use the same composite
  selected-OR-monitor filter as TrunkLink, preserving the passive-observer /
  earliest-monitor-talker arbitration.
- tests: test_X5_paired_inbound_owner_tg_reaches_monitoring_twin_clients —
  mirror image of test_X4 (TG owned by the remote PAIRED peer; selecting and
  monitoring receivers on both twins). Red before the fix, green after.
- topology.py: add two test users (N0FOUR, N0FIVE) so the test can place
  five distinct callsigns.
2026-05-24 12:03:53 +02:00
Audric b268bfe595 fix(trunk): guard inbound send paths against closed sockets; clean up on heartbeat timeout
A non-paired trunk link could abort the reflector (assert sock >= 0 in
AsyncTcpConnection::write) when an inbound peer was timed out by the
heartbeat. disconnect() closes the socket but does not emit the disconnected
signal, so onInboundDisconnected never runs and m_inbound_con /
m_ib_hello_received stay set. isInboundReady() then reports the dead link as
ready, and the next send — e.g. a MsgPeerTgInterest scheduled by a client
publishing its monitored-TG list — falls through to sendMsgOnInbound and
writes to the closed socket. Reproduces the production abort seen on v1.3.12;
TrunkLink is unchanged through v1.3.13.

- sendMsgOnInbound / isInboundReady: bail when the inbound socket is closed.
- inbound heartbeat timeout: drive the full cleanup (onInboundDisconnected +
  drop the dead connection from the reflector inbound map) so the link
  self-heals and /status is honest, instead of leaving a phantom inbound that
  makes acceptInboundConnection reject every reconnect until restart.
- defense in depth: same isConnected() guard on sendMsgOnOutbound and
  SatelliteLink::sendMsg (currently unreachable, but never write to a closed
  socket regardless).
- tests: test_46 (no crash on timeout + TG-interest send), test_47 (inbound
  recovers after a timeout).
2026-05-21 14:27:27 +02:00
Audric 8f00196821 warn when [SATELLITE] section is set on a satellite node
A satellite (SATELLITE_OF set) returns early from Reflector::initialize()
before initSatelliteServer() runs, so any [SATELLITE] block is silently
ignored. Child satellites then get connection-refused with nothing in
the parent's log explaining why. Emit a warn at startup so the misconfig
surfaces immediately.
2026-05-19 14:48:02 +02:00
Audric edd188b457 docs(topology): expand international mesh diagrams to 5 countries
- §1 (01_intl_mesh.dot): full mesh now includes ES (214), SE (240),
  DE (262), IT (222), UA (255) — 5-node pentagon with 10 edges.
- §2 (02_flat_mesh.dot): international side likewise widened to the
  5-country full mesh; IT 222 stays as the rightmost gateway vertex.
  National-side Zones spread into a 2x2 block mirroring the
  international layout so the 10 national edges have room to breathe.
- ASCII art in TOPOLOGY_EXAMPLES.md §1 and §2 updated to match.
- TOPOLOGY_EXAMPLES.pdf rebuilt via docs/build_topology_pdf.sh.
2026-05-17 13:26:21 +02:00
Audric de7e4648ea docs: add MCC country-codes reference; MCC-anchor remaining bare prefix examples
- New docs/MCC_COUNTRY_CODES.md: 25-country table with ISO codes and
  MCC(s), notes on countries with multiple MCC allocations, and a
  pointer to the ITU-T E.212 source for everything else.
- INSTALL.md §6a/6b: replace toy single-digit LOCAL_PREFIX/REMOTE_PREFIX
  examples with MCC-anchored ones (LOCAL_PREFIX=262, REMOTE_PREFIX=240,
  TRUNK_DE_SE) plus a cross-reference to the new MCC table.
- DESIGN_SATELLITE_AND_CLUSTER.md: MCC-anchor the two stale config
  snippets (LOCAL_PREFIX 01->22201, REMOTE_PREFIX 02->22202) so the
  historical design doc no longer teaches the bare-regional-digit
  anti-pattern.
2026-05-17 13:26:15 +02:00
Audric 61aafc1c0c docs(italy): MCC-prefix LOCAL_PREFIX and REMOTE_PREFIX with 222
Bare 2-digit regional codes (e.g. LOCAL_PREFIX=01) carried no country
namespace and would collide with any other country picking the same
regional digits. Prefix every LOCAL_PREFIX and REMOTE_PREFIX with the
Italy MCC (222), so each value sits inside the 222 prefix space
(e.g. Lazio = 22201, Lombardia = 22221). Section names
[TRUNK_xx_yy] and SECRET=IT_xx_yy keep the 2-digit form as readable
identifiers — only the prefix values themselves are MCC-anchored.
Inventory table, prose explanation, complete Lazio config block,
per-region checklist, and the parallel Italian translation all
updated in lockstep.
2026-05-17 11:14:11 +02:00
Audric a9691cdf4e docs: remove handoff doc — contained third-party private chat 2026-05-17 10:56:45 +02:00
Audric f9bd1bd3cf docs: drop stale provenance line from monitor-tg handoff doc 2026-05-17 10:55:15 +02:00
Audric 28525b03d5 docs(satellite): document per-id SECRET_<id>= across deployment and design docs
- WW_DEPLOYMENT.md, DEPLOYMENT_ITALY.md (+ IT translation): add the
  per-id SECRET_<id>= snippet alongside the existing single-secret
  example so operators see both forms.
- TOPOLOGY_EXAMPLES.md: rewrite the obsolete 'future work:
  per-satellite secrets' callout in §3 to reflect the shipped feature;
  touch up §4 reference to the parent's SECRET.
- DESIGN_SATELLITE_AND_CLUSTER.md: preserve the original design body;
  add a brief postscript pointing readers to the per-id form in the
  README.
2026-05-17 10:55:13 +02:00
Audric a679ab28db docs(satellite): document per-id SECRET_<id>= in README 2026-05-17 02:24:37 +02:00
Audric d757384c9c fix(satellite): defer heartbeat until auth; reject hello triggers cleanup
SatelliteLink's heartbeat timer was constructed with the default
enabled=true, so it started ticking at connect time. When a hello was
rejected, m_con->disconnect() closed the socket but the timer kept
running; at the t=10s tx tick it called sendMsg, which hit
assert(sock >= 0) in TcpConnection::write and crashed the reflector.

TcpConnection::disconnect() intentionally does not emit the
disconnected signal (header comment), so the TcpServer's
clientDisconnected handler never ran -- the SatelliteLink stayed in
m_satellite_con_map with no path to cleanup. TrunkLink avoids this
by constructing its heartbeat with enabled=false and enabling it only
after auth (TrunkLink.cpp:197); SatelliteLink just missed the pattern.

Mirror TrunkLink: construct the heartbeat disabled, enable it after
successful authentication in handleMsgPeerHello. On all four rejection
branches, fire linkFailed(this) after m_con->disconnect() so the
existing onSatelliteLinkFailed -> processSatelliteCleanup path deletes
the leaked link.

Add test_rejection_does_not_crash_parent regression test that sends
a hello with a wrong-for-pinned-id secret, waits past the 10s
heartbeat threshold, and confirms /status still responds and shows
no phantom satellite entry.
2026-05-17 02:20:50 +02:00
Audric f51ead2d7b test(satellite): use dash in per-id satellite ids to match charset
Underscores are not in the configured per-id charset [A-Za-z0-9-]+,
so SECRET_SAT_PINNED= was correctly rejected as malformed at startup.
Switch SAT_PINNED -> SAT-PINNED (and same for SAT_UNPINNED) so the
test fixture matches the spec.
2026-05-17 02:19:13 +02:00
Audric c76802df2f docs(satellite): document per-id SECRET_<id>= in conf template 2026-05-17 01:13:01 +02:00
Audric 93c396eef9 feat(satellite): resolve secret per-id in MsgPeerHello handler 2026-05-17 01:04:25 +02:00
Audric 5ded17fd24 feat(satellite): add resolveSatelliteSecret helper 2026-05-17 00:58:43 +02:00
Audric d6110f91cb feat(satellite): parse per-id SECRET_<id>= entries in [SATELLITE] 2026-05-17 00:49:43 +02:00
Audric 0c23d5a627 test(satellite): drop unused HOST import in per-id test file 2026-05-17 00:43:47 +02:00
Audric c8e16de246 test(satellite): send rejection hello raw to avoid handshake() raise 2026-05-17 00:39:19 +02:00
Audric 02c220ab24 test(satellite): add failing per-id secret integration tests 2026-05-17 00:33:47 +02:00
Audric eeeefd5ad5 test(satellite): scaffold per-id secret topology entries 2026-05-17 00:06:37 +02:00
Audric 6a6cfadd95 fix(twin): mirror inbound trunk audio across the twin link
When an external PAIRED=1 peer transmits to a twin pair, it picks a
single sticky socket per transmission and sends every frame on it. The
sticky-selected twin's TrunkLink::handleMsgPeerAudio used to broadcast
locally and to satellites but never relayed to the partner twin — so
local clients on the non-sticky twin were deaf to the audio even though
the talker state was mirrored correctly. The satellite-receive path
already had the symmetric forwarder (forwardSatelliteRawAudioToTwin);
the trunk path was just missing it.

Add Reflector::forwardTrunkAudioToTwin and forwardTrunkFlushToTwin,
modelled on the satellite variants, and invoke them from
TrunkLink::handleMsgPeerAudio and handleMsgPeerFlush after the local +
satellite broadcasts. Loop safety: TwinLink::handleMsgPeerAudio does
not re-forward to trunks, so there is no echo back to the originating
peer. Requires the external peer to use PAIRED=1 with both twin
hostnames in a single section — two independent trunk sections would
defeat the source-trunk exclusion at the external owner and cause
duplicates/echo. The docs now flag PAIRED=1 as mandatory for this
topology.

Test: test_twin.py::test_X4_paired_inbound_reaches_both_twins drives a
refa client on TG 26201 and asserts both ref1 and ref2 receive audio
frames and flush. Also rewrite test_01_twin_handshake and
test_05_twin_wiring_no_errors to read /status.twin instead of scraping
a 120s docker-logs window — the previous form flaked when the mesh had
been up long enough for boot-time log lines to scroll off.
2026-05-14 19:37:44 +02:00
Audric ef42da52de docs(install): document config-dir override at build and runtime
Add a subsection to "Build" covering CMAKE_INSTALL_SYSCONFDIR for
baking a custom config directory into the binary (the common case:
-DCMAKE_INSTALL_SYSCONFDIR=/etc to read /etc/svxlink/svxreflector.conf),
the --config runtime override, and the full lookup order at startup.
2026-05-12 16:48:59 +02:00
Audric d5860ad1dc fix(reflector): restrict monitor-TG UDP audio to passive observers
A client with a non-zero selected TG must never receive UDP audio
for a monitored TG. svxlink's priority/auto-switch for monitor TGs
is driven by the TCP TalkerStart message; once svxlink decides to
switch, it sends MsgSelectTG and from then on the audio arrives via
the selected-TG arm of the fanout (TgFilter). The monitor arm is
only meaningful for passive observers (currentTG=0).

a661879 (v1.3.10) introduced the monitor arm to support passive
multi-hop monitoring, but gated it loosely. dc3a8c0 narrowed the
gate to "selected TG idle right now" — too eager, since a real
QSO has 0.5-3s inter-PTT gaps where the selected TG is talkerless.
5c585be added first-talker-wins on top, masking but not fixing
the leak. The net effect: while a user was mid-QSO on TG 9 with
TG 110 in MONITOR_TGS, TG 110 audio bled into the inter-PTT gaps
and was played by svxlink. Tragedy.

Replace SelectedTgIdleFilter with PassiveObserverFilter
(`m_current_tg == 0`) at all 9 UDP fanout sites in Reflector.cpp,
SatelliteClient.cpp, SatelliteLink.cpp, and TrunkLink.cpp.
EarliestMonitorTalkerFilter is retained — passive observers with
multiple monitor TGs still need first-talker-wins to avoid Opus
decoder mixing (test_44).

Tests:
- New test_45 pins down the contract: A select_tg=9,
  monitor_tgs=[110]; C continuously talks on 110; A receives zero
  TG 110 UDP frames. Fails on master, passes after fix.
- test_43 repurposed from "first-talker-wins for selected" (a
  property that should never have been asserted) to the
  multi-monitor variant of test_45.
- test_39/40/41/42/44 stay green by construction.

All suites: 48 trunk + 7 mqtt + 6 logging + 15 twin = 76/76.
2026-05-12 16:48:52 +02:00
Audric 5c585bebbc fix(reflector): first-talker-wins arbitration for multi-monitor TGs
dc3a8c0's SelectedTgIdleFilter closed the v1.3.10 mixing window only
when the listener's selected TG was busy. When the selected TG is
idle (or 0) and >=2 monitor TGs have simultaneous talkers, the filter
let every frame through and the single Opus decoder mixed them --
a configuration MONITOR_TGS=1++,9+,110,112 hits this whenever 110 and 112
overlap, since svxlink's priority logic stays on the prio-1 TG 9.

TGHandler now records a per-TG talker-start timestamp (local + trunk),
retained across talker-clear so the flush-fanout filter can still
identify the freshly-stopped TG. ReflectorClient gains
EarliestMonitorTalkerFilter(tg): returns true iff tg is the earliest-
started TG (local OR trunk) among the client's monitored set; ties
broken by smaller TG id. Wired alongside the existing
SelectedTgIdleFilter at all nine UDP fanout sites. The selected-TG
arm of the OR is untouched, so svxlink priority and the pre-v1.3.10
single-TG-at-a-time invariant both keep working.

Adds test_43 (selected idle + two simultaneous monitor talkers ->
only earliest delivered) and test_44 (same, passive observer).
test_39 and test_40-42 remain green; full test_trunk.py: 47/47.
2026-05-11 11:51:47 +02:00
Audric 93f0274b9e docs(peer-protocol): list type 129 in upstream-vs-fork file table 2026-05-10 23:29:56 +02:00
Audric 987353853c docs: refresh peer/twin protocol docs for recent fixes
PEER_PROTOCOL.md: UDP monitor-fanout filter is now gated by
SelectedTgIdleFilter (commit dc3a8c0).

TWIN_PROTOCOL.md: satellite-originated traffic now reaches the twin
partner via forwardSatellite*ToTwin (commit ace9da6).
2026-05-10 23:09:22 +02:00
Audric ace9da635b fix(twin): notify twin partner of satellite-originated talker traffic
SatelliteLink::handleMsgPeer{TalkerStart,TalkerStop,Audio,Flush} now
inform the twin partner the same way local-client TX already does
(Reflector.cpp:1433/1499/1662). Adds Reflector::forwardSatellite*ToTwin
helpers (one per event, guarded by m_twin_link != nullptr) that delegate
to TwinLink's existing onLocal* API; the satellite is presented to the
twin as a downstream-local talker, mirroring how it's already presented
to trunk peers via the parallel forwardSatellite*ToTrunks family.

Fixes issue #7. test_X3_satellite_tx_reaches_twin_partner (added in
the previous commit) now passes; full integration suite 73/73 green.
2026-05-10 22:48:49 +02:00
Audric 303186b083 test(twin): add test_X3 satellite TX → twin partner regression
Adds a TWIN integration test that fakes a satellite-client transmitting
through ref1's SatelliteLink and asserts the twin partner ref2's local
client receives the audio. Fails on current HEAD because the
SatelliteLink::handleMsgPeer* handlers never call m_twin_link — the
asymmetric counterpart to the existing local-client TX path that does
inform the twin (Reflector.cpp:1433/1499/1662). Issue #7.
2026-05-10 22:24:50 +02:00
Audric 66de2966d8 docs(reflector): handoff diagnosis for v1.3.10 monitor-TG audio mix bug
Verified-facts diagnostic doc for the audio mixing bug reported by
 2026-05-10 and fixed in dc3a8c0. Captures: the seven
UDP fanout sites a661879 widened (§2.1), TwinLink's bare-TgFilter
asymmetry (§2.2), TCP MsgTalkerStart/Stop OR-filter history (§2.3),
the symptom mechanism (§2.9), constraints driving the fix (§3),
and resolved verification questions (§4).
2026-05-10 21:22:10 +02:00
Audric dc3a8c018c fix(reflector): gate monitor TG UDP delivery on selected TG idle
Adds ReflectorClient::SelectedTgIdleFilter and wraps the TgMonitorFilter
arm at the seven UDP fanout sites that a661879 (v1.3.10) added it to.
Monitor-TG UDP audio is now delivered to a client only when its selected
TG has no active local or trunk talker; passive observers (currentTG=0)
keep receiving monitor UDP via a tg==0 short-circuit. svxlink's TCP
TalkerStart path and ++/+/plain priority logic are untouched.

Restores the pre-v1.3.10 single-TG-at-a-time invariant for selected-TG
clients while keeping test_39 (passive multi-hop) green. Adds test_40
(monitor-TG mixing regression), test_41 (priority switch via MsgSelectTG),
test_42 (passive observer sanity).
2026-05-10 19:50:05 +02:00
Audric 36d49fbbd6 test(reflector): add test_40 monitor-TG/selected-TG mixing regression
Reproduces the v1.3.10 bug reported 2026-05-10:
SELECT_TG=9 + MONITOR_TGS=[110] interleaves UDP audio when both
TGs have simultaneous talkers, garbling the single-decoder svxlink
client. Test fails on current HEAD; the next commit fixes it.
2026-05-10 19:08:01 +02:00
Audric e9bb1a9e2d fix(peer): heartbeat MsgPeerTgInterest re-sends to keep TTL alive
The 60 s heartbeat path was inheriting the skip-when-unchanged gate
from the 500 ms debounce path. Result: after the initial
edge-triggered advertisement, an idle reflector with a stable monitor
list would silently no-op every 60 s, the receiver's
m_peer_interested_tgs[tg] timestamp never got refreshed, and its
600 s TTL elapsed. A passive monitor would go deaf 10 minutes after
adding a foreign TG to monitoredTGs.

Split the two call sites: heartbeat passes force=true (always send),
debounce keeps force=false (skip when unchanged). The steady-state
heartbeat is one frame per trunk per minute, which is what the
receiver TTL needs.

Doc note in PEER_PROTOCOL.md was wrong (claimed both timers skipped
unchanged sends); corrected.

Affects v1.3.9; ship as v1.3.10.
2026-05-08 21:03:41 +02:00
Audric a6618790bb feat(peer): passive-monitor support via MsgPeerTgInterest
A node that has selected a TG without keying, or marked it in
monitoredTGs, never received any audio: peer interest was only
populated by talker activity, and the local UDP fanout filtered by
TgFilter alone (current TG match), ignoring monitor entries.

Adds:

- MsgPeerTgInterest (wire ID 129, peer_id + vector<uint32_t>) — each
  trunk peer advertises the union of its local clients' selected TG
  and monitoredTGs to peers whose prefix is the longest-prefix-match
  for the TG. Edge-triggered (500 ms debounce) on client connect /
  disconnect, MsgSelectTG, MsgTgMonitor, and trunk hello completion;
  60 s periodic refresh as a safety net, skipping when the outgoing
  set is unchanged. The receiver writes mapTgIn(tg) into
  m_peer_interested_tgs so the existing send-side gates
  (isPeerInterestedTG, shouldRelayInbound + forwardTrunkAudioToOther
  Trunks) deliver audio without requiring a PTT to bootstrap.

- Multi-hop propagation. Receivers re-advertise interest from other
  peers, prefix-filtered for the destination link and source-link
  excluded, so country-gateway-into-national-mesh layouts (§2)
  converge in one debounce per hop. Closes the gap where SE
  monitoring an Italian regional TG would never reach Z1 without
  IT 222 explicitly forwarding interest.

- TgMonitorFilter applied at every local UDP fanout (audio +
  MsgUdpFlushSamples) — Reflector::onUdpFrameReceived and the local
  talker stop, the trunk receive path, and both directions of the
  satellite mirror. Without this, the protocol-level interest
  arrives at the right reflector but stops at its UDP fanout — the
  passive monitor still hears nothing. Strict superset: no existing
  delivery path is removed.

Loop safety relies on filtering local-side MsgPeerTgInterest by
isSharedTG (same gate as audio fanout). Advertising to non-owner
peers would register ghost interest there, which gateway prefix
routing would then relay back across the mesh. Verified by
test_32_three_way_conversation (full mesh, no echo loops).

Tests: new test_39_passive_monitor_multihop covers the §2 chain
(SE-style monitor on a, talker on d, gateway b). All existing
tests pass: 42 trunk + 7 mqtt-deltas + 6 logging + 14 twin = 69/69.

Builds on the idea originally proposed in #4 by @sa2blv; the
single-hop and wire-ID-collision issues described in the close
comment are addressed in this rewrite.
2026-05-08 20:38:14 +02:00
Audric ccf34adbe6 feat(mqtt): add ts and duration_ms to talker start/stop events
Talker MQTT payloads now carry a Unix-epoch-ms `ts` field on both start
and stop. Stop additionally carries `duration_ms` whenever a matching
start was observed by the same MqttPublisher instance and the resulting
duration is non-negative. Both fields are additive — older consumers
that only read `callsign` continue to work unchanged.

Implementation
- MqttPublisher tracks per-(peer_id, tg) start_ms in a small std::map.
  Local talkers use peer_id="" as the map key. The entry is consumed on
  the matching stop.
- On stop, duration_ms is computed as `now - start_ms`. The field is
  omitted when:
  * no matching start was recorded (e.g. reflector restarted mid-talker)
  * the resulting duration is negative (backwards NTP correction during
    the transmission)
  Both edge cases are documented in docs/MQTT.md.
- Applies symmetrically across the four publish paths:
  onTalkerStart / onTalkerStop / onPeerTalkerStart / onPeerTalkerStop.

Tests
- test_trunk.py::test_18_mqtt_talker_event extended:
  * asserts `ts` is present on start, parses as int, lies within a
    +/- 60s window of the test's local clock.
  * asserts `ts` on stop is >= start ts.
  * asserts `duration_ms` on stop is present, >= the held-talker time
    (~500 ms), and equals stop_ts - start_ts.
- Edge-case behaviour (no-start, backwards clock jump) is guarded in
  code and documented; reaching it from the integration suite would
  require restarting the reflector mid-talker or injecting a clock
  step, so it is not asserted from outside.

Docs
- docs/MQTT.md: payload examples updated for both flat and
  peer-namespaced talker topics; new paragraph spelling out the two
  conditions under which duration_ms is omitted.
- docs/MESSAGING_IDEAS.md: Telegram-bot example extended to also
  handle /stop with a `duration_ms >= 1000` filter (kerchunk
  suppression) and a short note on how `ts`/`duration_ms` map to
  end-to-end pipeline latency and session length.
2026-05-07 17:02:39 +02:00
Audric 52b5e4f3cf feat(reflector): gateway prefix routing via shouldRelayInbound
A non-owner reflector with two trunk legs (a country gateway sitting
between an international mesh and a national mesh) now forwards inbound
trunk traffic toward the actual prefix owner — automatically, via
longest-prefix-match in its own [TRUNK_x] table. Cluster TGs keep their
deliberate single-hop semantic to prevent loops in cyclic meshes.

Implementation
- Reflector::shouldRelayInbound(tg) composes the inbound relay decision:
  * isLocalTG          -> fan out (existing owner-relay)
  * isClusterTG        -> stop (anti-loop; cluster TGs broadcast outbound
                                from local clients only)
  * hasPrefixRoute     -> gateway forwarding via per-trunk isSharedTG
- The four isLocalTG gates in TrunkLink::handleMsgPeer{TalkerStart,
  TalkerStop,Audio,Flush} are replaced by shouldRelayInbound. Source
  exclusion in forwardTrunk*ToOtherTrunks plus per-link interest
  tracking keep the topology naturally loop-free.

Tests
- topology.py: per-reflector `peers` filter for sparse layouts; new
  reflector `d` (prefix 1219, trunked only to `b`) demonstrating
  gateway-only reachability from `a` to `d`.
- generate_configs.py: honours the peers filter.
- test_trunk.py:
  * setUpClass and test_01 skip non-existent pairs in sparse layouts.
  * test_37_gateway_prefix_routing: a-client (122) <-> d-client (1219)
    over TG 121950 in both directions, no CLUSTER_TGS.
  * test_38_cluster_tg_local_client_broadcast: explicit coverage for
    the outbound local-client cluster broadcast path.
- All previously passing tests still pass: 41/41 trunk + 7/7
  mqtt-deltas + 14/14 twin.

Docs
- docs/TOPOLOGY_EXAMPLES.md (new) + .pdf + topology_pdf/ build sources +
  build_topology_pdf.sh: visual cookbook of the five topology shapes
  (international full-mesh, national mesh joined at gateway, satellite
  tree, hybrid satellite-under-regional, HA twin pair). Includes an
  MCC-range appendix with the recommendation to draw cluster TGs from
  100-199 / 800-999 to avoid country-prefix collisions.
- docs/PEER_PROTOCOL.md: rewrote the "Owner-Relay Fanout" section as
  "Inbound Relay (shouldRelayInbound)" with the three-regime
  composition and clarified the single-mesh fanout caveat.
- README.md: feature bullet now describes gateway prefix routing and
  links to TOPOLOGY_EXAMPLES.md (also added to the documentation list).
2026-05-07 16:12:14 +02:00
Audric 658a1b153f fix(peer): re-arm outbound TcpPrioClient after heartbeat RX timeout
When a heartbeat RX timeout fires on a peer link, heartbeatTick() calls
m_con.disconnect() to tear the connection down.  TcpPrioClient handles
that by transitioning its state machine to StateDisconnected, which has
no retry timer — only an explicit connect() advances it.  And manual
disconnect() does not emit the disconnected signal, so the listener-
based onDisconnected() path that *would* have retried is also bypassed.
Net effect: the outbound dial parks forever, and only a process restart
recovers the link.  This affected real-world TWIN deployments where
both peers' outbounds time out simultaneously and neither comes back.

Re-call connect() right after the timeout-driven disconnect at the three
sites: TwinLink::heartbeatTick (twin OB), TrunkLink::heartbeatTick (non-
paired OB), and TrunkLink::heartbeatTick (paired per-host OB).  Inbound
side does not need re-arming — it recovers when the partner's freshly-
re-armed outbound dials back in.

Add test_12_twin_heartbeat_recovery: docker pauses ref2 (cgroup freezer
keeps TCP alive while userspace stalls), waits for ref1's RX timeout
log, unpauses, and asserts /status.twin.outbound_connected flips back
to true.  Distinct from test_06 (SIGKILL → passive disconnect → already
worked).  Verified the test fails on the unpatched binary at Step 5
with the exact "StateDisconnected lockup regression" assertion.
2026-05-06 20:00:53 +02:00
Audric 2e1095e3da fix(mqtt): re-arm STATUS_INTERVAL timer with reset() instead of setEnable(true)
The periodic full-status republish was firing only once at startup. The
expiry lambda re-armed via m_mqtt_status_timer.setEnable(true), but
Async::Timer::setEnable() is guarded by `if (do_enable && !m_is_enabled)`
and m_is_enabled is never reset to false on expiry — so the call was a
no-op, the application erased the entry from its dispatch map, and the
timer never fired again regardless of STATUS_INTERVAL.

reset() does an unconditional delTimer+addTimer, which is what was
intended.

The pre-existing test_29_mqtt_full_status accepted ">=1 message, retained
or fresh", so the always-present retained snapshot from the very first
fire was enough to make it pass. New test_43_full_status_periodic_republish
filters out msg.retain==True and requires >=3 fresh publishes within a 4s
window with STATUS_INTERVAL=1000, plus an inter-arrival cadence check.
2026-04-30 01:58:09 +02:00
Audric d8df8cf70b fix: bump MAX_POSTAUTH_FRAME_SIZE 32 KiB -> 4 MiB
Twin and trunk peers were flapping every few minutes after v1.3.6 with
the symptom "Connection closed by remote peer" alternating with
"RX timeout, disconnecting".

Root cause: v1.3.6 extended MsgPeerNodeList (type 121) twice without
bumping the framed-tcp receive cap:
  - a3757ca added a per-client rich-status JSON blob (~1 KB/client)
  - 3d281e1 added a per-client sat_id vector

A reflector with even ~30 clients now produces a NodeList frame > 32 KiB,
which the receiver's Async::FramedTcpConnection::onDataReceived rejects
with DR_PROTOCOL_ERROR (closeConnection + onDisconnected). Both sides
reconnect, hello succeeds, the next NodeList tears the link down again.

Fix: raise the post-auth cap to 4 MiB. Comfortably fits thousands of
clients with rich status while keeping the receive-buffer ceiling
bounded against malicious oversized frames.

Lockstep upgrade: both sides of any twin/trunk pair must run a build
with the bumped constant. Mixed deployments still flap on the
unupgraded side until it's updated too.
2026-04-29 21:03:03 +02:00
Audric 7ebee2249b docs(satellite): KNOWN ISSUE note on tg=0 filter inconsistency
V2 clients authenticate with tg=0 (TG selection happens later via
select_tg), so SatelliteLink::sendClientConnected currently suppresses
every connect event when SATELLITE_FILTER is non-empty. The
fanoutClient{Disconnected,Rx,Status} paths in Reflector.cpp use
`tg == 0 || link->filterPassesTg(tg)` to default-allow — this method
should mirror that pattern.
2026-04-29 18:05:52 +02:00
Audric c19f7d7752 docs: peer-client liveness MQTT topics + protocol additions
- docs/MQTT.md: new peer/<id>/client/<call>/* topics, retained-rx
  migration, MQTT_NAME twin-mode requirement, retained-store
  growth note (housekeeping deferred per Task 11).
- docs/PEER_PROTOCOL.md: MsgPeerClient* types 125-128 with routing
  (satellite+twin only, not trunk).
- CLAUDE.md: refresh trunk/peer message overview to reflect rename
  and new types.
2026-04-29 17:50:31 +02:00
Audric db16676c16 test: integration coverage for peer-client liveness deltas
Adds tests for satellite-axis and twin-axis per-client deltas,
retained rx bootstrap on subscribe, 500ms debounce invariant,
SATELLITE_FILTER respect, trunk-peer absence of peer/+/client/+/*
topics, and MQTT_NAME twin-mode validation.

Snapshot-housekeeping coverage is deferred together with Task 11.
2026-04-29 17:26:22 +02:00
Audric 83bbfc4fab feat(reflector): require MQTT_NAME when twin-mode + MQTT both enabled
Two twin reflectors sharing a broker need disjoint MQTT subtrees;
MQTT_NAME is the per-reflector path component. Failing fast at
startup is better than silent retained-topic corruption when the
operator forgets to set it.
2026-04-29 16:46:23 +02:00
Audric f4bc684d7b feat(reflector): 500ms sender-side debounce on rx fanout
Caps peer/<id>/client/<call>/rx wire emit at 2Hz per local callsign,
preventing 50Hz native rx churn from saturating satellite/twin
links and the receiving brokers' retained store.

Local client/<call>/rx (also retained, on-broker only) is unaffected
— it carries the full native rate.
2026-04-28 21:16:40 +02:00
Audric b5b54cb8d6 feat(reflector): apply TG filter at fanout for events without inline TG
Disconnect, rx, and status messages don't carry a TG, so the sender
looks up the originating client's current TG via currentClientTg()
and tests it against each SatelliteLink's filter before emitting.
Connect events already have inline TG filtering inside
SatelliteLink::sendClientConnected.

If the lookup returns 0 (e.g. the client has just disconnected when
the fanout fires), default-allow rather than block — preserves the
event flow when the local client state is racing.

SatelliteClient and TwinLink have no filter today — they receive
unfiltered.
2026-04-28 20:57:54 +02:00
Audric 24a4bc98f9 feat(reflector): activate fanoutClient* across satellite+twin links
Replaces the no-op stubs from Task 4. Per-client liveness deltas
(MsgPeerClient{Connected,Disconnected,Rx,Status}) now flow over
satellite (parent->sat and sat->parent) and twin links. Trunk peers
are intentionally skipped — see spec §3 for the routing rationale.

Each receiving reflector republishes the events on its own MQTT
broker as peer/<peer_id>/client/<call>/<event>, retained for rx
and status, ephemeral for connect and disconnect.
2026-04-28 20:25:31 +02:00
Audric 6f407a5a77 feat(twin): add MsgPeerClient* send/receive on TwinLink
Twin pairs gain symmetric per-client liveness deltas — each twin's
broker now emits peer/<twin_id>/client/<call>/<event> for the other
twin's clients.

Also plumbs peer_id through TwinLink::handleMsgPeerTalkerStart
(switching from setTrunkTalkerForTG to setTrunkTalkerForTGViaPeer
with m_peer_id_config), closing the deferred fix from Task 6.5
and ensuring peer/<twin_id>/talker/<tg>/start fires correctly.
2026-04-28 20:11:47 +02:00
Audric 1bb847b3c8 fix(peer-client): plumb peer_id through Satellite talker paths
Satellite{Link,Client}::handleMsgPeerTalkerStart was calling
setTrunkTalkerForTG without recording peer_id, so the
trunkTalkerUpdated signal fired with peer_id="" and the new
peer/<id>/talker/<tg>/start MQTT topic became peer//talker/...
(malformed empty segment).

Use setTrunkTalkerForTGViaPeer with m_satellite_id / m_parent_id
so the topic is properly namespaced.

Also add a defensive early-return in MqttPublisher::onPeerTalker*
that logs a warning and skips the publish if peer_id is empty —
protects against future callers that emit signals without peer
attribution (e.g. TwinLink, addressed in Task 7).
2026-04-28 19:59:32 +02:00
Audric af746d7534 feat(mqtt): peer-namespaced talker topics
External (peer-side) talker events move from flat talker/<tg>/start
with is_trunk=true to peer/<peer_id>/talker/<tg>/start. Local-only
talker/<tg>/start retains today's behavior.

To carry peer_id through the signal path: add peer_id as a 4th
argument to TGHandler::trunkTalkerUpdated; reorder
clearTrunkTalkerForTG / clearTrunkTalkersForPeer / clearAllTrunkTalkers
so the signal fires before m_trunk_talker_peer_ids is erased;
pre-populate m_trunk_talker_peer_ids in setTrunkTalkerForTGViaPeer
before calling the inner setter; switch TrunkLink::handleMsgPeerTalkerStart
from setTrunkTalkerForTG to setTrunkTalkerForTGViaPeer.

Reasons: dashboards subscribing across the mesh can now use
peer/+/talker/+/start to enumerate peer talkers without parsing the
is_trunk payload flag, and the namespacing aligns with the new
peer/<peer_id>/client/<call>/* topics added in Tasks 5-6.
2026-04-28 19:45:08 +02:00
Audric 81672bae23 feat(satellite): add MsgPeerClient* send/receive on SatelliteClient
Satellite-side endpoint gains the symmetric send/receive paths so
that satellite-local client events propagate to the parent and the
parent's client events arrive at the satellite's broker.
2026-04-28 19:27:11 +02:00
Audric 11b1a7b518 feat(satellite): add MsgPeerClient* send/receive on SatelliteLink
Parent-side of the satellite link gains sendClient* (with TG-filter on
connect) and handleMsgPeerClient* (republishing to the local MQTT
broker as peer/<sat_id>/client/<call>/<event>, retained for rx/status).

A Reflector::mqtt() accessor was added to expose m_mqtt to link
classes for receive-side republishing.
2026-04-28 19:07:56 +02:00
Audric 37a6a11548 feat(reflector): fanoutClient* stubs + hook into MQTT emit points
Adds the dispatch surface for per-client liveness deltas. The fanout
methods are stubs in this commit — they will iterate satellite/twin
links once those gain sendClient* methods (Tasks 5-7).

Also wires the new local MQTT topic client/<call>/status (retained)
into Reflector::publishClientStatus so dashboards get rich status as
a per-client topic, not only via nodes/local.
2026-04-28 18:40:07 +02:00
Audric e25ae9caa1 feat(mqtt): add publishPeerClientEvent + onClientStatus, retain rx
- onRxUpdate now publishes client/<call>/rx as retained, so a fresh
  dashboard subscriber gets last-known rx on subscribe.
- onClientStatus is new: writes retained client/<call>/status from the
  rich per-client status blob (today only inside nodes/local).
- onClientDisconnected clears retained client/<call>/{rx,status}.
- publishPeerClientEvent / clearPeerClientRetained are receiver-side
  republish helpers for the new MsgPeerClient* messages.
2026-04-28 18:19:38 +02:00
Audric bc9b6e7b30 feat(proto): add MsgPeerClient{Connected,Disconnected,Rx,Status} (125-128)
Wire types for per-client liveness deltas. No call sites yet — emit
and dispatch added in subsequent commits.
2026-04-28 18:05:01 +02:00
Audric 18d92a2b11 refactor: rename MsgTrunk* -> MsgPeer*
The eight MsgTrunk* types flow over trunk, satellite, and twin links —
"Trunk" was a misleading prefix for what is actually a shared peer
protocol. Wire IDs (115-122) and field layouts are unchanged, so this
is wire-equivalent: a renamed reflector and an old reflector
interoperate identically.

Also renames docs/TRUNK_PROTOCOL.md -> docs/PEER_PROTOCOL.md.

Twin-only types MsgTwinExt* (123/124) stay as-is.
2026-04-28 18:00:24 +02:00
Audric 3d281e16d7 sat: full partner-node parity across reflector + satellites
Extends MsgTrunkNodeList (type 121) with a 7th vector `sat_ids` so a
parent reflector can advertise both its own clients (sat_id="") and
clients learned from each connected satellite (sat_id=<satellite_id>)
in a single message. The sat_id is recipient-relative — empty means
"on whoever sent this list" — so the same field is reused on the
trunk, twin and satellite paths without a global namespace.

Reflector::sendNodeListToAllPeers now builds a combined view (parent-
local + every connected satellite's stamped roster) and fans it out:
  - to trunks and twin: full combined list
  - to each satellite: combined minus that sat's own contribution,
    additionally filtered by SATELLITE_FILTER (self-echo guard +
    audio-path scoping)
  - up to the parent (when running as a satellite): local clients only

SatelliteLink (parent side) and SatelliteClient (sat side) gain
sendNodeList / handleMsgTrunkNodeList wired into the type-121 dispatch.
Parent stamps each ingested entry with the SatelliteLink's id, then
schedules a debounced re-broadcast so trunk peers and sibling sats see
the new contribution. /status now exposes:
  - parent: /status.satellites[<id>].nodes (per-sat partner roster)
  - parent: /status.trunks[*].nodes[*].sat_id (attribution)
  - satellite: /status.satellite.parent_nodes (parent's combined view)

Result: refA, S1, S2 all render the same set of callsigns, with each
entry tagged so consumers can tell where it physically lives.

Wire-format note: this is the second lockstep bump on type 121 within
~24h of a3757ca. Peers running an older fork build will fail to unpack
and silently empty their partner roster until upgraded; pre-jay peers
keep ignoring it.

Tests: 35 → 39. Three /status-level checks (sat-attached client visible
on parent, on far-trunk peer with sat_id, parent-local visible on
satellite) plus a multi-sat wire-level cross-visibility test that
verifies sat_id stamping and the self-echo guard.
2026-04-28 15:11:40 +02:00
Audric d9ec356f10 mqtt: raise default STATUS_INTERVAL from 1000 ms to 30000 ms
The full-status snapshot is a bootstrap / drift-correction mechanism;
per-event topics (talker, client, trunk, nodes) already deliver every
change live. The retained payload scales with mesh size — at a few
hundred nodes with the rich per-client status blob it is hundreds of
KB, which makes a 1 s republish expensive on broker bandwidth and
reflector CPU. Lower it explicitly via [MQTT] STATUS_INTERVAL only
when a small mesh has a consumer that depends on near-real-time full
snapshots.

Test configs keep STATUS_INTERVAL=1000 to verify retained-status
behaviour in seconds.
2026-04-28 11:30:50 +02:00
Audric a3757ca634 trunk: ship rich per-client status blob in MsgTrunkNodeList (fixes #3)
Extends type 121 with a parallel string vector carrying each local
client's m_status["nodes"][callsign] verbatim. Receivers parse,
recursively sanitize (depth/length bounded), and surface the rich
blob under /status.trunks[*].nodes (and /status.twin.nodes), MQTT
nodes/<peer> and Redis live:peer_node:<peer>:<callsign>.status —
bringing partner nodes to parity with local-client status entries
(monitoredTGs, restrictedTG, qth, rx/tx config, protoVer, ...).

isTalker is derived on the receive side from the live trunk-talker
map (MsgTrunkTalkerStart/Stop) rather than carried in the blob,
since blob cadence is event-debounced login/logout/TG-change.

Lockstep wire bump: peers running an older fork build that knows
type 121 with the original 5-vector shape will fail to unpack and
silently empty their partner roster until upgraded. Pre-jayReflector
peers (no type 121 at all) keep ignoring it as before.
2026-04-28 11:24:40 +02:00
Audric 69c3c2eea3 docs: document owner-relay fanout + peer-interest TTL
README.md: "Full-mesh topology" bullet now spells out single-hop
owner-relay: a non-owner sends to the TG's owner, owner fans out to
every other trunk peer with interest, no daisy-chain relay.

docs/TRUNK_PROTOCOL.md: new "Owner-Relay Fanout" subsection under "TG
Ownership and Routing" with the fanout model, a refA/refB/refC
worked example matching test_32, scaling argument (O(N) TCP sends on
the owner for N reflectors), and the peer-interest caveat. The caveat
paragraph now also states the 10-minute inactivity TTL
(PEER_INTEREST_TIMEOUT_S = 600), refresh-on-each-packet behavior,
and immediate clear on trunk disconnect — so sysops don't have to
hunt for the timeout in the code.
2026-04-20 18:55:44 +02:00
Audric 60c69b05ff docs: TESTS.md for test_32 + owner-relay semantics, bump to 35 tests 2026-04-20 18:36:03 +02:00
Audric 7241239c92 test: 3-way mesh conversation (test_32) + N0THRD third test client
test_32_three_way_conversation drives one distinct V2 client on each of
the three mesh reflectors. All three select a TG owned by reflector 'b'
(121001), then each talks in round-robin while the other two listen.
Pass 1 primes m_peer_interested_tgs on every reflector pair; pass 2
measures and fails if any of the six sender→listener pairs delivers no
UDP audio/flush.

Exercises the owner-relay path (refA→refB→refC and refC→refB→refA) that
test_11 and test_17 miss because they only use two reflectors.

TEST_CLIENTS gains N0THRD — distinct callsigns are mandatory: when two
non-owners forward TrunkTalkerStart to the owner with the same
callsign, the owner's per-TG trunk-talker slot cannot disambiguate.

A small MsgHeartbeat (type 1) keepalive is sent between turns so idle
listener sockets do not hit HEARTBEAT_RX_CNT_RESET (15s).
2026-04-20 18:35:58 +02:00
Audric 9f4011d3e2 trunk: owner-relay received audio/flush/talker to other trunk peers
Trunks are meant to form a full audio mesh, but the previous code
broadcast trunk-received audio only to local clients and satellites —
never to other trunk peers. That made three-way conversations impossible
whenever the speaker and the intended listener were both non-owners of
the TG (e.g. refA and refC on a TG owned by refB).

Now, when a TrunkLink receives MsgTrunkTalkerStart/Stop/Audio/Flush for
a TG this reflector locally owns, Reflector re-forwards the event to
every other trunk peer via the existing onLocal* filters (shared /
cluster / peer-interest). Loop prevention: only the owner relays and
the source link is excluded from the fanout, so it stays single-hop.

isLocalTG(tg) performs longest-prefix-match across m_local_prefixes
vs. m_all_prefixes — owner if our prefix wins globally.
2026-04-20 18:35:45 +02:00
Audric 962e1ffc10 docs: surface SATELLITE_FILTER in /status + bump test count to 34
README: add an "Observability" paragraph noting that the active filter
appears under /status.satellites[<id>].filter — and by extension in the
MQTT retained status topic and Redis live📡<id> snapshot,
since those surfaces reserialize the same JSON. Omitted when no filter
is set.

DESIGN_SATELLITE_AND_CLUSTER: add an "Observable state" row to the
TrunkLink vs SatelliteLink comparison table listing the fields in
SatelliteLink::statusJson() including the new filter field.

tests/TESTS.md: bump trunk test count 33 -> 34 and add a row for
test_16c (satellite filter visible in /status).
2026-04-20 15:16:27 +02:00
Audric a4f0e9522d Merge branch 'feature/satellite-status-filter'
Exposes the active SATELLITE_FILTER in SatelliteLink::statusJson() as
satellites[<id>].filter. One edit feeds all three observer surfaces
(HTTP /status, MQTT retained status, Redis live snapshot) since they
all serialize the same JSON.

Contains:
  - satellite: emit filter in statusJson when non-empty
  - test: test_16c verifies filter appears and clears in /status
2026-04-20 15:09:18 +02:00
Audric f24098cd05 test: satellite filter visible in /status (test_16c)
Verifies three behaviors in one test against the HTTP /status endpoint:
  1. The "filter" key is ABSENT when no filter has been sent.
  2. After sat.send_filter("222"), /status.satellites[SAT_ID].filter
     converges to "222" within the wait_until timeout.
  3. After sat.send_filter(""), the key is dropped again.

Covers the passive observability path added in the prior commit. Since
all three observer surfaces (HTTP, MQTT, Redis) serialize the same
statusJson(), the HTTP check is representative.
2026-04-20 14:55:09 +02:00
Audric bf74bbdc78 satellite: expose active TG filter in statusJson
When a satellite advertises a SATELLITE_FILTER via MsgTrunkFilter, the
parent-side SatelliteLink now emits it as satellites[<id>].filter in
its JSON status. Key is omitted when no filter is set (empty => all TGs
pass), so existing consumers that check for its absence keep working.

This single field propagates to three observer surfaces for free:
  - HTTP /status — Reflector::refreshStatus() copies statusJson() into
    m_status["satellites"].
  - Redis live snapshot — statusChanged -> publishSatelliteStatusToRedis
    reserializes statusJson() to live📡<id> on every filter
    change (handleMsgTrunkFilter already emits statusChanged).
  - MQTT retained "status" topic — the periodic publishFullStatus(m_status)
    timer includes the same JSON.

Passive propagation only — no dedicated MQTT filter-change event.
Follow-up work if active notifications are needed: emit a
satellite/<id>/filter topic from handleMsgTrunkFilter.
2026-04-20 14:54:19 +02:00
Audric de47c62dfa docs: document SATELLITE_FILTER and bump test count to 33
README: drop "satellite forwards all TGs unconditionally" claim. Add a
SATELLITE_FILTER line to the satellite-side config example and a section
explaining the bidirectional, opt-in scope (advertised via
MsgTrunkFilter type 122).

DESIGN_SATELLITE_AND_CLUSTER: update the routing comparison row —
satellite is still unfiltered by default but now has SATELLITE_FILTER.

TRUNK_PROTOCOL: promote MsgTrunkFilter from "intended for" to
"used by" satellite links, describe when it is sent.

tests/TESTS.md: bump trunk test count 32 -> 33 and add a row for
test_16b (satellite TG filter honored by parent).
2026-04-20 14:42:26 +02:00
Audric 2d3f2c97af Merge branch 'feature/satellite-filter'
Adds SATELLITE_FILTER support (bidirectional TG filter between a
satellite and its parent) via MsgTrunkFilter (type 122).

Contains:
  - test: satellite TG filter (RED commit reproducing the bug)
  - satellite: sysop patch (Jens DJ1JAY / FM-Funknetz) making it pass
  - docs: clarify that SATELLITE_FILTER is bidirectional in scope
2026-04-20 14:31:16 +02:00
Audric b94a447bf1 docs: clarify SATELLITE_FILTER is bidirectional
The filter is applied on both legs of the satellite: outbound to the
parent (local events for non-matching TGs are suppressed) and inbound
from the parent (advertised via MsgTrunkFilter so the parent skips
forwarding non-matching TGs). The previous comments only mentioned
the inbound direction, which was misleading.
2026-04-20 14:05:32 +02:00
Audric ba5d03e491 test: satellite TG filter (RED — reproduces bug)
Add test_16b_satellite_tg_filter exercising MsgTrunkFilter (type 122):
satellite sends a filter matching only CLUSTER_TGS[0], then a trunk peer
originates talker+audio on both CLUSTER_TGs. The satellite must receive
the matching TG and NOT receive the non-matching one.

Fails on current master: the parent has no handler for MsgTrunkFilter,
so the filter is silently ignored and every cluster TG is forwarded to
the satellite. This commit documents the bug; the next commit applies
the sysop patch that makes the assertion pass.

Adds MSG_TRUNK_FILTER = 122 wire constant, a build_trunk_filter()
packer, and SatellitePeer.send_filter() helper.
2026-04-20 12:52:41 +02:00
Audric bd31369e5e docs: sync README / MQTT / TWIN / TESTS with v1.3.3
- README /status example adds twin{...}, trunks[X].nodes and muted;
  node-list bullet now mentions twin partner as well as trunk peers.
- docs/MQTT.md documents the nodes/local + nodes/<peer_id> topics
  (retained) that were already being published but absent from the
  docs; the QoS/retain table is extended accordingly.
- docs/TWIN_PROTOCOL.md status line bumped to v1.3.x+twin2 and test
  count updated (8 -> 11) to include the partner-roster test.
- tests/TESTS.md bumps the trunk suite (31 -> 32) and twin suite
  (10 -> 11) counts and adds entries for the two new roster tests.
2026-04-19 00:45:44 +02:00
Audric 69c993ad77 version: SVXREFLECTOR 1.3.99.13+trunk.twin2
Bump the twin suffix to reflect roster exchange over the [TWIN]
link and /status / MQTT / Redis attribution work merged for
issue #3.
2026-04-19 00:15:53 +02:00
Audric bf5af3eca0 trunk: expose peer roster in /status.trunks[SECTION].nodes
Cache the most recent sanitized MsgTrunkNodeList per TrunkLink in
m_partner_nodes and surface it from statusJson() as trunks[X].nodes.
/status now matches the roster that was already flowing to MQTT
(nodes/<peer_id>) and Redis (pushPeerNode).

Cleared when the link goes fully inactive — single, paired inbound,
and paired outbound disconnect paths all check isActive() before
clearing so a single surviving inbound/outbound in a paired group
keeps the cache live. Redis tombstones are already handled by
Reflector::onTrunkStateChanged() and unchanged here.

Caveat (pre-existing): in PAIRED mode the two sources share one
peerId(), so the latest arrival overwrites the prior one — same
behaviour MQTT and Redis already have. Fixing that requires
per-connection peer_id attribution, out of scope for this patch.
2026-04-19 00:02:58 +02:00
Audric cadc5c5aa2 twin: fan twin partner roster into MQTT and Redis
Route the twin-received MsgTrunkNodeList through
Reflector::onPeerNodeList() — the same fan-out TrunkLink uses —
so MQTT publishes nodes/<peer_id> and Redis pushPeerNode entries
also cover the twin partner, not just trunk peers.

Before this, /status exposed twin.nodes but MQTT/Redis did not;
consumers reading only from Redis or MQTT missed the roster of
the twin partner entirely.

On twin link-down, clearPartnerRosterIfInactive() pushes an
empty list so onPeerNodeList's tombstone path clears Redis /
empties the MQTT topic — matching the cleanup we do for a
trunk peer that goes down.
2026-04-18 23:49:34 +02:00
Audric fa6f137e1c twin: expose partner roster in /status (fixes #3)
Reflector::refreshStatus() now emits a m_status["twin"] object
(host, port, connection/hello state, prefix, peer_id, priorities)
mirroring the existing trunks[] pattern.

To populate the partner's connected-stations list, TwinLink now
carries MsgTrunkNodeList (type 121) over the [TWIN] socket —
reusing the trunk wire message, no new protocol type. Local
roster changes flow via Reflector::sendNodeListToAllPeers() ->
TwinLink::onLocalNodeListUpdated(); incoming lists are sanitized
and cached in m_partner_nodes, surfaced as twin.nodes.

Without this, [TWIN]-paired reflectors could not observe each
other's rosters from /status — the data was not on the wire at
all (TwinLink only carried talker state).
2026-04-18 23:33:57 +02:00
Audric 4bbd53172a docs: link docs/LOGGING.md from README index 2026-04-18 21:30:33 +02:00
Audric efa02459e9 logging: address code-review feedback
- Fix a critical regression where startup errors emitted before
  geulog::configure() (bad --config path, unknown CLI flag, --version
  banner) were queued into the async deque with no running worker
  and silently dropped on exit(). detail::enqueue() now falls back to
  synchronous ::write() to stdout/stderr when the worker is inactive.
- Remove the dead TRUNK_DEBUG parse block in Reflector.cpp and the
  m_trunk_debug member in Reflector.h — all gates were already
  removed in Phase 1; only the (unread) parse remained.
- Replace the #TRUNK_DEBUG=0 comment in svxreflector.conf.in with a
  documented LOG= reference block.
- Restore the [host:port] peer identity on the ReflectorClient
  ENOTCONN debug line so sysops can still correlate failures.
- Revert sighup_handler and sigterm_handler to async-signal-safe
  ::write(STDERR_FILENO, ...) instead of calling the (mutex-taking,
  allocating) facade from signal context.
- Retag two MsgTrunk* diagnostic sites in ReflectorMsg.h from core
  to trunk to match the enclosing-class rule.
- Doc: note that argument expressions are evaluated at the call site
  before the shouldLog() gate runs, and reword the "never drops"
  claim to acknowledge rare short-write truncation.
2026-04-18 21:02:42 +02:00
Audric 9761c6147f docs: add LOGGING.md — sysop reference for the logging facade
Covers the LOG= config tag, the PTY commands (LOG SHOW / LOG sub=lvl /
LOG RESET), the seven subsystem tags, Docker vs. --logfile deployment
paths, performance guarantees (async, gate-before-format), and the
TRUNK_DEBUG migration story.

Follows the style of docs/MQTT.md / docs/REDIS.md.
2026-04-18 19:29:43 +02:00
Audric 14878d285c logging: migrate remaining cold paths to facade
Sweeps startup banners, config validation, HTTP /status lifecycle, TLS
and certificate diagnostics, MQTT and Redis publisher lifecycle, and
ReflectorMsg serialisation errors through geulog::{info,warn,error}.
No behaviour change — every line retains its message content and level.

After this commit, grep for cout/cerr << in src/svxlink/reflector/
returns no real call sites (only #if 0 blocks and string literals).
2026-04-18 19:28:16 +02:00
Audric ccec8f1e95 logging: facade (hand-rolled async worker) + hot-path migration; drop TRUNK_DEBUG
Adds src/misc/Log.h / Log.cpp exposing geulog::{trace,debug,info,warn,error}
(subsystem, args...) with gate-before-format. Seven named loggers
(trunk, satellite, twin, client, mqtt, redis, core) share a mutex-guarded
deque drained by a single background worker thread writing to fd=1.
Levels come from [GLOBAL] LOG=*=warn,trunk=debug,... and are runtime-
settable via /dev/shm/reflector_ctrl (LOG SHOW / LOG sub=lvl / LOG RESET).
Writes continue to fd=1 so LogWriter file/syslog paths are unchanged.

Migrated hot paths only: audio relay, talker start/stop, handshake,
heartbeat, per-client RX, per-frame trunk/satellite/twin relay, plus the
ENOTCONN sendMsg race at ReflectorClient:302 (demoted to debug since it
is per-disconnect noise, not a fault).

Cold paths (startup banners, config validation, TLS/CA diagnostics,
MQTT/Redis publisher lifecycle) remain on raw cout/cerr and move in the
next commit.

TRUNK_DEBUG is removed; a startup warning points at LOG=trunk=debug.
2026-04-18 18:35:51 +02:00
Audric 59ae728713 reflector: fix clientStatus() isMember check to target nodes subtree
The existence guard in clientStatus() checked m_status.isMember(callsign)
against the root object, which never matched a real callsign, so every
call wiped m_status["nodes"][callsign] back to an empty object. Check
m_status["nodes"].isMember(callsign) instead so the init only fires for
genuinely new callsigns and existing per-node state survives refreshes.
2026-04-17 17:02:08 +02:00
Audric bc02c8c6d8 mqtt: log mosquitto_publish() failures with rate-limited cerr
Publish failures (invalid topic, offline broker, queue full) were silent
because the rc was discarded. At production volume a naive log floods on
any flap, so emit on first failure + error-code change, then suppress for
60s and include the suppressed count on the next line.
2026-04-17 15:36:49 +02:00
Audric bd196d6365 build: opt-out WITH_MQTT/WITH_REDIS flags + extend Redis to /status parity
- Add CMake options WITH_MQTT (default ON) and WITH_REDIS (default ON).
  When OFF, the matching .cpp is dropped from the target, the pkg_check
  is skipped, and MqttPublisher.h / RedisStore.h expose no-op stub
  classes so every call site in Reflector.cpp / ReflectorClient.cpp /
  TrunkLink.cpp keeps compiling. svxreflector.cpp's --import-conf-to-redis
  is gated on WITH_REDIS. Lets sysops who don't run MQTT or Redis drop
  libmosquitto-dev / libhiredis-dev from their build environment.
  README.md and docs/INSTALL.md document the flags.

- Fill the gap between /status and Redis with three new event-driven
  keys (all small, all using the existing 60s TTL refresh):
    * live:meta  — mode, version, local_prefix, listen_port, http_port,
      cluster_tgs, satellite-server stats. Written at startup, on
      reloadClusterTgs(), and on satellite connect/disconnect.
    * live📡<sat_id> — per-satellite status blob. Written via
      a new SatelliteLink::statusChanged signal on hello + on every
      talker start/stop. Cleared on disconnect / cleanup.
    * live:trunk:<section>.status — extended trunk hash with the full
      TrunkLink::statusJson() snapshot. Written at startup, on trunk
      state changes, and on config.changed-all reloads.

  A dashboard can now reconstruct the equivalent of GET /status from a
  handful of small Redis keys instead of one ~500 KB blob — idiomatic
  Redis usage, no per-second hot-write churn.

- New Redis tests: live_meta_populated_at_startup,
  live_trunk_carries_status_blob.

All four flag combinations build cleanly. 31 trunk + 10 twin + 16 redis
pass.
2026-04-17 02:52:36 +02:00
Audric 688a62ec5b publishing: MQTT works in satellite mode + Redis publishes per-client status blob
- Move MQTT init above the satellite early-return in Reflector::initialize so
  satellite-mode reflectors publish to MQTT (client connect/disconnect, talker
  events, full status, etc.) just like full reflectors.
- Add reflector-sat (SATELLITE_OF=reflector-a) to the default test compose so
  satellite mode is exercised end-to-end. New test_31 verifies MQTT
  client-connect/disconnect events under the satellite's own topic prefix.
- Add RedisStore::pushClientStatus and Reflector::publishClientStatus to write
  the per-client status JSON (qth, rx siglev/sql_open/enabled/active,
  monitoredTGs, selected TG, ...) to live:client:<callsign>.status. Hooked
  from publishRxUpdate, handleNodeInfo, setMonitoredTGs, and setTg.
- New Redis test_live_client_status_blob sends a synthetic MsgNodeInfoV2 with
  qth+rx and asserts the parsed blob contains the expected fields.

31/31 trunk + 10/10 twin + 14/14 redis pass.
2026-04-17 01:05:37 +02:00
Audric 6b7a1f0306 docs(tests): sync counts + document Redis peer-node tests
Trunk count 27→30 (MQTT tests 28-30 from 0700e01) and Redis count
10→13 with three new rows for RedisPeerNodeTest (populate+diff,
hostile-string sanitization, trunk-down cleanup) from 7b95d0d.
2026-04-16 21:36:52 +02:00
Audric 7b95d0d2ce redis: mirror peer node lists + sanitize trunk-received strings
Peer node lists (MsgTrunkNodeList, type 121) now propagate into Redis
alongside the existing MQTT publish, so dashboards reading Redis see a
complete view of local + peer rosters. Each remote entry is stored as
live:peer_node:<peer_id>:<callsign> with 60s TTL; a per-peer cache
diffs incoming snapshots so dropped callsigns are DEL'd, and a full
trunk-down deletes all of that peer's entries.

All untrusted strings arriving via the trunk (peer_id from the hello,
plus callsign/qth/lat/lon in node lists) are now sanitized at receive:
control chars + ':' stripped, length bounded (32 callsign, 64 peer_id
and qth), non-finite and out-of-range coordinates cleared. Entries
whose callsign becomes empty after sanitization are dropped.

Also reorders TrunkLink in/outbound onDisconnected so the state-change
notification fires after the per-direction state is cleared, letting
consumers that inspect isActive() (like the Redis peer-node cleanup)
see the correct post-disconnect state.

Adds RedisPeerNodeTest (3 cases: populate+diff, sanitization, trunk-
down cleanup) and a build_node_list wire helper in test_trunk.py.
Exposes the trunk port in docker-compose.redis.yml so the host can
inject trunk frames against the r1 test reflector.
2026-04-16 21:25:37 +02:00
Audric 0700e01453 test(mqtt): add tests for client connect/disconnect, full status, and local nodes
Tests 28-30 cover MQTT publish paths that were untested:
- client connected/disconnected events with tg and ip fields
- periodic retained status message (mirrors /status endpoint)
- retained nodes/local list on client connect
2026-04-16 18:48:03 +02:00
Audric 5777bbb56e docs(tests): document twin satellite tests and Redis harness
Reflect tests added since the last doc sync: twin tests 9-10
(satellite + twin audio mirror), the satellite-on-ref1 in the twin
topology, and the separate Redis integration harness and its 10
test_redis.py cases.
2026-04-16 01:03:28 +02:00
Audric 337cfa7208 TWIN: forward mirrored audio/flush to satellites + integration tests
TwinLink::handleMsgTrunkAudio and handleMsgTrunkFlush now call
forwardAudioToSatellitesExcept / forwardFlushToSatellitesExcept,
mirroring TrunkLink. Without this, satellites attached to a twin
member only saw talker-state updates for traffic originated on the
partner — the audio frames themselves were dropped.

Adds test_09 (satellite handshakes with the twin parent) and test_10
(client on ref2 transmits; satellite on ref1 receives TalkerStart +
audio frames via the TWIN-mirror path). Wires a [SATELLITE] section
and host port mapping into the twin topology generator and lets
SatellitePeer.connect_satellite take an explicit port override.
2026-04-16 00:18:27 +02:00
Audric 7507c116e6 docs: polish TWIN_PROTOCOL and TESTS for shipped-feature framing
TWIN_PROTOCOL.md:
- Drop "DESIGN DRAFT" from the title.
- Rename "Implementation Sketch (non-binding)" to "Implementation" and
  rewrite as descriptive prose naming the actual files that shipped.
- Rename "Resolved Decisions" to "Design Rationale"; drop "from the
  original draft" framing.
- Correct the split-brain reconnect note: state heals via normal event
  flow; there is no bulk state-dump on reconnect.

TESTS.md:
- Document the two-phase run (default 3-reflector mesh + twin 4-reflector
  topology) and the --topology twin flag.
- Add a "Twin Test Topology" section with diagram and port-mapping table.
- Add a new test-case table for the 8 twin-protocol tests.
- List test_twin.py and the twin-related topology fields in File Structure.
2026-04-15 23:07:55 +02:00
Audric b25cbff36a docs(TWIN): reflect that audio-mirror path is now integration-tested 2026-04-15 23:03:20 +02:00
Audric 600542c8a8 Merge feature/twin-protocol: TWIN (HA-pair) protocol
Adds a dedicated [TWIN] link between two reflectors that share a
LOCAL_PREFIX, with active/active external-trunk ownership via a new
PAIRED=1 flag on existing [TRUNK_x] sections. External peers see the
twin pair as one logical trunk with sticky per-transmission socket
selection and instant failover.

Highlights:
- New TwinLink class, twin TCP server on port 5304, 2s/5s heartbeat.
- New messages: MsgTwinExtTalkerStart/Stop (types 123/124), ROLE_TWIN (=2).
- TGHandler gains per-peer attribution (setTrunkTalkerForTGViaPeer,
  clearTrunkTalkersForPeer, peerIdForTG) so external trunk-talker state
  mirrored across the twin link can be cleaned up per-peer on disconnect.
- TrunkLink extended for PAIRED=1: multi-host HOST list, one TcpPrioClient
  per host, relaxed one-inbound-per-section rule, sticky per-transmission
  send with instant failover.
- 8 integration tests covering handshake, mirror, failover, audio path.

Spec: docs/TWIN_PROTOCOL.md
2026-04-15 23:01:17 +02:00
Audric 81bd3eabf3 TWIN audio-mirror: stale-inbound cleanup + end-to-end integration test
Two changes:

1. TwinLink::acceptInboundConnection now treats an existing but-disconnected
   m_inbound_con as stale and replaces it with the new arriving connection,
   and wires a disconnected signal on the inbound so m_inbound_con is
   cleared when the remote end goes away. Without these, a partner container
   restart left the surviving twin holding a dead inbound reference that
   kept rejecting the partner's reconnection attempts until the heartbeat
   RX timeout cleared it (5s window, mid-test).

2. New test_08_audio_mirror_between_twins integration test. Reuses ClientPeer
   from test_trunk.py to connect a V2 sender to ref1 and a V2 receiver to
   ref2, both on TG 26201 (prefix 262). Sends audio from ref1's client,
   asserts the receiver on ref2 gets UDP audio + flush datagrams. Proves
   the Phase C1 path end-to-end:
     ref1 client UDP audio
       -> TGHandler.talkerUpdated -> TwinLink.onLocalAudio
       -> MsgTrunkAudio over [TWIN]
       -> ref2.handleMsgTrunkAudio -> broadcastUdpMsg
       -> ref2 client UDP socket.

All 8 tests now pass (36s wall clock).
2026-04-15 22:59:21 +02:00
Audric 06a2275ee6 Fix: guard send paths against writing to closed sockets; lower test port bases
Three fixes surfaced while running the E3 integration suite end-to-end:

1. sendMsgOnPairedInbound / sendMsgOnPairedOutbound / TwinLink sendMsgOn*
   now check isConnected() before calling write(). Without the guard, a
   heartbeat TX firing between the remote peer dying and our RX-timeout
   cleanup tripped an "assert sock >= 0" inside Async::TcpConnection::write
   and crashed the reflector (seen in test_07 as ref2 exiting with SIGSEGV
   after ref1 was killed).

2. Twin topology trunk_port_base values reduced (45000-48000) so the
   http-port offset (+3080) stays <= 65535. The earlier 60000-63000 bases
   produced 66080, which docker compose rejected as an invalid hostPort.

3. Twin reflector names lowercased (refa, refc) to satisfy Docker's image
   tag constraint (lowercase-only).

All 7 integration tests now pass end-to-end:
  - twin handshake (mutual authenticated hello)
  - no HMAC/prefix errors on startup
  - refa's PAIRED=1 trunk reports connected=True
  - both pair members see TRUNK_IT_DE back to refa
  - no twin-related ERRORs in startup logs
  - kill ref2 -> ref1 detects timeout, restart -> re-handshakes
  - kill ref1 -> refa stays connected to the pair via ref2 (failover)
2026-04-15 22:47:05 +02:00
Audric a2b5d448fa docs: TWIN protocol implemented; bump version 2026-04-15 22:29:36 +02:00
Audric 9acb765110 tests: integration tests for TWIN handshake, mirror, failover
Adds tests/test_twin.py with 7 tests covering the TWIN topology:
  1–2. Twin handshake presence and absence of auth errors on ref1/ref2
  3–4. PAIRED=1 trunk (refA↔DE pair) reported connected on all three sides
  5.   Twin wiring smoke test (no ERROR[TWIN], server-listen log present)
  6.   Twin disconnect/recovery: kill ref2, verify ref1 detects timeout,
       verify re-handshake after restart
  7.   PAIRED trunk failover: kill ref1, verify refA still routes via ref2

run_tests.sh extended to tear down the default mesh, regenerate configs
with --topology twin, run test_twin.py, then restore the default topology.
2026-04-15 22:28:42 +02:00
Audric 9cfea32da6 tests: topology schema supports twin_of and paired trunks
Add TWIN_TOPOLOGY data (TWIN_REFLECTORS, TWIN_TRUNKS) to topology.py and
extend generate_configs.py to render [TWIN] sections, TWIN_LISTEN_PORT, and
PAIRED=1 multi-host trunk sections when invoked with --topology twin (or
TOPOLOGY=twin env var).  Default topology and its generated output are
unchanged.
2026-04-15 22:23:48 +02:00
Audric 0d110172ea conf: document [TWIN] section and PAIRED=1 external trunk 2026-04-15 22:20:07 +02:00
Audric e120951382 TrunkLink: sticky per-transmission socket selection with failover (PAIRED=1) 2026-04-15 22:18:32 +02:00
Audric 17bed97d1c TrunkLink: accept multiple inbound connections when PAIRED=1
Add PairedInboundState struct (parallel to PairedClientState) and
m_ib_states vector to track per-inbound heartbeat/hello state.
acceptInboundConnection branches on m_paired: in paired mode, push
each new inbound into m_ib_cons/m_ib_states, wire a lambda frameReceived
handler to onPairedInboundFrame, and send the hello reply immediately.
Non-paired path is unchanged.

Add onPairedInboundFrame (mirrors onPairedOutboundFrame: resets hb_rx_cnt,
dispatches data messages to shared handlers), onPairedInboundDisconnected
(removes by index from both vectors without deleting — Reflector owns the
object), pairedInboundIndex (linear scan), and sendMsgOnPairedInbound
(mirrors sendMsgOnPairedOutbound).

Route onInboundDisconnected through the paired handler when m_paired.
Update sendMsg paired fallback to iterate m_ib_cons instead of calling
the legacy sendMsgOnInbound. Update heartbeatTick paired branch to iterate
m_ib_cons/m_ib_states instead of m_inbound_con scalars. Update
isInboundReady to check m_ib_states in paired mode. Destructor clears
m_ib_cons/m_ib_states without deleting connections.
2026-04-15 22:08:55 +02:00
Audric 70195e10c3 TrunkLink: open one outbound per host when PAIRED=1
For each host in m_peer_hosts, create a FramedTcpClient with its own
connected/disconnected/frameReceived signal wiring and per-client
PairedClientState (hello_received, hb_tx_cnt, hb_rx_cnt).

- onPairedOutboundConnected: resets per-client state, enables heartbeat
  timer, sends MsgTrunkHello on that client
- onPairedOutboundDisconnected: resets per-client state; TcpPrioClient
  auto-reconnects
- onPairedOutboundFrame: per-client RX counter reset; dispatches
  MsgTrunkHello (HMAC verify, sets hello_received) and MsgTrunkHeartbeat
  inline; all other message types forwarded to shared handlers via ss
  (already positioned past header)
- sendMsgOnPairedOutbound(idx): serialises and writes on m_ob_cons[idx]
- pairedClientIndex: linear scan returning SIZE_MAX on miss
- sendMsg: paired branch iterates m_ob_cons in order, picks first with
  connected+hello_received (D4 will make this sticky); falls back to
  inbound
- heartbeatTick: paired branch iterates per-client counters; legacy OB
  block untouched; "disable timer" check uses any_ob_connected flag
- isOutboundReady: returns true if any paired client is ready
- ~TrunkLink: disconnects and deletes all m_ob_cons entries

Single-host path is unchanged; all new code is inside m_paired branches.
2026-04-15 21:54:25 +02:00