Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 | 1x 1x 1x 1x 1x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 2x 1x 1x 1x 11x 4x 48x 48x 48x 4x 44x 44x 44x 46x 46x 46x 46x 44x 44x 6x 4x 6x 5x 4x 4x 46x 46x 46x 44x 2x 2x 3x 2x 1x 1x 1x 46x 46x 46x 46x 8x 38x 38x 38x 38x 38x 36x 36x 36x 36x 36x 34x 32x 34x 83x 83x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 38x 38x 38x 38x 48x 1x 47x 47x 1x 1x 1x 46x 5x 5x 5x 5x 41x 38x 34x 41x 40x 1x 34x 41x 41x 41x 1x 1x 1x 40x 40x 34x 38x 38x 38x 38x 38x 40x 47x 47x 47x 35x 35x 35x 38x 38x 40x 40x 40x 40x 40x 40x 6x 6x 40x 40x 40x 34x 34x 40x 40x 40x 38x 38x 38x 9x 34x 29x 29x 29x 29x 29x 34x 40x 46x 46x 46x 46x 46x 46x 46x 46x 46x 5x 46x 6x 46x 46x 46x 46x 46x 40x 40x 46x 46x 46x 5x 5x 2x 3x 3x 3x 3x 46x 46x 41x 35x 35x 35x 3x 32x 32x 32x 35x 35x 35x 35x 34x 33x 33x 30x 29x 30x 30x 2x 5x 5x 5x 5x 5x 5x 7x 7x 7x 1x 6x 6x 6x 6x 7x 7x 6x 5x 46x 46x 46x 46x 178x 178x 93x 85x 85x 85x 25x 24x 1x 1x 1x 1x | import * as vscode from 'vscode';
import picomatch from 'picomatch';
import { IWorkspaceFileService, WorkspaceFileListChangeEvent } from './workspace-file-service.interface';
import { IWorkspaceIndexerService, IndexingStatistics } from './workspace-indexer.interface';
import { IDocumentFactory } from '../document/document-factory.interface';
import { IDocumentTokenSource } from '../document/document-token-source.interface';
import { DocumentContextService } from '../document/document-context-service';
import { DocumentDiagnosticsService } from '../document/document-diagnostics-service';
import { getConfig } from '@src/utilities/vscode/config';
import { isDocumentOpen } from '@src/utilities/vscode/editors';
import { describeUriPath } from '@src/utilities/vscode/log';
import { normalizeGlobPattern } from '@src/utilities/glob';
import { createEventLoopYielder } from '@src/utilities/scheduling';
import { getErrorMessage } from '@src/utilities/error';
import { getHeapUsedMb } from '@src/utilities/runtime';
import { CanonicalWorkspaceUri, WorkspaceUri } from '@src/providers/workspace-uri';
/**
* Per-file indexing duration (ms) above which a file is logged as slow. A single
* RDF file should index in well under a second; anything at or above this points
* to a stall (e.g. a token-wait timeout) rather than genuine parsing work.
*/
const SLOW_FILE_THRESHOLD_MS = 1000;
/**
* How many of the slowest files to list in the per-run timing summary.
*/
const SLOWEST_FILES_TO_LOG = 10;
/**
* How many `fs.stat` calls the pre-scan issues concurrently. The stats are
* independent; bounding the fan-out keeps remote file systems responsive.
*/
const SCAN_CONCURRENCY = 16;
/**
* How many upcoming files the indexing loop reads ahead. Parsing is CPU-bound
* and serialized; prefetching overlaps the next files' I/O with the current
* file's parse so the loop never idles on a cold read.
*/
const READ_PREFETCH = 4;
/**
* How long changes to the workspace file list are collected before the index is
* updated, so that a folder operation reported as several events is handled in
* one indexing pass.
*/
const FILE_LIST_SYNC_DELAY_MS = 500;
/**
* Service for indexing RDF documents in the current workspace.
* Uses WorkspaceFileService for file discovery to avoid duplicate workspace scans.
*/
export class WorkspaceIndexerService implements IWorkspaceIndexerService, vscode.Disposable {
/**
* Indicates if all workspace files have been indexed.
*/
private _indexingFinished = false;
/**
* Summary statistics of the most recent indexing run.
*/
private _statistics?: IndexingStatistics;
/**
* The promise of the indexing pass currently in flight, or `undefined` when idle.
* Used to serialize concurrent {@link indexWorkspace} calls.
*/
private _activeRun?: Promise<void>;
/**
* Indicates that another indexing pass was requested while one was in flight.
*/
private _rerunRequested = false;
/**
* Whether the coalesced trailing pass should force re-indexing.
*/
private _rerunReindex = false;
/**
* Files whose documents are removed from the index at the start of the next indexing
* pass, because they were deleted or changed on disk. Keyed by URI string.
*/
private readonly _pendingRemovals = new Map<string, vscode.Uri>();
/**
* The timer that starts an indexing pass for pending file list changes, or `undefined`.
*/
private _fileListSyncTimer?: ReturnType<typeof setTimeout>;
/**
* Cancels the workspace diagnostics that run after an indexing pass, or `undefined`.
*/
private _diagnosticsCancellation?: vscode.CancellationTokenSource;
/**
* A promise that resolves when all background indexing tasks have
* settled (either fulfilled or rejected).
*/
private readonly _onDidFinishIndexing = new vscode.EventEmitter<boolean>();
/**
* An event that is fired when all workspace files have been indexed.
*/
readonly onDidFinishIndexing = this._onDidFinishIndexing.event;
/**
* A log output channel for indexing-related messages.
*/
private readonly _statusLog: vscode.LogOutputChannel = vscode.window.createOutputChannel('Mentor Indexer', { log: true });
/**
* A status bar item to show indexing related status messages.
*/
// Priorities -10000/-10001/-10002 keep the indexer, graph and SPARQL items in a
// single contiguous group (indexer → graph → SPARQL, left-to-right). The low
// values place the group at the far right of the left-aligned status bar — after
// built-in items like "Auto Attach" (priority 0) — so they are the last items.
private readonly _statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, -10001);
/**
* When the indexing progress was last rendered; see {@link _reportProgress}.
*/
private _lastProgressReport = 0;
constructor(
private readonly _documentFactory: IDocumentFactory,
private readonly _contextService: DocumentContextService,
private readonly _workspaceFileService: IWorkspaceFileService,
private readonly _tokenSource: IDocumentTokenSource,
private readonly _diagnosticsService: DocumentDiagnosticsService
) {
vscode.commands.executeCommand('setContext', 'mentor.workspace.isIndexing', false);
this._statusBarItem.command = {
command: 'mentor.command.openSettings',
title: 'Open Indexing Settings',
arguments: ['workspace.indexing']
};
this._statusBarItem.tooltip = 'Click to open the indexing settings.';
// Show the indexer item immediately so the Mentor icon is always visible in the
// status bar — including on an empty workspace (0 files), where the indexing code
// paths that update the text run late or with nothing to report.
this._statusBarItem.text = '$(list-tree) Indexed 0 files';
this._statusBarItem.show();
this._statusLog.clear();
}
/**
* Loads an open document again during re-indexing through a token delivery: its current
* text is parsed once, its triples are reloaded and its diagnostics are updated.
* @param uri The document URI.
* @returns `true` once the document is loaded again, or `false` if it has no context yet
* and needs to be loaded from its content.
*/
private async _reloadOpenDocument(uri: string): Promise<boolean> {
if (!this._tokenSource.refreshTokens(uri)) {
return false;
}
await this._contextService.waitUntilLoaded(uri);
return true;
}
/**
* Indicates if all workspace files have been indexed.
*/
get indexingFinished(): boolean {
return this._indexingFinished;
}
/**
* Summary statistics of the most recent indexing run, or `undefined` if none completed yet.
*/
get statistics(): IndexingStatistics | undefined {
return this._statistics;
}
/**
* Builds an index of all RDF resources in the current workspace.
* Uses files discovered by WorkspaceFileService instead of scanning again.
*
* Concurrent calls are serialized: while a pass is in flight, additional
* requests are coalesced into a single trailing pass instead of running
* overlapping indexing runs (which would corrupt progress reporting and the
* shared store). If any pending request asks for a reindex, the trailing
* pass forces a reindex.
* @param reindex Whether to force re-indexing of already indexed files.
*/
async indexWorkspace(reindex: boolean = false): Promise<void> {
this._rerunRequested = true;
this._rerunReindex = this._rerunReindex || reindex;
if (this._activeRun) {
return this._activeRun;
}
this._activeRun = (async () => {
try {
while (this._rerunRequested) {
this._rerunRequested = false;
const passReindex = this._rerunReindex;
this._rerunReindex = false;
await this._runIndexingPass(passReindex);
}
} catch (e) {
this._statusLog.error(`Error: ${e}`);
} finally {
this._activeRun = undefined;
}
})();
return this._activeRun;
}
/**
* Updates the index after files were added to, removed from or changed in the
* workspace file list. The documents of removed and changed files are removed from
* the index and the files that are not indexed are indexed by an incremental pass.
* @param e The changes to the workspace file list.
*/
handleFileListChanged(e: WorkspaceFileListChangeEvent): void {
for (const uri of [...e.removed, ...e.changed]) {
this._pendingRemovals.set(uri.toString(), uri);
}
// The delay also lets handlers of a rename read the contexts of the old
// files before they are removed.
if (!this._fileListSyncTimer) {
this._fileListSyncTimer = setTimeout(() => {
this._fileListSyncTimer = undefined;
void this.indexWorkspace();
}, FILE_LIST_SYNC_DELAY_MS);
}
}
/**
* Removes the documents of deleted and changed files from the index and clears
* their diagnostics. Open documents are kept, since their content is still
* available in the editor and kept up to date by it.
*/
private _removePendingDocuments(): void {
const uris = [...this._pendingRemovals.values()].filter(uri => !isDocumentOpen(uri));
this._pendingRemovals.clear();
if (uris.length === 0) {
return;
}
this._contextService.removeDocuments(uris);
for (const uri of uris) {
this._diagnosticsService.deleteDiagnostics(uri);
}
this._statusLog.info(`Removed ${uris.length} deleted or changed files from the index`);
}
/**
* Cancels a scheduled update for pending file list changes.
*/
dispose(): void {
clearTimeout(this._fileListSyncTimer);
this._fileListSyncTimer = undefined;
this._cancelWorkspaceDiagnostics();
}
/**
* Executes a single indexing pass over the discovered workspace files.
* @param reindex Whether to force re-indexing of already indexed files.
*/
private async _runIndexingPass(reindex: boolean): Promise<void> {
// Removing documents only between passes ensures that no pass is loading a
// document while its context and graphs are deleted.
this._removePendingDocuments();
const run = this._startIndexingRun(reindex);
const startTime = performance.now();
if (run.fileUris.length === 0) {
// No files to index — still finalize so the status bar shows the
// summary instead of remaining stuck on the indexing spinner.
this._finalizeIndexingRun(0, [], { completed: 0, errorCount: 0 }, startTime);
} else {
const scanResult = await this._scanIndexFiles(run);
this._reportProgress(0, scanResult.targetFileUris.length);
const summary = await this._runIndexingTasks(scanResult.targetFileUris, run);
this._finalizeIndexingRun(run.fileUris.length, scanResult.skippedFiles, summary, startTime);
if (run.diagnoseFiles) {
this._startWorkspaceDiagnostics(scanResult.targetFileUris);
}
}
}
/**
* Validates the files of a finished indexing pass in the background, for the
* workspace-wide problems overview of `index.diagnoseFiles`. Neither go to
* definition nor the definition tree need the diagnostics, so they no longer
* hold up the end of indexing. A new indexing pass cancels the validation.
* @param uris The files the pass indexed.
*/
private _startWorkspaceDiagnostics(uris: readonly vscode.Uri[]): void {
this._cancelWorkspaceDiagnostics();
const cancellation = new vscode.CancellationTokenSource();
this._diagnosticsCancellation = cancellation;
this._diagnosticsService.diagnoseFiles(uris, undefined, cancellation.token).catch(error => {
this._statusLog.error(`Failed to diagnose the indexed files: ${getErrorMessage(error)}`, error);
}).finally(() => {
if (this._diagnosticsCancellation === cancellation) {
this._diagnosticsCancellation = undefined;
}
cancellation.dispose();
});
}
/**
* Cancels the workspace diagnostics of the previous indexing pass, if they still run.
*/
private _cancelWorkspaceDiagnostics(): void {
this._diagnosticsCancellation?.cancel();
this._diagnosticsCancellation = undefined;
}
/**
* Initializes a workspace indexing run and returns the immutable inputs shared
* across the remaining indexing phases.
* @param reindex Whether to force re-indexing of already indexed files.
* @returns The shared indexing run state.
*/
private _startIndexingRun(reindex: boolean): IndexingRun {
this._indexingFinished = false;
this._cancelWorkspaceDiagnostics();
vscode.commands.executeCommand('setContext', 'mentor.workspace.isIndexing', true);
// Show indexing progress on the indexer's own status bar item so the live
// status and the final summary share the same location.
this._statusBarItem.text = '$(sync~spin) Indexing workspace...';
this._statusBarItem.show();
this._statusLog.info(`-- Started workspace indexing${reindex ? ' (reindex)' : ''}...`);
// The default value is set to Number.MAX_SAFE_INTEGER to disable the
// file size limit and make issues with the configuration more visible.
const maxSize = getConfig().get<number>('index.maxFileSize', Number.MAX_SAFE_INTEGER);
this._statusLog.info(`Using max file size of ${maxSize} bytes`);
// Every workspace URI is derived from this root. Logging it once per run makes
// a run that maps no files at all ("Indexed 0 of N files") diagnosable from
// the log alone, instead of only reporting the files that failed to map.
//
// The raw `path` is logged rather than `toString()`: mapping a file into the workspace
// compares `Uri.path` values, but `toString()` (and `toString(true)`, and `fsPath`)
// lowercases a Windows drive letter. A root and a file that differ only in that letter
// therefore serialise to strings where one is a literal prefix of the other, making a
// total mapping failure look impossible in the log.
this._statusLog.info(`Using workspace root ${describeUriPath(WorkspaceUri.getEffectiveRootUri())}`);
return {
// Snapshot the discovered files so file-watcher mutations during the
// run cannot change the pass total mid-flight.
fileUris: [...this._workspaceFileService.files],
includeMatchers: this._loadIncludePatterns(),
maxSize,
diagnoseFiles: getConfig().get<boolean>('index.diagnoseFiles', true),
reindex,
};
}
/**
* Filters workspace files down to the URIs that should be indexed for this run.
* @param run The shared indexing run state.
* @returns The URIs to index and the skipped file paths for reporting.
*/
private async _scanIndexFiles(run: IndexingRun): Promise<IndexScanResult> {
const indexedUris: vscode.Uri[] = [];
const skippedFiles: string[] = [];
const candidates: { fileUri: vscode.Uri; path: string }[] = [];
for (const fileUri of run.fileUris) {
if (this._contextService.contexts[fileUri.toString()] && !run.reindex) {
continue;
}
// A file that cannot be mapped into the workspace disqualifies only that
// file. Both outcomes -- an unmappable URI and a URI the conversion
// rejects outright -- are skipped so the pass keeps indexing the rest;
// letting the throw escape here aborted the whole run.
let workspaceUri: CanonicalWorkspaceUri | undefined;
try {
workspaceUri = WorkspaceUri.toWorkspaceUri(fileUri);
} catch (error) {
this._statusLog.error(`Could not parse workspace URI from ${describeUriPath(fileUri)}: ${getErrorMessage(error)}`, error);
skippedFiles.push(fileUri.toString());
continue;
}
if (!workspaceUri) {
// Reported against the raw path so it can be compared with the workspace root
// logged at the start of the run -- see the note there.
const message = `Could not parse workspace URI from ${describeUriPath(fileUri)}`;
this._statusLog.error(message);
skippedFiles.push(fileUri.toString());
continue;
}
candidates.push({ fileUri, path: this._normalizeFilePath(workspaceUri.path) });
}
// Stat the candidates with bounded concurrency: the stats are independent
// I/O round-trips, and issuing them one-by-one serializes disk/remote-fs
// latency across the whole corpus.
for (let i = 0; i < candidates.length; i += SCAN_CONCURRENCY) {
const chunk = candidates.slice(i, i + SCAN_CONCURRENCY);
// Settle each stat individually: a single unreadable file (deleted between
// discovery and the stat, or denied by the file system) would otherwise
// reject the whole chunk and abort the pass.
const stats = await Promise.all(chunk.map(({ fileUri }) => vscode.workspace.fs.stat(fileUri).then(
stat => ({ size: stat.size, error: undefined }),
(error: unknown) => ({ size: undefined, error: error ?? new Error('Unknown error') })
)));
for (let j = 0; j < chunk.length; j++) {
const { fileUri, path } = chunk[j];
const { size, error } = stats[j];
if (size === undefined) {
this._statusLog.warn(`Could not stat ${fileUri.toString()}: ${getErrorMessage(error)}`);
skippedFiles.push(fileUri.toString());
continue;
}
Iif (size > run.maxSize && !run.includeMatchers.some(match => match(path))) {
const message = `Skipped large file ${fileUri.toString()} (${size} bytes)`;
this._statusLog.warn(message);
skippedFiles.push(fileUri.toString());
continue;
}
indexedUris.push(fileUri);
}
}
return { targetFileUris: indexedUris, skippedFiles };
}
/**
* Indexes each file sequentially and returns a completion summary.
* @param indexedUris The file URIs that should be indexed.
* @param run The shared indexing run state.
* @returns Completion and error counts for the run.
*/
private async _runIndexingTasks(indexedUris: readonly vscode.Uri[], run: IndexingRun): Promise<IndexingTaskSummary> {
let completed = 0;
let errorCount = 0;
const timings: FileIndexTiming[] = [];
// Content read-ahead: parsing is CPU-bound and serialized, so the next few
// files' reads are started while the current file parses. Rejections are
// silenced here (they would otherwise be unhandled while queued) and
// surface when the consumer awaits the entry.
const prefetchedReads = new Map<string, Promise<Uint8Array>>();
const prefetch = (index: number) => {
for (let i = index; i < Math.min(index + READ_PREFETCH, indexedUris.length); i++) {
const uri = indexedUris[i];
const key = uri.toString();
if (!prefetchedReads.has(key) && !this._documentFactory.isSupportedNotebookFile(uri)) {
const read = Promise.resolve(vscode.workspace.fs.readFile(uri));
read.catch(() => undefined);
prefetchedReads.set(key, read);
}
}
};
// Parsing and inference are CPU-bound; with the reads prefetched, the
// per-file awaits resolve as microtasks and the loop would never return
// to the event loop, freezing the extension host for the whole pass.
const eventLoop = createEventLoopYielder();
for (let index = 0; index < indexedUris.length; index++) {
const fileUri = indexedUris[index];
await eventLoop.yieldIfBusy();
prefetch(index);
const fileStart = performance.now();
let phases: FileIndexPhases | undefined;
try {
phases = await this._indexWorkspaceFile(fileUri, run, prefetchedReads);
} catch (error) {
// Never swallow the reason: the summary reports the error count, so
// a failure without a log line leaves "1 error" with nothing to act on.
errorCount++;
this._statusLog.error(`Failed to index ${fileUri.toString()}: ${getErrorMessage(error)}`, error);
} finally {
prefetchedReads.delete(fileUri.toString());
}
const totalMs = Math.round(performance.now() - fileStart);
// Log every file's duration so the log carries the raw numbers. The
// open/load split shows whether time went to opening the document (I/O)
// or to parsing, loading triples and inference (CPU).
if (phases) {
this._statusLog.info(
`Indexed ${fileUri.toString()} in ${totalMs} ms (read ${phases.readMs} ms, load ${phases.loadMs} ms)`
);
timings.push({ uri: fileUri.toString(), totalMs, readMs: phases.readMs, loadMs: phases.loadMs });
}
// Flag files that took unusually long so latent per-file stalls (e.g. a
// token-wait timeout) stand out in the log.
Iif (totalMs >= SLOW_FILE_THRESHOLD_MS) {
this._statusLog.warn(`Slow file: ${fileUri.toString()} took ${totalMs} ms`);
}
completed++;
this._reportIndexingProgress(completed, indexedUris.length);
}
this._logIndexingTimings(timings);
return { completed, errorCount };
}
/**
* Logs aggregate per-file timing for a run: total, average and the slowest
* files. This turns the raw per-file lines into a quick summary for spotting
* which files dominate the indexing time.
* @param timings The per-file timings collected during the run.
*/
private _logIndexingTimings(timings: FileIndexTiming[]): void {
if (timings.length === 0) {
return;
}
const totalMs = timings.reduce((sum, t) => sum + t.totalMs, 0);
const avgMs = Math.round(totalMs / timings.length);
this._statusLog.info(`Per-file indexing: ${timings.length} files, ${totalMs} ms total, ${avgMs} ms avg`);
const slowest = [...timings].sort((a, b) => b.totalMs - a.totalMs).slice(0, SLOWEST_FILES_TO_LOG);
this._statusLog.info(`Slowest ${slowest.length} files:`);
for (const t of slowest) {
this._statusLog.info(` ${t.totalMs} ms (read ${t.readMs} ms, load ${t.loadMs} ms) ${t.uri}`);
}
}
/**
* Routes a workspace file to the appropriate indexing strategy.
* @param fileUri The URI of the workspace file to index.
* @param run The shared indexing run state.
* @param prefetchedReads Read-ahead file contents keyed by URI, when available.
* @returns The open/load phase timings for the file.
*/
private _indexWorkspaceFile(fileUri: vscode.Uri, run: IndexingRun, prefetchedReads?: Map<string, Promise<Uint8Array>>): Promise<FileIndexPhases> {
return this._documentFactory.isSupportedNotebookFile(fileUri)
? this._indexNotebookDocument(fileUri, run.reindex)
: this._indexTextDocument(fileUri, run, prefetchedReads);
}
/**
* Finalizes a completed indexing run by updating status output and lifecycle state.
* @param totalFiles The total number of discovered workspace files.
* @param skippedFiles The file URIs skipped before indexing.
* @param summary The settled task summary.
* @param startTime The run start time in milliseconds.
*/
private _finalizeIndexingRun(
totalFiles: number,
skippedFiles: string[],
summary: IndexingTaskSummary,
startTime: number
): void {
const indexedFiles = totalFiles - skippedFiles.length;
const duration = Math.round(performance.now() - startTime);
const successfulFiles = indexedFiles - summary.errorCount;
this._statistics = {
indexedFiles: successfulFiles,
errorCount: summary.errorCount,
skippedFiles: skippedFiles.length,
durationMs: duration,
};
// The heap figure makes the memory cost of an index visible in the output
// channel, so a workspace can be checked without a profiler attached.
const heapUsedMb = getHeapUsedMb();
const heapSuffix = heapUsedMb === undefined ? '' : ` (heap ${heapUsedMb} MB)`;
this._statusLog.info(`Indexed ${successfulFiles} of ${totalFiles} files in ${duration} ms${heapSuffix}`);
const parts = [`$(list-tree) Indexed ${successfulFiles} files`];
if (summary.errorCount > 0) {
parts.push(`${summary.errorCount} error${summary.errorCount > 1 ? 's' : ''}`);
}
if (skippedFiles.length > 0) {
parts.push(`${skippedFiles.length} skipped`);
}
// The tooltip mirrors the format of the SHACL validation status bar item.
const tooltip = `Workspace indexing: ${totalFiles} files discovered, `
+ `${successfulFiles} indexed, ${summary.errorCount} errors, ${skippedFiles.length} skipped.`
+ '\nClick to open the indexing settings.';
this._statusBarItem.text = parts.join('; ');
this._statusBarItem.tooltip = tooltip;
this._statusBarItem.show();
this._finishIndexing();
}
/**
* Reports per-file indexing progress using completed and total file counts.
* @param completed The number of completed indexing tasks.
* @param total The total number of scheduled indexing tasks.
*/
private _reportIndexingProgress(completed: number, total: number): void {
Iif (total === 0) {
return;
}
this._reportProgress(completed, total);
}
/**
* Gets the list of files to include in the workspace index, based on the
* 'mentor.index.includeFiles' configuration setting.
* @returns An array of canonical workspace URIs as strings.
*/
private _loadIncludePatterns(): picomatch.Matcher[] {
const result: picomatch.Matcher[] = [];
let hasErrors = false;
for (const rawPattern of getConfig().get<string[]>('index.includeFiles', [])) {
const pattern = normalizeGlobPattern(rawPattern);
if (!pattern) {
// A blank entry is a settings-UI artifact — clearing a list row
// persists an empty string — and cannot change what is indexed.
// Skip it quietly instead of reporting a configuration error.
continue;
}
try {
// Treat patterns as repository/workspace-relative globs.
// Examples: data/**/*.ttl, ontologies/*.trig
const matcher = picomatch(pattern, {
dot: true,
nocase: false,
bash: false
});
result.push(matcher);
this._statusLog.info(`Loaded include glob: ${pattern}`);
} catch (error) {
this._statusLog.error(`Invalid glob pattern in 'mentor.index.includeFiles': ${rawPattern}`, error);
hasErrors = true;
}
}
Iif (hasErrors) {
const message = "One or more invalid glob patterns detected in mentor.index.includeFiles";
const action = "View Log";
void vscode.window.showWarningMessage(message, action).then(selected => {
if (selected === action) {
void vscode.commands.executeCommand("mentor.command.showIndexStatus");
}
});
}
return result;
}
/**
* Normalizes a file path by trimming whitespace, converting backslashes to forward slashes,
* and removing leading slashes. This ensures consistent matching against normalized glob patterns.
* @param path The file path to normalize.
* @returns The normalized file path.
*/
private _normalizeFilePath(path: string): string {
return path
.trim()
.replace(/\\/g, "/")
.replace(/^\/+/, "");
}
/**
* Index a regular text document.
*
* Reads the file bytes and builds the context from content instead of opening
* a VS Code text document per file: profiling showed `openTextDocument`
* (document-model creation + `onDidOpenTextDocument` notifications) dominated
* indexing time, while the actual RDF parsing is cheap. An already-open
* document is reused so live, possibly unsaved, content wins.
* @param uri The URI of the document to index.
* @param run The shared indexing run state.
* @param prefetchedReads Read-ahead file contents keyed by URI, when available.
* @returns The read/load phase timings for the document.
*/
private async _indexTextDocument(uri: vscode.Uri, run: IndexingRun, prefetchedReads?: Map<string, Promise<Uint8Array>>): Promise<FileIndexPhases> {
// The `open` phase now measures reading the content (from an open document
// or from disk) rather than opening a text document.
const openStart = performance.now();
// Prefer an already-open document so unsaved edits win. This set is tiny
// during indexing, so the lookup is cheap.
const openDocument = vscode.workspace.textDocuments.find(d => d.uri.toString() === uri.toString());
let content: string;
if (openDocument) {
content = openDocument.getText();
} else {
try {
// A prefetched read may already be resolved (started while the previous
// file was parsing), in which case this await is effectively free.
const bytes = await (prefetchedReads?.get(uri.toString()) ?? vscode.workspace.fs.readFile(uri));
content = new TextDecoder().decode(bytes);
} catch (error) {
// Log and rethrow so the background settlement can count failures accurately.
this._statusLog.error(`File ${uri.toString()} cannot be read`);
throw error;
}
}
const readMs = Math.round(performance.now() - openStart);
// Re-check after the async read: handleActiveEditorChanged may have registered
// this context while we were awaiting (TOCTOU guard).
Iif (this._contextService.contexts[uri.toString()] && !run.reindex) {
return { readMs, loadMs: 0 };
}
// Load the document so that its graph is created and can be used for showing definitions, descriptions etc..
const loadStart = performance.now();
// An open document is reloaded through a token delivery, which also updates its
// diagnostics and editor features; loading its content first parsed and loaded it twice.
if (!(openDocument && run.reindex && await this._reloadOpenDocument(uri.toString()))) {
await this._contextService.loadDocumentContent(uri, content, run.reindex);
}
const loadMs = Math.round(performance.now() - loadStart);
// A file that is not open in an editor is parsed again only when it is opened
// or changes, so from here on only its index maps and graphs need to stay in
// memory. The workspace diagnostics after the pass read the file again.
if (!openDocument) {
this._releaseTokens(uri);
}
return { readMs, loadMs };
}
/**
* Releases the tokens and the parse result of an indexed file that is not open
* in an editor, if its context keeps them.
* @param uri The URI of the indexed file.
*/
private _releaseTokens(uri: vscode.Uri): void {
const context = this._contextService.contexts[uri.toString()];
if (context && context.isTokenized()) {
context.releaseTokens();
}
}
/**
* Index RDF cells within a notebook document.
* @param notebookUri The URI of the notebook file.
* @param reindex Whether to force re-indexing of already indexed cells.
* @returns The open/load phase timings for the notebook.
*/
private async _indexNotebookDocument(notebookUri: vscode.Uri, reindex: boolean): Promise<FileIndexPhases> {
const openStart = performance.now();
const notebook = await vscode.workspace.openNotebookDocument(notebookUri);
const readMs = Math.round(performance.now() - openStart);
const loadStart = performance.now();
// Each cell pays a full parse, triple load and inference pass; yield
// between cells so a large notebook does not block the extension host.
const eventLoop = createEventLoopYielder();
for (const cell of notebook.getCells()) {
await eventLoop.yieldIfBusy();
const lang = cell.document.languageId;
if (!this._documentFactory.supportedLanguages.has(lang)) {
continue;
}
const cellUri = cell.document.uri.toString();
Iif (this._contextService.contexts[cellUri] && !reindex) {
continue;
}
try {
// Load the cell document to create its context, passing the slug so that
// graphIri is slug-based from the very first loadTriples call.
const slug = cell.metadata?.slug as string | undefined;
// A cell is reloaded through a token delivery like an open document (see
// _indexTextDocument), unless its slug changed and its graph IRI with it.
const isReloadable = reindex && this._contextService.contexts[cellUri]?.slug === slug;
if (!(isReloadable && await this._reloadOpenDocument(cellUri))) {
await this._contextService.loadDocument(cell.document, reindex, slug);
}
} catch (error) {
// Log and rethrow so the background settlement can count failures accurately.
this._statusLog.error(`Failed to index notebook cell ${cellUri}:`, error);
throw error;
}
}
return { readMs, loadMs: Math.round(performance.now() - loadStart) };
}
/**
* Marks indexing as finished, fires the completion event, and resets the VS Code context flag.
*/
private _finishIndexing(): void {
this._indexingFinished = true;
vscode.commands.executeCommand('setContext', 'mentor.workspace.isIndexing', false);
this._onDidFinishIndexing.fire(true);
this._statusLog.info('-- Finished workspace indexing.');
}
/**
* Reports indexing progress on the status bar item. Throttled to ~10
* updates per second: each update is an IPC message to the renderer, and a
* fast pass over many small files would otherwise flood it. The first and
* final counts always render so the bar never sticks below the total.
* @param completed The number of files indexed so far.
* @param total The total number of files to index.
*/
private _reportProgress(completed: number, total: number): void {
const now = Date.now();
if (completed > 0 && completed < total && now - this._lastProgressReport < 100) {
return;
}
this._lastProgressReport = now;
this._statusBarItem.text = `$(sync~spin) Indexing: ${completed} of ${total} files...`;
this._statusBarItem.show();
}
/**
* Wait for all workspace files to be indexed.
* @returns A promise that resolves when all workspace files were indexed.
*/
async waitForIndexed(): Promise<void> {
if (this._indexingFinished) {
return;
}
return new Promise((resolve) => {
const listener = this._onDidFinishIndexing.event(() => {
listener.dispose();
resolve();
});
});
}
/**
* Open the debug console and show detailed log messages from the indexing process.
*/
showIndexStatus(): void {
this._statusLog.show();
}
}
/**
* Shared immutable inputs for a single workspace indexing run.
*/
type IndexingRun = {
/**
* The workspace files discovered before pre-scan filtering is applied.
*/
fileUris: ReadonlyArray<vscode.Uri>;
/**
* The configured include globs that can override file size exclusions.
*/
includeMatchers: picomatch.Matcher[];
/**
* The maximum file size allowed for indexing unless explicitly included.
*/
maxSize: number;
/**
* Whether syntax/lint diagnostics are computed for the indexed files once the
* run has finished. Snapshotted once per run.
*/
diagnoseFiles: boolean;
/**
* Indicates whether already indexed files should be indexed again.
*/
reindex: boolean;
};
/**
* The result of scanning workspace files before scheduling indexing tasks.
*/
type IndexScanResult = {
/**
* The file URIs that passed pre-scan checks and should be indexed.
*/
targetFileUris: vscode.Uri[];
/**
* The file identifiers skipped during the pre-scan phase.
*/
skippedFiles: string[];
};
/**
* The read/load phase durations (ms) measured while indexing a single file.
*/
type FileIndexPhases = {
/**
* Time spent acquiring the content — reading the file bytes, or reading an
* already-open document's text (I/O) — in milliseconds.
*/
readMs: number;
/**
* Time spent loading the document — parsing, loading triples and inference
* (CPU) — in milliseconds.
*/
loadMs: number;
};
/**
* A single file's indexing timing, including its URI, for run summaries.
*/
type FileIndexTiming = FileIndexPhases & {
/**
* The indexed file URI.
*/
uri: string;
/**
* The total wall-clock time to index the file (ms), including overhead
* around the open/load phases.
*/
totalMs: number;
};
/**
* Settlement summary for the indexing tasks in a run.
*/
type IndexingTaskSummary = {
/**
* The number of indexing tasks that completed.
*/
completed: number;
/**
* The number of indexing tasks that failed.
*/
errorCount: number;
}; |