Skip to content

A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search

fix: dont trigger background jobs if bookmark doesn't change on updateTags call

Mohamed Bassemfbc63b92aa4f
diff --git a/packages/trpc/routers/bookmarks.test.ts b/packages/trpc/routers/bookmarks.test.ts
index aaee5447..13df8a9e 100644
--- a/packages/trpc/routers/bookmarks.test.ts
+++ b/packages/trpc/routers/bookmarks.test.ts
@@ -1,17 +1,38 @@
import { eq } from "drizzle-orm";
-import { assert, beforeEach, describe, expect, test } from "vitest";
+import { assert, beforeEach, describe, expect, test, vi } from "vitest";
import {
bookmarkLinks,
bookmarks,
rssFeedImportsTable,
+ tagsOnBookmarks,
users,
} from "@karakeep/db/schema";
+import * as sharedServer from "@karakeep/shared-server";
import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";
import type { APICallerType, CustomTestContext } from "../testUtils";
import { defaultBeforeEach } from "../testUtils";
+vi.mock("@karakeep/shared-server", async (original) => {
+ const mod = (await original()) as typeof import("@karakeep/shared-server");
+ return {
+ ...mod,
+ LinkCrawlerQueue: {
+ enqueue: vi.fn(),
+ },
+ OpenAIQueue: {
+ enqueue: vi.fn(),
+ },
+ SearchIndexingQueue: {
+ enqueue: vi.fn(),
+ },
+ triggerRuleEngineOnEvent: vi.fn(),
+ triggerSearchReindex: vi.fn(),
+ triggerWebhook: vi.fn(),
+ };
+});
+
beforeEach<CustomTestContext>(defaultBeforeEach(true));
describe("Bookmark Routes", () => {
@@ -455,6 +476,60 @@ describe("Bookmark Routes", () => {
expect(duplicateTagCount).toEqual(1); // Should only be attached once
});
+ test<CustomTestContext>("update tags no-op does not retrigger indexing or update modifiedAt", async ({
+ apiCallers,
+ db,
+ }) => {
+ const api = apiCallers[0].bookmarks;
+ const triggerSearchReindexMock = vi.mocked(
+ sharedServer.triggerSearchReindex,
+ );
+ triggerSearchReindexMock.mockClear();
+
+ const bookmark = await api.createBookmark({
+ url: "https://bookmark.com",
+ type: BookmarkTypes.LINK,
+ });
+ const tag = await apiCallers[0].tags.create({ name: "stable-tag" });
+ await db.insert(tagsOnBookmarks).values({
+ bookmarkId: bookmark.id,
+ tagId: tag.id,
+ attachedBy: "human",
+ });
+
+ await api.updateTags({
+ bookmarkId: bookmark.id,
+ attach: [],
+ detach: [{ tagId: tag.id }],
+ });
+
+ const [beforeNoopUpdate] = await db
+ .select({ modifiedAt: bookmarks.modifiedAt })
+ .from(bookmarks)
+ .where(eq(bookmarks.id, bookmark.id));
+ assert(beforeNoopUpdate?.modifiedAt);
+
+ triggerSearchReindexMock.mockClear();
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ await api.updateTags({
+ bookmarkId: bookmark.id,
+ attach: [],
+ detach: [{ tagId: tag.id }],
+ });
+
+ const [afterNoopUpdate] = await db
+ .select({ modifiedAt: bookmarks.modifiedAt })
+ .from(bookmarks)
+ .where(eq(bookmarks.id, bookmark.id));
+ assert(afterNoopUpdate?.modifiedAt);
+
+ expect(triggerSearchReindexMock).not.toHaveBeenCalled();
+ expect(afterNoopUpdate.modifiedAt.getTime()).toEqual(
+ beforeNoopUpdate.modifiedAt.getTime(),
+ );
+ });
+
test<CustomTestContext>("updateTags with attachedBy field", async ({
apiCallers,
}) => {
diff --git a/packages/trpc/routers/bookmarks.ts b/packages/trpc/routers/bookmarks.ts
index 782566cf..61902ddf 100644
--- a/packages/trpc/routers/bookmarks.ts
+++ b/packages/trpc/routers/bookmarks.ts
@@ -814,9 +814,10 @@ export const bookmarksAppRouter = router({
const idsToRemove = detachTagsWithNames.map((t) => t.id);
const res = await ctx.db.transaction(async (tx) => {
+ let numChanges = 0;
// Detaches
if (idsToRemove.length > 0) {
- await tx
+ const res = await tx
.delete(tagsOnBookmarks)
.where(
and(
@@ -824,11 +825,12 @@ export const bookmarksAppRouter = router({
inArray(tagsOnBookmarks.tagId, idsToRemove),
),
);
+ numChanges += res.changes;
}
// Attach tags
if (allIdsToAttach.length > 0) {
- await tx
+ const res = await tx
.insert(tagsOnBookmarks)
.values(
allIdsToAttach.map((i) => ({
@@ -838,44 +840,50 @@ export const bookmarksAppRouter = router({
})),
)
.onConflictDoNothing();
+ numChanges += res.changes;
}
// Update bookmark modified timestamp
- await tx
- .update(bookmarks)
- .set({ modifiedAt: new Date() })
- .where(
- and(
- eq(bookmarks.id, input.bookmarkId),
- eq(bookmarks.userId, ctx.user.id),
- ),
- );
+ if (numChanges > 0) {
+ await tx
+ .update(bookmarks)
+ .set({ modifiedAt: new Date() })
+ .where(
+ and(
+ eq(bookmarks.id, input.bookmarkId),
+ eq(bookmarks.userId, ctx.user.id),
+ ),
+ );
+ }
return {
bookmarkId: input.bookmarkId,
attached: allIdsToAttach,
detached: idsToRemove,
+ numChanges,
};
});
- await Promise.allSettled([
- triggerRuleEngineOnEvent(input.bookmarkId, [
- ...res.detached.map((t) => ({
- type: "tagRemoved" as const,
- tagId: t,
- })),
- ...res.attached.map((t) => ({
- type: "tagAdded" as const,
- tagId: t,
- })),
- ]),
- triggerSearchReindex(input.bookmarkId, {
- groupId: ctx.user.id,
- }),
- triggerWebhook(input.bookmarkId, "edited", ctx.user.id, {
- groupId: ctx.user.id,
- }),
- ]);
+ if (res.numChanges > 0) {
+ await Promise.allSettled([
+ triggerRuleEngineOnEvent(input.bookmarkId, [
+ ...res.detached.map((t) => ({
+ type: "tagRemoved" as const,
+ tagId: t,
+ })),
+ ...res.attached.map((t) => ({
+ type: "tagAdded" as const,
+ tagId: t,
+ })),
+ ]),
+ triggerSearchReindex(input.bookmarkId, {
+ groupId: ctx.user.id,
+ }),
+ triggerWebhook(input.bookmarkId, "edited", ctx.user.id, {
+ groupId: ctx.user.id,
+ }),
+ ]);
+ }
return res;
}),
getBrokenLinks: authedProcedure