-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathworkspaceMonitor.ts
More file actions
232 lines (206 loc) · 6.64 KB
/
workspaceMonitor.ts
File metadata and controls
232 lines (206 loc) · 6.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import { Api } from "coder/site/src/api/api";
import { Workspace } from "coder/site/src/api/typesGenerated";
import { formatDistanceToNowStrict } from "date-fns";
import { EventSource } from "eventsource";
import * as vscode from "vscode";
import { createStreamingFetchAdapter } from "./api";
import { errToStr } from "./api-helper";
import { Storage } from "./storage";
/**
* Monitor a single workspace using SSE for events like shutdown and deletion.
* Notify the user about relevant changes and update contexts as needed. The
* workspace status is also shown in the status bar menu.
*/
export class WorkspaceMonitor implements vscode.Disposable {
private eventSource: EventSource;
private disposed = false;
// How soon in advance to notify about autostop and deletion.
private autostopNotifyTime = 1000 * 60 * 30; // 30 minutes.
private deletionNotifyTime = 1000 * 60 * 60 * 24; // 24 hours.
// Only notify once.
private notifiedAutostop = false;
private notifiedDeletion = false;
private notifiedOutdated = false;
private notifiedNotRunning = false;
readonly onChange = new vscode.EventEmitter<Workspace>();
private readonly statusBarItem: vscode.StatusBarItem;
// For logging.
private readonly name: string;
constructor(
workspace: Workspace,
private readonly restClient: Api,
private readonly storage: Storage,
// We use the proposed API to get access to useCustom in dialogs.
private readonly vscodeProposed: typeof vscode,
) {
this.name = `${workspace.owner_name}/${workspace.name}`;
const url = this.restClient.getAxiosInstance().defaults.baseURL;
const watchUrl = new URL(`${url}/api/v2/workspaces/${workspace.id}/watch`);
this.storage.writeToCoderOutputChannel(`Monitoring ${this.name}...`);
const eventSource = new EventSource(watchUrl.toString(), {
fetch: createStreamingFetchAdapter(this.restClient.getAxiosInstance()),
});
eventSource.addEventListener("data", (event) => {
try {
const newWorkspaceData = JSON.parse(event.data) as Workspace;
this.update(newWorkspaceData);
this.maybeNotify(newWorkspaceData);
this.onChange.fire(newWorkspaceData);
} catch (error) {
this.notifyError(error);
}
});
eventSource.addEventListener("error", (event) => {
this.notifyError(event);
});
// Store so we can close in dispose().
this.eventSource = eventSource;
const statusBarItem = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Left,
999,
);
statusBarItem.name = "Coder Workspace Update";
statusBarItem.text = "$(fold-up) Update Workspace";
statusBarItem.command = "coder.workspace.update";
// Store so we can update when the workspace data updates.
this.statusBarItem = statusBarItem;
this.update(workspace); // Set initial state.
}
/**
* Permanently close the SSE stream.
*/
dispose() {
if (!this.disposed) {
this.storage.writeToCoderOutputChannel(`Unmonitoring ${this.name}...`);
this.statusBarItem.dispose();
this.eventSource.close();
this.disposed = true;
}
}
private update(workspace: Workspace) {
this.updateContext(workspace);
this.updateStatusBar(workspace);
}
private maybeNotify(workspace: Workspace) {
this.maybeNotifyOutdated(workspace);
this.maybeNotifyAutostop(workspace);
this.maybeNotifyDeletion(workspace);
this.maybeNotifyNotRunning(workspace);
}
private maybeNotifyAutostop(workspace: Workspace) {
if (
workspace.latest_build.status === "running" &&
workspace.latest_build.deadline &&
!this.notifiedAutostop &&
this.isImpending(workspace.latest_build.deadline, this.autostopNotifyTime)
) {
const toAutostopTime = formatDistanceToNowStrict(
new Date(workspace.latest_build.deadline),
);
vscode.window.showInformationMessage(
`${this.name} is scheduled to shut down in ${toAutostopTime}.`,
);
this.notifiedAutostop = true;
}
}
private maybeNotifyDeletion(workspace: Workspace) {
if (
workspace.deleting_at &&
!this.notifiedDeletion &&
this.isImpending(workspace.deleting_at, this.deletionNotifyTime)
) {
const toShutdownTime = formatDistanceToNowStrict(
new Date(workspace.deleting_at),
);
vscode.window.showInformationMessage(
`${this.name} is scheduled for deletion in ${toShutdownTime}.`,
);
this.notifiedDeletion = true;
}
}
private maybeNotifyNotRunning(workspace: Workspace) {
if (
!this.notifiedNotRunning &&
workspace.latest_build.status !== "running"
) {
this.notifiedNotRunning = true;
this.vscodeProposed.window
.showInformationMessage(
`${this.name} is no longer running!`,
{
detail: `The workspace status is "${workspace.latest_build.status}". Reload the window to reconnect.`,
modal: true,
useCustom: true,
},
"Reload Window",
)
.then((action) => {
if (!action) {
return;
}
vscode.commands.executeCommand("workbench.action.reloadWindow");
});
}
}
private isImpending(target: string, notifyTime: number): boolean {
const nowTime = new Date().getTime();
const targetTime = new Date(target).getTime();
const timeLeft = targetTime - nowTime;
return timeLeft >= 0 && timeLeft <= notifyTime;
}
private maybeNotifyOutdated(workspace: Workspace) {
if (!this.notifiedOutdated && workspace.outdated) {
this.notifiedOutdated = true;
// Check if update notifications are disabled
const disableNotifications = vscode.workspace
.getConfiguration("coder")
.get<boolean>("disableUpdateNotifications", false);
if (disableNotifications) {
return;
}
this.restClient
.getTemplate(workspace.template_id)
.then((template) => {
return this.restClient.getTemplateVersion(template.active_version_id);
})
.then((version) => {
const infoMessage = version.message
? `A new version of your workspace is available: ${version.message}`
: "A new version of your workspace is available.";
vscode.window
.showInformationMessage(infoMessage, "Update")
.then((action) => {
if (action === "Update") {
vscode.commands.executeCommand(
"coder.workspace.update",
workspace,
this.restClient,
);
}
});
});
}
}
private notifyError(error: unknown) {
// For now, we are not bothering the user about this.
const message = errToStr(
error,
"Got empty error while monitoring workspace",
);
this.storage.writeToCoderOutputChannel(message);
}
private updateContext(workspace: Workspace) {
vscode.commands.executeCommand(
"setContext",
"coder.workspace.updatable",
workspace.outdated,
);
}
private updateStatusBar(workspace: Workspace) {
if (!workspace.outdated) {
this.statusBarItem.hide();
} else {
this.statusBarItem.show();
}
}
}