nitro_plugin 0.30.0

Plugin loading and definition for Nitrolaunch
Documentation
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt::Debug;
use std::path::PathBuf;
use std::sync::Arc;

use anyhow::Context;
use anyhow::bail;
use nitro_shared::output::NitroOutput;
use serde::Serialize;
use serde::{Deserialize, Deserializer};
use tokio::sync::Mutex;

use crate::PluginPaths;
use crate::hook::Hook;
use crate::hook::PLUGIN_DIR_TOKEN;
use crate::hook::WASM_FILE_NAME;
use crate::hook::call::HookCallArg;
use crate::hook::call::HookCallContext;
use crate::hook::call::HookHandle;
use crate::hook::hooks::StartWorker;
use crate::hook::wasm::call_wasm;
use crate::hook::wasm::loader::WASMLoader;
use crate::host::PluginContext;

/// The newest protocol version for plugin communication
pub const NEWEST_PROTOCOL_VERSION: u16 = 3;
/// The default protocol version used for compatability
pub const DEFAULT_PROTOCOL_VERSION: u16 = 1;
/// Token used for file replacement in hook handlers
pub static FILE_REPLACEMENT_TOKEN: &str = "$file:";

/// A plugin
pub struct Plugin {
	/// The plugin's ID
	id: String,
	/// The plugin's manifest
	pub manifest: PluginManifest,
	/// The custom config for the plugin, serialized from JSON
	custom_config: Option<String>,
	/// The working directory for the plugin
	working_dir: Option<PathBuf>,
	/// The persistent state of the plugin
	persistence: Arc<Mutex<PluginPersistence>>,
}

impl Plugin {
	/// Create a new plugin from an ID and manifest
	pub fn new(id: String, manifest: PluginManifest) -> Self {
		Self {
			id,
			manifest,
			custom_config: None,
			working_dir: None,
			persistence: Arc::new(Mutex::new(PluginPersistence::new())),
		}
	}

	/// Get the ID of the plugin
	pub fn get_id(&self) -> &String {
		&self.id
	}

	/// Get the manifest of the plugin
	pub fn get_manifest(&self) -> &PluginManifest {
		&self.manifest
	}

	/// Call a hook on the plugin
	pub async fn call_hook<H: Hook>(
		&self,
		hook: &H,
		arg: &H::Arg,
		paths: &PluginPaths,
		nitro_version: Option<&str>,
		plugin_list: &[String],
		wasm_loader: Arc<Mutex<WASMLoader>>,
		context: Option<&Arc<dyn PluginContext>>,
		o: &mut impl NitroOutput,
	) -> anyhow::Result<Option<HookHandle<H>>> {
		let Some(handler) = self.manifest.hooks.get(hook.get_name()) else {
			return Ok(None);
		};

		self.call_hook_handler(
			hook,
			handler,
			arg,
			paths,
			nitro_version,
			plugin_list,
			wasm_loader,
			context,
			o,
		)
		.await
	}

