(options: {
coderService: CoderService;
getArchiveBehavior: () => CoderWorkspaceArchiveBehavior;
timeoutMs?: number;
})
| 52 | } |
| 53 | |
| 54 | export function createCoderArchiveHook(options: { |
| 55 | coderService: CoderService; |
| 56 | getArchiveBehavior: () => CoderWorkspaceArchiveBehavior; |
| 57 | timeoutMs?: number; |
| 58 | }): BeforeArchiveHook { |
| 59 | const timeoutMs = options.timeoutMs ?? DEFAULT_STOP_TIMEOUT_MS; |
| 60 | |
| 61 | return async ({ workspaceId, workspaceMetadata }): Promise<Result<void>> => { |
| 62 | const runtimeConfig = workspaceMetadata.runtimeConfig; |
| 63 | if (!isSSHRuntime(runtimeConfig) || !runtimeConfig.coder) { |
| 64 | return Ok(undefined); |
| 65 | } |
| 66 | |
| 67 | const coder = runtimeConfig.coder; |
| 68 | |
| 69 | // Important safety invariant: |
| 70 | // Only stop/delete Coder workspaces that mux created (dedicated workspaces). If the user |
| 71 | // connected mux to an existing Coder workspace, archiving in mux should *not* manage their |
| 72 | // environment. |
| 73 | if (coder.existingWorkspace === true) { |
| 74 | return Ok(undefined); |
| 75 | } |
| 76 | |
| 77 | const workspaceName = coder.workspaceName?.trim(); |
| 78 | if (!workspaceName) { |
| 79 | return Ok(undefined); |
| 80 | } |
| 81 | |
| 82 | const archiveBehavior = options.getArchiveBehavior(); |
| 83 | if (archiveBehavior === "keep") { |
| 84 | return Ok(undefined); |
| 85 | } |
| 86 | |
| 87 | if (archiveBehavior === "delete") { |
| 88 | log.debug("Deleting Coder workspace before mux archive", { |
| 89 | workspaceId, |
| 90 | coderWorkspaceName: workspaceName, |
| 91 | }); |
| 92 | |
| 93 | try { |
| 94 | await options.coderService.deleteWorkspace(workspaceName); |
| 95 | return Ok(undefined); |
| 96 | } catch (error) { |
| 97 | return Err( |
| 98 | `Failed to delete Coder workspace "${workspaceName}": ${getErrorMessage(error)}` |
| 99 | ); |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | // Best-effort: skip the stop call if the control-plane already thinks the workspace is down. |
| 104 | const status = await options.coderService.getWorkspaceStatus(workspaceName, { |
| 105 | timeoutMs: DEFAULT_STATUS_TIMEOUT_MS, |
| 106 | }); |
| 107 | |
| 108 | if (isAlreadyStoppedOrGone(status)) { |
| 109 | return Ok(undefined); |
| 110 | } |
| 111 |
no test coverage detected