Skip to content

⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.

code cleanup

daniel31x1314340afb99db
diff --git a/apps/worker/worker.ts b/apps/worker/worker.ts
index 0ec3af7c..803b704d 100644
--- a/apps/worker/worker.ts
+++ b/apps/worker/worker.ts
@@ -1,312 +1,15 @@
-import { prisma } from "@linkwarden/prisma";
-import archiveHandler from "./lib/archiveHandler";
-import Parser from "rss-parser";
-import { LinkWithCollectionOwnerAndTags } from "@linkwarden/types";
-import getLinkBatch from "./lib/getLinkBatch";
-import { meiliClient } from "@linkwarden/lib";
-import { rssHandler } from "@linkwarden/lib";
+import { startIndexing } from "./workers/linkIndexing";
+import { startProcessing } from "./workers/linkProcessing";
+import { startRSSPolling } from "./workers/rssPolling";
-const archiveTakeCount = Number(process.env.ARCHIVE_TAKE_COUNT || "") || 5;
-const indexTakeCount = Number(process.env.INDEX_TAKE_COUNT || "") || 50;
-
-function delay(sec: number) {
- return new Promise((resolve) => setTimeout(resolve, sec * 1000));
-}
-
-const pollingIntervalInSeconds =
- (Number(process.env.NEXT_PUBLIC_RSS_POLLING_INTERVAL_MINUTES) || 60) * 60; // Default to one hour if not set
-
-async function startRSSPolling() {
- console.log("\x1b[34m%s\x1b[0m", "Starting RSS polling...");
- while (true) {
- const rssSubscriptions = await prisma.rssSubscription.findMany({});
-
- const parser = new Parser();
-
- await Promise.all(
- rssSubscriptions.map(async (rssSubscription) => {
- rssHandler(rssSubscription, parser);
- })
- );
- await delay(pollingIntervalInSeconds);
- }
-}
-
-const archiveIntervalInSeconds =
+const workerIntervalInSeconds =
Number(process.env.ARCHIVE_SCRIPT_INTERVAL) || 10;
-async function startArchiveProcessing() {
- console.log("\x1b[34m%s\x1b[0m", "Starting link preservation...");
- while (true) {
- const links = await getLinkBatch({
- where: {
- url: { not: null },
- OR: [
- {
- image: null,
- },
- {
- pdf: null,
- },
- {
- readable: null,
- },
- {
- monolith: null,
- },
- {
- createdBy: {
- aiTagExistingLinks: true,
- NOT: {
- aiTaggingMethod: "DISABLED",
- },
- },
- aiTagged: false,
- },
- ],
- },
- take: archiveTakeCount,
- include: {
- collection: {
- include: {
- owner: true,
- },
- },
- tags: true,
- },
- });
-
- if (links.length === 0) {
- await delay(archiveIntervalInSeconds);
- continue;
- }
-
- const archiveLink = async (link: LinkWithCollectionOwnerAndTags) => {
- try {
- console.log(
- "\x1b[34m%s\x1b[0m",
- `Processing link ${link.url} for user ${link.collection.ownerId}`
- );
-
- await archiveHandler(link);
-
- console.log(
- "\x1b[34m%s\x1b[0m",
- `Succeeded processing link ${link.url} for user ${link.collection.ownerId}.`
- );
- } catch (error) {
- console.error(
- "\x1b[34m%s\x1b[0m",
- `Error processing link ${link.url} for user ${link.collection.ownerId}:`,
- error
- );
- }
- };
-
- // Process each link in the batch concurrently
- const processingPromises = links.map((e) => archiveLink(e));
-
- await Promise.allSettled(processingPromises);
-
- const unprocessedLinkCount = await prisma.link.count({
- where: {
- lastPreserved: null,
- url: { not: null },
- },
- });
-
- console.log(
- "\x1b[34m%s\x1b[0m",
- `Processed ${links.length} link${
- links.length === 1 ? "" : "s"
- }, ${unprocessedLinkCount} left.`
- );
-
- await delay(archiveIntervalInSeconds);
- }
-}
-
-async function setupLinksIndexSchema() {
- if (!meiliClient) return;
-
- let linksIndexExists = true;
- try {
- await meiliClient.getIndex("links");
- } catch (err) {
- linksIndexExists = false;
- }
-
- if (!linksIndexExists) {
- await meiliClient.createIndex("links", { primaryKey: "id" });
- }
-
- const updateFilterableAttributes = await meiliClient
- .index("links")
- .updateFilterableAttributes([
- "collectionOwnerId",
- "collectionMemberIds",
- "collectionName",
- "tags",
- "pinnedBy",
- "url",
- "type",
- "name",
- "description",
- "collectionIsPublic",
- "creationTimestamp",
- ]);
- await meiliClient
- .index("links")
- .waitForTask(updateFilterableAttributes.taskUid, {
- timeOutMs: Number(process.env.MEILI_TIMEOUT) || 1000000,
- })
- .catch((err) => {
- console.error("\x1b[34m%s\x1b[0m", `Error indexing links:`, err);
- });
-
- const updateSortableAttributes = await meiliClient
- .index("links")
- .updateSortableAttributes(["id", "name"]);
-
- await meiliClient
- .index("links")
- .waitForTask(updateSortableAttributes.taskUid, {
- timeOutMs: Number(process.env.MEILI_TIMEOUT) || 1000000,
- })
- .catch((err) => {
- console.error("\x1b[34m%s\x1b[0m", `Error indexing links:`, err);
- });
-
- // if (process.env.NODE_ENV !== "production") await clearIndexes(); // For development/debugging purposes ONLY! This function clears all the indexes and you'll have to reindex everything...
-}
-
-export async function startIndexing() {
- if (!meiliClient) return;
-
- await setupLinksIndexSchema();
-
- console.log("\x1b[34m%s\x1b[0m", "Starting link indexing...");
-
- const INDEX_VERSION = 1;
-
- while (true) {
- const links = await getLinkBatch({
- where: {
- AND: [
- {
- OR: [
- { indexVersion: { not: INDEX_VERSION } },
- { indexVersion: null },
- ],
- },
- {
- OR: [
- { lastPreserved: { not: null } },
- {
- url: null,
- },
- ],
- },
- ],
- },
- take: indexTakeCount,
- include: {
- collection: {
- include: {
- owner: true,
- members: {
- select: { userId: true },
- },
- },
- },
- tags: {
- select: { name: true },
- },
- pinnedBy: {
- select: { id: true },
- },
- },
- });
-
- if (links.length === 0) {
- await delay(archiveIntervalInSeconds);
- continue;
- }
-
- const docs = links.map((link) => ({
- ...link,
- collectionOwnerId: link.collection.ownerId,
- collectionMemberIds: link.collection.members.map((m) => m.userId),
- collectionIsPublic: link.collection.isPublic,
- collectionName: link.collection.name,
- tags: link.tags.map((t) => t.name),
- pinnedBy: link.pinnedBy.map((p) => p.id),
- creationTimestamp: Date.parse(link.createdAt.toISOString()) / 1000,
- indexVersion: INDEX_VERSION,
- }));
-
- const task = await meiliClient.index("links").addDocuments(docs);
- await meiliClient
- .index("links")
- .waitForTask(task.taskUid, {
- timeOutMs: Number(process.env.MEILI_TIMEOUT) || 1000000,
- })
- .catch((err) => {
- console.error("\x1b[34m%s\x1b[0m", `Error indexing links:`, err);
- });
-
- const ids = links.map((l) => l.id);
- await prisma.link.updateMany({
- where: { id: { in: ids } },
- data: { indexVersion: INDEX_VERSION },
- });
-
- const indexesLeft = await prisma.link.count({
- where: {
- OR: [{ indexVersion: { not: INDEX_VERSION } }, { indexVersion: null }],
- lastPreserved: { not: null },
- },
- });
-
- console.log(
- "\x1b[34m%s\x1b[0m",
- `Indexed ${links.length} link${
- links.length === 1 ? "" : "s"
- }, ${indexesLeft} left.`
- );
-
- await delay(archiveIntervalInSeconds);
- }
-}
-
async function init() {
console.log("\x1b[34m%s\x1b[0m", "Initializing the worker...");
startRSSPolling();
- startArchiveProcessing();
- startIndexing();
+ startProcessing(workerIntervalInSeconds);
+ startIndexing(workerIntervalInSeconds);
}
init();
-
-// const clearIndexes = async () => {
-// console.log("Clearing db indexes...");
-
-// const clearedLinks = await prisma.link.updateMany({
-// where: {},
-// data: {
-// indexVersion: null,
-// },
-// });
-
-// console.log("Cleared db indexes:", clearedLinks);
-
-// if (!meiliClient) return;
-
-// const deleteAllDocuments = await meiliClient
-// .index("links")
-// .deleteAllDocuments();
-
-// await meiliClient.index("links").waitForTask(deleteAllDocuments.taskUid, {
-// timeOutMs: 1000000,
-// });
-// };
diff --git a/apps/worker/workers/linkIndexing.ts b/apps/worker/workers/linkIndexing.ts
new file mode 100644
index 00000000..948f4e2d
--- /dev/null
+++ b/apps/worker/workers/linkIndexing.ts
@@ -0,0 +1,181 @@
+import { delay, meiliClient } from "@linkwarden/lib";
+import { prisma } from "@linkwarden/prisma";
+import getLinkBatch from "../lib/getLinkBatch";
+
+const takeCount = Number(process.env.INDEX_TAKE_COUNT || "") || 50;
+
+async function setupLinksIndexSchema() {
+ if (!meiliClient) return;
+
+ let linksIndexExists = true;
+ try {
+ await meiliClient.getIndex("links");
+ } catch (err) {
+ linksIndexExists = false;
+ }
+
+ if (!linksIndexExists) {
+ await meiliClient.createIndex("links", { primaryKey: "id" });
+ }
+
+ const updateFilterableAttributes = await meiliClient
+ .index("links")
+ .updateFilterableAttributes([
+ "collectionOwnerId",
+ "collectionMemberIds",
+ "collectionName",
+ "tags",
+ "pinnedBy",
+ "url",
+ "type",
+ "name",
+ "description",
+ "collectionIsPublic",
+ "creationTimestamp",
+ ]);
+ await meiliClient
+ .index("links")
+ .waitForTask(updateFilterableAttributes.taskUid, {
+ timeOutMs: Number(process.env.MEILI_TIMEOUT) || 1000000,
+ })
+ .catch((err) => {
+ console.error("\x1b[34m%s\x1b[0m", `Error indexing links:`, err);
+ });
+
+ const updateSortableAttributes = await meiliClient
+ .index("links")
+ .updateSortableAttributes(["id", "name"]);
+
+ await meiliClient
+ .index("links")
+ .waitForTask(updateSortableAttributes.taskUid, {
+ timeOutMs: Number(process.env.MEILI_TIMEOUT) || 1000000,
+ })
+ .catch((err) => {
+ console.error("\x1b[34m%s\x1b[0m", `Error indexing links:`, err);
+ });
+
+ // if (process.env.NODE_ENV !== "production") await clearIndexes(); // For development/debugging purposes ONLY! This function clears all the indexes and you'll have to reindex everything...
+}
+
+export async function startIndexing(interval = 10) {
+ if (!meiliClient) return;
+
+ await setupLinksIndexSchema();
+
+ console.log("\x1b[34m%s\x1b[0m", "Starting link indexing...");
+
+ const INDEX_VERSION = 1;
+
+ while (true) {
+ const links = await getLinkBatch({
+ where: {
+ AND: [
+ {
+ OR: [
+ { indexVersion: { not: INDEX_VERSION } },
+ { indexVersion: null },
+ ],
+ },
+ {
+ OR: [
+ { lastPreserved: { not: null } },
+ {
+ url: null,
+ },
+ ],
+ },
+ ],
+ },
+ take: takeCount,
+ include: {
+ collection: {
+ include: {
+ owner: true,
+ members: {
+ select: { userId: true },
+ },
+ },
+ },
+ tags: {
+ select: { name: true },
+ },
+ pinnedBy: {
+ select: { id: true },
+ },
+ },
+ });
+
+ if (links.length === 0) {
+ await delay(interval);
+ continue;
+ }
+
+ const docs = links.map((link) => ({
+ ...link,
+ collectionOwnerId: link.collection.ownerId,
+ collectionMemberIds: link.collection.members.map((m) => m.userId),
+ collectionIsPublic: link.collection.isPublic,
+ collectionName: link.collection.name,
+ tags: link.tags.map((t) => t.name),
+ pinnedBy: link.pinnedBy.map((p) => p.id),
+ creationTimestamp: Date.parse(link.createdAt.toISOString()) / 1000,
+ indexVersion: INDEX_VERSION,
+ }));
+
+ const task = await meiliClient.index("links").addDocuments(docs);
+ await meiliClient
+ .index("links")
+ .waitForTask(task.taskUid, {
+ timeOutMs: Number(process.env.MEILI_TIMEOUT) || 1000000,
+ })
+ .catch((err) => {
+ console.error("\x1b[34m%s\x1b[0m", `Error indexing links:`, err);
+ });
+
+ const ids = links.map((l) => l.id);
+ await prisma.link.updateMany({
+ where: { id: { in: ids } },
+ data: { indexVersion: INDEX_VERSION },
+ });
+
+ const indexesLeft = await prisma.link.count({
+ where: {
+ OR: [{ indexVersion: { not: INDEX_VERSION } }, { indexVersion: null }],
+ lastPreserved: { not: null },
+ },
+ });
+
+ console.log(
+ "\x1b[34m%s\x1b[0m",
+ `Indexed ${links.length} link${
+ links.length === 1 ? "" : "s"
+ }, ${indexesLeft} left.`
+ );
+
+ await delay(interval);
+ }
+}
+
+// const clearIndexes = async () => {
+// console.log("Clearing db indexes...");
+
+// const clearedLinks = await prisma.link.updateMany({
+// where: {},
+// data: {
+// indexVersion: null,
+// },
+// });
+
+// console.log("Cleared db indexes:", clearedLinks);
+
+// if (!meiliClient) return;
+
+// const deleteAllDocuments = await meiliClient
+// .index("links")
+// .deleteAllDocuments();
+
+// await meiliClient.index("links").waitForTask(deleteAllDocuments.taskUid, {
+// timeOutMs: 1000000,
+// });
+// };
diff --git a/apps/worker/workers/linkProcessing.ts b/apps/worker/workers/linkProcessing.ts
new file mode 100644
index 00000000..10e3ed37
--- /dev/null
+++ b/apps/worker/workers/linkProcessing.ts
@@ -0,0 +1,89 @@
+import { prisma } from "@linkwarden/prisma";
+import archiveHandler from "../lib/archiveHandler";
+import { LinkWithCollectionOwnerAndTags } from "@linkwarden/types";
+import getLinkBatch from "../lib/getLinkBatch";
+import { delay } from "@linkwarden/lib";
+
+const takeCount = Number(process.env.ARCHIVE_TAKE_COUNT || "") || 5;
+
+export async function startProcessing(interval = 10) {
+ console.log("\x1b[34m%s\x1b[0m", "Starting link processing...");
+ while (true) {
+ const links = await getLinkBatch({
+ where: {
+ url: { not: null },
+ OR: [
+ {
+ lastPreserved: null,
+ },
+ {
+ createdBy: {
+ aiTagExistingLinks: true,
+ NOT: {
+ aiTaggingMethod: "DISABLED",
+ },
+ },
+ aiTagged: false,
+ },
+ ],
+ },
+ take: takeCount,
+ include: {
+ collection: {
+ include: {
+ owner: true,
+ },
+ },
+ tags: true,
+ },
+ });
+
+ if (links.length === 0) {
+ await delay(interval);
+ continue;
+ }
+
+ const archiveLink = async (link: LinkWithCollectionOwnerAndTags) => {
+ try {
+ console.log(
+ "\x1b[34m%s\x1b[0m",
+ `Processing link ${link.url} for user ${link.collection.ownerId}`
+ );
+
+ await archiveHandler(link);
+
+ console.log(
+ "\x1b[34m%s\x1b[0m",
+ `Succeeded processing link ${link.url} for user ${link.collection.ownerId}.`
+ );
+ } catch (error) {
+ console.error(
+ "\x1b[34m%s\x1b[0m",
+ `Error processing link ${link.url} for user ${link.collection.ownerId}:`,
+ error
+ );
+ }
+ };
+
+ // Process each link in the batch concurrently
+ const processingPromises = links.map((e) => archiveLink(e));
+
+ await Promise.allSettled(processingPromises);
+
+ const unprocessedLinkCount = await prisma.link.count({
+ where: {
+ lastPreserved: null,
+ url: { not: null },
+ },
+ });
+
+ console.log(
+ "\x1b[34m%s\x1b[0m",
+ `Processed ${links.length} link${
+ links.length === 1 ? "" : "s"
+ }, ${unprocessedLinkCount} left.`
+ );
+
+ await delay(interval);
+ }
+}
diff --git a/apps/worker/workers/rssPolling.ts b/apps/worker/workers/rssPolling.ts
new file mode 100644
index 00000000..c89e7438
--- /dev/null
+++ b/apps/worker/workers/rssPolling.ts
@@ -0,0 +1,22 @@
+import { prisma } from "@linkwarden/prisma";
+import Parser from "rss-parser";
+import { delay, rssHandler } from "@linkwarden/lib";
+
+const pollingIntervalInSeconds =
+ (Number(process.env.NEXT_PUBLIC_RSS_POLLING_INTERVAL_MINUTES) || 60) * 60; // Default to one hour if not set
+
+export async function startRSSPolling() {
+ console.log("\x1b[34m%s\x1b[0m", "Starting RSS polling...");
+ while (true) {
+ const rssSubscriptions = await prisma.rssSubscription.findMany({});
+
+ const parser = new Parser();
+
+ await Promise.all(
+ rssSubscriptions.map(async (rssSubscription) => {
+ rssHandler(rssSubscription, parser);
+ })
+ );
+ await delay(pollingIntervalInSeconds);
+ }
+}
diff --git a/packages/lib/utils.ts b/packages/lib/utils.ts
index 804fa7b3..6fc2f738 100644
--- a/packages/lib/utils.ts
+++ b/packages/lib/utils.ts
@@ -6,3 +6,7 @@ export function titleCase(str: string) {
}
return splitStr.join(" ");
}
+
+export function delay(sec: number) {
+ return new Promise((resolve) => setTimeout(resolve, sec * 1000));
+}