feat(voice): guarantee an empty generated channel disappears
A generated channel could survive with nobody in it: the row was dropped before the channel was really gone, so a refused delete call left a room nothing could track anymore, and an event missed while the bot was down was never retried. The row is now kept until Discord confirms the channel is gone, and a sweep at startup then every minute deletes whatever the event missed. The grace period is tunable with VOICE_EMPTY_GRACE_MS, 0 deleting as soon as the room empties.
This commit is contained in:
5 files changed
+227
-36
No files matched your search
@@ -10,6 +10,13 @@ const readBool = (key, fallback = false) => {
|
||||
const value = read(key);
|
||||
return value === '' ? fallback : value === 'true';
|
||||
};
|
||||
/** Durations accept 0, which `readInt` cannot express because 0 is falsy. */
|
||||
const readDuration = (key, fallback) => {
|
||||
const value = read(key);
|
||||
if (value === '') return fallback;
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
|
||||
};
|
||||
|
||||
export const env = Object.freeze({
|
||||
nodeEnv: read('NODE_ENV', 'development'),
|
||||
@@ -47,6 +54,10 @@ export const env = Object.freeze({
|
||||
voiceCategory: read('CATEGORY_VOICE_ID'),
|
||||
},
|
||||
|
||||
voice: {
|
||||
emptyGraceMs: readDuration('VOICE_EMPTY_GRACE_MS', 5_000),
|
||||
},
|
||||
|
||||
gitea: {
|
||||
url: read('GITEA_URL').replace(/\/+$/, ''),
|
||||
token: read('GITEA_TOKEN'),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ActivityType, Events } from 'discord.js';
|
||||
import { createLogger } from '../core/logger.js';
|
||||
import { startPollScheduler } from '../services/polls/poll-service.js';
|
||||
import { sweepVoiceChannels } from '../services/voice/voice-service.js';
|
||||
import { startVoiceJanitor, sweepVoiceChannels } from '../services/voice/voice-service.js';
|
||||
|
||||
const log = createLogger('discord');
|
||||
|
||||
@@ -12,6 +12,7 @@ export async function execute(client) {
|
||||
client.user.setActivity('FWS Arch', { type: ActivityType.Watching });
|
||||
startPollScheduler(client);
|
||||
await sweepVoiceChannels(client);
|
||||
startVoiceJanitor(client);
|
||||
log.info(`Connected as ${client.user.tag}`, {
|
||||
guilds: client.guilds.cache.size,
|
||||
commands: client.commands.size,
|
||||
|
||||
@@ -41,8 +41,13 @@ export const DEFAULT_TEMPLATE = '🔊 Salon de {user}';
|
||||
/** Discord caps the user limit of a voice channel at 99 (0 means unlimited). */
|
||||
export const LIMIT_MAX = 99;
|
||||
export const NAME_MAX = 100;
|
||||
/** Delay before an empty temporary channel is deleted, so a quick move does not destroy it. */
|
||||
const EMPTY_GRACE_MS = 5_000;
|
||||
/**
|
||||
* Delay before an empty temporary channel is deleted, so a quick move does not destroy a channel
|
||||
* its owner customised. `VOICE_EMPTY_GRACE_MS=0` deletes it as soon as it is empty (M14-T04).
|
||||
*/
|
||||
const EMPTY_GRACE_MS = Math.max(0, env.voice.emptyGraceMs);
|
||||
/** Interval of the safety net that catches the channels an event could not clean up. */
|
||||
const SWEEP_INTERVAL_MS = 60_000;
|
||||
|
||||
/** Creation in flight per member, to never create two channels for the same person (M14-T02). */
|
||||
const pendingCreations = new Set();
|
||||
@@ -443,44 +448,82 @@ export async function createFromTrigger(member, trigger) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Deletes a temporary channel and forgets it. */
|
||||
/**
|
||||
* Deletes a temporary channel. The row is only dropped once the channel is really gone, so that a
|
||||
* failed API call leaves a channel the sweep can retry instead of an orphaned room (M14-T04).
|
||||
*/
|
||||
export async function deleteVoiceChannel(channel, reason = 'Salon vocal temporaire supprimé') {
|
||||
removeVoiceChannel(channel.id);
|
||||
panelMessages.delete(channel.id);
|
||||
return channel.delete(reason).catch((error) => log.warn('Could not delete the voice channel', error));
|
||||
try {
|
||||
await channel.delete(reason);
|
||||
} catch (error) {
|
||||
if (!(await isChannelGone(channel, error))) {
|
||||
log.warn('Could not delete the voice channel', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
forgetVoiceChannel(channel.id);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** A 404 or an unknown-channel error means the channel is already deleted, whatever the cause. */
|
||||
async function isChannelGone(channel, error) {
|
||||
const codes = [error?.code, String(error?.code ?? '')];
|
||||
if (error?.status === 404 || codes.includes(10003)) return true;
|
||||
|
||||
const fresh = await channel.guild.channels.fetch(channel.id).catch(() => null);
|
||||
return fresh === null;
|
||||
}
|
||||
|
||||
/** Resolves a channel from the cache or the API, or `null` when it does not exist anymore. */
|
||||
async function resolveChannel(guild, channelId) {
|
||||
return guild.channels.cache.get(channelId) ?? (await guild.channels.fetch(channelId).catch(() => null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an empty temporary channel after a short grace period, so that a member
|
||||
* moving between channels does not lose their channel (M14-T04).
|
||||
* Deletes an empty temporary channel after a short grace period, so that a member moving between
|
||||
* channels does not lose the one they customised (M14-T04).
|
||||
*/
|
||||
export async function cleanupVoiceChannel(guild, channelId) {
|
||||
export async function cleanupVoiceChannel(guild, channelId, { graceMs = EMPTY_GRACE_MS } = {}) {
|
||||
const row = getVoiceChannel(channelId);
|
||||
if (!row) return;
|
||||
|
||||
const channel =
|
||||
guild.channels.cache.get(channelId) ?? (await guild.channels.fetch(channelId).catch(() => null));
|
||||
const channel = await resolveChannel(guild, channelId);
|
||||
if (!channel) {
|
||||
removeVoiceChannel(channelId);
|
||||
forgetVoiceChannel(channelId);
|
||||
return;
|
||||
}
|
||||
if (channel.members.size > 0) return;
|
||||
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
const fresh =
|
||||
guild.channels.cache.get(channelId) ?? (await guild.channels.fetch(channelId).catch(() => null));
|
||||
if (!fresh || fresh.members.size > 0) return;
|
||||
|
||||
await deleteVoiceChannel(fresh, 'Salon vocal temporaire vide').catch(() => {});
|
||||
logEvent({ guildId: guild.id, type: 'voice.deleted', payload: { channelId } });
|
||||
} catch (error) {
|
||||
log.warn('Could not clean up an empty voice channel', error);
|
||||
const removeEmptyChannel = async () => {
|
||||
const fresh = await resolveChannel(guild, channelId);
|
||||
if (!fresh) {
|
||||
forgetVoiceChannel(channelId);
|
||||
return;
|
||||
}
|
||||
}, EMPTY_GRACE_MS).unref();
|
||||
if (fresh.members.size > 0) return;
|
||||
|
||||
if (await deleteVoiceChannel(fresh, 'Salon vocal temporaire vide')) {
|
||||
logEvent({ guildId: guild.id, type: 'voice.deleted', payload: { channelId } });
|
||||
}
|
||||
};
|
||||
|
||||
if (graceMs <= 0) {
|
||||
await removeEmptyChannel().catch((error) => log.warn('Could not clean up an empty voice channel', error));
|
||||
return;
|
||||
}
|
||||
|
||||
setTimeout(
|
||||
() => removeEmptyChannel().catch((error) => log.warn('Could not clean up an empty voice channel', error)),
|
||||
graceMs,
|
||||
).unref();
|
||||
}
|
||||
|
||||
/** Startup sweep: forget deleted channels, remove the ones left empty by a restart (M14-T07). */
|
||||
/**
|
||||
* Forgets the channels that no longer exist and deletes the ones with nobody left in them
|
||||
* (M14-T04 / M14-T07). Run at startup and then every minute: the voice state event is the fast
|
||||
* path, this sweep is the guarantee when an event is missed or a deletion failed.
|
||||
*/
|
||||
export async function sweepVoiceChannels(client) {
|
||||
for (const guild of client.guilds.cache.values()) {
|
||||
let rows = [];
|
||||
@@ -492,21 +535,30 @@ export async function sweepVoiceChannels(client) {
|
||||
}
|
||||
|
||||
for (const row of rows) {
|
||||
const channel =
|
||||
guild.channels.cache.get(row.channel_id) ??
|
||||
(await guild.channels.fetch(row.channel_id).catch(() => null));
|
||||
const channel = await resolveChannel(guild, row.channel_id);
|
||||
if (!channel) {
|
||||
removeVoiceChannel(row.channel_id);
|
||||
panelMessages.delete(row.channel_id);
|
||||
forgetVoiceChannel(row.channel_id);
|
||||
continue;
|
||||
}
|
||||
if (channel.members.size === 0) {
|
||||
await deleteVoiceChannel(channel, 'Salon vocal temporaire vide après redémarrage');
|
||||
if (channel.members.size > 0) continue;
|
||||
|
||||
if (await deleteVoiceChannel(channel, 'Salon vocal temporaire vide')) {
|
||||
log.info(`Deleted the empty temporary channel ${row.channel_id}`);
|
||||
logEvent({ guildId: guild.id, type: 'voice.deleted', payload: { channelId: row.channel_id } });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Starts the periodic sweep; the returned interval can be cleared to stop it (M14-T04). */
|
||||
export function startVoiceJanitor(client, intervalMs = SWEEP_INTERVAL_MS) {
|
||||
const timer = setInterval(() => {
|
||||
sweepVoiceChannels(client).catch((error) => log.error('Voice channel sweep failed', error));
|
||||
}, intervalMs);
|
||||
timer.unref?.();
|
||||
return timer;
|
||||
}
|
||||
|
||||
export function activeChannelCount(guildId) {
|
||||
return countVoiceChannels(guildId);
|
||||
}
|
||||
@@ -525,18 +577,20 @@ export async function resolveManagedChannel(interaction, { channelId = null } =
|
||||
const row = id ? getVoiceChannel(id) : null;
|
||||
if (!row) {
|
||||
throw new UserFacingError(
|
||||
'Rejoins ton salon vocal temporaire pour le gérer, ou précise l’option `channel`.',
|
||||
'Je ne trouve pas ton salon temporaire : entre dans ton salon vocal, puis relance la commande — ou indique‑le avec l’option `channel`.',
|
||||
);
|
||||
}
|
||||
if (channelId && channelId !== interaction.member?.voice?.channelId && !isStaff(interaction.member)) {
|
||||
// An explicit channel is a staff convenience only: a member manages their own channel.
|
||||
throw new PermissionDeniedError('Seul le staff peut cibler le salon d’un autre membre.');
|
||||
throw new PermissionDeniedError(
|
||||
'C’est réservé à l’équipe : chaque personne gère son propre salon. Tu peux modifier le tien, sans option `channel`.',
|
||||
);
|
||||
}
|
||||
|
||||
const channel = await interaction.guild.channels.fetch(row.channel_id).catch(() => null);
|
||||
if (!channel) {
|
||||
removeVoiceChannel(row.channel_id);
|
||||
throw new UserFacingError('Ce salon vocal n’existe plus.');
|
||||
forgetVoiceChannel(row.channel_id);
|
||||
throw new UserFacingError('Ce salon n’existe plus — il a sûrement déjà été supprimé.');
|
||||
}
|
||||
return { channel, row };
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user