Skip to content

Commit 70c708d

Browse files
committed
chore: fix compiler errors
1 parent 97156be commit 70c708d

File tree

9 files changed

+46
-50
lines changed

9 files changed

+46
-50
lines changed

bun.lockb

8 Bytes
Binary file not shown.

src/cache.ts

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
/**
22
* LRU Cache - Least Recently Used Cache
3-
*
3+
*
44
* Simple cache implementation using Map.
5-
*
5+
*
66
*/
77
export type RemoveCallbackType<T> = (key: string, value: T) => Promise<void>;
88

@@ -11,7 +11,8 @@ export class LRUCache<T> {
1111

1212
constructor(
1313
private capacity: number,
14-
private removeCallback: RemoveCallbackType<T> = async () => { }) {
14+
private removeCallback: RemoveCallbackType<T> = async () => {}
15+
) {
1516
this.capacity = capacity;
1617
this.cache = new Map();
1718
}
@@ -34,7 +35,9 @@ export class LRUCache<T> {
3435
}
3536
if (this.cache.size === this.capacity) {
3637
const firstKey = this.cache.keys().next().value;
37-
this.cache.delete(firstKey);
38+
if (firstKey) {
39+
this.cache.delete(firstKey);
40+
}
3841
}
3942
this.cache.set(key, value);
4043
}
@@ -48,7 +51,9 @@ export class LRUCache<T> {
4851
}
4952

5053
async clear() {
51-
await Promise.all(Array.from(this.cache.keys()).map((key) => this.remove(key)));
54+
await Promise.all(
55+
Array.from(this.cache.keys()).map((key) => this.remove(key))
56+
);
5257
}
5358

5459
size() {
@@ -62,4 +67,4 @@ export class LRUCache<T> {
6267
values() {
6368
return this.cache.values();
6469
}
65-
}
70+
}

src/controllers/utils.ts

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,15 @@
11
import { ServerWebSocket } from "bun";
2+
import { BufferSource } from "../interfaces";
23

34
const RETRY_TIMEOUT = 1000;
45

56
export function respond(ws: ServerWebSocket<any>, id: number, data: any = {}) {
6-
const response = JSON.stringify({
7-
id,
8-
data,
9-
});
7+
const response = JSON.stringify({ id, data });
108

119
send(ws, response);
1210
}
1311

