⚡️⚡️⚡️ 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
refactor(worker): move preserved-link auto-tagging into dedicated worker
daniel31x1355961444524d
diff --git a/apps/worker/lib/archiveHandler.ts b/apps/worker/lib/archiveHandler.tsindex 41861b1c..b1f4027b 100644--- a/apps/worker/lib/archiveHandler.ts+++ b/apps/worker/lib/archiveHandler.ts@@ -10,7 +10,6 @@ import handleArchivePreview from "./preservationScheme/handleArchivePreview";import handleScreenshotAndPdf from "./preservationScheme/handleScreenshotAndPdf";import imageHandler from "./preservationScheme/imageHandler";import pdfHandler from "./preservationScheme/pdfHandler";-import autoTagLink from "./autoTagLink";import { LinkWithCollectionOwnerAndTags } from "@linkwarden/types/global";import { isArchivalTag } from "@linkwarden/lib/isArchivalTag";import { ArchivalSettings } from "@linkwarden/types/global";@@ -55,19 +54,6 @@ export default async function archiveHandler(monolith: "unavailable",pdf: "unavailable",preview: "unavailable",-- // To prevent re-archiving the same link- aiTagged:- user.aiTaggingMethod !== AiTaggingMethod.DISABLED &&- !link.aiTagged &&- (process.env.NEXT_PUBLIC_OLLAMA_ENDPOINT_URL ||- process.env.OPENAI_API_KEY ||- process.env.AZURE_API_KEY ||- process.env.ANTHROPIC_API_KEY ||- process.env.OPENROUTER_API_KEY ||- process.env.PERPLEXITY_API_KEY)- ? true- : undefined,indexVersion: null,},});@@ -194,21 +180,6 @@ export default async function archiveHandler(await handleScreenshotAndPdf(link, page, archivalSettings);}- // Auto-tagging- if (- archivalSettings.aiTag &&- user.aiTaggingMethod !== AiTaggingMethod.DISABLED &&- !link.aiTagged &&- (process.env.NEXT_PUBLIC_OLLAMA_ENDPOINT_URL ||- process.env.OPENAI_API_KEY ||- process.env.AZURE_API_KEY ||- process.env.ANTHROPIC_API_KEY ||- process.env.OPENROUTER_API_KEY ||- process.env.PERPLEXITY_API_KEY)- ) {- await autoTagLink(user, link.id);- }-// Monolithif (archivalSettings.archiveAsMonolith &&@@ -248,11 +219,6 @@ export default async function archiveHandler(monolith: !finalLink.monolith ? "unavailable" : undefined,pdf: !finalLink.pdf ? "unavailable" : undefined,preview: !finalLink.preview ? "unavailable" : undefined,- aiTagged:- user.aiTaggingMethod !== AiTaggingMethod.DISABLED &&- !finalLink.aiTagged- ? true- : undefined,indexVersion: null,},});diff --git a/apps/worker/lib/getLinkBatchFairly.ts b/apps/worker/lib/getLinkBatchFairly.tsindex 44f4bf32..cc6237f9 100644--- a/apps/worker/lib/getLinkBatchFairly.ts+++ b/apps/worker/lib/getLinkBatchFairly.ts@@ -3,6 +3,7 @@ import { Prisma } from "@linkwarden/prisma/client";type PickLinksOptions = {maxBatchLinks: number;+ mode: "links" | "tags";};const TRIAL_PERIOD_DAYS = process.env.NEXT_PUBLIC_TRIAL_PERIOD_DAYS || 14;@@ -10,24 +11,36 @@ const REQUIRE_CC = process.env.NEXT_PUBLIC_REQUIRE_CC === "true";export default async function getLinkBatchFairly({maxBatchLinks,+ mode,}: PickLinksOptions) {if (maxBatchLinks <= 0) return [];- const baseLinkWhere: Prisma.LinkWhereInput = {- url: { not: null },- OR: [- { lastPreserved: null },- {- createdBy: {- is: {- aiTagExistingLinks: true,- NOT: { aiTaggingMethod: "DISABLED" },+ const baseLinkWhere: Prisma.LinkWhereInput =+ mode === "tags"+ ? {+ url: { not: null },+ type: "url",+ lastPreserved: { not: null },+ aiTagged: false,+ collection: {+ is: {+ owner: {+ is: {+ aiTaggingMethod: { not: "DISABLED" },+ },+ },+ },},- },- aiTagged: false,- },- ],- };+ }+ : {+ url: { not: null },+ lastPreserved: null,+ };++ const userLinksOrderBy: Prisma.LinkOrderByWithRelationInput[] =+ mode === "tags"+ ? [{ lastPreserved: "desc" }, { id: "desc" }]+ : [{ createdAt: "desc" }];const users = await prisma.user.findMany({where: {@@ -74,7 +87,7 @@ export default async function getLinkBatchFairly({for (const user of users) {const userLinks = await prisma.link.findMany({where: { createdBy: { id: user.id }, ...baseLinkWhere },- orderBy: [{ createdAt: "desc" }],+ orderBy: userLinksOrderBy,take: maxBatchLinks,select: { id: true },});@@ -108,7 +121,7 @@ export default async function getLinkBatchFairly({const userLinks = await prisma.link.findMany({where: { ...baseLinkWhere, createdBy: { id: userId } },- orderBy: [{ createdAt: "desc" }],+ orderBy: userLinksOrderBy,skip,take: toTake,select: { id: true },@@ -155,7 +168,7 @@ export default async function getLinkBatchFairly({console.log("\x1b[34m%s\x1b[0m",- `Processing ${batch.length} ${+ `${mode === "tags" ? "Auto-tagging" : "Processing"} ${batch.length} ${batch.length > 1 ? "links" : "link"} for the following ${uniqueUsersWithLinks.length > 1 ? "userIds" : "userId"diff --git a/apps/worker/worker.ts b/apps/worker/worker.tsindex cffe65a4..de16fbea 100644--- a/apps/worker/worker.ts+++ b/apps/worker/worker.ts@@ -1,3 +1,4 @@+import { autoTagPreservedLinks } from "./workers/autoTagPreservedLinks";import { startIndexing } from "./workers/linkIndexing";import { linkProcessing } from "./workers/linkProcessing";import { migrationWorker } from "./workers/migrationWorker";@@ -13,6 +14,7 @@ async function init() {console.log("\x1b[34m%s\x1b[0m", "Initializing the worker...");startRSSPolling();linkProcessing(workerIntervalInSeconds);+ autoTagPreservedLinks(workerIntervalInSeconds);startIndexing(workerIntervalInSeconds);trialEndEmailWorker();}diff --git a/apps/worker/workers/autoTagPreservedLinks.ts b/apps/worker/workers/autoTagPreservedLinks.tsnew file mode 100644index 00000000..d03ef0e9--- /dev/null+++ b/apps/worker/workers/autoTagPreservedLinks.ts@@ -0,0 +1,75 @@+import { delay } from "@linkwarden/lib/utils";+import { prisma } from "@linkwarden/prisma";+import { LinkWithCollectionOwnerAndTags } from "@linkwarden/types/global";+import autoTagLink from "../lib/autoTagLink";+import getLinkBatchFairly from "../lib/getLinkBatchFairly";++const AUTO_TAG_TAKE_COUNT = Number(process.env.ARCHIVE_TAKE_COUNT || "") || 5;++const hasAiTaggingProvider = () =>+ Boolean(+ process.env.NEXT_PUBLIC_OLLAMA_ENDPOINT_URL ||+ process.env.OPENAI_API_KEY ||+ process.env.AZURE_API_KEY ||+ process.env.ANTHROPIC_API_KEY ||+ process.env.OPENROUTER_API_KEY ||+ process.env.PERPLEXITY_API_KEY+ );++export async function autoTagPreservedLinks(interval = 10) {+ if (!hasAiTaggingProvider()) return;++ console.log("\x1b[34m%s\x1b[0m", "Starting preserved link auto-tagging...");++ while (true) {+ const links = await getLinkBatchFairly({+ maxBatchLinks: AUTO_TAG_TAKE_COUNT,+ mode: "tags",+ });++ if (links.length === 0) {+ await delay(interval);+ continue;+ }++ const autoTagPromises = links.map(+ async (link: LinkWithCollectionOwnerAndTags) => {+ try {+ console.log(+ "\x1b[34m%s\x1b[0m",+ `Auto-tagging link ${link.url} for user ${link.collection.ownerId}.`+ );++ await autoTagLink(link.collection.owner, link.id);++ console.log(+ "\x1b[34m%s\x1b[0m",+ `Succeeded auto-tagging link ${link.url} for user ${link.collection.ownerId}.`+ );+ } catch (error: any) {+ console.error(+ "\x1b[34m%s\x1b[0m",+ `Error auto-tagging link ${link.url} for user ${link.collection.ownerId}:`,+ error+ );+ } finally {+ await prisma.link+ .update({+ where: { id: link.id },+ data: { aiTagged: true },+ })+ .catch((error) => {+ console.error(+ "\x1b[34m%s\x1b[0m",+ `Error marking link ${link.id} as auto-tagged:`,+ error+ );+ });+ }+ }+ );++ await Promise.allSettled(autoTagPromises);+ await delay(interval);+ }+}diff --git a/apps/worker/workers/linkProcessing.ts b/apps/worker/workers/linkProcessing.tsindex 886c3b4f..01602866 100644--- a/apps/worker/workers/linkProcessing.ts+++ b/apps/worker/workers/linkProcessing.ts@@ -34,6 +34,7 @@ export async function linkProcessing(interval = 10) {const links = await getLinkBatchFairly({maxBatchLinks: ARCHIVE_TAKE_COUNT,+ mode: "links",});if (links.length === 0) {