Skip to content

Commit

Permalink
chore: lint to coding standards
Browse files Browse the repository at this point in the history
  • Loading branch information
Deivu committed Jan 4, 2025
1 parent 8d6473c commit c4d7334
Show file tree
Hide file tree
Showing 13 changed files with 61 additions and 61 deletions.
32 changes: 16 additions & 16 deletions src/Indomitable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ export class Indomitable extends EventEmitter {
super();
this.clusterCount = options.clusterCount || 'auto';
this.shardCount = options.shardCount || 'auto';
this.clientOptions = options.clientOptions || {intents: [1 << 0]};
this.clientOptions = options.clientOptions || { intents: [ 1 << 0 ] };
this.clusterSettings = options.clusterSettings || {};
this.ipcTimeout = options.ipcTimeout ?? 30000;
this.spawnTimeout = options.spawnTimeout ?? 60000;
Expand Down Expand Up @@ -277,7 +277,7 @@ export class Indomitable extends EventEmitter {
const sessions = await this.fetchSessions();
this.concurrencyServer = new ConcurrencyServer(this, sessions.session_start_limit.max_concurrency);
const info = await this.concurrencyServer.start();
this.emit(LibraryEvents.DEBUG, `Handle concurrency is currently enabled! =>\n Server is currently bound to:\n Address: ${info.address}:${info.port}\n Concurrency: ${sessions.session_start_limit.max_concurrency}`);
this.emit(LibraryEvents.DEBUG, `Handle concurrency is currently enabled! =>\n Server is currently bound to:\n Address: ${ info.address }:${ info.port }\n Concurrency: ${ sessions.session_start_limit.max_concurrency }`);
}

if (typeof this.clusterCount !== 'number')
Expand All @@ -290,15 +290,15 @@ export class Indomitable extends EventEmitter {
if (this.shardCount < this.clusterCount)
this.clusterCount = this.shardCount;

this.emit(LibraryEvents.DEBUG, `Starting ${this.shardCount} websocket shards across ${this.clusterCount} clusters`);
const shards = [...Array(this.shardCount).keys()];
this.emit(LibraryEvents.DEBUG, `Starting ${ this.shardCount } websocket shards across ${ this.clusterCount } clusters`);
const shards = [ ...Array(this.shardCount).keys() ];
const chunks = Chunk(shards, Math.round(this.shardCount / this.clusterCount));

Cluster.setupPrimary({...{serialization: 'json'}, ...this.clusterSettings});
Cluster.setupPrimary({ ...{ serialization: 'json' }, ...this.clusterSettings });

for (let id = 0; id < this.clusterCount; id++) {
const chunk = chunks.shift()!;
const cluster = new ClusterManager({id, shards: chunk, manager: this});
const cluster = new ClusterManager({ id, shards: chunk, manager: this });
this.clusters.set(id, cluster);
}

Expand All @@ -313,7 +313,7 @@ export class Indomitable extends EventEmitter {
public async restart(clusterId: number): Promise<void> {
if (!Cluster.isPrimary) return;
const cluster = this.clusters.get(clusterId);
if (!cluster) throw new Error(`Invalid clusterId, or a cluster with this id doesn\'t exist, received id ${clusterId}`);
if (!cluster) throw new Error(`Invalid clusterId, or a cluster with this id doesn\'t exist, received id ${ clusterId }`);
await this.addToSpawnQueue(cluster);
}

Expand Down Expand Up @@ -362,7 +362,7 @@ export class Indomitable extends EventEmitter {
* @returns An array of promise that resolves to undefined or an unknown value depending on how you reply to it
*/
public broadcast(sendable: Sendable): Promise<unknown[]> {
const clusters = [...this.clusters.keys()];
const clusters = [ ...this.clusters.keys() ];
return Promise.all(clusters.map(id => this.send(id, sendable)));
}

Expand All @@ -377,28 +377,28 @@ export class Indomitable extends EventEmitter {
const sessions = await this.fetchSessions();
this.shardCount = sessions.shards;
}
this.emit(LibraryEvents.DEBUG, `Reconfigured Indomitable to use ${this.shardCount} shard(s)`);
this.emit(LibraryEvents.DEBUG, `Reconfigured Indomitable to use ${ this.shardCount } shard(s)`);
const oldClusterCount = Number(this.clusters.size);
this.clusterCount = options.clusters || this.clusters.size;
const shards = [...Array(this.shardCount).keys()];
const shards = [ ...Array(this.shardCount).keys() ];
const chunks = Chunk(shards, Math.round(this.shardCount as number / this.clusterCount));
if (oldClusterCount < this.clusterCount) {
const count = this.clusterCount - oldClusterCount;
for (let id = this.clusterCount - 1; id < count; id++) {
const cluster = new ClusterManager({id, shards: [], manager: this});
const cluster = new ClusterManager({ id, shards: [], manager: this });
this.clusters.set(id, cluster);
}
}
if (oldClusterCount > this.clusterCount) {
const keys = [...this.clusters.keys()].reverse();
const keys = [ ...this.clusters.keys() ].reverse();
const range = keys.slice(0, oldClusterCount - this.clusterCount);
for (const key of range) {
const cluster = this.clusters.get(key);
cluster!.destroy();
this.clusters.delete(key);
}
}
this.emit(LibraryEvents.DEBUG, `Reconfigured Indomitable to use ${this.clusterCount} cluster(s) from ${oldClusterCount} cluster(s)`);
this.emit(LibraryEvents.DEBUG, `Reconfigured Indomitable to use ${ this.clusterCount } cluster(s) from ${ oldClusterCount } cluster(s)`);
for (const cluster of this.clusters.values()) {
cluster.shards = chunks.shift()!;
}
Expand Down Expand Up @@ -429,7 +429,7 @@ export class Indomitable extends EventEmitter {
data: {},
internal: true
};
await this.send(id, {content, reply: true});
await this.send(id, { content, reply: true });
}

/**
Expand All @@ -439,7 +439,7 @@ export class Indomitable extends EventEmitter {
private async processQueue(): Promise<void> {
if (this.isBusy || !this.spawnQueue.length) return;
this.busy = true;
this.emit(LibraryEvents.DEBUG, `Processing spawn queue with ${this.spawnQueue.length} clusters waiting to be spawned....`);
this.emit(LibraryEvents.DEBUG, `Processing spawn queue with ${ this.spawnQueue.length } clusters waiting to be spawned....`);
let cluster: ClusterManager;
while (this.spawnQueue.length > 0) {
try {
Expand All @@ -453,7 +453,7 @@ export class Indomitable extends EventEmitter {
} catch (error: unknown) {
this.emit(LibraryEvents.ERROR, error as Error);
if (cluster! && this.autoRestart) {
this.emit(LibraryEvents.DEBUG, `Failed to spawn Cluster ${cluster.id} containing [ ${cluster.shards.join(', ')} ] shard(s). Re-queuing if not in spawn queue`);
this.emit(LibraryEvents.DEBUG, `Failed to spawn Cluster ${ cluster.id } containing [ ${ cluster.shards.join(', ') } ] shard(s). Re-queuing if not in spawn queue`);
this.spawnQueue.push(cluster);
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/Util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ export function Fetch(url: string, options: RequestOptions): Promise<FetchRespon
response.on('end', () => {
const code = response.statusCode ?? 500;
const body = chunks.join('');
resolve({code, body, message: response.statusMessage ?? ''});
resolve({ code, body, message: response.statusMessage ?? '' });
});
});

Expand All @@ -261,12 +261,12 @@ export async function FetchSessions(token: string): Promise<SessionObject> {
const url = new URL('https://discord.com/api/v10/gateway/bot');
const response = await Fetch(url.toString(), {
method: 'GET',
headers: {authorization: `Bot ${token}`}
headers: { authorization: `Bot ${ token }` }
});
if (response.code >= 200 && response.code <= 299)
return JSON.parse(response.body);
else
throw new Error(`Response received is not ok, code: ${response.code}`)
throw new Error(`Response received is not ok, code: ${ response.code }`)
}

/**
Expand Down Expand Up @@ -300,8 +300,8 @@ export function MakeAbortableRequest(delay: number): AbortableData {
const controller = new AbortController();
const seconds = Math.round(delay / 1000);
const timeout = setTimeout(
() => controller.abort(new Error(`The request has been aborted in ${seconds} second(s)`)),
() => controller.abort(new Error(`The request has been aborted in ${ seconds } second(s)`)),
delay
);
return {controller, timeout};
return { controller, timeout };
}
16 changes: 8 additions & 8 deletions src/client/ShardClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,26 +59,26 @@ export class ShardClient {
// tests the server if it's accessible first before starting the client
this.client.emit('debug', '[Indomitable]: Handle concurrency enabled! Testing the identify server before logging in...');
const date = await this.concurrency.checkServer();
this.client.emit('debug', `[Indomitable]: Identify server responded and is working, Trip Latency: ${Math.round(Date.now() - date)}ms`);
this.client.emit('debug', `[Indomitable]: Identify server responded and is working, Trip Latency: ${ Math.round(Date.now() - date) }ms`);
}
// attach listeners
this.client.once('ready', () => this.send({op: ClientEvents.READY, data: {clusterId: this.clusterId}}));
this.client.once('ready', () => this.send({ op: ClientEvents.READY, data: { clusterId: this.clusterId } }));
this.client.on('shardReady', (shardId: number) => this.send({
op: ClientEvents.SHARD_READY,
data: {clusterId: this.clusterId, shardId}
data: { clusterId: this.clusterId, shardId }
}));
this.client.on('shardReconnecting', (shardId: number) => this.send({
op: ClientEvents.SHARD_RECONNECT,
data: {clusterId: this.clusterId, shardId}
data: { clusterId: this.clusterId, shardId }
}));
this.client.on('shardResume', (shardId: number, replayed: number) => this.send({
op: ClientEvents.SHARD_RESUME,
data: {clusterId: this.clusterId, shardId, replayed}
data: { clusterId: this.clusterId, shardId, replayed }
}));
// @ts-ignore -- Discord.JS faulty typings?
this.client.on('shardDisconnect', (event: CloseEvent, shardId: number) => this.send({
op: ClientEvents.SHARD_DISCONNECT,
data: {clusterId: this.clusterId, shardId, event}
data: { clusterId: this.clusterId, shardId, event }
}));
await this.client.login(token);
}
Expand All @@ -91,9 +91,9 @@ export class ShardClient {
private send(partial: PartialInternalEvents): void {
// @ts-ignore -- our own class
const shardClientUtil = this.client.shard as ShardClientUtil;
const content: ClientEventData = {...partial, internal: true};
const content: ClientEventData = { ...partial, internal: true };
shardClientUtil
.send({content, reply: false})
.send({ content, reply: false })
.catch((error: unknown) => this.client.emit(ClientEvents.ERROR, error as Error));
}
}
16 changes: 8 additions & 8 deletions src/client/ShardClientUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export class ShardClientUtil extends EventEmitter {
internal: true
};
const start = process.hrtime.bigint();
const end = await this.send({content, reply: true}) as number;
const end = await this.send({ content, reply: true }) as number;
return Number(BigInt(end) - start);
}

Expand All @@ -73,10 +73,10 @@ export class ShardClientUtil extends EventEmitter {
public broadcastEval(script: Function, context: any = {}): Promise<unknown[]> {
const content: InternalOpsData = {
op: InternalOps.EVAL,
data: `(${script.toString()})(this, ${JSON.stringify(context)})`,
data: `(${ script.toString() })(this, ${ JSON.stringify(context) })`,
internal: true
};
return this.send({content, reply: true}) as Promise<unknown[]>;
return this.send({ content, reply: true }) as Promise<unknown[]>;
}

/**
Expand All @@ -95,10 +95,10 @@ export class ShardClientUtil extends EventEmitter {
public fetchSessions(update: boolean = false): Promise<SessionObject> {
const content: InternalOpsData = {
op: InternalOps.SESSION_INFO,
data: {update},
data: { update },
internal: true
};
return this.send({content, reply: true}) as Promise<SessionObject>;
return this.send({ content, reply: true }) as Promise<SessionObject>;
}

/**
Expand All @@ -108,10 +108,10 @@ export class ShardClientUtil extends EventEmitter {
public restart(clusterId: number): Promise<undefined> {
const content: InternalOpsData = {
op: InternalOps.RESTART,
data: {clusterId},
data: { clusterId },
internal: true
};
return this.send({content}) as Promise<undefined>;
return this.send({ content }) as Promise<undefined>;
}

/**
Expand All @@ -124,7 +124,7 @@ export class ShardClientUtil extends EventEmitter {
data: {},
internal: true
};
return this.send({content}) as Promise<undefined>;
return this.send({ content }) as Promise<undefined>;
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/concurrency/AsyncQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ export class AsyncQueue {
return this.queue.length;
}

public wait({signal}: AsyncQueueWaitOptions): Promise<void[]> {
public wait({ signal }: AsyncQueueWaitOptions): Promise<void[]> {

const next = this.remaining ? once(this.queue[this.remaining - 1], 'resolve', {signal}) : Promise.resolve([]);
const next = this.remaining ? once(this.queue[this.remaining - 1], 'resolve', { signal }) : Promise.resolve([]);

const emitter = new EventEmitter() as NodeJS.EventEmitter;

Expand Down
12 changes: 6 additions & 6 deletions src/concurrency/ConcurrencyClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,17 @@ export class ConcurrencyClient {
* If it errors that isn't anything from websocket shard, this will have issues
*/
public async waitForIdentify(shardId: number, signal: AbortSignal): Promise<void> {
const url = new URL(`http://${this.address}:${this.port}/concurrency/acquire`);
const url = new URL(`http://${ this.address }:${ this.port }/concurrency/acquire`);
url.searchParams.append('shardId', shardId.toString());

const listener = () => {
const url = new URL(`http://${this.address}:${this.port}/concurrency/cancel`);
const url = new URL(`http://${ this.address }:${ this.port }/concurrency/cancel`);

url.searchParams.append('shardId', shardId.toString());

Fetch(url.toString(), {
method: 'DELETE',
headers: {authorization: this.password}
headers: { authorization: this.password }
}).catch(() => null);
}

Expand All @@ -39,7 +39,7 @@ export class ConcurrencyClient {

const response = await Fetch(url.toString(), {
method: 'POST',
headers: {authorization: this.password}
headers: { authorization: this.password }
});

if (response.code === 202 || response.code === 204) {
Expand All @@ -61,11 +61,11 @@ export class ConcurrencyClient {
}

public async checkServer(): Promise<number> {
const url = new URL(`http://${this.address}:${this.port}/concurrency/check`);
const url = new URL(`http://${ this.address }:${ this.port }/concurrency/check`);
url.searchParams.append('shardId', '0');
const response = await Fetch(url.toString(), {
method: 'POST',
headers: {authorization: this.password}
headers: { authorization: this.password }
});
return Number(response.body);
}
Expand Down
4 changes: 2 additions & 2 deletions src/concurrency/ConcurrencyManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class ConcurrencyManager {
});

try {
await state.queue.wait({signal: abort.signal});
await state.queue.wait({ signal: abort.signal });

const difference = state.resets - Date.now();

Expand All @@ -57,6 +57,6 @@ export class ConcurrencyManager {
*/
public abortIdentify(shardId: number): void {
const signal = this.signals.get(shardId);
signal?.abort(`Shard ${shardId} aborted the identify request`);
signal?.abort(`Shard ${ shardId } aborted the identify request`);
}
}
2 changes: 1 addition & 1 deletion src/concurrency/ConcurrencyServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export class ConcurrencyServer {
return void response.end('Expected shardId to be a number');
}

this.manager.emit(LibraryEvents.DEBUG, `Received a request in concurrency server! =>\n Url: ${request.url}\n Method: ${request.method}\n ShardId: ${shardId}`);
this.manager.emit(LibraryEvents.DEBUG, `Received a request in concurrency server! =>\n Url: ${ request.url }\n Method: ${ request.method }\n ShardId: ${ shardId }`);

if (request.method === 'DELETE' && request.url.includes('/concurrency/cancel')) {
this.concurrency.abortIdentify(shardId);
Expand Down
2 changes: 1 addition & 1 deletion src/ipc/BaseSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export abstract class BaseSocket {
};
this.socket.write(JSON.stringify(data));
if (!data.reply) return resolve(undefined);
this.waitForPromise({nonce, resolve, reject, signal: transportable.signal});
this.waitForPromise({ nonce, resolve, reject, signal: transportable.signal });
});
}

Expand Down
6 changes: 3 additions & 3 deletions src/ipc/ClientSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ export class ClientSocket extends BaseSocket {
}

public connect(): void {
this.socket.connect({path: `./indomitable-${this.serverId}`}, () => {
this.identify({clusterId: this.shard.clusterId, serverId: this.serverId})
this.socket.connect({ path: `./indomitable-${ this.serverId }` }, () => {
this.identify({ clusterId: this.shard.clusterId, serverId: this.serverId })
.catch(() => null);
});

Expand All @@ -29,7 +29,7 @@ export class ClientSocket extends BaseSocket {
internal: true,
data
};
return this.send({content, reply: true}) as Promise<void>;
return this.send({ content, reply: true }) as Promise<void>;
}

protected handleClose(): void {
Expand Down
4 changes: 2 additions & 2 deletions src/ipc/IpcServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@ export class IpcServer {

this.server.once('error', listener);

this.server.listen(`./indomitable-${this.serverId}`, () => {
this.server.listen(`./indomitable-${ this.serverId }`, () => {
// @ts-expect-error: why this errors?

Check failure on line 33 in src/ipc/IpcServer.ts

View workflow job for this annotation

GitHub Actions / compile (16.x)

Unused '@ts-expect-error' directive.
this.server.removeListener('error', listener);

this.server
.on('connection', (socket) => {

})
.on('error', (code) => this.manager.emit(LibraryEvents.ERROR, new Error(`IPC server errored with code: ${code}`)));
.on('error', (code) => this.manager.emit(LibraryEvents.ERROR, new Error(`IPC server errored with code: ${ code }`)));

resolve();
});
Expand Down
2 changes: 1 addition & 1 deletion src/ipc/ServerSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export class ServerSocket extends BaseSocket {
}

protected handleClose(): void {
this.manager.emit(LibraryEvents.DEBUG, `A socket closed with ${this.socket.bytesRead} byte(s) data written`);
this.manager.emit(LibraryEvents.DEBUG, `A socket closed with ${ this.socket.bytesRead } byte(s) data written`);
}

protected handleError(error: Error): void {
Expand Down
Loading

0 comments on commit c4d7334

Please sign in to comment.