Visual Studio Code, rebuilt in Rust
Rust
//! performance.ts marks of the port (`code/...`, one process, so all under `renderer`) and of the extension host
//! (`$setPerformanceMarks`), with mainThreadExtensionService.ts's activation times; Developer: Startup Performance
//! (workbench/perf_view.rs) reads them. Global as upstream's `vs/base/common/performance` is.
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::Value;
use crate::notifications::Severity;
/// A mark's name and its time in milliseconds since the epoch, as `PerformanceMark.startTime`.
pub type Mark = (String, f64);
/// `ActivationTimes` and the `ExtensionActivationReason` of one extension.
#[derive(Clone)]
pub struct Activation {
pub id: String,
pub startup: bool,
pub code_loading: f64,
pub activate_call: f64,
pub activate_resolved: f64,
pub event: String,
pub by: String,
}
static MARKS: Mutex<Vec<Mark>> = Mutex::new(Vec::new());
static EXT_HOST_MARKS: Mutex<Vec<Mark>> = Mutex::new(Vec::new());
static ACTIVATIONS: Mutex<Vec<Activation>> = Mutex::new(Vec::new());
/// `ExtensionStatus.runtimeErrors` as (extension id, `getErrorMessage`) and `messages` as (extension id, severity, message).
static RUNTIME_ERRORS: Mutex<Vec<(String, String)>> = Mutex::new(Vec::new());
static MESSAGES: Mutex<Vec<(String, Severity, String)>> = Mutex::new(Vec::new());
/// timerService.ts `editorIds`: the editor ids visible once the startup editors were restored.
static STARTUP_EDITORS: Mutex<Vec<String>> = Mutex::new(Vec::new());
pub fn mark(name: &str) {
let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("the clock is after 1970").as_secs_f64() * 1000.;
MARKS.lock().unwrap().push((name.to_owned(), now.round()));
}
/// `ITimerService.getPerformanceMarks`: each source with its marks.
pub fn performance_marks() -> Vec<(&'static str, Vec<Mark>)> {
let mut sources = vec![("renderer", MARKS.lock().unwrap().clone())];
let ext_host = EXT_HOST_MARKS.lock().unwrap().clone();
if !ext_host.is_empty() {
sources.push(("localExtHost", ext_host));
}
sources
}
pub fn set_startup_editors(ids: Vec<String>) {
*STARTUP_EDITORS.lock().unwrap() = ids;
}
pub fn startup_editors() -> Vec<String> {
STARTUP_EDITORS.lock().unwrap().clone()
}
/// The duration between two port marks, when both happened.
pub fn between(from: &str, to: &str) -> Option<f64> {
let marks = MARKS.lock().unwrap();
let time = |name: &str| marks.iter().find(|(mark, _)| mark == name).map(|(_, time)| *time);
Some(time(to)? - time(from)?)
}
/// `$setPerformanceMarks`: `[{ name, startTime }]`.
pub fn set_ext_host_marks(marks: &Value) {
let marks = marks.as_array().into_iter().flatten().map(|mark| (mark["name"].as_str().unwrap_or_default().to_owned(), mark["startTime"].as_f64().unwrap_or_default()));
*EXT_HOST_MARKS.lock().unwrap() = marks.collect();
}
/// `$onDidActivateExtension(extensionId, codeLoadingTime, activateCallTime, activateResolvedTime, activationReason)`.
pub fn extension_activated(args: &[Value]) {
let reason = &args[4];
ACTIVATIONS.lock().unwrap().push(Activation {
id: args[0]["value"].as_str().unwrap_or_default().to_owned(),
startup: reason["startup"] == true,
code_loading: args[1].as_f64().unwrap_or_default(),
activate_call: args[2].as_f64().unwrap_or_default(),
activate_resolved: args[3].as_f64().unwrap_or_default(),
event: reason["activationEvent"].as_str().unwrap_or_default().to_owned(),
by: reason["extensionId"]["value"].as_str().unwrap_or_default().to_owned(),
});
}
/// `IExtensionsStatus.activationTimes` of the extension.
pub fn activation(id: &str) -> Option<Activation> {
ACTIVATIONS.lock().unwrap().iter().find(|activation| activation.id.eq_ignore_ascii_case(id)).cloned()
}
/// `$onExtensionRuntimeError(extensionId, error)`: `addRuntimeError` with errors.ts `getErrorMessage`.
pub fn extension_runtime_error(args: &[Value]) {
let error = &args[1];
let message = match (error["message"].as_str().filter(|message| !message.is_empty()), error["stack"].as_str().filter(|stack| !stack.is_empty())) {
(Some(message), _) => message.to_owned(),
(None, Some(stack)) => stack.lines().next().unwrap_or_default().to_owned(),
(None, None) => "Error".to_owned(),
};
RUNTIME_ERRORS.lock().unwrap().push((args[0]["value"].as_str().unwrap_or_default().to_owned(), message));
}
/// `_handleExtensionPointMessage`: an extension point's message about the extension (`ExtensionStatus.addMessage`).
pub fn extension_point_message(id: &str, severity: Severity, message: String) {
let mut messages = MESSAGES.lock().unwrap();
// Upstream handles a point once per extension delta; the port reads the snippet files again on every refresh.
if !messages.iter().any(|(extension, kind, text)| extension == id && *kind == severity && *text == message) {
messages.push((id.to_owned(), severity, message));
}
}
/// `IExtensionsStatus.runtimeErrors` of the extension.
pub fn runtime_errors(id: &str) -> Vec<String> {
RUNTIME_ERRORS.lock().unwrap().iter().filter(|(extension, _)| extension.eq_ignore_ascii_case(id)).map(|(_, error)| error.clone()).collect()
}
/// `IExtensionsStatus.messages` of the extension.
pub fn messages(id: &str) -> Vec<(Severity, String)> {
MESSAGES.lock().unwrap().iter().filter(|(extension, ..)| extension.eq_ignore_ascii_case(id)).map(|(_, severity, message)| (*severity, message.clone())).collect()
}
/// perfviewEditor.ts `_addExtensionsTable` rows: eager activations first.
pub fn activations() -> Vec<Vec<String>> {
let activations = ACTIVATIONS.lock().unwrap();
let row = |activation: &Activation| {
let numbers = [activation.code_loading, activation.activate_call, activation.activate_resolved].map(|time| time.to_string());
[vec![activation.id.clone(), activation.startup.to_string()], numbers.to_vec(), vec![activation.event.clone(), activation.by.clone()]].concat()
};
let eager = activations.iter().filter(|activation| activation.startup).map(row);
let normal = activations.iter().filter(|activation| !activation.startup).map(row);
eager.chain(normal).collect()
}
#[cfg(test)]
mod tests {
#[test]
fn ext_host_marks_are_listed_as_local_ext_host() {
super::set_ext_host_marks(&serde_json::json!([{ "name": "code/extHost/willConnectToRenderer", "startTime": 12.5 }]));
let marks = super::performance_marks();
let (_, ext_host) = marks.iter().find(|(source, _)| *source == "localExtHost").unwrap();
assert_eq!(ext_host, &vec![("code/extHost/willConnectToRenderer".to_owned(), 12.5)]);
}
}