Skip to content

Commit

Permalink
Calculate and emit "idle" event only when testing
Browse files Browse the repository at this point in the history
Only some tests rely on the "idle" event. Push/Shift operations on the idleStack introduce extra work (O(N)) in order to calculate the idle status. This kind of routine work should not affect the rate calculation process which is required to be as fast as possible.
  • Loading branch information
weyoss committed Dec 3, 2021
1 parent bcbf067 commit 7948d9b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 17 deletions.
34 changes: 18 additions & 16 deletions src/system/consumer/consumer-message-rate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,6 @@ export class ConsumerMessageRate extends MessageRate<IConsumerMessageRateFields>
protected unacknowledgedRate = 0;
protected idleStack: number[] = new Array(5).fill(0);

// When the idle status is true, it indicates that the consumer has been
// inactive for the last 5 seconds
protected isIdle = false;

constructor(consumer: Consumer, redisClient: RedisClient) {
super(redisClient);
this.consumer = consumer;
Expand All @@ -34,6 +30,22 @@ export class ConsumerMessageRate extends MessageRate<IConsumerMessageRateFields>
this.keyConsumerRateUnacknowledged = keyRateConsumerUnacknowledged;
}

// Returns true if the consumer has been
// inactive for the last 5 seconds
isIdle(): boolean {
if (
this.processingRate === 0 &&
this.acknowledgedRate === 0 &&
this.unacknowledgedRate === 0
) {
this.idleStack.push(1);
} else {
this.idleStack.push(0);
}
this.idleStack.shift();
return this.idleStack.find((i) => i === 0) === undefined;
}

getRateFields(): IConsumerMessageRateFields {
this.processingRate = this.processingSlots.reduce(
(acc: number, cur: number) => acc + cur,
Expand All @@ -50,23 +62,13 @@ export class ConsumerMessageRate extends MessageRate<IConsumerMessageRateFields>
0,
);
this.unacknowledgedSlots.fill(0);
if (
this.processingRate === 0 &&
this.acknowledgedRate === 0 &&
this.unacknowledgedRate === 0
) {
this.idleStack.push(1);
} else {
this.idleStack.push(0);
if (process.env.NODE_ENV === 'test' && this.isIdle()) {
this.consumer.emit(events.IDLE);
}
this.idleStack.shift();
this.isIdle = this.idleStack.find((i) => i === 0) === undefined;
if (this.isIdle) this.consumer.emit(events.IDLE);
return {
processingRate: this.processingRate,
acknowledgedRate: this.acknowledgedRate,
unacknowledgedRate: this.unacknowledgedRate,
isIdle: this.isIdle,
};
}

Expand Down
1 change: 0 additions & 1 deletion types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ export interface IConsumerMessageRateFields
acknowledgedRate: number;
unacknowledgedRate: number;
processingRate: number;
isIdle: boolean;
}

export interface IProducerMessageRateFields extends Record<string, number> {
Expand Down

0 comments on commit 7948d9b

Please sign in to comment.