	/// Call a hook handler on the plugin
	async fn call_hook_handler<H: Hook>(
		&self,
		hook: &H,
		handler: &HookHandler,
		arg: &H::Arg,
		paths: &PluginPaths,
		nitro_version: Option<&str>,
		plugin_list: &[String],
		wasm_loader: Arc<Mutex<WASMLoader>>,
		context: Option<&Arc<dyn PluginContext>>,
		o: &mut impl NitroOutput,
	) -> anyhow::Result<Option<HookHandle<H>>> {
		match handler {
			HookHandler::Wasm { .. } => {
				let file = self
					.working_dir
					.as_ref()
					.context("WASM handler without working dir")?
					.join(WASM_FILE_NAME)
					.to_string_lossy()
					.to_string();

				let subscriptions = HashSet::new();
				let ctx = HookCallContext {
					subscriptions: &subscriptions,
					custom_config: self.custom_config.clone(),
					nitro_version,
					plugin_list,
					global_context: context,
				};

				let arg = HookCallArg {
					cmd: &file,
					arg,
					additional_args: &[],
					working_dir: self.working_dir.as_deref(),
					ctx,
					use_base64: !self.manifest.raw_transfer,
					persistence: self.persistence.clone(),
					paths,
					plugin_id: &self.id,
					protocol_version: self
						.manifest
						.protocol_version
						.unwrap_or(DEFAULT_PROTOCOL_VERSION),
					wasm_loader,
				};
				call_wasm(hook, arg, o).await.map(Some)
			}
			HookHandler::Execute {
				executable,
				args,
				priority: _,
				subscriptions,
			} => {
				let ctx = HookCallContext {
					subscriptions,
					custom_config: self.custom_config.clone(),
					nitro_version,
					plugin_list,
					global_context: context,
				};

				let arg = HookCallArg {
					cmd: executable,
					arg,
					additional_args: args,
					working_dir: self.working_dir.as_deref(),
					ctx,
					use_base64: !self.manifest.raw_transfer,
					persistence: self.persistence.clone(),
					paths,
					plugin_id: &self.id,
					protocol_version: self
						.manifest
						.protocol_version
						.unwrap_or(DEFAULT_PROTOCOL_VERSION),
					wasm_loader,
				};
				hook.call(arg, o).await.map(Some)
			}
			HookHandler::Constant {
				constant,
				priority: _,
			} => {
				// Replace file tokens
				let mut value = constant.clone();

				replace_file_tokens(&mut value, &self.working_dir, false)?;

				Ok(Some(HookHandle::constant(
					serde_json::from_value(value)?,
					self.id.clone(),
				)))
			}
			HookHandler::File { file, priority: _ } => {
				let Some(working_dir) = &self.working_dir else {
					bail!("Plugin does not have a directory for the file hook handler to look in");
				};

				let path = working_dir.join(file);
				let contents = std::fs::read_to_string(path)
					.context("Failed to read hook result from file")?;

				// Try to read the result with quotes wrapping it if it doesn't deserialize properly the first time
				let result = match serde_json::from_str(&contents) {
					Ok(result) => result,
					Err(_) => serde_json::from_value(serde_json::Value::String(contents))
						.context("Failed to deserialize hook result")?,
				};

				Ok(Some(HookHandle::constant(result, self.id.clone())))
			}
			HookHandler::Match {
				property,
				cases,
				priority: _,
			} => {
				let arg2 = serde_json::to_value(arg)?;
				let lhs = if let Some(property) = property {
					let arg2 = arg2.as_object().context(
						"Hook argument is not an object, so a property cannot be matched",
					)?;
					arg2.get(property)
						.context("Property does not exist on hook argument")
						.cloned()?
				} else {
					arg2
				};
				let lhs = serde_json::to_string(&lhs)?;

				for (case, handler) in cases.iter() {
					if &lhs == case {
						return Box::pin(self.call_hook_handler(
							hook,
							handler,
							arg,
							paths,
							nitro_version,
							plugin_list,
							wasm_loader,
							context,
							o,
						))
						.await;
					}
				}

				Ok(None)
			}
			HookHandler::Native {
				function,
				priority: _,
			} => {
				let arg = serde_json::to_value(arg)
					.context("Failed to serialize native hook argument")?;
				let result = function
					.call(arg)
					.await
					.context("Native hook handler failed")?;
				let result = serde_json::from_value(result)
					.context("Failed to deserialize native hook result")?;
				Ok(Some(HookHandle::constant(result, self.id.clone())))
			}
		}
	}

	/// Set the custom config of the plugin
	pub fn set_custom_config(&mut self, config: serde_json::Value) -> anyhow::Result<()> {
		let serialized =
			serde_json::to_string(&config).context("Failed to serialize custom plugin config")?;
		self.custom_config = Some(serialized);
		Ok(())
	}

	/// Set the working dir of the plugin
	pub fn set_working_dir(&mut self, dir: PathBuf) {
		self.working_dir = Some(dir);
	}

	/// Set the plugin's worker handle
	pub async fn set_worker(&mut self, worker: HookHandle<StartWorker>) -> anyhow::Result<()> {
		let mut lock = self.persistence.lock().await;
		lock.worker = Some(worker);

		Ok(())
	}

