Skip to content

Commit

Permalink
Acks on 100ms interval. Minizmize logging overhead.
Browse files Browse the repository at this point in the history
  • Loading branch information
jhonnold committed Jul 23, 2023
1 parent 0af25ff commit fedb3ba
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
24 changes: 23 additions & 1 deletion src/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,20 @@ class Connection {

private unproccessed: string[];

private acks: string[];

private timer: NodeJS.Timeout;

private ackTimer: NodeJS.Timeout;

private lock: AsyncLock;

constructor(host: string, port: number, handler: Handler) {
this.host = host;
this.port = port;
this.handler = handler;
this.unproccessed = [];
this.acks = [];
this.lock = new AsyncLock();

this.socket = createSocket('udp4');
Expand Down Expand Up @@ -65,6 +70,19 @@ class Connection {
logger.error(`Error processing messages - ${err}`, { port: this.port });
});
}, PROCESSING_INTERVAL);

this.ackTimer = setInterval(() => {
this.lock.acquire('acks', () => {
const ids = [...this.acks];
this.acks = [];
return ids;
})
.then((ids) => {
if (!ids.length) return;

ids.forEach(id => this.send(`ACK: ${id}`));
})
}, PROCESSING_INTERVAL);
}

private onError(err: Error): void {
Expand All @@ -86,7 +104,10 @@ class Connection {

if (fullMessage.startsWith('<')) {
const [idString, ...rest] = fullMessage.substring(1).split('>');
this.send(`ACK: ${idString}`);

this.lock.acquire('acks', () => {
this.acks.push(idString);
});

const id = parseInt(idString);
if (id === 1) {
Expand Down Expand Up @@ -117,6 +138,7 @@ class Connection {

close(): void {
clearInterval(this.timer);
clearInterval(this.ackTimer);
this.socket.close();
}
}
Expand Down
11 changes: 5 additions & 6 deletions src/util/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ const { blue, green, yellow, red } = chalk;
const { combine, timestamp, printf } = format;

const colorMap: { [key: string]: chalk.Chalk } = {
DEBUG: blue,
INFO: green,
WARN: yellow,
ERROR: red,
debug: blue,
info: green,
warn: yellow,
error: red,
};

const logger = createLogger({
Expand All @@ -20,8 +20,7 @@ const logger = createLogger({
timestamp(),
printf(
(info) =>
`${info.timestamp} ${colorMap[info.level.toUpperCase()](`[${info.level.toUpperCase().padStart(5)}]`)} ` +
`${info.port ? `[P${info.port}] ` : ''}${info.message}`,
`${info.timestamp} ${colorMap[info.level](`[${info.level}]`)} [P${info.port}] ${info.message}`,
),
),
});
Expand Down

0 comments on commit fedb3ba

Please sign in to comment.