forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatus-checker.ts
More file actions
67 lines (58 loc) · 1.64 KB
/
Copy pathstatus-checker.ts
File metadata and controls
67 lines (58 loc) · 1.64 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
import {
COPILOT_CLOUD_API_URL,
COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,
Severity,
} from "@copilotkit/shared";
const STATUS_CHECK_INTERVAL = 1000 * 60 * 5; // 5 minutes
export type Status = {
severity: Severity;
message: string;
};
export class StatusChecker {
private activeKey: string | null = null;
private intervalId: ReturnType<typeof setInterval> | null = null;
private instanceCount = 0;
private lastResponse: Status | null = null;
async start(
publicApiKey: string,
onUpdate?: (status: Status | null) => void,
) {
this.instanceCount++;
if (this.activeKey === publicApiKey) return;
if (this.intervalId) clearInterval(this.intervalId);
const checkStatus = async () => {
try {
const response = await fetch(`${COPILOT_CLOUD_API_URL}/ciu`, {
method: "GET",
headers: {
[COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey,
},
}).then((response) => response.json() as Promise<Status>);
this.lastResponse = response;
onUpdate?.(response);
return response;
} catch (error) {
// Silently fail
return null;
}
};
const initialResponse = await checkStatus();
this.intervalId = setInterval(checkStatus, STATUS_CHECK_INTERVAL);
this.activeKey = publicApiKey;
return initialResponse;
}
getLastResponse() {
return this.lastResponse;
}
stop() {
this.instanceCount--;
if (this.instanceCount === 0) {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
this.activeKey = null;
this.lastResponse = null;
}
}
}
}