fix: relay Signals reset to plugins (#13510)

This PR will close #13501

# Description

This PR expands on [the relay of signals to running plugin
processes](https://github.com/nushell/nushell/pull/13181). The Ctrlc
relay has been generalized to SignalAction::Interrupt and when
reset_signal is called on the main EngineState, a SignalAction::Reset is
now relayed to running plugins.

# User-Facing Changes

The signal handler closure now takes a `signals::SignalAction`, while
previously it took no arguments. The handler will now be called on both
interrupt and reset. The method to register a handler on the plugin side
is now called `register_signal_handler` instead of
`register_ctrlc_handler`
[example](https://github.com/nushell/nushell/pull/13510/files#diff-3e04dff88fd0780a49778a3d1eede092ec729a1264b4ef07ca0d2baa859dad05L38).
This will only affect plugin authors who have started making use of
https://github.com/nushell/nushell/pull/13181, which isn't currently
part of an official release.

The change will also require all of user's plugins to be recompiled in
order that they don't error when a signal is received on the
PluginInterface.

# Testing

```
: example ctrlc
interrupt status: false
waiting for interrupt signal...
^Cinterrupt status: true
peace.
Error:   × Operation interrupted
   ╭─[display_output hook:1:1]
 1 │ if (term size).columns >= 100 { table -e } else { table }
   · ─┬
   ·  ╰── This operation was interrupted
   ╰────

: example ctrlc
interrupt status: false   <-- NOTE status is false
waiting for interrupt signal...
^Cinterrupt status: true
peace.
Error:   × Operation interrupted
   ╭─[display_output hook:1:1]
 1 │ if (term size).columns >= 100 { table -e } else { table }
   · ─┬
   ·  ╰── This operation was interrupted
   ╰────
   ```
This commit is contained in:
Andy Gayton
2024-08-06 06:35:40 -04:00
committed by GitHub
parent 73e8de9753
commit 1cd0544a3f
12 changed files with 86 additions and 79 deletions

View File

@@ -1,139 +0,0 @@
use std::fmt::Debug;
use std::sync::{Arc, Mutex};
use crate::{engine::Sequence, ShellError};
/// Handler is a closure that can be sent across threads and shared.
pub type Handler = Box<dyn Fn() + Send + Sync>;
/// Manages a collection of handlers.
#[derive(Clone)]
pub struct Handlers {
/// List of handler tuples containing an ID and the handler itself.
handlers: Arc<Mutex<Vec<(usize, Handler)>>>,
/// Sequence generator for unique IDs.
next_id: Arc<Sequence>,
}
impl Debug for Handlers {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Handlers")
.field("next_id", &self.next_id)
.finish()
}
}
/// Guard that unregisters a handler when dropped.
#[derive(Clone)]
pub struct Guard {
/// Unique ID of the handler.
id: usize,
/// Reference to the handlers list.
handlers: Arc<Mutex<Vec<(usize, Handler)>>>,
}
impl Drop for Guard {
/// Drops the `Guard`, removing the associated handler from the list.
fn drop(&mut self) {
if let Ok(mut handlers) = self.handlers.lock() {
handlers.retain(|(id, _)| *id != self.id);
}
}
}
impl Debug for Guard {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Guard").field("id", &self.id).finish()
}
}
impl Handlers {
pub fn new() -> Handlers {
let handlers = Arc::new(Mutex::new(vec![]));
let next_id = Arc::new(Sequence::default());
Handlers { handlers, next_id }
}
/// Registers a new handler and returns an RAII guard which will unregister the handler when
/// dropped.
pub fn register(&self, handler: Handler) -> Result<Guard, ShellError> {
let id = self.next_id.next()?;
if let Ok(mut handlers) = self.handlers.lock() {
handlers.push((id, handler));
}
Ok(Guard {
id,
handlers: Arc::clone(&self.handlers),
})
}
/// Runs all registered handlers.
pub fn run(&self) {
if let Ok(handlers) = self.handlers.lock() {
for (_, handler) in handlers.iter() {
handler();
}
}
}
}
impl Default for Handlers {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, Ordering};
#[test]
/// Tests registering and running multiple handlers.
fn test_multiple_handlers() {
let handlers = Handlers::new();
let called1 = Arc::new(AtomicBool::new(false));
let called2 = Arc::new(AtomicBool::new(false));
let called1_clone = Arc::clone(&called1);
let called2_clone = Arc::clone(&called2);
let _guard1 = handlers.register(Box::new(move || {
called1_clone.store(true, Ordering::SeqCst);
}));
let _guard2 = handlers.register(Box::new(move || {
called2_clone.store(true, Ordering::SeqCst);
}));
handlers.run();
assert!(called1.load(Ordering::SeqCst));
assert!(called2.load(Ordering::SeqCst));
}
#[test]
/// Tests the dropping of a guard and ensuring the handler is unregistered.
fn test_guard_drop() {
let handlers = Handlers::new();
let called = Arc::new(AtomicBool::new(false));
let called_clone = Arc::clone(&called);
let guard = handlers.register(Box::new(move || {
called_clone.store(true, Ordering::Relaxed);
}));
// Ensure the handler is registered
assert_eq!(handlers.handlers.lock().unwrap().len(), 1);
drop(guard);
// Ensure the handler is removed after dropping the guard
assert_eq!(handlers.handlers.lock().unwrap().len(), 0);
handlers.run();
// Ensure the handler is not called after being dropped
assert!(!called.load(Ordering::Relaxed));
}
}

