Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

Synchronisations fixes (#2070)

Ivan Starkov260ca1e9a59b
diff --git a/apps/builder/app/builder/features/topbar/sync-status.tsx b/apps/builder/app/builder/features/topbar/sync-status.tsx
index 16c7721aea..faa666e446 100644
--- a/apps/builder/app/builder/features/topbar/sync-status.tsx
+++ b/apps/builder/app/builder/features/topbar/sync-status.tsx
@@ -18,37 +18,63 @@ const subscribeIsOnline = () => {
};
export const SyncStatus = () => {
- const status = useStore(queueStatus);
+ const statusObject = useStore(queueStatus);
const isOnline = useStore(isOnlineStore);
useEffect(subscribeIsOnline, []);
- if (status !== "failed") {
+ if (
+ statusObject.status === "idle" ||
+ statusObject.status === "running" ||
+ statusObject.status === "recovering"
+ ) {
return null;
}
- return (
- <Flex align="center" justify="center">
- <Tooltip
- variant="wrapped"
- content={
- <>
- Offline changes will be synced with Webstudio once you go online.
- {isOnline ? (
- ""
- ) : (
- <>
- <br />
- Please check your internet connection.
- </>
- )}
- </>
- }
- >
- <OfflineIcon
- aria-label={`Sync status: ${status}`}
- color={rawTheme.colors.foregroundDestructive}
- />
- </Tooltip>
- </Flex>
- );
+ if (statusObject.status === "failed") {
+ return (
+ <Flex align="center" justify="center">
+ <Tooltip
+ variant="wrapped"
+ content={
+ <>
+ {isOnline ? (
+ <>
+ Experiencing connectivity issues. Your changes will be synced
+ with Webstudio once resolved.
+ </>
+ ) : (
+ <>
+ Offline changes will be synced with Webstudio once you go
+ online.
+ <br />
+ Please check your internet connection.
+ </>
+ )}
+ </>
+ }
+ >
+ <OfflineIcon
+ aria-label={`Sync status: failed`}
+ color={rawTheme.colors.foregroundDestructive}
+ />
+ </Tooltip>
+ </Flex>
+ );
+ }
+
+ if (statusObject.status === "fatal") {
+ return (
+ <Flex align="center" justify="center">
+ <Tooltip variant="wrapped" content={<>{statusObject.error}</>}>
+ <OfflineIcon
+ aria-label={`Sync status: fatal`}
+ color={rawTheme.colors.foregroundDestructive}
+ />
+ </Tooltip>
+ </Flex>
+ );
+ }
+
+ /* exhaustive check */
+ statusObject satisfies never;
};
diff --git a/apps/builder/app/builder/shared/sync/command-queue.ts b/apps/builder/app/builder/shared/sync/command-queue.ts
new file mode 100644
index 0000000000..ed9825584b
--- /dev/null
+++ b/apps/builder/app/builder/shared/sync/command-queue.ts
@@ -0,0 +1,51 @@
+import type { Project } from "@webstudio-is/project";
+import type { Build } from "@webstudio-is/project-build";
+import type { SyncItem } from "immerhin";
+
+type Command =
+ | {
+ type: "transactions";
+ projectId: Project["id"];
+ transactions: SyncItem[];
+ }
+ | {
+ type: "setDetails";
+ projectId: Project["id"];
+ version: number;
+ buildId: Build["id"];
+ authToken: string | undefined;
+ };
+
+const projectCommandsQueue: Command[] = [];
+
+export const enqueue = (command: Command) => {
+ if (command.type !== "transactions") {
+ projectCommandsQueue.push(command);
+ return;
+ }
+
+ // merge transactions in case of no commands in queue
+ for (const projectCommand of projectCommandsQueue.reverse()) {
+ if (projectCommand.type !== "transactions") {
+ break;
+ }
+
+ if (projectCommand.projectId === command.projectId) {
+ projectCommand.transactions.push(...command.transactions);
+ return;
+ }
+ }
+
+ projectCommandsQueue.push(command);
+};
+
+export const dequeue = () => {
+ const command = projectCommandsQueue.pop();
+ return command;
+};
+
+export const dequeueAll = () => {
+ const commands = [...projectCommandsQueue];
+ projectCommandsQueue.length = 0;
+ return commands;
+};
diff --git a/apps/builder/app/builder/shared/sync/sync-server.ts b/apps/builder/app/builder/shared/sync/sync-server.ts
index 7a5704577c..68d4798339 100644
--- a/apps/builder/app/builder/shared/sync/sync-server.ts
+++ b/apps/builder/app/builder/shared/sync/sync-server.ts
@@ -1,11 +1,13 @@
-import { useEffect, useRef } from "react";
+import { useEffect } from "react";
import { useBeforeUnload } from "react-use";
import { atom } from "nanostores";
import { sync } from "immerhin";
-import type { Project } from "@webstudio-is/project";
+import { Project } from "@webstudio-is/project";
import type { Build } from "@webstudio-is/project-build";
import type { AuthPermit } from "@webstudio-is/trpc-interface/index.server";
+import * as commandQueue from "./command-queue";
import { restPatchPath } from "~/shared/router-utils";
+import { toast } from "@webstudio-is/design-system";
// Periodic check for new entries to group them into one job/call in sync queue.
const NEW_ENTRIES_INTERVAL = 1000;
@@ -16,100 +18,276 @@ const INTERVAL_RECOVERY = 2000;
// After this amount of retries without success, we consider connection status error.
const MAX_RETRY_RECOVERY = 5;
+// We are assuming that error is fatal (unrecoverable) after this amount of attempts with API error.
+const MAX_ALLOWED_API_ERRORS = 5;
+
// When we reached max failed attempts we will slow down the attempts interval.
const INTERVAL_ERROR = 5000;
+const MAX_INTERVAL_ERROR = 2 * 60000;
const pause = (timeout: number) => {
return new Promise((resolve) => setTimeout(resolve, timeout));
};
-export type QueueStatus = "running" | "idle" | "recovering" | "failed";
+export type QueueStatus =
+ | { status: "running" }
+ | { status: "idle" }
+ | { status: "recovering" }
+ | { status: "failed" }
+ | { status: "fatal"; error: string };
-export const queueStatus = atom<QueueStatus>("idle");
+export const queueStatus = atom<QueueStatus>({ status: "idle" });
+const getRandomBetween = (a: number, b: number) => {
+ return Math.random() * (b - a) + a;
+};
// polling is important to queue new transactions independently
// from async iterator and batch them into single job
-const pollTransactions = async function* () {
+const pollCommands = async function* () {
while (true) {
- const transactions = sync();
- if (transactions.length > 0) {
- queueStatus.set("running");
- yield transactions;
- queueStatus.set("idle");
+ const commands = commandQueue.dequeueAll();
+ if (commands.length > 0) {
+ queueStatus.set({ status: "running" });
+ yield* commands;
+ await pause(NEW_ENTRIES_INTERVAL);
+ // Do not switch on idle state until there is possibility that queue is not empty
+ continue;
}
+ queueStatus.set({ status: "idle" });
await pause(NEW_ENTRIES_INTERVAL);
}
};
const retry = async function* () {
let failedAttempts = 0;
+ let delay = INTERVAL_ERROR;
+
while (true) {
yield;
failedAttempts += 1;
if (failedAttempts < MAX_RETRY_RECOVERY) {
- queueStatus.set("recovering");
+ queueStatus.set({ status: "recovering" });
await pause(INTERVAL_RECOVERY);
} else {
- queueStatus.set("failed");
- await pause(INTERVAL_ERROR);
+ queueStatus.set({ status: "failed" });
+
+ // Clamped exponential backoff with decorrelated jitter
+ // to prevent clients from sending simultaneous requests after server issues
+ delay = getRandomBetween(INTERVAL_ERROR, delay * 3);
+ delay = Math.min(delay, MAX_INTERVAL_ERROR);
+
+ await pause(delay);
}
}
};
-const syncServer = async function ({
- authToken,
- buildId,
- projectId,
- lastVersion,
-}: {
- buildId: Build["id"];
- projectId: Project["id"];
- authToken: string | undefined;
- lastVersion: number;
-}) {
- polling: for await (const transactions of pollTransactions()) {
+let syncServerIsRunning = false;
+
+const syncServer = async function () {
+ if (syncServerIsRunning) {
+ return;
+ }
+
+ syncServerIsRunning = true;
+
+ const detailsMap = new Map<
+ Project["id"],
+ { version: number; buildId: Build["id"]; authToken: string | undefined }
+ >();
+
+ polling: for await (const command of pollCommands()) {
+ if (command.type === "setDetails") {
+ // At this moment we can be sure that all transactions for the command.projectId is already synchronized
+ // There are 2 options
+ // - Project opened again before transactions synchronized,
+ // in that case project is outdated and we need to ask user to reload it.
+ // - Project opened after sync, everything is ok.
+ if (command.version < (detailsMap.get(command.projectId)?.version ?? 0)) {
+ const error =
+ "The project is outdated. Synchronization was incomplete when the project was opened. " +
+ "Please reload the page to get the latest version.";
+ const shouldReload = confirm(error);
+
+ if (shouldReload) {
+ location.reload();
+ }
+
+ // stop synchronization and wait til user reload
+ queueStatus.set({ status: "fatal", error });
+
+ if (shouldReload === false) {
+ toast.error(
+ "Synchronization has been paused. Please reload to continue.",
+ { id: "outdated-error", duration: Number.POSITIVE_INFINITY }
+ );
+ }
+
+ break polling;
+ }
+
+ detailsMap.set(command.projectId, {
+ version: command.version,
+ buildId: command.buildId,
+ authToken: command.authToken,
+ });
+ continue;
+ }
+
+ const { projectId, transactions } = command;
+ const details = detailsMap.get(projectId);
+
+ if (details === undefined) {
+ const error =
+ "Project details not found. Synchronization has been paused. Please reload to continue.";
+
+ toast.error(error, {
+ id: "details-error",
+ duration: Number.POSITIVE_INFINITY,
+ });
+
+ queueStatus.set({ status: "fatal", error });
+
+ return;
+ }
+
+ // We don't know how to handle api errors. Like parsing errors, etc.
+ // Let
+ let apiErrorCount = 0;
+
for await (const _ of retry()) {
// in case of any error continue retrying
try {
- const response = await fetch(restPatchPath({ authToken }), {
- method: "post",
- body: JSON.stringify({
- transactions,
- buildId,
- projectId,
- // provide latest stored version to server
- version: lastVersion,
- }),
- });
+ const response = await fetch(
+ restPatchPath({ authToken: details.authToken }),
+ {
+ method: "post",
+ body: JSON.stringify({
+ transactions,
+ buildId: details.buildId,
+ projectId,
+ // provide latest stored version to server
+ version: details.version,
+ }),
+ }
+ );
+
if (response.ok) {
const result = await response.json();
if (result.status === "ok") {
- lastVersion += 1;
+ details.version += 1;
// stop retrying and wait next transactions
continue polling;
}
// when versions mismatched ask user to reload
// user may cancel to copy own state before reloading
if (result.status === "version_mismatched") {
- const shouldReload = confirm(
+ const error =
"You are currently in single-player mode. " +
- "The project has been edited in a different tab, browser, or by another user. " +
- "Please reload the page to get the latest version."
- );
+ "The project has been edited in a different tab, browser, or by another user. " +
+ "Please reload the page to get the latest version.";
+
+ const shouldReload = confirm(error);
if (shouldReload) {
location.reload();
}
+
+ queueStatus.set({ status: "fatal", error });
+
+ if (shouldReload === false) {
+ toast.error(
+ "Synchronization has been paused. Please reload to continue.",
+ { duration: Number.POSITIVE_INFINITY }
+ );
+ }
+
// stop synchronization and wait til user reload
break polling;
}
+
+ if (apiErrorCount >= MAX_ALLOWED_API_ERRORS) {
+ const error = `Fatal error. ${
+ result.errors ?? JSON.stringify(result.errors)
+ } Synchronization has been paused.`;
+ // Api error we don't know how to handle, as retries will not help probably
+ // We should show error and break synchronization
+ queueStatus.set({ status: "fatal", error });
+
+ toast.error(error, {
+ id: "fatal-error",
+ duration: Number.POSITIVE_INFINITY,
+ });
+
+ break polling;
+ }
+
+ apiErrorCount += 1;
+ } else {
+ // Various 500 responses, from proxies etc
+ // It's usually ok to be here, probably restorable with retries
+ const text = await response.text();
+ // To investigate some strange errors we have seen
+ // eslint-disable-next-line no-console
+ console.info(`Non ok respone: ${text}`);
+ }
+ } catch (e) {
+ if (navigator.onLine) {
+ // ERR_CONNECTION_REFUSED or like, probably restorable with retries
+ // anyway lets's log it
+ // eslint-disable-next-line no-console
+ console.info(e instanceof Error ? e.message : JSON.stringify(e));
}
- } catch {
- //
}
}
}
};
+const useSyncProject = async ({
+ projectId,
+ buildId,
+ version,
+ authPermit,
+ authToken,
+}: {
+ buildId: Build["id"];
+ projectId: Project["id"];
+ authToken: string | undefined;
+ version: number;
+ authPermit: AuthPermit;
+}) => {
+ useEffect(() => {
+ if (authPermit === "view") {
+ return;
+ }
+ syncServer();
+
+ commandQueue.enqueue({
+ type: "setDetails",
+ projectId,
+ buildId,
+ version,
+ authToken,
+ });
+
+ const updateProjectTransactions = () => {
+ const transactions = sync();
+ if (transactions.length === 0) {
+ return;
+ }
+ commandQueue.enqueue({ type: "transactions", transactions, projectId });
+ };
+
+ const intervalHandle = setInterval(
+ updateProjectTransactions,
+ NEW_ENTRIES_INTERVAL
+ );
+
+ return () => {
+ updateProjectTransactions();
+ clearInterval(intervalHandle);
+ };
+ }, [authPermit, authToken, buildId, projectId, version]);
+};
+
type SyncServerProps = {
buildId: Build["id"];
projectId: Project["id"];
@@ -125,18 +303,18 @@ export const useSyncServer = ({
authPermit,
version,
}: SyncServerProps) => {
- // save the initial version from loaded build
- const initialized = useRef(false);
- useEffect(() => {
- if (authPermit === "view" || initialized.current === true) {
- return;
- }
- initialized.current = true;
- syncServer({ buildId, projectId, authToken, lastVersion: version });
- }, [buildId, projectId, authToken, authPermit, version]);
+ useSyncProject({
+ buildId,
+ projectId,
+ authToken,
+ version,
+ authPermit,
+ });
useBeforeUnload(
- () => queueStatus.get() !== "idle",
+ () =>
+ queueStatus.get().status !== "idle" &&
+ queueStatus.get().status !== "fatal",
"You have unsaved changes. Are you sure you want to leave?"
);
};
diff --git a/apps/builder/app/routes/rest.patch.ts b/apps/builder/app/routes/rest.patch.ts
index c6ad207988..3b490e6e07 100644
--- a/apps/builder/app/routes/rest.patch.ts
+++ b/apps/builder/app/routes/rest.patch.ts
@@ -44,226 +44,232 @@ type PatchData = {
};
export const action = async ({ request }: ActionArgs) => {
- const {
- buildId,
- projectId,
- transactions,
- version: clientVersion,
- }: PatchData = await request.json();
- if (buildId === undefined) {
- return { errors: "Build id required" };
- }
- if (projectId === undefined) {
- return { errors: "Project id required" };
- }
+ try {
+ const {
+ buildId,
+ projectId,
+ transactions,
+ version: clientVersion,
+ }: PatchData = await request.json();
+ if (buildId === undefined) {
+ return { errors: "Build id required" };
+ }
+ if (projectId === undefined) {
+ return { errors: "Project id required" };
+ }
- const context = await createContext(request);
- const canEdit = await authorizeProject.hasProjectPermit(
- { projectId, permit: "edit" },
- context
- );
- if (canEdit === false) {
- throw Error("You don't have edit access to this project");
- }
+ const context = await createContext(request);
+ const canEdit = await authorizeProject.hasProjectPermit(
+ { projectId, permit: "edit" },
+ context
+ );
+ if (canEdit === false) {
+ throw Error("You don't have edit access to this project");
+ }
- const build = await prisma.build.findUnique({
- where: { id_projectId: { projectId, id: buildId } },
- });
- if (build === null) {
- throw Error(`Build ${buildId} not found`);
- }
+ // await new Promise((r) => setTimeout(r, 10000));
- const serverVersion = build.version;
- if (clientVersion !== serverVersion) {
- return {
- status: "version_mismatched",
- };
- }
+ const build = await prisma.build.findUnique({
+ where: { id_projectId: { projectId, id: buildId } },
+ });
+ if (build === null) {
+ throw Error(`Build ${buildId} not found`);
+ }
- const buildData: {
- pages?: Pages;
- breakpoints?: Breakpoints;
- instances?: Instances;
- props?: Props;
- dataSources?: DataSources;
- styleSources?: StyleSources;
- styleSourceSelections?: StyleSourceSelections;
- styles?: Styles;
- } = {};
-
- const skipValidation = true;
-
- // Used to optimize by validating only changed styles, as they accounted for 99% of validation time
- const patchedStyleDeclKeysSet = new Set<string>();
-
- for await (const transaction of transactions) {
- for await (const change of transaction.changes) {
- const { namespace, patches } = change;
- if (patches.length === 0) {
- continue;
- }
+ const serverVersion = build.version;
+ if (clientVersion !== serverVersion) {
+ return {
+ status: "version_mismatched",
+ };
+ }
- if (namespace === "pages") {
- // lazily parse build data before patching
- const pages =
- buildData.pages ?? parsePages(build.pages, skipValidation);
- buildData.pages = applyPatches(pages, patches);
- continue;
- }
+ const buildData: {
+ pages?: Pages;
+ breakpoints?: Breakpoints;
+ instances?: Instances;
+ props?: Props;
+ dataSources?: DataSources;
+ styleSources?: StyleSources;
+ styleSourceSelections?: StyleSourceSelections;
+ styles?: Styles;
+ } = {};
+
+ const skipValidation = true;
+
+ // Used to optimize by validating only changed styles, as they accounted for 99% of validation time
+ const patchedStyleDeclKeysSet = new Set<string>();
+
+ for await (const transaction of transactions) {
+ for await (const change of transaction.changes) {
+ const { namespace, patches } = change;
+ if (patches.length === 0) {
+ continue;
+ }
- if (namespace === "instances") {
- const instances =
- buildData.instances ??
- parseInstances(build.instances, skipValidation);
- buildData.instances = applyPatches(instances, patches);
- continue;
- }
+ if (namespace === "pages") {
+ // lazily parse build data before patching
+ const pages =
+ buildData.pages ?? parsePages(build.pages, skipValidation);
+ buildData.pages = applyPatches(pages, patches);
+ continue;
+ }
+
+ if (namespace === "instances") {
+ const instances =
+ buildData.instances ??
+ parseInstances(build.instances, skipValidation);
+ buildData.instances = applyPatches(instances, patches);
+ continue;
+ }
- if (namespace === "styleSourceSelections") {
- const styleSourceSelections =
- buildData.styleSourceSelections ??
- parseStyleSourceSelections(
- build.styleSourceSelections,
- skipValidation
+ if (namespace === "styleSourceSelections") {
+ const styleSourceSelections =
+ buildData.styleSourceSelections ??
+ parseStyleSourceSelections(
+ build.styleSourceSelections,
+ skipValidation
+ );
+ buildData.styleSourceSelections = applyPatches(
+ styleSourceSelections,
+ patches
);
- buildData.styleSourceSelections = applyPatches(
- styleSourceSelections,
- patches
- );
- continue;
- }
+ continue;
+ }
- if (namespace === "styleSources") {
- const styleSources =
- buildData.styleSources ??
- parseStyleSources(build.styleSources, skipValidation);
- buildData.styleSources = applyPatches(styleSources, patches);
- continue;
- }
+ if (namespace === "styleSources") {
+ const styleSources =
+ buildData.styleSources ??
+ parseStyleSources(build.styleSources, skipValidation);
+ buildData.styleSources = applyPatches(styleSources, patches);
+ continue;
+ }
- if (namespace === "styles") {
- // It's somehow implementation detail leak, as we use the fact that styles patches has ids in path
- for (const patch of patches) {
- patchedStyleDeclKeysSet.add(`${patch.path[0]}`);
+ if (namespace === "styles") {
+ // It's somehow implementation detail leak, as we use the fact that styles patches has ids in path
+ for (const patch of patches) {
+ patchedStyleDeclKeysSet.add(`${patch.path[0]}`);
+ }
+
+ const styles =
+ buildData.styles ?? parseStyles(build.styles, skipValidation);
+ buildData.styles = applyPatches(styles, patches);
+ continue;
}
- const styles =
- buildData.styles ?? parseStyles(build.styles, skipValidation);
- buildData.styles = applyPatches(styles, patches);
- continue;
- }
+ if (namespace === "props") {
+ const props =
+ buildData.props ?? parseProps(build.props, skipValidation);
+ buildData.props = applyPatches(props, patches);
+ continue;
+ }
- if (namespace === "props") {
- const props =
- buildData.props ?? parseProps(build.props, skipValidation);
- buildData.props = applyPatches(props, patches);
- continue;
- }
+ if (namespace === "dataSources") {
+ const dataSources =
+ buildData.dataSources ?? parseDataSources(build.dataSources);
+ buildData.dataSources = applyPatches(dataSources, patches);
+ continue;
+ }
- if (namespace === "dataSources") {
- const dataSources =
- buildData.dataSources ?? parseDataSources(build.dataSources);
- buildData.dataSources = applyPatches(dataSources, patches);
- continue;
- }
+ if (namespace === "breakpoints") {
+ const breakpoints =
+ buildData.breakpoints ??
+ parseBreakpoints(build.breakpoints, skipValidation);
+ buildData.breakpoints = applyPatches(breakpoints, patches);
+ continue;
+ }
- if (namespace === "breakpoints") {
- const breakpoints =
- buildData.breakpoints ??
- parseBreakpoints(build.breakpoints, skipValidation);
- buildData.breakpoints = applyPatches(breakpoints, patches);
- continue;
- }
+ if (namespace === "assets") {
+ // assets implements own patching
+ // @todo parallelize the updates
+ // currently not possible because we fetch the entire tree
+ // and parallelized updates will cause unpredictable side effects
+ await patchAssets({ projectId }, patches, context);
+ continue;
+ }
- if (namespace === "assets") {
- // assets implements own patching
- // @todo parallelize the updates
- // currently not possible because we fetch the entire tree
- // and parallelized updates will cause unpredictable side effects
- await patchAssets({ projectId }, patches, context);
- continue;
+ return { errors: `Unknown namespace "${namespace}"` };
}
-
- return { errors: `Unknown namespace "${namespace}"` };
}
- }
- // save build data when all patches applied
- const dbBuildData: Parameters<typeof prisma.build.update>[0]["data"] = {
- version: clientVersion + 1,
- };
+ // save build data when all patches applied
+ const dbBuildData: Parameters<typeof prisma.build.update>[0]["data"] = {
+ version: clientVersion + 1,
+ };
- if (buildData.pages) {
- // parse with zod before serialization to avoid saving invalid data
- dbBuildData.pages = serializePages(Pages.parse(buildData.pages));
- }
+ if (buildData.pages) {
+ // parse with zod before serialization to avoid saving invalid data
+ dbBuildData.pages = serializePages(Pages.parse(buildData.pages));
+ }
- if (buildData.breakpoints) {
- dbBuildData.breakpoints = serializeBreakpoints(
- Breakpoints.parse(buildData.breakpoints)
- );
- }
+ if (buildData.breakpoints) {
+ dbBuildData.breakpoints = serializeBreakpoints(
+ Breakpoints.parse(buildData.breakpoints)
+ );
+ }
- if (buildData.instances) {
- dbBuildData.instances = serializeInstances(
- Instances.parse(buildData.instances)
- );
- }
+ if (buildData.instances) {
+ dbBuildData.instances = serializeInstances(
+ Instances.parse(buildData.instances)
+ );
+ }
- if (buildData.props) {
- dbBuildData.props = serializeProps(Props.parse(buildData.props));
- }
+ if (buildData.props) {
+ dbBuildData.props = serializeProps(Props.parse(buildData.props));
+ }
- if (buildData.dataSources) {
- dbBuildData.dataSources = serializeDataSources(
- DataSources.parse(buildData.dataSources)
- );
- }
+ if (buildData.dataSources) {
+ dbBuildData.dataSources = serializeDataSources(
+ DataSources.parse(buildData.dataSources)
+ );
+ }
- if (buildData.styleSources) {
- dbBuildData.styleSources = serializeStyleSources(
- StyleSources.parse(buildData.styleSources)
- );
- }
- if (buildData.styleSourceSelections) {
- dbBuildData.styleSourceSelections = serializeStyleSourceSelections(
- StyleSourceSelections.parse(buildData.styleSourceSelections)
- );
- }
+ if (buildData.styleSources) {
+ dbBuildData.styleSources = serializeStyleSources(
+ StyleSources.parse(buildData.styleSources)
+ );
+ }
+ if (buildData.styleSourceSelections) {
+ dbBuildData.styleSourceSelections = serializeStyleSourceSelections(
+ StyleSourceSelections.parse(buildData.styleSourceSelections)
+ );
+ }
+
+ if (buildData.styles) {
+ // Optimize by validating only changed styles, as they accounted for 99% of validation time
+ const stylesToValidate: Styles = new Map();
+ for (const styleId of patchedStyleDeclKeysSet) {
+ const style = buildData.styles.get(styleId);
+ // In case of deletion style could be undefined
+ if (style === undefined) {
+ continue;
+ }
- if (buildData.styles) {
- // Optimize by validating only changed styles, as they accounted for 99% of validation time
- const stylesToValidate: Styles = new Map();
- for (const styleId of patchedStyleDeclKeysSet) {
- const style = buildData.styles.get(styleId);
- // In case of deletion style could be undefined
- if (style === undefined) {
- continue;
+ stylesToValidate.set(styleId, style);
}
- stylesToValidate.set(styleId, style);
- }
+ Styles.parse(stylesToValidate);
- Styles.parse(stylesToValidate);
+ dbBuildData.styles = serializeStyles(buildData.styles);
+ }
- dbBuildData.styles = serializeStyles(buildData.styles);
- }
+ const { count } = await prisma.build.updateMany({
+ data: dbBuildData,
+ where: {
+ projectId,
+ id: buildId,
+ version: clientVersion,
+ },
+ });
+ // ensure only build with client version is updated
+ // to avoid race conditions
+ if (count === 0) {
+ return {
+ status: "version_mismatched",
+ };
+ }
- const { count } = await prisma.build.updateMany({
- data: dbBuildData,
- where: {
- projectId,
- id: buildId,
- version: clientVersion,
- },
- });
- // ensure only build with client version is updated
- // to avoid race conditions
- if (count === 0) {
- return {
- status: "version_mismatched",
- };
+ return { status: "ok" };
+ } catch (e) {
+ return { errors: e instanceof Error ? e.message : JSON.stringify(e) };
}
-
- return { status: "ok" };
};
diff --git a/packages/design-system/src/components/toast.tsx b/packages/design-system/src/components/toast.tsx
index a696b74c40..39a090efe6 100644
--- a/packages/design-system/src/components/toast.tsx
+++ b/packages/design-system/src/components/toast.tsx
@@ -100,12 +100,18 @@ export const Toaster = () => {
const { startPause, endPause } = handlers;
return (
<ToastPrimitive.ToastProvider>
- {toasts.map((toast) => (
+ {toasts.map((toastData) => (
<StyledToast
- variant={toast.type}
- key={toast.id}
+ variant={toastData.type}
+ key={toastData.id}
onMouseEnter={startPause}
onMouseLeave={endPause}
+ onClick={() => {
+ // To give a way to dismiss the infinite toast
+ if (toastData.duration === Number.POSITIVE_INFINITY) {
+ toast.dismiss(toastData.id);
+ }
+ }}
>
<Box
css={{
@@ -115,9 +121,11 @@ export const Toaster = () => {
},
}}
>
- {toast.type === "blank" && <InfoIcon />}
+ {toastData.type === "blank" && <InfoIcon />}
</Box>
- <StyledTitle>{resolveValue(toast.message, toast)}</StyledTitle>
+ <StyledTitle>
+ {resolveValue(toastData.message, toastData)}
+ </StyledTitle>
</StyledToast>
))}
<StyledViewport />