Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ and Spinbox says once what is missing.
Sign Out, under **Spinbox** in the Command Palette.
- **Links**: `vscode://spin-stack.spinbox/open?workspace=<id>` opens a workspace from a browser,
and `&path=<absolute path>` a folder inside it.
- **Reconnects that start the workspace**: a window reopening a workspace over Remote-SSH, by a
reload or from the recent list, has Spinbox start it and attach your VS Code's server first; a
refusal is shown with what fixes it, and the window leaves the remote instead of Remote-SSH
failing on its own.
- **Errors you can act on**: an outdated CLI, a missing SSH key or no room for a workspace each say
what fixes it, with a button for it where there is one.

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"main": "./dist/extension.js",
"activationEvents": [
"onStartupFinished",
"onResolveRemoteAuthority:ssh-remote",
"onUri",
"onCommand:spinbox.openWorkspace",
"onCommand:spinbox.signIn",
Expand Down
6 changes: 5 additions & 1 deletion src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ import { registerAuth } from "./auth"
import { createSpin } from "./cli/vscode"
import { configureErrors } from "./errors"
import { registerOpen } from "./open"
import { connectWindow } from "./remote"
import { registerStatus } from "./status"
import { registerViews } from "./views"

export function activate(context: vscode.ExtensionContext): void {
// activate resolves once a window connecting to a Spinbox workspace over Remote-SSH has it ready:
// VS Code waits for it before Remote-SSH resolves (src/remote/connect.ts).
export async function activate(context: vscode.ExtensionContext): Promise<void> {
const spin = createSpin(context)
configureErrors({
cli: spin.cli,
Expand All @@ -20,6 +23,7 @@ export function activate(context: vscode.ExtensionContext): void {
// Signing in or out from the Accounts menu changes what the view lists.
context.subscriptions.push(auth.onDidChangeSessions(() => void tree.refresh()))
registerStatus(context, spin.cli)
await connectWindow(spin.cli)
}

export function deactivate(): void {}
81 changes: 81 additions & 0 deletions src/remote/connect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import type { SpinCli } from "../cli/client"
import { parseSpinRemote } from "../status/authority"
import type { Trace } from "../telemetry"

// Remote-SSH connects a window to ssh-remote+spin.<workspace> by itself: on a reconnect, a reload
// or a recent folder, nothing of Spinbox's ran first, and a stopped workspace or a refused key is
// an opaque Remote-SSH error. So Spinbox activates on onResolveRemoteAuthority:ssh-remote, which
// VS Code waits for before Remote-SSH resolves, and readies the workspace first, as Coder's
// extension does (coder/vscode-coder docs/ARCHITECTURE.md): `spin code --start` starts it,
// attaches this VS Code's server, writes the ssh config, and connects once through it - which runs
// `spin ssh-prepare` and its launch-claim check - so a refusal is the CLI's error, with its action,
// here. A failure closes the remote, so Remote-SSH does not go on to fail its own way.

export type ConnectCli = Pick<SpinCli, "code">

export interface ConnectUi {
// Runs task under a cancelable notification, as OpenUi's progress.
progress<T>(
title: string,
task: (signal: AbortSignal, report: (message: string) => void) => Promise<T>,
): Promise<T>
// The CLI's failure with its action, resolving once it is answered and the action has run.
showCliError(error: unknown, retry: () => Promise<void>): Promise<void>
// workbench.action.remote.close: the window leaves the remote it was connecting to.
closeRemote(): Promise<void>
}

export interface ConnectDeps {
cli: ConnectCli
ui: ConnectUi
commit(): Promise<string>
vscodeVersion: string
trace: Trace
}

// prepareConnection readies the workspace this window is resolving over Remote-SSH. It answers
// undefined for an authority that is no Spinbox workspace, having done nothing; true when Remote-SSH
// may connect; false when it closed the remote: the open failed and its retry did not take, or the
// person cancelled.
export async function prepareConnection(
deps: ConnectDeps,
remoteName: string | undefined,
authority: string | undefined,
): Promise<boolean | undefined> {
const remote = remoteName === "ssh-remote" ? parseSpinRemote(remoteName, authority) : undefined
if (remote === undefined) {
return undefined
}
let ready = false
const attempt = async (): Promise<void> => {
const commit = await deps.commit()
const traceparent = deps.trace()
ready = await deps.ui.progress(`Connecting to ${remote.workspace}`, async (signal, report) => {
try {
await deps.cli.code(remote.workspace, undefined, commit, {
start: true,
vscodeVersion: deps.vscodeVersion,
signal,
traceparent,
onPreparing: (p) =>
report(`Preparing VS Code ${p.vscode_version} for this installation (once): ${p.step}`),
})
return true
} catch (err) {
if (signal.aborted) {
return false
}
throw err
}
})
}
try {
await attempt()
} catch (err) {
await deps.ui.showCliError(err, attempt)
}
if (!ready) {
await deps.ui.closeRemote()
}
return ready
}
95 changes: 95 additions & 0 deletions src/remote/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { homedir } from "node:os"
import { join } from "node:path"
import * as vscode from "vscode"
import { CliError } from "../cli/client"
import { showCliError } from "../errors"
import { readCommit } from "../open/editor"
import { parseSpinRemote } from "../status/authority"
import { trace } from "../telemetry/vscode"
import { type ConnectCli, prepareConnection } from "./connect"
import { fileProxyStatus, type ProxyFailure, proxyFailure, watchProxy } from "./proxy"

export const CLOSE_REMOTE = "workbench.action.remote.close"

// How often, and how long, the proxy's status is read while Remote-SSH connects.
const PROXY_INTERVAL_MS = 1_000
const PROXY_TIMEOUT_MS = 120_000

const closeRemote = async (): Promise<void> => {
await vscode.commands.executeCommand(CLOSE_REMOTE)
}

// connectWindow readies the Spinbox workspace this window is resolving over Remote-SSH, if it is
// one (connect.ts), and then follows the connection Remote-SSH makes (proxy.ts). Activation waits
// on it, and Remote-SSH on activation, so it returns before following.
export async function connectWindow(cli: ConnectCli): Promise<void> {
// The window's folder names the authority it resolves: env.remoteAuthority is the resolvers
// proposal's, which this extension does not have.
const authority = (vscode.workspace.workspaceFolders?.[0]?.uri ?? vscode.workspace.workspaceFile)
?.authority
const ready = await prepareConnection(
{
cli,
ui: {
progress: (title, task) =>
Promise.resolve(
vscode.window.withProgress(
{ location: vscode.ProgressLocation.Notification, title, cancellable: true },
(progress, token) => {
const abort = new AbortController()
token.onCancellationRequested(() => abort.abort())
return task(abort.signal, (message) => progress.report({ message }))
},
),
),
showCliError,
closeRemote,
},
commit: () => readCommit(vscode.env.appRoot),
vscodeVersion: vscode.version,
trace,
},
vscode.env.remoteName,
authority,
)
const remote = parseSpinRemote(vscode.env.remoteName, authority)
if (ready === true && remote !== undefined) {
// From now: spin code's own ssh, and the shared connection it leaves, began before.
void followProxy(remote.host, Date.now())
}
}

async function followProxy(host: string, since: number): Promise<void> {
let said: vscode.Disposable | undefined
const dir = join(homedir(), ".spin", "ssh", "status")
const status = await watchProxy(fileProxyStatus(dir, host, since), {
intervalMs: PROXY_INTERVAL_MS,
timeoutMs: PROXY_TIMEOUT_MS,
report: (message) => {
said?.dispose()
said = vscode.window.setStatusBarMessage(`$(sync~spin) Spinbox: ${message}`)
},
})
said?.dispose()
const failure = status === undefined ? undefined : proxyFailure(status)
if (failure !== undefined) {
await showProxyFailure(failure)
await closeRemote()
}
}

const OPEN = "Open"

async function showProxyFailure(failure: ProxyFailure): Promise<void> {
if ("envelope" in failure) {
await showCliError(new CliError(failure.envelope))
return
}
const pick = await vscode.window.showErrorMessage(
failure.message,
...(failure.url === undefined ? [] : [OPEN]),
)
if (pick === OPEN && failure.url !== undefined) {
await vscode.env.openExternal(vscode.Uri.parse(failure.url))
}
}
173 changes: 173 additions & 0 deletions src/remote/proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import { readdir, readFile } from "node:fs/promises"
import { join } from "node:path"
import { type ErrorEnvelope, isErrorEnvelope } from "../cli/contract"

// While Remote-SSH connects, `spin ssh-prepare` and `spin ssh-proxy` - children of its ssh - write
// what happens to that connection to ~/.spin/ssh/status/<ssh pid>.json (spin-stack/spin#1180),
// atomically. Spinbox reads it, says each phase, and shows a refusal with what resolves it, where
// Remote-SSH would show only that ssh exited.

export const STATUS_VERSION = 1

export type ProxyPhase = "resolving" | "connecting" | "connected" | "refused" | "failed"

const PHASES: readonly ProxyPhase[] = ["resolving", "connecting", "connected", "refused", "failed"]

// The CLI's -o json error envelope's error, as written: its code may be one this extension's
// contract does not know yet, so it is not narrowed to ErrorCode here.
export interface ProxyError {
code: string
action: string
message: string
release?: string
workspace_id?: string
url?: string
}

export interface ProxyStatus {
version: typeof STATUS_VERSION
host: string
ssh_pid: number
phase: ProxyPhase
// ssh reuses an open connection, and no proxy runs.
shared?: boolean
workspace_id?: string
error?: ProxyError
started_at: string
updated_at: string
}

export interface ProxyStatusSource {
// The status of the connection being made, or undefined while there is none to read.
read(): Promise<ProxyStatus | undefined>
}

// readProxyStatus parses one status file, or answers undefined for one that is not a status of
// the version this extension reads.
export function readProxyStatus(body: string): ProxyStatus | undefined {
let v: unknown
try {
v = JSON.parse(body)
} catch {
return undefined
}
if (typeof v !== "object" || v === null) {
return undefined
}
const s = v as Record<string, unknown>
if (
s.version !== STATUS_VERSION ||
typeof s.host !== "string" ||
typeof s.ssh_pid !== "number" ||
!PHASES.includes(s.phase as ProxyPhase) ||
!isTime(s.started_at) ||
!isTime(s.updated_at) ||
(s.error !== undefined && !isProxyError(s.error))
) {
return undefined
}
return s as unknown as ProxyStatus
}

function isTime(v: unknown): v is string {
return typeof v === "string" && !Number.isNaN(Date.parse(v))
}

function isProxyError(v: unknown): v is ProxyError {
if (typeof v !== "object" || v === null) {
return false
}
const e = v as Record<string, unknown>
return typeof e.code === "string" && typeof e.action === "string" && typeof e.message === "string"
}

// fileProxyStatus reads, of the status files in dir (~/.spin/ssh/status), the one last updated for
// host whose connection began at or after since: a connection to another workspace, or one made
// before this window's, is never read as its.
export function fileProxyStatus(dir: string, host: string, since: number): ProxyStatusSource {
return {
read: async () => {
let names: string[]
try {
names = (await readdir(dir)).filter((n) => n.endsWith(".json"))
} catch {
return undefined
}
let newest: ProxyStatus | undefined
for (const name of names) {
const s = readProxyStatus(await readFile(join(dir, name), "utf8").catch(() => ""))
if (
s !== undefined &&
s.host === host &&
Date.parse(s.started_at) >= since &&
(newest === undefined || Date.parse(s.updated_at) > Date.parse(newest.updated_at))
) {
newest = s
}
}
return newest
},
}
}

// What a refused or failed connection shows: the CLI's error, with its action, when its code is one
// the contract knows; otherwise its message, and the page that resolves it when it names one.
export type ProxyFailure = { envelope: ErrorEnvelope } | { message: string; url?: string }

export function proxyFailure(status: ProxyStatus): ProxyFailure | undefined {
if (status.phase !== "refused" && status.phase !== "failed") {
return undefined
}
const error = status.error
if (error === undefined) {
return { message: `Spinbox could not connect to ${status.host}.` }
}
const envelope = { error }
if (isErrorEnvelope(envelope)) {
return { envelope }
}
const message = `Spinbox could not connect to ${status.host}: ${error.message}`
return error.url === undefined ? { message } : { message, url: error.url }
}

// What each phase on the way says, as the person reads it.
export const SAYS: Record<"resolving" | "connecting", string> = {
resolving: "finding the workspace",
connecting: "connecting to the workspace",
}

export interface WatchOptions {
intervalMs: number
// How long to read before giving up quietly: Remote-SSH says by then what it has.
timeoutMs: number
// Hears each phase on the way, once.
report(message: string): void
signal?: AbortSignal
}

// watchProxy reads source every intervalMs until it is connected, refused or failed, and answers
// that status; or undefined at timeoutMs, or once signal aborts.
export async function watchProxy(
source: ProxyStatusSource,
opts: WatchOptions,
): Promise<ProxyStatus | undefined> {
const end = Date.now() + opts.timeoutMs
let said: ProxyPhase | undefined
while (opts.signal?.aborted !== true) {
const status = await source.read()
if (status !== undefined) {
if (status.phase !== "resolving" && status.phase !== "connecting") {
return status
}
if (status.phase !== said) {
said = status.phase
opts.report(SAYS[status.phase])
}
}
if (Date.now() >= end) {
return undefined
}
await new Promise((resolve) => setTimeout(resolve, opts.intervalMs))
}
return undefined
}
Loading
Loading