14-
export function send(ws: ServerWebSocket<any>, data: string | Buffer) {
12+
export function send(ws: ServerWebSocket<any>, data: string | BufferSource) {
1513
if (ws.readyState == 2 || ws.readyState == 3) {
1614
return;
1715
}
@@ -20,4 +18,3 @@ export function send(ws: ServerWebSocket<any>, data: string | Buffer) {
2018
setTimeout(() => send(ws, data), RETRY_TIMEOUT);
2119
}
2220
}
23-

src/controllers/websocket/message-broker.ts

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
*
77
*/
88

9-
import { EventEmitter } from 'events';
9+
import { EventEmitter } from "events";
10+
import { BufferSource } from "../../interfaces";
1011

1112
export interface Message<T> {
1213
id: number;
@@ -25,10 +26,8 @@ export class MessageBroker<T> extends EventEmitter {
2526
} = {};
2627

2728
constructor(
28-
private send: (msg: string | Buffer) => Promise<void>,
29-
private opts = {
30-
messageTimeout: 15000,
31-
},
29+
private send: (msg: string | BufferSource) => Promise<void>,
30+
private opts = { messageTimeout: 15000 }
3231
) {
3332
super();
3433
}
@@ -39,10 +38,7 @@ export class MessageBroker<T> extends EventEmitter {
3938
}
4039

4140
sendData<K>(data: T, { noack }: { noack?: boolean } = {}): Promise<K> {
42-
const msg = {
43-
id: this.messageId++,
44-
data,
45-
};
41+
const msg = { id: this.messageId++, data };
4642

4743
// TODO: Support binary data too.
4844
this.send(JSON.stringify(msg));
@@ -52,20 +48,17 @@ export class MessageBroker<T> extends EventEmitter {
5248
}
5349

5450
return new Promise((resolve, reject) => {
55-
this.pendingMessages[msg.id] = {
56-
resolve,
57-
reject,
58-
};
51+
this.pendingMessages[msg.id] = { resolve, reject };
5952

6053
let responseHandler: (data: K) => void;
6154

6255
const timeout = setTimeout(() => {
6356
delete this.pendingMessages[msg.id];
6457
this.removeListener(`${msg.id}`, responseHandler);
65-
reject(new Error('Timeout'));
58+
reject(new Error("Timeout"));
6659
}, this.opts.messageTimeout);
6760

68-
this.messageTimeouts[msg.id] = timeout; // Track the timeout
61+
this.messageTimeouts[msg.id] = timeout; // Track the timeout
6962

7063
responseHandler = (data: K) => {
7164
delete this.pendingMessages[msg.id];
@@ -79,7 +72,7 @@ export class MessageBroker<T> extends EventEmitter {
7972

8073
close() {
8174
for (const key in this.pendingMessages) {
82-
this.pendingMessages[key].reject(new Error('Connection closed'));
75+
this.pendingMessages[key].reject(new Error("Connection closed"));
8376
if (this.messageTimeouts[key]) {
8477
clearTimeout(this.messageTimeouts[key]);
8578
delete this.messageTimeouts[key];

src/controllers/websocket/queue-events.ts

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { ServerWebSocket } from "bun";
22
import { MessageBroker } from "./message-broker";
33
import { QueueEvents, ConnectionOptions, QueueEventsListener } from "bullmq";
44

5-
import { WebSocketBehaviour } from "../../interfaces/websocket-behaviour";
5+
import { WebSocketBehaviour, BufferSource } from "../../interfaces";
66
import { send } from "../utils";
77
import { info } from "../../utils/log";
88

@@ -30,21 +30,15 @@ export const openQueueEvents = async (
3030
}));
3131

3232
const messageBroker = (ws.data.mb = new MessageBroker<object>(
33-
async (msg: string | Buffer) => send(ws, msg)
33+
async (msg: string | BufferSource) => send(ws, msg)
3434
));
3535

3636
const events = ws.data.events || [];
3737
const cleanUps = [];
3838

3939
events.forEach((event) => {
4040
const eventHandler = async (...args: any[]) => {
41-
await messageBroker.sendData(
42-
{
43-
event,
44-
args,
45-
},
46-
{ noack: true }
47-
);
41+
await messageBroker.sendData({ event, args }, { noack: true });
4842
};
4943
info(`Subscribing to event: ${event}, for queue: ${queueName}`);
5044
queueEvents.on(event, eventHandler);
@@ -58,17 +52,17 @@ export const QueueEventsController: WebSocketBehaviour = {
5852
message: async (
5953
_ws: ServerWebSocket<QueueEventsWebSocketData>,
6054
_message: string | Buffer
61-
) => { },
55+
) => {},
6256

6357
drain: (_ws) => {
6458
// console.log("WebSocket backpressure: " + ws.getBufferedAmount());
6559
},
6660

6761
close: async (ws, code, message) => {
6862
info(
69-
`WebSocket closed for queue events (${ws.data.queueName}) with code ${code}${message ? `and message ${Buffer.from(
70-
message
71-
).toString()}` : ""}`
63+
`WebSocket closed for queue events (${ws.data.queueName}) with code ${code}${
64+
message ? `and message ${Buffer.from(message).toString()}` : ""
65+
}`
7266
);
7367

7468
const { queueEvents } = ws.data;

src/controllers/websocket/queue.ts

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { Queue, ConnectionOptions } from "bullmq";
33
import { Value } from "@sinclair/typebox/value";
44
import { ServerWebSocket } from "bun";
55

6-
import { WebSocketBehaviour } from "../../interfaces/websocket-behaviour";
6+
import { WebSocketBehaviour, BufferSource } from "../../interfaces";
77
import { respond, send } from "../utils";
88
import { info } from "../../utils/log";
99
import { QueueSchema, QueueSchemaType } from "../commands";
@@ -20,7 +20,9 @@ export const openQueue = async (ws: ServerWebSocket<QueueWebSocketData>) => {
2020
info(`Queue connected for queue ${queueName}`);
2121

2222
ws.data.queue = new Queue(queueName, { connection });
23-
ws.data.mb = new MessageBroker<object>(async (msg: string | Buffer) => send(ws, msg));
23+
ws.data.mb = new MessageBroker<object>(async (msg: string | BufferSource) =>
24+
send(ws, msg)
25+
);
2426
};
2527

2628
export const QueueController: WebSocketBehaviour = {
@@ -40,14 +42,16 @@ export const QueueController: WebSocketBehaviour = {
4042
if (firstError) {
4143
// The errors are difficult to read, so we'll just send a generic one
4244
// until we can do something better.
43-
respond(ws, parsedMessage.id, { err: { message: `Invalid message ${message}`, stack: "" } })
45+
respond(ws, parsedMessage.id, {
46+
err: { message: `Invalid message ${message}`, stack: "" },
47+
});
4448
return;
4549
}
4650

4751
const queue = ws.data.queue;
48-
const { fn, args }: { fn: string, args: any[] } = parsedMessage.data;
52+
const { fn, args }: { fn: string; args: any[] } = parsedMessage.data;
4953
try {
50-
const queueMethod = (<any>queue)[fn] as Function
54+
const queueMethod = (<any>queue)[fn] as Function;
5155
const result = await queueMethod.apply(queue, args);
5256
respond(ws, parsedMessage.id, { ok: result });
5357
} catch (err) {
@@ -64,9 +68,9 @@ export const QueueController: WebSocketBehaviour = {
6468

6569
close: async (ws, code, message) => {
6670
info(
67-
`WebSocket closed for queue (${ws.data.queueName}) with code ${code}${message ? `and message ${Buffer.from(
68-
message
69-
).toString()}` : ""}`
71+
`WebSocket closed for queue (${ws.data.queueName}) with code ${code}${
72+
message ? `and message ${Buffer.from(message).toString()}` : ""
73+
}`
7074
);
7175

7276
const queue = ws.data.queue;

src/controllers/websocket/worker.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { Worker, ConnectionOptions, Job } from "bullmq";
44

55
import { send } from "../utils";
66
import { info } from "../../utils/log";
7+
import { BufferSource } from "../../interfaces";
78

89
export interface WorkerWebSocketData {
910
connection: ConnectionOptions;
@@ -20,7 +21,7 @@ export const openWorker = async (ws: ServerWebSocket<WorkerWebSocketData>) => {
2021
`Worker connected for queue ${queueName} with concurrency ${concurrency}`
2122
);
2223

23-
const mb = (ws.data.mb = new MessageBroker<object>(async (msg: string | Buffer) =>
24+
const mb = (ws.data.mb = new MessageBroker<object>(async (msg: string | BufferSource) =>
2425
send(ws, msg)
2526
));
2627

src/interfaces/buffer-source.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export type BufferSource = NodeJS.TypedArray | DataView | ArrayBufferLike;

src/interfaces/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ export * from './http-handler-opts';
22
export * from './websocket-behaviour';
33
export * from './worker-endpoint';
44
export * from './worker-metadata';
5+
export * from './buffer-source';

0 commit comments

Comments
 (0)