1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
use std::sync::Arc;
use nu_protocol::{CustomValue, ShellError, Span, Spanned, Value};
use serde::{Deserialize, Serialize};
use crate::plugin::PluginIdentity;
#[cfg(test)]
mod tests;
/// An opaque container for a custom value that is handled fully by a plugin
///
/// This is the only type of custom value that is allowed to cross the plugin serialization
/// boundary.
///
/// [`EngineInterface`](crate::interface::EngineInterface) is responsible for ensuring
/// that local plugin custom values are converted to and from [`PluginCustomData`] on the boundary.
///
/// [`PluginInterface`](crate::interface::PluginInterface) is responsible for adding the
/// appropriate [`PluginIdentity`](crate::plugin::PluginIdentity), ensuring that only
/// [`PluginCustomData`] is contained within any values sent, and that the `source` of any
/// values sent matches the plugin it is being sent to.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PluginCustomValue {
/// The name of the custom value as defined by the plugin (`value_string()`)
pub name: String,
/// The bincoded representation of the custom value on the plugin side
pub data: Vec<u8>,
/// Which plugin the custom value came from. This is not defined on the plugin side. The engine
/// side is responsible for maintaining it, and it is not sent over the serialization boundary.
#[serde(skip, default)]
pub source: Option<Arc<PluginIdentity>>,
}
#[typetag::serde]
impl CustomValue for PluginCustomValue {
fn clone_value(&self, span: nu_protocol::Span) -> nu_protocol::Value {
Value::custom_value(Box::new(self.clone()), span)
}
fn value_string(&self) -> String {
self.name.clone()
}
fn to_base_value(
&self,
span: nu_protocol::Span,
) -> Result<nu_protocol::Value, nu_protocol::ShellError> {
let wrap_err = |err: ShellError| ShellError::GenericError {
error: format!(
"Unable to spawn plugin `{}` to get base value",
self.source
.as_ref()
.map(|s| s.plugin_name.as_str())
.unwrap_or("<unknown>")
),
msg: err.to_string(),
span: Some(span),
help: None,
inner: vec![err],
};
let identity = self.source.clone().ok_or_else(|| {
wrap_err(ShellError::NushellFailed {
msg: "The plugin source for the custom value was not set".into(),
})
})?;
let empty_env: Option<(String, String)> = None;
let plugin = identity.spawn(empty_env).map_err(wrap_err)?;
plugin
.custom_value_to_base_value(Spanned {
item: self.clone(),
span,
})
.map_err(wrap_err)
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
impl PluginCustomValue {
/// Serialize a custom value into a [`PluginCustomValue`]. This should only be done on the
/// plugin side.
pub(crate) fn serialize_from_custom_value(
custom_value: &dyn CustomValue,
span: Span,
) -> Result<PluginCustomValue, ShellError> {
let name = custom_value.value_string();
bincode::serialize(custom_value)
.map(|data| PluginCustomValue {
name,
data,
source: None,
})
.map_err(|err| ShellError::CustomValueFailedToEncode {
msg: err.to_string(),
span,
})
}
/// Deserialize a [`PluginCustomValue`] into a `Box<dyn CustomValue>`. This should only be done
/// on the plugin side.
pub(crate) fn deserialize_to_custom_value(
&self,
span: Span,
) -> Result<Box<dyn CustomValue>, ShellError> {
bincode::deserialize::<Box<dyn CustomValue>>(&self.data).map_err(|err| {
ShellError::CustomValueFailedToDecode {
msg: err.to_string(),
span,
}
})
}
/// Add a [`PluginIdentity`] to all [`PluginCustomValue`]s within a value, recursively.
pub(crate) fn add_source(value: &mut Value, source: &Arc<PluginIdentity>) {
let span = value.span();
match value {
// Set source on custom value
Value::CustomValue { ref val, .. } => {
if let Some(custom_value) = val.as_any().downcast_ref::<PluginCustomValue>() {
// Since there's no `as_mut_any()`, we have to copy the whole thing
let mut custom_value = custom_value.clone();
custom_value.source = Some(source.clone());
*value = Value::custom_value(Box::new(custom_value), span);
}
}
// Any values that can contain other values need to be handled recursively
Value::Range { ref mut val, .. } => {
Self::add_source(&mut val.from, source);
Self::add_source(&mut val.to, source);
Self::add_source(&mut val.incr, source);
}
Value::Record { ref mut val, .. } => {
for (_, rec_value) in val.iter_mut() {
Self::add_source(rec_value, source);
}
}
Value::List { ref mut vals, .. } => {
for list_value in vals.iter_mut() {
Self::add_source(list_value, source);
}
}
// All of these don't contain other values
Value::Bool { .. }
| Value::Int { .. }
| Value::Float { .. }
| Value::Filesize { .. }
| Value::Duration { .. }
| Value::Date { .. }
| Value::String { .. }
| Value::Glob { .. }
| Value::Block { .. }
| Value::Closure { .. }
| Value::Nothing { .. }
| Value::Error { .. }
| Value::Binary { .. }
| Value::CellPath { .. } => (),
// LazyRecord could generate other values, but we shouldn't be receiving it anyway
//
// It's better to handle this as a bug
Value::LazyRecord { .. } => unimplemented!("add_source for LazyRecord"),
}
}
/// Check that all [`CustomValue`]s present within the `value` are [`PluginCustomValue`]s that
/// come from the given `source`, and return an error if not.
///
/// This method will collapse `LazyRecord` in-place as necessary to make the guarantee,
/// since `LazyRecord` could return something different the next time it is called.
pub(crate) fn verify_source(
value: &mut Value,
source: &PluginIdentity,
) -> Result<(), ShellError> {
let span = value.span();
match value {
// Set source on custom value
Value::CustomValue { val, .. } => {
if let Some(custom_value) = val.as_any().downcast_ref::<PluginCustomValue>() {
if custom_value.source.as_deref() == Some(source) {
Ok(())
} else {
Err(ShellError::CustomValueIncorrectForPlugin {
name: custom_value.name.clone(),
span,
dest_plugin: source.plugin_name.clone(),
src_plugin: custom_value.source.as_ref().map(|s| s.plugin_name.clone()),
})
}
} else {
// Only PluginCustomValues can be sent
Err(ShellError::CustomValueIncorrectForPlugin {
name: val.value_string(),
span,
dest_plugin: source.plugin_name.clone(),
src_plugin: None,
})
}
}
// Any values that can contain other values need to be handled recursively
Value::Range { val, .. } => {
Self::verify_source(&mut val.from, source)?;
Self::verify_source(&mut val.to, source)?;
Self::verify_source(&mut val.incr, source)
}
Value::Record { ref mut val, .. } => val
.iter_mut()
.try_for_each(|(_, rec_value)| Self::verify_source(rec_value, source)),
Value::List { ref mut vals, .. } => vals
.iter_mut()
.try_for_each(|list_value| Self::verify_source(list_value, source)),
// All of these don't contain other values
Value::Bool { .. }
| Value::Int { .. }
| Value::Float { .. }
| Value::Filesize { .. }
| Value::Duration { .. }
| Value::Date { .. }
| Value::String { .. }
| Value::Glob { .. }
| Value::Block { .. }
| Value::Closure { .. }
| Value::Nothing { .. }
| Value::Error { .. }
| Value::Binary { .. }
| Value::CellPath { .. } => Ok(()),
// LazyRecord would be a problem for us, since it could return something else the next
// time, and we have to collect it anyway to serialize it. Collect it in place, and then
// verify the source of the result
Value::LazyRecord { val, .. } => {
*value = val.collect()?;
Self::verify_source(value, source)
}
}
}
/// Convert all plugin-native custom values to [`PluginCustomValue`] within the given `value`,
/// recursively. This should only be done on the plugin side.
pub(crate) fn serialize_custom_values_in(value: &mut Value) -> Result<(), ShellError> {
let span = value.span();
match value {
Value::CustomValue { ref val, .. } => {
if val.as_any().downcast_ref::<PluginCustomValue>().is_some() {
// Already a PluginCustomValue
Ok(())
} else {
let serialized = Self::serialize_from_custom_value(&**val, span)?;
*value = Value::custom_value(Box::new(serialized), span);
Ok(())
}
}
// Any values that can contain other values need to be handled recursively
Value::Range { ref mut val, .. } => {
Self::serialize_custom_values_in(&mut val.from)?;
Self::serialize_custom_values_in(&mut val.to)?;
Self::serialize_custom_values_in(&mut val.incr)
}
Value::Record { ref mut val, .. } => val
.iter_mut()
.try_for_each(|(_, rec_value)| Self::serialize_custom_values_in(rec_value)),
Value::List { ref mut vals, .. } => vals
.iter_mut()
.try_for_each(Self::serialize_custom_values_in),
// All of these don't contain other values
Value::Bool { .. }
| Value::Int { .. }
| Value::Float { .. }
| Value::Filesize { .. }
| Value::Duration { .. }
| Value::Date { .. }
| Value::String { .. }
| Value::Glob { .. }
| Value::Block { .. }
| Value::Closure { .. }
| Value::Nothing { .. }
| Value::Error { .. }
| Value::Binary { .. }
| Value::CellPath { .. } => Ok(()),
// Collect any lazy records that exist and try again
Value::LazyRecord { val, .. } => {
*value = val.collect()?;
Self::serialize_custom_values_in(value)
}
}
}
/// Convert all [`PluginCustomValue`]s to plugin-native custom values within the given `value`,
/// recursively. This should only be done on the plugin side.
pub(crate) fn deserialize_custom_values_in(value: &mut Value) -> Result<(), ShellError> {
let span = value.span();
match value {
Value::CustomValue { ref val, .. } => {
if let Some(val) = val.as_any().downcast_ref::<PluginCustomValue>() {
let deserialized = val.deserialize_to_custom_value(span)?;
*value = Value::custom_value(deserialized, span);
Ok(())
} else {
// Already not a PluginCustomValue
Ok(())
}
}
// Any values that can contain other values need to be handled recursively
Value::Range { ref mut val, .. } => {
Self::deserialize_custom_values_in(&mut val.from)?;
Self::deserialize_custom_values_in(&mut val.to)?;
Self::deserialize_custom_values_in(&mut val.incr)
}
Value::Record { ref mut val, .. } => val
.iter_mut()
.try_for_each(|(_, rec_value)| Self::deserialize_custom_values_in(rec_value)),
Value::List { ref mut vals, .. } => vals
.iter_mut()
.try_for_each(Self::deserialize_custom_values_in),
// All of these don't contain other values
Value::Bool { .. }
| Value::Int { .. }
| Value::Float { .. }
| Value::Filesize { .. }
| Value::Duration { .. }
| Value::Date { .. }
| Value::String { .. }
| Value::Glob { .. }
| Value::Block { .. }
| Value::Closure { .. }
| Value::Nothing { .. }
| Value::Error { .. }
| Value::Binary { .. }
| Value::CellPath { .. } => Ok(()),
// Collect any lazy records that exist and try again
Value::LazyRecord { val, .. } => {
*value = val.collect()?;
Self::deserialize_custom_values_in(value)
}
}
}
}