Skip to content

Visual Studio Code, rebuilt in Rust

Rust
15.0 KB
Raw Blame

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::Providers is the FileSystem that 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's workspace.fs calls on the exthost-session thread (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_files queues it, the session thread runs it in app/src/main_thread.rs with Providers, 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_files runs the job at once on Disk, 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) call std::fs on the main thread. app/src/explorer.rs::root_error calls files::resolve on Disk there 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 app starts it with cx.background_spawn; the session starts a std::thread per findFiles or findTextInFiles request. The exception is exthost/src/main_thread_workspace.rs::MainThreadWorkspace::glob_file_exists (a workspaceContains: 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_changed touches 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 one exists 100 ms later.
  • The direct std::fs calls 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::entries runs when the rows are built, so it costs one stat of 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 is modified, 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 new std::fs call to a render, 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:

  1. files/src/watcher.rs::forward, on the thread of notify: maps the event to Added, Updated or Deleted. A create, remove or rename is Added when the path exists afterwards, else Deleted, as parcel reports FSEvents. This is one lstat per path of such an event; a plain modify needs none.
  2. files/src/watcher.rs::deliver_batches, on file-watcher: after the first event it collects for 75 ms (upstream's FILE_CHANGES_HANDLER_DELAY). The window is fixed from the first event; later events do not extend it.
  3. 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 /var is reported as /var/... even though the event names /private/var/....
  4. files/src/watcher.rs::coalesce, a port of EventCoalescer: one event per path, create then delete dropped, delete then create turned into Updated, 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_watcher watches each workspace folder recursively minus files.watcherExclude, plus the visible file outside the folders, one watch at a time (watch_visible_file). files_changed is 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::MainThreadFiles watches the same folders again for the host, and serves the host's $watch calls. A correlated flat watch or a vscode-userdata watch gets a Watcher of 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 own Watcher and 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_changed waits 100 ms before it believes a delete (upstream issue 13665).
  • An event covered by two watches of one Watcher is reported once, under the root of whichever watch matches first. Watches that need their own paths or their own events need their own Watcher.
  • Paths are keyed ignoring case in coalesce and exclude patterns match ignoring case, as upstream does on macOS. This holds on every OS here.
  • The callback is dropped by Drop of Watcher on the dropping thread, not on file-watcher: a channel sender dropped there would wake a GPUI foreground task off the main thread. Drop a Watcher on the thread its callback's captures belong to: the main thread in app, the session thread in exthost.
  • 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 --files and 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 than search/src/ripgrep.rs::MAX_SYMLINK_LOOPS loop 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 Cancellation per 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 Arc of its Cancellation and must call cancel when 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-universal of 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.rs has 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.rs has no unit test.
  • Globs (upstream's glob.test.ts cases): 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 with port/tools/api-tests (testing.md).
  • After a rename or a move: bun port/tools/docs-check.ts.