Elffuss BraidHub

kikocis/continue public

6e4b7e9fc0a8 · 14.6 KiBRawPermalink
1import crypto from "node:crypto";
2import * as fs from "node:fs";
3
4import plimit from "p-limit";
5import { open, type Database } from "sqlite";
6import sqlite3 from "sqlite3";
7
8import { FileStatsMap, IndexTag, IndexingProgressUpdate } from "../index.js";
9import { getIndexSqlitePath } from "../util/paths.js";
10
11import {
12 CodebaseIndex,
13 IndexResultType,
14 MarkCompleteCallback,
15 PathAndCacheKey,
16 RefreshIndexResults,
17} from "./types.js";
18
19export type DatabaseConnection = Database<sqlite3.Database>;
20
21export class SqliteDb {
22 static db: DatabaseConnection | null = null;
23
24 private static async createTables(db: DatabaseConnection) {
25 await db.exec("PRAGMA journal_mode=WAL;");
26
27 await db.exec(
28 `CREATE TABLE IF NOT EXISTS tag_catalog (
29 id INTEGER PRIMARY KEY AUTOINCREMENT,
30 dir STRING NOT NULL,
31 branch STRING NOT NULL,
32 artifactId STRING NOT NULL,
33 path STRING NOT NULL,
34 cacheKey STRING NOT NULL,
35 lastUpdated INTEGER NOT NULL
36 )`,
37 );
38
39 await db.exec(
40 `CREATE TABLE IF NOT EXISTS global_cache (
41 id INTEGER PRIMARY KEY AUTOINCREMENT,
42 cacheKey STRING NOT NULL,
43 dir STRING NOT NULL,
44 branch STRING NOT NULL,
45 artifactId STRING NOT NULL
46 )`,
47 );
48 // Delete duplicate rows from tag_catalog
49 await db.exec(`
50 DELETE FROM tag_catalog
51 WHERE id NOT IN (
52 SELECT MIN(id)
53 FROM tag_catalog
54 GROUP BY dir, branch, artifactId, path, cacheKey
55 )
56 `);
57
58 // Delete duplicate rows from global_cache
59 await db.exec(`
60 DELETE FROM global_cache
61 WHERE id NOT IN (
62 SELECT MIN(id)
63 FROM global_cache
64 GROUP BY cacheKey, dir, branch, artifactId
65 )
66 `);
67
68 // Add unique constraints if they don't exist
69 await db.exec(
70 `CREATE UNIQUE INDEX IF NOT EXISTS idx_tag_catalog_unique
71 ON tag_catalog(dir, branch, artifactId, path, cacheKey)`,
72 );
73
74 await db.exec(
75 `CREATE UNIQUE INDEX IF NOT EXISTS idx_global_cache_unique
76 ON global_cache(cacheKey, dir, branch, artifactId)`,
77 );
78 }
79
80 private static indexSqlitePath = getIndexSqlitePath();
81
82 static async get() {
83 if (SqliteDb.db && fs.existsSync(SqliteDb.indexSqlitePath)) {
84 return SqliteDb.db;
85 }
86
87 SqliteDb.indexSqlitePath = getIndexSqlitePath();
88 SqliteDb.db = await open({
89 filename: SqliteDb.indexSqlitePath,
90 driver: sqlite3.Database,
91 });
92
93 await SqliteDb.db.exec("PRAGMA busy_timeout = 3000;");
94
95 await SqliteDb.createTables(SqliteDb.db);
96
97 return SqliteDb.db;
98 }
99}
100
101async function getSavedItemsForTag(
102 tag: IndexTag,
103): Promise<{ path: string; cacheKey: string; lastUpdated: number }[]> {
104 const db = await SqliteDb.get();
105 const stmt = await db.prepare(
106 `SELECT path, cacheKey, lastUpdated FROM tag_catalog
107 WHERE dir = ? AND branch = ? AND artifactId = ?`,
108 tag.directory,
109 tag.branch,
110 tag.artifactId,
111 );
112 const rows = await stmt.all();
113 return rows;
114}
115
116enum AddRemoveResultType {
117 Add = "add",
118 Remove = "remove",
119 UpdateNewVersion = "updateNewVersion",
120 UpdateOldVersion = "updateOldVersion",
121 UpdateLastUpdated = "updateLastUpdated",
122 Compute = "compute",
123}
124
125// Don't attempt to index anything over 5MB
126const MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024;
127
128async function getAddRemoveForTag(
129 tag: IndexTag,
130 currentFiles: FileStatsMap,
131 readFile: (path: string) => Promise<string>,
132): Promise<
133 [
134 PathAndCacheKey[],
135 PathAndCacheKey[],
136 PathAndCacheKey[],
137 MarkCompleteCallback,
138 ]
139> {
140 const newLastUpdatedTimestamp = Date.now();
141 const files = { ...currentFiles };
142
143 for (const path in files) {
144 if (files[path].size > MAX_FILE_SIZE_BYTES) {
145 delete files[path];
146 }
147 }
148
149 const saved = await getSavedItemsForTag(tag);
150
151 const updateNewVersion: PathAndCacheKey[] = [];
152 const updateOldVersion: PathAndCacheKey[] = [];
153 const remove: PathAndCacheKey[] = [];
154 const updateLastUpdated: PathAndCacheKey[] = [];
155
156 // First, group items by path and find latest timestamp for each
157 const pathGroups = new Map<
158 string,
159 {
160 latest: { lastUpdated: number; cacheKey: string };
161 allVersions: Array<{ cacheKey: string }>;
162 }
163 >();
164
165 for (const item of saved) {
166 const { lastUpdated, path, cacheKey } = item;
167
168 if (!pathGroups.has(path)) {
169 pathGroups.set(path, {
170 latest: { lastUpdated, cacheKey },
171 allVersions: [{ cacheKey }],
172 });
173 } else {
174 const group = pathGroups.get(path)!;
175 group.allVersions.push({ cacheKey });
176 if (lastUpdated > group.latest.lastUpdated) {
177 group.latest = { lastUpdated, cacheKey };
178 }
179 }
180 }
181
182 // Now process each unique path
183 for (const [path, group] of pathGroups) {
184 if (files[path] === undefined) {
185 // Was indexed, but no longer exists. Remove all versions
186 for (const version of group.allVersions) {
187 remove.push({ path, cacheKey: version.cacheKey });
188 }
189 } else {
190 // Exists in old and new, so determine whether it was updated
191 if (group.latest.lastUpdated < files[path].lastModified) {
192 // Change was made after last update
193 const newHash = calculateHash(await readFile(path));
194 if (group.latest.cacheKey !== newHash) {
195 updateNewVersion.push({
196 path,
197 cacheKey: newHash,
198 });
199 for (const version of group.allVersions) {
200 updateOldVersion.push({ path, cacheKey: version.cacheKey });
201 }
202 } else {
203 // File contents did not change
204 updateLastUpdated.push({ path, cacheKey: group.latest.cacheKey });
205 for (const version of group.allVersions) {
206 if (version.cacheKey !== group.latest.cacheKey) {
207 updateOldVersion.push({ path, cacheKey: version.cacheKey });
208 }
209 }
210 }
211 } else {
212 // Already updated, do nothing
213 }
214
215 // Remove path, so that only newly created paths remain
216 delete files[path];
217 }
218 }
219
220 // limit to only 10 concurrent file reads to avoid issues such as
221 // "too many file handles". A large number here does not improve
222 // throughput due to the nature of disk or network i/o -- huge
223 // amounts of readers generally does not improve performance
224 const limit = plimit(10);
225 const promises = Object.keys(files).map(async (path) => {
226 const fileContents = await limit(() => readFile(path));
227 return { path, cacheKey: calculateHash(fileContents) };
228 });
229 const add: PathAndCacheKey[] = await Promise.all(promises);
230
231 // Create the markComplete callback function
232 const db = await SqliteDb.get();
233 const itemToAction: {
234 [key in AddRemoveResultType]: PathAndCacheKey[];
235 } = {
236 [AddRemoveResultType.Add]: [],
237 [AddRemoveResultType.Remove]: [],
238 [AddRemoveResultType.UpdateNewVersion]: [],
239 [AddRemoveResultType.UpdateOldVersion]: [],
240 [AddRemoveResultType.UpdateLastUpdated]: [],
241 [AddRemoveResultType.Compute]: [],
242 };
243
244 async function markComplete(
245 items: PathAndCacheKey[],
246 resultType: IndexResultType,
247 ) {
248 const addRemoveResultType =
249 mapIndexResultTypeToAddRemoveResultType(resultType);
250
251 const actionItems = itemToAction[addRemoveResultType];
252 if (!actionItems) {
253 console.warn(`No action items found for result type: ${resultType}`);
254 return;
255 }
256
257 for (const item of items) {
258 const { path, cacheKey } = item;
259 switch (addRemoveResultType) {
260 case AddRemoveResultType.Compute:
261 await db.run(
262 "REPLACE INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)",
263 path,
264 cacheKey,
265 newLastUpdatedTimestamp,
266 tag.directory,
267 tag.branch,
268 tag.artifactId,
269 );
270 break;
271 case AddRemoveResultType.Add:
272 await db.run(
273 "REPLACE INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)",
274 path,
275 cacheKey,
276 newLastUpdatedTimestamp,
277 tag.directory,
278 tag.branch,
279 tag.artifactId,
280 );
281 break;
282 case AddRemoveResultType.Remove:
283 await db.run(
284 `DELETE FROM tag_catalog WHERE
285 cacheKey = ? AND
286 path = ? AND
287 dir = ? AND
288 branch = ? AND
289 artifactId = ?
290 `,
291 cacheKey,
292 path,
293 tag.directory,
294 tag.branch,
295 tag.artifactId,
296 );
297 break;
298 case AddRemoveResultType.UpdateLastUpdated:
299 case AddRemoveResultType.UpdateNewVersion:
300 await db.run(
301 `UPDATE tag_catalog SET
302 cacheKey = ?,
303 lastUpdated = ?
304 WHERE
305 path = ? AND
306 dir = ? AND
307 branch = ? AND
308 artifactId = ?
309 `,
310 cacheKey,
311 newLastUpdatedTimestamp,
312 path,
313 tag.directory,
314 tag.branch,
315 tag.artifactId,
316 );
317 break;
318 case AddRemoveResultType.UpdateOldVersion:
319 break;
320 }
321 }
322 }
323
324 for (const item of updateNewVersion) {
325 itemToAction[AddRemoveResultType.UpdateNewVersion].push(item);
326 }
327 for (const item of add) {
328 itemToAction[AddRemoveResultType.Add].push(item);
329 }
330 for (const item of updateOldVersion) {
331 itemToAction[AddRemoveResultType.UpdateOldVersion].push(item);
332 }
333 for (const item of remove) {
334 itemToAction[AddRemoveResultType.Remove].push(item);
335 }
336
337 return [
338 [...add, ...updateNewVersion],
339 [...remove, ...updateOldVersion],
340 updateLastUpdated,
341 markComplete,
342 ];
343}
344
345/**
346 * Check the global cache for items with this cacheKey for the given artifactId.
347 * Return all of the tags that it exists under, which could be an empty array
348 */
349async function getTagsFromGlobalCache(
350 cacheKey: string,
351 artifactId: string,
352): Promise<IndexTag[]> {
353 const db = await SqliteDb.get();
354 const stmt = await db.prepare(
355 "SELECT dir, branch, artifactId FROM global_cache WHERE cacheKey = ? AND artifactId = ?",
356 );
357 const rows = await stmt.all(cacheKey, artifactId);
358 return rows;
359}
360
361function calculateHash(fileContents: string): string {
362 const hash = crypto.createHash("sha256");
363 hash.update(fileContents);
364 return hash.digest("hex");
365}
366
367function mapIndexResultTypeToAddRemoveResultType(
368 resultType: IndexResultType,
369): AddRemoveResultType {
370 switch (resultType) {
371 case "updateLastUpdated":
372 return AddRemoveResultType.UpdateLastUpdated;
373 case "compute":
374 return AddRemoveResultType.Compute;
375 case "addTag":
376 return AddRemoveResultType.Add;
377 case "del":
378 case "removeTag":
379 return AddRemoveResultType.Remove;
380 default:
381 throw new Error(`Unexpected result type: ${resultType}`);
382 }
383}
384
385export async function getComputeDeleteAddRemove(
386 tag: IndexTag,
387 currentFiles: FileStatsMap,
388 readFile: (path: string) => Promise<string>,
389 repoName: string | undefined,
390): Promise<[RefreshIndexResults, PathAndCacheKey[], MarkCompleteCallback]> {
391 const [add, remove, lastUpdated, markComplete] = await getAddRemoveForTag(
392 tag,
393 currentFiles,
394 readFile,
395 );
396
397 const compute: PathAndCacheKey[] = [];
398 const del: PathAndCacheKey[] = [];
399 const addTag: PathAndCacheKey[] = [];
400 const removeTag: PathAndCacheKey[] = [];
401
402 for (const { path, cacheKey } of add) {
403 const existingTags = await getTagsFromGlobalCache(cacheKey, tag.artifactId);
404 if (existingTags.length > 0) {
405 addTag.push({ path, cacheKey });
406 } else {
407 compute.push({ path, cacheKey });
408 }
409 }
410
411 for (const { path, cacheKey } of remove) {
412 const existingTags = await getTagsFromGlobalCache(cacheKey, tag.artifactId);
413 if (existingTags.length > 1) {
414 removeTag.push({ path, cacheKey });
415 } else {
416 if (existingTags.length === 0) {
417 // console.warn("Existing tags should not be empty when trying to remove");
418 }
419
420 del.push({ path, cacheKey });
421 }
422 }
423
424 const results = {
425 compute,
426 del,
427 addTag,
428 removeTag,
429 };
430
431 const globalCacheIndex = await GlobalCacheCodeBaseIndex.create();
432
433 return [
434 results,
435 lastUpdated,
436 async (items, resultType) => {
437 // Update tag catalog
438 await markComplete(items, resultType);
439
440 // Update the global cache
441 const results: any = {
442 compute: [],
443 del: [],
444 addTag: [],
445 removeTag: [],
446 };
447 results[resultType] = items;
448 for await (const _ of globalCacheIndex.update(
449 tag,
450 results,
451 async () => {},
452 repoName,
453 )) {
454 }
455 },
456 ];
457}
458
459export class GlobalCacheCodeBaseIndex implements CodebaseIndex {
460 relativeExpectedTime: number = 1;
461
462 constructor(private db: DatabaseConnection) {}
463
464 artifactId = "globalCache";
465
466 static async create(): Promise<GlobalCacheCodeBaseIndex> {
467 return new GlobalCacheCodeBaseIndex(await SqliteDb.get());
468 }
469
470 async *update(
471 tag: IndexTag,
472 results: RefreshIndexResults,
473 _: MarkCompleteCallback,
474 repoName: string | undefined,
475 ): AsyncGenerator<IndexingProgressUpdate> {
476 const add = [...results.compute, ...results.addTag];
477 const remove = [...results.del, ...results.removeTag];
478 await Promise.all([
479 ...remove.map(({ cacheKey }) => {
480 return this.deleteOrRemoveTag(cacheKey, tag);
481 }),
482 ...add.map(({ cacheKey }) => {
483 return this.computeOrAddTag(cacheKey, tag);
484 }),
485 ]);
486 yield { progress: 1, desc: "Done updating global cache", status: "done" };
487 }
488
489 private async computeOrAddTag(
490 cacheKey: string,
491 tag: IndexTag,
492 ): Promise<void> {
493 await this.db.run(
494 "REPLACE INTO global_cache (cacheKey, dir, branch, artifactId) VALUES (?, ?, ?, ?)",
495 cacheKey,
496 tag.directory,
497 tag.branch,
498 tag.artifactId,
499 );
500 }
501 private async deleteOrRemoveTag(
502 cacheKey: string,
503 tag: IndexTag,
504 ): Promise<void> {
505 await this.db.run(
506 "DELETE FROM global_cache WHERE cacheKey = ? AND dir = ? AND branch = ? AND artifactId = ?",
507 cacheKey,
508 tag.directory,
509 tag.branch,
510 tag.artifactId,
511 );
512 }
513}
514
515const SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000;
516
517export function truncateToLastNBytes(input: string, maxBytes: number): string {
518 let bytes = 0;
519 let startIndex = 0;
520
521 for (let i = input.length - 1; i >= 0; i--) {
522 bytes += new TextEncoder().encode(input[i]).length;
523 if (bytes > maxBytes) {
524 startIndex = i + 1;
525 break;
526 }
527 }
528
529 return input.substring(startIndex, input.length);
530}
531
532export function truncateSqliteLikePattern(input: string, safety: number = 100) {
533 return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH - safety);
534}