-
Notifications
You must be signed in to change notification settings - Fork 10
/
message-id-counter.ts
47 lines (41 loc) · 1.3 KB
/
message-id-counter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Always return **next** the current counter value and increment the counter.
* @param epoch epoch of the message
* @throws Error if the counter exceeds the message limit
*/
export interface IMessageIDCounter {
messageLimit: bigint;
/**
* Return the current counter value and increment the counter.
*
* @param epoch
*/
getMessageIDAndIncrement(epoch: bigint): Promise<bigint>
}
type EpochMap = {
[epoch: string]: bigint
}
export class MemoryMessageIDCounter implements IMessageIDCounter {
protected _messageLimit: bigint
protected epochToMessageID: EpochMap
constructor(messageLimit: bigint) {
this._messageLimit = messageLimit
this.epochToMessageID = {}
}
get messageLimit(): bigint {
return this._messageLimit
}
async getMessageIDAndIncrement(epoch: bigint): Promise<bigint> {
const epochStr = epoch.toString()
// Initialize the message id counter if it doesn't exist
if (this.epochToMessageID[epochStr] === undefined) {
this.epochToMessageID[epochStr] = BigInt(0)
}
const messageID = this.epochToMessageID[epochStr]
if (messageID >= this.messageLimit) {
throw new Error(`Message ID counter exceeded message limit ${this.messageLimit}`)
}
this.epochToMessageID[epochStr] = messageID + BigInt(1)
return messageID
}
}