nitro_config 0.30.0

Serialization for Nitrolaunch configuration
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
use std::collections::HashMap;

use anyhow::Context;
use nitro_shared::Side;
use nitro_shared::id::TemplateID;
use nitro_shared::output::{MessageContents, NitroOutput};
use nitro_shared::pkg::{PkgRequest, PkgRequestSource};
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::instance::InstanceConfig;
use super::package::PackageConfigDeser;

/// Configuration for a template
#[derive(Deserialize, Serialize, Clone, Default)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct TemplateConfig {
	/// The configuration for the instance
	#[serde(flatten)]
	pub instance: InstanceConfig,
	/// Loader configuration
	#[serde(default)]
	pub loader: TemplateLoaderConfiguration,
	/// Package configuration
	#[serde(default)]
	pub packages: TemplatePackageConfiguration,
}

impl TemplateConfig {
	/// Merge this template with another one
	pub fn merge(&mut self, other: Self) {
		self.instance.merge(other.instance);
		self.loader.merge(&other.loader);
		self.packages.merge(other.packages);
	}
}

/// Different representations of loader configuration on a template
#[derive(Deserialize, Serialize, Debug, Clone)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(untagged)]
pub enum TemplateLoaderConfiguration {
	/// Same loader for client and server
	Simple(Option<String>),
	/// Full configuration
	Full {
		/// Loader for the client
		client: Option<String>,
		/// Loader for the server
		server: Option<String>,
	},
}

impl Default for TemplateLoaderConfiguration {
	fn default() -> Self {
		Self::Simple(None)
	}
}

impl TemplateLoaderConfiguration {
	/// Gets the client side of this configuration
	pub fn client(&self) -> Option<&String> {
		match self {
			Self::Simple(loader) => loader.as_ref(),
			Self::Full { client, .. } => client.as_ref(),
		}
	}

	/// Gets the server side of this configuration
	pub fn server(&self) -> Option<&String> {
		match self {
			Self::Simple(loader) => loader.as_ref(),
			Self::Full { server, .. } => server.as_ref(),
		}
	}

	/// Merges this configuration with another one
	pub fn merge(&mut self, other: &Self) {
		let out = Self::Full {
			client: other.client().or(self.client()).cloned(),
			server: other.server().or(self.server()).cloned(),
		};
		*self = if out.client() == out.server() {
			Self::Simple(out.client().cloned())
		} else {
			out
		};
	}
}

/// Different representations of package configuration on a template
#[derive(Deserialize, Serialize, Debug, Clone)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(untagged)]
pub enum TemplatePackageConfiguration {
	/// Is just a list of packages for every instance
	Simple(Vec<PackageConfigDeser>),
	/// Full configuration
	Full {
		/// Packages to apply to every instance
		#[serde(default)]
		global: Vec<PackageConfigDeser>,
		/// Packages to apply to only clients
		#[serde(default)]
		client: Vec<PackageConfigDeser>,
		/// Packages to apply to only servers
		#[serde(default)]
		server: Vec<PackageConfigDeser>,
	},
}

impl Default for TemplatePackageConfiguration {
	fn default() -> Self {
		Self::Simple(Vec::new())
	}
}

impl TemplatePackageConfiguration {
	/// Merge this configuration with one from another template, with right taking precedence
	pub fn merge(&mut self, other: Self) {
		match (&mut *self, other) {
			(Self::Simple(left), Self::Simple(right)) => {
				left.extend(right);
			}
			(Self::Full { global, .. }, Self::Simple(right)) => {
				global.extend(right);
			}
			(
				Self::Simple(left),
				Self::Full {
					global,
					client,
					server,
				},
			) => {
				left.extend(global);
				*self = Self::Full {
					global: left.clone(),
					client,
					server,
				};
			}
			(
				Self::Full {
					global: global1,
					client: client1,
					server: server1,
				},
				Self::Full {
					global: global2,
					client: client2,
					server: server2,
				},
			) => {
				global1.extend(global2);
				client1.extend(client2);
				server1.extend(server2);
			}
		}
	}

	/// Validate all the configured packages
	pub fn validate(&self) -> anyhow::Result<()> {
		match &self {
			Self::Simple(global) => {
				for pkg in global {
					pkg.validate()?;
				}
			}
			Self::Full {
				global,
				client,
				server,
			} => {
				for pkg in global.iter().chain(client.iter()).chain(server.iter()) {
					pkg.validate()?;
				}
			}
		}

		Ok(())
	}

	/// Iterate over all of the packages
	pub fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = &'a PackageConfigDeser> + 'a> {
		match &self {
			Self::Simple(global) => Box::new(global.iter()),
			Self::Full {
				global,
				client,
				server,
			} => Box::new(global.iter().chain(client.iter()).chain(server.iter())),
		}
	}

	/// Iterate over the global package list
	pub fn iter_global(&self) -> impl Iterator<Item = &PackageConfigDeser> {
		match &self {
			Self::Simple(global) => global,
			Self::Full { global, .. } => global,
		}
		.iter()
	}

	/// Iterate over the package list for a specific side
	pub fn iter_side(&self, side: Side) -> impl Iterator<Item = &PackageConfigDeser> {
		match &self {
			Self::Simple(..) => [].iter(),
			Self::Full { client, server, .. } => match side {
				Side::Client => client.iter(),
				Side::Server => server.iter(),
			},
		}
	}

	/// Adds a package to the global list
	pub fn add_global_package(&mut self, pkg: PackageConfigDeser) {
		match self {
			Self::Simple(global) => global.push(pkg),
			Self::Full { global, .. } => global.push(pkg),
		}
	}

