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 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
51 changes: 49 additions & 2 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 @@ -489,12 +519,12 @@ export const postWorkspaceBuild = async (

export const startWorkspace = (
workspaceId: string,
templateVersionID: string,
templateVersionId: string,
logLevel?: TypesGen.CreateWorkspaceBuildRequest["log_level"],
) =>
postWorkspaceBuild(workspaceId, {
transition: "start",
template_version_id: templateVersionID,
template_version_id: templateVersionId,
log_level: logLevel,
})
export const stopWorkspace = (
Expand All @@ -505,6 +535,7 @@ export const stopWorkspace = (
transition: "stop",
log_level: logLevel,
})

export const deleteWorkspace = (
workspaceId: string,
logLevel?: TypesGen.CreateWorkspaceBuildRequest["log_level"],
Expand All @@ -523,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
6 changes: 6 additions & 0 deletions site/src/components/Workspace/Workspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,14 @@ export interface WorkspaceProps {
}
handleStart: () => void
handleStop: () => void
handleRestart: () => void
handleDelete: () => void
handleUpdate: () => void
handleCancel: () => void
handleSettings: () => void
handleChangeVersion: () => void
isUpdating: boolean
isRestarting: boolean
workspace: TypesGen.Workspace
resources?: TypesGen.WorkspaceResource[]
builds?: TypesGen.WorkspaceBuild[]
Expand All @@ -72,13 +74,15 @@ export const Workspace: FC<React.PropsWithChildren<WorkspaceProps>> = ({
scheduleProps,
handleStart,
handleStop,
handleRestart,
handleDelete,
handleUpdate,
handleCancel,
handleSettings,
handleChangeVersion,
workspace,
isUpdating,
isRestarting,
resources,
builds,
canUpdateWorkspace,
Expand Down Expand Up @@ -132,13 +136,15 @@ export const Workspace: FC<React.PropsWithChildren<WorkspaceProps>> = ({
isOutdated={workspace.outdated}
handleStart={handleStart}
handleStop={handleStop}
handleRestart={handleRestart}
handleDelete={handleDelete}
handleUpdate={handleUpdate}
handleCancel={handleCancel}
handleSettings={handleSettings}
handleChangeVersion={handleChangeVersion}
canChangeVersions={canChangeVersions}
isUpdating={isUpdating}
isRestarting={isRestarting}
/>
</Stack>
}
Expand Down
33 changes: 26 additions & 7 deletions site/src/components/WorkspaceActions/Buttons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,17 @@ import BlockIcon from "@material-ui/icons/Block"
import CloudQueueIcon from "@material-ui/icons/CloudQueue"
import CropSquareIcon from "@material-ui/icons/CropSquare"
import PlayCircleOutlineIcon from "@material-ui/icons/PlayCircleOutline"
import ReplayIcon from "@material-ui/icons/Replay"
import { LoadingButton } from "components/LoadingButton/LoadingButton"
import { FC } from "react"
import { FC, PropsWithChildren } from "react"
import { useTranslation } from "react-i18next"
import { makeStyles } from "@material-ui/core/styles"

interface WorkspaceAction {
handleAction: () => void
}

export const UpdateButton: FC<React.PropsWithChildren<WorkspaceAction>> = ({
export const UpdateButton: FC<PropsWithChildren<WorkspaceAction>> = ({
handleAction,
}) => {
const { t } = useTranslation("workspacePage")
Expand All @@ -30,7 +31,7 @@ export const UpdateButton: FC<React.PropsWithChildren<WorkspaceAction>> = ({
)
}

export const StartButton: FC<React.PropsWithChildren<WorkspaceAction>> = ({
export const StartButton: FC<PropsWithChildren<WorkspaceAction>> = ({
handleAction,
}) => {
const { t } = useTranslation("workspacePage")
Expand All @@ -48,7 +49,7 @@ export const StartButton: FC<React.PropsWithChildren<WorkspaceAction>> = ({
)
}

export const StopButton: FC<React.PropsWithChildren<WorkspaceAction>> = ({
export const StopButton: FC<PropsWithChildren<WorkspaceAction>> = ({
handleAction,
}) => {
const { t } = useTranslation("workspacePage")
Expand All @@ -66,7 +67,25 @@ export const StopButton: FC<React.PropsWithChildren<WorkspaceAction>> = ({
)
}

export const CancelButton: FC<React.PropsWithChildren<WorkspaceAction>> = ({
export const RestartButton: FC<PropsWithChildren<WorkspaceAction>> = ({
handleAction,
}) => {
const { t } = useTranslation("workspacePage")
const styles = useStyles()

return (
<Button
variant="outlined"
startIcon={<ReplayIcon />}
onClick={handleAction}
className={styles.fixedWidth}
>
{t("actionButton.restart")}
</Button>
)
}

export const CancelButton: FC<PropsWithChildren<WorkspaceAction>> = ({
handleAction,
}) => {
return (
Expand All @@ -80,7 +99,7 @@ interface DisabledProps {
label: string
}

export const DisabledButton: FC<React.PropsWithChildren<DisabledProps>> = ({
export const DisabledButton: FC<PropsWithChildren<DisabledProps>> = ({
label,
}) => {
return (
Expand All @@ -94,7 +113,7 @@ interface LoadingProps {
label: string
}

export const ActionLoadingButton: FC<React.PropsWithChildren<LoadingProps>> = ({
export const ActionLoadingButton: FC<PropsWithChildren<LoadingProps>> = ({
label,
}) => {
const styles = useStyles()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const Template: Story<WorkspaceActionsProps> = (args) => (
const defaultArgs = {
handleStart: action("start"),
handleStop: action("stop"),
handleRestart: action("restart"),
handleDelete: action("delete"),
handleUpdate: action("update"),
handleCancel: action("cancel"),
Expand Down
20 changes: 18 additions & 2 deletions site/src/components/WorkspaceActions/WorkspaceActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ import { makeStyles } from "@material-ui/core/styles"
import MoreVertOutlined from "@material-ui/icons/MoreVertOutlined"
import { FC, ReactNode, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { WorkspaceStatus } from "../../api/typesGenerated"
import { WorkspaceStatus } from "api/typesGenerated"
import {
ActionLoadingButton,
CancelButton,
DisabledButton,
StartButton,
StopButton,
RestartButton,
UpdateButton,
} from "./Buttons"
import {
Expand All @@ -28,12 +29,14 @@ export interface WorkspaceActionsProps {
isOutdated: boolean
handleStart: () => void
handleStop: () => void
handleRestart: () => void
handleDelete: () => void
handleUpdate: () => void
handleCancel: () => void
handleSettings: () => void
handleChangeVersion: () => void
isUpdating: boolean
isRestarting: boolean
children?: ReactNode
canChangeVersions: boolean
}
Expand All @@ -43,12 +46,14 @@ export const WorkspaceActions: FC<WorkspaceActionsProps> = ({
isOutdated,
handleStart,
handleStop,
handleRestart,
handleDelete,
handleUpdate,
handleCancel,
handleSettings,
handleChangeVersion,
isUpdating,
isRestarting,
canChangeVersions,
}) => {
const styles = useStyles()
Expand Down Expand Up @@ -91,6 +96,13 @@ export const WorkspaceActions: FC<WorkspaceActionsProps> = ({
key={ButtonTypesEnum.stopping}
/>
),
[ButtonTypesEnum.restart]: <RestartButton handleAction={handleRestart} />,
[ButtonTypesEnum.restarting]: (
<ActionLoadingButton
label="Restarting"
key={ButtonTypesEnum.restarting}
/>
),
[ButtonTypesEnum.deleting]: (
<ActionLoadingButton
label={t("actionButton.deleting")}
Expand Down Expand Up @@ -129,7 +141,11 @@ export const WorkspaceActions: FC<WorkspaceActionsProps> = ({
(isUpdating
? buttonMapping[ButtonTypesEnum.updating]
: buttonMapping[ButtonTypesEnum.update])}
{actionsByStatus.map((action) => buttonMapping[action])}
{isRestarting && buttonMapping[ButtonTypesEnum.restarting]}
{!isRestarting &&
actionsByStatus.map((action) => (
<span key={action}>{buttonMapping[action]}</span>
))}
{canCancel && <CancelButton handleAction={handleCancel} />}
<div>
<Button
Expand Down
4 changes: 3 additions & 1 deletion site/src/components/WorkspaceActions/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ export enum ButtonTypesEnum {
starting = "starting",
stop = "stop",
stopping = "stopping",
restart = "restart",
restarting = "restarting",
deleting = "deleting",
update = "update",
updating = "updating",
Expand Down Expand Up @@ -39,7 +41,7 @@ const statusToActions: Record<WorkspaceStatus, WorkspaceAbilities> = {
canAcceptJobs: false,
},
running: {
actions: [ButtonTypesEnum.stop],
actions: [ButtonTypesEnum.stop, ButtonTypesEnum.restart],
canCancel: false,
canAcceptJobs: true,
},
Expand Down
1 change: 1 addition & 0 deletions site/src/i18n/en/workspacePage.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"actionButton": {
"start": "Start",
"stop": "Stop",
"restart": "Restart",
"delete": "Delete",
"cancel": "Cancel",
"update": "Update",
Expand Down
11 changes: 11 additions & 0 deletions site/src/pages/WorkspacePage/WorkspacePage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,17 @@ describe("WorkspacePage", () => {
)
})

it("requests a stop when the user presses Restart", async () => {
const stopWorkspaceMock = jest
.spyOn(api, "stopWorkspace")
.mockResolvedValueOnce(MockWorkspaceBuild)

await testButton("Restart", stopWorkspaceMock)

const button = await screen.findByText("Restarting")
expect(button).toBeInTheDocument()
})

it("requests cancellation when the user presses Cancel", async () => {
server.use(
rest.get(
Expand Down
11 changes: 10 additions & 1 deletion site/src/pages/WorkspacePage/WorkspaceReadyPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { UpdateBuildParametersDialog } from "./UpdateBuildParametersDialog"
import { ChangeVersionDialog } from "./ChangeVersionDialog"
import { useQuery } from "@tanstack/react-query"
import { getTemplateVersions } from "api/api"
import { useRestartWorkspace } from "./hooks"

interface WorkspaceReadyPageProps {
workspaceState: StateFrom<typeof workspaceMachine>
Expand Down Expand Up @@ -77,6 +78,12 @@ export const WorkspaceReadyPage = ({
enabled: changeVersionDialogOpen,
})

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

// keep banner machine in sync with workspace
useEffect(() => {
bannerSend({ type: "REFRESH_WORKSPACE", workspace })
Expand Down Expand Up @@ -120,9 +127,11 @@ export const WorkspaceReadyPage = ({
),
}}
isUpdating={workspaceState.matches("ready.build.requestingUpdate")}
isRestarting={isRestarting}
workspace={workspace}
handleStart={() => workspaceSend({ type: "START" })}
handleStop={() => workspaceSend({ type: "STOP" })}
handleRestart={() => restartWorkspace(workspace)}
handleDelete={() => workspaceSend({ type: "ASK_DELETE" })}
handleUpdate={() => workspaceSend({ type: "UPDATE" })}
handleCancel={() => workspaceSend({ type: "CANCEL" })}
Expand All @@ -140,7 +149,7 @@ export const WorkspaceReadyPage = ({
hideVSCodeDesktopButton={featureVisibility["browser_only"]}
workspaceErrors={{
[WorkspaceErrors.GET_BUILDS_ERROR]: getBuildsError,
[WorkspaceErrors.BUILD_ERROR]: buildError,
[WorkspaceErrors.BUILD_ERROR]: buildError || restartBuildError,
[WorkspaceErrors.CANCELLATION_ERROR]: cancellationError,
}}
buildInfo={buildInfo}
Expand Down
8 changes: 8 additions & 0 deletions site/src/pages/WorkspacePage/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { restartWorkspace } from "api/api"
import { useMutation } from "@tanstack/react-query"

export const useRestartWorkspace = () => {
return useMutation({
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!