mcvm 0.25.0

A fast, extensible, and powerful Minecraft launcher
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
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::sync::Arc;

use itertools::Itertools;
use mcvm_core::net::download::get_transfer_limit;
use mcvm_pkg::properties::PackageProperties;
use mcvm_pkg::repo::PackageFlag;
use mcvm_pkg::PkgRequest;
use mcvm_shared::output::{MCVMOutput, MessageContents, MessageLevel};
use mcvm_shared::pkg::{ArcPkgReq, PackageID};
use mcvm_shared::translate;
use mcvm_shared::versions::VersionInfo;
use tokio::sync::Semaphore;
use tokio::task::JoinSet;

use crate::instance::Instance;
use crate::pkg::eval::{resolve, EvalConstants, EvalInput, EvalParameters};
use crate::util::select_random_n_items_from_list;
use mcvm_shared::id::InstanceID;

use super::InstanceUpdateContext;

use anyhow::Context;

/// Install packages on multiple instances. Returns a set of all unique packages
pub async fn update_instance_packages<'a, O: MCVMOutput>(
	instances: &mut [&mut Instance],
	constants: &EvalConstants,
	ctx: &mut InstanceUpdateContext<'a, O>,
	force: bool,
) -> anyhow::Result<HashSet<ArcPkgReq>> {
	// Resolve dependencies
	ctx.output.start_process();
	ctx.output.display(
		MessageContents::StartProcess(translate!(ctx.output, StartResolvingDependencies)),
		MessageLevel::Important,
	);
	let resolved_packages = resolve_and_batch(instances, constants, ctx)
		.await
		.context("Failed to resolve dependencies for profile")?;
	ctx.output.display(
		MessageContents::Success(translate!(ctx.output, FinishResolvingDependencies)),
		MessageLevel::Important,
	);
	ctx.output.end_process();

	// Evaluate first to install all of the addons
	ctx.output.display(
		MessageContents::StartProcess(translate!(ctx.output, StartAcquiringAddons)),
		MessageLevel::Important,
	);
	let mut tasks = HashMap::new();
	let mut evals = HashMap::new();
	for (package, package_instances) in resolved_packages
		.package_to_instances
		.iter()
		.sorted_by_key(|x| x.0)
	{
		// Check the package to display warnings
		check_package(ctx, package)
			.await
			.with_context(|| format!("Failed to check package {package}"))?;

		// Install the package on it's instances
		let mut notices = Vec::new();
		for instance_id in package_instances {
			let instance = instances
				.iter_mut()
				.find(|x| &x.id == instance_id)
				.expect("Instance should exist");

			let mut params = EvalParameters::new(instance.kind.to_side());
			params.stability = instance.config.package_stability;
			if let Some(config) = instance.get_package_config(&package.to_string()) {
				params
					.apply_config(config, &PackageProperties::default())
					.context("Failed to apply config")?;
			}

			let input = EvalInput { constants, params };
			let (eval, new_tasks) = instance
				.get_package_addon_tasks(
					package,
					input,
					ctx.packages,
					ctx.paths,
					force,
					ctx.client,
					ctx.plugins,
					ctx.output,
				)
				.await
				.with_context(|| {
					format!("Failed to get addon install tasks for package '{package}' on instance")
				})?;
			tasks.extend(new_tasks);

			// Add any notices to the list
			notices.extend(
				eval.notices
					.iter()
					.map(|x| (instance_id.clone(), x.to_owned())),
			);

			// Add the eval to the map
			evals.insert((package, instance_id), eval);
		}

		// Display any accumulated notices from the installation
		for (instance, notice) in notices {
			ctx.output.display(
				format_package_update_message(
					package,
					Some(&instance),
					MessageContents::Notice(notice),
				),
				MessageLevel::Important,
			);
		}
	}

	// Run the acquire tasks
	run_addon_tasks(tasks, ctx.output)
		.await
		.context("Failed to acquire addons")?;

	ctx.output.display(
		MessageContents::Success(translate!(ctx.output, FinishAcquiringAddons)),
		MessageLevel::Important,
	);

	// Install each package one after another onto all of its instances
	ctx.output.display(
		MessageContents::StartProcess(translate!(ctx.output, StartInstallingPackages)),
		MessageLevel::Important,
	);
	for (package, package_instances) in resolved_packages
		.package_to_instances
		.iter()
		.sorted_by_key(|x| x.0)
	{
		ctx.output.start_process();

		for instance_id in package_instances {
			let instance = instances
				.iter_mut()
				.find(|x| &x.id == instance_id)
				.expect("Instance should exist");

			let version_info = VersionInfo {
				version: constants.version.clone(),
				versions: constants.version_list.clone(),
			};
			let eval = evals
				.get(&(package, instance_id))
				.expect("Evaluation should be in map");
			instance
				.install_eval_data(
					package,
					eval,
					&version_info,
					ctx.paths,
					ctx.lock,
					ctx.output,
				)
				.await
				.context("Failed to install package on instance")?;
		}

		ctx.output.display(
			format_package_update_message(
				package,
				None,
				MessageContents::Success(translate!(ctx.output, FinishInstallingPackage)),
			),
			MessageLevel::Important,
		);
		ctx.output.end_process();
	}

	// Use the instance-package map to remove unused packages and addons
	for (instance_id, packages) in resolved_packages.instance_to_packages {
		let instance = instances
			.iter()
			.find(|x| x.id == instance_id)
			.expect("Instance should exist");

		let files_to_remove = ctx
			.lock
			.remove_unused_packages(
				&instance_id,
				&packages
					.iter()
					.map(|x| x.id.clone())
					.collect::<Vec<PackageID>>(),
			)
			.context("Failed to remove unused packages")?;
		for file in files_to_remove {
			instance
				.remove_addon_file(&file, ctx.paths)
				.with_context(|| {
					format!(
						"Failed to remove addon file {} for instance {}",
						file.display(),
						instance_id
					)
				})?;
		}
	}

	// Get the set of unique packages
	let mut out = HashSet::new();
	out.extend(resolved_packages.package_to_instances.keys().cloned());

	Ok(out)
}