View File

@@ -2,14 +2,14 @@ use crate::{
ast::Block,
debugger::{Debugger, NoopDebugger},
engine::{
ctrlc,
usage::{build_usage, Usage},
CachedFile, Command, CommandType, EnvVars, OverlayFrame, ScopeFrame, Stack, StateDelta,
Variable, Visibility, DEFAULT_OVERLAY_NAME,
},
eval_const::create_nu_constant,
BlockId, Category, Config, DeclId, FileId, GetSpan, HistoryConfig, Module, ModuleId, OverlayId,
ShellError, Signals, Signature, Span, SpanId, Type, Value, VarId, VirtualPathId,
BlockId, Category, Config, DeclId, FileId, GetSpan, Handlers, HistoryConfig, Module, ModuleId,
OverlayId, ShellError, SignalAction, Signals, Signature, Span, SpanId, Type, Value, VarId,
VirtualPathId,
};
use fancy_regex::Regex;
use lru::LruCache;
@@ -86,8 +86,8 @@ pub struct EngineState {
pub spans: Vec<Span>,
usage: Usage,
pub scope: ScopeFrame,
pub ctrlc_handlers: Option<ctrlc::Handlers>,
signals: Signals,
pub signal_handlers: Option<Handlers>,
pub env_vars: Arc<EnvVars>,
pub previous_env_vars: Arc<HashMap<String, Value>>,
pub config: Arc<Config>,
@@ -147,7 +147,7 @@ impl EngineState {
0,
false,
),
ctrlc_handlers: None,
signal_handlers: None,
signals: Signals::empty(),
env_vars: Arc::new(
[(DEFAULT_OVERLAY_NAME.to_string(), HashMap::new())]
@@ -186,7 +186,10 @@ impl EngineState {
}
pub fn reset_signals(&mut self) {
self.signals.reset()
self.signals.reset();
if let Some(ref handlers) = self.signal_handlers {
handlers.run(SignalAction::Reset);
}
}
pub fn set_signals(&mut self, signals: Signals) {
@@ -272,9 +275,9 @@ impl EngineState {
#[cfg(feature = "plugin")]
if !delta.plugins.is_empty() {
for plugin in std::mem::take(&mut delta.plugins) {
// Connect plugins to the ctrlc handlers
if let Some(handlers) = &self.ctrlc_handlers {
plugin.clone().configure_ctrlc_handler(handlers)?;
// Connect plugins to the signal handlers
if let Some(handlers) = &self.signal_handlers {
plugin.clone().configure_signal_handler(handlers)?;
}
// Replace plugins that overlap in identity.

View File

@@ -34,5 +34,3 @@ pub use stack_out_dest::*;
pub use state_delta::*;
pub use state_working_set::*;
pub use variable::*;
pub mod ctrlc;