-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathhotkeys.ts
More file actions
72 lines (68 loc) · 2.01 KB
/
hotkeys.ts
File metadata and controls
72 lines (68 loc) · 2.01 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
72
import { type WebSocket } from "ws"
import { VALKEY } from "../../../../common/src/constants"
import { withDeps, Deps } from "./utils"
type HotKeysResponse = {
nodeId: string
hotkeys: [[]]
checkAt: number
monitorRunning: boolean
}
const sendHotKeysFulfilled = (
ws: WebSocket,
connectionId: string,
parsedResponse: HotKeysResponse,
) => {
ws.send(
JSON.stringify({
type: VALKEY.HOTKEYS.hotKeysFulfilled,
payload: {
connectionId,
parsedResponse,
},
}),
)
}
const sendHotKeysError = (
ws: WebSocket,
connectionId: string,
error: unknown,
) => {
console.log(error)
ws.send(
JSON.stringify({
type: VALKEY.HOTKEYS.hotKeysError,
payload: {
connectionId,
error: error instanceof Error ? error.message : String(error),
},
}),
)
}
export const hotKeysRequested = withDeps<Deps, void>(
async ({ ws, connectionId, metricsServerURIs }) => {
const metricsServerURI = metricsServerURIs.get(connectionId)
try {
const initialResponse = await fetch(`${metricsServerURI}/hot-keys`)
const initialParsedResponse: HotKeysResponse = await initialResponse.json() as HotKeysResponse
// Initial request starts monitoring and returns when to fetch results (`checkAt`).
if (initialParsedResponse.checkAt) {
const delay = Math.max(initialParsedResponse.checkAt - Date.now(), 0)
// Schedule the follow-up request for when the monitor cycle finishes
setTimeout(async () => {
try {
const dataResponse = await fetch(`${metricsServerURI}/hot-keys`)
const dataParsedResponse = await dataResponse.json() as HotKeysResponse
sendHotKeysFulfilled(ws, connectionId, dataParsedResponse)
} catch (error) {
sendHotKeysError(ws, connectionId, error)
}
}, delay)
}
else {
sendHotKeysFulfilled(ws, connectionId, initialParsedResponse)
}
} catch (error) {
sendHotKeysError(ws, connectionId, error)
}
},
)