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