Skip to content

fix(UI): workspace restart button stops build before starting a new one #7301

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 7 commits into from
Apr 28, 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
PR feedback
  • Loading branch information
Kira-Pilot committed Apr 27, 2023
commit 5041d5e22765894564fda82c37c96ffad91828d3
69 changes: 52 additions & 17 deletions site/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import dayjs from "dayjs"
import * as Types from "./types"
import { DeploymentConfig } from "./types"
import * as TypesGen from "./typesGenerated"
import { delay } from "utils/delay"

// Adds 304 for the default axios validateStatus function
// https://github.com/axios/axios#handling-errors Check status here
Expand Down Expand Up @@ -476,6 +477,35 @@ export const getWorkspaceByOwnerAndName = async (
return response.data
}

export function waitForBuild(build: TypesGen.WorkspaceBuild) {
return new Promise<TypesGen.ProvisionerJob | undefined>((res, reject) => {
void (async () => {
let latestJobInfo: TypesGen.ProvisionerJob | undefined = undefined

while (
!["succeeded", "canceled"].some((status) =>
latestJobInfo?.status.includes(status),
)
) {
const { job } = await getWorkspaceBuildByNumber(
build.workspace_owner_name,
build.workspace_name,
String(build.build_number),
)
latestJobInfo = job

if (latestJobInfo.status === "failed") {
return reject(latestJobInfo)
}

await delay(1000)
}

return res(latestJobInfo)
})()
})
}

