⚡️⚡️⚡️ 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
daniel31x13658434afaf54
diff --git a/.env.sample b/.env.sampleindex e204f52d..16eee397 100644--- a/.env.sample+++ b/.env.sample@@ -17,7 +17,7 @@ NEXT_PUBLIC_CREDENTIALS_ENABLED=DISABLE_NEW_SSO_USERS=MAX_LINKS_PER_USER=ARCHIVE_TAKE_COUNT=-ARCHIVE_USER_TAKE_COUNT=+ARCHIVE_MIN_USER_TAKE_COUNT=ARCHIVE_PER_USER_CAP=BROWSER_TIMEOUT=IGNORE_UNAUTHORIZED_CA=diff --git a/apps/worker/lib/getLinkBatchFairly.ts b/apps/worker/lib/getLinkBatchFairly.tsindex 5cbf1c1d..498238f5 100644--- a/apps/worker/lib/getLinkBatchFairly.ts+++ b/apps/worker/lib/getLinkBatchFairly.ts@@ -1,107 +1,158 @@import { prisma } from "@linkwarden/prisma";+import { Prisma } from "@linkwarden/prisma/client";-type Options = {- usersPerRound: number;- perUserCap: number;- batchLimit: number;- overfetchFactor?: number;+type PickLinksOptions = {+ perUserLimit: number;+ maxBatchLinks: number;+ leastNumberOfUsersPerBatch: number;};-export async function getLinkBatchFairly(opts: Options) {- const { usersPerRound, perUserCap, batchLimit, overfetchFactor = 3 } = opts;+export default async function getLinkBatchFairly({+ perUserLimit,+ maxBatchLinks,+ leastNumberOfUsersPerBatch,+}: PickLinksOptions) {+ // Sanity: cannot include more users than links+ const minUsers = Math.min(leastNumberOfUsersPerBatch, maxBatchLinks);- const candidates = await prisma.user.findMany({- where: {- subscriptions: {- is: {- active: true,- currentPeriodEnd: { gt: new Date() },- },- },- collections: {- some: {- links: {- some: {- url: { not: null },- OR: [- { lastPreserved: null },- {- aiTagged: false,- createdBy: {- aiTagExistingLinks: true,- NOT: { aiTaggingMethod: "DISABLED" },- },- },- ],- },+ const pickedLinkIds: number[] = [];+ const pickedUserIds = new Set<number>();++ // Your existing eligibility filter (typed, no readonly)+ const baseLinkWhere: Prisma.LinkWhereInput = {+ url: { not: null },+ OR: [+ { lastPreserved: null },+ {+ createdBy: {+ is: {+ aiTagExistingLinks: true,+ NOT: { aiTaggingMethod: "DISABLED" },},},+ aiTagged: false,},- },- orderBy: { lastPickedAt: "asc" },- take: usersPerRound,- select: { id: true },- });+ ],+ };- console.log("Found candidates:", candidates);+ // Keyset pagination over users by (lastPickedAt ASC, id ASC)+ let lastPickedAtCursor: Date | null = null;+ let lastIdCursor: number | null = null;- if (candidates.length === 0) return [];+ // We only count a user towards "min users" if they contribute at least 1 link+ while (pickedLinkIds.length < maxBatchLinks) {+ const baseUserWhere: Prisma.UserWhereInput = {+ subscriptions: { is: { active: true } }, // only active subscribers+ };- const ownerIds = candidates.map((u) => u.id);+ const userWhere: Prisma.UserWhereInput =+ lastPickedAtCursor && lastIdCursor+ ? {+ AND: [+ baseUserWhere,+ {+ OR: [+ { lastPickedAt: { gt: lastPickedAtCursor } },+ {+ AND: [+ { lastPickedAt: { equals: lastPickedAtCursor } },+ { id: { gt: lastIdCursor } },+ ],+ },+ ],+ },+ ],+ }+ : baseUserWhere;- const targetCount = Math.min(- batchLimit * overfetchFactor,- usersPerRound * perUserCap * overfetchFactor- );+ const users = await prisma.user.findMany({+ where: userWhere,+ orderBy: [{ lastPickedAt: "asc" }, { id: "asc" }],+ select: { id: true, lastPickedAt: true },+ });- const links = await prisma.link.findMany({- where: {- url: { not: null },- collection: { ownerId: { in: ownerIds } },- OR: [- { lastPreserved: null },- {- aiTagged: false,- createdBy: {- aiTagExistingLinks: true,- NOT: { aiTaggingMethod: "DISABLED" },- },+ 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 } },},- ],- },- include: {- collection: { include: { owner: true } },- tags: true,- },- orderBy: { id: "desc" },- take: targetCount,- });+ orderBy: [+ { createdAt: "desc" }, // newest first per user+ { id: "desc" }, // tiebreaker+ ],+ take: maxForThisUser,+ select: { id: true },+ });- if (links.length === 0) return [];+ if (links.length > 0) {+ for (const l of links) pickedLinkIds.push(l.id);+ pickedUserIds.add(u.id);+ }+ }- const perUserPicked: Record<number, number> = {};- const picked: typeof links = [];+ const tail = users[users.length - 1];+ lastPickedAtCursor = tail.lastPickedAt;+ lastIdCursor = tail.id;- for (const l of links) {- const ownerId = l.collection.ownerId;- const count = perUserPicked[ownerId] ?? 0;- if (count < perUserCap) {- perUserPicked[ownerId] = count + 1;- picked.push(l);- if (picked.length >= batchLimit) break;+ // Stop early if we’ve satisfied both constraints+ if (+ pickedLinkIds.length >= maxBatchLinks &&+ pickedUserIds.size >= minUsers+ ) {+ break;}}- if (picked.length === 0) return [];+ console.log(+ "\x1b[34m%s\x1b[0m",+ `Processing ${+ pickedLinkIds.length+ } links for the following users: ${Array.from(pickedUserIds).join(", ")}`+ );- const touchedUserIds = [...new Set(picked.map((l) => l.collection.ownerId))];+ if (pickedLinkIds.length === 0) return [];++ // Stamp lastPickedAt only for users that contributed links in this batch+ const now = new Date();+ await prisma.user.updateMany({+ where: { id: { in: Array.from(pickedUserIds) } },+ data: { lastPickedAt: now },+ });++ // Return same shape as your original findMany include+ const batch = await prisma.link.findMany({+ where: { id: { in: pickedLinkIds } },+ include: {+ collection: { include: { owner: true } },+ tags: true,+ },+ });- await prisma.$transaction([- prisma.user.updateMany({- where: { id: { in: touchedUserIds } },- data: { lastPickedAt: new Date() },- }),- ]);+ // 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)!);- return picked;+ return batch;}diff --git a/apps/worker/workers/linkProcessing.ts b/apps/worker/workers/linkProcessing.tsindex 03c9fbc5..3630586c 100644--- a/apps/worker/workers/linkProcessing.ts+++ b/apps/worker/workers/linkProcessing.ts@@ -2,11 +2,11 @@ import { prisma } from "@linkwarden/prisma";import archiveHandler from "../lib/archiveHandler";import { LinkWithCollectionOwnerAndTags } from "@linkwarden/types";import { delay } from "@linkwarden/lib";-import { getLinkBatchFairly } from "../lib/getLinkBatchFairly";+import getLinkBatchFairly from "../lib/getLinkBatchFairly";const ARCHIVE_TAKE_COUNT = Number(process.env.ARCHIVE_TAKE_COUNT || "") || 5;-const ARCHIVE_USER_TAKE_COUNT =- Number(process.env.ARCHIVE_USER_TAKE_COUNT || "") || 1;+const ARCHIVE_MIN_USER_TAKE_COUNT =+ Number(process.env.ARCHIVE_MIN_USER_TAKE_COUNT || "") || 1;const ARCHIVE_PER_USER_CAP =Number(process.env.ARCHIVE_PER_USER_CAP || "") || 5;@@ -14,10 +14,9 @@ export async function startProcessing(interval = 10) {console.log("\x1b[34m%s\x1b[0m", "Starting link processing...");while (true) {const links = await getLinkBatchFairly({- usersPerRound: ARCHIVE_USER_TAKE_COUNT,- perUserCap: ARCHIVE_PER_USER_CAP,- batchLimit: ARCHIVE_TAKE_COUNT,- overfetchFactor: 3,+ leastNumberOfUsersPerBatch: ARCHIVE_MIN_USER_TAKE_COUNT,+ perUserLimit: ARCHIVE_PER_USER_CAP,+ maxBatchLinks: ARCHIVE_TAKE_COUNT,});if (links.length === 0) {@@ -29,7 +28,7 @@ export async function startProcessing(interval = 10) {try {console.log("\x1b[34m%s\x1b[0m",- `Processing link ${link.url} for user ${link.collection.ownerId}`+ `- Link ${link.url} for user ${link.collection.ownerId}`);await archiveHandler(link);