From a6618790bb32004f20fcbfdb18ee8e21242f0883 Mon Sep 17 00:00:00 2001 From: Audric Date: Fri, 8 May 2026 19:56:44 +0200 Subject: [PATCH] feat(peer): passive-monitor support via MsgPeerTgInterest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) — 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. --- docs/PEER_PROTOCOL.md | 55 +++++++ docs/TOPOLOGY_EXAMPLES.md | 19 ++- src/svxlink/reflector/Reflector.cpp | 72 ++++++++- src/svxlink/reflector/Reflector.h | 13 ++ src/svxlink/reflector/ReflectorClient.cpp | 14 +- src/svxlink/reflector/ReflectorMsg.h | 30 ++++ src/svxlink/reflector/SatelliteClient.cpp | 8 +- src/svxlink/reflector/SatelliteLink.cpp | 11 +- src/svxlink/reflector/TrunkLink.cpp | 179 +++++++++++++++++++++- src/svxlink/reflector/TrunkLink.h | 46 +++++- tests/test_trunk.py | 72 +++++++++ 11 files changed, 496 insertions(+), 23 deletions(-) diff --git a/docs/PEER_PROTOCOL.md b/docs/PEER_PROTOCOL.md index 8c5eab1..68cbaa4 100644 --- a/docs/PEER_PROTOCOL.md +++ b/docs/PEER_PROTOCOL.md @@ -242,6 +242,61 @@ inactivity on that TG from the peer, and is cleared immediately on trunk disconnect. The interest map is per-link — disconnecting one peer does not affect interest tracked for other peers. +#### Bootstrapping interest for passive monitors (`MsgPeerTgInterest`, type 129) + +The talker-driven mechanism above only registers interest after a peer has +actually transmitted on the TG. A node that has *selected* a TG without +keying, or marked it in its `monitoredTGs`, would never receive any audio +until something forced it to PTT first. To close that gap, each reflector +periodically advertises its local interest set to its trunk peers. + +> The same change makes UDP audio (and `MsgUdpFlushSamples`) on a TG fan +> out to local clients monitoring it, not just the ones with that TG +> selected — the local broadcast filter is now +> `TgFilter ∪ TgMonitorFilter` for both client-originated audio and +> trunk- / satellite-received audio. Without that, the protocol-level +> interest propagation would arrive at the right reflector but stop at +> its UDP fanout — passive monitors would still hear nothing. + +`MsgPeerTgInterest(peer_id, tgs)` carries a list of TGs that this +reflector's local clients have either selected (`tg`) or are monitoring +(`monitoredTGs`), with `tg=0` excluded. The receiver writes each TG into +its per-link `m_peer_interested_tgs` map, populating peer interest exactly +as a `MsgPeerTalkerStart` would, but without requiring an actual +transmission. + +Sending is gated by `isSharedTG` for the destination link, so an interest +record is only advertised to the peer that is the longest-prefix-match +owner (or next hop toward the owner) for the TG. This avoids registering +ghost interest on non-owner peers — without that filter, gateway prefix +routing would relay an originator's own audio back through cyclic paths. + +Send cadence: + +- **Edge-triggered** on local-state changes that affect the set: client + connect / disconnect, `MsgSelectTG`, `MsgTgMonitor`, and trunk hello + completion. Coalesced with a 500 ms debounce so a client toggling its + monitor list one TG at a time sends one update, not many. +- **Periodic refresh** every 60 s as a safety net against lost deltas. + Both timers skip the actual send when the outgoing set is unchanged + since the last transmission, so an idle reflector generates no traffic. + +Multi-hop propagation: when a reflector receives `MsgPeerTgInterest` from +a peer P, it triggers a refresh on its other trunk links. Each other +link's outgoing set is the union of (a) this reflector's own local +interest and (b) interest learned from *other* peers (P excluded), with +both filtered by `isSharedTG` for the destination. This re-advertises +interest one prefix-route hop further toward the owner — the same shape +as the audio gateway path (`Reflector::shouldRelayInbound`). The source +peer is excluded so an interest record never echoes back to its +originator. + +Convergence and freshness: a fresh interest record is propagated within +one debounce per hop (≤ 500 ms × hops); when a monitor stops monitoring, +the reflector simply omits the TG from subsequent advertisements and the +receiver-side 600 s TTL takes care of cleanup (worst-case staleness on +disconnect ≈ 600 s — there is no explicit withdrawal message). + ### Satellite Links — No TG Filtering Satellite links (`SatelliteClient` / `SatelliteLink`) do **not** apply any TG diff --git a/docs/TOPOLOGY_EXAMPLES.md b/docs/TOPOLOGY_EXAMPLES.md index 826c8cc..c77612c 100644 --- a/docs/TOPOLOGY_EXAMPLES.md +++ b/docs/TOPOLOGY_EXAMPLES.md @@ -53,10 +53,16 @@ forwards going down. Two other behaviours show up repeatedly in the flow descriptions below: -- **Peer interest** is populated when a peer emits `PeerTalkerStart` / - `PeerAudio` for a TG. Until that happens, the owner doesn't know to - fan that TG back to that peer. Interest expires after **10 minutes** of - inactivity on that TG from that peer (or immediately on trunk disconnect). +- **Peer interest** is populated either when a peer emits `PeerTalkerStart` + / `PeerAudio` on a TG, or proactively when a peer advertises its local + clients' selected / monitored TGs via `MsgPeerTgInterest` (type 129). + The proactive path means a passive listener — a SvxLink node that has + selected a foreign TG or added it to `monitoredTGs` without keying — + registers as interested at the owner without first transmitting; the + receiver re-advertises one hop further toward the owner so multi-hop + national-mesh layouts (§2) propagate correctly. Interest expires after + **10 minutes** of inactivity on that TG from that peer (or immediately + on trunk disconnect). - **MCC-style country prefixes** are used for the international mesh: IT = `222`, SE = `240`, DE = `262`. Reusing the DMR MCC layout makes ownership self-documenting. @@ -152,7 +158,10 @@ section. SE only knows the prefixes it has trunks for: `222` (IT) and `262` route for `2222`). Z2 plays locally and fans the audio out to its national peers (excluding IT as the source). The return leg works the same way: audio from a Z3 client reaches SE because IT's `isPeerInterestedTG` for - `22221` was registered on the SE side when SE's PTT first arrived. + `22221` was registered on the SE side — either by a previous PTT from + SE, or proactively as soon as the Swedish operator selected (or + monitored) `22221` on their SvxLink node, via `MsgPeerTgInterest` + (type 129). > **Cluster TGs are for unowned TGs, not for cross-mesh routing.** > Gateway prefix routing handles foreign-to-regional reach automatically diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 699c263..9d9c9df 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -1111,6 +1111,7 @@ void Reflector::clientDisconnected(Async::FramedTcpConnection *con, m_redis->clearLiveClient(client->callsign()); } scheduleNodeListUpdate(); + scheduleTgInterestUpdate(); } //Application::app().runTask([=]{ delete client; }); delete client; @@ -1408,7 +1409,9 @@ void Reflector::udpDatagramReceived(const IpAddress& addr, uint16_t port, broadcastUdpMsg(msg, ReflectorClient::mkAndFilter( ReflectorClient::ExceptFilter(client), - ReflectorClient::TgFilter(tg))); + ReflectorClient::mkOrFilter( + ReflectorClient::TgFilter(tg), + ReflectorClient::TgMonitorFilter(tg)))); if (m_is_satellite && m_satellite_client != nullptr) { m_satellite_client->onLocalAudio(tg, msg.audioData()); @@ -1572,7 +1575,9 @@ void Reflector::onTalkerUpdated(uint32_t tg, ReflectorClient* old_talker, } broadcastUdpMsg(MsgUdpFlushSamples(), ReflectorClient::mkAndFilter( - ReflectorClient::TgFilter(tg), + ReflectorClient::mkOrFilter( + ReflectorClient::TgFilter(tg), + ReflectorClient::TgMonitorFilter(tg)), ReflectorClient::ExceptFilter(old_talker))); if (m_mqtt != nullptr) { @@ -2847,7 +2852,9 @@ void Reflector::onTrunkTalkerUpdated(uint32_t tg, ReflectorClient::TgFilter(tg), ReflectorClient::TgMonitorFilter(tg)))); broadcastUdpMsg(MsgUdpFlushSamples(), - ReflectorClient::TgFilter(tg)); + ReflectorClient::mkOrFilter( + ReflectorClient::TgFilter(tg), + ReflectorClient::TgMonitorFilter(tg))); if (m_mqtt != nullptr) { m_mqtt->onPeerTalkerStop(peer_id, tg, old_cs); @@ -3435,6 +3442,7 @@ void Reflector::onClientAuthenticated(const std::string& callsign, m_redis->pushLiveClient(callsign, ip, "", tg); } scheduleNodeListUpdate(); + scheduleTgInterestUpdate(); } /* Reflector::onClientAuthenticated */ @@ -3461,6 +3469,64 @@ void Reflector::scheduleNodeListUpdate(void) } /* Reflector::scheduleNodeListUpdate */ +void Reflector::scheduleTgInterestUpdate(void) +{ + // Union of every connected client's selected TG and monitored TGs. tg=0 + // is the protocol sentinel "no TG selected" — never of interest. The + // per-link debounce in TrunkLink absorbs bursts of edge triggers + // (e.g. a client toggling its monitor list one TG at a time). + std::set local_interest; + for (const auto& kv : m_client_con_map) + { + ReflectorClient* c = kv.second; + if (c == nullptr || c->callsign().empty()) continue; + const uint32_t tg = c->currentTG(); + if (tg != 0) local_interest.insert(tg); + for (uint32_t mt : c->monitoredTGs()) + { + if (mt != 0) local_interest.insert(mt); + } + } + + for (auto* link : m_trunk_links) + { + link->scheduleTgInterestRefresh(local_interest); + } +} /* Reflector::scheduleTgInterestUpdate */ + + +std::set Reflector::aggregatePeerInterestsForLink( + const TrunkLink* dest) const +{ + std::set out; + if (dest == nullptr) return out; + + const time_t now = std::time(nullptr); + const time_t expiry = TrunkLink::PEER_INTEREST_TIMEOUT_S; + + for (const auto* link : m_trunk_links) + { + // Source-link exclusion: never advertise an interest record back to the + // peer we learned it from. Combined with the prefix-match filter below, + // this matches the gateway-prefix-routing rule used for audio + // (Reflector::shouldRelayInbound + forwardTrunkAudioToOtherTrunks). + if (link == dest) continue; + for (const auto& kv : link->peerInterestedTGs()) + { + const uint32_t tg = kv.first; + const time_t ts = kv.second; + if ((now - ts) >= expiry) continue; + // Re-advertise toward dest only if dest's prefix table claims this TG + // (longest-prefix-match in dest->m_remote_prefix wins, with no longer + // match elsewhere in m_all_prefixes). + if (!dest->isSharedTG(tg)) continue; + out.insert(tg); + } + } + return out; +} /* Reflector::aggregatePeerInterestsForLink */ + + void Reflector::sendNodeListToAllPeers(void) { // 1. Local clients — sat_id stays empty (recipient-relative: "on me"). diff --git a/src/svxlink/reflector/Reflector.h b/src/svxlink/reflector/Reflector.h index 9ceeca8..0bd46cc 100644 --- a/src/svxlink/reflector/Reflector.h +++ b/src/svxlink/reflector/Reflector.h @@ -347,6 +347,19 @@ class Reflector : public sigc::trackable void onPeerNodeList(const std::string& peer_id, const std::vector& nodes); + // Triggered when a local client connects, disconnects, selects a TG, or + // changes its monitoredTGs set. Recomputes local TG interest (selected + // tg + monitoredTGs across every client, tg=0 excluded) and schedules a + // debounced advertisement to every trunk peer. + void scheduleTgInterestUpdate(void); + // Aggregate TGs other peers have advertised interest in (or have shown + // interest in via talker activity), filtered to the ones that match the + // destination link's prefix scope. Used by TrunkLink::sendTgInterest to + // propagate interest toward the prefix owner — the multi-hop leg the + // single-hop "advertise local clients only" approach can't do alone. + std::set aggregatePeerInterestsForLink( + const TrunkLink* dest) const; + protected: private: diff --git a/src/svxlink/reflector/ReflectorClient.cpp b/src/svxlink/reflector/ReflectorClient.cpp index 91b3c57..258ed90 100644 --- a/src/svxlink/reflector/ReflectorClient.cpp +++ b/src/svxlink/reflector/ReflectorClient.cpp @@ -1401,7 +1401,13 @@ void ReflectorClient::setMonitoredTGs(const std::set& tgs) monitored_tgs.append(tg); } } - if (m_reflector != nullptr) m_reflector->publishClientStatus(this); + if (m_reflector != nullptr) + { + m_reflector->publishClientStatus(this); + // Monitored set drives MsgPeerTgInterest; tell trunk peers so they can + // forward audio without waiting for a PTT to bootstrap interest. + m_reflector->scheduleTgInterestUpdate(); + } } /* ReflectorClient::setMonitoredTGs */ @@ -1422,7 +1428,11 @@ void ReflectorClient::setTg(uint32_t tg) } m_current_tg = tg; - if (m_reflector != nullptr) m_reflector->scheduleNodeListUpdate(); + if (m_reflector != nullptr) + { + m_reflector->scheduleNodeListUpdate(); + m_reflector->scheduleTgInterestUpdate(); + } } if (m_status != nullptr) diff --git a/src/svxlink/reflector/ReflectorMsg.h b/src/svxlink/reflector/ReflectorMsg.h index d076b28..2fe2ed6 100644 --- a/src/svxlink/reflector/ReflectorMsg.h +++ b/src/svxlink/reflector/ReflectorMsg.h @@ -2115,6 +2115,36 @@ class MsgTwinExtTalkerStop : public ReflectorMsgBase<124> }; /* MsgTwinExtTalkerStop */ +/** +@brief Trunk message: advertise the TGs this peer is interested in (type 129) + +Lets a reflector tell its trunk peers which TGs its local clients have +selected or are monitoring, so the peers can pre-populate their per-link +peer-interest table and forward audio without requiring a PTT to bootstrap +interest. Receivers re-advertise the set onward toward the prefix owner +(longest-prefix-match in the local trunk table, source-link excluded), so +multi-hop layouts (country gateway between an international mesh and a +national mesh) work end-to-end. +*/ +class MsgPeerTgInterest : public ReflectorMsgBase<129> +{ + public: + MsgPeerTgInterest(void) {} + MsgPeerTgInterest(const std::string& peer_id, + const std::vector& tgs) + : m_peer_id(peer_id), m_tgs(tgs) {} + + const std::string& peerId(void) const { return m_peer_id; } + const std::vector& tgs(void) const { return m_tgs; } + + ASYNC_MSG_MEMBERS(m_peer_id, m_tgs) + + private: + std::string m_peer_id; + std::vector m_tgs; +}; /* MsgPeerTgInterest */ + + #endif /* REFLECTOR_MSG_INCLUDED */ diff --git a/src/svxlink/reflector/SatelliteClient.cpp b/src/svxlink/reflector/SatelliteClient.cpp index 117824f..df9170a 100644 --- a/src/svxlink/reflector/SatelliteClient.cpp +++ b/src/svxlink/reflector/SatelliteClient.cpp @@ -363,7 +363,9 @@ void SatelliteClient::handleMsgPeerAudio(std::istream& is) MsgUdpAudio udp_msg(msg.audio()); m_reflector->broadcastUdpMsg(udp_msg, - ReflectorClient::TgFilter(msg.tg())); + ReflectorClient::mkOrFilter( + ReflectorClient::TgFilter(msg.tg()), + ReflectorClient::TgMonitorFilter(msg.tg()))); } /* SatelliteClient::handleMsgPeerAudio */ @@ -373,7 +375,9 @@ void SatelliteClient::handleMsgPeerFlush(std::istream& is) if (!msg.unpack(is)) return; m_reflector->broadcastUdpMsg(MsgUdpFlushSamples(), - ReflectorClient::TgFilter(msg.tg())); + ReflectorClient::mkOrFilter( + ReflectorClient::TgFilter(msg.tg()), + ReflectorClient::TgMonitorFilter(msg.tg()))); } /* SatelliteClient::handleMsgPeerFlush */ diff --git a/src/svxlink/reflector/SatelliteLink.cpp b/src/svxlink/reflector/SatelliteLink.cpp index 937005c..1c57ae1 100644 --- a/src/svxlink/reflector/SatelliteLink.cpp +++ b/src/svxlink/reflector/SatelliteLink.cpp @@ -374,9 +374,12 @@ void SatelliteLink::handleMsgPeerAudio(std::istream& is) if (msg.audio().empty()) return; if (m_sat_active_tgs.find(tg) == m_sat_active_tgs.end()) return; - // Broadcast to local clients on the parent + // Broadcast to local clients on the parent — both selected and monitoring. MsgUdpAudio udp_msg(msg.audio()); - m_reflector->broadcastUdpMsg(udp_msg, ReflectorClient::TgFilter(tg)); + m_reflector->broadcastUdpMsg(udp_msg, + ReflectorClient::mkOrFilter( + ReflectorClient::TgFilter(tg), + ReflectorClient::TgMonitorFilter(tg))); // Forward to trunk peers m_reflector->forwardSatelliteRawAudioToTrunks(tg, msg.audio()); @@ -394,7 +397,9 @@ void SatelliteLink::handleMsgPeerFlush(std::istream& is) uint32_t tg = msg.tg(); m_reflector->broadcastUdpMsg(MsgUdpFlushSamples(), - ReflectorClient::TgFilter(tg)); + ReflectorClient::mkOrFilter( + ReflectorClient::TgFilter(tg), + ReflectorClient::TgMonitorFilter(tg))); m_reflector->forwardSatelliteFlushToTrunks(tg); m_reflector->forwardFlushToSatellitesExcept(this, tg); diff --git a/src/svxlink/reflector/TrunkLink.cpp b/src/svxlink/reflector/TrunkLink.cpp index 2d41147..f5fe4be 100644 --- a/src/svxlink/reflector/TrunkLink.cpp +++ b/src/svxlink/reflector/TrunkLink.cpp @@ -194,7 +194,9 @@ TrunkLink::TrunkLink(Reflector* reflector, Async::Config& cfg, const std::string& section) : m_reflector(reflector), m_cfg(cfg), m_section(section), m_peer_port(5302), m_priority(0), m_peer_priority(0), - m_heartbeat_timer(1000, Timer::TYPE_PERIODIC, false) + m_heartbeat_timer(1000, Timer::TYPE_PERIODIC, false), + m_tg_interest_timer(TG_INTEREST_HEARTBEAT_MS, Timer::TYPE_PERIODIC, false), + m_tg_interest_debounce(TG_INTEREST_DEBOUNCE_MS, Timer::TYPE_ONESHOT, false) { // Generate a random priority nonce for tie-breaking (once, for lifetime) std::random_device rd; @@ -209,6 +211,10 @@ TrunkLink::TrunkLink(Reflector* reflector, Async::Config& cfg, m_heartbeat_timer.expired.connect( mem_fun(*this, &TrunkLink::heartbeatTick)); + m_tg_interest_timer.expired.connect( + mem_fun(*this, &TrunkLink::onTgInterestTimer)); + m_tg_interest_debounce.expired.connect( + mem_fun(*this, &TrunkLink::onTgInterestDebounce)); } /* TrunkLink::TrunkLink */ @@ -622,6 +628,9 @@ void TrunkLink::acceptInboundConnection(Async::FramedTcpConnection* con, sendMsgOnPairedInbound(m_ib_cons.size() - 1, MsgPeerHello(m_peer_id_config, joinPrefixes(m_local_prefix), m_priority, m_secret)); + + m_tg_interest_timer.setEnable(true); + m_reflector->scheduleTgInterestUpdate(); return; } @@ -670,6 +679,12 @@ void TrunkLink::acceptInboundConnection(Async::FramedTcpConnection* con, sendMsgOnInbound(MsgPeerHello(m_peer_id_config, joinPrefixes(m_local_prefix), m_priority, m_secret)); + + // Arm the interest-refresh path now that the inbound link is up. The peer + // can authenticate via the inbound socket alone (outbound may still be + // pending), so the symmetric trigger to handleMsgPeerHello belongs here. + m_tg_interest_timer.setEnable(true); + m_reflector->scheduleTgInterestUpdate(); } /* TrunkLink::acceptInboundConnection */ @@ -785,6 +800,18 @@ void TrunkLink::onLocalFlush(uint32_t tg) } /* TrunkLink::onLocalFlush */ +void TrunkLink::scheduleTgInterestRefresh( + const std::set& local_interest) +{ + m_local_tg_interest = local_interest; + if (!isActive()) return; + // 500 ms one-shot debounce: coalesce rapid changes (e.g. a client toggling + // monitoredTGs entries one at a time) into a single advertisement. + m_tg_interest_debounce.reset(); + m_tg_interest_debounce.setEnable(true); +} /* TrunkLink::scheduleTgInterestRefresh */ + + /**************************************************************************** * * TrunkLink private methods @@ -882,7 +909,11 @@ void TrunkLink::onFrameReceived(FramedTcpConnection* con, m_ob_hb_rx_cnt = HEARTBEAT_RX_CNT_RESET; } - if (header.type() != MsgPeerHeartbeat::TYPE) + // Suppress per-frame debug for routine, noisy message types: heartbeat + // (per-second) and MsgPeerTgInterest (60 s heartbeat plus edge triggers). + // Both have their own log lines at the dispatcher level. + if (header.type() != MsgPeerHeartbeat::TYPE && + header.type() != MsgPeerTgInterest::TYPE) { geulog::debug("trunk", m_section, ": rx ", (is_inbound ? "IB" : "OB"), " type=", header.type(), " len=", data.size()); @@ -911,6 +942,9 @@ void TrunkLink::onFrameReceived(FramedTcpConnection* con, case MsgPeerNodeList::TYPE: handleMsgPeerNodeList(ss); break; + case MsgPeerTgInterest::TYPE: + handleMsgPeerTgInterest(ss); + break; default: geulog::warn("trunk", "[", m_section, "] Unknown trunk message type=", header.type()); @@ -974,6 +1008,13 @@ void TrunkLink::handleMsgPeerHello(std::istream& is, bool is_inbound) " ib_connected=", (m_inbound_con != nullptr), " ib_hello=", m_ib_hello_received, " isActive=", isActive()); + + // Hello complete -> arm the periodic interest refresh and ask the + // Reflector for a fresh local snapshot so we can advertise immediately + // (the receiver registers our interest only after receiving a frame, so + // the new peer needs the first send before any client transmits). + m_tg_interest_timer.setEnable(true); + m_reflector->scheduleTgInterestUpdate(); } /* TrunkLink::handleMsgPeerHello */ @@ -1115,8 +1156,12 @@ void TrunkLink::handleMsgPeerAudio(std::istream& is) m_peer_interested_tgs[local_tg] = std::time(nullptr); // Rebuild a UDP audio message and broadcast to local clients on this TG + // — both clients with this TG selected and clients monitoring it. MsgUdpAudio udp_msg(msg.audio()); - m_reflector->broadcastUdpMsg(udp_msg, ReflectorClient::TgFilter(local_tg)); + m_reflector->broadcastUdpMsg(udp_msg, + ReflectorClient::mkOrFilter( + ReflectorClient::TgFilter(local_tg), + ReflectorClient::TgMonitorFilter(local_tg))); // Forward trunk audio to connected satellites m_reflector->forwardAudioToSatellitesExcept(nullptr, local_tg, msg.audio()); @@ -1152,7 +1197,9 @@ void TrunkLink::handleMsgPeerFlush(std::istream& is) } m_reflector->broadcastUdpMsg(MsgUdpFlushSamples(), - ReflectorClient::TgFilter(local_tg)); + ReflectorClient::mkOrFilter( + ReflectorClient::TgFilter(local_tg), + ReflectorClient::TgMonitorFilter(local_tg))); // Forward trunk flush to connected satellites m_reflector->forwardFlushToSatellitesExcept(nullptr, local_tg); @@ -1544,6 +1591,9 @@ void TrunkLink::onPairedInboundFrame(Async::FramedTcpConnection* con, case MsgPeerNodeList::TYPE: handleMsgPeerNodeList(ss); break; + case MsgPeerTgInterest::TYPE: + handleMsgPeerTgInterest(ss); + break; default: geulog::warn("trunk", "[", m_section, "] Unknown trunk message type=", header.type(), " on paired ib#", idx); @@ -1680,6 +1730,9 @@ void TrunkLink::onPairedOutboundFrame(FramedTcpClient* client, geulog::info("trunk", m_section, ": paired outbound #", idx, " hello received (peer='", msg.id(), "' priority=", msg.priority(), " authenticated)"); + + m_tg_interest_timer.setEnable(true); + m_reflector->scheduleTgInterestUpdate(); break; } @@ -1708,6 +1761,9 @@ void TrunkLink::onPairedOutboundFrame(FramedTcpClient* client, case MsgPeerNodeList::TYPE: handleMsgPeerNodeList(ss); break; + case MsgPeerTgInterest::TYPE: + handleMsgPeerTgInterest(ss); + break; default: geulog::warn("trunk", "[", m_section, "] Unknown trunk message type=", header.type(), " on paired ob#", idx); @@ -1728,9 +1784,124 @@ void TrunkLink::clearPeerTalkerState(void) m_peer_active_tgs.clear(); m_yielded_tgs.clear(); m_peer_interested_tgs.clear(); + m_last_sent_tg_interest.clear(); + m_tg_interest_timer.setEnable(false); + m_tg_interest_debounce.setEnable(false); } /* TrunkLink::clearPeerTalkerState */ +void TrunkLink::handleMsgPeerTgInterest(std::istream& is) +{ + MsgPeerTgInterest msg; + if (!msg.unpack(is)) + { + geulog::error("trunk", "[", m_section, + "] Failed to unpack MsgPeerTgInterest"); + return; + } + + const time_t now = std::time(nullptr); + for (uint32_t wire_tg : msg.tgs()) + { + // Translate the peer's TG numbering into ours; existing entries in + // m_peer_interested_tgs (populated by talker activity at lines ~1025 + // and ~1115) are keyed in local numbering, so we must match. + const uint32_t local_tg = mapTgIn(wire_tg); + if (local_tg == 0) continue; + m_peer_interested_tgs[local_tg] = now; + } + + geulog::debug("trunk", m_section, + ": rx MsgPeerTgInterest count=", msg.tgs().size(), + " peer_interested_total=", m_peer_interested_tgs.size()); + + // Re-advertise across the mesh. This peer's interest may be relevant to + // a different trunk (e.g. SE -> IT 222 advertises 22212; IT 222 has a + // 2221 -> Z1 prefix route and must let Z1 know). The Reflector walks + // every trunk and triggers a refresh; each link's debounce will pick + // up the new aggregate via buildOutgoingTgInterest(). + m_reflector->scheduleTgInterestUpdate(); +} /* TrunkLink::handleMsgPeerTgInterest */ + + +void TrunkLink::onTgInterestTimer(Async::Timer*) +{ + sendTgInterest(); +} /* TrunkLink::onTgInterestTimer */ + + +void TrunkLink::onTgInterestDebounce(Async::Timer* t) +{ + t->setEnable(false); + sendTgInterest(); +} /* TrunkLink::onTgInterestDebounce */ + + +std::set TrunkLink::buildOutgoingTgInterest(void) const +{ + std::set out; + + // Only advertise to peers that are the longest-prefix-match for the TG + // (the owner, or the next hop toward the owner). Advertising to any other + // peer registers ghost interest there: when audio on that TG comes in via + // the standard owner-relay path, the non-owner peer would relay it back + // through gateway prefix routing, creating cross-mesh loops. + // isSharedTG(tg) is the same gate used by the audio fanout. + auto include = [&](uint32_t tg) { + if (tg == 0) return false; + if (isBlacklisted(tg) || !isAllowed(tg)) return false; + return isSharedTG(tg); + }; + + for (uint32_t tg : m_local_tg_interest) + { + if (include(tg)) out.insert(tg); + } + + // Re-advertise interest learned from other peers; the Reflector aggregator + // already source-excludes and prefix-filters via dest->isSharedTG, but + // applying include() again normalises blacklist/allow handling. + std::set from_peers = + m_reflector->aggregatePeerInterestsForLink(this); + for (uint32_t tg : from_peers) + { + if (include(tg)) out.insert(tg); + } + + return out; +} /* TrunkLink::buildOutgoingTgInterest */ + + +void TrunkLink::sendTgInterest(void) +{ + if (!isActive()) return; + + std::set outgoing = buildOutgoingTgInterest(); + if (outgoing == m_last_sent_tg_interest) + { + // Nothing changed since the last advertisement — let the receiver's TTL + // ride on the previous send. Keeps the heartbeat refresh from generating + // idle traffic when the monitored set is stable. + return; + } + + // Translate to peer numbering on the wire so the receiver's mapTgIn + // brings it back to its local numbering symmetrically. + std::vector wire_tgs; + wire_tgs.reserve(outgoing.size()); + for (uint32_t tg : outgoing) + { + wire_tgs.push_back(mapTgOut(tg)); + } + + sendMsg(MsgPeerTgInterest(m_peer_id_config, wire_tgs)); + m_last_sent_tg_interest = std::move(outgoing); + + geulog::debug("trunk", m_section, + ": tx MsgPeerTgInterest count=", wire_tgs.size()); +} /* TrunkLink::sendTgInterest */ + + void TrunkLink::reloadConfig(void) { m_blacklist_filter = TgFilter{}; diff --git a/src/svxlink/reflector/TrunkLink.h b/src/svxlink/reflector/TrunkLink.h index 2f99237..00374a1 100644 --- a/src/svxlink/reflector/TrunkLink.h +++ b/src/svxlink/reflector/TrunkLink.h @@ -118,6 +118,17 @@ class TrunkLink : public sigc::trackable { return m_remote_prefix; } + // Read-only view of TGs the peer is interested in (TalkerStart activity + // or MsgPeerTgInterest advertisement). Used by Reflector to aggregate + // interest for re-advertisement toward the prefix owner. + const std::map& peerInterestedTGs(void) const + { + return m_peer_interested_tgs; + } + // 10 minutes of inactivity expires a peer-interest entry. Public so the + // Reflector aggregator can apply the same staleness filter when + // composing re-advertisements toward the prefix owner. + static const time_t PEER_INTEREST_TIMEOUT_S = 600; bool isPaired(void) const { return m_paired; } bool hasInboundConnection(void) const @@ -149,6 +160,13 @@ class TrunkLink : public sigc::trackable // to the peer. Called from Reflector after debounce. void sendNodeList(const std::vector& nodes); + // Schedule a debounced advertisement of TG interest to this peer. The + // local-interest set (selected tg + monitoredTGs of every connected + // client) is supplied by the caller; the link unions it with interest + // re-routed from other peers (longest-prefix-match toward the owner) + // before sending. Coalesces multiple calls within the debounce window. + void scheduleTgInterestRefresh(const std::set& local_interest); + // PTY-driven controls void muteCallsign(const std::string& callsign) { @@ -209,12 +227,23 @@ class TrunkLink : public sigc::trackable // Cleared when the link goes fully inactive. std::vector m_partner_nodes; - // TGs the peer has shown interest in (sent TalkerStart for). - // Maps TG number to last activity timestamp. Entries expire after - // PEER_INTEREST_TIMEOUT_S seconds of inactivity. - static const time_t PEER_INTEREST_TIMEOUT_S = 600; // 10 minutes + // TGs the peer has shown interest in (sent TalkerStart for, or advertised + // via MsgPeerTgInterest). Maps TG number to last activity timestamp. + // Entries expire after PEER_INTEREST_TIMEOUT_S seconds of inactivity. std::map m_peer_interested_tgs; + // TG-interest advertisement state. Heartbeat refresh is paced loosely + // against PEER_INTEREST_TIMEOUT_S; debounce coalesces edge-triggered + // updates so e.g. a client toggling its monitor list does not blast + // the wire. Last-sent set lets us skip the heartbeat send when nothing + // has changed since the previous transmission. + static const unsigned TG_INTEREST_HEARTBEAT_MS = 60 * 1000; + static const unsigned TG_INTEREST_DEBOUNCE_MS = 500; + Async::Timer m_tg_interest_timer; // periodic refresh + Async::Timer m_tg_interest_debounce; // one-shot, edge-triggered + std::set m_local_tg_interest; // last seen local set + std::set m_last_sent_tg_interest; // last set actually sent + // PAIRED mode: one logical peer backed by multiple physical hosts bool m_paired = false; std::vector m_peer_hosts; // HOST=h1,h2,... @@ -263,6 +292,15 @@ class TrunkLink : public sigc::trackable void handleMsgPeerFlush(std::istream& is); void handleMsgPeerHeartbeat(void); void handleMsgPeerNodeList(std::istream& is); + void handleMsgPeerTgInterest(std::istream& is); + + void sendTgInterest(void); + void onTgInterestTimer(Async::Timer* t); + void onTgInterestDebounce(Async::Timer* t); + // Build the set we should advertise to this peer: local interest, plus + // TGs we have learned from other peers whose longest-prefix-match in + // m_all_prefixes points at this peer (gateway re-advertisement). + std::set buildOutgoingTgInterest(void) const; void sendMsg(const ReflectorMsg& msg); void sendMsgOnOutbound(const ReflectorMsg& msg); diff --git a/tests/test_trunk.py b/tests/test_trunk.py index 412fd42..3b51d09 100644 --- a/tests/test_trunk.py +++ b/tests/test_trunk.py @@ -2656,6 +2656,78 @@ class TestTrunkIntegration(unittest.TestCase): sender.close() receiver.close() + # ------------------------------------------------------------------ + # Test 39: passive monitor actually hears audio across a multi-hop gateway + # ------------------------------------------------------------------ + def test_39_passive_monitor_multihop(self): + """A passive monitor on reflector-a hears audio from a TG owned by + reflector-d, with reflector-b acting as a gateway, *without* the + monitor ever PTT'ing to bootstrap interest. + + Topology (test_37 setup): + a prefix 122 trunks: b, c (no direct trunk to d) + b prefix 121 trunks: a, c, d (gateway) + d prefix 1219 trunks: b only + + TG `121951` is owned by d. a's monitored set is advertised via + MsgPeerTgInterest to b; b longest-prefix-matches `1219` → d and + re-advertises the interest to d. d's PTT then fans out to b + (peer-interest), b forwards to a (peer-interest), and a delivers + UDP audio to the local monitoring client via TgMonitorFilter. The + whole chain works without a transmitting once. + """ + if "d" not in REFLECTOR_NAMES: + self.skipTest("test_39 requires reflector 'd' in topology") + + tg = 121951 # owned by d (longest 1219); next-longest at b is 121 + + a_client = ClientPeer() + d_client = ClientPeer() + try: + # a-client: connects to a, selects tg=0 (no PTT possible), + # monitors `tg` passively. This is the "Swedish ham listening + # to an Italian regional TG" case — interest must propagate to + # the owner without the monitor transmitting. + a_port = T.mapped_client_port("a") + a_client.connect(HOST, a_port) + a_client.authenticate(callsign=CLIENT_CALLSIGN, password=CLIENT_PASSWORD) + a_client.setup_udp(udp_port=a_port) + a_client.select_tg(0) + a_client.monitor_tgs([tg]) + + # d-client: connects to d, selects `tg`, will PTT. + d_port = T.mapped_client_port("d") + d_client.connect(HOST, d_port) + d_client.authenticate(callsign=CLIENT2_CALLSIGN, password=CLIENT2_PASSWORD) + d_client.setup_udp(udp_port=d_port) + d_client.select_tg(tg) + + # Advertisement is debounced 500 ms in TrunkLink, then re-advertised + # at b on receipt → debounced again toward d. 2 s gives both legs + # plus a safety margin. + time.sleep(2.0) + + # Drain any backlog before the measurement burst. + a_client.recv_udp_all(timeout=0.05) + + for _ in range(6): + d_client.send_udp_audio(b"\xBE\xEF" * 80) + time.sleep(0.02) + d_client.send_udp_flush() + time.sleep(1.5) + + msgs = a_client.recv_udp_all(timeout=1.0) + audio = sum(1 for t, _ in msgs if t == UDP_AUDIO) + flush = sum(1 for t, _ in msgs if t == UDP_FLUSH) + self.assertGreater(audio + flush, 0, + f"passive monitor on reflector-a did not hear TG {tg} " + f"audio from reflector-d via gateway b — " + f"MsgPeerTgInterest multi-hop propagation or " + f"TgMonitorFilter UDP delivery broken") + finally: + a_client.close() + d_client.close() + # --------------------------------------------------------------------------- # Custom test runner with clean, readable output