	/// Adds a package to the client list
	pub fn add_client_package(&mut self, pkg: PackageConfigDeser) {
		match self {
			Self::Simple(global) => {
				*self = Self::Full {
					global: global.clone(),
					client: vec![pkg],
					server: Vec::new(),
				}
			}
			Self::Full { client, .. } => client.push(pkg),
		}
	}

	/// Adds a package to the server list
	pub fn add_server_package(&mut self, pkg: PackageConfigDeser) {
		match self {
			Self::Simple(global) => {
				*self = Self::Full {
					global: global.clone(),
					client: Vec::new(),
					server: vec![pkg],
				}
			}
			Self::Full { server, .. } => server.push(pkg),
		}
	}
}

/// Consolidates template configs into the full templates
pub fn consolidate_template_configs(
	templates: HashMap<TemplateID, TemplateConfig>,
	base_template: Option<&TemplateConfig>,
	o: &mut impl NitroOutput,
) -> HashMap<TemplateID, TemplateConfig> {
	let mut out: HashMap<_, TemplateConfig> = HashMap::with_capacity(templates.len());

	let max_iterations = 10000;

	// We do this by repeatedly finding a template with an already resolved ancenstor
	let mut i = 0;
	while out.len() != templates.len() {
		for (id, template) in &templates {
			// Don't redo templates that are already done
			if out.contains_key(id) {
				continue;
			}

			if template.instance.from.is_empty() {
				// Templates with no ancestor can just be added directly to the output, after deriving from the base template
				let mut template = template.clone();
				if let Some(base_template) = base_template {
					let overlay = template;
					template = base_template.clone();
					template.merge(overlay);
				}
				out.insert(id.clone(), template);
			} else {
				for parent in template.instance.from.iter() {
					// If the parent is already in the map (already consolidated) then we can derive from it and add to the map
					let parent_id = TemplateID::from(parent.clone());
					if let Some(parent) = out.get(&parent_id) {
						let mut new = parent.clone();
						new.merge(template.clone());
						out.insert(id.clone(), new);
					} else {
						// Check if the parent template actually doesn't exist or if we just haven't consolidated it yet
						if !templates.contains_key(&parent_id) {
							o.display(MessageContents::Error(format!(
								"Parent template '{parent}' does not exist"
							)));
						}
					}
				}
			}
		}

		i += 1;
		if i > max_iterations {
			panic!(
				"Max iterations exceeded while resolving templates. You likely have cyclic templates."
			);
		}
	}

	out
}

impl InstanceConfig {
	/// Applies the derived templates of this config
	pub fn apply_templates(
		&mut self,
		templates: &HashMap<TemplateID, TemplateConfig>,
	) -> anyhow::Result<Self> {
		let templates: anyhow::Result<Vec<_>> = self
			.from
			.iter()
			.map(|x| {
				templates
					.get(&TemplateID::from(x.clone()))
					.with_context(|| format!("Derived template '{x}' does not exist"))
			})
			.collect();
		let templates = templates?;

		// Merge with the template
		let mut config = self.clone();
		for template in &templates {
			let mut template_config = template.instance.clone();
			template_config.merge(config);
			config = template_config;
		}

		let side = config.side.context("Instance type was not specified")?;

		// Consolidate all of the package configs into the instance package config list
		let packages = consolidate_package_configs(&templates, &config, side);

		config.packages = packages.clone();

		// Loader
		let template_loaders = templates.iter().fold(
			TemplateLoaderConfiguration::default(),
			|mut acc, template| {
				acc.merge(&template.loader);
				acc
			},
		);

		let loader = match side {
			Side::Client => config.loader.clone().or(template_loaders.client().cloned()),
			Side::Server => config.loader.clone().or(template_loaders.server().cloned()),
		};

		config.loader = loader.clone();

		Ok(config)
	}
}

/// Combines all of the package configs from global, template, and instance together into
/// the configurations for just one instance
pub fn consolidate_package_configs(
	templates: &[&TemplateConfig],
	instance: &InstanceConfig,
	side: Side,
) -> Vec<PackageConfigDeser> {
	// We use a map so that we can override packages from more general sources
	// with those from more specific ones
	let mut map = HashMap::new();
	for template in templates {
		for pkg in template.packages.iter_global() {
			map.insert(
				PkgRequest::parse(pkg.get_pkg_id(), PkgRequestSource::UserRequire).id,
				pkg.clone(),
			);
		}
		for pkg in template.packages.iter_side(side) {
			map.insert(
				PkgRequest::parse(pkg.get_pkg_id(), PkgRequestSource::UserRequire).id,
				pkg.clone(),
			);
		}
	}
	for pkg in &instance.packages {
		map.insert(
			PkgRequest::parse(pkg.get_pkg_id(), PkgRequestSource::UserRequire).id,
			pkg.clone(),
		);
	}

	map.into_values().collect()
}

#[cfg(test)]
mod tests {
	use nitro_shared::{output::NoOp, util::DeserListOrSingle};

	use super::*;

	/// Make sure that consolidated templates are not removed
	#[test]
	fn test_consolidated_still_exists() {
		let mut templates = HashMap::new();
		templates.insert(TemplateID::from("foo"), TemplateConfig::default());
		templates.insert(
			TemplateID::from("bar"),
			TemplateConfig {
				instance: InstanceConfig {
					from: DeserListOrSingle::Single("foo".into()),
					..Default::default()
				},
				..Default::default()
			},
		);

		// Ensure determinism
		for _ in 0..30 {
			let consolidated = consolidate_template_configs(templates.clone(), None, &mut NoOp);
			assert!(consolidated.contains_key(&TemplateID::from("foo")));
			assert!(consolidated.contains_key(&TemplateID::from("bar")));
		}
	}
}