-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathusageTimeoutManager.ts
More file actions
71 lines (57 loc) · 2 KB
/
usageTimeoutManager.ts
File metadata and controls
71 lines (57 loc) · 2 KB
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
import { UsageManager } from "../usage/types.js";
import { TaskRunExceededMaxDuration, TimeoutManager } from "./types.js";
export class UsageTimeoutManager implements TimeoutManager {
private _abortController: AbortController;
private _abortSignal: AbortSignal | undefined;
private _intervalId: NodeJS.Timeout | undefined;
private _listener?: (
timeoutInSeconds: number,
elapsedTimeInSeconds: number
) => void | Promise<void>;
constructor(private readonly usageManager: UsageManager) {
this._abortController = new AbortController();
}
registerListener(
listener: (timeoutInSeconds: number, elapsedTimeInSeconds: number) => void | Promise<void>
): void {
this._listener = listener;
}
get signal(): AbortSignal | undefined {
return this._abortSignal;
}
reset(): void {
this._abortController = new AbortController();
this._abortSignal = undefined;
if (this._intervalId) {
clearInterval(this._intervalId);
this._intervalId = undefined;
}
}
abortAfterTimeout(timeoutInSeconds?: number): AbortController {
this._abortSignal = this._abortController.signal;
if (!timeoutInSeconds) {
return this._abortController;
}
if (this._intervalId) {
clearInterval(this._intervalId);
}
// Now we need to start an interval that will measure usage and abort the signal if the usage is too high
this._intervalId = setInterval(() => {
const sample = this.usageManager.sample();
if (sample) {
if (sample.cpuTime > timeoutInSeconds * 1000) {
clearInterval(this._intervalId);
const elapsedTimeInSeconds = sample.cpuTime / 1000;
// Call the listener if registered
if (this._listener) {
void this._listener(timeoutInSeconds, elapsedTimeInSeconds);
}
this._abortController.abort(
new TaskRunExceededMaxDuration(timeoutInSeconds, elapsedTimeInSeconds)
);
}
}
}, 1000);
return this._abortController;
}
}