diff --git a/.env.example b/.env.example index 97ea3f2..e64da61 100644 --- a/.env.example +++ b/.env.example @@ -47,6 +47,9 @@ CATEGORY_TICKETS_ID= CHANNEL_VOICE_TRIGGER_ID= # Catégorie d'accueil des salons vocaux créés (facultatif) CATEGORY_VOICE_ID= +# Délai avant qu'un salon généré devenu vide soit supprimé, en ms (0 = immédiat) +VOICE_EMPTY_GRACE_MS=5000 + # --- Gitea (M5-T01) ---------------------------------------------------------- GITEA_URL=https://gitea.nocode-var.tech diff --git a/src/config/env.js b/src/config/env.js index 9b9e5e3..4a4b13f 100644 --- a/src/config/env.js +++ b/src/config/env.js @@ -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'), diff --git a/src/events/client-ready.js b/src/events/client-ready.js index f148589..373d835 100644 --- a/src/events/client-ready.js +++ b/src/events/client-ready.js @@ -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, diff --git a/src/services/voice/voice-service.js b/src/services/voice/voice-service.js index 266c137..1734a70 100644 --- a/src/services/voice/voice-service.js +++ b/src/services/voice/voice-service.js @@ -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 }; } diff --git a/tests/voice.test.js b/tests/voice.test.js index 6b5921b..8b0b37f 100644 --- a/tests/voice.test.js +++ b/tests/voice.test.js @@ -22,7 +22,9 @@ import { bottomPosition, buildChannelName, clampLimit, + cleanupVoiceChannel, createFromTrigger, + deleteVoiceChannel, findTrigger, getVoiceTrigger, getVoiceTriggers, @@ -32,6 +34,8 @@ import { sanitizeChannelName, saveVoiceTrigger, setTriggerEnabled, + startVoiceJanitor, + sweepVoiceChannels, } from '../src/services/voice/voice-service.js'; const member = (roleIds = [], { id = 'u1', guildOwnerId = 'someone-else' } = {}) => ({ @@ -349,6 +353,124 @@ describe('voice channel creation from a trigger', () => { }); }); +describe('empty generated channels', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => { + getDatabase().exec('DELETE FROM voice_channels'); + }); + + const track = (channelId, ownerId = 'u1', triggerId = 'dev') => + addVoiceChannel({ channelId, guildId: 'g', ownerId, triggerId, name: `salon-${channelId}` }); + + const voiceChannel = (id, { members = [] } = {}) => ({ + id, + parentId: 'cat', + members: new Collection(members.map((memberId) => [memberId, { id: memberId }])), + deleted: false, + failure: null, + async delete() { + if (this.failure) throw this.failure; + this.deleted = true; + }, + }); + + /** Guild mock whose `fetch` only knows the cached channels, like a channel deleted by hand. */ + const makeGuild = (channels) => { + const cache = new Collection(channels.map((channel) => [channel.id, channel])); + const guild = { id: 'g', channels: { cache, fetch: async (id) => cache.get(id) ?? null } }; + for (const channel of cache.values()) channel.guild = guild; + return guild; + }; + + const clientOf = (...guilds) => ({ guilds: { cache: new Collection(guilds.map((g) => [g.id, g])) } }); + + it('deletes a generated channel as soon as nobody is left in it', async () => { + track('c1'); + const channel = voiceChannel('c1'); + + await cleanupVoiceChannel(makeGuild([channel]), 'c1', { graceMs: 0 }); + + assert.equal(channel.deleted, true); + assert.equal(getVoiceChannel('c1'), null, 'the row is forgotten too'); + }); + + it('keeps a channel that still has members', async () => { + track('c1'); + const channel = voiceChannel('c1', { members: ['u2'] }); + + await cleanupVoiceChannel(makeGuild([channel]), 'c1', { graceMs: 0 }); + + assert.equal(channel.deleted, false); + assert.ok(getVoiceChannel('c1')); + }); + + it('leaves a grace period during which the owner can come back', async () => { + track('c1'); + const channel = voiceChannel('c1'); + + const pending = cleanupVoiceChannel(makeGuild([channel]), 'c1', { graceMs: 30 }); + channel.members.set('u1', { id: 'u1' }); + await pending; + await new Promise((resolve) => setTimeout(resolve, 60)); + + assert.equal(channel.deleted, false, 'the customised channel survives a quick move'); + assert.ok(getVoiceChannel('c1')); + }); + + it('deletes the empty channels and forgets the vanished ones in one sweep', async () => { + track('vide'); + track('occupe', 'u2'); + track('disparu', 'u3', 'sio'); + + const empty = voiceChannel('vide'); + const busy = voiceChannel('occupe', { members: ['u2'] }); + await sweepVoiceChannels(clientOf(makeGuild([empty, busy]))); + + assert.equal(empty.deleted, true); + assert.equal(busy.deleted, false); + assert.equal(getVoiceChannel('vide'), null); + assert.equal(getVoiceChannel('disparu'), null, 'a channel deleted by hand is forgotten'); + assert.ok(getVoiceChannel('occupe')); + }); + + it('runs that sweep on an interval', async () => { + track('c1'); + const channel = voiceChannel('c1'); + + const timer = startVoiceJanitor(clientOf(makeGuild([channel])), 20); + await new Promise((resolve) => setTimeout(resolve, 60)); + clearInterval(timer); + + assert.equal(channel.deleted, true); + assert.equal(getVoiceChannel('c1'), null); + }); + + it('keeps the row when the deletion fails, so the sweep can retry', async () => { + track('c1'); + const channel = voiceChannel('c1'); + channel.failure = Object.assign(new Error('Missing Permissions'), { code: 50013, status: 403 }); + makeGuild([channel]); + + assert.equal(await deleteVoiceChannel(channel, 'test'), false); + assert.ok(getVoiceChannel('c1'), 'the channel is not leaked'); + + channel.failure = null; + assert.equal(await deleteVoiceChannel(channel, 'test'), true); + assert.equal(getVoiceChannel('c1'), null); + }); + + it('forgets a channel that Discord has already deleted', async () => { + track('c1'); + const channel = voiceChannel('c1'); + channel.failure = Object.assign(new Error('Unknown Channel'), { code: 10003 }); + makeGuild([channel]); + + assert.equal(await deleteVoiceChannel(channel, 'test'), true); + assert.equal(getVoiceChannel('c1'), null); + }); +}); + describe('voice helpers', () => { it('normalises a channel name', () => { assert.equal(sanitizeChannelName(' Salon de Léa '), 'Salon de Léa');