mirror of
https://github.com/nushell/nushell.git
synced 2025-08-19 08:41:29 +02:00
Keep plugins persistently running in the background (#12064)
# Description This PR uses the new plugin protocol to intelligently keep plugin processes running in the background for further plugin calls. Running plugins can be seen by running the new `plugin list` command, and stopped by running the new `plugin stop` command. This is an enhancement for the performance of plugins, as starting new plugin processes has overhead, especially for plugins in languages that take a significant amount of time on startup. It also enables plugins that have persistent state between commands, making the migration of features like dataframes and `stor` to plugins possible. Plugins are automatically stopped by the new plugin garbage collector, configurable with `$env.config.plugin_gc`: ```nushell $env.config.plugin_gc = { # Configuration for plugin garbage collection default: { enabled: true # true to enable stopping of inactive plugins stop_after: 10sec # how long to wait after a plugin is inactive to stop it } plugins: { # alternate configuration for specific plugins, by name, for example: # # gstat: { # enabled: false # } } } ``` If garbage collection is enabled, plugins will be stopped after `stop_after` passes after they were last active. Plugins are counted as inactive if they have no running plugin calls. Reading the stream from the response of a plugin call is still considered to be activity, but if a plugin holds on to a stream but the call ends without an active streaming response, it is not counted as active even if it is reading it. Plugins can explicitly disable the GC as appropriate with `engine.set_gc_disabled(true)`. The `version` command now lists plugin names rather than plugin commands. The list of plugin commands is accessible via `plugin list`. Recommend doing this together with #12029, because it will likely force plugin developers to do the right thing with mutability and lead to less unexpected behavior when running plugins nested / in parallel. # User-Facing Changes - new command: `plugin list` - new command: `plugin stop` - changed command: `version` (now lists plugin names, rather than commands) - new config: `$env.config.plugin_gc` - Plugins will keep running and be reused, at least for the configured GC period - Plugins that used mutable state in weird ways like `inc` did might misbehave until fixed - Plugins can disable GC if they need to - Had to change plugin signature to accept `&EngineInterface` so that the GC disable feature works. #12029 does this anyway, and I'm expecting (resolvable) conflicts with that # Tests + Formatting - 🟢 `toolkit fmt` - 🟢 `toolkit clippy` - 🟢 `toolkit test` - 🟢 `toolkit test stdlib` Because there is some specific OS behavior required for plugins to not respond to Ctrl-C directly, I've developed against and tested on both Linux and Windows to ensure that works properly. # After Submitting I think this probably needs to be in the book somewhere
This commit is contained in:
@@ -13,6 +13,7 @@ pub use self::completer::CompletionAlgorithm;
|
||||
pub use self::helper::extract_value;
|
||||
pub use self::hooks::Hooks;
|
||||
pub use self::output::ErrorStyle;
|
||||
pub use self::plugin_gc::{PluginGcConfig, PluginGcConfigs};
|
||||
pub use self::reedline::{
|
||||
create_menus, EditBindings, HistoryFileFormat, NuCursorShape, ParsedKeybinding, ParsedMenu,
|
||||
};
|
||||
@@ -22,6 +23,7 @@ mod completer;
|
||||
mod helper;
|
||||
mod hooks;
|
||||
mod output;
|
||||
mod plugin_gc;
|
||||
mod reedline;
|
||||
mod table;
|
||||
|
||||
@@ -96,6 +98,8 @@ pub struct Config {
|
||||
/// match the registered plugin name so `register nu_plugin_example` will be able to place
|
||||
/// its configuration under a `nu_plugin_example` column.
|
||||
pub plugins: HashMap<String, Value>,
|
||||
/// Configuration for plugin garbage collection.
|
||||
pub plugin_gc: PluginGcConfigs,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
@@ -162,6 +166,7 @@ impl Default for Config {
|
||||
highlight_resolved_externals: false,
|
||||
|
||||
plugins: HashMap::new(),
|
||||
plugin_gc: PluginGcConfigs::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -671,6 +676,9 @@ impl Value {
|
||||
);
|
||||
}
|
||||
}
|
||||
"plugin_gc" => {
|
||||
config.plugin_gc.process(&[key], value, &mut errors);
|
||||
}
|
||||
// Menus
|
||||
"menus" => match create_menus(value) {
|
||||
Ok(map) => config.menus = map,
|
||||
|
252
crates/nu-protocol/src/config/plugin_gc.rs
Normal file
252
crates/nu-protocol/src/config/plugin_gc.rs
Normal file
@@ -0,0 +1,252 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{record, ShellError, Span, Value};
|
||||
|
||||
use super::helper::{
|
||||
process_bool_config, report_invalid_key, report_invalid_value, ReconstructVal,
|
||||
};
|
||||
|
||||
/// Configures when plugins should be stopped if inactive
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub struct PluginGcConfigs {
|
||||
/// The config to use for plugins not otherwise specified
|
||||
pub default: PluginGcConfig,
|
||||
/// Specific configs for plugins (by name)
|
||||
pub plugins: HashMap<String, PluginGcConfig>,
|
||||
}
|
||||
|
||||
impl PluginGcConfigs {
|
||||
/// Get the plugin GC configuration for a specific plugin name. If not specified by name in the
|
||||
/// config, this is `default`.
|
||||
pub fn get(&self, plugin_name: &str) -> &PluginGcConfig {
|
||||
self.plugins.get(plugin_name).unwrap_or(&self.default)
|
||||
}
|
||||
|
||||
pub(super) fn process(
|
||||
&mut self,
|
||||
path: &[&str],
|
||||
value: &mut Value,
|
||||
errors: &mut Vec<ShellError>,
|
||||
) {
|
||||
if let Value::Record { val, .. } = value {
|
||||
// Handle resets to default if keys are missing
|
||||
if !val.contains("default") {
|
||||
self.default = PluginGcConfig::default();
|
||||
}
|
||||
if !val.contains("plugins") {
|
||||
self.plugins = HashMap::new();
|
||||
}
|
||||
|
||||
val.retain_mut(|key, value| {
|
||||
let span = value.span();
|
||||
match key {
|
||||
"default" => {
|
||||
self.default
|
||||
.process(&join_path(path, &["default"]), value, errors)
|
||||
}
|
||||
"plugins" => process_plugins(
|
||||
&join_path(path, &["plugins"]),
|
||||
value,
|
||||
errors,
|
||||
&mut self.plugins,
|
||||
),
|
||||
_ => {
|
||||
report_invalid_key(&join_path(path, &[key]), span, errors);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
} else {
|
||||
report_invalid_value("should be a record", value.span(), errors);
|
||||
*value = self.reconstruct_value(value.span());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ReconstructVal for PluginGcConfigs {
|
||||
fn reconstruct_value(&self, span: Span) -> Value {
|
||||
Value::record(
|
||||
record! {
|
||||
"default" => self.default.reconstruct_value(span),
|
||||
"plugins" => reconstruct_plugins(&self.plugins, span),
|
||||
},
|
||||
span,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn process_plugins(
|
||||
path: &[&str],
|
||||
value: &mut Value,
|
||||
errors: &mut Vec<ShellError>,
|
||||
plugins: &mut HashMap<String, PluginGcConfig>,
|
||||
) {
|
||||
if let Value::Record { val, .. } = value {
|
||||
// Remove any plugin configs that aren't in the value
|
||||
plugins.retain(|key, _| val.contains(key));
|
||||
|
||||
val.retain_mut(|key, value| {
|
||||
if matches!(value, Value::Record { .. }) {
|
||||
plugins.entry(key.to_owned()).or_default().process(
|
||||
&join_path(path, &[key]),
|
||||
value,
|
||||
errors,
|
||||
);
|
||||
true
|
||||
} else {
|
||||
report_invalid_value("should be a record", value.span(), errors);
|
||||
if let Some(conf) = plugins.get(key) {
|
||||
// Reconstruct the value if it existed before
|
||||
*value = conf.reconstruct_value(value.span());
|
||||
true
|
||||
} else {
|
||||
// Remove it if it didn't
|
||||
false
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn reconstruct_plugins(plugins: &HashMap<String, PluginGcConfig>, span: Span) -> Value {
|
||||
Value::record(
|
||||
plugins
|
||||
.iter()
|
||||
.map(|(key, val)| (key.to_owned(), val.reconstruct_value(span)))
|
||||
.collect(),
|
||||
span,
|
||||
)
|
||||
}
|
||||
|
||||
/// Configures when a plugin should be stopped if inactive
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PluginGcConfig {
|
||||
/// True if the plugin should be stopped automatically
|
||||
pub enabled: bool,
|
||||
/// When to stop the plugin if not in use for this long (in nanoseconds)
|
||||
pub stop_after: i64,
|
||||
}
|
||||
|
||||
impl Default for PluginGcConfig {
|
||||
fn default() -> Self {
|
||||
PluginGcConfig {
|
||||
enabled: true,
|
||||
stop_after: 10_000_000_000, // 10sec
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginGcConfig {
|
||||
fn process(&mut self, path: &[&str], value: &mut Value, errors: &mut Vec<ShellError>) {
|
||||
if let Value::Record { val, .. } = value {
|
||||
// Handle resets to default if keys are missing
|
||||
if !val.contains("enabled") {
|
||||
self.enabled = PluginGcConfig::default().enabled;
|
||||
}
|
||||
if !val.contains("stop_after") {
|
||||
self.stop_after = PluginGcConfig::default().stop_after;
|
||||
}
|
||||
|
||||
val.retain_mut(|key, value| {
|
||||
let span = value.span();
|
||||
match key {
|
||||
"enabled" => process_bool_config(value, errors, &mut self.enabled),
|
||||
"stop_after" => match value {
|
||||
Value::Duration { val, .. } => {
|
||||
if *val >= 0 {
|
||||
self.stop_after = *val;
|
||||
} else {
|
||||
report_invalid_value("must not be negative", span, errors);
|
||||
*val = self.stop_after;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
report_invalid_value("should be a duration", span, errors);
|
||||
*value = Value::duration(self.stop_after, span);
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
report_invalid_key(&join_path(path, &[key]), span, errors);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
})
|
||||
} else {
|
||||
report_invalid_value("should be a record", value.span(), errors);
|
||||
*value = self.reconstruct_value(value.span());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ReconstructVal for PluginGcConfig {
|
||||
fn reconstruct_value(&self, span: Span) -> Value {
|
||||
Value::record(
|
||||
record! {
|
||||
"enabled" => Value::bool(self.enabled, span),
|
||||
"stop_after" => Value::duration(self.stop_after, span),
|
||||
},
|
||||
span,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn join_path<'a>(a: &[&'a str], b: &[&'a str]) -> Vec<&'a str> {
|
||||
a.iter().copied().chain(b.iter().copied()).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn test_pair() -> (PluginGcConfigs, Value) {
|
||||
(
|
||||
PluginGcConfigs {
|
||||
default: PluginGcConfig {
|
||||
enabled: true,
|
||||
stop_after: 30_000_000_000,
|
||||
},
|
||||
plugins: [(
|
||||
"my_plugin".to_owned(),
|
||||
PluginGcConfig {
|
||||
enabled: false,
|
||||
stop_after: 0,
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
},
|
||||
Value::test_record(record! {
|
||||
"default" => Value::test_record(record! {
|
||||
"enabled" => Value::test_bool(true),
|
||||
"stop_after" => Value::test_duration(30_000_000_000),
|
||||
}),
|
||||
"plugins" => Value::test_record(record! {
|
||||
"my_plugin" => Value::test_record(record! {
|
||||
"enabled" => Value::test_bool(false),
|
||||
"stop_after" => Value::test_duration(0),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process() {
|
||||
let (expected, mut input) = test_pair();
|
||||
let mut errors = vec![];
|
||||
let mut result = PluginGcConfigs::default();
|
||||
result.process(&[], &mut input, &mut errors);
|
||||
assert!(errors.is_empty(), "errors: {errors:#?}");
|
||||
assert_eq!(expected, result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconstruct() {
|
||||
let (input, expected) = test_pair();
|
||||
assert_eq!(expected, input.reconstruct_value(Span::test_data()));
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user