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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
|
import { Env, PageOrNoteChunks, TweetChunks, vectorObj } from "../types";
import { typeDecider } from "./utils/typeDecider";
import { isErr, wrap } from "../errors/results";
import { processNote } from "./helpers/processNotes";
import { processPage } from "./helpers/processPage";
import { getThreadData, getTweetData } from "./helpers/processTweet";
import { tweetToMd } from "@repo/shared-types/utils";
import { chunkNote, chunkPage } from "./chunkers/chunkPageOrNotes";
import { chunkThread } from "./chunkers/chunkTweet";
import { batchCreateChunksAndEmbeddings, initQuery } from "../helper";
import { z } from "zod";
import { Metadata } from "./utils/get-metadata";
import { BaseError } from "../errors/baseError";
import { database } from "../db";
import {
storedContent,
space,
contentToSpace,
users,
jobs,
Job,
} from "@repo/db/schema";
import { and, eq, inArray, sql } from "drizzle-orm";
class VectorInsertError extends BaseError {
constructor(message?: string, source?: string) {
super("[Vector Insert Error]", message, source);
}
}
const vectorErrorFactory = (err: Error) => new VectorInsertError(err.message);
class D1InsertError extends BaseError {
constructor(message?: string, source?: string) {
super("[D1 Insert Error]", message, source);
}
}
const d1ErrorFactory = (err: Error, source: string) =>
new D1InsertError(err.message, source);
const calculateExponentialBackoff = (
attempts: number,
baseDelaySeconds: number,
) => {
return baseDelaySeconds ** attempts;
};
const BASE_DELAY_SECONDS = 5;
export async function queue(
batch: MessageBatch<{
content: string;
space: Array<number>;
user: string;
type: string;
}>,
env: Env,
): Promise<void> {
const db = database(env);
for (let message of batch.messages) {
const body = message.body;
const type = body.type;
const userExists = await wrap(
db.select().from(users).where(eq(users.id, body.user)).limit(1),
d1ErrorFactory,
"Error when trying to verify user",
);
if (isErr(userExists)) {
throw userExists.error;
}
//check if this is a retry job.. by checking if the combination of the userId and the url already exists on the queue
let jobId;
const existingJob = await wrap(
db
.select()
.from(jobs)
.where(
and(
eq(jobs.userId, userExists.value[0].id),
eq(jobs.url, body.content),
),
)
.limit(1),
d1ErrorFactory,
"Error when checking for existing job",
);
if (isErr(existingJob)) {
throw existingJob.error;
}
if (existingJob.value.length > 0) {
jobId = existingJob.value[0].id;
await wrap(
db
.update(jobs)
.set({
attempts: existingJob.value[0].attempts + 1,
updatedAt: new Date(),
status: "Processing",
})
.where(eq(jobs.id, jobId)),
d1ErrorFactory,
"Error when updating job attempts",
);
} else {
const job = await wrap(
db
.insert(jobs)
.values({
userId: userExists.value[0].id as string,
url: body.content,
status: "Processing",
attempts: 1,
createdAt: new Date(),
updatedAt: new Date(),
})
.returning({ jobId: jobs.id }),
d1ErrorFactory,
"Error When inserting into jobs table",
);
if (isErr(job)) {
throw job.error;
}
jobId = job.value[0].jobId;
}
let pageContent: string;
let vectorData: string;
let metadata: Metadata;
let storeToSpaces = body.space;
let chunks: TweetChunks | PageOrNoteChunks;
let noteId = 0;
switch (type) {
case "note": {
console.log("note hit");
const note = processNote(body.content);
if (isErr(note)) {
throw note.error;
}
pageContent = note.value.noteContent.noteContent;
noteId = note.value.noteContent.noteId;
metadata = note.value.metadata;
vectorData = pageContent;
chunks = chunkNote(pageContent);
break;
}
case "page": {
console.log("page hit");
const page = await processPage({
url: body.content,
securityKey: env.MD_SEC_KEY,
});
if (isErr(page)) {
console.log("there is a page error here");
throw page.error;
}
pageContent = page.value.pageContent;
metadata = page.value.metadata;
vectorData = pageContent;
chunks = chunkPage(pageContent);
break;
}
case "tweet": {
const tweet = await getTweetData(body.content.split("/").pop());
const thread = await getThreadData({
tweetUrl: body.content,
env: env,
});
console.log("[This is the thread]", thread);
if (isErr(tweet)) {
throw tweet.error;
}
pageContent = tweetToMd(tweet.value);
metadata = {
baseUrl: body.content,
description: tweet.value.text.slice(0, 200),
image: tweet.value.user.profile_image_url_https,
title: `Tweet by ${tweet.value.user.name}`,
};
if (isErr(thread)) {
console.log("Thread worker is down!");
vectorData = JSON.stringify(pageContent);
console.error(thread.error);
} else {
console.log("thread worker is fine");
vectorData = thread.value;
}
chunks = chunkThread(vectorData);
break;
}
}
//add to mem0, abstract
const includeMessages = {
note: "information of this user based on the provided note.",
tweet: "interests of this user based on a twitter post they are saving.",
page: "interests of this user based on a web page they are saving.",
};
const mem0Response = fetch("https://api.mem0.ai/v1/memories/", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${env.MEM0_API_KEY}`,
},
body: JSON.stringify({
messages: [
{
role: "user",
content: `Extract information about the user based on this saved content provided, remember that the date was ${new Date().toUTCString()} in utc time zone`,
},
{
role: "user",
content: vectorData.replace(/<raw>.*?<\/raw>/g, ""),
},
],
includes: includeMessages[type],
user_id: body.user,
}),
});
// see what's up with the storedToSpaces in this block
const { store } = await initQuery(env);
type body = z.infer<typeof vectorObj>;
const Chunkbody: body = {
pageContent: pageContent,
spaces: storeToSpaces.map((spaceId) => spaceId.toString()),
user: body.user,
type: type,
url: metadata.baseUrl,
description: metadata.description,
title: metadata.title,
};
try {
const vectorResult = await wrap(
batchCreateChunksAndEmbeddings({
store: store,
body: Chunkbody,
chunks: chunks,
env: env,
}),
vectorErrorFactory,
"Error when Inserting into vector database",
);
if (isErr(vectorResult)) {
await db
.update(jobs)
.set({ error: vectorResult.error.message, status: "error" })
.where(eq(jobs.id, jobId));
message.retry({
delaySeconds: calculateExponentialBackoff(
message.attempts,
BASE_DELAY_SECONDS,
),
});
throw vectorResult.error;
}
const saveToDbUrl =
(metadata.baseUrl.split("#supermemory-user-")[0] ?? metadata.baseUrl) +
"#supermemory-user-" +
body.user;
let contentId: number;
const insertResponse = await wrap(
db
.insert(storedContent)
.values({
content: pageContent as string,
title: metadata.title,
description: metadata.description,
url: saveToDbUrl,
baseUrl: saveToDbUrl,
image: metadata.image,
savedAt: new Date(),
userId: body.user,
type: type,
noteId: noteId,
})
.returning({ id: storedContent.id }),
d1ErrorFactory,
"Error when inserting into storedContent",
);
if (isErr(insertResponse)) {
await db
.update(jobs)
.set({ error: insertResponse.error.message, status: "error" })
.where(eq(jobs.id, jobId));
message.retry({
delaySeconds: calculateExponentialBackoff(
message.attempts,
BASE_DELAY_SECONDS,
),
});
throw insertResponse.error;
}
contentId = insertResponse.value[0].id;
if (storeToSpaces.length > 0) {
// Adding the many-to-many relationship between content and spaces
const spaceData = await wrap(
db
.select()
.from(space)
.where(
and(inArray(space.id, storeToSpaces), eq(space.user, body.user)),
)
.all(),
d1ErrorFactory,
"Error when getting data from spaces",
);
if (isErr(spaceData)) {
throw spaceData.error;
}
try {
await Promise.all(
spaceData.value.map(async (s) => {
try {
await db
.insert(contentToSpace)
.values({ contentId: contentId, spaceId: s.id });
await db.update(space).set({ numItems: s.numItems + 1 });
} catch (e) {
console.error(`Error updating space ${s.id}:`, e);
throw e;
}
}),
);
} catch (e) {
console.error("Error in updateSpacesWithContent:", e);
throw new Error(`Failed to update spaces: ${e.message}`);
}
}
} catch (e) {
console.error("Error in simulated transaction", e.message);
message.retry({
delaySeconds: calculateExponentialBackoff(
message.attempts,
BASE_DELAY_SECONDS,
),
});
throw new D1InsertError(
"Error when inserting into d1",
"D1 stuff after the vectorize",
);
}
// After the d1 and vectories suceeds then finally update the jobs table to indicate that the job has completed
await db
.update(jobs)
.set({ status: "Processed" })
.where(eq(jobs.id, jobId));
return;
}
}
/*
To do:
Figure out rate limits!!
*/
|