export const postWorkspaceBuild = async (
workspaceId: string,
data: TypesGen.CreateWorkspaceBuildRequest,
Expand All @@ -487,19 +517,11 @@ export const postWorkspaceBuild = async (
return response.data
}

// it is necessary to create an interface here for react query
// as startWorkspace requires multiple parameters
interface StartWorkspaceParams {
workspaceId: string
templateVersionId: string
logLevel?: TypesGen.CreateWorkspaceBuildRequest["log_level"]
}

export const startWorkspace = ({
workspaceId,
templateVersionId,
logLevel,
}: StartWorkspaceParams) =>
export const startWorkspace = (
workspaceId: string,
templateVersionId: string,
logLevel?: TypesGen.CreateWorkspaceBuildRequest["log_level"],
) =>
postWorkspaceBuild(workspaceId, {
transition: "start",
template_version_id: templateVersionId,
Expand Down Expand Up @@ -532,6 +554,22 @@ export const cancelWorkspaceBuild = async (
return response.data
}

export const restartWorkspace = async (workspace: TypesGen.Workspace) => {
const stopBuild = await stopWorkspace(workspace.id)
const awaitedStopBuild = await waitForBuild(stopBuild)

// If the restart is canceled halfway through, make sure we bail
if (awaitedStopBuild?.status === "canceled") {
return
}

const startBuild = await startWorkspace(
workspace.id,
workspace.latest_build.template_version_id,
)
await waitForBuild(startBuild)
}

export const cancelTemplateVersionBuild = async (
templateVersionId: TypesGen.TemplateVersion["id"],
): Promise<Types.Message> => {
Expand Down Expand Up @@ -963,10 +1001,7 @@ export const updateWorkspaceVersion = async (
workspace: TypesGen.Workspace,
): Promise<TypesGen.WorkspaceBuild> => {
const template = await getTemplate(workspace.template_id)
return startWorkspace({
workspaceId: workspace.id,
templateVersionId: template.active_version_id,
})
return startWorkspace(workspace.id, template.active_version_id)
}

export const getWorkspaceBuildParameters = async (
Expand Down
17 changes: 6 additions & 11 deletions site/src/pages/WorkspacePage/WorkspaceReadyPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,16 +78,11 @@ export const WorkspaceReadyPage = ({
enabled: changeVersionDialogOpen,
})

const [restartBuildError, setRestartBuildError] = useState<
Error | unknown | undefined
>(undefined)

const [isRestarting, setIsRestarting] = useState<boolean>(false)

const { mutate: restartWorkspace } = useRestartWorkspace(
setRestartBuildError,
setIsRestarting,
)
const {
mutate: restartWorkspace,
error: restartBuildError,
isLoading: isRestarting,
} = useRestartWorkspace()

// keep banner machine in sync with workspace
useEffect(() => {
Expand Down Expand Up @@ -136,7 +131,7 @@ export const WorkspaceReadyPage = ({
workspace={workspace}
handleStart={() => workspaceSend({ type: "START" })}
handleStop={() => workspaceSend({ type: "STOP" })}
handleRestart={() => restartWorkspace(workspace.id)}
handleRestart={() => restartWorkspace(workspace)}
handleDelete={() => workspaceSend({ type: "ASK_DELETE" })}
handleUpdate={() => workspaceSend({ type: "UPDATE" })}
handleCancel={() => workspaceSend({ type: "CANCEL" })}
Expand Down
64 changes: 3 additions & 61 deletions site/src/pages/WorkspacePage/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,66 +1,8 @@
import {
getWorkspaceBuildByNumber,
stopWorkspace,
startWorkspace,
} from "api/api"
import { delay } from "utils/delay"
import { ProvisionerJob, WorkspaceBuild } from "api/typesGenerated"
import { restartWorkspace } from "api/api"
import { useMutation } from "@tanstack/react-query"

export function waitForBuild(build: WorkspaceBuild) {
return new Promise((res, reject) => {
void (async () => {
let latestJobInfo: ProvisionerJob | undefined = undefined

while (latestJobInfo?.status !== "succeeded") {
const { job } = await getWorkspaceBuildByNumber(
build.workspace_owner_name,
build.workspace_name,
String(build.build_number),
)
latestJobInfo = job

if (
["failed", "canceled"].some((status) =>
latestJobInfo?.status.includes(status),
)
) {
return reject(latestJobInfo)
}

await delay(1000)
}

return res(latestJobInfo)
})()
})
}

export const useRestartWorkspace = (
setBuildError: (arg: Error | unknown | undefined) => void,
setLoading: (arg: boolean) => void,
) => {
export const useRestartWorkspace = () => {
return useMutation({
mutationFn: stopWorkspace,
onMutate: () => setLoading(true),
onSuccess: async (data: WorkspaceBuild) => {
try {
await waitForBuild(data)
const startBuild = await startWorkspace({
workspaceId: data.workspace_id,
templateVersionId: data.template_version_id,
})
await waitForBuild(startBuild)

setLoading(false)
} catch (error) {
if ((error as WorkspaceBuild).status === "canceled") {
setLoading(false)
return
}
setBuildError(error)
setLoading(false)
}
},
mutationFn: restartWorkspace,
})
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Originally, I wanted to use an implementation closer to the following, which react query's docs suggest is possible:

 const requestStopWorkspace = useMutation({ mutationFn: stopWorkspace })
 const requestStartWorkspace = useMutation({ mutationFn: startWorkspace })

  const restartWorkspace = async () => {
    try {
      await requestStopWorkspace.mutateAsync(workspace.id)
      await waitForStop(requestStopWorkspace.data)
      await requestStartWorkspace.mutateAsync({
        workspaceId,
        templateVersionId,
      })
    } catch (error) {
      ...   
    }
  }

but mutateAsync does not seem to be working and the queries are not treated asynchronously. @BrunoQuaresma is this something you've run into before?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I put a comment above, I think you don't need to have each API call into a "query". You can have a single function to restart the workspace and wrap this function into a query.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmmm that's a good idea. Let me try it!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@BrunoQuaresma Woo that's a lot better! Thanks!

11 changes: 5 additions & 6 deletions site/src/xServices/workspace/workspaceXService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -779,12 +779,11 @@ export const workspaceMachine = createMachine(
},
startWorkspace: (context) => async (send) => {
if (context.workspace) {
const startWorkspacePromise = await API.startWorkspace({
workspaceId: context.workspace.id,
templateVersionId:
context.workspace.latest_build.template_version_id,
logLevel: context.createBuildLogLevel,
})
const startWorkspacePromise = await API.startWorkspace(
context.workspace.id,
context.workspace.latest_build.template_version_id,
context.createBuildLogLevel,
)
send({ type: "REFRESH_TIMELINE" })
return startWorkspacePromise
} else {
Expand Down