1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
|
import deepEql from "deep-equal";
import { and, eq } from "drizzle-orm";
import { bookmarks, tagsOnBookmarks } from "@karakeep/db/schema";
import { LinkCrawlerQueue } from "@karakeep/shared-server";
import {
RuleEngineAction,
RuleEngineCondition,
RuleEngineEvent,
RuleEngineRule,
} from "@karakeep/shared/types/rules";
import { AuthedContext } from "..";
import { List } from "../models/lists";
import { RuleEngineRuleModel } from "../models/rules";
async function fetchBookmark(db: AuthedContext["db"], bookmarkId: string) {
return await db.query.bookmarks.findFirst({
where: eq(bookmarks.id, bookmarkId),
with: {
link: {
columns: {
url: true,
},
},
text: true,
asset: true,
tagsOnBookmarks: true,
rssFeeds: {
columns: {
rssFeedId: true,
},
},
user: {
columns: {},
with: {
rules: {
with: {
actions: true,
},
},
},
},
},
});
}
type ReturnedBookmark = NonNullable<Awaited<ReturnType<typeof fetchBookmark>>>;
export interface RuleEngineEvaluationResult {
type: "success" | "failure";
ruleId: string;
message: string;
}
export class RuleEngine {
private constructor(
private ctx: AuthedContext,
private bookmark: Omit<ReturnedBookmark, "user">,
private rules: RuleEngineRule[],
) {}
static async forBookmark(ctx: AuthedContext, bookmarkId: string) {
const [bookmark, rules] = await Promise.all([
fetchBookmark(ctx.db, bookmarkId),
RuleEngineRuleModel.getAll(ctx),
]);
if (!bookmark) {
throw new Error(`Bookmark ${bookmarkId} not found`);
}
return new RuleEngine(
ctx,
bookmark,
rules.map((r) => r.rule),
);
}
doesBookmarkMatchConditions(condition: RuleEngineCondition): boolean {
switch (condition.type) {
case "alwaysTrue": {
return true;
}
case "urlContains": {
return (this.bookmark.link?.url ?? "").includes(condition.str);
}
case "importedFromFeed": {
return this.bookmark.rssFeeds.some(
(f) => f.rssFeedId === condition.feedId,
);
}
case "bookmarkTypeIs": {
return this.bookmark.type === condition.bookmarkType;
}
case "hasTag": {
return this.bookmark.tagsOnBookmarks.some(
(t) => t.tagId === condition.tagId,
);
}
case "isFavourited": {
return this.bookmark.favourited;
}
case "isArchived": {
return this.bookmark.archived;
}
case "and": {
return condition.conditions.every((c) =>
this.doesBookmarkMatchConditions(c),
);
}
case "or": {
return condition.conditions.some((c) =>
this.doesBookmarkMatchConditions(c),
);
}
default: {
const _exhaustiveCheck: never = condition;
return false;
}
}
}
async evaluateRule(
rule: RuleEngineRule,
event: RuleEngineEvent,
): Promise<RuleEngineEvaluationResult[]> {
if (!rule.enabled) {
return [];
}
if (!deepEql(rule.event, event, { strict: true })) {
return [];
}
if (!this.doesBookmarkMatchConditions(rule.condition)) {
return [];
}
const results = await Promise.allSettled(
rule.actions.map((action) => this.executeAction(action)),
);
return results.map((result) => {
if (result.status === "fulfilled") {
return {
type: "success",
ruleId: rule.id,
message: result.value,
};
} else {
return {
type: "failure",
ruleId: rule.id,
message: (result.reason as Error).message,
};
}
});
}
async executeAction(action: RuleEngineAction): Promise<string> {
switch (action.type) {
case "addTag": {
await this.ctx.db
.insert(tagsOnBookmarks)
.values([
{
attachedBy: "human",
bookmarkId: this.bookmark.id,
tagId: action.tagId,
},
])
.onConflictDoNothing();
return `Added tag ${action.tagId}`;
}
case "removeTag": {
await this.ctx.db
.delete(tagsOnBookmarks)
.where(
and(
eq(tagsOnBookmarks.tagId, action.tagId),
eq(tagsOnBookmarks.bookmarkId, this.bookmark.id),
),
);
return `Removed tag ${action.tagId}`;
}
case "addToList": {
const list = await List.fromId(this.ctx, action.listId);
await list.addBookmark(this.bookmark.id);
return `Added to list ${action.listId}`;
}
case "removeFromList": {
const list = await List.fromId(this.ctx, action.listId);
await list.removeBookmark(this.bookmark.id);
return `Removed from list ${action.listId}`;
}
case "downloadFullPageArchive": {
await LinkCrawlerQueue.enqueue(
{
bookmarkId: this.bookmark.id,
archiveFullPage: true,
runInference: false,
},
{
groupId: this.bookmark.userId,
},
);
return `Enqueued full page archive`;
}
case "favouriteBookmark": {
await this.ctx.db
.update(bookmarks)
.set({
favourited: true,
})
.where(eq(bookmarks.id, this.bookmark.id));
return `Marked as favourited`;
}
case "archiveBookmark": {
await this.ctx.db
.update(bookmarks)
.set({
archived: true,
})
.where(eq(bookmarks.id, this.bookmark.id));
return `Marked as archived`;
}
default: {
const _exhaustiveCheck: never = action;
return "";
}
}
}
async onEvent(event: RuleEngineEvent): Promise<RuleEngineEvaluationResult[]> {
const results = await Promise.all(
this.rules.map((rule) => this.evaluateRule(rule, event)),
);
return results.flat();
}
}
|