-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathruntimeFactory.ts
More file actions
320 lines (292 loc) · 11.6 KB
/
Copy pathruntimeFactory.ts
File metadata and controls
320 lines (292 loc) · 11.6 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import * as fs from "fs/promises";
import * as path from "path";
import type { Runtime, WorkspaceInitParams, WorkspaceInitResult } from "./Runtime";
import { LocalRuntime } from "./LocalRuntime";
import { WorktreeRuntime } from "./WorktreeRuntime";
import { SSHRuntime } from "./SSHRuntime";
import { CoderSSHRuntime } from "./CoderSSHRuntime";
import { createSSHTransport } from "./transports";
import { DockerRuntime, getContainerName } from "./DockerRuntime";
import { DevcontainerRuntime } from "./DevcontainerRuntime";
import type { RuntimeConfig, RuntimeMode, RuntimeAvailabilityStatus } from "@/common/types/runtime";
import { hasSrcBaseDir } from "@/common/types/runtime";
import { isIncompatibleRuntimeConfig } from "@/common/utils/runtimeCompatibility";
import { execFileAsync } from "@/node/utils/disposableExec";
import type { CoderService } from "@/node/services/coderService";
import { Config } from "@/node/config";
import { checkDevcontainerCliVersion } from "./devcontainerCli";
import { buildDevcontainerConfigInfo, scanDevcontainerConfigs } from "./devcontainerConfigs";
import { resolveCoderSSHHost } from "@/constants/coder";
import { getErrorMessage } from "@/common/utils/errors";
// Global CoderService singleton - set during app init so all createRuntime calls can use it
let globalCoderService: CoderService | undefined;
/**
* Set the global CoderService instance for runtime factory.
* Call this during app initialization so createRuntime() can create CoderSSHRuntime
* without requiring callers to pass coderService explicitly.
*/
export function setGlobalCoderService(service: CoderService): void {
globalCoderService = service;
}
/**
* Run the full init sequence: postCreateSetup (if present) then initWorkspace.
* Use this everywhere instead of calling initWorkspace directly to ensure
* runtimes with provisioning steps (Docker, CoderSSH) work correctly.
*/
export async function runFullInit(
runtime: Runtime,
params: WorkspaceInitParams
): Promise<WorkspaceInitResult> {
if (runtime.postCreateSetup) {
await runtime.postCreateSetup(params);
}
return runtime.initWorkspace(params);
}
/**
* Fire-and-forget init with standardized error handling.
* Use this for background init after workspace creation (workspaceService, taskService).
*/
export function runBackgroundInit(
runtime: Runtime,
params: WorkspaceInitParams,
workspaceId: string,
logger?: { error: (msg: string, ctx: object) => void }
): void {
void runFullInit(runtime, params).catch((error: unknown) => {
const errorMsg = getErrorMessage(error);
logger?.error(`Workspace init failed for ${workspaceId}:`, { error });
params.initLogger.logStderr(`Initialization failed: ${errorMsg}`);
params.initLogger.logComplete(-1);
});
}
function shouldUseSSH2Runtime(): boolean {
// Windows always uses SSH2 (no native OpenSSH)
if (process.platform === "win32") {
return true;
}
// Other platforms: check config (defaults to OpenSSH)
const config = new Config();
return config.loadConfigOrDefault().useSSH2Transport ?? false;
}
/**
* Error thrown when a workspace has an incompatible runtime configuration,
* typically from a newer version of mux that added new runtime types.
*/
export class IncompatibleRuntimeError extends Error {
constructor(message: string) {
super(message);
this.name = "IncompatibleRuntimeError";
}
}
/**
* Options for creating a runtime.
*/
export interface CreateRuntimeOptions {
/**
* Project path - required for project-dir local runtimes (type: "local" without srcBaseDir).
* For Docker runtimes with existing workspaces, used together with workspaceName to derive container name.
* For other runtime types, this is optional and used only for getWorkspacePath calculations.
*/
projectPath?: string;
/**
* Workspace name - required for Docker runtimes when connecting to an existing workspace.
* Used together with projectPath to derive the container name.
*/
workspaceName?: string;
/**
* Persisted workspace path from config.json.
* Used by devcontainer runtimes to preserve the exact host path from startup.
*/
workspacePath?: string;
/**
* Coder service - required for SSH runtimes with Coder configuration.
* When provided and config has coder field, returns a Coder SSH runtime (SSH/SSH2).
*/
coderService?: CoderService;
}
/**
* Create a Runtime instance based on the configuration.
*
* Handles runtime types:
* - "local" without srcBaseDir: Project-dir runtime (no isolation) - requires projectPath in options
* - "local" with srcBaseDir: Legacy worktree config (backward compat)
* - "worktree": Explicit worktree runtime
* - "ssh": Remote SSH runtime
* - "docker": Docker container runtime
*/
export function createRuntime(config: RuntimeConfig, options?: CreateRuntimeOptions): Runtime {
// Check for incompatible configs from newer versions
if (isIncompatibleRuntimeConfig(config)) {
throw new IncompatibleRuntimeError(
`This workspace uses a runtime configuration from a newer version of mux. ` +
`Please upgrade mux to use this workspace.`
);
}
const runtimeIdentity = {
projectPath: options?.projectPath,
workspaceName: options?.workspaceName,
workspacePath: options?.workspacePath,
};
switch (config.type) {
case "local":
// Check if this is legacy "local" with srcBaseDir (= worktree semantics)
// or new "local" without srcBaseDir (= project-dir semantics)
if (hasSrcBaseDir(config)) {
// Legacy: "local" with srcBaseDir is treated as worktree
return new WorktreeRuntime(config.srcBaseDir, runtimeIdentity);
}
// Project-dir: uses project path directly, no isolation
if (!runtimeIdentity.projectPath) {
throw new Error(
"LocalRuntime requires projectPath in options for project-dir config (type: 'local' without srcBaseDir)"
);
}
return new LocalRuntime(runtimeIdentity.projectPath);
case "worktree":
return new WorktreeRuntime(config.srcBaseDir, runtimeIdentity);
case "ssh": {
// Normalize Coder host before transport creation so both transport
// and runtime use the canonical *.mux--coder hostname from the start.
const sshHost = resolveCoderSSHHost(config.host, config.coder?.workspaceName);
const sshConfig = {
host: sshHost,
srcBaseDir: config.srcBaseDir,
bgOutputDir: config.bgOutputDir,
identityFile: config.identityFile,
port: config.port,
};
const useSSH2 = shouldUseSSH2Runtime();
const transport = createSSHTransport(sshConfig, useSSH2);
// Use a Coder SSH runtime for SSH+Coder when coderService is available (explicit or global)
const coderService = options?.coderService ?? globalCoderService;
if (config.coder) {
if (!coderService) {
throw new Error("Coder runtime requested but CoderService is not initialized");
}
return new CoderSSHRuntime(
{ ...sshConfig, coder: config.coder },
transport,
coderService,
runtimeIdentity
);
}
return new SSHRuntime(sshConfig, transport, runtimeIdentity);
}
case "docker": {
// For existing workspaces, derive container name from project+workspace
const containerName =
runtimeIdentity.projectPath && runtimeIdentity.workspaceName
? getContainerName(runtimeIdentity.projectPath, runtimeIdentity.workspaceName)
: config.containerName;
return new DockerRuntime({
image: config.image,
containerName,
shareCredentials: config.shareCredentials,
});
}
case "devcontainer": {
// Devcontainer uses worktrees on host + container exec
// srcBaseDir sourced from config to honor MUX_ROOT and dev-mode suffixes
const runtime = new DevcontainerRuntime({
srcBaseDir: new Config().srcDir,
configPath: config.configPath,
shareCredentials: config.shareCredentials,
});
// Set workspace path for existing workspaces
// For existing workspaces, prefer the persisted workspacePath — Docker labels
// devcontainers by the exact host path from startup, so canonical reconstruction
// can diverge for migrated/non-canonical entries.
if (options?.workspacePath) {
runtime.setCurrentWorkspacePath(options.workspacePath);
} else if (runtimeIdentity.projectPath && runtimeIdentity.workspaceName) {
runtime.setCurrentWorkspacePath(
runtime.getWorkspacePath(runtimeIdentity.projectPath, runtimeIdentity.workspaceName)
);
}
return runtime;
}
default: {
const unknownConfig = config as { type?: string };
throw new Error(`Unknown runtime type: ${unknownConfig.type ?? "undefined"}`);
}
}
}
/**
* Check if a project has a .git directory (is a git repository).
*/
async function isGitRepository(projectPath: string): Promise<boolean> {
try {
const gitPath = path.join(projectPath, ".git");
const stat = await fs.stat(gitPath);
// .git can be a directory (normal repo) or a file (worktree)
return stat.isDirectory() || stat.isFile();
} catch {
return false;
}
}
/**
* Check if Docker daemon is running and accessible.
*/
async function isDockerAvailable(): Promise<boolean> {
let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
try {
using proc = execFileAsync("docker", ["info"]);
const timeout = new Promise<never>((_, reject) => {
timeoutHandle = setTimeout(() => reject(new Error("timeout")), 5000);
});
await Promise.race([proc.result, timeout]);
return true;
} catch {
return false;
} finally {
if (timeoutHandle) clearTimeout(timeoutHandle);
}
}
type RuntimeAvailabilityMap = Record<RuntimeMode, RuntimeAvailabilityStatus>;
/**
* Check availability of all runtime types for a given project.
* Returns a record of runtime mode to availability status.
*/
export async function checkRuntimeAvailability(
projectPath: string
): Promise<RuntimeAvailabilityMap> {
const [isGit, dockerAvailable, devcontainerCliInfo, devcontainerConfigs] = await Promise.all([
isGitRepository(projectPath),
isDockerAvailable(),
checkDevcontainerCliVersion(),
scanDevcontainerConfigs(projectPath),
]);
const devcontainerConfigInfo = buildDevcontainerConfigInfo(devcontainerConfigs);
const gitRequiredReason = "Requires git repository";
// Determine devcontainer availability
let devcontainerAvailability: RuntimeAvailabilityStatus;
if (!isGit) {
devcontainerAvailability = { available: false, reason: gitRequiredReason };
} else if (!devcontainerCliInfo) {
devcontainerAvailability = {
available: false,
reason: "Dev Container CLI not installed. Run: npm install -g @devcontainers/cli",
};
} else if (!dockerAvailable) {
devcontainerAvailability = { available: false, reason: "Docker daemon not running" };
} else if (devcontainerConfigInfo.length === 0) {
devcontainerAvailability = { available: false, reason: "No devcontainer.json found" };
} else {
devcontainerAvailability = {
available: true,
configs: devcontainerConfigInfo,
cliVersion: devcontainerCliInfo.version,
};
}
return {
local: { available: true },
worktree: isGit ? { available: true } : { available: false, reason: gitRequiredReason },
ssh: isGit ? { available: true } : { available: false, reason: gitRequiredReason },
docker: !isGit
? { available: false, reason: gitRequiredReason }
: !dockerAvailable
? { available: false, reason: "Docker daemon not running" }
: { available: true },
devcontainer: devcontainerAvailability,
};
}