/// Evaluates addon acquire tasks efficiently with a progress display to the user
async fn run_addon_tasks(
	tasks: HashMap<String, impl Future<Output = anyhow::Result<()>> + Send + 'static>,
	o: &mut impl MCVMOutput,
) -> anyhow::Result<()> {
	let total_count = tasks.len();
	let mut task_set = JoinSet::new();

	let sem = Arc::new(Semaphore::new(get_transfer_limit()));
	for task in tasks.into_values() {
		let permit = sem.clone().acquire_owned().await;
		let task = async move {
			let _permit = permit?;

			task.await
		};
		task_set.spawn(task);
	}

	o.start_process();
	while let Some(result) = task_set.join_next().await {
		result
			.context("Failed to run addon acquire task")?
			.context("Failed to acquire addon")?;

		// Update progress bar
		let progress = MessageContents::Progress {
			current: (total_count - task_set.len()) as u32,
			total: total_count as u32,
		};

		o.display(progress, MessageLevel::Important);
	}

	o.end_process();

	Ok(())
}

/// Resolve packages and create a mapping of packages to a list of instances.
/// This allows us to update packages in a reasonable order to the user.
/// It also returns a map of instances to packages so that unused packages can be removed
async fn resolve_and_batch<'a, O: MCVMOutput>(
	instances: &[&mut Instance],
	constants: &EvalConstants,
	ctx: &mut InstanceUpdateContext<'a, O>,
) -> anyhow::Result<ResolvedPackages> {
	let mut batched: HashMap<ArcPkgReq, Vec<InstanceID>> = HashMap::new();
	let mut resolved = HashMap::new();

	for instance in instances {
		let mut params = EvalParameters::new(instance.kind.to_side());
		params.stability = instance.config.package_stability;

		let instance_pkgs = instance.get_configured_packages();
		let instance_resolved = resolve(
			instance_pkgs,
			constants,
			params,
			ctx.paths,
			ctx.packages,
			ctx.client,
			ctx.plugins,
			ctx.output,
		)
		.await
		.with_context(|| {
			format!(
				"Failed to resolve package dependencies for instance '{}'",
				instance.id
			)
		})?;
		for package in &instance_resolved.packages {
			if let Some(entry) = batched.get_mut(package) {
				entry.push(instance.id.clone());
			} else {
				batched.insert(package.clone(), vec![instance.id.clone()]);
			}
		}
		resolved.insert(instance.id.clone(), instance_resolved.packages);
	}

	Ok(ResolvedPackages {
		package_to_instances: batched,
		instance_to_packages: resolved,
	})
}

