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.

Prevent user from editing outdated builds (#1682)

Bogdan Chadkinfe00228f7e0b
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsx
index b62b787846..65294e43e5 100644
--- a/apps/builder/app/builder/builder.tsx
+++ b/apps/builder/app/builder/builder.tsx
@@ -276,6 +276,7 @@ export const Builder = ({
projectId: project.id,
authToken,
authPermit,
+ version: build.version,
});
useSharedShortcuts({ source: "builder" });
useSetIsPreviewMode(authPermit === "view");
diff --git a/apps/builder/app/builder/shared/sync/queue.test.ts b/apps/builder/app/builder/shared/sync/queue.test.ts
index a007917915..81e0a5172d 100644
--- a/apps/builder/app/builder/shared/sync/queue.test.ts
+++ b/apps/builder/app/builder/shared/sync/queue.test.ts
@@ -26,7 +26,7 @@ describe("queue", () => {
});
test("enqueue with failure", async () => {
- enqueue(() => Promise.resolve({ ok: false }));
+ enqueue(() => Promise.resolve({ ok: false, retry: true }));
const jobPromise = dequeue();
expect(queueStatus.get()).toBe("running");
expect(state.failedAttempts).toBe(0);
@@ -40,7 +40,13 @@ describe("queue", () => {
test("recovering > failed > idle", async () => {
let response = Promise.resolve({ ok: false });
- await enqueue(() => response);
+ await enqueue(async () => {
+ const { ok } = await response;
+ if (ok) {
+ return { ok: true };
+ }
+ return { ok: false, retry: true };
+ });
expect(queueStatus.get()).toBe("recovering");
diff --git a/apps/builder/app/builder/shared/sync/queue.ts b/apps/builder/app/builder/shared/sync/queue.ts
index de4c518bfb..3a307cfdfd 100644
--- a/apps/builder/app/builder/shared/sync/queue.ts
+++ b/apps/builder/app/builder/shared/sync/queue.ts
@@ -5,7 +5,7 @@ const MAX_RETRY_RECOVERY = 5;
export type QueueStatus = "running" | "idle" | "recovering" | "failed";
-type BaseResult = { ok: boolean };
+type BaseResult = { ok: true } | { ok: false; retry: boolean };
export const queueStatus = atom<QueueStatus>("idle");
@@ -50,7 +50,9 @@ export const dequeue = () => {
return job()
.then((result) => {
if (result.ok === false) {
- throw Error("Bad response");
+ if (result.retry) {
+ throw Error("Bad response");
+ }
}
state.failedAttempts = 0;
queueStatus.set(getStatus("end"));
diff --git a/apps/builder/app/builder/shared/sync/sync-server.ts b/apps/builder/app/builder/shared/sync/sync-server.ts
index 924ebe1be5..6acb7b37bb 100644
--- a/apps/builder/app/builder/shared/sync/sync-server.ts
+++ b/apps/builder/app/builder/shared/sync/sync-server.ts
@@ -40,11 +40,14 @@ const useErrorCheck = () => {
}, []);
};
+let lastVersion: undefined | number = undefined;
+
const useNewEntriesCheck = ({
buildId,
projectId,
authToken,
authPermit,
+ version,
}: UserSyncServerProps) => {
useEffect(() => {
if (authPermit === "view") {
@@ -62,20 +65,47 @@ const useNewEntriesCheck = ({
return;
}
- enqueue(() =>
- fetch(restPatchPath({ authToken }), {
+ enqueue(async () => {
+ // save the initial version from loaded build
+ if (lastVersion === undefined) {
+ lastVersion = version;
+ }
+ const response = await fetch(restPatchPath({ authToken }), {
method: "post",
body: JSON.stringify({
transactions,
buildId,
projectId,
+ // provide latest stored version to server
+ version: lastVersion,
}),
- })
- );
+ });
+ if (response.ok) {
+ const result = await response.json();
+ if (result.status === "ok") {
+ lastVersion += 1;
+ return { ok: true };
+ }
+ // when versions mismatched ask user to reload
+ // user may cancel to copy own state before reloading
+ if (result.status === "version_mismatched") {
+ const shouldReload = confirm(
+ "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."
+ );
+ if (shouldReload) {
+ location.reload();
+ }
+ return { ok: false, retry: false };
+ }
+ }
+ return { ok: false, retry: true };
+ });
}, NEW_ENTRIES_INTERVAL);
return () => clearInterval(intervalId);
- }, [buildId, projectId, authToken, authPermit]);
+ }, [buildId, projectId, authToken, authPermit, version]);
};
type UserSyncServerProps = {
@@ -83,6 +113,7 @@ type UserSyncServerProps = {
projectId: Project["id"];
authToken: string | undefined;
authPermit: AuthPermit;
+ version: number;
};
export const useSyncServer = (props: UserSyncServerProps) => {
diff --git a/apps/builder/app/routes/rest.patch.ts b/apps/builder/app/routes/rest.patch.ts
index c722868fff..f6709ae3a8 100644
--- a/apps/builder/app/routes/rest.patch.ts
+++ b/apps/builder/app/routes/rest.patch.ts
@@ -1,3 +1,4 @@
+import { applyPatches } from "immer";
import type { ActionArgs } from "@remix-run/node";
import type { SyncItem } from "immerhin";
import { prisma } from "@webstudio-is/prisma-client";
@@ -29,18 +30,23 @@ import {
} from "@webstudio-is/project-build/index.server";
import { patchAssets } from "@webstudio-is/asset-uploader/index.server";
import type { Project } from "@webstudio-is/project";
-import { createContext } from "~/shared/context.server";
import { authorizeProject } from "@webstudio-is/trpc-interface/index.server";
-import { applyPatches } from "immer";
+import { createContext } from "~/shared/context.server";
type PatchData = {
transactions: Array<SyncItem>;
buildId: Build["id"];
projectId: Project["id"];
+ version: number;
};
export const action = async ({ request }: ActionArgs) => {
- const { buildId, projectId, transactions }: PatchData = await request.json();
+ const {
+ buildId,
+ projectId,
+ transactions,
+ version: clientVersion,
+ }: PatchData = await request.json();
if (buildId === undefined) {
return { errors: "Build id required" };
}
@@ -64,6 +70,13 @@ export const action = async ({ request }: ActionArgs) => {
throw Error(`Build ${buildId} not found`);
}
+ const serverVersion = build.version;
+ if (clientVersion !== serverVersion) {
+ return {
+ status: "version_mismatched",
+ };
+ }
+
const buildData: {
pages?: Pages;
breakpoints?: Breakpoints;
@@ -165,7 +178,10 @@ export const action = async ({ request }: ActionArgs) => {
}
// save build data when all patches applied
- const dbBuildData: Parameters<typeof prisma.build.update>[0]["data"] = {};
+ 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));
@@ -216,14 +232,20 @@ export const action = async ({ request }: ActionArgs) => {
dbBuildData.styles = serializeStyles(buildData.styles);
}
- // check any build data is changed because only assets could change
- if (Object.keys(dbBuildData).length > 0) {
- await prisma.build.update({
- data: dbBuildData,
- where: {
- id_projectId: { projectId, id: buildId },
- },
- });
+ 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" };
diff --git a/packages/prisma-client/prisma/migrations/20230529133454_build_version/migration.sql b/packages/prisma-client/prisma/migrations/20230529133454_build_version/migration.sql
new file mode 100644
index 0000000000..a4da59df85
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230529133454_build_version/migration.sql
@@ -0,0 +1,3 @@
+-- AlterTable
+ALTER TABLE "Build" ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ADD COLUMN "version" INTEGER NOT NULL DEFAULT 0;
diff --git a/packages/prisma-client/prisma/schema.prisma b/packages/prisma-client/prisma/schema.prisma
index d42fe3cfd4..15a80d24c1 100644
--- a/packages/prisma-client/prisma/schema.prisma
+++ b/packages/prisma-client/prisma/schema.prisma
@@ -93,7 +93,9 @@ model Project {
model Build {
id String @default(uuid())
+ version Int @default(0)
createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
pages String
project Project @relation(fields: [projectId], references: [id])
diff --git a/packages/project-build/src/db/build.ts b/packages/project-build/src/db/build.ts
index 69a3b67899..2fd100867a 100644
--- a/packages/project-build/src/db/build.ts
+++ b/packages/project-build/src/db/build.ts
@@ -55,6 +55,7 @@ const parseBuild = async (build: DbBuild): Promise<Build> => {
return {
id: build.id,
projectId: build.projectId,
+ version: build.version,
isDev: build.isDev,
isProd: build.isProd,
createdAt: build.createdAt.toISOString(),
diff --git a/packages/project-build/src/types.ts b/packages/project-build/src/types.ts
index ab37ab7c55..48c539cae2 100644
--- a/packages/project-build/src/types.ts
+++ b/packages/project-build/src/types.ts
@@ -9,6 +9,7 @@ import type { StyleSourceSelection } from "./schema/style-source-selections";
export type Build = {
id: string;
projectId: string;
+ version: number;
createdAt: string;
isDev: boolean;
isProd: boolean;