diff options
| author | Mohamed Bassem <me@mbassem.com> | 2025-09-06 06:24:05 +0000 |
|---|---|---|
| committer | Mohamed Bassem <me@mbassem.com> | 2025-09-06 06:25:15 +0000 |
| commit | 3760d23abc4d02eb2c3823b8aa322f53914fd9b6 (patch) | |
| tree | 1d720b1f1d1391317185b319d1fb1fba3f18a274 /packages | |
| parent | fcfe6a53b49dc2fdff6abac876b41b52f1b0fed7 (diff) | |
| download | karakeep-3760d23abc4d02eb2c3823b8aa322f53914fd9b6.tar.zst | |
refactor: Extract quota logic into its own class
Diffstat (limited to 'packages')
| -rw-r--r-- | packages/api/utils/upload.ts | 11 | ||||
| -rw-r--r-- | packages/shared-server/package.json | 1 | ||||
| -rw-r--r-- | packages/shared-server/src/index.ts | 1 | ||||
| -rw-r--r-- | packages/shared-server/src/services/quotaService.ts | 93 | ||||
| -rw-r--r-- | packages/trpc/lib/storageQuota.ts | 57 | ||||
| -rw-r--r-- | packages/trpc/package.json | 2 | ||||
| -rw-r--r-- | packages/trpc/routers/bookmarks.ts | 33 |
7 files changed, 114 insertions, 84 deletions
diff --git a/packages/api/utils/upload.ts b/packages/api/utils/upload.ts index 6f18790b..a843e29c 100644 --- a/packages/api/utils/upload.ts +++ b/packages/api/utils/upload.ts @@ -5,6 +5,7 @@ import { Readable } from "stream"; import { pipeline } from "stream/promises"; import { assets, AssetTypes } from "@karakeep/db/schema"; +import { QuotaService, StorageQuotaError } from "@karakeep/shared-server"; import { newAssetId, saveAssetFromFile, @@ -12,10 +13,6 @@ import { } from "@karakeep/shared/assetdb"; import serverConfig from "@karakeep/shared/config"; import { AuthedContext } from "@karakeep/trpc"; -import { - checkStorageQuota, - StorageQuotaError, -} from "@karakeep/trpc/lib/storageQuota"; const MAX_UPLOAD_SIZE_BYTES = serverConfig.maxAssetSizeMb * 1024 * 1024; @@ -73,7 +70,11 @@ export async function uploadAsset( let quotaApproved; try { - quotaApproved = await checkStorageQuota(db, user.id, data.size); + quotaApproved = await QuotaService.checkStorageQuota( + db, + user.id, + data.size, + ); } catch (error) { if (error instanceof StorageQuotaError) { return { error: error.message, status: 403 }; diff --git a/packages/shared-server/package.json b/packages/shared-server/package.json index 8ac98e21..6ba6b6d9 100644 --- a/packages/shared-server/package.json +++ b/packages/shared-server/package.json @@ -5,6 +5,7 @@ "private": true, "type": "module", "dependencies": { + "@karakeep/db": "workspace:^0.1.0", "@karakeep/plugins-search-meilisearch": "workspace:^0.1.0", "@karakeep/shared": "workspace:^0.1.0" }, diff --git a/packages/shared-server/src/index.ts b/packages/shared-server/src/index.ts index a17576ad..ff3c6abc 100644 --- a/packages/shared-server/src/index.ts +++ b/packages/shared-server/src/index.ts @@ -1 +1,2 @@ export { loadAllPlugins } from "./plugins"; +export { QuotaService, StorageQuotaError } from "./services/quotaService"; diff --git a/packages/shared-server/src/services/quotaService.ts b/packages/shared-server/src/services/quotaService.ts new file mode 100644 index 00000000..a09b76bf --- /dev/null +++ b/packages/shared-server/src/services/quotaService.ts @@ -0,0 +1,93 @@ +import { count, eq, sum } from "drizzle-orm"; + +import type { DB, KarakeepDBTransaction } from "@karakeep/db"; +import { assets, bookmarks, users } from "@karakeep/db/schema"; +import { QuotaApproved } from "@karakeep/shared/storageQuota"; + +export class StorageQuotaError extends Error { + constructor( + public readonly currentUsage: number, + public readonly quota: number, + public readonly requestedSize: number, + ) { + super( + `Storage quota exceeded. Current usage: ${Math.round(currentUsage / 1024 / 1024)}MB, Quota: ${Math.round(quota / 1024 / 1024)}MB, Requested: ${Math.round(requestedSize / 1024 / 1024)}MB`, + ); + this.name = "StorageQuotaError"; + } +} + +// TODO: Change the API of this class to either return a boolean +// or throw an exception on lack of quota because now, it's inconsistent. +export class QuotaService { + // TODO: Use quota approval tokens for bookmark creation when + // bookmark creation logic is in the model. + static async canCreateBookmark(db: DB, userId: string) { + const user = await db.query.users.findFirst({ + where: eq(users.id, userId), + columns: { + bookmarkQuota: true, + }, + }); + + if (user?.bookmarkQuota !== null && user?.bookmarkQuota !== undefined) { + const currentBookmarkCount = await db + .select({ count: count() }) + .from(bookmarks) + .where(eq(bookmarks.userId, userId)); + + if (currentBookmarkCount[0].count >= user.bookmarkQuota) { + return { + result: false, + error: `Bookmark quota exceeded. You can only have ${user.bookmarkQuota} bookmarks.`, + } as const; + } + } + return { + result: true, + } as const; + } + + static async checkStorageQuota( + db: DB | KarakeepDBTransaction, + userId: string, + requestedSize: number, + ): Promise<QuotaApproved> { + const user = await db.query.users.findFirst({ + where: eq(users.id, userId), + columns: { + storageQuota: true, + }, + }); + + if (user?.storageQuota === null || user?.storageQuota === undefined) { + // No quota limit - approve the request + return QuotaApproved._create(userId, requestedSize); + } + + const currentUsage = await this.getCurrentStorageUsage(db, userId); + + if (currentUsage + requestedSize > user.storageQuota) { + throw new StorageQuotaError( + currentUsage, + user.storageQuota, + requestedSize, + ); + } + + // Quota check passed - return approval token + return QuotaApproved._create(userId, requestedSize); + } + + static async getCurrentStorageUsage( + db: DB | KarakeepDBTransaction, + userId: string, + ): Promise<number> { + const currentUsageResult = await db + .select({ totalSize: sum(assets.size) }) + .from(assets) + .where(eq(assets.userId, userId)); + + return Number(currentUsageResult[0]?.totalSize ?? 0); + } +} diff --git a/packages/trpc/lib/storageQuota.ts b/packages/trpc/lib/storageQuota.ts deleted file mode 100644 index 49b96af8..00000000 --- a/packages/trpc/lib/storageQuota.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { eq, sum } from "drizzle-orm"; - -import type { DB, KarakeepDBTransaction } from "@karakeep/db"; -import { assets, users } from "@karakeep/db/schema"; -import { QuotaApproved } from "@karakeep/shared/storageQuota"; - -export class StorageQuotaError extends Error { - constructor( - public readonly currentUsage: number, - public readonly quota: number, - public readonly requestedSize: number, - ) { - super( - `Storage quota exceeded. Current usage: ${Math.round(currentUsage / 1024 / 1024)}MB, Quota: ${Math.round(quota / 1024 / 1024)}MB, Requested: ${Math.round(requestedSize / 1024 / 1024)}MB`, - ); - this.name = "StorageQuotaError"; - } -} - -export async function checkStorageQuota( - db: DB | KarakeepDBTransaction, - userId: string, - requestedSize: number, -): Promise<QuotaApproved> { - const user = await db.query.users.findFirst({ - where: eq(users.id, userId), - columns: { - storageQuota: true, - }, - }); - - if (user?.storageQuota === null || user?.storageQuota === undefined) { - // No quota limit - approve the request - return QuotaApproved._create(userId, requestedSize); - } - - const currentUsage = await getCurrentStorageUsage(db, userId); - - if (currentUsage + requestedSize > user.storageQuota) { - throw new StorageQuotaError(currentUsage, user.storageQuota, requestedSize); - } - - // Quota check passed - return approval token - return QuotaApproved._create(userId, requestedSize); -} - -export async function getCurrentStorageUsage( - db: DB | KarakeepDBTransaction, - userId: string, -): Promise<number> { - const currentUsageResult = await db - .select({ totalSize: sum(assets.size) }) - .from(assets) - .where(eq(assets.userId, userId)); - - return Number(currentUsageResult[0]?.totalSize ?? 0); -} diff --git a/packages/trpc/package.json b/packages/trpc/package.json index 31cb3d9a..c4e16675 100644 --- a/packages/trpc/package.json +++ b/packages/trpc/package.json @@ -14,8 +14,8 @@ }, "dependencies": { "@karakeep/db": "workspace:*", - "@karakeep/plugins-search-meilisearch": "workspace:*", "@karakeep/shared": "workspace:*", + "@karakeep/shared-server": "workspace:*", "@trpc/server": "^11.4.3", "bcryptjs": "^2.4.3", "deep-equal": "^2.2.3", diff --git a/packages/trpc/routers/bookmarks.ts b/packages/trpc/routers/bookmarks.ts index 298f0961..db9d33fc 100644 --- a/packages/trpc/routers/bookmarks.ts +++ b/packages/trpc/routers/bookmarks.ts @@ -1,5 +1,5 @@ import { experimental_trpcMiddleware, TRPCError } from "@trpc/server"; -import { and, count, eq, gt, inArray, lt, or } from "drizzle-orm"; +import { and, eq, gt, inArray, lt, or } from "drizzle-orm"; import { EnqueueOptions } from "liteque"; import invariant from "tiny-invariant"; import { z } from "zod"; @@ -20,8 +20,8 @@ import { bookmarkTexts, customPrompts, tagsOnBookmarks, - users, } from "@karakeep/db/schema"; +import { QuotaService } from "@karakeep/shared-server"; import { deleteAsset, SUPPORTED_BOOKMARK_ASSET_TYPES, @@ -273,26 +273,17 @@ export const bookmarksAppRouter = router({ } // Check user quota - const user = await ctx.db.query.users.findFirst({ - where: eq(users.id, ctx.user.id), - columns: { - bookmarkQuota: true, - }, - }); - - if (user?.bookmarkQuota !== null && user?.bookmarkQuota !== undefined) { - const currentBookmarkCount = await ctx.db - .select({ count: count() }) - .from(bookmarks) - .where(eq(bookmarks.userId, ctx.user.id)); - - if (currentBookmarkCount[0].count >= user.bookmarkQuota) { - throw new TRPCError({ - code: "FORBIDDEN", - message: `Bookmark quota exceeded. You can only have ${user.bookmarkQuota} bookmarks.`, - }); - } + const quotaResult = await QuotaService.canCreateBookmark( + ctx.db, + ctx.user.id, + ); + if (!quotaResult.result) { + throw new TRPCError({ + code: "FORBIDDEN", + message: quotaResult.error, + }); } + const bookmark = await ctx.db.transaction(async (tx) => { const bookmark = ( await tx |