	/// Get the priority of the given hook
	pub fn get_hook_priority<H: Hook>(&self, hook: &H) -> HookPriority {
		let Some(handler) = self.manifest.hooks.get(hook.get_name()) else {
			return HookPriority::Any;
		};
		match handler {
			HookHandler::Wasm { priority, .. }
			| HookHandler::Execute { priority, .. }
			| HookHandler::Constant { priority, .. }
			| HookHandler::File { priority, .. }
			| HookHandler::Match { priority, .. }
			| HookHandler::Native { priority, .. } => *priority,
		}
	}
}

/// The manifest for a plugin that describes how it works
#[derive(Deserialize, Debug, Default)]
#[serde(default)]
pub struct PluginManifest {
	/// ID for the plugin
	pub id: Option<String>,
	/// Metadata for the plugin
	#[serde(flatten)]
	pub meta: PluginMetadata,
	/// The current version of the plugin
	pub version: Option<String>,
	/// The Nitrolaunch version this plugin is for
	#[serde(alias = "mcvm_version")]
	pub nitro_version: Option<String>,
	/// The hook handlers for the plugin
	pub hooks: HashMap<String, HookHandler>,
	/// Plugins that this plugin depends on
	pub dependencies: Vec<String>,
	/// Message to display when the plugin is installed
	pub install_message: Option<String>,
	/// The protocol version of the plugin
	pub protocol_version: Option<u16>,
	/// Whether to disable base64 encoding in the protocol
	pub raw_transfer: bool,
	/// Whether the plugin supports creating custom instances
	pub supports_instance_creation: bool,
	/// Whether the plugin supports creating custom templates
	pub supports_template_creation: bool,
	/// The subcommands the plugin provides
	pub subcommands: HashMap<String, PluginProvidedSubcommand>,
}

impl PluginManifest {
	/// Create a new PluginManifest
	pub fn new() -> Self {
		Self::default()
	}
}

/// Optional metadata for a plugin
#[derive(Serialize, Deserialize, Default, Debug)]
#[serde(default)]
pub struct PluginMetadata {
	/// The display name of the plugin
	pub name: Option<String>,
	/// The short description of the plugin
	pub description: Option<String>,
	/// URL for plugin documentation
	pub documentation: Option<String>,
}

/// A CLI subcommand provided by a plugin
#[derive(Deserialize, Debug)]
#[serde(untagged)]
pub enum PluginProvidedSubcommand {
	/// A root-level subcommand, containing the description
	Global(String),
	/// A subsubcommand
	Specific {
		/// The command to be under
		supercommand: String,
		/// The description
		description: String,
	},
}

/// A handler for a single hook that a plugin uses
#[derive(Deserialize)]
#[serde(untagged)]
#[serde(rename_all = "snake_case")]
pub enum HookHandler {
	/// Handle this hook by running WASM
	Wasm {
		/// Marker thingy
		wasm: bool,
		/// The priority for the hook
		#[serde(default)]
		priority: HookPriority,
	},
	/// Handle this hook by running an executable
	Execute {
		/// The executable to run
		executable: String,
		/// Arguments for the executable
		#[serde(default)]
		args: Vec<String>,
		/// The priority for the hook
		#[serde(default)]
		priority: HookPriority,
		/// Data for the hook to subscribe to
		#[serde(default)]
		subscriptions: HashSet<HookSubscription>,
	},
	/// Handle this hook by returning a constant result
	Constant {
		/// The constant result
		constant: serde_json::Value,
		/// The priority for the hook
		#[serde(default)]
		priority: HookPriority,
	},
	/// Handle this hook by getting the contents of a file
	File {
		/// The path to the file, relative to the plugin directory
		file: String,
		/// The priority for the hook
		#[serde(default)]
		priority: HookPriority,
	},
	/// Match against the argument to handle the hook differently
	Match {
		/// The property to match against
		#[serde(default)]
		property: Option<String>,
		/// The cases of the match
		cases: HashMap<String, Box<HookHandler>>,
		/// The priority for the hook
		#[serde(default)]
		priority: HookPriority,
	},
	/// Handle this hook with a native function call
	Native {
		/// The function to handle the hook
		#[serde(deserialize_with = "deserialize_native_function")]
		function: Arc<dyn NativeHookHandler>,
		/// The priority for the hook
		#[serde(default)]
		priority: HookPriority,
	},
}

