Elffuss BraidHub

kikocis/continue public

99fe51849b68 · 7.2 KiBRawPermalink
1import * as path from "path";
2
3import { RunResult } from "sqlite3";
4
5import { IContinueServerClient } from "../../continueServer/interface.js";
6import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js";
7import { DatabaseConnection, SqliteDb } from "../refreshIndex.js";
8import {
9 IndexResultType,
10 MarkCompleteCallback,
11 PathAndCacheKey,
12 RefreshIndexResults,
13 type CodebaseIndex,
14} from "../types.js";
15
16import { getUriPathBasename } from "../../util/uri.js";
17import { tagToString } from "../utils.js";
18import { chunkDocument, shouldChunk } from "./chunk.js";
19
20export 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 await db.run(
81 `
82 INSERT INTO chunk_tags (chunkId, tag)
83 SELECT id, ? FROM chunks
84 WHERE cacheKey = ?
85 `,
86 [tagString, item.cacheKey],
87 );
88 await markComplete([item], IndexResultType.AddTag);
89 accumulatedProgress += 1 / results.addTag.length / 4;
90 yield {
91 progress: accumulatedProgress,
92 desc: `Adding ${getUriPathBasename(item.path)}`,
93 status: "indexing",
94 };
95 }
96
97 // Remove tag
98 for (const item of results.removeTag) {
99 await db.run(
100 `
101 DELETE FROM chunk_tags
102 WHERE tag = ?
103 AND chunkId IN (
104 SELECT id FROM chunks
105 WHERE cacheKey = ? AND path = ?
106 )
107 `,
108 [tagString, item.cacheKey, item.path],
109 );
110 await markComplete([item], IndexResultType.RemoveTag);
111 accumulatedProgress += 1 / results.removeTag.length / 4;
112 yield {
113 progress: accumulatedProgress,
114 desc: `Removing ${getUriPathBasename(item.path)}`,
115 status: "indexing",
116 };
117 }
118
119 // Delete
120 for (const item of results.del) {
121 const chunkToDelete = await db.get(
122 "SELECT id FROM chunks WHERE cacheKey = ?",
123 [item.cacheKey],
124 );
125
126 if (chunkToDelete) {
127 await db.run("DELETE FROM chunks WHERE id = ?", [chunkToDelete.id]);
128
129 // Delete from chunk_tags
130 await db.run("DELETE FROM chunk_tags WHERE chunkId = ?", [
131 chunkToDelete.id,
132 ]);
133 } else {
134 console.debug("Chunk to delete wasn't found in the table: ", item.path);
135 }
136
137 await markComplete([item], IndexResultType.Delete);
138 accumulatedProgress += 1 / results.del.length / 4;
139 yield {
140 progress: accumulatedProgress,
141 desc: `Removing ${getUriPathBasename(item.path)}`,
142 status: "indexing",
143 };
144 }
145 }
146
147 private async createTables(db: DatabaseConnection) {
148 await db.exec(`CREATE TABLE IF NOT EXISTS chunks (
149 id INTEGER PRIMARY KEY AUTOINCREMENT,
150 cacheKey TEXT NOT NULL,
151 path TEXT NOT NULL,
152 idx INTEGER NOT NULL,
153 startLine INTEGER NOT NULL,
154 endLine INTEGER NOT NULL,
155 content TEXT NOT NULL
156 )`);
157
158 await db.exec(`CREATE TABLE IF NOT EXISTS chunk_tags (
159 id INTEGER PRIMARY KEY AUTOINCREMENT,
160 tag TEXT NOT NULL,
161 chunkId INTEGER NOT NULL,
162 FOREIGN KEY (chunkId) REFERENCES chunks (id),
163 UNIQUE (tag, chunkId)
164 )`);
165 }
166
167 private async packToChunks(pack: PathAndCacheKey): Promise<Chunk[]> {
168 const contents = await this.readFile(pack.path);
169 if (!shouldChunk(pack.path, contents)) {
170 return [];
171 }
172 const chunks: Chunk[] = [];
173 const chunkParams = {
174 filepath: pack.path,
175 contents,
176 maxChunkSize: this.maxChunkSize,
177 digest: pack.cacheKey,
178 };
179 for await (const c of chunkDocument(chunkParams)) {
180 chunks.push(c);
181 }
182 return chunks;
183 }
184
185 private async computeChunks(paths: PathAndCacheKey[]): Promise<Chunk[]> {
186 const chunkLists = await Promise.all(
187 paths.map((p) => this.packToChunks(p)),
188 );
189 return chunkLists.flat();
190 }
191
192 private async insertChunks(
193 db: DatabaseConnection,
194 tagString: string,
195 chunks: Chunk[],
196 ) {
197 await new Promise<void>((resolve, reject) => {
198 db.db.serialize(() => {
199 db.db.exec("BEGIN", (err: Error | null) => {
200 if (err) {
201 reject(new Error("error creating transaction", { cause: err }));
202 }
203 });
204 const chunksSQL =
205 "INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)";
206 chunks.map((c) => {
207 db.db.run(
208 chunksSQL,
209 [c.digest, c.filepath, c.index, c.startLine, c.endLine, c.content],
210 (result: RunResult, err: Error) => {
211 if (err) {
212 reject(
213 new Error("error inserting into chunks table", {
214 cause: err,
215 }),
216 );
217 }
218 },
219 );
220 const chunkTagsSQL =
221 "INSERT INTO chunk_tags (chunkId, tag) VALUES (last_insert_rowid(), ?)";
222 db.db.run(
223 chunkTagsSQL,
224 [tagString],
225 (result: RunResult, err: Error) => {
226 if (err) {
227 reject(
228 new Error("error inserting into chunk_tags table", {
229 cause: err,
230 }),
231 );
232 }
233 },
234 );
235 });
236 db.db.exec("COMMIT", (err: Error | null) => {
237 if (err) {
238 reject(
239 new Error("error while committing insert chunks transaction", {
240 cause: err,
241 }),
242 );
243 } else {
244 resolve();
245 }
246 });
247 });
248 });
249 }
250}