Test: live:client hash appears/disappears on V2 auth/disconnect

Add RedisLiveStateTest (2 tests) to test_redis.py verifying that
live:client:<callsign> hashes appear in Redis on V2 client auth and
are deleted on disconnect.

Fix a pre-existing bug in RedisStore where drainLiveQueue() sent HSET/
DEL/EXPIRE commands on m_async — the same hiredis context used for
SUBSCRIBE. Redis rejects non-pub/sub commands on a subscribed connection,
causing the repeated "async disconnect" loop seen in logs. Add a second
async context m_async_write exclusively for live-state writes; the sub
context m_async is now used only for SUBSCRIBE/config.changed delivery.

All 7 Redis integration tests pass.
This commit is contained in:
Audric committed 2026-04-15 11:54:48 +02:00
1 parent 685696b6b2
commit 9ce6211b03
3 files changed
+134 -12

No files matched your search

+61 -11
View File
@@ -25,6 +25,11 @@ void onAsyncDisconnectThunk(const redisAsyncContext* ac, int status) {
if (self) self->onAsyncDisconnect(status); if (self) self->onAsyncDisconnect(status);
} }
void onAsyncWriteDisconnectThunk(const redisAsyncContext* ac, int status) {
auto* self = static_cast<RedisStore*>(ac->data);
if (self) self->onAsyncWriteDisconnect(status);
}
} // namespace } // namespace
RedisStore::RedisStore(const Config& cfg) : m_cfg(cfg) {} RedisStore::RedisStore(const Config& cfg) : m_cfg(cfg) {}
@@ -34,6 +39,7 @@ RedisStore::~RedisStore() {
delete m_heartbeat_timer; m_heartbeat_timer = nullptr; delete m_heartbeat_timer; m_heartbeat_timer = nullptr;
delete m_drain_timer; m_drain_timer = nullptr; delete m_drain_timer; m_drain_timer = nullptr;
delete m_live_queue; m_live_queue = nullptr; delete m_live_queue; m_live_queue = nullptr;
if (m_async_write) { redisAsyncFree(m_async_write); m_async_write = nullptr; }
if (m_async) { redisAsyncFree(m_async); m_async = nullptr; } if (m_async) { redisAsyncFree(m_async); m_async = nullptr; }
if (m_sync) { redisFree(m_sync); m_sync = nullptr; } if (m_sync) { redisFree(m_sync); m_sync = nullptr; }
} }
@@ -78,6 +84,7 @@ bool RedisStore::connect(void) {
if (!connectSync()) return false; if (!connectSync()) return false;
if (!connectAsync()) return false; if (!connectAsync()) return false;
subscribe(); subscribe();
if (!connectAsyncWrite()) return false;
m_live_queue = new RedisLiveQueue(4096); m_live_queue = new RedisLiveQueue(4096);
m_drain_timer = new Async::Timer(75, Async::Timer::TYPE_PERIODIC); m_drain_timer = new Async::Timer(75, Async::Timer::TYPE_PERIODIC);
@@ -329,6 +336,35 @@ bool RedisStore::connectAsync(void) {
return true; return true;
} }
bool RedisStore::connectAsyncWrite(void) {
if (!m_cfg.unix_socket.empty()) {
m_async_write = redisAsyncConnectUnix(m_cfg.unix_socket.c_str());
} else {
m_async_write = redisAsyncConnect(m_cfg.host.c_str(), m_cfg.port);
}
if (!m_async_write || m_async_write->err) {
std::cerr << "*** ERROR: Redis async-write connect failed: "
<< (m_async_write ? m_async_write->errstr : "alloc failed")
<< std::endl;
if (m_async_write) { redisAsyncFree(m_async_write); m_async_write = nullptr; }
return false;
}
m_async_write->data = this;
if (!RedisAsyncAdapter::attach(m_async_write)) {
redisAsyncFree(m_async_write); m_async_write = nullptr;
return false;
}
redisAsyncSetDisconnectCallback(m_async_write, onAsyncWriteDisconnectThunk);
if (!m_cfg.password.empty()) {
redisAsyncCommand(m_async_write, nullptr, nullptr, "AUTH %s", m_cfg.password.c_str());
}
if (m_cfg.db != 0) {
redisAsyncCommand(m_async_write, nullptr, nullptr, "SELECT %d", m_cfg.db);
}
return true;
}
void RedisStore::subscribe(void) { void RedisStore::subscribe(void) {
if (!m_async) return; if (!m_async) return;
std::string ch = channelName(); std::string ch = channelName();
@@ -343,6 +379,13 @@ void RedisStore::onAsyncDisconnect(int /*status*/) {
scheduleReconnect(); scheduleReconnect();
} }
void RedisStore::onAsyncWriteDisconnect(int /*status*/) {
if (m_shutting_down) return;
std::cerr << "*** WARN: Redis async-write disconnect" << std::endl;
m_async_write = nullptr;
scheduleReconnect();
}
void RedisStore::scheduleReconnect(void) { void RedisStore::scheduleReconnect(void) {
if (m_shutting_down) return; if (m_shutting_down) return;
delete m_reconnect_timer; delete m_reconnect_timer;
@@ -350,7 +393,18 @@ void RedisStore::scheduleReconnect(void) {
Async::Timer::TYPE_ONESHOT); Async::Timer::TYPE_ONESHOT);
m_reconnect_timer->expired.connect([this](Async::Timer*) { m_reconnect_timer->expired.connect([this](Async::Timer*) {
if (m_shutting_down) return; if (m_shutting_down) return;
if (connectAsync()) { // Reconnect sub context if needed.
if (!m_async && !connectAsync()) {
m_reconnect_backoff_s = std::min(m_reconnect_backoff_s * 2, 30);
scheduleReconnect();
return;
}
if (!m_async_write && !connectAsyncWrite()) {
m_reconnect_backoff_s = std::min(m_reconnect_backoff_s * 2, 30);
scheduleReconnect();
return;
}
// If sub was freshly reconnected, re-subscribe.
subscribe(); subscribe();
// Rebuild sync context too — its TCP socket is likely dead. // Rebuild sync context too — its TCP socket is likely dead.
if (m_sync) { redisFree(m_sync); m_sync = nullptr; } if (m_sync) { redisFree(m_sync); m_sync = nullptr; }
@@ -365,15 +419,11 @@ void RedisStore::scheduleReconnect(void) {
"full reload" << std::endl; "full reload" << std::endl;
m_reconnect_backoff_s = 1; m_reconnect_backoff_s = 1;
configChanged.emit("all"); configChanged.emit("all");
} else {
m_reconnect_backoff_s = std::min(m_reconnect_backoff_s * 2, 30);
scheduleReconnect();
}
}); });
} }
void RedisStore::onPubSubMessage(const std::string&, const std::string&) {} void RedisStore::onPubSubMessage(const std::string&, const std::string&) {}
void RedisStore::drainLiveQueue(Async::Timer*) { void RedisStore::drainLiveQueue(Async::Timer*) {
if (!m_async || !m_live_queue) return; if (!m_async_write || !m_live_queue) return;
std::vector<RedisLiveQueue::Op> ops; std::vector<RedisLiveQueue::Op> ops;
m_live_queue->drain(ops); m_live_queue->drain(ops);
if (ops.empty()) return; if (ops.empty()) return;
@@ -389,21 +439,21 @@ void RedisStore::drainLiveQueue(Async::Timer*) {
argv.push_back(kv.first.c_str()); argl.push_back(kv.first.size()); argv.push_back(kv.first.c_str()); argl.push_back(kv.first.size());
argv.push_back(kv.second.c_str()); argl.push_back(kv.second.size()); argv.push_back(kv.second.c_str()); argl.push_back(kv.second.size());
} }
redisAsyncCommandArgv(m_async, nullptr, nullptr, redisAsyncCommandArgv(m_async_write, nullptr, nullptr,
static_cast<int>(argv.size()), static_cast<int>(argv.size()),
argv.data(), argl.data()); argv.data(), argl.data());
if (op.ttl_s > 0) { if (op.ttl_s > 0) {
redisAsyncCommand(m_async, nullptr, nullptr, redisAsyncCommand(m_async_write, nullptr, nullptr,
"EXPIRE %s %d", op.key.c_str(), op.ttl_s); "EXPIRE %s %d", op.key.c_str(), op.ttl_s);
} }
break; break;
} }
case RedisLiveQueue::OpType::DEL: case RedisLiveQueue::OpType::DEL:
redisAsyncCommand(m_async, nullptr, nullptr, redisAsyncCommand(m_async_write, nullptr, nullptr,
"DEL %s", op.key.c_str()); "DEL %s", op.key.c_str());
break; break;
case RedisLiveQueue::OpType::EXPIRE: case RedisLiveQueue::OpType::EXPIRE:
redisAsyncCommand(m_async, nullptr, nullptr, redisAsyncCommand(m_async_write, nullptr, nullptr,
"EXPIRE %s %d", op.key.c_str(), op.ttl_s); "EXPIRE %s %d", op.key.c_str(), op.ttl_s);
break; break;
} }
@@ -411,7 +461,7 @@ void RedisStore::drainLiveQueue(Async::Timer*) {
// Notify dashboards once per drain cycle. // Notify dashboards once per drain cycle.
std::string ch = keyFor("live.changed"); std::string ch = keyFor("live.changed");
redisAsyncCommand(m_async, nullptr, nullptr, redisAsyncCommand(m_async_write, nullptr, nullptr,
"PUBLISH %s tick", ch.c_str()); "PUBLISH %s tick", ch.c_str());
} }
void RedisStore::refreshLiveExpire(Async::Timer*) { void RedisStore::refreshLiveExpire(Async::Timer*) {
+4 -1
View File
@@ -82,11 +82,13 @@ class RedisStore : public sigc::trackable
size_t liveQueueSize(void) const; size_t liveQueueSize(void) const;
void onAsyncDisconnect(int status); void onAsyncDisconnect(int status);
void onAsyncWriteDisconnect(int status);
private: private:
Config m_cfg; Config m_cfg;
redisContext* m_sync = nullptr; redisContext* m_sync = nullptr;
redisAsyncContext* m_async = nullptr; redisAsyncContext* m_async = nullptr; // pub/sub subscriber only
redisAsyncContext* m_async_write = nullptr; // live-state writes (HSET/DEL)
RedisAsyncAdapter* m_adapter = nullptr; RedisAsyncAdapter* m_adapter = nullptr;
RedisLiveQueue* m_live_queue = nullptr; RedisLiveQueue* m_live_queue = nullptr;
Async::Timer* m_drain_timer = nullptr; Async::Timer* m_drain_timer = nullptr;
@@ -99,6 +101,7 @@ class RedisStore : public sigc::trackable
bool connectSync(void); bool connectSync(void);
bool connectAsync(void); bool connectAsync(void);
bool connectAsyncWrite(void);
void subscribe(void); void subscribe(void);
void scheduleReconnect(void); void scheduleReconnect(void);
void onPubSubMessage(const std::string& channel, const std::string& payload); void onPubSubMessage(const std::string& channel, const std::string& payload);
+69
View File
@@ -221,5 +221,74 @@ class RedisPtyMuteTest(unittest.TestCase):
self._wait_for_members(key, "SM0XYZ", present=False) self._wait_for_members(key, "SM0XYZ", present=False)
class RedisLiveStateTest(unittest.TestCase):
"""Verify live:client:<callsign> hashes appear/disappear as V2 clients
connect and disconnect. Talker and trunk live-state are not covered here
(require UDP/trunk-peer scaffolding; deferred)."""
def setUp(self):
flushdb()
# Populate the user so authentication succeeds.
redis_cli("HSET", k("user:N0TEST"), "group", "TestGroup", "enabled", "1")
redis_cli("HSET", k("group:TestGroup"), "password", "testpass")
publish("users")
time.sleep(0.3)
def _wait_for_hash(self, key: str, present: bool,
timeout: float = 3.0):
"""Poll HGETALL until the key has/lacks fields. Redis TYPE is
checked via EXISTS — empty hashes don't exist."""
deadline = time.time() + timeout
last = ""
while time.time() < deadline:
exists = redis_cli("EXISTS", key).strip() == "1"
if present and exists:
last = redis_cli("HGETALL", key)
return last
if (not present) and (not exists):
return ""
time.sleep(0.1)
self.fail(
f"Timed out waiting for {key} "
f"{'to exist' if present else 'to be absent'}. Last: {last!r}")
def test_live_client_hash_appears_on_auth(self):
peer = ClientPeer()
peer.connect(HOST, R1_CLIENT_PORT)
try:
peer.authenticate(callsign="N0TEST", password="testpass")
raw = self._wait_for_hash(k("live:client:N0TEST"), present=True)
# HGETALL returns alternating field\nvalue\nfield\nvalue\n
fields = raw.splitlines()
mapping = dict(zip(fields[0::2], fields[1::2]))
self.assertIn("connected_at", mapping)
self.assertIn("ip", mapping)
self.assertIn("tg", mapping)
# codecs may be "" — just verify the field exists
self.assertIn("codecs", mapping)
# connected_at is a unix timestamp; sanity-check it's a
# reasonable value (positive, within last minute).
ts = int(mapping["connected_at"])
self.assertGreater(ts, 0)
self.assertLess(abs(ts - time.time()), 60)
finally:
try:
peer.tcp.close()
except Exception:
pass
def test_live_client_hash_disappears_on_disconnect(self):
peer = ClientPeer()
peer.connect(HOST, R1_CLIENT_PORT)
peer.authenticate(callsign="N0TEST", password="testpass")
self._wait_for_hash(k("live:client:N0TEST"), present=True)
# Forceful close — reflector should see disconnect quickly.
peer.tcp.close()
# Drain queue + Redis publish should take <100ms. Give more for slack.
self._wait_for_hash(k("live:client:N0TEST"), present=False, timeout=5.0)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main(verbosity=2) unittest.main(verbosity=2)