⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.
TypeScript bookmarkbookmark-managercollaborationnextjsreact-nativeread-it-laterself-hostedtypescript
improvement
daniel31x13794c2f26579b
diff --git a/apps/worker/lib/getLinkBatchFairly.ts b/apps/worker/lib/getLinkBatchFairly.tsindex 498238f5..8c0e3153 100644--- a/apps/worker/lib/getLinkBatchFairly.ts+++ b/apps/worker/lib/getLinkBatchFairly.ts@@ -2,23 +2,14 @@ import { prisma } from "@linkwarden/prisma";import { Prisma } from "@linkwarden/prisma/client";type PickLinksOptions = {- perUserLimit: number;maxBatchLinks: number;- leastNumberOfUsersPerBatch: number;};export default async function getLinkBatchFairly({- perUserLimit,maxBatchLinks,- leastNumberOfUsersPerBatch,}: PickLinksOptions) {- // Sanity: cannot include more users than links- const minUsers = Math.min(leastNumberOfUsersPerBatch, maxBatchLinks);+ if (maxBatchLinks <= 0) return [];- const pickedLinkIds: number[] = [];- const pickedUserIds = new Set<number>();-- // Your existing eligibility filter (typed, no readonly)const baseLinkWhere: Prisma.LinkWhereInput = {url: { not: null },OR: [@@ -35,16 +26,14 @@ export default async function getLinkBatchFairly({],};- // Keyset pagination over users by (lastPickedAt ASC, id ASC)+ const candidateUserIds: number[] = [];let lastPickedAtCursor: Date | null = null;let lastIdCursor: number | null = null;- // We only count a user towards "min users" if they contribute at least 1 link- while (pickedLinkIds.length < maxBatchLinks) {+ while (candidateUserIds.length < maxBatchLinks) {const baseUserWhere: Prisma.UserWhereInput = {- subscriptions: { is: { active: true } }, // only active subscribers+ subscriptions: { is: { active: true } },};-const userWhere: Prisma.UserWhereInput =lastPickedAtCursor && lastIdCursor? {@@ -74,53 +63,46 @@ export default async function getLinkBatchFairly({if (users.length === 0) break;for (const u of users) {- if (pickedLinkIds.length >= maxBatchLinks) break;-- const remainingSlots = maxBatchLinks - pickedLinkIds.length;- const remainingUsersNeeded = Math.max(0, minUsers - pickedUserIds.size);-- // Ensure we leave at least one slot for each still‑needed user (including this user’s peers)- // If we still need K users after this one, we must keep K slots free.- // So the most we can take now is remainingSlots - (remainingUsersNeeded - 1).- // (If remainingUsersNeeded === 0, we can take up to perUserLimit or remainingSlots.)- const maxForThisUser = Math.min(- perUserLimit,- remainingUsersNeeded > 0- ? Math.max(1, remainingSlots - (remainingUsersNeeded - 1))- : remainingSlots- );-- if (maxForThisUser <= 0) continue;-- const links = await prisma.link.findMany({- where: {- ...baseLinkWhere,- collection: { is: { ownerId: u.id } },- },- orderBy: [- { createdAt: "desc" }, // newest first per user- { id: "desc" }, // tiebreaker- ],- take: maxForThisUser,+ if (candidateUserIds.length >= maxBatchLinks) break;++ const oneLink = await prisma.link.findFirst({+ where: { ...baseLinkWhere, collection: { is: { ownerId: u.id } } },+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],select: { id: true },});- if (links.length > 0) {- for (const l of links) pickedLinkIds.push(l.id);- pickedUserIds.add(u.id);- }+ if (oneLink) candidateUserIds.push(u.id);}const tail = users[users.length - 1];lastPickedAtCursor = tail.lastPickedAt;lastIdCursor = tail.id;+ }++ if (candidateUserIds.length === 0) return [];++ const U = candidateUserIds.length;+ const perUserCap = Math.ceil(maxBatchLinks / U);++ const pickedLinkIds: number[] = [];+ const pickedUserIds = new Set<number>();++ for (const userId of candidateUserIds) {+ if (pickedLinkIds.length >= maxBatchLinks) break;++ const remaining = maxBatchLinks - pickedLinkIds.length;+ const take = Math.min(perUserCap, remaining);++ const links = await prisma.link.findMany({+ where: { ...baseLinkWhere, collection: { is: { ownerId: userId } } },+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],+ take,+ select: { id: true },+ });- // Stop early if we’ve satisfied both constraints- if (- pickedLinkIds.length >= maxBatchLinks &&- pickedUserIds.size >= minUsers- ) {- break;+ if (links.length > 0) {+ for (const l of links) pickedLinkIds.push(l.id);+ pickedUserIds.add(userId);}}@@ -133,14 +115,12 @@ export default async function getLinkBatchFairly({if (pickedLinkIds.length === 0) return [];- // Stamp lastPickedAt only for users that contributed links in this batchconst now = new Date();await prisma.user.updateMany({where: { id: { in: Array.from(pickedUserIds) } },data: { lastPickedAt: now },});- // Return same shape as your original findMany includeconst batch = await prisma.link.findMany({where: { id: { in: pickedLinkIds } },include: {@@ -149,7 +129,6 @@ export default async function getLinkBatchFairly({},});- // Preserve selection order (per-user newest first, fairness order)const order = new Map<number, number>();pickedLinkIds.forEach((id, i) => order.set(id, i));batch.sort((a, b) => order.get(a.id)! - order.get(b.id)!);diff --git a/apps/worker/workers/linkProcessing.ts b/apps/worker/workers/linkProcessing.tsindex 3630586c..73b7416a 100644--- a/apps/worker/workers/linkProcessing.ts+++ b/apps/worker/workers/linkProcessing.ts@@ -14,8 +14,6 @@ export async function startProcessing(interval = 10) {console.log("\x1b[34m%s\x1b[0m", "Starting link processing...");while (true) {const links = await getLinkBatchFairly({- leastNumberOfUsersPerBatch: ARCHIVE_MIN_USER_TAKE_COUNT,- perUserLimit: ARCHIVE_PER_USER_CAP,maxBatchLinks: ARCHIVE_TAKE_COUNT,});diff --git a/packages/prisma/migrations/20250813025203_remove_default_from_field/migration.sql b/packages/prisma/migrations/20250813025203_remove_default_from_field/migration.sqlnew file mode 100644index 00000000..f893b6c0--- /dev/null+++ b/packages/prisma/migrations/20250813025203_remove_default_from_field/migration.sql@@ -0,0 +1,3 @@+-- AlterTable+ALTER TABLE "User" ALTER COLUMN "lastPickedAt" DROP NOT NULL,+ALTER COLUMN "lastPickedAt" DROP DEFAULT;diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prismaindex e24fb0be..4252d11d 100644--- a/packages/prisma/schema.prisma+++ b/packages/prisma/schema.prisma@@ -67,7 +67,7 @@ model User {isPrivate Boolean @default(false)referredBy String?dashboardSections DashboardSection[]- lastPickedAt DateTime @default(now())+ lastPickedAt DateTime?createdAt DateTime @default(now())updatedAt DateTime @default(now()) @updatedAt}