Leave voice before closing the server on shutdown

AlreadyConnected kept coming back after every rebuild. Shutdown closed
the HTTP server first, which blocks while the panel's WebSocket is open,
so Docker's grace period ran out and the process was killed before it
ever left the voice channels — and Stoat only clears a bot's voice state
when it disconnects, leaving the stale entry that refuses the next join.

Voice channels are now left first, and each shutdown step has its own
deadline so neither can eat the grace period.

A failed join_call also escaped as an unhandled rejection with a full
stack, because revoice awaits it inside an async executor it never
guards; the error is already latched and reported, so that call no longer
settles at all.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Leonid Pershin
2026-09-09 02:44:36 +03:00
co-authored by Claude Opus 5
parent 224d5679a3
commit c7f2080604
3 changed files with 33 additions and 10 deletions
+8 -2
View File
@@ -164,8 +164,14 @@ cd /opt/stoat-mbot && docker compose up -d --build && docker compose logs -f
docker compose exec redis valkey-cli SREM 'vc_members:<ID_голосового_канала>' '<ID_бота>' docker compose exec redis valkey-cli SREM 'vc_members:<ID_голосового_канала>' '<ID_бота>'
``` ```
В норме состояние снимает `voice-ingress` по вебхуку от LiveKit — если ситуация повторяется Решает дело именно `DEL vc:<ID_бота>` — он должен вернуть `(integer) 1`. `SREM` часто
после каждого перезапуска, смотрите `docker compose logs voice-ingress`. возвращает `0`, это нормально: участники там хранятся в другом виде.
Само состояние снимает Stoat, когда бот отключается от LiveKit, поэтому важно, чтобы бот
успевал корректно выйти при остановке контейнера — он выходит из каналов первым делом, с
отдельным лимитом времени. Если проблема всё же повторяется после каждого перезапуска,
смотрите `docker compose logs voice-ingress`: снимать состояние по вебхуку от LiveKit —
его работа.
4. **Бот в канале, но звука нет.** Это уже медиа-трафик: LiveKit анонсирует клиентам свой адрес 4. **Бот в канале, но звука нет.** Это уже медиа-трафик: LiveKit анонсирует клиентам свой адрес
из `rtc.node_ip` / `use_external_ip` в `/opt/stoat/livekit.yml` и ждёт UDP на 50000-50100. из `rtc.node_ip` / `use_external_ip` в `/opt/stoat/livekit.yml` и ждёт UDP на 50000-50100.
Если анонсируется внешний IP, а роутер не умеет NAT loopback, пакеты от контейнера до него не Если анонсируется внешний IP, а роутер не умеет NAT loopback, пакеты от контейнера до него не
+5
View File
@@ -108,6 +108,11 @@ export function createRevoice(token: string, baseURL: string, node: string): Rev
return await post(path, payload, params); return await post(path, payload, params);
} catch (err) { } catch (err) {
pendingError = describeApiError(err); pendingError = describeApiError(err);
// revoice awaits this inside an async executor it never guards, so a
// rejection here escapes as an unhandled rejection with a full stack for
// what is an ordinary, already-reported error. Our join() wrapper below
// picks the latched error up, so this call simply never settles.
if (path.endsWith("/join_call")) return new Promise<never>(() => {});
throw pendingError; throw pendingError;
} }
}; };
+19 -7
View File
@@ -59,16 +59,28 @@ async function main(): Promise<void> {
const bot = await startBot(manager); const bot = await startBot(manager);
const app = await startApiServer({ manager, context: bot.context }); const app = await startApiServer({ manager, context: bot.context });
/** Never let a slow step eat the container's grace period. */
const withDeadline = async (task: Promise<unknown>, ms: number, what: string): Promise<void> => {
let timer: NodeJS.Timeout | undefined;
const deadline = new Promise<void>((resolve) => {
timer = setTimeout(() => {
logger.warn({ step: what }, "shutdown step timed out, moving on");
resolve();
}, ms);
});
await Promise.race([task.catch((err) => logger.error({ err, step: what }, "shutdown step failed")), deadline]);
if (timer) clearTimeout(timer);
};
const shutdown = async (signal: string): Promise<void> => { const shutdown = async (signal: string): Promise<void> => {
logger.info({ signal }, "shutting down"); logger.info({ signal }, "shutting down");
try { // Leaving voice comes first and gets its own deadline: Stoat only clears the
await app.close(); // bot's voice state when it disconnects, and a state left behind makes the
await bot.stop(); // next join fail with AlreadyConnected. Closing the HTTP server can block on
} catch (err) { // an open panel WebSocket, which used to eat the whole grace period.
logger.error({ err }, "shutdown failed"); await withDeadline(bot.stop(), 5000, "leave voice channels");
} finally { await withDeadline(app.close(), 3000, "close http server");
process.exit(0); process.exit(0);
}
}; };
process.on("SIGINT", () => void shutdown("SIGINT")); process.on("SIGINT", () => void shutdown("SIGINT"));