struct ResolvedPackages {
	/// A mapping of package IDs to all of the instances they are installed on
	pub package_to_instances: HashMap<ArcPkgReq, Vec<InstanceID>>,
	/// A reverse mapping of instance IDs to all of the packages they have resolved
	pub instance_to_packages: HashMap<InstanceID, Vec<ArcPkgReq>>,
}

/// Checks a package with the registry to report any warnings about it
async fn check_package<'a, O: MCVMOutput>(
	ctx: &mut InstanceUpdateContext<'a, O>,
	pkg: &ArcPkgReq,
) -> anyhow::Result<()> {
	let flags = ctx
		.packages
		.flags(pkg, ctx.paths, ctx.client, ctx.output)
		.await
		.context("Failed to get flags for package")?;
	if flags.contains(&PackageFlag::OutOfDate) {
		ctx.output.display(
			MessageContents::Warning(translate!(ctx.output, PackageOutOfDate, "pkg" = &pkg.id)),
			MessageLevel::Important,
		);
	}

	if flags.contains(&PackageFlag::Deprecated) {
		ctx.output.display(
			MessageContents::Warning(translate!(ctx.output, PackageDeprecated, "pkg" = &pkg.id)),
			MessageLevel::Important,
		);
	}

	if flags.contains(&PackageFlag::Insecure) {
		ctx.output.display(
			MessageContents::Error(translate!(ctx.output, PackageInsecure, "pkg" = &pkg.id)),
			MessageLevel::Important,
		);
	}

	if flags.contains(&PackageFlag::Malicious) {
		ctx.output.display(
			MessageContents::Error(translate!(ctx.output, PackageMalicious, "pkg" = &pkg.id)),
			MessageLevel::Important,
		);
	}

	Ok(())
}

/// Prints support messages about installed packages when updating
pub async fn print_package_support_messages<'a, O: MCVMOutput>(
	packages: &[ArcPkgReq],
	ctx: &mut InstanceUpdateContext<'a, O>,
) -> anyhow::Result<()> {
	let package_count = 5;
	let packages = select_random_n_items_from_list(packages, package_count);
	let mut links = Vec::new();
	for package in packages {
		if let Some(link) = ctx
			.packages
			.get_metadata(package, ctx.paths, ctx.client, ctx.output)
			.await?
			.support_link
			.clone()
		{
			links.push((package, link))
		}
	}
	if !links.is_empty() {
		ctx.output.display(
			MessageContents::Header(translate!(ctx.output, PackageSupportHeader)),
			MessageLevel::Important,
		);
		for (req, link) in links {
			let msg = format_package_update_message(req, None, MessageContents::Hyperlink(link));
			ctx.output.display(msg, MessageLevel::Important);
		}
	}

	Ok(())
}

/// Creates the output message for package installation when updating profiles
fn format_package_update_message(
	pkg: &PkgRequest,
	instance: Option<&str>,
	message: MessageContents,
) -> MessageContents {
	let msg = if let Some(instance) = instance {
		MessageContents::Package(
			pkg.to_owned(),
			Box::new(MessageContents::Associated(
				Box::new(MessageContents::Simple(instance.to_string())),
				Box::new(message),
			)),
		)
	} else {
		MessageContents::Package(pkg.to_owned(), Box::new(message))
	};

	MessageContents::ListItem(Box::new(msg))
}