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