-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi-monitor-cs-main.ts
79 lines (73 loc) · 2.21 KB
/
api-monitor-cs-main.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
79
import { EMsg, windowListen, windowPost } from './api/communication.ts';
import { IS_DEV } from './api/env.ts';
import { TELEMETRY_FREQUENCY_1PS } from './api/const.ts';
import { adjustTelemetryDelay, Timer } from './api/time.ts';
import {
onEachSecond,
setSettings,
cleanHistory,
collectMetrics,
runMediaCommand,
runTimerCommand,
type TTelemetry,
} from './wrapper/Wrapper.ts';
import diff from './api/diff.ts';
let originalMetrics: TTelemetry | null;
let currentMetrics: TTelemetry | null;
const eachSecond = new Timer({ delay: 1e3, repetitive: true }, onEachSecond);
const tick = new Timer(
{ delay: TELEMETRY_FREQUENCY_1PS, repetitive: false },
function apiMonitorTelemetryTick() {
const now = Date.now();
currentMetrics = structuredClone(collectMetrics());
if (!originalMetrics) {
originalMetrics = currentMetrics;
windowPost({
msg: EMsg.TELEMETRY,
timeOfCollection: now,
telemetry: originalMetrics,
});
} else {
const delta = diff.diff(originalMetrics, currentMetrics);
if (delta) {
windowPost({
msg: EMsg.TELEMETRY,
timeOfCollection: now,
telemetryDelta: delta,
});
} else {
tick.start();
}
}
}
);
windowListen((o) => {
if (o.msg === EMsg.TELEMETRY_ACKNOWLEDGED) {
tick.delay = adjustTelemetryDelay(o.timeOfCollection);
originalMetrics = currentMetrics;
eachSecond.isPending() && tick.start();
} else if (
o.msg === EMsg.SETTINGS &&
o.settings &&
typeof o.settings === 'object'
) {
setSettings(o.settings);
} else if (o.msg === EMsg.START_OBSERVE) {
originalMetrics = currentMetrics = null;
tick.trigger();
eachSecond.start();
} else if (o.msg === EMsg.STOP_OBSERVE) {
tick.stop();
eachSecond.stop();
originalMetrics = currentMetrics = null;
} else if (o.msg === EMsg.RESET_WRAPPER_HISTORY) {
originalMetrics = currentMetrics = null;
cleanHistory();
!tick.isPending() && tick.trigger();
} else if (o.msg === EMsg.TIMER_COMMAND) {
runTimerCommand(o.type, o.handler);
} else if (o.msg === EMsg.MEDIA_COMMAND) {
runMediaCommand(o.mediaId, o.cmd, o.property);
}
});
IS_DEV && console.debug('cs-main.ts');