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
@@ -47,6 +47,9 @@ CATEGORY_TICKETS_ID=
|
|||||||
CHANNEL_VOICE_TRIGGER_ID=
|
CHANNEL_VOICE_TRIGGER_ID=
|
||||||
# Catégorie d'accueil des salons vocaux créés (facultatif)
|
# Catégorie d'accueil des salons vocaux créés (facultatif)
|
||||||
CATEGORY_VOICE_ID=
|
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 (M5-T01) ----------------------------------------------------------
|
||||||
GITEA_URL=https://gitea.nocode-var.tech
|
GITEA_URL=https://gitea.nocode-var.tech
|
||||||
|
|||||||
@@ -10,6 +10,13 @@ const readBool = (key, fallback = false) => {
|
|||||||
const value = read(key);
|
const value = read(key);
|
||||||
return value === '' ? fallback : value === 'true';
|
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({
|
export const env = Object.freeze({
|
||||||
nodeEnv: read('NODE_ENV', 'development'),
|
nodeEnv: read('NODE_ENV', 'development'),
|
||||||
@@ -47,6 +54,10 @@ export const env = Object.freeze({
|
|||||||
voiceCategory: read('CATEGORY_VOICE_ID'),
|
voiceCategory: read('CATEGORY_VOICE_ID'),
|
||||||
},
|
},
|
||||||
|
|
||||||
|
voice: {
|
||||||
|
emptyGraceMs: readDuration('VOICE_EMPTY_GRACE_MS', 5_000),
|
||||||
|
},
|
||||||
|
|
||||||
gitea: {
|
gitea: {
|
||||||
url: read('GITEA_URL').replace(/\/+$/, ''),
|
url: read('GITEA_URL').replace(/\/+$/, ''),
|
||||||
token: read('GITEA_TOKEN'),
|
token: read('GITEA_TOKEN'),
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { ActivityType, Events } from 'discord.js';
|
import { ActivityType, Events } from 'discord.js';
|
||||||
import { createLogger } from '../core/logger.js';
|
import { createLogger } from '../core/logger.js';
|
||||||
import { startPollScheduler } from '../services/polls/poll-service.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');
|
const log = createLogger('discord');
|
||||||
|
|
||||||
@@ -12,6 +12,7 @@ export async function execute(client) {
|
|||||||
client.user.setActivity('FWS Arch', { type: ActivityType.Watching });
|
client.user.setActivity('FWS Arch', { type: ActivityType.Watching });
|
||||||
startPollScheduler(client);
|
startPollScheduler(client);
|
||||||
await sweepVoiceChannels(client);
|
await sweepVoiceChannels(client);
|
||||||
|
startVoiceJanitor(client);
|
||||||
log.info(`Connected as ${client.user.tag}`, {
|
log.info(`Connected as ${client.user.tag}`, {
|
||||||
guilds: client.guilds.cache.size,
|
guilds: client.guilds.cache.size,
|
||||||
commands: client.commands.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). */
|
/** Discord caps the user limit of a voice channel at 99 (0 means unlimited). */
|
||||||
export const LIMIT_MAX = 99;
|
export const LIMIT_MAX = 99;
|
||||||
export const NAME_MAX = 100;
|
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). */
|
/** Creation in flight per member, to never create two channels for the same person (M14-T02). */
|
||||||
const pendingCreations = new Set();
|
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é') {
|
export async function deleteVoiceChannel(channel, reason = 'Salon vocal temporaire supprimé') {
|
||||||
removeVoiceChannel(channel.id);
|
try {
|
||||||
panelMessages.delete(channel.id);
|
await channel.delete(reason);
|
||||||
return channel.delete(reason).catch((error) => log.warn('Could not delete the voice channel', error));
|
} 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
|
* Deletes an empty temporary channel after a short grace period, so that a member moving between
|
||||||
* moving between channels does not lose their channel (M14-T04).
|
* 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);
|
const row = getVoiceChannel(channelId);
|
||||||
if (!row) return;
|
if (!row) return;
|
||||||
|
|
||||||
const channel =
|
const channel = await resolveChannel(guild, channelId);
|
||||||
guild.channels.cache.get(channelId) ?? (await guild.channels.fetch(channelId).catch(() => null));
|
|
||||||
if (!channel) {
|
if (!channel) {
|
||||||
removeVoiceChannel(channelId);
|
forgetVoiceChannel(channelId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (channel.members.size > 0) return;
|
if (channel.members.size > 0) return;
|
||||||
|
|
||||||
setTimeout(async () => {
|
const removeEmptyChannel = async () => {
|
||||||
try {
|
const fresh = await resolveChannel(guild, channelId);
|
||||||
const fresh =
|
if (!fresh) {
|
||||||
guild.channels.cache.get(channelId) ?? (await guild.channels.fetch(channelId).catch(() => null));
|
forgetVoiceChannel(channelId);
|
||||||
if (!fresh || fresh.members.size > 0) return;
|
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);
|
|
||||||
}
|
}
|
||||||
}, 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) {
|
export async function sweepVoiceChannels(client) {
|
||||||
for (const guild of client.guilds.cache.values()) {
|
for (const guild of client.guilds.cache.values()) {
|
||||||
let rows = [];
|
let rows = [];
|
||||||
@@ -492,21 +535,30 @@ export async function sweepVoiceChannels(client) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
const channel =
|
const channel = await resolveChannel(guild, row.channel_id);
|
||||||
guild.channels.cache.get(row.channel_id) ??
|
|
||||||
(await guild.channels.fetch(row.channel_id).catch(() => null));
|
|
||||||
if (!channel) {
|
if (!channel) {
|
||||||
removeVoiceChannel(row.channel_id);
|
forgetVoiceChannel(row.channel_id);
|
||||||
panelMessages.delete(row.channel_id);
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (channel.members.size === 0) {
|
if (channel.members.size > 0) continue;
|
||||||
await deleteVoiceChannel(channel, 'Salon vocal temporaire vide après redémarrage');
|
|
||||||
|
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) {
|
export function activeChannelCount(guildId) {
|
||||||
return countVoiceChannels(guildId);
|
return countVoiceChannels(guildId);
|
||||||
}
|
}
|
||||||
@@ -525,18 +577,20 @@ export async function resolveManagedChannel(interaction, { channelId = null } =
|
|||||||
const row = id ? getVoiceChannel(id) : null;
|
const row = id ? getVoiceChannel(id) : null;
|
||||||
if (!row) {
|
if (!row) {
|
||||||
throw new UserFacingError(
|
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)) {
|
if (channelId && channelId !== interaction.member?.voice?.channelId && !isStaff(interaction.member)) {
|
||||||
// An explicit channel is a staff convenience only: a member manages their own channel.
|
// 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);
|
const channel = await interaction.guild.channels.fetch(row.channel_id).catch(() => null);
|
||||||
if (!channel) {
|
if (!channel) {
|
||||||
removeVoiceChannel(row.channel_id);
|
forgetVoiceChannel(row.channel_id);
|
||||||
throw new UserFacingError('Ce salon vocal n’existe plus.');
|
throw new UserFacingError('Ce salon n’existe plus — il a sûrement déjà été supprimé.');
|
||||||
}
|
}
|
||||||
return { channel, row };
|
return { channel, row };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,7 +22,9 @@ import {
|
|||||||
bottomPosition,
|
bottomPosition,
|
||||||
buildChannelName,
|
buildChannelName,
|
||||||
clampLimit,
|
clampLimit,
|
||||||
|
cleanupVoiceChannel,
|
||||||
createFromTrigger,
|
createFromTrigger,
|
||||||
|
deleteVoiceChannel,
|
||||||
findTrigger,
|
findTrigger,
|
||||||
getVoiceTrigger,
|
getVoiceTrigger,
|
||||||
getVoiceTriggers,
|
getVoiceTriggers,
|
||||||
@@ -32,6 +34,8 @@ import {
|
|||||||
sanitizeChannelName,
|
sanitizeChannelName,
|
||||||
saveVoiceTrigger,
|
saveVoiceTrigger,
|
||||||
setTriggerEnabled,
|
setTriggerEnabled,
|
||||||
|
startVoiceJanitor,
|
||||||
|
sweepVoiceChannels,
|
||||||
} from '../src/services/voice/voice-service.js';
|
} from '../src/services/voice/voice-service.js';
|
||||||
|
|
||||||
const member = (roleIds = [], { id = 'u1', guildOwnerId = 'someone-else' } = {}) => ({
|
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', () => {
|
describe('voice helpers', () => {
|
||||||
it('normalises a channel name', () => {
|
it('normalises a channel name', () => {
|
||||||
assert.equal(sanitizeChannelName(' Salon de Léa '), 'Salon de Léa');
|
assert.equal(sanitizeChannelName(' Salon de Léa '), 'Salon de Léa');
|
||||||
|
|||||||
Reference in new issue
Block a user