diff --git a/apps/builder/app/builder/features/publish/diagnostics-utils.ts b/apps/builder/app/builder/features/publish/diagnostics-utils.ts new file mode 100644 index 0000000000..dac05b91a6 --- /dev/null +++ b/apps/builder/app/builder/features/publish/diagnostics-utils.ts @@ -0,0 +1,86 @@ +import type { PublishValidationFinding } from "./diagnostics"; +import type { PublishLog } from "./use-publish-logs"; +import { publishLogStatus } from "./constants"; + +export const getDiagnosticsReport = ({ + findings, + items, + canViewPublishLogs, + includeLatestPublishFindings = true, +}: { + findings: PublishValidationFinding[]; + items: PublishLog[]; + canViewPublishLogs: boolean; + includeLatestPublishFindings?: boolean; +}) => { + const latestPublish = includeLatestPublishFindings ? items[0] : undefined; + const reportFindings = [ + ...findings, + ...(latestPublish?.findings ?? []), + ...(latestPublish?.target === "static" && latestPublish.status === "failed" + ? [ + { + severity: "error" as const, + source: "publish" as const, + buildId: latestPublish.buildId, + title: publishLogStatus.failed.text, + reportText: publishLogStatus.failed.text, + }, + ] + : []), + ...(canViewPublishLogs + ? (latestPublish?.issues?.map((issue) => ({ + severity: issue.severity, + source: "build" as const, + title: issue.message, + reportText: `${issue.severity.toUpperCase()}: ${issue.message}`, + })) ?? []) + : []), + ].filter( + (finding, index, all) => + all.findIndex( + (other) => + other.source === finding.source && + other.buildId === finding.buildId && + other.reportText === finding.reportText + ) === index + ); + const findingTabs = [ + { + value: "warnings" as const, + label: "Warnings", + findings: reportFindings.filter(({ severity }) => severity === "warning"), + }, + { + value: "errors" as const, + label: "Errors", + findings: reportFindings.filter(({ severity }) => severity === "error"), + }, + ]; + const populatedTabs = findingTabs.filter( + ({ findings }) => findings.length > 0 + ); + const orderedItems = [...items].reverse(); + const reportText = reportFindings + .map(({ reportText }) => reportText) + .join("\n\n"); + const publishText = orderedItems + .filter( + (item) => item.logState === "available" && item.logText !== undefined + ) + .map((item) => + [ + ...(item.domains.length > 0 ? item.domains : ["Static export"]), + item.logText, + ].join("\n") + ) + .join("\n\n"); + return { + findings: reportFindings, + tabs: populatedTabs, + publishes: orderedItems, + reportText, + publishText, + issuesOmitted: latestPublish?.issuesOmitted, + }; +}; diff --git a/apps/builder/app/builder/features/publish/diagnostics.test.tsx b/apps/builder/app/builder/features/publish/diagnostics.test.tsx index 1b583e38f5..cc54cbf115 100644 --- a/apps/builder/app/builder/features/publish/diagnostics.test.tsx +++ b/apps/builder/app/builder/features/publish/diagnostics.test.tsx @@ -68,6 +68,45 @@ const openDetails = (element: HTMLElement) => { act(() => button?.click()); }; +test("keeps audit and build findings in severity tabs, not in publish logs", async () => { + render( + [], + true, + [ + { + buildId: "build-separated", + target: "site", + domains: ["example.com"], + status: "failed", + findings: [createFinding("warning", 42)], + issues: [{ severity: "error", message: "build-issue-42" }], + logState: "available", + logText: "runner-output-42", + }, + ], + undefined, + true + ); + const tabs = Array.from( + document.body.querySelectorAll('[role="tab"]') + ); + expect(tabs).toHaveLength(3); + const publishTab = tabs.find((tab) => tab.textContent === "Publish")!; + await act(async () => userEvent.click(publishTab)); + const active = document.body.querySelector( + '[role="tabpanel"][data-state="active"]' + )!; + expect(active.textContent).toContain("runner-output-42"); + expect(active.textContent).not.toContain("warning-42"); + expect(active.textContent).not.toContain("build-issue-42"); + const warningsTab = tabs.find((tab) => tab.textContent === "Warnings")!; + await act(async () => userEvent.click(warningsTab)); + expect(document.body.textContent).toContain("warning-42"); + const errorsTab = tabs.find((tab) => tab.textContent === "Errors")!; + await act(async () => userEvent.click(errorsTab)); + expect(document.body.textContent).toContain("build-issue-42"); +}); + test.each(["findings", "details", "publish"] as const)( "scrolls overflowing %s with the native scroll container", async (view) => { @@ -455,6 +494,14 @@ test("collapses each complete publish and copies its full log from the header", await act(async () => userEvent.click(copyButtons[0]!)); expect(writeText).toHaveBeenCalledWith("Complete second publish log"); expect(triggers[0]?.getAttribute("aria-expanded")).toBe("true"); + const keyboardCopy = document.body.querySelector( + 'button[aria-label="Copy log"]' + )!; + expect(keyboardCopy.parentElement?.closest("button")).toBeNull(); + act(() => keyboardCopy.focus()); + await act(async () => userEvent.keyboard("{Enter}")); + expect(writeText).toHaveBeenCalledTimes(2); + expect(triggers[0]?.getAttribute("aria-expanded")).toBe("true"); }); test("can maximize Diagnostics and aligns publish content with its title", async () => { @@ -513,6 +560,7 @@ test("publish failure is plain text and links to the Publish tab", async () => { severity: "error", source: "publish", title: "Build failed before deployment", + buildId: "build-1", summary: "Build failed before deployment", reportText: "Build failed before deployment", }, @@ -561,6 +609,7 @@ test("Free publish failures link to a Publish upgrade banner without exposing lo severity: "error", source: "publish", title: "Publish failed", + buildId: "build-1", reportText: "Publish failed", }, ], @@ -665,6 +714,45 @@ test("pre-dispatch failure has no link to an absent Publish tab", () => { ).toBe(false); }); +test.each([true, false])( + "pre-dispatch failure does not link an older publish (paid: %s)", + (paid) => { + render( + [ + { + severity: "error", + source: "publish", + title: "new-request-rejection", + reportText: "new-request-rejection", + }, + ], + paid, + [ + { + buildId: "old-build", + target: "site", + domains: ["example.com"], + status: "success", + findings: [], + logState: "available", + logText: "old-output", + }, + ], + undefined, + true + ); + expect( + document.body.querySelector('[role="tab"][aria-selected="true"]') + ?.textContent + ).toBe("Errors"); + expect( + Array.from(document.body.querySelectorAll("button")).some( + (button) => button.textContent === "show logs" + ) + ).toBe(false); + } +); + test("Free audit summaries do not expose long cached details", () => { const longSummary = `Short reason ${"private context ".repeat(30)}`; const element = render( diff --git a/apps/builder/app/builder/features/publish/diagnostics.tsx b/apps/builder/app/builder/features/publish/diagnostics.tsx index 0aa364d5c5..b02eac16b1 100644 --- a/apps/builder/app/builder/features/publish/diagnostics.tsx +++ b/apps/builder/app/builder/features/publish/diagnostics.tsx @@ -1,3 +1,4 @@ +import { getDiagnosticsReport } from "./diagnostics-utils"; import { Fragment, useEffect, useState, type ReactNode } from "react"; import { Button, @@ -38,6 +39,7 @@ export type PublishValidationFinding = { link?: ReactNode; relatedInstanceId?: string; reportText: string; + buildId?: string; }; const shortFinding = (finding: PublishValidationFinding) => @@ -96,11 +98,15 @@ const FindingList = ({ canViewPublishLogs, onSelect, onOpenPublish, + issuesOmitted = 0, + publishBuildIds, }: { findings: PublishValidationFinding[]; canViewPublishLogs: boolean; onSelect: (finding: PublishValidationFinding) => void; onOpenPublish?: () => void; + issuesOmitted?: number; + publishBuildIds: string[]; }) => ( @@ -115,22 +121,24 @@ const FindingList = ({ {finding.source === "publish" ? ( {canViewPublishLogs ? finding.title : shortFinding(finding)} - {onOpenPublish !== undefined && ( - <> - {" "} - - show logs - - - )} + {onOpenPublish !== undefined && + finding.buildId !== undefined && + publishBuildIds.includes(finding.buildId) && ( + <> + {" "} + + show logs + + + )} ) : canViewPublishLogs ? ( + + {finding.title} + + {finding.details !== undefined && ( + + {finding.details} + + )} +
{ + if ( + event.button !== 0 || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey + ) { + return; + } + onNavigate(); + }} + > + {finding.link} +
+
+); + +const PublishHistoryEntry = ({ + item, + defaultOpen, + canViewPublishLogs, +}: { + item: PublishLog; + defaultOpen: boolean; + canViewPublishLogs: boolean; +}) => { + const duration = getPublishDuration(item); + return ( + + + + } + suffix={ + canViewPublishLogs && + item.logState === "available" && + item.logText !== undefined && ( + + event.stopPropagation()} + > + + + + ) + } + > + + {item.domains.length > 0 + ? item.domains.join(", ") + : "Static export"} + + + + + + {publishLogStatus[item.status].text} + {canViewPublishLogs && item.startedAt !== undefined && ( + Started: {new Date(item.startedAt).toLocaleString()} + )} + {canViewPublishLogs && duration !== undefined && ( + Duration: {duration}s + )} + {canViewPublishLogs && + item.status === "failed" && + (item.failedStage !== undefined || item.code !== undefined) && ( + + {[item.failedStage, item.code?.replaceAll("_", " ")] + .filter(Boolean) + .join(" · ")} + + )} + {canViewPublishLogs && + item.status !== "pending" && + (item.logState === "available" ? ( + + {item.logText} + + ) : ( + + {item.logHandle === undefined || + item.logState === "unavailable" + ? "Publish logs are unavailable." + : "Loading logs…"} + + ))} + + + + + + ); +}; + +const PublishHistory = ({ + items, + canViewPublishLogs, + onLoadLog, +}: { + items: PublishLog[]; + canViewPublishLogs: boolean; + onLoadLog?: (item: PublishLog) => void; +}) => { + useEffect(() => { + if (!canViewPublishLogs) { + return; + } + for (const item of items) { + if ( + item.status !== "pending" && + item.logHandle !== undefined && + item.logState === undefined + ) { + onLoadLog?.(item); + } + } + }, [canViewPublishLogs, items, onLoadLog]); + return ( + + + {!canViewPublishLogs && ( + + Upgrade to Pro to view publish logs. + + )} + {items.length === 0 && ( + No publishes in this session. + )} + {items.map((item, index) => ( + + ))} + + + ); +}; + export const PublishDiagnosticsDialog = ({ findings, open, @@ -161,6 +364,7 @@ export const PublishDiagnosticsDialog = ({ initialTab, items = [], canViewPublishLogs = true, + includeLatestPublishFindings = true, onLoadLog, }: { findings: PublishValidationFinding[]; @@ -170,6 +374,7 @@ export const PublishDiagnosticsDialog = ({ initialTab?: "warnings" | "errors" | "publish"; items?: PublishLog[]; canViewPublishLogs?: boolean; + includeLatestPublishFindings?: boolean; onLoadLog?: (item: PublishLog) => void; }) => { const [internalOpen, setInternalOpen] = useState(false); @@ -177,33 +382,29 @@ export const PublishDiagnosticsDialog = ({ useState(); const isOpen = open ?? internalOpen; const setIsOpen = onOpenChange ?? setInternalOpen; - const errors = findings.filter(({ severity }) => severity === "error"); - const warnings = findings.filter(({ severity }) => severity === "warning"); - const defaultTab = initialTab ?? (errors.length > 0 ? "errors" : "warnings"); + + const { + findings: reportFindings, + tabs, + publishes: orderedItems, + reportText, + publishText, + issuesOmitted, + } = getDiagnosticsReport({ + findings, + items, + canViewPublishLogs, + includeLatestPublishFindings, + }); + const defaultTab = initialTab ?? tabs.at(-1)?.value ?? "publish"; const [tab, setTab] = useState(defaultTab); - const orderedItems = [...items].reverse(); + const activeTab = - (tab === "warnings" && warnings.length > 0) || - (tab === "errors" && errors.length > 0) || - (tab === "publish" && items.length > 0) + (tab === "publish" && items.length > 0) || + tabs.some(({ value }) => value === tab) ? tab - : errors.length > 0 - ? "errors" - : warnings.length > 0 - ? "warnings" - : "publish"; - const reportText = findings.map(({ reportText }) => reportText).join("\n\n"); - const publishText = orderedItems - .filter( - (item) => item.logState === "available" && item.logText !== undefined - ) - .map((item) => - [ - ...(item.domains.length > 0 ? item.domains : ["Static export"]), - item.logText, - ].join("\n") - ) - .join("\n\n"); + : (tabs.at(-1)?.value ?? "publish"); + const copyText = activeTab === "publish" ? publishText : reportText; useEffect(() => { @@ -217,22 +418,7 @@ export const PublishDiagnosticsDialog = ({ } }, [canViewPublishLogs]); - useEffect(() => { - if (isOpen === false || activeTab !== "publish" || !canViewPublishLogs) { - return; - } - for (const item of items) { - if ( - item.status !== "pending" && - item.logHandle !== undefined && - item.logState === undefined - ) { - onLoadLog?.(item); - } - } - }, [activeTab, canViewPublishLogs, isOpen, items, onLoadLog]); - - if (open === undefined && findings.length === 0) { + if (open === undefined && reportFindings.length === 0 && items.length === 0) { return null; } @@ -240,7 +426,7 @@ export const PublishDiagnosticsDialog = ({ <> {open === undefined && ( setIsOpen(true)} /> )} @@ -274,46 +460,11 @@ export const PublishDiagnosticsDialog = ({ Diagnostics {selectedFinding !== undefined && canViewPublishLogs ? ( - - - - {selectedFinding.title} - - {selectedFinding.details !== undefined && ( - - - {selectedFinding.details} - - - )} -
{ - if ( - event.button !== 0 || - event.metaKey || - event.ctrlKey || - event.shiftKey || - event.altKey - ) { - return; - } - setIsOpen(false); - }} - > - {selectedFinding.link} -
-
+ setSelectedFinding(undefined)} + onNavigate={() => setIsOpen(false)} + /> ) : ( - {warnings.length > 0 && ( - Warnings - )} - {errors.length > 0 && ( - Errors - )} + {tabs.map(({ value, label }) => ( + + {label} + + ))} {items.length > 0 && ( Publish )} - - 0 ? () => setTab("publish") : undefined - } - /> - - - 0 ? () => setTab("publish") : undefined - } - /> - + {tabs.map(({ value, findings }) => ( + + buildId)} + onSelect={setSelectedFinding} + onOpenPublish={ + items.length > 0 ? () => setTab("publish") : undefined + } + /> + + ))} - - - {!canViewPublishLogs && ( - - Upgrade to Pro to view publish logs. - - )} - {items.length === 0 && ( - No publishes in this session. - )} - {orderedItems.map((item, index) => { - const duration = getPublishDuration(item); - return ( - - - - } - suffix={ - canViewPublishLogs && - item.logState === "available" && - item.logText !== undefined && ( - - - event.stopPropagation() - } - > - - - - ) - } - > - - {item.domains.length > 0 - ? item.domains.join(", ") - : "Static export"} - - - - - - - {publishLogStatus[item.status].text} - - {canViewPublishLogs && - item.startedAt !== undefined && ( - - Started:{" "} - {new Date( - item.startedAt - ).toLocaleString()} - - )} - {canViewPublishLogs && - duration !== undefined && ( - Duration: {duration}s - )} - {canViewPublishLogs && - item.status === "failed" && - (item.failedStage !== undefined || - item.code !== undefined) && ( - - {[ - item.failedStage, - item.code?.replaceAll("_", " "), - ] - .filter(Boolean) - .join(" · ")} - - )} - {canViewPublishLogs && - item.status !== "pending" && - (item.logState === "available" ? ( - - {item.logText} - - ) : ( - - {item.logHandle === undefined || - item.logState === "unavailable" - ? "Publish logs are unavailable." - : "Loading logs…"} - - ))} - {item.findings.length > 0 && ( - - Audit - {item.findings.map((finding, index) => ( - - {canViewPublishLogs - ? (finding.summary ?? finding.title) - : shortFinding(finding)} - - ))} - - )} - {canViewPublishLogs && - item.issues !== undefined && - item.issues.length > 0 && ( - Build - )} - {canViewPublishLogs && - item.issues?.map((issue, index) => ( - - {issue.message} - - ))} - {canViewPublishLogs && - (item.issuesOmitted ?? 0) > 0 && ( - - {item.issuesOmitted} more issues not - shown. - - )} - - - - - - ); - })} - - + )} diff --git a/apps/builder/app/builder/features/publish/domain-publish-status.tsx b/apps/builder/app/builder/features/publish/domain-publish-status.tsx new file mode 100644 index 0000000000..86dbc311e3 --- /dev/null +++ b/apps/builder/app/builder/features/publish/domain-publish-status.tsx @@ -0,0 +1,39 @@ +import type { ReactNode } from "react"; +import { IconButton, Tooltip } from "@webstudio-is/design-system"; +import type { AlertIcon } from "@webstudio-is/icons"; +import { publishLogStatus } from "./constants"; +import type { PublishLog } from "./use-publish-logs"; + +export const DomainPublishStatus = ({ + domain, + buildId, + latestLog, + fallback, + onOpenReport, +}: { + domain: string; + buildId?: string; + latestLog?: Pick; + fallback: { Icon: typeof AlertIcon; color: string; text: ReactNode }; + onOpenReport?: () => void; +}) => { + const currentLog = latestLog?.buildId === buildId ? latestLog : undefined; + const { Icon, color, text } = + currentLog === undefined ? fallback : publishLogStatus[currentLog.status]; + return ( + + { + event.preventDefault(); + event.stopPropagation(); + onOpenReport?.(); + }} + > + + + + ); +}; diff --git a/apps/builder/app/builder/features/publish/domains.test.tsx b/apps/builder/app/builder/features/publish/domains.test.tsx index b4d29a9fd8..a24f451209 100644 --- a/apps/builder/app/builder/features/publish/domains.test.tsx +++ b/apps/builder/app/builder/features/publish/domains.test.tsx @@ -1,8 +1,10 @@ import { act } from "react-dom/test-utils"; import { createRoot, type Root } from "react-dom/client"; -import { afterEach, expect, test } from "vitest"; +import { afterEach, expect, test, vi } from "vitest"; import { TooltipProvider } from "@webstudio-is/design-system"; -import { __testing__, PENDING_TIMEOUT, type Domain } from "./domains"; +import { __testing__, type Domain } from "./domains"; +import { PENDING_TIMEOUT } from "./publish-status"; +import type { PublishLog } from "./use-publish-logs"; const { StatusIcon } = __testing__; let root: Root | undefined; @@ -21,8 +23,19 @@ afterEach(() => { const renderStatus = ( publishStatus: "PENDING" | "PUBLISHED" | "FAILED" | undefined, - age = 0, - isLoading = false + { + age = 0, + isLoading = false, + latestLog, + onOpenReport, + onSectionClick, + }: { + age?: number; + isLoading?: boolean; + latestLog?: PublishLog; + onOpenReport?: (domain: string) => void; + onSectionClick?: () => void; + } = {} ) => { if (container === undefined) { container = document.createElement("div"); @@ -34,21 +47,30 @@ const renderStatus = ( root = createRoot(container); } const projectDomain = { + domain: "example.com", status: "ACTIVE", verified: true, latestBuildVirtual: publishStatus === undefined ? null : { + buildId: "current-build", publishStatus, createdAt: new Date(Date.now() - age).toISOString(), }, } as Domain; act(() => root?.render( - - - +
+ + + +
) ); const icon = container.querySelector("svg"); @@ -69,8 +91,10 @@ test.each([ test("keeps status loading neutral and expired publishing red", () => { expect(renderStatus("PENDING")).toBe("rgb(200, 160, 0)"); - expect(renderStatus("PENDING", 0, true)).toBe("rgb(100, 100, 100)"); - expect(renderStatus("PENDING", PENDING_TIMEOUT + 1000)).toBe( + expect(renderStatus("PENDING", { isLoading: true })).toBe( + "rgb(100, 100, 100)" + ); + expect(renderStatus("PENDING", { age: PENDING_TIMEOUT + 1000 })).toBe( "rgb(200, 0, 0)" ); }); @@ -78,3 +102,54 @@ test("keeps status loading neutral and expired publishing red", () => { test("does not show success for a domain that has never been published", () => { expect(renderStatus(undefined)).toBe("rgb(100, 100, 100)"); }); + +test.each([ + ["pending", "rgb(200, 160, 0)"], + ["failed", "rgb(200, 0, 0)"], + ["success", "rgb(0, 160, 0)"], +] as const)( + "uses the matching %s session log instead of the persisted status", + (status, color) => { + expect( + renderStatus(status === "failed" ? "PUBLISHED" : "PENDING", { + age: PENDING_TIMEOUT + 1000, + latestLog: { + buildId: "current-build", + target: "site", + domains: ["example.com"], + findings: [], + status, + }, + }) + ).toBe(color); + } +); + +test("ignores a log for a different domain build", () => { + expect( + renderStatus("PUBLISHED", { + latestLog: { + buildId: "old-build", + target: "site", + domains: ["example.com"], + findings: [], + status: "failed", + }, + }) + ).toBe("rgb(0, 160, 0)"); +}); + +test("opening a domain report does not toggle the surrounding section", () => { + const onOpenReport = vi.fn(); + const onSectionClick = vi.fn(); + renderStatus("PUBLISHED", { onOpenReport, onSectionClick }); + const event = new MouseEvent("click", { bubbles: true, cancelable: true }); + act(() => + container! + .querySelector('button[aria-label="Publish log: example.com"]') + ?.dispatchEvent(event) + ); + expect(onOpenReport).toHaveBeenCalledExactlyOnceWith("example.com"); + expect(onSectionClick).not.toHaveBeenCalled(); + expect(event.defaultPrevented).toBe(true); +}); diff --git a/apps/builder/app/builder/features/publish/domains.tsx b/apps/builder/app/builder/features/publish/domains.tsx index a557fd6c65..01ac23721d 100644 --- a/apps/builder/app/builder/features/publish/domains.tsx +++ b/apps/builder/app/builder/features/publish/domains.tsx @@ -18,11 +18,9 @@ import { import type { Project } from "@webstudio-is/project"; import { AlertIcon, - CheckCircleIcon, CopyIcon, HelpIcon, InfoCircleIcon, - SpinnerIcon, } from "@webstudio-is/icons"; import { CollapsibleDomainSection } from "./collapsible-domain-section"; import { @@ -42,11 +40,11 @@ import { extractCname } from "./cname"; import { useEffectEvent } from "~/shared/hook-utils/effect-event"; import { DomainCheckbox } from "./domain-checkbox"; import { CopyToClipboard } from "~/shared/copy-to-clipboard"; -import { RelativeTime } from "~/builder/shared/relative-time"; +import { getPublishStatusAndText } from "./publish-status"; import { $currentSystem } from "~/shared/system"; import { getPublishUrl } from "./publish-url"; import type { PublishLog } from "./use-publish-logs"; -import { publishLogStatus } from "./constants"; +import { DomainPublishStatus } from "./domain-publish-status"; export type Domain = Project["domainsVirtual"][number]; @@ -63,54 +61,6 @@ export const getStatus = (projectDomain: Domain) => ? (`VERIFIED_${projectDomain.status}` as const) : `UNVERIFIED`; -export const PENDING_TIMEOUT = - process.env.NODE_ENV === "production" ? 60 * 3 * 1000 : 35000; - -export const getPublishStatusAndText = ({ - createdAt, - publishStatus, -}: Pick< - NonNullable, - "createdAt" | "publishStatus" ->) => { - let status = publishStatus; - - const delta = Date.now() - new Date(createdAt).getTime(); - // Assume build failed after 3 minutes - - if (publishStatus === "PENDING" && delta > PENDING_TIMEOUT) { - status = "FAILED"; - } - - const textStart = - status === "PUBLISHED" - ? "Published" - : status === "FAILED" - ? "Publish failed" - : "Publishing started"; - - const statusText = ( - <> - {textStart} - - ); - - const color = - status === "PUBLISHED" - ? cssVar("--foreground-positive") - : status === "FAILED" - ? cssVar("--foreground-negative") - : cssVar("--foreground-warning"); - const Icon = - status === "PUBLISHED" - ? CheckCircleIcon - : status === "FAILED" - ? AlertIcon - : SpinnerIcon; - - return { statusText, status, color, Icon }; -}; - const getStatusText = (props: { projectDomain: Domain; isLoading: boolean; @@ -172,28 +122,14 @@ const StatusIcon = (props: { onOpenReport?: (domain: string) => void; }) => { const fallback = getStatusText(props); - const latestLog = - props.latestLog?.buildId === props.projectDomain.latestBuildVirtual?.buildId - ? props.latestLog - : undefined; - const { Icon, color, text } = - latestLog === undefined ? fallback : publishLogStatus[latestLog.status]; - return ( - - { - event.preventDefault(); - event.stopPropagation(); - props.onOpenReport?.(props.projectDomain.domain); - }} - css={{ color }} - > - - - + props.onOpenReport?.(props.projectDomain.domain)} + /> ); }; const DomainItem = ({ diff --git a/apps/builder/app/builder/features/publish/publish-click.render.test.tsx b/apps/builder/app/builder/features/publish/publish-click.render.test.tsx index 54f043ff3a..363f97224b 100644 --- a/apps/builder/app/builder/features/publish/publish-click.render.test.tsx +++ b/apps/builder/app/builder/features/publish/publish-click.render.test.tsx @@ -9,7 +9,7 @@ import { test, vi, } from "vitest"; -import { TooltipProvider } from "@webstudio-is/design-system"; +import { TooltipProvider, toast } from "@webstudio-is/design-system"; import type { Project } from "@webstudio-is/project"; const reactEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }; @@ -27,6 +27,8 @@ let nanoStates: typeof import("~/shared/nano-states"); let builderStates: typeof import("~/builder/shared/nano-states"); const requests: Array<{ path: string; input: unknown }> = []; let publishResponse: unknown = { success: false, error: "Publish blocked" }; +let jobStatus: "failed" | "success" = "failed"; +let didPublish = false; beforeAll(async () => { Object.defineProperty(Element.prototype, "scrollIntoView", { @@ -42,19 +44,65 @@ beforeAll(async () => { requestInit?.body === undefined ? JSON.parse(url.searchParams.get("input") ?? "{}") : JSON.parse(String(requestInit.body)); - requests.push({ path: url.pathname, input }); - let data: unknown; - switch (url.pathname) { - case "/trpc/domain.publish": - data = publishResponse; - break; - case "/trpc/api.publish.getJob": - data = { status: "failed", code: "BUILD_FAILED" }; - break; - default: - throw new Error(`Unexpected request: ${url.pathname}`); - } - return new Response(JSON.stringify([{ result: { data } }]), { + const results = url.pathname + .slice("/trpc/".length) + .split(",") + .map((route, index) => { + const path = `/trpc/${route}`; + requests.push({ path, input: { "0": input[String(index)] } }); + let data: unknown; + switch (path) { + case "/trpc/domain.publish": + if (publishResponse instanceof Error) { + throw publishResponse; + } + data = publishResponse; + didPublish = (publishResponse as { success: boolean }).success; + break; + case "/trpc/api.publish.getJob": + data = { status: jobStatus, code: "BUILD_FAILED" }; + break; + case "/trpc/domain.project": + data = { + success: true, + project: { + id: "project-1", + domain: "example", + domainsVirtual: [], + latestBuildVirtual: didPublish + ? { + domain: "example", + buildId: "build-1", + createdAt: new Date().toISOString(), + publishStatus: + jobStatus === "success" ? "PUBLISHED" : "FAILED", + } + : null, + }, + }; + break; + case "/trpc/domain.countTotalDomains": + data = { success: true, data: 0 }; + break; + case "/trpc/project.userPublishCount": + data = { success: true, data: 0, limit: 100 }; + break; + default: + return { + error: { + message: `Unexpected request: ${path}`, + code: -32603, + data: { + code: "INTERNAL_SERVER_ERROR", + httpStatus: 500, + path: route, + }, + }, + }; + } + return { result: { data } }; + }); + return new Response(JSON.stringify(results), { headers: { "Content-Type": "application/json" }, }); } @@ -71,6 +119,85 @@ beforeEach(() => { reactEnvironment.IS_REACT_ACT_ENVIRONMENT = true; publishResponse = { success: false, error: "Publish blocked" }; requests.length = 0; + jobStatus = "failed"; + didPublish = false; +}); + +test("a successful site runner finishes the current publish and retains its report", async () => { + jobStatus = "success"; + publishResponse = { + success: true, + buildId: "build-1", + logHandle: "log-handle", + findings: [], + }; + stores.$project.set({ + id: "project-1", + domain: "example", + domainsVirtual: [], + latestStaticBuild: null, + } as unknown as Project); + nanoStates.$authTokenPermissions.set({ + canClone: true, + canCopy: true, + canPublish: true, + }); + builderStates.$publishDialog.set("publish"); + resetStores = () => { + stores.$project.set(undefined); + builderStates.$publishDialog.set("none"); + }; + const container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + await act(async () => + root?.render( + + + + ) + ); + const domain = document.body.querySelector( + 'input[name="domainToPublish[]"]' + )!; + if (domain.checked === false) { + await act(async () => + document.body.querySelector('[role="checkbox"]')?.click() + ); + } + const publish = Array.from( + document.body.querySelectorAll("button") + ) + .filter((button) => button.textContent === "Publish") + .at(-1)!; + await act(async () => publish.click()); + await act(async () => + vi.waitFor(() => + expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("build-1") + ) + ); + expect(requests.map(({ path }) => path)).toContain( + "/trpc/api.publish.getJob" + ); + expect(publish.disabled).toBe(false); + const report = document.body.querySelector( + 'button[aria-label^="Publish log:"]' + )!; + await act(async () => report.click()); + expect( + document.body.querySelector('[role="tab"][aria-selected="true"]') + ?.textContent + ).toBe("Publish"); + expect( + document.body.querySelector( + '[role="tabpanel"][data-state="active"] button[aria-expanded]' + ) + ).not.toBeNull(); + // The status label is the public result of a completed publish. + expect( + document.body.querySelector('[role="tabpanel"][data-state="active"]') + ?.textContent + ).toContain("Published"); }); afterEach(() => { @@ -81,6 +208,7 @@ afterEach(() => { root = undefined; resetStores = undefined; document.body.innerHTML = ""; + vi.restoreAllMocks(); }); afterAll(() => { @@ -221,15 +349,23 @@ test("keeps Diagnostics visible but disabled before there is anything to show", ).find((item) => item.textContent?.trim() === "Diagnostics"); expect(diagnostics).toBeDefined(); expect(diagnostics?.getAttribute("data-disabled")).not.toBeNull(); + expect( + requests.filter(({ path }) => path === "/trpc/project.userPublishCount") + ).toHaveLength(1); }); test.each([ - ["Validate", "Errors", false], - ["Publish", "Errors", false], - ["Publish", "Publish", true], + ["Validate", "Errors", false, false], + ["Publish", "Errors", false, false], + ["Publish", "Publish", true, false], + ["Publish", "Errors", false, true], ] as const)( "%s keeps the result in the popover until See issues opens %s", - async (action, expectedTab, accepted) => { + async (action, expectedTab, accepted, transport) => { + const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); + if (transport) { + publishResponse = new Error("transport-failure"); + } if (accepted) { publishResponse = { success: true, @@ -306,6 +442,9 @@ test.each([ } expect(builderStates.$publishDialog.get()).toBe("publish"); + if (action === "Validate" || transport) { + expect(errorToast).not.toHaveBeenCalled(); + } if (accepted) { expect(requests.map(({ path }) => path)).toContain( "/trpc/api.publish.getJob" @@ -315,6 +454,12 @@ test.each([ const seeIssues = Array.from( document.body.querySelectorAll("button") ).find((button) => button.textContent?.trim() === "See issues"); + if (transport) { + // The transport error payload must remain visible in the popover banner. + expect(seeIssues?.parentElement?.textContent).toContain( + "transport-failure" + ); + } await act(async () => seeIssues?.click()); expect(builderStates.$publishDialog.get()).toBe("none"); expect(document.body.querySelector('[role="tablist"]')).not.toBeNull(); diff --git a/apps/builder/app/builder/features/publish/publish-progress.test.tsx b/apps/builder/app/builder/features/publish/publish-progress.test.tsx index 645e2ef26d..2b966b7bb9 100644 --- a/apps/builder/app/builder/features/publish/publish-progress.test.tsx +++ b/apps/builder/app/builder/features/publish/publish-progress.test.tsx @@ -6,7 +6,7 @@ import { TooltipProvider, toast } from "@webstudio-is/design-system"; import type { Project } from "@webstudio-is/project"; import { $publishDialog } from "~/builder/shared/nano-states"; import { $project } from "~/shared/sync/data-stores"; -import { __testing__ } from "./publish"; +import { __testing__ } from "./use-publish-progress"; import { DomainCheckbox, domainToPublishName } from "./domain-checkbox"; import { PublishDiagnosticsDialog } from "./diagnostics"; @@ -563,7 +563,7 @@ test("an old poll cannot update a newly mounted copy of the same project", async expect($project.get()).toBe(reopenedProject); }); -test("publish failure shows a toast while the Publish panel is open", () => { +test("publish failure updates the banner without a duplicate toast while Publish is open", () => { const successToast = vi.spyOn(toast, "success").mockImplementation(() => ""); const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); const setPublishError = vi.fn(); @@ -585,7 +585,7 @@ test("publish failure shows a toast while the Publish panel is open", () => { }); expect(successToast).not.toHaveBeenCalled(); - expect(errorToast).toHaveBeenCalledOnce(); + expect(errorToast).not.toHaveBeenCalled(); expect(setPublishError).toHaveBeenCalledOnce(); }); @@ -648,10 +648,10 @@ test("publish completion shows a toast after the dialog closes", () => { expect(successToast).toHaveBeenCalledOnce(); expect(errorToast).toHaveBeenCalledOnce(); - expect(setPublishError).toHaveBeenCalledWith(failedStatusText); + expect(setPublishError).toHaveBeenCalledWith(failedStatusText, undefined); }); -test("a rejected publish request shows a toast while the dialog is open", async () => { +test("a rejected publish request updates the banner without a duplicate toast", async () => { const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); $publishDialog.set("publish"); $project.set({ id: "project" } as Project); @@ -683,7 +683,7 @@ test("a rejected publish request shows a toast while the dialog is open", async expect(container.querySelector("output")?.textContent).toBe( "Network unavailable" ); - expect(errorToast).toHaveBeenCalledOnce(); + expect(errorToast).not.toHaveBeenCalled(); }); test("starting validation clears a previous request failure", async () => { @@ -756,7 +756,7 @@ test("a rejected publish request shows a toast after the dialog closes", async ( ); }); -test("a rejected publish request shows a toast after the panel reopens", async () => { +test("a rejected publish request does not duplicate its banner after the panel reopens", async () => { const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); $publishDialog.set("publish"); $project.set({ id: "project" } as Project); @@ -806,7 +806,7 @@ test("a rejected publish request shows a toast after the panel reopens", async ( expect(container.querySelector("output")?.textContent).toBe( "Network unavailable" ); - expect(errorToast).toHaveBeenCalledOnce(); + expect(errorToast).not.toHaveBeenCalled(); }); test("a publish failure remains available after the panel remounts", () => { @@ -848,7 +848,7 @@ test("a publish failure remains available after the panel remounts", () => { act(() => finish.click()); expect(container.querySelector("output")?.textContent).toBe("Build failed"); - expect(errorToast).toHaveBeenCalledOnce(); + expect(errorToast).not.toHaveBeenCalled(); }); test("a successful status refresh clears a persisted publish failure", () => { @@ -1121,7 +1121,7 @@ test("publish diagnostics remain visible after the panel remounts", () => { @@ -1688,36 +666,6 @@ const useUserPublishCount = () => { }; }; -const getRefreshedProject = async ({ - projectId, - showError = true, - query = () => nativeClient.domain.project.query({ projectId }), - isCurrent = () => true, -}: { - projectId: Project["id"]; - showError?: boolean; - query?: () => ReturnType; - isCurrent?: () => boolean; -}) => { - if ($project.get()?.id !== projectId || !isCurrent()) { - return; - } - - const result = await query(); - if ($project.get()?.id !== projectId || !isCurrent()) { - return; - } - - if (result.success) { - $project.set(result.project); - return result.project; - } - - if (showError) { - toast.error(result.error); - } -}; - const refreshProject = async () => { await getRefreshedProject({ projectId: $project.get()!.id }); }; @@ -1728,10 +676,16 @@ const buttonLinkClass = css({ ...textVariants.link, }).toString(); -const UpgradeBanner = ({ hasCustomDomains }: { hasCustomDomains: boolean }) => { +const UpgradeBanner = ({ + hasCustomDomains, + quota, +}: { + hasCustomDomains: boolean; + quota: ReturnType; +}) => { const restrictedFeatures = useStore($restrictedFeatures); const { canAddDomain } = useCanAddDomain(); - const { userPublishCount, maxDailyPublishesPerUser } = useUserPublishCount(); + const { userPublishCount, maxDailyPublishesPerUser } = quota; if (userPublishCount >= maxDailyPublishesPerUser) { return ( @@ -1837,13 +791,7 @@ const UpgradeBanner = ({ hasCustomDomains }: { hasCustomDomains: boolean }) => { const Content = (props: { projectId: Project["id"]; onExportClick: () => void; - validation: ReturnType; - progress: ReturnType; - publishLogs: ReturnType; - onOpenReport: ( - domain: string | undefined, - tab: "warnings" | "errors" | "publish" - ) => void; + flow: ReturnType; }) => { const restrictedFeatures = useStore($restrictedFeatures); const [newDomains, setNewDomains] = useState(new Set()); @@ -1854,9 +802,8 @@ const Content = (props: { if (project == null) { throw new Error("Project not found"); } - const projectState = "idle"; - const { userPublishCount, maxDailyPublishesPerUser } = useUserPublishCount(); + const quota = useUserPublishCount(); const hasUnpublishedDomains = project.domainsVirtual.some( (domain) => @@ -1869,17 +816,14 @@ const Content = (props: { const hasCustomDomains = project.domainsVirtual.some( (domain) => domain.status === "ACTIVE" && domain.verified ); - const hasSitePublish = props.publishLogs.items.some( + const hasSitePublish = props.flow.logs.some( ({ target }) => target === "site" ); - const diagnosticFindings = [ - ...props.progress.manualValidationFindings.findings, - ...props.progress.publishFindings, - ]; + const diagnosticFindings = props.flow.siteFindings; const hasDiagnostics = hasSitePublish || diagnosticFindings.length > 0 || - props.progress.publishError !== undefined; + props.flow.siteError !== undefined; return ( <> @@ -1909,11 +853,11 @@ const Content = (props: { icon={} disabled={!hasDiagnostics} onSelect={() => - props.onOpenReport( + props.flow.openSiteReport( undefined, hasSitePublish ? "publish" - : props.progress.publishError !== undefined || + : props.flow.siteError !== undefined || diagnosticFindings.some( ({ severity }) => severity === "error" ) @@ -1944,11 +888,12 @@ const Content = (props: { props.onOpenReport(domain, "publish")} - latestLog={props.publishLogs.items.find( + validatedDomains={props.flow.validatedDomains} + onOpenReport={(domain) => + props.flow.openSiteReport(domain, "publish") + } + latestLog={props.flow.logs.find( (item) => item.target === "site" && item.domains.includes(project.domain) @@ -1960,9 +905,11 @@ const Content = (props: { domains={project.domainsVirtual} refresh={refreshProject} project={project} - validatedDomains={props.progress.manualValidationFindings.domains} - onOpenReport={(domain) => props.onOpenReport(domain, "publish")} - publishLogs={props.publishLogs.items} + validatedDomains={props.flow.validatedDomains} + onOpenReport={(domain) => + props.flow.openSiteReport(domain, "publish") + } + publishLogs={props.flow.logs} /> @@ -1980,7 +927,7 @@ const Content = (props: { }} /> {isAddingDomain && } - + {hasUnpublishedDomains && ( @@ -1995,14 +942,9 @@ const Content = (props: { )} @@ -2048,13 +990,7 @@ type DeployTargets = keyof typeof deployTargets; const isDeployTargets = (value: string): value is DeployTargets => Object.keys(deployTargets).includes(value); -const ExportContent = (props: { - projectId: Project["id"]; - publishLogs: ReturnType; - progress: ReturnType; - onOpenReport: (tab?: "warnings" | "errors" | "publish") => void; - onFindings: (findings: PublishValidationFinding[]) => void; -}) => { +const ExportContent = (props: { flow: ReturnType }) => { const npxCommand = "npx webstudio@latest"; const [deployTarget, setDeployTarget] = useState("docker"); @@ -2084,12 +1020,8 @@ const ExportContent = (props: { {deployTargets[deployTarget].ssgTemplates && (
@@ -2241,225 +1173,24 @@ export const PublishButton = ({ projectId }: PublishProps) => { const publishDialog = useStore($publishDialog); const authTokenPermissions = useStore($authTokenPermissions); const { allowPublishLogs = false } = useStore($planFeatures); - const publishLogs = usePublishLogs(projectId, allowPublishLogs); - const pendingLogs = useRef(publishLogs.items); - pendingLogs.current = publishLogs.items; - const { complete: completePublishLog, loadLog: loadPublishLog } = publishLogs; - const [staticFindings, setStaticFindings] = useState< - PublishValidationFinding[] - >([]); - const [selectedReport, setSelectedReport] = useState<{ - target: "static" | "site"; - domain?: string; - tab: "warnings" | "errors" | "publish"; - }>(); - useEffect(() => { - setSelectedReport(undefined); - setStaticFindings([]); - }, [projectId]); - const validation = usePublishValidationState(publishDialog); - const publishProgress = usePublishProgress(projectId); - const { - dismissCountdown, - reconcileRefreshedProject, - watchPendingPublish, - beginPopoverRefresh, - isRefreshCurrent, - } = publishProgress; - useEffect(() => { - if (publishDialog !== "publish") { - dismissCountdown(); - } - }, [publishDialog, dismissCountdown]); - useEffect(() => { - // Refresh a build that finished while the popover was closed, including - // after a publish status request failed. - if (publishDialog !== "none" && publishProgress.isPublishing === false) { - let isOpen = true; - const generation = beginPopoverRefresh(); - void refreshUntilSuccess( - async (showError) => { - const refreshedProject = await getRefreshedProject({ - projectId, - showError, - isCurrent: () => isOpen && isRefreshCurrent(generation), - }); - if ( - isOpen && - isRefreshCurrent(generation) && - refreshedProject !== undefined - ) { - reconcileRefreshedProject(refreshedProject); - } - return refreshedProject; - }, - () => isOpen, - () => { - const target = publishDialog === "export" ? "static" : "site"; - const pending = pendingLogs.current.find( - (item) => item.target === target && item.status === "pending" - ); - if (target === "static" && pending === undefined) { - return; - } - void watchPendingPublish( - () => - getRefreshedProject({ - projectId, - showError: false, - isCurrent: () => isRefreshCurrent(generation), - }), - generation, - pending === undefined - ? undefined - : { - projectId, - buildId: pending.buildId, - logHandle: pending.logHandle, - target, - }, - (result) => { - if ( - pending !== undefined && - (result?.status === "PUBLISHED" || result?.status === "FAILED") - ) { - const status = - result.status === "PUBLISHED" ? "success" : "failed"; - completePublishLog(pending.buildId, status, result.code); - loadPublishLog({ ...pending, status }); - if ( - pending.target === "static" && - status === "success" && - pending.staticName !== undefined - ) { - window.location.href = `/cgi/static/ssg/${pending.staticName}`; - } - } - } - ); - }, - () => - pendingLogs.current.some( - (item) => - item.target === - (publishDialog === "export" ? "static" : "site") && - item.status === "pending" - ) - ); - return () => { - isOpen = false; - }; - } - }, [ - projectId, - publishDialog, - publishProgress.isPublishing, - reconcileRefreshedProject, - watchPendingPublish, - beginPopoverRefresh, - isRefreshCurrent, - completePublishLog, - loadPublishLog, - ]); + const flow = usePublishFlow(projectId, allowPublishLogs, publishDialog); + const { selectedReport, closeReport, reportFindings, reportItems } = flow; const { canPublishToStagingOnly } = useStore($permissions); const isPublishEnabled = authTokenPermissions.canPublish || canPublishToStagingOnly; const tooltipContent = isPublishEnabled ? undefined : "Only the owner, an admin, or content editors with publish permissions can publish projects"; - const handleExportClick = () => { - validation.reset(); - publishProgress.dismissCountdown(); + flow.reset(); $publishDialog.set("export"); }; - const handleOpenChange = (isOpen: boolean) => { if (isOpen === false) { - validation.reset(); - publishProgress.dismissCountdown(); + flow.reset(); } $publishDialog.set(isOpen ? "publish" : "none"); }; - - const openSiteReport = ( - domain: string | undefined, - tab: "warnings" | "errors" | "publish" - ) => { - $publishDialog.set("none"); - setSelectedReport({ target: "site", domain, tab }); - }; - const openStaticReport = ( - tab: "warnings" | "errors" | "publish" = "publish" - ) => { - $publishDialog.set("none"); - setSelectedReport({ target: "static", tab }); - }; - const reportItems = selectPublishLogs( - publishLogs.items, - selectedReport?.target ?? "site", - selectedReport?.domain - ); - const latestReportItem = reportItems[0]; - const domain = selectedReport?.domain; - const showingPublish = selectedReport?.tab === "publish"; - const candidateFindings: PublishValidationFinding[] = [ - ...(selectedReport?.target === "static" - ? showingPublish - ? [] - : staticFindings - : [ - ...(!showingPublish && - (domain === undefined || - publishProgress.manualValidationFindings.domains?.includes(domain)) - ? publishProgress.manualValidationFindings.findings - : []), - ...(!showingPublish && - (domain === undefined || - publishProgress.publishDiagnosticsDomains.includes(domain)) - ? publishProgress.publishFindings - : []), - ...(publishProgress.publishError === undefined || - (domain !== undefined && - publishProgress.publishErrorDomains !== undefined && - !publishProgress.publishErrorDomains.includes(domain)) - ? [] - : [ - { - severity: "error" as const, - source: "publish" as const, - title: publishProgress.publishError, - summary: - typeof publishProgress.publishError === "string" - ? publishProgress.publishError.slice(0, 160) - : "Publish failed", - reportText: - typeof publishProgress.publishError === "string" - ? publishProgress.publishError - : "Publish failed", - }, - ]), - ]), - ...(showingPublish ? (latestReportItem?.findings ?? []) : []), - ...(showingPublish && allowPublishLogs - ? (latestReportItem?.issues?.map((issue) => ({ - severity: issue.severity, - title: issue.message, - summary: issue.message, - source: "build" as const, - reportText: `${issue.severity.toUpperCase()}: ${issue.message}`, - })) ?? []) - : []), - ]; - const reportFindings = candidateFindings.filter( - (finding, index, all) => - all.findIndex( - (other) => - other.reportText === finding.reportText && - other.source === finding.source - ) === index - ); - return ( <> { {publishDialog === "export" && ( <> Export - { - if (publishLogs.isCurrent()) { - setStaticFindings(findings); - } - }} - /> + )} @@ -2507,20 +1228,18 @@ export const PublishButton = ({ projectId }: PublishProps) => { )} { if (open === false) { - setSelectedReport(undefined); + closeReport(); } }} target={ @@ -2531,18 +1250,10 @@ export const PublishButton = ({ projectId }: PublishProps) => { initialTab={selectedReport?.tab} items={reportItems} canViewPublishLogs={allowPublishLogs} - onLoadLog={publishLogs.loadLog} + onLoadLog={flow.loadLog} /> ); }; -export const __testing__ = { - usePublishProgress, - useManualValidationFindings, - waitForPublishStatus, - refreshUntilSuccess, - getRefreshedProject, - reportPublishResult, - PublishStatic, -}; +export const __testing__ = { PublishStatic }; diff --git a/apps/builder/app/builder/features/publish/use-publish-flow.test.tsx b/apps/builder/app/builder/features/publish/use-publish-flow.test.tsx new file mode 100644 index 0000000000..cd639012f7 --- /dev/null +++ b/apps/builder/app/builder/features/publish/use-publish-flow.test.tsx @@ -0,0 +1,463 @@ +import { act } from "react-dom/test-utils"; +import { createRoot, type Root } from "react-dom/client"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + expect, + test, + vi, +} from "vitest"; +import { toast } from "@webstudio-is/design-system"; +import type { Project } from "@webstudio-is/project"; + +const deferred = () => { + let resolve!: (value: T) => void; + let reject!: (error: Error) => void; + const promise = new Promise((done, fail) => { + resolve = done; + reject = fail; + }); + return { promise, resolve, reject }; +}; +const respond = (data: unknown) => + new Response(JSON.stringify([{ result: { data } }]), { + headers: { "Content-Type": "application/json" }, + }); +let checks = deferred(); +let dispatch = deferred(); +let checkRequests = 0; +let checksRead = 0; +let publishRequests = 0; +let flowModule: typeof import("./use-publish-flow"); +let stores: typeof import("~/shared/sync/data-stores"); +let publishDialog: typeof import("~/builder/shared/nano-states").$publishDialog; +let flow: ReturnType; +let root: Root; +let container: HTMLDivElement; +let getDiagnosticsReport: typeof import("./diagnostics-utils").getDiagnosticsReport; + +const Harness = ({ paid = false }: { paid?: boolean }) => { + flow = flowModule.usePublishFlow("project", paid, "none"); + return null; +}; + +beforeAll(async () => { + ( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } + ).IS_REACT_ACT_ENVIRONMENT = true; + vi.resetModules(); + vi.stubGlobal("fetch", async (requestInfo: RequestInfo | URL) => { + const path = new URL(String(requestInfo), "http://localhost").pathname; + if (path === "/trpc/domain.publish") { + publishRequests += 1; + return dispatch.promise; + } + if (path === "/trpc/api.publish.getJob") { + return respond({ status: "failed", code: "BUILD_FAILED" }); + } + if (path === "/trpc/api.publish.getLog") { + return respond({ + availability: "available", + log: { + encoding: "base64url", + chunk: btoa("old-runner-output"), + complete: true, + issues: [{ severity: "error", message: "old-build-issue" }], + issuesOmitted: 2, + }, + }); + } + if ( + path === "/trpc/api.publish.validate" || + path === "/trpc/build.contentDatabasePublishDiagnostics" + ) { + checkRequests += 1; + try { + const response = (await checks.promise).clone(); + const json = response.json.bind(response); + response.json = async () => { + const result = await json(); + checksRead += 1; + return result; + }; + return response; + } catch (error) { + checksRead += 1; + throw error; + } + } + throw new Error(`Unexpected request: ${path}`); + }); + flowModule = await import("./use-publish-flow"); + getDiagnosticsReport = (await import("./diagnostics-utils")) + .getDiagnosticsReport; + stores = await import("~/shared/sync/data-stores"); + publishDialog = (await import("~/builder/shared/nano-states")).$publishDialog; + (await import("~/shared/csrf.client")).updateCsrfToken("test-token"); +}); +beforeEach(() => { + checks = deferred(); + dispatch = deferred(); + checkRequests = 0; + checksRead = 0; + publishRequests = 0; + vi.spyOn(toast, "error").mockImplementation(() => ""); + stores.$project.set({ id: "project" } as Project); + publishDialog.set("none"); + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + act(() => root.render()); +}); +afterEach(async () => { + act(() => root.unmount()); + checks.resolve(respond({ mdxErrors: [], mdxOmissions: [] })); + dispatch.resolve(respond({ success: false, error: "cleanup" })); + await act(async () => + vi.waitFor(() => expect(checksRead).toBe(checkRequests)) + ); + container.remove(); + stores.$project.set(undefined); + publishDialog.set("none"); + vi.restoreAllMocks(); +}); +afterAll(() => vi.unstubAllGlobals()); + +const start = (target: "site" | "static", domains = ["example.com"]) => + act(() => { + if (target === "site") { + flow.openSiteReport(undefined, "errors"); + flow.publish({ + target, + domains, + timesLeft: 10, + maxDailyPublishesPerUser: 20, + }); + } else { + flow.openStaticReport("errors"); + flow.publish({ target, templates: ["ssg"] }); + } + }); +const waitForUpdate = (check: () => void) => + vi.waitFor(async () => { + await act(async () => {}); + check(); + }); +const completeChecks = async (fail = false) => + act(async () => { + if (fail) { + checks.reject(new Error("check-failure")); + } else { + checks.resolve( + respond({ + diagnostics: { mdxErrors: [], mdxOmissions: [] }, + cssValid: false, + mdxErrors: [], + mdxOmissions: [ + { + filename: "check.mdx", + templateName: "missing", + blockInstanceId: "block", + assetId: "asset", + }, + ], + }) + ); + } + await checks.promise.catch(() => {}); + await vi.waitFor(() => expect(checksRead).toBe(checkRequests)); + }); + +test.each([ + ["site", "checks-first", false], + ["site", "checks-first", true], + ["site", "server-first", false], + ["site", "server-first", true], + ["static", "checks-first", false], + ["static", "checks-first", true], + ["static", "server-first", false], + ["static", "server-first", true], +] as const)( + "%s audit rejection wins with %s (failed checks: %s)", + async (target, order, failChecks) => { + start(target); + await act(async () => + vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([1, 1])) + ); + let completed: string[] = []; + if (order === "checks-first") { + await completeChecks(failChecks); + await waitForUpdate(() => + expect(flow.reportFindings.length).toBeGreaterThan(0) + ); + completed = flow.reportFindings.map(({ reportText }) => reportText); + } + await act(async () => { + dispatch.resolve( + respond({ + success: false, + auditFindings: [{ severity: "error", message: "server-rejection" }], + }) + ); + await dispatch.promise; + }); + await waitForUpdate(() => + expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([ + ...completed, + "ERROR: server-rejection", + ]) + ); + if (order === "server-first") { + await completeChecks(failChecks); + } + expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([ + ...completed, + "ERROR: server-rejection", + ]); + } +); + +test.each([ + ["request", "checks-first"], + ["request", "server-first"], + ["transport", "checks-first"], + ["transport", "server-first"], +] as const)( + "retains a static %s failure with %s and preserves the site failure", + async (failure, order) => { + start("site"); + await act(async () => + vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([1, 1])) + ); + await act(async () => { + dispatch.resolve(respond({ success: false, error: "site-rejection" })); + await dispatch.promise; + }); + await waitForUpdate(() => + expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([ + "site-rejection", + ]) + ); + dispatch = deferred(); + act(() => flow.publish({ target: "static", templates: ["ssg"] })); + await act(async () => + vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([2, 2])) + ); + expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([ + "site-rejection", + ]); + let completed: string[] = []; + if (order === "checks-first") { + act(() => flow.openStaticReport("errors")); + await completeChecks(); + await waitForUpdate(() => + expect( + flow.reportFindings.some(({ severity }) => severity === "warning") + ).toBe(true) + ); + completed = flow.reportFindings.map(({ reportText }) => reportText); + } + const message = `${failure}-failure`; + await act(async () => { + if (failure === "request") { + dispatch.resolve(respond({ success: false, error: message })); + } else { + dispatch.reject(new Error(message)); + } + await dispatch.promise.catch(() => {}); + }); + await waitForUpdate(() => + expect(flow.staticError?.reportText).toBe(message) + ); + act(() => flow.openStaticReport()); + expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([ + ...completed, + message, + ]); + expect(flow.selectedReport?.tab).toBe("errors"); + expect(toast.error).toHaveBeenCalledWith(message); + if (order === "server-first") { + await completeChecks(); + } + expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([ + ...completed, + message, + ]); + act(() => flow.openSiteReport(undefined, "errors")); + expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([ + "site-rejection", + ]); + } +); + +test.each(["checks-first", "server-first"] as const)( + "site transport error retains finished findings with %s", + async (order) => { + start("site"); + await act(async () => + vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([1, 1])) + ); + let completed: string[] = []; + if (order === "checks-first") { + await completeChecks(); + await waitForUpdate(() => + expect( + flow.reportFindings.some(({ severity }) => severity === "warning") + ).toBe(true) + ); + completed = flow.reportFindings.map(({ reportText }) => reportText); + } + await act(async () => { + dispatch.reject(new Error("site-transport")); + await dispatch.promise.catch(() => {}); + }); + await waitForUpdate(() => expect(flow.siteError).toBe("site-transport")); + if (order === "server-first") { + await completeChecks(); + } + expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([ + ...completed, + "site-transport", + ]); + act(() => flow.openSiteReport("other.example", "errors")); + expect(flow.reportFindings).toEqual([]); + // The popover consumes the unfiltered error even when another domain's + // report is selected; scoping must not hide the attempt's banner. + expect(flow.siteErrorSource).toBe("transport"); + expect(flow.siteError).toBe("site-transport"); + act(() => flow.openSiteReport("example.com", "errors")); + expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([ + ...completed, + "site-transport", + ]); + } +); + +test.each(["site", "static"] as const)( + "%s check failure has one visible notice while Publish is open", + async (target) => { + start(target); + publishDialog.set("publish"); + await act(async () => + vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([1, 1])) + ); + await completeChecks(true); + await waitForUpdate(() => + expect(flow.reportFindings.length).toBeGreaterThan(0) + ); + expect(toast.error).toHaveBeenCalledTimes(target === "site" ? 0 : 1); + } +); + +test("an accepted site failure keeps the build association used by the log link", async () => { + start("site"); + await act(async () => + vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([1, 1])) + ); + await act(async () => { + dispatch.resolve( + respond({ + success: true, + buildId: "accepted-build", + logHandle: "handle", + findings: [], + }) + ); + await dispatch.promise; + }); + await waitForUpdate(() => + expect( + flow.reportFindings.find(({ source }) => source === "publish")?.buildId + ).toBe("accepted-build") + ); +}); + +test.each([ + ["static", "request"], + ["static", "transport"], + ["static", "audit"], + ["site", "request"], + ["site", "transport"], + ["site", "audit"], +] as const)( + "a newer %s %s rejection does not mix in the older accepted failure", + async (target, failure) => { + act(() => root.render()); + start(target, ["example.com", "other.example"]); + await act(async () => + vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([1, 1])) + ); + await completeChecks(); + await act(async () => { + dispatch.resolve( + respond({ + success: true, + buildId: "old-accepted", + logHandle: "old-handle", + findings: [{ severity: "warning", message: "old-audit" }], + ...(target === "static" ? { name: "site.zip" } : {}), + }) + ); + await dispatch.promise; + }); + await waitForUpdate(() => expect(flow.logs[0]?.logState).toBe("available")); + checks = deferred(); + dispatch = deferred(); + start(target); + await act(async () => + vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([2, 2])) + ); + const message = `new-${failure}`; + await act(async () => { + if (failure === "transport") { + dispatch.reject(new Error(message)); + } else { + dispatch.resolve( + respond( + failure === "audit" + ? { + success: false, + auditFindings: [{ severity: "error", message }], + } + : { success: false, error: message } + ) + ); + } + await dispatch.promise.catch(() => {}); + }); + const expected = failure === "audit" ? `ERROR: ${message}` : message; + await waitForUpdate(() => + expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([ + expected, + ]) + ); + const report = () => + getDiagnosticsReport({ + findings: flow.reportFindings, + items: flow.reportItems, + canViewPublishLogs: true, + includeLatestPublishFindings: flow.includeLatestPublishFindings, + }); + expect(report().findings.map(({ reportText }) => reportText)).toEqual([ + expected, + ]); + expect(report().issuesOmitted).toBeUndefined(); + expect(report().publishes.map(({ buildId }) => buildId)).toEqual([ + "old-accepted", + ]); + expect(report().publishText).toBe( + target === "static" + ? "Static export\nold-runner-output" + : "example.com\nother.example\nold-runner-output" + ); + if (target === "site" && failure === "request") { + act(() => flow.openSiteReport("other.example", "errors")); + expect(report().findings.map(({ reportText }) => reportText)).toEqual([ + "WARNING: old-audit", + "ERROR: old-build-issue", + ]); + } + } +); diff --git a/apps/builder/app/builder/features/publish/use-publish-flow.tsx b/apps/builder/app/builder/features/publish/use-publish-flow.tsx new file mode 100644 index 0000000000..10036ee0b6 --- /dev/null +++ b/apps/builder/app/builder/features/publish/use-publish-flow.tsx @@ -0,0 +1,504 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { Link, Text, Tooltip, toast } from "@webstudio-is/design-system"; +import type { Project } from "@webstudio-is/project"; +import { + publishedDeploymentDestination, + type Templates, +} from "@webstudio-is/sdk"; +import { $project } from "~/shared/sync/data-stores"; +import { $publishDialog } from "~/builder/shared/nano-states"; +import { nativeClient } from "~/shared/trpc/trpc-client"; +import { usePublishValidationState } from "./publish-actions"; +import { + usePublishProgress, + waitForPublishStatus, + refreshUntilSuccess, + getRefreshedProject, + reportPublishResult, +} from "./use-publish-progress"; +import { + selectPublishLogs, + usePublishLogs, + type PublishLog, +} from "./use-publish-logs"; +import { + runPublishDiagnostics, + runPublishValidation, + reportPublishValidationFailure, + getServerPublishFindings, +} from "./publish-validation"; +import { runPublishAfterBestEffortChecks } from "./publish-preflight"; +import type { PublishValidationFinding } from "./diagnostics"; + +const downloadStatic = (name: string) => { + window.location.href = `/cgi/static/ssg/${name}`; +}; + +const getPublishErrorFinding = ( + error: JSX.Element | string, + buildId?: string +): PublishValidationFinding => ({ + severity: "error", + source: "publish", + buildId, + title: error, + summary: typeof error === "string" ? error.slice(0, 160) : "Publish failed", + reportText: typeof error === "string" ? error : "Publish failed", +}); + +export const usePublishFlow = ( + projectId: Project["id"], + allowPublishLogs: boolean, + publishDialog: "none" | "publish" | "export" +) => { + const publishLogs = usePublishLogs(projectId, allowPublishLogs); + const pendingLogs = useRef(publishLogs.items); + pendingLogs.current = publishLogs.items; + const [selectedReport, setSelectedReport] = useState<{ + target: "static" | "site"; + domain?: string; + tab: "warnings" | "errors" | "publish"; + }>(); + useEffect(() => { + setSelectedReport(undefined); + }, [projectId]); + const validation = usePublishValidationState(publishDialog); + const progress = usePublishProgress(projectId); + const { + dismissCountdown, + reconcileRefreshedProject, + watchPendingPublish, + beginPopoverRefresh, + isRefreshCurrent, + } = progress; + useEffect(() => { + if (publishDialog !== "publish") { + dismissCountdown(); + } + }, [publishDialog, dismissCountdown]); + const { + complete: completePublishLog, + loadLog: loadPublishLog, + isCurrent, + } = publishLogs; + const validationFindings = progress.manualValidationFindings; + const { invalidate: invalidateValidationFindings } = validationFindings; + const { update: onValidationStateChange } = validation; + const { isCurrentProject } = progress; + const invalidateValidation = useCallback(() => { + invalidateValidationFindings(); + onValidationStateChange("idle"); + }, [invalidateValidationFindings, onValidationStateChange]); + + const finishPublish = useCallback( + ( + item: PublishLog | undefined, + result: Awaited>, + onDownload = downloadStatic + ) => { + if ( + item === undefined || + !isCurrent() || + (result?.status !== "PUBLISHED" && result?.status !== "FAILED") + ) { + return; + } + const status = result.status === "PUBLISHED" ? "success" : "failed"; + completePublishLog(item.buildId, status, result.code); + loadPublishLog({ ...item, status }); + if ( + item.target === "static" && + status === "success" && + item.staticName !== undefined + ) { + onDownload(item.staticName); + } + }, + [completePublishLog, loadPublishLog, isCurrent] + ); + + const waitForCompletion = async ( + item: PublishLog | undefined, + previousBuildId?: string, + onDownload = downloadStatic + ) => { + if (item === undefined) { + return; + } + const result = await waitForPublishStatus( + () => getRefreshedProject({ projectId, isCurrent }), + isCurrent, + previousBuildId, + { + projectId, + buildId: item.buildId, + logHandle: item.logHandle, + target: item.target, + } + ); + finishPublish(item, result, onDownload); + return result; + }; + useEffect(() => { + // Refresh a build that finished while the popover was closed, including + // after a publish status request failed. + if (publishDialog !== "none" && progress.isPublishing === false) { + let isOpen = true; + const generation = beginPopoverRefresh(); + void refreshUntilSuccess( + async (showError) => { + const refreshedProject = await getRefreshedProject({ + projectId, + showError, + isCurrent: () => isOpen && isRefreshCurrent(generation), + }); + if ( + isOpen && + isRefreshCurrent(generation) && + refreshedProject !== undefined + ) { + reconcileRefreshedProject(refreshedProject); + } + return refreshedProject; + }, + () => isOpen, + () => { + const target = publishDialog === "export" ? "static" : "site"; + const pending = pendingLogs.current.find( + (item) => item.target === target && item.status === "pending" + ); + if (target === "static" && pending === undefined) { + return; + } + void watchPendingPublish( + () => + getRefreshedProject({ + projectId, + showError: false, + isCurrent: () => isRefreshCurrent(generation), + }), + generation, + pending === undefined + ? undefined + : { + projectId, + buildId: pending.buildId, + logHandle: pending.logHandle, + target, + }, + (result) => finishPublish(pending, result) + ); + }, + () => + pendingLogs.current.some( + (item) => + item.target === + (publishDialog === "export" ? "static" : "site") && + item.status === "pending" + ) + ); + return () => { + isOpen = false; + }; + } + }, [ + projectId, + publishDialog, + progress.isPublishing, + reconcileRefreshedProject, + watchPendingPublish, + beginPopoverRefresh, + isRefreshCurrent, + finishPublish, + ]); + const openSiteReport = ( + domain: string | undefined, + tab: "warnings" | "errors" | "publish" + ) => { + $publishDialog.set("none"); + setSelectedReport({ target: "site", domain, tab }); + }; + const openStaticReport = ( + tab: "warnings" | "errors" | "publish" = staticError === undefined + ? "publish" + : "errors" + ) => { + $publishDialog.set("none"); + setSelectedReport({ target: "static", tab }); + }; + const reportItems = selectPublishLogs( + publishLogs.items, + selectedReport?.target ?? "site", + selectedReport?.domain + ); + const domain = selectedReport?.domain; + const siteFindings = [ + ...validationFindings.findings, + ...progress.publishFindings, + ]; + const staticDiagnostics = progress.publishDiagnostics.static; + const staticError = staticDiagnostics.rejected + ? staticDiagnostics.findings + .filter(({ severity }) => severity === "error") + .at(-1) + : undefined; + const findings: PublishValidationFinding[] = []; + const diagnostics = + progress.publishDiagnostics[selectedReport?.target ?? "site"]; + const isReportForDiagnostics = + domain === undefined || diagnostics.domains.includes(domain); + if (isReportForDiagnostics) { + findings.push(...diagnostics.findings); + } + if (selectedReport?.target !== "static") { + if (domain === undefined || validationFindings.domains?.includes(domain)) { + findings.push(...validationFindings.findings); + } + const { publishError, publishErrorDomains } = progress; + if ( + publishError !== undefined && + (domain === undefined || + publishErrorDomains === undefined || + publishErrorDomains.includes(domain)) + ) { + findings.push( + getPublishErrorFinding(publishError, progress.publishErrorBuildId) + ); + } + } + + const validate = async (domains: string[]) => { + const session = validationFindings.begin(domains); + progress.clearErrors(); + progress.beginPublishDiagnostics(domains); + if (domains.length === 0) { + toast.error("Please select at least one domain to publish"); + return; + } + + try { + const checks = await runPublishValidation(projectId, domains); + if (validationFindings.isCurrent(session) === false) { + return; + } + validationFindings.update(session, checks.findings); + if (checks.passed === false) { + onValidationStateChange("idle"); + return; + } + onValidationStateChange("passed"); + } catch (error) { + if (validationFindings.isCurrent(session) === false) { + return; + } + onValidationStateChange("idle"); + reportPublishValidationFailure( + error, + (findings) => validationFindings.update(session, findings), + { showToast: $publishDialog.get() !== "publish" } + ); + } + }; + + const publish = ( + request: + | { + target: "site"; + domains: string[]; + timesLeft: number; + maxDailyPublishesPerUser: number; + } + | { + target: "static"; + templates: readonly Templates[]; + onDownload?: (name: string) => void; + } + ) => { + if (!isCurrent()) { + return; + } + const domains = request.target === "site" ? request.domains : []; + if (request.target === "site") { + validationFindings.invalidate(); + onValidationStateChange("idle"); + if (domains.length === 0) { + toast.error("Please select at least one domain to publish"); + return; + } + } + const diagnostics = progress.beginPublishDiagnostics( + domains, + request.target + ); + progress.start( + async () => { + const previousBuildId = + request.target === "site" + ? $project.get()?.latestBuildVirtual?.buildId + : undefined; + const publishResult = await runPublishAfterBestEffortChecks({ + checks: async () => { + const checks = await runPublishDiagnostics( + projectId, + request.target === "site" ? domains : undefined + ); + diagnostics.setFindings(checks.findings); + }, + onCheckFailure: (error) => { + if (isCurrent() && diagnostics.isCurrent()) { + reportPublishValidationFailure(error, diagnostics.setFindings, { + publishingContinues: true, + showToast: + request.target === "static" || + $publishDialog.get() !== "publish", + }); + } + }, + publish: () => + nativeClient.domain.publish.mutate( + request.target === "site" + ? { + projectId, + destination: publishedDeploymentDestination, + domains, + } + : { + projectId, + destination: "static", + templates: [...request.templates], + } + ), + }); + if (!isCurrent()) { + return; + } + if (publishResult.success === false) { + if ("auditFindings" in publishResult) { + diagnostics.finish((findings) => [ + ...findings, + ...getServerPublishFindings(publishResult.auditFindings), + ]); + if (request.target === "static") { + openStaticReport("errors"); + } + return; + } + if (request.target === "static") { + diagnostics.finish((findings) => [ + ...findings, + getPublishErrorFinding(publishResult.error), + ]); + toast.error(publishResult.error.slice(0, 200)); + return; + } + diagnostics.finish(); + console.error(publishResult.error); + + let error: JSX.Element | string = publishResult.error; + if (publishResult.error === "NOT_IMPLEMENTED") { + error = ( + <> + + {$project.get()?.latestBuildVirtual?.buildId} + + } + > + Build data + {" "} + for publishing has been successfully created. Use{" "} + + Webstudio CLI + {" "} + to generate the code. + + ); + } + progress.setPublishError(error, domains); + if (publishResult.error === "NOT_IMPLEMENTED") { + toast.info(error); + } else if ($publishDialog.get() !== "publish") { + toast.error( + typeof error === "string" ? error.slice(0, 200) : error + ); + } + + if (process.env.NODE_ENV === "development") { + // Refresh locally as it's always an error + await getRefreshedProject({ projectId, isCurrent }); + } + + return; + } + + const accepted = publishLogs.record({ + buildId: publishResult.buildId, + logHandle: publishResult.logHandle, + target: request.target, + domains, + findings: getServerPublishFindings(publishResult.findings), + staticName: "name" in publishResult ? publishResult.name : undefined, + }); + if (request.target === "static" && accepted?.staticName == null) { + toast.error('File name must be defined in "result"'); + } + const outcome = await waitForCompletion( + accepted, + previousBuildId, + request.target === "static" ? request.onDownload : undefined + ); + if (request.target === "site") { + reportPublishResult({ + result: outcome, + buildId: accepted?.buildId, + timesLeft: request.timesLeft, + maxDailyPublishesPerUser: request.maxDailyPublishesPerUser, + setPublishError: progress.setPublishStatusError, + isCurrentProject, + }); + } else if (isCurrent() && outcome?.status === "FAILED") { + toast.error(outcome.statusText); + } + }, + { + target: request.target, + domains, + onError: (message) => + diagnostics.finish( + request.target === "static" + ? (findings) => [...findings, getPublishErrorFinding(message)] + : undefined + ), + } + ); + }; + return { + isPublishing: progress.isPublishing, + countdown: progress.countdown, + validationState: validation.validationState, + validatedDomains: validationFindings.domains, + siteError: progress.publishError, + siteErrorSource: progress.publishErrorSource, + siteFindings, + staticError, + logs: publishLogs.items, + loadLog: publishLogs.loadLog, + selectedReport, + closeReport: () => setSelectedReport(undefined), + reportItems, + reportFindings: findings, + includeLatestPublishFindings: !( + diagnostics.rejected && isReportForDiagnostics + ), + openSiteReport, + openStaticReport, + validate, + publish, + invalidateValidation, + reset: () => { + validation.reset(); + dismissCountdown(); + }, + }; +}; diff --git a/apps/builder/app/builder/features/publish/use-publish-progress.tsx b/apps/builder/app/builder/features/publish/use-publish-progress.tsx new file mode 100644 index 0000000000..8e3b7adcdb --- /dev/null +++ b/apps/builder/app/builder/features/publish/use-publish-progress.tsx @@ -0,0 +1,583 @@ +import { + useCallback, + useEffect, + useRef, + useState, + type SetStateAction, +} from "react"; +import { toast } from "@webstudio-is/design-system"; +import type { Project } from "@webstudio-is/project"; +import { $project } from "~/shared/sync/data-stores"; +import { $publishDialog } from "~/builder/shared/nano-states"; +import { nativeClient } from "~/shared/trpc/trpc-client"; +import { + PENDING_TIMEOUT, + getPublishStatusAndText, + getStaticPublishStatusAndText, +} from "./publish-status"; +import type { PublishValidationFinding } from "./diagnostics"; + +const COUNTDOWN_DURATION = 60_000; + +const STATUS_REFRESH_RETRY_DELAY = 5_000; + +const STATUS_REFRESH_MAX_ATTEMPTS = 3; + +type PublishExecution = { + projectId: string; + buildId: string; + logHandle?: string; + target?: "site" | "static"; +}; + +export const usePublishProgress = (projectId: Project["id"]) => { + const projectScope = useRef({ projectId, token: 0 }); + if (projectScope.current.projectId !== projectId) { + projectScope.current = { projectId, token: projectScope.current.token + 1 }; + } + const scopeToken = projectScope.current.token; + const manualValidationFindings = useManualValidationFindings(); + const invalidateManualFindings = manualValidationFindings.invalidate; + const [startedAt, setStartedAt] = useState(); + const [showCountdown, setShowCountdown] = useState(false); + const [isPublishing, setIsPublishing] = useState(false); + const [publishDiagnostics, setPublishDiagnostics] = useState< + Record< + "site" | "static", + { + domains: string[]; + findings: PublishValidationFinding[]; + rejected?: boolean; + } + > + >({ + site: { domains: [], findings: [] }, + static: { domains: [], findings: [] }, + }); + const publishDiagnosticsSession = useRef({ site: 0, static: 0 }); + const [publishErrorState, setPublishErrorState] = useState<{ + value: JSX.Element | string; + source: "request" | "transport" | "status"; + domains?: string[]; + buildId?: string; + }>(); + const [now, setNow] = useState(Date.now); + const isMounted = useRef(false); + const requestBaselineBuildId = useRef(); + const hasStartedPublishRequest = useRef(false); + const refreshGeneration = useRef(0); + const recoveredPoll = useRef<{ + generation: number; + promise: Promise; + }>(); + + useEffect(() => { + isMounted.current = true; + return () => { + isMounted.current = false; + }; + }, []); + + useEffect(() => { + publishDiagnosticsSession.current.site += 1; + publishDiagnosticsSession.current.static += 1; + setPublishDiagnostics({ + site: { domains: [], findings: [] }, + static: { domains: [], findings: [] }, + }); + setPublishErrorState(undefined); + setIsPublishing(false); + invalidateManualFindings(); + }, [projectId, invalidateManualFindings]); + + const isCurrentProject = useCallback( + () => + isMounted.current && + $project.get()?.id === projectId && + projectScope.current.token === scopeToken, + [projectId, scopeToken] + ); + + const beginPopoverRefresh = useCallback(() => { + refreshGeneration.current += 1; + return refreshGeneration.current; + }, []); + + const isRefreshCurrent = useCallback( + (generation: number) => + isCurrentProject() && refreshGeneration.current === generation, + [isCurrentProject] + ); + + const setPublishError = ( + value: JSX.Element | string | undefined, + domains?: string[] + ) => { + setPublishErrorState( + value === undefined ? undefined : { value, source: "request", domains } + ); + }; + + const setPublishStatusError = useCallback( + (value: JSX.Element | string, buildId?: string) => { + setPublishErrorState({ value, source: "status", buildId }); + }, + [] + ); + + const clearErrors = useCallback(() => { + setPublishErrorState(undefined); + }, []); + + const beginPublishDiagnostics = useCallback( + (domains: string[] = [], target: "site" | "static" = "site") => { + const session = ++publishDiagnosticsSession.current[target]; + setPublishDiagnostics((current) => ({ + ...current, + [target]: { domains, findings: [] }, + })); + const setFindings = ( + findings: SetStateAction + ) => { + if (publishDiagnosticsSession.current[target] === session) { + setPublishDiagnostics((current) => ({ + ...current, + [target]: { + domains, + findings: + typeof findings === "function" + ? findings(current[target].findings) + : findings, + }, + })); + } + }; + return { + isCurrent: () => publishDiagnosticsSession.current[target] === session, + setFindings, + finish: (findings?: SetStateAction) => { + if (findings !== undefined) { + setFindings(findings); + } + if (publishDiagnosticsSession.current[target] === session) { + setPublishDiagnostics((current) => ({ + ...current, + [target]: { ...current[target], rejected: true }, + })); + publishDiagnosticsSession.current[target] += 1; + } + }, + }; + }, + [] + ); + + const reconcileRefreshedProject = useCallback((project: Project) => { + const build = project.latestBuildVirtual; + if (build == null) { + setPublishErrorState((current) => + current?.source === "status" ? undefined : current + ); + return; + } + const { status, statusText } = getPublishStatusAndText(build); + const isNewBuild = + build.buildId !== undefined && + build.buildId !== requestBaselineBuildId.current; + if (status === "FAILED") { + if (hasStartedPublishRequest.current && isNewBuild) { + setPublishErrorState({ + value: statusText, + source: "status", + buildId: build.buildId, + }); + } + } else { + setPublishErrorState((current) => + current?.source === "status" || + (isNewBuild && current?.source === "transport") + ? undefined + : current + ); + } + }, []); + + const watchPendingPublish = useCallback( + ( + refresh: () => Promise, + generation = refreshGeneration.current, + execution?: PublishExecution, + onResult?: ( + result: Awaited> + ) => void + ) => { + if (recoveredPoll.current?.generation === generation) { + return recoveredPoll.current.promise; + } + const polling = waitForPublishStatus( + refresh, + () => isRefreshCurrent(generation), + undefined, + execution + ) + .then((result) => { + if (isRefreshCurrent(generation) === false) { + return; + } + if (execution?.target !== "static") { + reportPublishResult({ + result, + buildId: execution?.buildId, + setPublishError: setPublishStatusError, + isCurrentProject, + }); + } else if (result?.status === "FAILED") { + toast.error(result.statusText); + } + onResult?.(result); + }) + .finally(() => { + if (recoveredPoll.current?.promise === polling) { + recoveredPoll.current = undefined; + } + }); + recoveredPoll.current = { generation, promise: polling }; + return polling; + }, + [isCurrentProject, isRefreshCurrent, setPublishStatusError] + ); + + useEffect(() => { + if (isPublishing === false || showCountdown === false) { + return; + } + const interval = setInterval(() => setNow(Date.now()), 1000); + return () => clearInterval(interval); + }, [isPublishing, showCountdown]); + + const countdown = + isPublishing && showCountdown && startedAt !== undefined + ? Math.max(0, Math.ceil((COUNTDOWN_DURATION - (now - startedAt)) / 1000)) + : undefined; + + const dismissCountdown = useCallback(() => setShowCountdown(false), []); + + const start = ( + publish: () => Promise, + { + target = "site", + domains, + onError, + }: { + target?: "site" | "static"; + domains?: string[]; + onError?: (message: string) => void; + } = {} + ) => { + const startedAt = Date.now(); + if (target === "site") { + hasStartedPublishRequest.current = true; + requestBaselineBuildId.current = + $project.get()?.latestBuildVirtual?.buildId; + setPublishErrorState(undefined); + } + setStartedAt(startedAt); + setNow(startedAt); + setShowCountdown(true); + setIsPublishing(true); + publish() + .catch((error) => { + if (target === "site") { + console.error(error); + } + const message = + error instanceof Error ? error.message : "Unknown error"; + if (isCurrentProject()) { + onError?.(message); + if (target === "site") { + setPublishErrorState({ + value: message, + source: "transport", + domains, + }); + } + if (target === "static" || $publishDialog.get() !== "publish") { + toast.error(target === "static" ? message.slice(0, 200) : message); + } + } + }) + .finally(() => { + if (isCurrentProject()) { + setIsPublishing(false); + } + }); + }; + + return { + manualValidationFindings, + isPublishing, + publishFindings: publishDiagnostics.site.findings, + publishDiagnostics, + beginPublishDiagnostics, + publishError: publishErrorState?.value, + publishErrorSource: publishErrorState?.source, + publishErrorDomains: publishErrorState?.domains, + publishErrorBuildId: publishErrorState?.buildId, + setPublishError, + setPublishStatusError, + clearErrors, + isCurrentProject, + beginPopoverRefresh, + isRefreshCurrent, + reconcileRefreshedProject, + watchPendingPublish, + countdown, + start, + dismissCountdown, + }; +}; + +export const waitForPublishStatus = async ( + refresh: () => Promise, + isCurrentProject: () => boolean, + previousBuildId?: string, + execution?: PublishExecution, + getJob: (input: { + projectId: string; + jobId: string; + logHandle: string; + }) => Promise<{ status: string; code?: string }> = nativeClient.api.publish + .getJob.query +) => { + let sleepTime = 15000; + const timeToFinish = Date.now() + PENDING_TIMEOUT + 2 * sleepTime; + + while (Date.now() < timeToFinish && isCurrentProject()) { + try { + let runnerPending = false; + if (execution?.logHandle !== undefined) { + try { + const job = await getJob({ + projectId: execution.projectId, + jobId: execution.buildId, + logHandle: execution.logHandle, + }); + if (isCurrentProject() === false) { + return; + } + if (job.status === "failed") { + return { + status: "FAILED" as const, + statusText: "Publish failed", + code: job.code, + }; + } + runnerPending = job.status === "pending"; + } catch (error) { + console.error("Could not refresh publish status", error); + } + } + const refreshedProject = await refresh(); + if (isCurrentProject() === false) { + return; + } + const buildId = + execution?.target === "static" + ? refreshedProject?.latestStaticBuild?.buildId + : refreshedProject?.latestBuildVirtual?.buildId; + if ( + refreshedProject !== undefined && + (previousBuildId === undefined || buildId !== previousBuildId) && + (execution === undefined || buildId === execution.buildId) + ) { + const { statusText, status } = + execution?.target === "static" && + refreshedProject.latestStaticBuild != null + ? getStaticPublishStatusAndText(refreshedProject.latestStaticBuild) + : refreshedProject.latestBuildVirtual != null + ? getPublishStatusAndText(refreshedProject.latestBuildVirtual) + : { + statusText: "Not published", + status: "PENDING" as const, + }; + + if (!runnerPending && (status === "PUBLISHED" || status === "FAILED")) { + return { status, statusText }; + } + } + } catch (error) { + if (isCurrentProject() === false) { + return; + } + // A failed status request should not stop watching an ongoing publish. + console.error("Could not refresh publish status", error); + } + + await new Promise((resolve) => setTimeout(resolve, sleepTime)); + sleepTime = Math.max(5000, sleepTime - 5000); + } +}; + +export const refreshUntilSuccess = async ( + refresh: (showError: boolean) => Promise, + isOpen: () => boolean, + onPending: (project: Project) => void = () => {}, + hasSessionPending: (project: Project) => boolean = () => false +) => { + for ( + let attempt = 1; + attempt <= STATUS_REFRESH_MAX_ATTEMPTS && isOpen(); + attempt++ + ) { + const isLastAttempt = attempt === STATUS_REFRESH_MAX_ATTEMPTS; + try { + const refreshedProject = await refresh(isLastAttempt); + if (refreshedProject !== undefined) { + if ( + (refreshedProject.latestBuildVirtual != null && + getPublishStatusAndText(refreshedProject.latestBuildVirtual) + .status === "PENDING") || + hasSessionPending(refreshedProject) + ) { + onPending(refreshedProject); + } + return; + } + } catch (error) { + console.error("Could not refresh publish status", error); + if (isLastAttempt && isOpen()) { + toast.error(error instanceof Error ? error.message : "Unknown error"); + } + } + + if (isLastAttempt === false && isOpen()) { + await new Promise((resolve) => + setTimeout(resolve, STATUS_REFRESH_RETRY_DELAY) + ); + } + } +}; + +export const reportPublishResult = ({ + result, + buildId, + timesLeft, + maxDailyPublishesPerUser, + setPublishError, + isCurrentProject = () => true, +}: { + result: Awaited>; + buildId?: string; + timesLeft?: number; + maxDailyPublishesPerUser?: number; + setPublishError: (error: string | JSX.Element, buildId?: string) => void; + isCurrentProject?: () => boolean; +}) => { + if (isCurrentProject() === false) { + return; + } + if (result?.status === "PUBLISHED") { + if ($publishDialog.get() === "none") { + toast.success( + <> + The project has been successfully published.{" "} + {timesLeft !== undefined && + maxDailyPublishesPerUser !== undefined && + timesLeft > 0 && + timesLeft <= 10 && ( +
+ You have {timesLeft} out of {maxDailyPublishesPerUser} daily + publications remaining. The counter resets tomorrow. +
+ )} + , + { duration: 10000 } + ); + } + return; + } + + if (result?.status === "FAILED") { + if ($publishDialog.get() !== "publish") { + toast.error(result.statusText); + } + setPublishError(result.statusText, buildId); + } +}; + +const useManualValidationFindings = () => { + const [findings, setFindings] = useState([]); + const [domains, setDomains] = useState(); + const session = useRef(0); + const requestedDomains = useRef([]); + + useEffect(() => { + return () => { + session.current += 1; + }; + }, []); + + const begin = useCallback((domains: string[] = []) => { + session.current += 1; + requestedDomains.current = domains; + setFindings([]); + setDomains(undefined); + return session.current; + }, []); + + const invalidate = useCallback(() => { + session.current += 1; + setFindings([]); + setDomains(undefined); + }, []); + + const isCurrent = useCallback((id: number) => session.current === id, []); + + const update = useCallback((id: number, next: PublishValidationFinding[]) => { + if (session.current === id) { + setFindings(next); + setDomains(next.length > 0 ? requestedDomains.current : undefined); + } + }, []); + + return { findings, domains, begin, invalidate, isCurrent, update }; +}; + +export const getRefreshedProject = async ({ + projectId, + showError = true, + query = () => nativeClient.domain.project.query({ projectId }), + isCurrent = () => true, +}: { + projectId: Project["id"]; + showError?: boolean; + query?: () => ReturnType; + isCurrent?: () => boolean; +}) => { + if ($project.get()?.id !== projectId || !isCurrent()) { + return; + } + + const result = await query(); + if ($project.get()?.id !== projectId || !isCurrent()) { + return; + } + + if (result.success) { + $project.set(result.project); + return result.project; + } + + if (showError) { + toast.error(result.error); + } +}; + +export const __testing__ = { + usePublishProgress, + waitForPublishStatus, + refreshUntilSuccess, + reportPublishResult, + useManualValidationFindings, + getRefreshedProject, +};