nushell/crates/nu_plugin_custom_values/src/handle_make.rs
Devyn Cairns cbf7feef22
Make drop notification timing for plugin custom values more consistent (#12341)
# Description
This keeps plugin custom values that have requested drop notification
around during the lifetime of a plugin call / stream by sending them to
a channel that gets persisted during the lifetime of the call.

Before this change, it was very likely that the drop notification would
be sent before the plugin ever had a chance to handle the value it
received.

Tests have been added to make sure this works - see the `custom_values`
plugin.

cc @ayax79 

# User-Facing Changes
This is basically just a bugfix, just a slightly big one.

However, I did add an `as_mut_any()` function for custom values, to
avoid having to clone them. This is a breaking change.
2024-04-04 09:13:25 +02:00

48 lines
1.2 KiB
Rust

use std::sync::atomic;
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand};
use nu_protocol::{LabeledError, Signature, Type, Value};
use crate::{handle_custom_value::HandleCustomValue, CustomValuePlugin};
pub struct HandleMake;
impl SimplePluginCommand for HandleMake {
type Plugin = CustomValuePlugin;
fn name(&self) -> &str {
"custom-value handle make"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_type(Type::Any, Type::Custom("HandleCustomValue".into()))
}
fn usage(&self) -> &str {
"Store a value in plugin memory and return a handle to it"
}
fn run(
&self,
plugin: &Self::Plugin,
_engine: &EngineInterface,
call: &EvaluatedCall,
input: &Value,
) -> Result<Value, LabeledError> {
// Generate an id and store in the plugin.
let new_id = plugin.counter.fetch_add(1, atomic::Ordering::Relaxed);
plugin
.handles
.lock()
.map_err(|err| LabeledError::new(err.to_string()))?
.insert(new_id, input.clone());
Ok(Value::custom(
Box::new(HandleCustomValue(new_id)),
call.head,
))
}
}