impl Debug for HookHandler {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "HookHandler")
	}
}

/// Priority for a hook
#[derive(Deserialize, PartialEq, PartialOrd, Eq, Ord, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum HookPriority {
	/// The plugin will try to run before other ones
	First,
	/// The plugin will run at any time, usually in the middle
	#[default]
	Any,
	/// The plugin will try to run after other ones
	Last,
}

/// Data that an executable handler can subscribe to receiving
#[derive(Deserialize, PartialEq, Eq, Clone, Copy, Hash)]
#[serde(rename_all = "snake_case")]
pub enum HookSubscription {
	/// List of instances
	Instances,
	/// List of templates
	Templates,
}

/// Deserialize function for the native hook. No plugin manifests should ever use this,
/// so just return a function that does nothing.
fn deserialize_native_function<'de, D>(_: D) -> Result<Arc<dyn NativeHookHandler>, D::Error>
where
	D: Deserializer<'de>,
{
	Ok(Arc::new(NoneHookHandler))
}

/// Trait for native plugin hook handlers
#[async_trait::async_trait]
pub trait NativeHookHandler: Send + Sync {
	/// Call the hook
	async fn call(&self, arg: serde_json::Value) -> anyhow::Result<serde_json::Value>;
}

/// Used for deserialization
struct NoneHookHandler;

#[async_trait::async_trait]
impl NativeHookHandler for NoneHookHandler {
	async fn call(&self, arg: serde_json::Value) -> anyhow::Result<serde_json::Value> {
		let _ = arg;
		Ok(serde_json::Value::Null)
	}
}

/// Persistent state for plugins
pub struct PluginPersistence {
	/// The persistent state of the plugin
	pub state: serde_json::Value,
	/// The long-running plugin worker
	pub worker: Option<HookHandle<StartWorker>>,
}

impl Default for PluginPersistence {
	fn default() -> Self {
		Self::new()
	}
}

impl PluginPersistence {
	/// Initalize the persistent plugin state
	pub fn new() -> Self {
		Self {
			state: serde_json::Value::Null,
			worker: None,
		}
	}
}

/// Replaces file tokens in the string values of JSON value
fn replace_file_tokens(
	value: &mut serde_json::Value,
	working_dir: &Option<PathBuf>,
	test: bool,
) -> anyhow::Result<()> {
	match value {
		serde_json::Value::Array(values) => {
			for value in values {
				replace_file_tokens(value, working_dir, test)?;
			}
		}
		serde_json::Value::Object(props) => {
			for prop in props.values_mut() {
				replace_file_tokens(prop, working_dir, test)?;
			}
		}
		serde_json::Value::String(value) => {
			if let Some(path) = value.strip_prefix(FILE_REPLACEMENT_TOKEN) {
				if test {
					*value = "test".into();
					return Ok(());
				}

				let Some(working_dir) = working_dir else {
					bail!("Plugin does not have a directory for the file hook handler to look in");
				};

				let path = working_dir.join(path);
				let contents = std::fs::read_to_string(path)
					.context("Failed to read hook result from file")?;

				*value = contents;
			}

			if let Some(working_dir) = working_dir {
				*value = value.replace(PLUGIN_DIR_TOKEN, &working_dir.to_string_lossy());
			}
		}
		_ => {}
	}

	Ok(())
}

#[cfg(test)]
mod tests {
	use super::*;
	use serde_json::json;

	#[test]
	fn test_file_token_replacement() {
		let mut json = json!([{
			"foo": "bar",
			"baz": format!("{FILE_REPLACEMENT_TOKEN}foobar")
		}]);

		replace_file_tokens(&mut json, &None, true).unwrap();

		let expected = json!([{
			"foo": "bar",
			"baz": "test"
		}]);
		assert_eq!(json, expected);
	}
}