-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathworkspace.ts
More file actions
214 lines (186 loc) · 5.88 KB
/
workspace.ts
File metadata and controls
214 lines (186 loc) · 5.88 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
import { type Api } from "coder/site/src/api/api";
import {
type WorkspaceAgentLog,
type ProvisionerJobLog,
type Workspace,
} from "coder/site/src/api/typesGenerated";
import { spawn } from "node:child_process";
import * as vscode from "vscode";
import { type FeatureSet } from "../featureSet";
import { getGlobalShellFlags, type CliAuth } from "../settings/cli";
import { escapeCommandArg } from "../util";
import { type UnidirectionalStream } from "../websocket/eventStreamConnection";
import { errToStr, createWorkspaceIdentifier } from "./api-helper";
import { type CoderApi } from "./coderApi";
/** Opens a stream once; subsequent open() calls are no-ops until closed. */
export class LazyStream<T> {
private stream: UnidirectionalStream<T> | null = null;
private opening: Promise<void> | null = null;
async open(factory: () => Promise<UnidirectionalStream<T>>): Promise<void> {
if (this.stream) return;
// Deduplicate concurrent calls; close() clears the reference to cancel.
if (!this.opening) {
const promise = factory().then((s) => {
if (this.opening === promise) {
this.stream = s;
this.opening = null;
} else {
s.close();
}
});
this.opening = promise;
}
await this.opening;
}
close(): void {
this.stream?.close();
this.stream = null;
this.opening = null;
}
}
interface CliContext {
restClient: Api;
auth: CliAuth;
binPath: string;
workspace: Workspace;
writeEmitter: vscode.EventEmitter<string>;
featureSet: FeatureSet;
}
/**
* Spawn a Coder CLI subcommand and stream its output.
* Resolves when the process exits successfully; rejects on non-zero exit.
*/
function runCliCommand(ctx: CliContext, args: string[]): Promise<void> {
return new Promise((resolve, reject) => {
const fullArgs = [
...getGlobalShellFlags(vscode.workspace.getConfiguration(), ctx.auth),
...args,
createWorkspaceIdentifier(ctx.workspace),
];
const cmd = `${escapeCommandArg(ctx.binPath)} ${fullArgs.join(" ")}`;
const proc = spawn(cmd, { shell: true });
proc.stdout.on("data", (data: Buffer) => {
for (const line of splitLines(data)) {
ctx.writeEmitter.fire(line + "\r\n");
}
});
let capturedStderr = "";
proc.stderr.on("data", (data: Buffer) => {
for (const line of splitLines(data)) {
ctx.writeEmitter.fire(line + "\r\n");
capturedStderr += line + "\n";
}
});
proc.on("close", (code: number) => {
if (code === 0) {
resolve();
} else {
let errorText = `"${fullArgs.join(" ")}" exited with code ${code}`;
if (capturedStderr !== "") {
errorText += `: ${capturedStderr}`;
}
reject(new Error(errorText));
}
});
});
}
function splitLines(data: Buffer): string[] {
return data
.toString()
.split(/\r*\n/)
.filter((line) => line !== "");
}
/**
* Start a stopped or failed workspace using `coder start`.
* No-ops if the workspace is already running.
*/
export async function startWorkspace(ctx: CliContext): Promise<Workspace> {
if (!["stopped", "failed"].includes(ctx.workspace.latest_build.status)) {
return ctx.workspace;
}
const args = ["start", "--yes"];
if (ctx.featureSet.buildReason) {
args.push("--reason", "vscode_connection");
}
await runCliCommand(ctx, args);
return ctx.restClient.getWorkspace(ctx.workspace.id);
}
/**
* Update a workspace to the latest template version.
*
* Uses `coder update` when the CLI supports it (>= 2.25).
* Falls back to the REST API: stop, wait, then updateWorkspaceVersion.
*/
export async function updateWorkspace(ctx: CliContext): Promise<Workspace> {
if (ctx.featureSet.cliUpdate) {
await runCliCommand(ctx, ["update"]);
return ctx.restClient.getWorkspace(ctx.workspace.id);
}
// REST API fallback for older CLIs.
if (ctx.workspace.latest_build.status === "running") {
ctx.writeEmitter.fire("Stopping workspace for update...\r\n");
const stopBuild = await ctx.restClient.stopWorkspace(ctx.workspace.id);
const stoppedJob = await ctx.restClient.waitForBuild(stopBuild);
if (stoppedJob?.status === "canceled") {
throw new Error("Workspace update canceled during stop");
}
}
ctx.writeEmitter.fire("Starting workspace with updated template...\r\n");
await ctx.restClient.updateWorkspaceVersion(ctx.workspace);
return ctx.restClient.getWorkspace(ctx.workspace.id);
}
/**
* Streams build logs in real-time via a callback.
* Returns the websocket for lifecycle management.
*/
export async function streamBuildLogs(
client: CoderApi,
onOutput: (line: string) => void,
buildId: string,
): Promise<UnidirectionalStream<ProvisionerJobLog>> {
const socket = await client.watchBuildLogsByBuildId(buildId, []);
socket.addEventListener("message", (data) => {
if (data.parseError) {
onOutput(errToStr(data.parseError, "Failed to parse message"));
} else {
onOutput(data.parsedMessage.output);
}
});
socket.addEventListener("error", (error) => {
const baseUrlRaw = client.getAxiosInstance().defaults.baseURL;
onOutput(
`Error watching workspace build logs on ${baseUrlRaw}: ${errToStr(error, "no further details")}`,
);
});
socket.addEventListener("close", () => {
onOutput("Build complete");
});
return socket;
}
/**
* Streams agent logs in real-time via a callback.
* Returns the websocket for lifecycle management.
*/
export async function streamAgentLogs(
client: CoderApi,
onOutput: (line: string) => void,
agentId: string,
): Promise<UnidirectionalStream<WorkspaceAgentLog[]>> {
const socket = await client.watchWorkspaceAgentLogs(agentId, []);
socket.addEventListener("message", (data) => {
if (data.parseError) {
onOutput(errToStr(data.parseError, "Failed to parse message"));
} else {
for (const log of data.parsedMessage) {
onOutput(log.output);
}
}
});
socket.addEventListener("error", (error) => {
const baseUrlRaw = client.getAxiosInstance().defaults.baseURL;
onOutput(
`Error watching agent logs on ${baseUrlRaw}: ${errToStr(error, "no further details")}`,
);
});
return socket;
}