Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Consistent debug log spacing #10349

Merged
merged 4 commits into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 10 additions & 16 deletions packages/discord.js/src/client/websocket/WebSocketManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)}`,
);
}

Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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);
Expand All @@ -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;
}

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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' });
}
Expand Down
26 changes: 14 additions & 12 deletions packages/discord.js/src/client/websocket/WebSocketShard.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
}

Expand Down Expand Up @@ -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;

/**
Expand All @@ -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` : ''}.`,
Jiralite marked this conversation as resolved.
Show resolved Hide resolved
`Unavailable guild count: ${this.expectedGuilds.size}`,
]);

this.readyTimeout = null;
this.status = Status.Ready;
Expand Down
12 changes: 12 additions & 0 deletions packages/util/__tests__/formatDebugLog.test.ts
Original file line number Diff line number Diff line change
@@ -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!');
});
});
16 changes: 16 additions & 0 deletions packages/util/src/formatDebugLog.ts
Original file line number Diff line number Diff line change
@@ -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')}`
: ''
}`;
}
1 change: 1 addition & 0 deletions packages/util/src/index.ts
Original file line number Diff line number Diff line change
@@ -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';

/**
Expand Down
13 changes: 2 additions & 11 deletions packages/ws/src/ws/WebSocketShard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -915,15 +915,6 @@ export class WebSocketShard extends AsyncEventEmitter<WebSocketShardEventsMap> {
}

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) });
}
}
Loading