From 9ce6211b03c3441c17624e1620eafdd3f81177e4 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 11:54:48 +0200 Subject: [PATCH] Test: live:client hash appears/disappears on V2 auth/disconnect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add RedisLiveStateTest (2 tests) to test_redis.py verifying that live:client: 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. --- src/svxlink/reflector/RedisStore.cpp | 94 +++++++++++++++++++++------- src/svxlink/reflector/RedisStore.h | 5 +- tests/test_redis.py | 69 ++++++++++++++++++++ 3 files changed, 145 insertions(+), 23 deletions(-) diff --git a/src/svxlink/reflector/RedisStore.cpp b/src/svxlink/reflector/RedisStore.cpp index 5fe483d..3c854cb 100644 --- a/src/svxlink/reflector/RedisStore.cpp +++ b/src/svxlink/reflector/RedisStore.cpp @@ -25,6 +25,11 @@ void onAsyncDisconnectThunk(const redisAsyncContext* ac, int status) { if (self) self->onAsyncDisconnect(status); } +void onAsyncWriteDisconnectThunk(const redisAsyncContext* ac, int status) { + auto* self = static_cast(ac->data); + if (self) self->onAsyncWriteDisconnect(status); +} + } // namespace RedisStore::RedisStore(const Config& cfg) : m_cfg(cfg) {} @@ -34,6 +39,7 @@ RedisStore::~RedisStore() { delete m_heartbeat_timer; m_heartbeat_timer = nullptr; delete m_drain_timer; m_drain_timer = 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_sync) { redisFree(m_sync); m_sync = nullptr; } } @@ -78,6 +84,7 @@ bool RedisStore::connect(void) { if (!connectSync()) return false; if (!connectAsync()) return false; subscribe(); + if (!connectAsyncWrite()) return false; m_live_queue = new RedisLiveQueue(4096); m_drain_timer = new Async::Timer(75, Async::Timer::TYPE_PERIODIC); @@ -329,6 +336,35 @@ bool RedisStore::connectAsync(void) { 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) { if (!m_async) return; std::string ch = channelName(); @@ -343,6 +379,13 @@ void RedisStore::onAsyncDisconnect(int /*status*/) { 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) { if (m_shutting_down) return; delete m_reconnect_timer; @@ -350,30 +393,37 @@ void RedisStore::scheduleReconnect(void) { Async::Timer::TYPE_ONESHOT); m_reconnect_timer->expired.connect([this](Async::Timer*) { if (m_shutting_down) return; - if (connectAsync()) { - subscribe(); - // Rebuild sync context too — its TCP socket is likely dead. - if (m_sync) { redisFree(m_sync); m_sync = nullptr; } - if (!connectSync()) { - std::cerr << "*** WARN: Redis sync reconnect failed" << std::endl; - // async is up but sync isn't — schedule another retry so we fix sync. - m_reconnect_backoff_s = std::min(m_reconnect_backoff_s * 2, 30); - scheduleReconnect(); - return; - } - std::cout << "RedisStore: reconnected, re-subscribing and requesting " - "full reload" << std::endl; - m_reconnect_backoff_s = 1; - configChanged.emit("all"); - } else { + // 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(); + // Rebuild sync context too — its TCP socket is likely dead. + if (m_sync) { redisFree(m_sync); m_sync = nullptr; } + if (!connectSync()) { + std::cerr << "*** WARN: Redis sync reconnect failed" << std::endl; + // async is up but sync isn't — schedule another retry so we fix sync. + m_reconnect_backoff_s = std::min(m_reconnect_backoff_s * 2, 30); + scheduleReconnect(); + return; + } + std::cout << "RedisStore: reconnected, re-subscribing and requesting " + "full reload" << std::endl; + m_reconnect_backoff_s = 1; + configChanged.emit("all"); }); } void RedisStore::onPubSubMessage(const std::string&, const std::string&) {} void RedisStore::drainLiveQueue(Async::Timer*) { - if (!m_async || !m_live_queue) return; + if (!m_async_write || !m_live_queue) return; std::vector ops; m_live_queue->drain(ops); 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.second.c_str()); argl.push_back(kv.second.size()); } - redisAsyncCommandArgv(m_async, nullptr, nullptr, + redisAsyncCommandArgv(m_async_write, nullptr, nullptr, static_cast(argv.size()), argv.data(), argl.data()); 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); } break; } case RedisLiveQueue::OpType::DEL: - redisAsyncCommand(m_async, nullptr, nullptr, + redisAsyncCommand(m_async_write, nullptr, nullptr, "DEL %s", op.key.c_str()); break; 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); break; } @@ -411,7 +461,7 @@ void RedisStore::drainLiveQueue(Async::Timer*) { // Notify dashboards once per drain cycle. std::string ch = keyFor("live.changed"); - redisAsyncCommand(m_async, nullptr, nullptr, + redisAsyncCommand(m_async_write, nullptr, nullptr, "PUBLISH %s tick", ch.c_str()); } void RedisStore::refreshLiveExpire(Async::Timer*) { diff --git a/src/svxlink/reflector/RedisStore.h b/src/svxlink/reflector/RedisStore.h index 1f8d8b7..655668a 100644 --- a/src/svxlink/reflector/RedisStore.h +++ b/src/svxlink/reflector/RedisStore.h @@ -82,11 +82,13 @@ class RedisStore : public sigc::trackable size_t liveQueueSize(void) const; void onAsyncDisconnect(int status); + void onAsyncWriteDisconnect(int status); private: Config m_cfg; 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; RedisLiveQueue* m_live_queue = nullptr; Async::Timer* m_drain_timer = nullptr; @@ -99,6 +101,7 @@ class RedisStore : public sigc::trackable bool connectSync(void); bool connectAsync(void); + bool connectAsyncWrite(void); void subscribe(void); void scheduleReconnect(void); void onPubSubMessage(const std::string& channel, const std::string& payload); diff --git a/tests/test_redis.py b/tests/test_redis.py index 69a2f2c..83bd40b 100755 --- a/tests/test_redis.py +++ b/tests/test_redis.py @@ -221,5 +221,74 @@ class RedisPtyMuteTest(unittest.TestCase): self._wait_for_members(key, "SM0XYZ", present=False) +class RedisLiveStateTest(unittest.TestCase): + """Verify live:client: 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__": unittest.main(verbosity=2)