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.
This commit is contained in:
Audric committed 2026-04-15 21:54:25 +02:00
1 parent adfe04e8b1
commit 70195e10c3
2 files changed
+349 -4

No files matched your search

+329 -4
View File
@@ -138,6 +138,14 @@ TrunkLink::~TrunkLink(void)
TGHandler::instance()->clearTrunkTalkerForTG(tg);
}
m_peer_active_tgs.clear();
// PAIRED mode: tear down per-host outbound clients
for (auto* c : m_ob_cons)
{
c->disconnect();
delete c;
}
m_ob_cons.clear();
} /* TrunkLink::~TrunkLink */
@@ -289,10 +297,37 @@ bool TrunkLink::initialize(void)
<< (m_blacklist_filter.empty() ? "" : " [blacklist]")
<< (m_allow_filter.empty() ? "" : " [whitelist]")
<< (m_tg_map_in.empty() ? "" : " [tg_map]")
<< " [outbound deferred to D2]"
<< endl;
// Outbound connections for PAIRED mode are created in D2.
// For now, leave m_con unconnected and return successfully.
// Create one outbound client per host
m_ob_cons.reserve(m_peer_hosts.size());
m_ob_states.resize(m_peer_hosts.size());
for (size_t i = 0; i < m_peer_hosts.size(); ++i)
{
auto* client = new FramedTcpClient();
client->setMaxFrameSize(ReflectorMsg::MAX_POSTAUTH_FRAME_SIZE);
client->connected.connect(
[this, client]() { onPairedOutboundConnected(client); });
client->disconnected.connect(
[this, client](Async::TcpConnection* c,
Async::TcpConnection::DisconnectReason r) {
onPairedOutboundDisconnected(client, c, r);
});
client->frameReceived.connect(
[this, client](Async::FramedTcpConnection* c,
std::vector<uint8_t>& data) {
onPairedOutboundFrame(client, c, data);
});
client->addStaticSRVRecord(0, 0, 0, m_peer_port, m_peer_hosts[i]);
client->setReconnectMinTime(2000);
client->setReconnectMaxTime(30000);
client->connect();
m_ob_cons.push_back(client);
cout << m_section << ": paired outbound #" << i
<< " connecting to " << m_peer_hosts[i] << ":" << m_peer_port
<< endl;
}
return true;
}
@@ -994,6 +1029,35 @@ void TrunkLink::handleMsgTrunkFlush(std::istream& is)
void TrunkLink::sendMsg(const ReflectorMsg& msg)
{
if (m_paired)
{
// In paired mode, try each outbound client in order (D4 will make sticky)
for (size_t i = 0; i < m_ob_cons.size(); ++i)
{
if (m_ob_cons[i]->isConnected() && m_ob_states[i].hello_received)
{
sendMsgOnPairedOutbound(i, msg);
return;
}
}
// Inbound fallback (D3 will expand this)
if (isInboundReady())
{
if (m_debug)
{
cout << m_section << " [DEBUG]: paired tx fallback to IB type="
<< msg.type() << endl;
}
sendMsgOnInbound(msg);
}
else if (m_debug)
{
cerr << m_section << " [DEBUG]: paired tx dropped type=" << msg.type()
<< " (no active connection)" << endl;
}
return;
}
if (isOutboundReady())
{
sendMsgOnOutbound(msg);
@@ -1048,7 +1112,82 @@ void TrunkLink::sendMsgOnInbound(const ReflectorMsg& msg)
void TrunkLink::heartbeatTick(Async::Timer* t)
{
// Outbound heartbeat
if (m_paired)
{
// Per-host outbound heartbeat for paired mode
bool any_ob_connected = false;
for (size_t i = 0; i < m_ob_cons.size(); ++i)
{
if (!m_ob_cons[i]->isConnected() || m_ob_states[i].hb_rx_cnt == 0)
continue;
any_ob_connected = true;
if (--m_ob_states[i].hb_tx_cnt == 0)
{
if (m_debug)
{
cout << m_section << " [DEBUG]: paired OB#" << i << " heartbeat tx"
<< " hb_rx=" << m_ob_states[i].hb_rx_cnt << endl;
}
sendMsgOnPairedOutbound(i, MsgTrunkHeartbeat());
}
if (--m_ob_states[i].hb_rx_cnt == 0)
{
cerr << "*** ERROR[" << m_section
<< "]: Paired outbound #" << i << " heartbeat timeout" << endl;
m_ob_cons[i]->disconnect();
}
else if (m_debug && m_ob_states[i].hb_rx_cnt <= 5)
{
cerr << m_section << " [DEBUG]: paired OB#" << i
<< " heartbeat rx countdown: " << m_ob_states[i].hb_rx_cnt << endl;
}
}
// Inbound heartbeat (same as non-paired path)
if (m_inbound_con != nullptr && m_ib_hb_rx_cnt > 0)
{
if (--m_ib_hb_tx_cnt == 0)
{
if (m_debug)
{
cout << m_section << " [DEBUG]: IB heartbeat tx"
<< " ib_hb_rx=" << m_ib_hb_rx_cnt << endl;
}
sendMsgOnInbound(MsgTrunkHeartbeat());
}
if (--m_ib_hb_rx_cnt == 0)
{
cerr << "*** ERROR[" << m_section
<< "]: Inbound heartbeat timeout" << endl;
m_inbound_con->disconnect();
}
else if (m_debug && m_ib_hb_rx_cnt <= 5)
{
cerr << m_section << " [DEBUG]: IB heartbeat rx countdown: "
<< m_ib_hb_rx_cnt << endl;
}
}
// Prune expired peer interest entries
time_t now = std::time(nullptr);
for (auto it = m_peer_interested_tgs.begin();
it != m_peer_interested_tgs.end(); )
{
if ((now - it->second) >= PEER_INTEREST_TIMEOUT_S)
it = m_peer_interested_tgs.erase(it);
else
++it;
}
// Disable timer only when all paired outbounds AND inbound are down
if (!any_ob_connected && m_inbound_con == nullptr)
{
m_heartbeat_timer.setEnable(false);
}
return;
}
// Outbound heartbeat (non-paired)
if (m_con.isConnected() && m_ob_hb_rx_cnt > 0)
{
if (--m_ob_hb_tx_cnt == 0)
@@ -1129,6 +1268,16 @@ bool TrunkLink::isActive(void) const
bool TrunkLink::isOutboundReady(void) const
{
if (m_paired)
{
// Any paired outbound client that has completed the handshake is enough
for (size_t i = 0; i < m_ob_cons.size(); ++i)
{
if (m_ob_cons[i]->isConnected() && m_ob_states[i].hello_received)
return true;
}
return false;
}
return m_con.isConnected() && m_ob_hello_received;
} /* TrunkLink::isOutboundReady */
@@ -1139,6 +1288,182 @@ bool TrunkLink::isInboundReady(void) const
} /* TrunkLink::isInboundReady */
size_t TrunkLink::pairedClientIndex(FramedTcpClient* client) const
{
for (size_t i = 0; i < m_ob_cons.size(); ++i)
{
if (m_ob_cons[i] == client)
return i;
}
return SIZE_MAX;
} /* TrunkLink::pairedClientIndex */
void TrunkLink::sendMsgOnPairedOutbound(size_t idx, const ReflectorMsg& msg)
{
if (idx >= m_ob_cons.size()) return;
ostringstream ss;
ReflectorMsg header(msg.type());
if (!header.pack(ss) || !msg.pack(ss))
{
cerr << "*** ERROR[" << m_section << "]: Failed to pack trunk message "
"type=" << msg.type() << " for paired outbound #" << idx << endl;
return;
}
m_ob_states[idx].hb_tx_cnt = HEARTBEAT_TX_CNT_RESET;
m_ob_cons[idx]->write(ss.str().data(), ss.str().size());
} /* TrunkLink::sendMsgOnPairedOutbound */
void TrunkLink::onPairedOutboundConnected(FramedTcpClient* client)
{
size_t idx = pairedClientIndex(client);
if (idx == SIZE_MAX) return;
m_ob_states[idx].hello_received = false;
m_ob_states[idx].hb_tx_cnt = HEARTBEAT_TX_CNT_RESET;
m_ob_states[idx].hb_rx_cnt = HEARTBEAT_RX_CNT_RESET;
m_heartbeat_timer.setEnable(true);
cout << m_section << ": paired outbound #" << idx
<< " connected to " << m_peer_hosts[idx] << ":" << m_peer_port << endl;
if (m_debug)
{
cout << m_section << " [DEBUG]: paired ob#" << idx
<< " sending hello with priority=" << m_priority << endl;
}
sendMsgOnPairedOutbound(idx,
MsgTrunkHello(m_peer_id_config, joinPrefixes(m_local_prefix),
m_priority, m_secret, MsgTrunkHello::ROLE_PEER));
} /* TrunkLink::onPairedOutboundConnected */
void TrunkLink::onPairedOutboundDisconnected(FramedTcpClient* client,
Async::TcpConnection* /*con*/,
Async::TcpConnection::DisconnectReason reason)
{
size_t idx = pairedClientIndex(client);
if (idx == SIZE_MAX) return;
cout << m_section << ": paired outbound #" << idx
<< " disconnected ("
<< Async::TcpConnection::disconnectReasonStr(reason) << ")" << endl;
m_ob_states[idx].hello_received = false;
m_ob_states[idx].hb_tx_cnt = 0;
m_ob_states[idx].hb_rx_cnt = 0;
// TcpPrioClient auto-reconnects; nothing else to do.
} /* TrunkLink::onPairedOutboundDisconnected */
void TrunkLink::onPairedOutboundFrame(FramedTcpClient* client,
Async::FramedTcpConnection* /*con*/, std::vector<uint8_t>& data)
{
size_t idx = pairedClientIndex(client);
if (idx == SIZE_MAX) return;
// Reset RX heartbeat counter for this client
m_ob_states[idx].hb_rx_cnt = HEARTBEAT_RX_CNT_RESET;
auto buf = reinterpret_cast<const char*>(data.data());
stringstream ss;
ss.write(buf, data.size());
ReflectorMsg header;
if (!header.unpack(ss))
{
cerr << "*** ERROR[" << m_section
<< "]: Failed to unpack frame on paired outbound #" << idx << endl;
return;
}
// Only allow hello and heartbeat before handshake completes
if (!m_ob_states[idx].hello_received &&
header.type() != MsgTrunkHello::TYPE &&
header.type() != MsgTrunkHeartbeat::TYPE)
{
cerr << "*** WARNING[" << m_section
<< "]: Ignoring paired ob#" << idx << " msg type=" << header.type()
<< " before hello" << endl;
return;
}
switch (header.type())
{
case MsgTrunkHello::TYPE:
{
MsgTrunkHello msg;
if (!msg.unpack(ss)) return;
if (msg.id().empty())
{
cerr << "*** ERROR[" << m_section
<< "]: Peer sent empty ID on paired ob#" << idx << endl;
client->disconnect();
return;
}
if (!msg.verify(m_secret))
{
cerr << "*** ERROR[" << m_section
<< "]: HMAC failed on paired outbound #" << idx
<< " (peer='" << msg.id() << "')" << endl;
client->disconnect();
return;
}
m_ob_states[idx].hello_received = true;
// Use priority/id from whichever client completes the handshake first
// (all twins share the same peer priority; last-writer wins is fine here)
m_peer_priority = msg.priority();
if (m_peer_id_received.empty())
m_peer_id_received = msg.id();
cout << m_section << ": paired outbound #" << idx
<< " hello received (peer='" << msg.id()
<< "' priority=" << msg.priority() << " authenticated)" << endl;
break;
}
case MsgTrunkHeartbeat::TYPE:
// hb_rx_cnt already reset above; nothing else needed
break;
default:
// For data messages (talker start/stop, audio, flush, node-list),
// dispatch to the shared handlers — they don't need per-client context.
// `ss` is already positioned past the header so we can pass it directly.
switch (header.type())
{
case MsgTrunkTalkerStart::TYPE:
handleMsgTrunkTalkerStart(ss);
break;
case MsgTrunkTalkerStop::TYPE:
handleMsgTrunkTalkerStop(ss);
break;
case MsgTrunkAudio::TYPE:
handleMsgTrunkAudio(ss);
break;
case MsgTrunkFlush::TYPE:
handleMsgTrunkFlush(ss);
break;
case MsgTrunkNodeList::TYPE:
handleMsgTrunkNodeList(ss);
break;
default:
cerr << "*** WARNING[" << m_section
<< "]: Unknown trunk message type=" << header.type()
<< " on paired ob#" << idx << endl;
break;
}
break;
}
} /* TrunkLink::onPairedOutboundFrame */
void TrunkLink::clearPeerTalkerState(void)
{
for (uint32_t tg : m_peer_active_tgs)
+20
View File
@@ -266,6 +266,26 @@ class TrunkLink : public sigc::trackable
void heartbeatTick(Async::Timer* t);
void clearPeerTalkerState(void);
// PAIRED mode: per-host outbound client handlers (D2)
void onPairedOutboundConnected(FramedTcpClient* client);
void onPairedOutboundDisconnected(FramedTcpClient* client,
Async::TcpConnection* con,
Async::TcpConnection::DisconnectReason reason);
void onPairedOutboundFrame(FramedTcpClient* client,
Async::FramedTcpConnection* con,
std::vector<uint8_t>& data);
size_t pairedClientIndex(FramedTcpClient* client) const;
void sendMsgOnPairedOutbound(size_t idx, const ReflectorMsg& msg);
// Per-client handshake/heartbeat state for paired outbound connections
struct PairedClientState
{
bool hello_received = false;
unsigned hb_tx_cnt = 0;
unsigned hb_rx_cnt = 0;
};
std::vector<PairedClientState> m_ob_states; // parallel to m_ob_cons
}; /* class TrunkLink */