Skip to content

feat: add VS code notifications for workspace actions #111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Jun 27, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
feat: add VS code notifications for workspace actions
  • Loading branch information
Kira-Pilot committed Jun 21, 2023
commit a810f989f7bbfab304c803f2cd355610aa86a56e
122 changes: 122 additions & 0 deletions src/WorkspaceAction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { Workspace, WorkspacesResponse } from "coder/site/src/api/typesGenerated"
import { getWorkspaces } from "coder/site/src/api/api"
import * as vscode from "vscode"

interface NotifiedWorkspace {
workspace: Workspace
wasNotified: boolean
}

export class WorkspaceAction {
#fetchWorkspacesInterval?: ReturnType<typeof setInterval>

#ownedWorkspaces: Workspace[] = []
#workspacesApproachingAutostop: NotifiedWorkspace[] = []
#workspacesApproachingDeletion: NotifiedWorkspace[] = []

private constructor(private readonly vscodeProposed: typeof vscode, ownedWorkspaces: Workspace[]) {
this.#ownedWorkspaces = ownedWorkspaces

// seed initial lists
this.seedNotificationLists()

// set up polling so we get current workspaces data
this.pollGetWorkspaces()
}

static async init(vscodeProposed: typeof vscode) {
// fetch all workspaces owned by the user and set initial public class fields
let ownedWorkspacesResponse: WorkspacesResponse
try {
ownedWorkspacesResponse = await getWorkspaces({ q: "owner:me" })
} catch (error) {
ownedWorkspacesResponse = { workspaces: [], count: 0 }
}

return new WorkspaceAction(vscodeProposed, ownedWorkspacesResponse.workspaces)
}

seedNotificationLists() {
this.#workspacesApproachingAutostop = this.#ownedWorkspaces
.filter(this.filterImpendingAutostopWorkspaces)
.map((workspace: Workspace) => {
const wasNotified =
this.#workspacesApproachingAutostop.find((wn) => wn.workspace.id === workspace.id)?.wasNotified ?? false
return { workspace, wasNotified }
})

// NOTE: this feature is currently in-progess; however, we're including scaffolding for it
// to exemplify the class pattern used for Workspace Actions
this.#workspacesApproachingDeletion = []
}

filterImpendingAutostopWorkspaces(workspace: Workspace) {
if (workspace.latest_build.transition !== "start" || !workspace.latest_build.deadline) {
return false
}

const hoursMilli = 1000 * 60 * 60
// return workspaces with a deadline that is in 1 hr or less
return Math.abs(new Date().getTime() - new Date(workspace.latest_build.deadline).getTime()) <= hoursMilli
}

async pollGetWorkspaces() {
let errorCount = 0
this.#fetchWorkspacesInterval = setInterval(async () => {
try {
const workspacesResult = await getWorkspaces({ q: "owner:me" })
this.#ownedWorkspaces = workspacesResult.workspaces
this.seedNotificationLists()
this.notifyAll()
} catch (error) {
if (errorCount === 3) {
clearInterval(this.#fetchWorkspacesInterval)
}
errorCount++
}
}, 1000 * 5)
}

notifyAll() {
this.notifyImpendingAutostop()
this.notifyImpendingDeletion()
}

notifyImpendingAutostop() {
this.#workspacesApproachingAutostop?.forEach((notifiedWorkspace: NotifiedWorkspace) => {
if (notifiedWorkspace.wasNotified) {
// don't message the user; we've already messaged
return
}

// we display individual notifications for each workspace as VS Code
// intentionally strips new lines from the message text
// https://github.com/Microsoft/vscode/issues/48900
this.vscodeProposed.window.showInformationMessage(
`${notifiedWorkspace.workspace.name} is scheduled to shut down in 1 hour.`,
)
notifiedWorkspace.wasNotified = true
})
}

notifyImpendingDeletion() {
this.#workspacesApproachingDeletion?.forEach((notifiedWorkspace: NotifiedWorkspace) => {
if (notifiedWorkspace.wasNotified) {
// don't message the user; we've already messaged
return
}

// we display individual notifications for each workspace as VS Code
// intentionally strips new lines from the message text
// https://github.com/Microsoft/vscode/issues/48900
this.vscodeProposed.window.showInformationMessage(
`${notifiedWorkspace.workspace.name} is scheduled for deletion.`,
)
notifiedWorkspace.wasNotified = true
})
}

