Skip to content

feat(site): display build logs on template creation #12271

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 18 commits into from
Feb 23, 2024
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
2 changes: 2 additions & 0 deletions site/jest.setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ global.TextDecoder = TextDecoder as any;
global.Blob = Blob as any;
global.scrollTo = jest.fn();

window.HTMLElement.prototype.scrollIntoView = function () {};
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
window.HTMLElement.prototype.scrollIntoView = function () {};
window.HTMLElement.prototype.scrollIntoView = jest.fn();


// Polyfill the getRandomValues that is used on utils/random.ts
Object.defineProperty(global.self, "crypto", {
value: {
Expand Down
3 changes: 3 additions & 0 deletions site/src/@types/storybook.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,8 @@ declare module "@storybook/react" {
features?: FeatureName[];
experiments?: Experiments;
queries?: { key: QueryKey; data: unknown }[];
webSocket?: {
messages: string[];
};
}
}
4 changes: 2 additions & 2 deletions site/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1543,7 +1543,7 @@ export const watchAgentMetadata = (agentId: string): EventSource => {
type WatchBuildLogsByTemplateVersionIdOptions = {
after?: number;
onMessage: (log: TypesGen.ProvisionerJobLog) => void;
onDone: () => void;
onDone?: () => void;
onError: (error: Error) => void;
};
export const watchBuildLogsByTemplateVersionId = (
Expand Down Expand Up @@ -1575,7 +1575,7 @@ export const watchBuildLogsByTemplateVersionId = (
});
socket.addEventListener("close", () => {
// When the socket closes, logs have finished streaming!
onDone();
onDone?.();
});
return socket;
};
Expand Down
22 changes: 16 additions & 6 deletions site/src/api/queries/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,16 +206,21 @@ export const createTemplate = () => {
};
};

const createTemplateFn = async (options: {
export type CreateTemplateOptions = {
organizationId: string;
version: CreateTemplateVersionRequest;
template: Omit<CreateTemplateRequest, "template_version_id">;
}) => {
onCreateVersion?: (version: TemplateVersion) => void;
onTemplateVersionChanges?: (version: TemplateVersion) => void;
};

const createTemplateFn = async (options: CreateTemplateOptions) => {
const version = await API.createTemplateVersion(
options.organizationId,
options.version,
);
await waitBuildToBeFinished(version);
options.onCreateVersion?.(version);
await waitBuildToBeFinished(version, options.onTemplateVersionChanges);
return API.createTemplate(options.organizationId, {
...options.template,
template_version_id: version.id,
Expand Down Expand Up @@ -278,12 +283,17 @@ export const previousTemplateVersion = (
};
};

const waitBuildToBeFinished = async (version: TemplateVersion) => {
const waitBuildToBeFinished = async (
version: TemplateVersion,
onRequest?: (data: TemplateVersion) => void,
) => {
let data: TemplateVersion;
let jobStatus: ProvisionerJobStatus;
let jobStatus: ProvisionerJobStatus | undefined = undefined;
do {
await delay(1000);
// When pending we want to poll more frequently
await delay(jobStatus === "pending" ? 250 : 1000);
data = await API.getTemplateVersion(version.id);
onRequest?.(data);
jobStatus = data.job.status;

if (jobStatus === "succeeded") {
Expand Down
124 changes: 72 additions & 52 deletions site/src/components/Form/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
useContext,
ReactNode,
ComponentProps,
forwardRef,
} from "react";
import { AlphaBadge, DeprecatedBadge } from "components/Badges/Badges";
import { Stack } from "components/Stack/Stack";
Expand Down Expand Up @@ -81,59 +82,49 @@ interface FormSectionProps {
deprecated?: boolean;
}

export const FormSection: FC<FormSectionProps> = ({
children,
title,
description,
classes = {},
alpha = false,
deprecated = false,
}) => {
const { direction } = useContext(FormContext);
const theme = useTheme();

return (
<div
css={{
display: "flex",
alignItems: "flex-start",
flexDirection: direction === "horizontal" ? "row" : "column",
gap: direction === "horizontal" ? 120 : 24,

[theme.breakpoints.down("md")]: {
flexDirection: "column",
gap: 16,
},
}}
className={classes.root}
>
<div
css={{
width: "100%",
maxWidth: direction === "horizontal" ? 312 : undefined,
flexShrink: 0,
position: direction === "horizontal" ? "sticky" : undefined,
top: 24,

[theme.breakpoints.down("md")]: {
width: "100%",
position: "initial" as const,
},
}}
className={classes.sectionInfo}
export const FormSection = forwardRef<HTMLDivElement, FormSectionProps>(
(
{
children,
title,
description,
classes = {},
alpha = false,
deprecated = false,
},
ref,
) => {
const { direction } = useContext(FormContext);

return (
<section
ref={ref}
css={[
styles.formSection,
direction === "horizontal" && styles.formSectionHorizontal,
]}
className={classes.root}
>
<h2 css={styles.formSectionInfoTitle} className={classes.infoTitle}>
{title}
{alpha && <AlphaBadge />}
{deprecated && <DeprecatedBadge />}
</h2>
<div css={styles.formSectionInfoDescription}>{description}</div>
</div>

{children}
</div>
);
};
<div
css={[
styles.formSectionInfo,
direction === "horizontal" && styles.formSectionInfoHorizontal,
]}
className={classes.sectionInfo}
>
<h2 css={styles.formSectionInfoTitle} className={classes.infoTitle}>
{title}
{alpha && <AlphaBadge />}
{deprecated && <DeprecatedBadge />}
</h2>
<div css={styles.formSectionInfoDescription}>{description}</div>
</div>

{children}
</section>
);
},
);

export const FormFields: FC<ComponentProps<typeof Stack>> = (props) => {
return (
Expand All @@ -147,6 +138,35 @@ export const FormFields: FC<ComponentProps<typeof Stack>> = (props) => {
};

const styles = {
formSection: (theme) => ({
display: "flex",
alignItems: "flex-start",
flexDirection: "column",
gap: 24,

[theme.breakpoints.down("md")]: {
flexDirection: "column",
gap: 16,
},
}),
formSectionHorizontal: {
flexDirection: "row",
gap: 120,
},
formSectionInfo: (theme) => ({
width: "100%",
flexShrink: 0,
top: 24,

[theme.breakpoints.down("md")]: {
width: "100%",
position: "initial" as const,
},
}),
formSectionInfoHorizontal: {
maxWidth: 312,
position: "sticky",
},
formSectionInfoTitle: (theme) => ({
fontSize: 20,
color: theme.palette.text.primary,
Expand Down
3 changes: 3 additions & 0 deletions site/src/components/FormFooter/FormFooter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ export interface FormFooterProps {
styles?: FormFooterStyles;
submitLabel?: string;
submitDisabled?: boolean;
extraActions?: React.ReactNode;
}

export const FormFooter: FC<FormFooterProps> = ({
onCancel,
extraActions,
isLoading,
submitDisabled,
submitLabel = Language.defaultSubmitLabel,
Expand Down Expand Up @@ -52,6 +54,7 @@ export const FormFooter: FC<FormFooterProps> = ({
>
{Language.cancelLabel}
</Button>
{extraActions}
</div>
);
};
Expand Down
42 changes: 42 additions & 0 deletions site/src/modules/templates/useWatchVersionLogs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { watchBuildLogsByTemplateVersionId } from "api/api";
import { ProvisionerJobLog, TemplateVersion } from "api/typesGenerated";
import { useState, useEffect } from "react";

export const useWatchVersionLogs = (
templateVersion: TemplateVersion | undefined,
options?: { onDone: () => Promise<unknown> },
) => {
const [logs, setLogs] = useState<ProvisionerJobLog[] | undefined>();
Copy link
Member

Choose a reason for hiding this comment

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

I should've been more specific, but my original issue was really more wondering why we need undefined to be a unique state from []. We could reset the state by just saying setLogs([]) and the onMessage handler wouldn't need to check if logs is defined or not, it could just be simplified to setLogs((logs) => [...logs, log]).

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I use the following:

  • undefined - connecting
  • [] - connected but empty

Wdyt? I use the same idea for fetching server data. query.data && <Loader /> and so on.

const templateVersionId = templateVersion?.id;
const templateVersionStatus = templateVersion?.job.status;

useEffect(() => {
setLogs(undefined);
}, [templateVersionId]);

useEffect(() => {
if (!templateVersionId || !templateVersionStatus) {
return;
}

if (templateVersionStatus !== "running") {
return;
}

const socket = watchBuildLogsByTemplateVersionId(templateVersionId, {
onMessage: (log) => {
setLogs((logs) => (logs ? [...logs, log] : [log]));
},
onDone: options?.onDone,
onError: (error) => {
console.error(error);
},
});

return () => {
socket.close();
};
}, [options?.onDone, templateVersionId, templateVersionStatus]);

return logs;
};
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ const styles = {
borderRadius: "0 0 8px 8px",
},

"&:first-child": {
"&:first-of-type": {
borderRadius: "8px 8px 0 0",
},
}),
Expand Down
53 changes: 53 additions & 0 deletions site/src/pages/CreateTemplatePage/BuildLogsDrawer.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { JobError } from "api/queries/templates";
import { BuildLogsDrawer } from "./BuildLogsDrawer";
import type { Meta, StoryObj } from "@storybook/react";
import {
MockProvisionerJob,
MockTemplateVersion,
MockWorkspaceBuildLogs,
} from "testHelpers/entities";
import { withWebSocket } from "testHelpers/storybook";

const meta: Meta<typeof BuildLogsDrawer> = {
title: "pages/CreateTemplatePage/BuildLogsDrawer",
component: BuildLogsDrawer,
args: {
open: true,
},
};

export default meta;
type Story = StoryObj<typeof BuildLogsDrawer>;

export const Loading: Story = {};

export const MissingVariables: Story = {
args: {
templateVersion: MockTemplateVersion,
error: new JobError(
{
...MockProvisionerJob,
error_code: "REQUIRED_TEMPLATE_VARIABLES",
},
MockTemplateVersion,
),
},
};

export const Logs: Story = {
args: {
templateVersion: {
...MockTemplateVersion,
job: {
...MockTemplateVersion.job,
status: "running",
},
},
},
decorators: [withWebSocket],
parameters: {
webSocket: {
messages: MockWorkspaceBuildLogs.map((log) => JSON.stringify(log)),
},
},
};
Loading