Visual Studio Code, rebuilt in Rust
Files, search and watchers
How the port reaches the disk, watches it and searches it: the files and search crates, and their callers in app and exthost. This file goes one level under ARCHITECTURE.md, section "Files, search and watchers". Upstream is src/vs/platform/files, src/vs/base/common/glob.ts and src/vs/workbench/services/search.
What is where
| File | Its one job | Upstream |
|---|---|---|
files/src/lib.rs |
The file service as free functions over a files/src/lib.rs::FileSystem: the checks, the error names and messages of each layer. |
src/vs/platform/files/common/fileService.ts |
files/src/disk.rs |
files/src/disk.rs::Disk, the file scheme, with Node's errno messages and the Trash. |
src/vs/platform/files/node/diskFileSystemProvider.ts |
files/src/operations.rs |
File operations that ask the participants first, report after, and return their undo. | workingCopyFileService.ts, bulkFileEdits.ts |
files/src/watcher.rs |
The disk watcher: batch, cover, coalesce. | src/vs/platform/files/common/watcher.ts |
files/src/glob.rs |
VS Code's glob dialect, expressions with sibling clauses, exclude expressions with ! exceptions. |
src/vs/base/common/glob.ts |
files/src/encoding.rs, files/src/unc.rs, files/src/user_data.rs |
Text encodings, the UNC host allowlist, the vscode-userdata scheme over the disk. |
encoding.ts, unc.ts, fileUserDataProvider.ts |
search/src/query.rs, search/src/search_paths.rs |
Build a search/src/query.rs::Query from options and the folders' settings, and from the search view's include and exclude inputs. |
src/vs/workbench/services/search/common/queryBuilder.ts |
search/src/ripgrep.rs |
Start ripgrep, read its lines, kill it. | ripgrep.ts, ripgrepSearchUtils.ts |
search/src/file_search.rs, search/src/text_search.rs |
The two searches: the ripgrep arguments, the parse of its output, the filters ripgrep cannot express. | fileSearch.ts, ripgrepFileSearch.ts, ripgrepTextSearchEngine.ts, textSearchManager.ts |
Both crates are synchronous and know nothing of GPUI or the extension host. The caller picks the thread. This is what lets the same code serve the workbench and the session thread.
Which thread touches the disk
There is no file service object. A caller passes a FileSystem to a function of files/src/lib.rs, and the call blocks until the disk or the provider answers. Three callers exist:
- The session thread.
exthost/src/main_thread_files.rs::Providersis theFileSystemthat knows every scheme: the disk,vscode-userdata, the settings scheme, debug memory, and extension providers, which it asks over the protocol. It answers the host'sworkspace.fscalls on theexthost-sessionthread (extension-host.md, "Threads"). - The workbench, through the session. A file operation that must run participants or reach an extension provider is a
app/src/host_sync.rs::FileJob.app/src/host_sync.rs::HostSync::run_filesqueues it, the session thread runs it inapp/src/main_thread.rswithProviders, and the main thread awaits the oneshot reply. The Explorer's create, move and delete, the file edits of a rename, and their undo take this path. With no host,run_filesruns the job at once onDisk, on the calling thread and without participants. - The workbench, directly. Opening and saving a text document (
app/src/workbench/text_files.rs::read_document,app/src/workbench/text_files.rs::write_text_file) and listing an Explorer folder (app/src/explorer.rs::read_children) callstd::fson the main thread.app/src/explorer.rs::root_errorcallsfiles::resolveonDiskthere too.
The rule of performance.md ("No I/O on the main thread in a hot path") applies like this:
- A search never runs on the main thread. Every caller in
appstarts it withcx.background_spawn; the session starts astd::threadperfindFilesorfindTextInFilesrequest. The exception isexthost/src/main_thread_workspace.rs::MainThreadWorkspace::glob_file_exists(aworkspaceContains:glob): it runs on the session thread and holds it until a file matches, at most 7 s. See "Search" below. - A watcher event never does I/O on the main thread before it is needed: the batch arrives as data, and
app/src/workbench/text_files.rs::files_changedtouches the disk only for a path that has an open model. A clean model reads its file again, a placeholder for a missing file opens it, and a delete is checked with oneexists100 ms later. - The direct
std::fscalls above run once per user action (open, save), not per frame or per key. The Explorer is the one that sits near a hot path:app/src/explorer.rs::entriesruns when the rows are built, so it costs onestatof each shown folder, and reads a folder again when its mtime changed. It also reads it on every call while the mtime is younger than 2 s (100 ms when the mtime has a sub-second part), while the sort order ismodified, and while a new item is being named in it. Keep that cache in front of any new per-row disk question. - New code that reads a file whose size the user controls, walks a tree, or starts a process goes to the background executor or to the session through
FileJob. Add no newstd::fscall to arender, a list row or a key handler.
Invariant: errors keep the JavaScript error name and message of the upstream layer that raised them (files/src/lib.rs::FileError), because extensions and upstream's API tests match on them. files/src/lib.rs::handle_error renames them once, at the boundary to the host. A new failure path builds its error with files/src/lib.rs::provider_error or, inside files, with files/src/disk.rs::io_error, not with a free-form string.
Invariant: on Windows the file service, the text file models and webview resources call files/src/unc.rs::check_unc_access before they touch a path. Disk calls it for every path. Code that calls std::fs directly must call it first, as read_document does. The Explorer listing (read_children) and the searches do not call it.
The watcher
files/src/watcher.rs::Watcher stands in for upstream's parcel watcher. One Watcher owns one notify watcher and one thread named file-watcher. Watches are added by id (files/src/watcher.rs::Watcher::watch), and one callback gets every batch.
An event goes through four steps, all off the main thread:
files/src/watcher.rs::forward, on the thread ofnotify: maps the event toAdded,UpdatedorDeleted. A create, remove or rename isAddedwhen the path exists afterwards, elseDeleted, as parcel reports FSEvents. This is onelstatper path of such an event; a plain modify needs none.files/src/watcher.rs::deliver_batches, onfile-watcher: after the first event it collects for 75 ms (upstream'sFILE_CHANGES_HANDLER_DELAY). The window is fixed from the first event; later events do not extend it.- Cover: each event is kept if a watch covers it (below its root, within its depth, not matched by its excludes) and gets the path below the root the watch was asked for, not the realpath. A file under
/varis reported as/var/...even though the event names/private/var/.... files/src/watcher.rs::coalesce, a port ofEventCoalescer: one event per path, create then delete dropped, delete then create turned intoUpdated, no delete below a deleted folder.
The callback then runs on file-watcher. It must only send: every caller pushes the batch into a channel. In app the channel is drained by a cx.spawn task on the main thread; in exthost a exthost/src/lib.rs::WakingSender wakes the session, which turns the batch into $onFileEvent (exthost/src/main_thread_files.rs::MainThreadFiles::take_events).
Who watches what:
- The workbench:
app/src/workbench/text_files.rs::start_file_watcherwatches each workspace folder recursively minusfiles.watcherExclude, plus the visible file outside the folders, one watch at a time (watch_visible_file).files_changedis the single entry for these events in the workbench; a new consumer of disk changes is called from there. - The session:
exthost/src/main_thread_files.rs::MainThreadFileswatches the same folders again for the host, and serves the host's$watchcalls. A correlated flat watch or avscode-userdatawatch gets aWatcherof its own, because a batch carries no watch id: the callback is the only place that knows the session and the scheme. - Single folders: settings (
app/src/workbench/configuration.rs),keybindings.json(app/src/workbench/keyboard.rs), the profile's extensions (app/src/workbench/extension_management.rs), and the policy file on Linux (app/src/policy/linux.rs). Each makes its ownWatcherand watches flat.
Traps:
- A batch says "something changed here", not "this is the state". A consumer reads the disk again or compares a stat;
files_changedwaits 100 ms before it believes a delete (upstream issue 13665). - An event covered by two watches of one
Watcheris reported once, under the root of whichever watch matches first. Watches that need their own paths or their own events need their ownWatcher. - Paths are keyed ignoring case in
coalesceand exclude patterns match ignoring case, as upstream does on macOS. This holds on every OS here. - The callback is dropped by
DropofWatcheron the dropping thread, not onfile-watcher: a channel sender dropped there would wake a GPUI foreground task off the main thread. Drop aWatcheron the thread its callback's captures belong to: the main thread inapp, the session thread inexthost. - A workspace folder is under two recursive watches (workbench and session). A change to watcher cost counts twice.
Search
A search is one call that blocks: search/src/file_search.rs::search or search/src/text_search.rs::search, given a Query, the path of ripgrep (search/src/ripgrep.rs::rg_path), a search/src/ripgrep.rs::Cancellation and a callback for results. It runs the query's folders one after the other, one ripgrep process at a time (search/src/ripgrep.rs::run). Results reach the callback while ripgrep still runs.
- File search lists with
rg --filesand filters here: the fuzzy file pattern, include globs, and the excludes ripgrep cannot express. A query with sibling clauses ("**/*.js": { "when": "$(basename).ts" }) keeps the whole listing and walks it as a tree once ripgrep is done, so its memory grows with the folder. - Text search runs
rg --json, parses matches and context lines, and groups them by file before the callback sees them. The limit is counted in match ranges, 20000 unless the query sets one. - Excludes with
!exceptions run ripgrep twice per folder: ripgrep does not descend into an excluded folder, so the second run uses--no-ignore, searches what the exceptions re-include, and skips what the first run reported. This follows upstream; the two runs are the design, not a leftover. - With
search.followSymlinks, more thansearch/src/ripgrep.rs::MAX_SYMLINK_LOOPSloop reports on stderr kill the run, and the folder is searched again without following links.
Ignore files are ripgrep's job. The port reads no .gitignore; it only passes flags. search/src/query.rs::FolderQuery carries disregard_ignore_files, disregard_parent_ignore_files and disregard_global_ignore_files, filled from the caller's options or else from search.useIgnoreFiles, search.useParentIgnoreFiles and search.useGlobalIgnoreFiles of the folder. They become --no-ignore, --no-ignore-parent and --no-ignore-global. Every run also passes --hidden, --no-require-git and --no-config. files.exclude and search.exclude are a different mechanism: search/src/query.rs::excludes merges them into the exclude expression of each FolderQuery, which becomes -g arguments plus the filters applied here. A caller that must see ignored files sets the disregard options in the query; it does not post-filter.
Cancellation: Cancellation::cancel sets a flag and kills the ripgrep child it holds. run stops at the next line, and the search function returns. A cancelled search can return Ok with partial results or Err; the caller asks is_cancelled to tell it from a real result or a real error, as app/src/workbench/search_actions.rs::search_complete does.
How callers run and cancel:
| Caller | Runs on | Cancelled by |
|---|---|---|
Search view and search editor (app/src/workbench/search_actions.rs::spawn_text_search) |
cx.background_spawn; file matches stream over an unbounded channel |
the next search; in the view also cancel_search and clear_search_results. Closing a search editor does not cancel its search |
Quick Open file list (app/src/workbench/quick_open.rs::load_file_query_cache) |
cx.background_spawn; one listing per picker, filtered in memory per key |
Drop of app/src/workbench/quick_open.rs::FilePickState |
Explorer find (app/src/workbench/explorer_find.rs::search_folders) |
cx.background_spawn |
the next pattern |
workspace.findFiles, findTextInFiles (exthost/src/main_thread_workspace.rs::MainThreadWorkspace::start) |
one std::thread per request; results go back through a WakingSender in order |
the host's Cancel for the request; the reply is then null |
Traps:
- One
Cancellationper search. It holds one child, so sharing it between two searches that run at the same time leaves the first child without a way to be killed. - Dropping the GPUI task does not stop ripgrep. The blocking call sits on a background thread until ripgrep ends. The owner keeps the
Arcof itsCancellationand must callcancelwhen the result is no longer wanted. - The result callback runs on the search thread. It sends or collects; it does not touch the workbench.
- ripgrep is the binary under
node_modules/@vscode/ripgrep-universalof the app root. A test that searches needs the app root of a checkout with its node modules. - The searches report paths relative to the folder and match globs against them with
/separators. An exclude key that starts with/is matched against the absolute path.files/src/glob.rshas no relative patterns (IRelativePattern): convert before calling.
Check a change
- The file service, operations:
port/tools/cargo-test -p files moves_and_copies,port/tools/cargo-test -p files operations.files/src/disk.rshas no unit test. - Globs (upstream's
glob.test.tscases):port/tools/cargo-test -p files glob. - The watcher:
port/tools/cargo-test -p files coalesces_like_the_event_coalescer reports_changes_below_the_requested_path. The second one writes real files and waits for FSEvents. - Watcher events in the workbench:
port/tools/cargo-test clean_models_follow_their_file_and_deleted_files_orphan_them. - Search:
port/tools/cargo-test -p search file_search,port/tools/cargo-test -p search text_search,port/tools/cargo-test -p search too_many_symlink_loops. - The host side (
workspace.fs, watch sessions,findFiles):port/tools/cargo-test -p exthost user_data_watch_events_keep_their_scheme, then upstream's API tests withport/tools/api-tests(testing.md). - After a rename or a move:
bun port/tools/docs-check.ts.