cleanupWorkspaceActions() {
clearInterval(this.#fetchWorkspacesInterval)
}
}
45 changes: 5 additions & 40 deletions src/remote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {
getBuildInfo,
getTemplate,
getWorkspace,
getWorkspaces,
getWorkspaceBuildLogs,
getWorkspaceByOwnerAndName,
startWorkspace,
Expand All @@ -23,6 +22,7 @@ import * as ws from "ws"
import { SSHConfig, SSHValues, defaultSSHConfigResponse, mergeSSHConfigValues } from "./sshConfig"
import { computeSSHProperties, sshSupportsSetEnv } from "./sshSupport"
import { Storage } from "./storage"
import { WorkspaceAction } from "./WorkspaceAction"

export class Remote {
// Prefix is a magic string that is prepended to SSH hosts to indicate that
Expand Down Expand Up @@ -127,43 +127,8 @@ export class Remote {
this.registerLabelFormatter(remoteAuthority, this.storage.workspace.owner_name, this.storage.workspace.name),
)

const notifyWorkspacesEligibleForAutostop = () => {
const eligibleWorkspaces = this.storage.ownedWorkspaces?.filter((workspace: Workspace) => {
if (workspace.latest_build.transition !== "start" || !workspace.latest_build.deadline) {
return false
}

const hoursMilli = 1000 * 60 * 60
// return workspaces with a deadline that is in 1 hr or less
return Math.abs(new Date().getTime() - new Date(workspace.latest_build.deadline).getTime()) <= hoursMilli
})

eligibleWorkspaces?.forEach((workspace: Workspace) => {
if (this.storage.workspaceIdsEligibleForAutostop?.includes(workspace.id)) {
// don't message the user; we've already messaged
return
}
// we display individual notifications for each workspace as VS Code
// intentionally strips new lines from the message text
// https://github.com/Microsoft/vscode/issues/48900
this.vscodeProposed.window.showInformationMessage(`${workspace.name} is scheduled to shut down in 1 hour.`)
this.storage.workspaceIdsEligibleForAutostop?.push(workspace.id)
})
}

let errorCount = 0
const fetchWorkspacesInterval = setInterval(async () => {
try {
const workspacesResult = await getWorkspaces({ q: "owner:me" })
this.storage.ownedWorkspaces = workspacesResult.workspaces
notifyWorkspacesEligibleForAutostop()
} catch (error) {
if (errorCount === 3) {
clearInterval(fetchWorkspacesInterval)
}
errorCount++
}
}, 1000 * 5)
// Initialize any WorkspaceAction notifications (auto-off, upcoming deletion)
const Action = await WorkspaceAction.init(this.vscodeProposed)

let buildComplete: undefined | (() => void)
if (this.storage.workspace.latest_build.status === "stopped") {
Expand Down Expand Up @@ -466,7 +431,7 @@ export class Remote {
return {
dispose: () => {
eventSource.close()
clearInterval(fetchWorkspacesInterval)
Action.cleanupWorkspaceActions()
disposables.forEach((d) => d.dispose())
},
}
Expand Down Expand Up @@ -533,7 +498,7 @@ export class Remote {
await sshConfig.load()

let binaryPath: string | undefined
if (this.mode === vscode.ExtensionMode.Production) {
if (this.mode !== vscode.ExtensionMode.Production) {
binaryPath = await this.storage.fetchBinary()
} else {
binaryPath = path.join(os.tmpdir(), "coder")
Expand Down
2 changes: 0 additions & 2 deletions src/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ import * as vscode from "vscode"

export class Storage {
public workspace?: Workspace
public ownedWorkspaces?: Workspace[] = []
public workspaceIdsEligibleForAutostop?: string[] = []

constructor(
private readonly output: vscode.OutputChannel,
Expand Down
11 changes: 3 additions & 8 deletions src/workspacesProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,15 @@ export class WorkspaceProvider implements vscode.TreeDataProvider<vscode.TreeIte
.then((workspaces) => {
const workspacesTreeItem: WorkspaceTreeItem[] = []
workspaces.workspaces.forEach((workspace) => {
const isOwnedWorkspace = this.getWorkspacesQuery === WorkspaceQuery.Mine
if (isOwnedWorkspace) {
// update ownedWorkspaces list in storage such that we can display to the user
// notifications about their own workspaces
this.storage.ownedWorkspaces?.push(workspace)

// Show metadata for workspaces owned by the user
const showMetadata = this.getWorkspacesQuery === WorkspaceQuery.Mine
if (showMetadata) {
const agents = extractAgents(workspace)
agents.forEach((agent) => this.monitorMetadata(agent.id)) // monitor metadata for all agents
}
const treeItem = new WorkspaceTreeItem(
workspace,
this.getWorkspacesQuery === WorkspaceQuery.All,
isOwnedWorkspace,
showMetadata,
)
workspacesTreeItem.push(treeItem)
})
Expand Down