This repository has been archived by the owner on Jul 7, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
response_waiter.ts
78 lines (70 loc) · 1.83 KB
/
response_waiter.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { Deferred, deferred } from "./deps.ts";
import { MessageId, ResponseMessage } from "./message.ts";
const DEFAULT_RESPONSE_TIMEOUT = 10000; // milliseconds
type Waiter = {
timer: number;
response: Deferred<ResponseMessage>;
};
export class TimeoutError extends Error {
constructor() {
super("the process didn't complete in time");
this.name = "TimeoutError";
}
}
/**
* ResponseWaiter is for waiting a response messages for 'msgid'
*/
export class ResponseWaiter {
#waiters: Map<MessageId, Waiter>;
#timeout: number;
constructor(timeout = DEFAULT_RESPONSE_TIMEOUT) {
this.#waiters = new Map();
this.#timeout = timeout;
}
/**
* The number of internal waiters
*/
get waiterCount(): number {
return this.#waiters.size;
}
/**
* Wait a response message of 'msgid'
*/
wait(msgid: MessageId, timeout?: number): Promise<ResponseMessage> {
let response = this.#waiters.get(msgid)?.response;
if (!response) {
response = deferred();
const timer = setTimeout(() => {
const response = this.#waiters.get(msgid)?.response;
if (!response) {
return;
}
response.reject(new TimeoutError());
this.#waiters.delete(msgid);
}, timeout ?? this.#timeout);
this.#waiters.set(msgid, {
timer,
response,
});
}
return response;
}
/**
* Provide a response message
*
* It returns false if no one seems to wait the message.
* Otherwise it returns true.
*/
provide(message: ResponseMessage): boolean {
const [_type, msgid, _error, _result] = message;
const waiter = this.#waiters.get(msgid);
if (!waiter) {
return false;
}
this.#waiters.delete(msgid);
const { timer, response } = waiter;
clearTimeout(timer);
response.resolve(message);
return true;
}
}