Elffuss BraidHub

kikocis/continue public

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