| 1 | import * as path from "path"; |
| 2 | |
| 3 | import { RunResult } from "sqlite3"; |
| 4 | |
| 5 | import { IContinueServerClient } from "../../continueServer/interface.js"; |
| 6 | import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js"; |
| 7 | import { DatabaseConnection, SqliteDb } from "../refreshIndex.js"; |
| 8 | import { |
| 9 | IndexResultType, |
| 10 | MarkCompleteCallback, |
| 11 | PathAndCacheKey, |
| 12 | RefreshIndexResults, |
| 13 | type CodebaseIndex, |
| 14 | } from "../types.js"; |
| 15 | |
| 16 | import { getUriPathBasename } from "../../util/uri.js"; |
| 17 | import { tagToString } from "../utils.js"; |
| 18 | import { chunkDocument, shouldChunk } from "./chunk.js"; |
| 19 | |
| 20 | export class ChunkCodebaseIndex implements CodebaseIndex { |
| 21 | relativeExpectedTime: number = 1; |
| 22 | static artifactId = "chunks"; |
| 23 | artifactId: string = ChunkCodebaseIndex.artifactId; |
| 24 | |
| 25 | constructor( |
| 26 | private readonly readFile: (filepath: string) => Promise<string>, |
| 27 | private readonly continueServerClient: IContinueServerClient, |
| 28 | private readonly maxChunkSize: number, |
| 29 | ) {} |
| 30 | |
| 31 | async *update( |
| 32 | tag: IndexTag, |
| 33 | results: RefreshIndexResults, |
| 34 | markComplete: MarkCompleteCallback, |
| 35 | repoName: string | undefined, |
| 36 | ): AsyncGenerator<IndexingProgressUpdate, any, unknown> { |
| 37 | const db = await SqliteDb.get(); |
| 38 | await this.createTables(db); |
| 39 | const tagString = tagToString(tag); |
| 40 | |
| 41 | // Check the remote cache |
| 42 | if (this.continueServerClient.connected) { |
| 43 | try { |
| 44 | const keys = results.compute.map(({ cacheKey }) => cacheKey); |
| 45 | const resp = await this.continueServerClient.getFromIndexCache( |
| 46 | keys, |
| 47 | "chunks", |
| 48 | repoName, |
| 49 | ); |
| 50 | |
| 51 | for (const [cacheKey, chunks] of Object.entries(resp.files)) { |
| 52 | await this.insertChunks(db, tagString, chunks); |
| 53 | } |
| 54 | results.compute = results.compute.filter( |
| 55 | (item) => !resp.files[item.cacheKey], |
| 56 | ); |
| 57 | } catch (e) { |
| 58 | console.error("Failed to fetch from remote cache: ", e); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | let accumulatedProgress = 0; |
| 63 | |
| 64 | if (results.compute.length > 0) { |
| 65 | const filepath = results.compute[0].path; |
| 66 | const folderName = path.basename(path.dirname(filepath)); |
| 67 | |
| 68 | yield { |
| 69 | desc: `Chunking files in ${folderName}`, |
| 70 | status: "indexing", |
| 71 | progress: accumulatedProgress, |
| 72 | }; |
| 73 | const chunks = await this.computeChunks(results.compute); |
| 74 | await this.insertChunks(db, tagString, chunks); |
| 75 | await markComplete(results.compute, IndexResultType.Compute); |
| 76 | } |
| 77 | |
| 78 | // Add tag |
| 79 | for (const item of results.addTag) { |
| 80 | try { |
| 81 | await db.run( |
| 82 | ` |
| 83 | INSERT INTO chunk_tags (chunkId, tag) |
| 84 | SELECT id, ? FROM chunks |
| 85 | WHERE cacheKey = ? |
| 86 | `, |
| 87 | [tagString, item.cacheKey], |
| 88 | ); |
| 89 | } catch (e: any) { |
| 90 | if (!e.message.includes("UNIQUE constraint")) { |
| 91 | // Throw any errors other than duplicate tag |
| 92 | // Possible the changes were already added by another instance of the extension |
| 93 | // For example vscode running side by side with intellij |
| 94 | throw e; |
| 95 | } |
| 96 | } |
| 97 | await markComplete([item], IndexResultType.AddTag); |
| 98 | accumulatedProgress += 1 / results.addTag.length / 4; |
| 99 | yield { |
| 100 | progress: accumulatedProgress, |
| 101 | desc: `Adding ${getUriPathBasename(item.path)}`, |
| 102 | status: "indexing", |
| 103 | }; |
| 104 | } |
| 105 | |
| 106 | // Remove tag |
| 107 | for (const item of results.removeTag) { |
| 108 | await db.run( |
| 109 | ` |
| 110 | DELETE FROM chunk_tags |
| 111 | WHERE tag = ? |
| 112 | AND chunkId IN ( |
| 113 | SELECT id FROM chunks |
| 114 | WHERE cacheKey = ? AND path = ? |
| 115 | ) |
| 116 | `, |
| 117 | [tagString, item.cacheKey, item.path], |
| 118 | ); |
| 119 | await markComplete([item], IndexResultType.RemoveTag); |
| 120 | accumulatedProgress += 1 / results.removeTag.length / 4; |
| 121 | yield { |
| 122 | progress: accumulatedProgress, |
| 123 | desc: `Removing ${getUriPathBasename(item.path)}`, |
| 124 | status: "indexing", |
| 125 | }; |
| 126 | } |
| 127 | |
| 128 | // Delete |
| 129 | for (const item of results.del) { |
| 130 | const chunkToDelete = await db.get( |
| 131 | "SELECT id FROM chunks WHERE cacheKey = ?", |
| 132 | [item.cacheKey], |
| 133 | ); |
| 134 | |
| 135 | if (chunkToDelete) { |
| 136 | await db.run("DELETE FROM chunks WHERE id = ?", [chunkToDelete.id]); |
| 137 | |
| 138 | // Delete from chunk_tags |
| 139 | await db.run("DELETE FROM chunk_tags WHERE chunkId = ?", [ |
| 140 | chunkToDelete.id, |
| 141 | ]); |
| 142 | } else { |
| 143 | console.debug("Chunk to delete wasn't found in the table: ", item.path); |
| 144 | } |
| 145 | |
| 146 | await markComplete([item], IndexResultType.Delete); |
| 147 | accumulatedProgress += 1 / results.del.length / 4; |
| 148 | yield { |
| 149 | progress: accumulatedProgress, |
| 150 | desc: `Removing ${getUriPathBasename(item.path)}`, |
| 151 | status: "indexing", |
| 152 | }; |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | private async createTables(db: DatabaseConnection) { |
| 157 | await db.exec(`CREATE TABLE IF NOT EXISTS chunks ( |
| 158 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 159 | cacheKey TEXT NOT NULL, |
| 160 | path TEXT NOT NULL, |
| 161 | idx INTEGER NOT NULL, |
| 162 | startLine INTEGER NOT NULL, |
| 163 | endLine INTEGER NOT NULL, |
| 164 | content TEXT NOT NULL |
| 165 | )`); |
| 166 | |
| 167 | await db.exec(`CREATE TABLE IF NOT EXISTS chunk_tags ( |
| 168 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 169 | tag TEXT NOT NULL, |
| 170 | chunkId INTEGER NOT NULL, |
| 171 | FOREIGN KEY (chunkId) REFERENCES chunks (id), |
| 172 | UNIQUE (tag, chunkId) |
| 173 | )`); |
| 174 | } |
| 175 | |
| 176 | private async packToChunks(pack: PathAndCacheKey): Promise<Chunk[]> { |
| 177 | const contents = await this.readFile(pack.path); |
| 178 | if (!shouldChunk(pack.path, contents)) { |
| 179 | return []; |
| 180 | } |
| 181 | const chunks: Chunk[] = []; |
| 182 | const chunkParams = { |
| 183 | filepath: pack.path, |
| 184 | contents, |
| 185 | maxChunkSize: this.maxChunkSize, |
| 186 | digest: pack.cacheKey, |
| 187 | }; |
| 188 | for await (const c of chunkDocument(chunkParams)) { |
| 189 | chunks.push(c); |
| 190 | } |
| 191 | return chunks; |
| 192 | } |
| 193 | |
| 194 | private async computeChunks(paths: PathAndCacheKey[]): Promise<Chunk[]> { |
| 195 | const chunkLists = await Promise.all( |
| 196 | paths.map((p) => this.packToChunks(p)), |
| 197 | ); |
| 198 | return chunkLists.flat(); |
| 199 | } |
| 200 | |
| 201 | private async insertChunks( |
| 202 | db: DatabaseConnection, |
| 203 | tagString: string, |
| 204 | chunks: Chunk[], |
| 205 | ) { |
| 206 | await new Promise<void>((resolve, reject) => { |
| 207 | db.db.serialize(() => { |
| 208 | db.db.exec("BEGIN", (err: Error | null) => { |
| 209 | if (err) { |
| 210 | reject(new Error("error creating transaction", { cause: err })); |
| 211 | } |
| 212 | }); |
| 213 | const chunksSQL = |
| 214 | "INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)"; |
| 215 | chunks.map((c) => { |
| 216 | db.db.run( |
| 217 | chunksSQL, |
| 218 | [c.digest, c.filepath, c.index, c.startLine, c.endLine, c.content], |
| 219 | (result: RunResult, err: Error) => { |
| 220 | if (err) { |
| 221 | reject( |
| 222 | new Error("error inserting into chunks table", { |
| 223 | cause: err, |
| 224 | }), |
| 225 | ); |
| 226 | } |
| 227 | }, |
| 228 | ); |
| 229 | const chunkTagsSQL = |
| 230 | "INSERT INTO chunk_tags (chunkId, tag) VALUES (last_insert_rowid(), ?)"; |
| 231 | db.db.run( |
| 232 | chunkTagsSQL, |
| 233 | [tagString], |
| 234 | (result: RunResult, err: Error) => { |
| 235 | if (err) { |
| 236 | reject( |
| 237 | new Error("error inserting into chunk_tags table", { |
| 238 | cause: err, |
| 239 | }), |
| 240 | ); |
| 241 | } |
| 242 | }, |
| 243 | ); |
| 244 | }); |
| 245 | db.db.exec("COMMIT", (err: Error | null) => { |
| 246 | if (err) { |
| 247 | reject( |
| 248 | new Error("error while committing insert chunks transaction", { |
| 249 | cause: err, |
| 250 | }), |
| 251 | ); |
| 252 | } else { |
| 253 | resolve(); |
| 254 | } |
| 255 | }); |
| 256 | }); |
| 257 | }); |
| 258 | } |
| 259 | } |