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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: Fix asset limit count visible assets (#5731)
Oleg Isonene9a2733691c9
diff --git a/apps/builder/app/builder/shared/assets/upload-assets.tsx b/apps/builder/app/builder/shared/assets/upload-assets.tsxindex 245bd7f13f..a6ace1c756 100644--- a/apps/builder/app/builder/shared/assets/upload-assets.tsx+++ b/apps/builder/app/builder/shared/assets/upload-assets.tsx@@ -145,6 +145,7 @@ const deduplicateAssetName = (name: string, existingNames: Set<string>) => {const uploadAsset = async ({authToken,projectId,+ assetId,fileOrUrl,assetType,onCompleted,@@ -152,6 +153,7 @@ const uploadAsset = async ({}: {authToken: undefined | string;projectId: string;+ assetId: Asset["id"];fileOrUrl: File | URL;assetType: AssetType;onCompleted: (data: AssetActionResponse) => void;@@ -162,6 +164,7 @@ const uploadAsset = async ({const fileName = getFileName(fileOrUrl);const metaFormData = new FormData();+ metaFormData.append("assetId", assetId);metaFormData.append("projectId", projectId);metaFormData.append("type", assetType);// sanitizeS3Key here is just because of https://github.com/remix-run/remix/issues/4443@@ -319,6 +322,7 @@ const processUpload = async (await uploadAsset({authToken,projectId,+ assetId,fileOrUrl:fileData.source === "file" ? fileData.file : new URL(fileData.url),assetType: fileData.type,diff --git a/apps/builder/app/routes/rest.assets.tsx b/apps/builder/app/routes/rest.assets.tsxindex 6e27c35f9b..1e5c25a25a 100644--- a/apps/builder/app/routes/rest.assets.tsx+++ b/apps/builder/app/routes/rest.assets.tsx@@ -34,14 +34,21 @@ export const action = async (props: ActionFunctionArgs) => {if (request.method === "POST") {const formData = await request.formData();- const projectId = formData.get("projectId") as string;- const type = formData.get("type") as string;- const filename = formData.get("filename") as string;- if (projectId === null || type === null || filename === null) {+ const assetId = formData.get("assetId");+ const projectId = formData.get("projectId");+ const type = formData.get("type");+ const filename = formData.get("filename");+ if (+ typeof assetId !== "string" ||+ typeof projectId !== "string" ||+ typeof type !== "string" ||+ typeof filename !== "string"+ ) {throw Error("Project id, asset id or filename are missing");}const name = await createUploadName({+ assetId,projectId,type,filename,diff --git a/packages/asset-uploader/src/upload.test.ts b/packages/asset-uploader/src/upload.test.tsnew file mode 100644index 0000000000..2bc83d7438--- /dev/null+++ b/packages/asset-uploader/src/upload.test.ts@@ -0,0 +1,100 @@+import { describe, expect, test } from "vitest";+import {+ createTestServer,+ db,+ empty,+ json,+ testContext,+} from "@webstudio-is/postgrest/testing";+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";+import { createUploadName } from "./upload";++const server = createTestServer();++const createContext = (): AppContext =>+ ({+ ...testContext,+ authorization: { type: "user", userId: "user-1" },+ getOwnerPlanFeatures: () => Promise.resolve({}),+ }) as unknown as AppContext;++const ownershipHandler = db.get("Project", ({ request }) => {+ const url = new URL(request.url);+ if (url.searchParams.has("userId")) {+ return json({ id: url.searchParams.get("id")?.replace("eq.", "") });+ }+ return json(null);+});++describe("createUploadName", () => {+ test("counts assets instead of uploaded files for the project limit", async () => {+ let insertedFile: unknown;++ server.use(+ ownershipHandler,+ db.head("Asset", ({ request }) => {+ const url = new URL(request.url);+ expect(url.searchParams.get("projectId")).toBe("eq.project-1");+ expect(url.searchParams.get("file.status")).toBe("eq.UPLOADED");+ return empty({ headers: { "Content-Range": "*/90" } });+ }),+ db.head("File", ({ request }) => {+ const url = new URL(request.url);+ expect(url.searchParams.get("uploaderProjectId")).toBe("eq.project-1");+ expect(url.searchParams.get("status")).toBe("eq.UPLOADING");+ return empty({ headers: { "Content-Range": "*/0" } });+ }),+ db.post("File", async ({ request }) => {+ insertedFile = await request.json();+ return empty({ status: 201 });+ }),+ db.post("Asset", async ({ request }) => {+ expect(await request.json()).toEqual({+ id: "asset-1",+ projectId: "project-1",+ name: expect.stringMatching(/^photo_.+\.png$/),+ });+ return empty({ status: 201 });+ })+ );++ const name = await createUploadName(+ {+ assetId: "asset-1",+ projectId: "project-1",+ type: "image/png",+ filename: "photo.png",+ maxAssetsPerProject: 350,+ },+ createContext()+ );++ expect(name).toMatch(/^photo_.+\.png$/);+ expect(insertedFile).toMatchObject({+ name,+ status: "UPLOADING",+ uploaderProjectId: "project-1",+ });+ });++ test("throws when uploaded assets and recent uploads reach the limit", async () => {+ server.use(+ ownershipHandler,+ db.head("Asset", () => empty({ headers: { "Content-Range": "*/349" } })),+ db.head("File", () => empty({ headers: { "Content-Range": "*/1" } }))+ );++ await expect(+ createUploadName(+ {+ assetId: "asset-2",+ projectId: "project-2",+ type: "image/png",+ filename: "photo.png",+ maxAssetsPerProject: 350,+ },+ createContext()+ )+ ).rejects.toThrow("The maximum number of assets per project is 350.");+ });+});diff --git a/packages/asset-uploader/src/upload.ts b/packages/asset-uploader/src/upload.tsindex 993407457b..bb26fde1b7 100644--- a/packages/asset-uploader/src/upload.ts+++ b/packages/asset-uploader/src/upload.ts@@ -10,6 +10,7 @@ import { sanitizeS3Key } from "./utils/sanitize-s3-key";import { formatAsset } from "./utils/format-asset";type UploadData = {+ assetId: Asset["id"];projectId: string;type: string;filename: string;@@ -22,7 +23,7 @@ export const createUploadName = async (data: UploadData,context: AppContext): Promise<string> => {- const { projectId, maxAssetsPerProject, type, filename } = data;+ const { assetId, projectId, maxAssetsPerProject, type, filename } = data;const canEdit = await authorizeProject.hasProjectPermit({ projectId, permit: "edit" },context@@ -39,12 +40,11 @@ export const createUploadName = async (* than UPLOADING_STALE_TIMEOUT milliseconds ago**/- const uploadedCount = await context.postgrest.client- .from("File")- .select("*", { count: "exact", head: true })- .eq("isDeleted", false)- .eq("uploaderProjectId", projectId)- .eq("status", "UPLOADED");+ const assetCount = await context.postgrest.client+ .from("Asset")+ .select("id, file:File!inner(status)", { count: "exact", head: true })+ .eq("projectId", projectId)+ .eq("file.status", "UPLOADED");const uploadingCount = await context.postgrest.client.from("File")@@ -57,11 +57,11 @@ export const createUploadName = async (new Date(Date.now() - UPLOADING_STALE_TIMEOUT).toISOString());- const count = (uploadedCount.count ?? 0) + (uploadingCount.count ?? 0);+ const count = (assetCount.count ?? 0) + (uploadingCount.count ?? 0);if (count >= maxAssetsPerProject) {/**- * Here is right to write `Max ${MAX_ASSETS_PER_PROJECT}` but see the comment below,+ * Here is right to write `Max ${maxAssetsPerProject}` but see the comment below,* it's probable that the user can exceed the limit a little bit.* So it can be a little bit strange that the limit is 5 but the user already has 7.**/@@ -73,7 +73,7 @@ export const createUploadName = async (/*** Create a temporary "UPLOADING" asset, so it can be counted in the next query* Assumptions:- * - it's possible to create more assets than MAX_ASSETS_PER_PROJECT,+ * - it's possible to create more assets than maxAssetsPerProject,* but for now we assume that the time since the `count` query above and the `create` query below is negligible,* and some kind of rate limiting exists on API.* Also no locking exists in Prisma, and no raw query locking like@@ -81,7 +81,7 @@ export const createUploadName = async (**/const name = getUniqueFilename(sanitizeS3Key(filename));- await context.postgrest.client.from("File").insert({+ const fileInsert = await context.postgrest.client.from("File").insert({name,status: "UPLOADING",// store content type in related field@@ -89,6 +89,20 @@ export const createUploadName = async (size: 0,uploaderProjectId: projectId,});+ if (fileInsert.error) {+ throw new Error(fileInsert.error.message);+ }++ const assetInsert = await context.postgrest.client.from("Asset").insert({+ id: assetId,+ projectId,+ name,+ });+ if (assetInsert.error) {+ await context.postgrest.client.from("File").delete().eq("name", name);+ throw new Error(assetInsert.error.message);+ }+return name;};@@ -146,6 +160,7 @@ export const uploadFile = async (file: file.data,});} catch (error) {+ await context.postgrest.client.from("Asset").delete().eq("name", name);await context.postgrest.client.from("File").delete().eq("name", name);throw error;