From 9db3d990a00b3a1dcb9868572393a553ea9092b6 Mon Sep 17 00:00:00 2001 From: Jiralite <33201955+Jiralite@users.noreply.github.com> Date: Thu, 13 Jun 2024 14:52:32 +0100 Subject: [PATCH 1/4] fix: consistent debug log spacing --- .../src/client/websocket/WebSocketManager.js | 26 +++++++------------ .../src/client/websocket/WebSocketShard.js | 26 ++++++++++--------- .../util/__tests__/formatDebugLog.test.ts | 12 +++++++++ packages/util/src/formatDebugLog.ts | 16 ++++++++++++ packages/util/src/index.ts | 1 + packages/ws/src/ws/WebSocketShard.ts | 13 ++-------- 6 files changed, 55 insertions(+), 39 deletions(-) create mode 100644 packages/util/__tests__/formatDebugLog.test.ts create mode 100644 packages/util/src/formatDebugLog.ts diff --git a/packages/discord.js/src/client/websocket/WebSocketManager.js b/packages/discord.js/src/client/websocket/WebSocketManager.js index 9b3dff3633ae..26f5e64dfff4 100644 --- a/packages/discord.js/src/client/websocket/WebSocketManager.js +++ b/packages/discord.js/src/client/websocket/WebSocketManager.js @@ -4,6 +4,7 @@ const EventEmitter = require('node:events'); const process = require('node:process'); const { setImmediate } = require('node:timers'); const { Collection } = require('@discordjs/collection'); +const { formatDebugLog } = require('@discordjs/util'); const { WebSocketManager: WSWebSocketManager, WebSocketShardEvents: WSWebSocketShardEvents, @@ -117,14 +118,14 @@ class WebSocketManager extends EventEmitter { /** * Emits a debug message. - * @param {string} message The debug message + * @param {string[]} messages The debug message * @param {?number} [shardId] The id of the shard that emitted this message, if any * @private */ - debug(message, shardId) { + debug(messages, shardId) { this.client.emit( Events.Debug, - `[WS => ${typeof shardId === 'number' ? `Shard ${shardId}` : 'Manager'}] ${message}`, + `[WS => ${typeof shardId === 'number' ? `Shard ${shardId}` : 'Manager'}] ${formatDebugLog(messages)}`, ); } @@ -170,15 +171,8 @@ class WebSocketManager extends EventEmitter { }); const { total, remaining } = sessionStartLimit; - - this.debug(`Fetched Gateway Information - URL: ${gatewayURL} - Recommended Shards: ${recommendedShards}`); - - this.debug(`Session Limit Information - Total: ${total} - Remaining: ${remaining}`); - + this.debug(['Fetched Gateway Information', `URL: ${gatewayURL}`, `Recommended Shards: ${recommendedShards}`]); + this.debug(['Session Limit Information', `Total: ${total}`, `Remaining: ${remaining}`]); this.gateway = `${gatewayURL}/`; this.client.options.shardCount = await this._ws.getShardCount(); @@ -231,7 +225,7 @@ class WebSocketManager extends EventEmitter { * @private */ attachEvents() { - this._ws.on(WSWebSocketShardEvents.Debug, ({ message, shardId }) => this.debug(message, shardId)); + this._ws.on(WSWebSocketShardEvents.Debug, ({ message, shardId }) => this.debug([message], shardId)); this._ws.on(WSWebSocketShardEvents.Dispatch, ({ data, shardId }) => { this.client.emit(Events.Raw, data, shardId); this.emit(data.t, data.d, shardId); @@ -258,7 +252,7 @@ class WebSocketManager extends EventEmitter { * @param {number} id The shard id that disconnected */ this.client.emit(Events.ShardDisconnect, { code, reason: reasonIsDeprecated, wasClean: true }, shardId); - this.debug(`Shard not resumable: ${code} (${GatewayCloseCodes[code] ?? CloseCodes[code]})`, shardId); + this.debug([`Shard not resumable: ${code} (${GatewayCloseCodes[code] ?? CloseCodes[code]})`], shardId); return; } @@ -291,7 +285,7 @@ class WebSocketManager extends EventEmitter { }); this._ws.on(WSWebSocketShardEvents.HeartbeatComplete, ({ heartbeatAt, latency, shardId }) => { - this.debug(`Heartbeat acknowledged, latency of ${latency}ms.`, shardId); + this.debug([`Heartbeat acknowledged, latency of ${latency}ms.`], shardId); const shard = this.shards.get(shardId); shard.lastPingTimestamp = heartbeatAt; shard.ping = latency; @@ -324,7 +318,7 @@ class WebSocketManager extends EventEmitter { async destroy() { if (this.destroyed) return; // TODO: Make a util for getting a stack - this.debug(Object.assign(new Error(), { name: 'Manager was destroyed:' }).stack); + this.debug([Object.assign(new Error(), { name: 'Manager was destroyed:' }).stack]); this.destroyed = true; await this._ws?.destroy({ code: CloseCodes.Normal, reason: 'Manager was destroyed' }); } diff --git a/packages/discord.js/src/client/websocket/WebSocketShard.js b/packages/discord.js/src/client/websocket/WebSocketShard.js index c96c97cdda9d..392387a26ddb 100644 --- a/packages/discord.js/src/client/websocket/WebSocketShard.js +++ b/packages/discord.js/src/client/websocket/WebSocketShard.js @@ -110,10 +110,13 @@ class WebSocketShard extends EventEmitter { wasClean: false, }, ) { - this.debug(`[CLOSE] - Event Code: ${event.code} - Clean : ${event.wasClean} - Reason : ${event.reason ?? 'No reason received'}`); + this.debug([ + '[CLOSE]', + `Event Code: ${event.code}`, + `Clean : ${event.wasClean}`, + `Reason : ${event.reason ?? 'No reason received'}`, + ]); + /** * Emitted when a shard's WebSocket closes. * @private @@ -130,7 +133,7 @@ class WebSocketShard extends EventEmitter { */ onReadyPacket(packet) { if (!packet) { - this.debug(`Received broken packet: '${packet}'.`); + this.debug([`Received broken packet: '${packet}'.`]); return; } @@ -167,7 +170,7 @@ class WebSocketShard extends EventEmitter { } // Step 1. If we don't have any other guilds pending, we are ready if (!this.expectedGuilds.size) { - this.debug('Shard received all its guilds. Marking as fully ready.'); + this.debug(['Shard received all its guilds. Marking as fully ready.']); this.status = Status.Ready; /** @@ -191,12 +194,11 @@ class WebSocketShard extends EventEmitter { this.readyTimeout = setTimeout( () => { - this.debug( - `Shard ${hasGuildsIntent ? 'did' : 'will'} not receive any more guild packets` + - `${hasGuildsIntent ? ` in ${waitGuildTimeout} ms` : ''}.\nUnavailable guild count: ${ - this.expectedGuilds.size - }`, - ); + this.debug([ + // eslint-disable-next-line max-len + `Shard ${hasGuildsIntent ? 'did' : 'will'} not receive anymore guild packets${hasGuildsIntent ? ` in ${waitGuildTimeout} ms` : ''}.`, + `Unavailable guild count: ${this.expectedGuilds.size}`, + ]); this.readyTimeout = null; this.status = Status.Ready; diff --git a/packages/util/__tests__/formatDebugLog.test.ts b/packages/util/__tests__/formatDebugLog.test.ts new file mode 100644 index 000000000000..aa0b339b5ad5 --- /dev/null +++ b/packages/util/__tests__/formatDebugLog.test.ts @@ -0,0 +1,12 @@ +import { describe, test, expect } from 'vitest'; +import { formatDebugLog } from '../src/index.js'; + +describe('formatDebugLog', () => { + test('GIVEN 1 message THEN returns singular message', () => { + expect(formatDebugLog(['Hello, world!'])).toBe('Hello, world!'); + }); + + test('GIVEN multiple messages THEN returns message with new lines', () => { + expect(formatDebugLog(['Hello, world!', 'Hello again!'])).toBe('Hello, world!\n\tHello again!'); + }); +}); diff --git a/packages/util/src/formatDebugLog.ts b/packages/util/src/formatDebugLog.ts new file mode 100644 index 000000000000..33365d409952 --- /dev/null +++ b/packages/util/src/formatDebugLog.ts @@ -0,0 +1,16 @@ +/** + * Formats debug log messages. + * + * @param messages - An array of messages to format + * @internal + */ +export function formatDebugLog(messages: [string, ...string[]]) { + return `${messages[0]}${ + messages.length > 1 + ? `\n${messages + .slice(1) + .map((message) => ` ${message}`) + .join('\n')}` + : '' + }`; +} diff --git a/packages/util/src/index.ts b/packages/util/src/index.ts index 2b9f050e122d..54e63364d6d1 100644 --- a/packages/util/src/index.ts +++ b/packages/util/src/index.ts @@ -1,6 +1,7 @@ export * from './types.js'; export * from './functions/index.js'; export * from './JSONEncodable.js'; +export * from './formatDebugLog.js'; export * from './Equatable.js'; /** diff --git a/packages/ws/src/ws/WebSocketShard.ts b/packages/ws/src/ws/WebSocketShard.ts index 5126002c4a31..956865b9e204 100644 --- a/packages/ws/src/ws/WebSocketShard.ts +++ b/packages/ws/src/ws/WebSocketShard.ts @@ -6,7 +6,7 @@ import { URLSearchParams } from 'node:url'; import { TextDecoder } from 'node:util'; import type * as nativeZlib from 'node:zlib'; import { Collection } from '@discordjs/collection'; -import { lazy, shouldUseGlobalFetchAndWebSocket } from '@discordjs/util'; +import { formatDebugLog, lazy, shouldUseGlobalFetchAndWebSocket } from '@discordjs/util'; import { AsyncQueue } from '@sapphire/async-queue'; import { AsyncEventEmitter } from '@vladfrangu/async_event_emitter'; import { @@ -915,15 +915,6 @@ export class WebSocketShard extends AsyncEventEmitter { } private debug(messages: [string, ...string[]]) { - const message = `${messages[0]}${ - messages.length > 1 - ? `\n${messages - .slice(1) - .map((message) => ` ${message}`) - .join('\n')}` - : '' - }`; - - this.emit(WebSocketShardEvents.Debug, { message }); + this.emit(WebSocketShardEvents.Debug, { message: formatDebugLog(messages) }); } } From ff46e95d3f2a7f1c9cefb25b8844c9872703ad8a Mon Sep 17 00:00:00 2001 From: Jiralite <33201955+Jiralite@users.noreply.github.com> Date: Thu, 13 Jun 2024 16:47:13 +0100 Subject: [PATCH 2/4] refactor: simplify formatting --- .../src/client/websocket/WebSocketManager.js | 3 +-- packages/util/__tests__/formatDebugLog.test.ts | 12 ------------ packages/util/src/formatDebugLog.ts | 16 ---------------- packages/util/src/index.ts | 1 - packages/ws/src/ws/WebSocketShard.ts | 4 ++-- 5 files changed, 3 insertions(+), 33 deletions(-) delete mode 100644 packages/util/__tests__/formatDebugLog.test.ts delete mode 100644 packages/util/src/formatDebugLog.ts diff --git a/packages/discord.js/src/client/websocket/WebSocketManager.js b/packages/discord.js/src/client/websocket/WebSocketManager.js index 26f5e64dfff4..7a1831ad6aea 100644 --- a/packages/discord.js/src/client/websocket/WebSocketManager.js +++ b/packages/discord.js/src/client/websocket/WebSocketManager.js @@ -4,7 +4,6 @@ const EventEmitter = require('node:events'); const process = require('node:process'); const { setImmediate } = require('node:timers'); const { Collection } = require('@discordjs/collection'); -const { formatDebugLog } = require('@discordjs/util'); const { WebSocketManager: WSWebSocketManager, WebSocketShardEvents: WSWebSocketShardEvents, @@ -125,7 +124,7 @@ class WebSocketManager extends EventEmitter { debug(messages, shardId) { this.client.emit( Events.Debug, - `[WS => ${typeof shardId === 'number' ? `Shard ${shardId}` : 'Manager'}] ${formatDebugLog(messages)}`, + `[WS => ${typeof shardId === 'number' ? `Shard ${shardId}` : 'Manager'}] ${messages.join('\n\t')}`, ); } diff --git a/packages/util/__tests__/formatDebugLog.test.ts b/packages/util/__tests__/formatDebugLog.test.ts deleted file mode 100644 index aa0b339b5ad5..000000000000 --- a/packages/util/__tests__/formatDebugLog.test.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { describe, test, expect } from 'vitest'; -import { formatDebugLog } from '../src/index.js'; - -describe('formatDebugLog', () => { - test('GIVEN 1 message THEN returns singular message', () => { - expect(formatDebugLog(['Hello, world!'])).toBe('Hello, world!'); - }); - - test('GIVEN multiple messages THEN returns message with new lines', () => { - expect(formatDebugLog(['Hello, world!', 'Hello again!'])).toBe('Hello, world!\n\tHello again!'); - }); -}); diff --git a/packages/util/src/formatDebugLog.ts b/packages/util/src/formatDebugLog.ts deleted file mode 100644 index 33365d409952..000000000000 --- a/packages/util/src/formatDebugLog.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Formats debug log messages. - * - * @param messages - An array of messages to format - * @internal - */ -export function formatDebugLog(messages: [string, ...string[]]) { - return `${messages[0]}${ - messages.length > 1 - ? `\n${messages - .slice(1) - .map((message) => ` ${message}`) - .join('\n')}` - : '' - }`; -} diff --git a/packages/util/src/index.ts b/packages/util/src/index.ts index 54e63364d6d1..2b9f050e122d 100644 --- a/packages/util/src/index.ts +++ b/packages/util/src/index.ts @@ -1,7 +1,6 @@ export * from './types.js'; export * from './functions/index.js'; export * from './JSONEncodable.js'; -export * from './formatDebugLog.js'; export * from './Equatable.js'; /** diff --git a/packages/ws/src/ws/WebSocketShard.ts b/packages/ws/src/ws/WebSocketShard.ts index 956865b9e204..1e3fcaed5a7e 100644 --- a/packages/ws/src/ws/WebSocketShard.ts +++ b/packages/ws/src/ws/WebSocketShard.ts @@ -6,7 +6,7 @@ import { URLSearchParams } from 'node:url'; import { TextDecoder } from 'node:util'; import type * as nativeZlib from 'node:zlib'; import { Collection } from '@discordjs/collection'; -import { formatDebugLog, lazy, shouldUseGlobalFetchAndWebSocket } from '@discordjs/util'; +import { lazy, shouldUseGlobalFetchAndWebSocket } from '@discordjs/util'; import { AsyncQueue } from '@sapphire/async-queue'; import { AsyncEventEmitter } from '@vladfrangu/async_event_emitter'; import { @@ -915,6 +915,6 @@ export class WebSocketShard extends AsyncEventEmitter { } private debug(messages: [string, ...string[]]) { - this.emit(WebSocketShardEvents.Debug, { message: formatDebugLog(messages) }); + this.emit(WebSocketShardEvents.Debug, { message: messages.join('\n\t') }); } } From c0f3428c2df62e81a02e6b3cb7289903a8a6ca2f Mon Sep 17 00:00:00 2001 From: Jiralite <33201955+Jiralite@users.noreply.github.com> Date: Thu, 13 Jun 2024 16:53:16 +0100 Subject: [PATCH 3/4] refactor: more readable ternary Co-Authored-By: Synbulat Biishev --- packages/discord.js/src/client/websocket/WebSocketShard.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/discord.js/src/client/websocket/WebSocketShard.js b/packages/discord.js/src/client/websocket/WebSocketShard.js index 392387a26ddb..19394f060d8e 100644 --- a/packages/discord.js/src/client/websocket/WebSocketShard.js +++ b/packages/discord.js/src/client/websocket/WebSocketShard.js @@ -195,8 +195,9 @@ class WebSocketShard extends EventEmitter { this.readyTimeout = setTimeout( () => { this.debug([ - // eslint-disable-next-line max-len - `Shard ${hasGuildsIntent ? 'did' : 'will'} not receive anymore guild packets${hasGuildsIntent ? ` in ${waitGuildTimeout} ms` : ''}.`, + hasGuildsIntent + ? `Shard did not receive any guild packets in ${waitGuildTimeout} ms.` + : 'Shard will not receive anymore guild packets.', `Unavailable guild count: ${this.expectedGuilds.size}`, ]); From c4bf51038589b7377935c736a1df61829819670b Mon Sep 17 00:00:00 2001 From: Jiralite <33201955+Jiralite@users.noreply.github.com> Date: Thu, 13 Jun 2024 17:03:38 +0100 Subject: [PATCH 4/4] fix: modify parameters and types --- packages/discord.js/src/client/websocket/WebSocketShard.js | 6 +++--- packages/discord.js/typings/index.d.ts | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/discord.js/src/client/websocket/WebSocketShard.js b/packages/discord.js/src/client/websocket/WebSocketShard.js index 19394f060d8e..d3d8167f928a 100644 --- a/packages/discord.js/src/client/websocket/WebSocketShard.js +++ b/packages/discord.js/src/client/websocket/WebSocketShard.js @@ -85,11 +85,11 @@ class WebSocketShard extends EventEmitter { /** * Emits a debug event. - * @param {string} message The debug message + * @param {string[]} messages The debug message * @private */ - debug(message) { - this.manager.debug(message, this.id); + debug(messages) { + this.manager.debug(messages, this.id); } /** diff --git a/packages/discord.js/typings/index.d.ts b/packages/discord.js/typings/index.d.ts index ad28287fc1d1..ae236f758fb6 100644 --- a/packages/discord.js/typings/index.d.ts +++ b/packages/discord.js/typings/index.d.ts @@ -3653,7 +3653,7 @@ export class WebSocketManager extends EventEmitter { public on(event: GatewayDispatchEvents, listener: (data: any, shardId: number) => void): this; public once(event: GatewayDispatchEvents, listener: (data: any, shardId: number) => void): this; - private debug(message: string, shardId?: number): void; + private debug(messages: readonly string[], shardId?: number): void; private connect(): Promise; private broadcast(packet: unknown): void; private destroy(): Promise; @@ -3684,7 +3684,7 @@ export class WebSocketShard extends EventEmitter { public status: Status; public ping: number; - private debug(message: string): void; + private debug(messages: readonly string[]): void; private onReadyPacket(packet: unknown): void; private gotGuild(guildId: Snowflake): void; private checkReady(): void;