1use std::{
4 collections::BTreeMap,
5 fmt,
6 path::{Path, PathBuf},
7};
8
9use serde::{de::Error as _, Deserialize, Deserializer, Serialize, Serializer};
10
11use crate::{
12 events::{CoreEvent, EventBus},
13 java::JavaInstanceConfig,
14 loaders::LoaderConfig,
15 lock::LockManager,
16 minecraft::MinecraftConfig,
17 mods::ModConfig,
18 Error, Result,
19};
20
21const INSTANCE_FORMAT_VERSION: u32 = 1;
22
23#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
25pub struct InstanceId(String);
26
27impl InstanceId {
28 pub fn new(id: impl Into<String>) -> Result<Self> {
30 let id = id.into();
31 if id.is_empty() {
32 return Err(invalid_id(id, "identifier is empty"));
33 }
34 if id.len() > 64 {
35 return Err(invalid_id(id, "identifier exceeds 64 bytes"));
36 }
37 if !id
38 .bytes()
39 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
40 {
41 return Err(invalid_id(
42 id,
43 "only ASCII letters, digits, hyphens, and underscores are allowed",
44 ));
45 }
46 Ok(Self(id))
47 }
48
49 #[must_use]
50 pub fn as_str(&self) -> &str {
51 &self.0
52 }
53}
54
55fn invalid_id(id: String, reason: &'static str) -> Error {
56 Error::InvalidInstanceId { id, reason }
57}
58
59impl fmt::Display for InstanceId {
60 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
61 formatter.write_str(&self.0)
62 }
63}
64
65impl Serialize for InstanceId {
66 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
67 where
68 S: Serializer,
69 {
70 serializer.serialize_str(&self.0)
71 }
72}
73
74impl<'de> Deserialize<'de> for InstanceId {
75 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
76 where
77 D: Deserializer<'de>,
78 {
79 let id = String::deserialize(deserializer)?;
80 Self::new(id).map_err(D::Error::custom)
81 }
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86pub struct ServerConfig {
87 pub host: String,
88 pub port: u16,
89}
90
91#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
93#[serde(deny_unknown_fields)]
94pub struct InstanceAuthPolicy {
95 #[serde(default)]
96 pub required: bool,
97 #[serde(default)]
99 pub providers: Vec<String>,
100}
101
102impl InstanceAuthPolicy {
103 pub fn validate(&self) -> Result<()> {
104 if self.required && self.providers.is_empty() {
105 return Err(Error::InvalidConfig(
106 "required instance authentication must list at least one provider".into(),
107 ));
108 }
109 if self.providers.len() > 32 {
110 return Err(Error::InvalidConfig(
111 "instance authentication policy contains too many providers".into(),
112 ));
113 }
114 let mut unique = std::collections::BTreeSet::new();
115 for id in &self.providers {
116 if id.is_empty()
117 || id.len() > 64
118 || !id.as_bytes()[0].is_ascii_alphanumeric()
119 || !id.bytes().all(|byte| {
120 byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':')
121 })
122 || !unique.insert(id)
123 {
124 return Err(Error::InvalidConfig(
125 "instance authentication policy contains an invalid provider id".into(),
126 ));
127 }
128 }
129 Ok(())
130 }
131
132 #[must_use]
133 pub fn allows(&self, provider_id: &str) -> bool {
134 self.providers.is_empty() || self.providers.iter().any(|id| id == provider_id)
135 }
136}
137
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140pub struct InstanceSpec {
141 id: InstanceId,
142 name: String,
143 minecraft: MinecraftConfig,
144 #[serde(default)]
145 java: JavaInstanceConfig,
146 loader: Option<LoaderConfig>,
147 #[serde(default)]
148 mods: Vec<ModConfig>,
149 server: Option<ServerConfig>,
150 #[serde(default)]
151 authentication: InstanceAuthPolicy,
152 #[serde(default)]
153 metadata: BTreeMap<String, String>,
154}
155
156impl InstanceSpec {
157 pub fn vanilla(
159 id: impl Into<String>,
160 name: impl Into<String>,
161 minecraft_version: impl Into<String>,
162 ) -> Result<Self> {
163 let spec = Self {
164 id: InstanceId::new(id)?,
165 name: name.into(),
166 minecraft: MinecraftConfig::new(minecraft_version)?,
167 java: JavaInstanceConfig::default(),
168 loader: None,
169 mods: Vec::new(),
170 server: None,
171 authentication: InstanceAuthPolicy::default(),
172 metadata: BTreeMap::new(),
173 };
174 spec.validate()?;
175 Ok(spec)
176 }
177
178 pub fn with_java(mut self, java: JavaInstanceConfig) -> Result<Self> {
180 self.java = java;
181 self.validate()?;
182 Ok(self)
183 }
184
185 pub fn with_loader(mut self, loader: LoaderConfig) -> Result<Self> {
187 self.loader = Some(loader);
188 self.validate()?;
189 Ok(self)
190 }
191
192 #[must_use]
194 pub fn with_mods(mut self, mods: Vec<ModConfig>) -> Self {
195 self.mods = mods;
196 self
197 }
198
199 #[must_use]
201 pub fn with_server(mut self, server: ServerConfig) -> Self {
202 self.server = Some(server);
203 self
204 }
205
206 pub fn with_authentication(mut self, policy: InstanceAuthPolicy) -> Result<Self> {
207 policy.validate()?;
208 self.authentication = policy;
209 Ok(self)
210 }
211
212 pub fn insert_metadata(&mut self, key: impl Into<String>, value: impl Into<String>) {
214 self.metadata.insert(key.into(), value.into());
215 }
216
217 pub fn validate(&self) -> Result<()> {
219 if self.name.trim().is_empty() || self.name.len() > 128 {
220 return Err(Error::InvalidConfig(
221 "instance name must contain 1-128 characters".into(),
222 ));
223 }
224 self.minecraft.validate()?;
225 if self.java.minimum_memory_mib == 0
226 || self.java.maximum_memory_mib < self.java.minimum_memory_mib
227 {
228 return Err(Error::InvalidConfig(
229 "Java memory limits are inconsistent".into(),
230 ));
231 }
232 if let Some(loader) = &self.loader {
233 loader.validate()?;
234 }
235 self.authentication.validate()?;
236 Ok(())
237 }
238
239 #[must_use]
240 pub fn id(&self) -> &InstanceId {
241 &self.id
242 }
243
244 #[must_use]
245 pub fn name(&self) -> &str {
246 &self.name
247 }
248
249 #[must_use]
250 pub fn minecraft(&self) -> &MinecraftConfig {
251 &self.minecraft
252 }
253
254 #[must_use]
255 pub fn java(&self) -> &JavaInstanceConfig {
256 &self.java
257 }
258
259 #[must_use]
260 pub fn loader(&self) -> Option<&LoaderConfig> {
261 self.loader.as_ref()
262 }
263
264 #[must_use]
265 pub fn mods(&self) -> &[ModConfig] {
266 &self.mods
267 }
268
269 #[must_use]
270 pub fn server(&self) -> Option<&ServerConfig> {
271 self.server.as_ref()
272 }
273
274 #[must_use]
275 pub fn authentication(&self) -> &InstanceAuthPolicy {
276 &self.authentication
277 }
278
279 #[must_use]
280 pub fn metadata(&self) -> &BTreeMap<String, String> {
281 &self.metadata
282 }
283}
284
285#[derive(Debug, Clone, PartialEq, Eq)]
287pub struct Instance {
288 spec: InstanceSpec,
289 path: PathBuf,
290}
291
292impl Instance {
293 #[must_use]
294 pub fn id(&self) -> &InstanceId {
295 self.spec.id()
296 }
297
298 #[must_use]
299 pub fn name(&self) -> &str {
300 self.spec.name()
301 }
302
303 #[must_use]
304 pub fn spec(&self) -> &InstanceSpec {
305 &self.spec
306 }
307
308 #[must_use]
309 pub fn path(&self) -> &Path {
310 &self.path
311 }
312
313 #[must_use]
314 pub fn minecraft_dir(&self) -> PathBuf {
315 self.path.join(".minecraft")
316 }
317
318 pub(crate) fn with_spec(&self, spec: InstanceSpec) -> Result<Self> {
319 spec.validate()?;
320 if spec.id() != self.id() {
321 return Err(Error::InvalidConfig(
322 "transient instance specification changed the instance id".into(),
323 ));
324 }
325 Ok(Self {
326 spec,
327 path: self.path.clone(),
328 })
329 }
330}
331
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
334#[serde(rename_all = "snake_case")]
335#[non_exhaustive]
336pub enum InstanceStatus {
337 #[deprecated(note = "use NotInstalled, Installing, Updating, Installed, Broken, or Running")]
340 Available,
341 NotFound,
342 NotInstalled,
343 Installing,
344 Updating,
345 Recoverable,
346 Installed,
347 Broken,
348 Running,
349}
350
351#[derive(Debug, Serialize, Deserialize)]
352struct InstanceDocument {
353 format_version: u32,
354 instance: InstanceSpec,
355}
356
357#[derive(Debug, Clone, Serialize, Deserialize)]
358struct InstallStateDocument {
359 format_version: u32,
360 status: PersistedInstallStatus,
361 version_id: String,
362 #[serde(default)]
363 error: Option<String>,
364}
365
366#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
367#[serde(rename_all = "snake_case")]
368enum PersistedInstallStatus {
369 Installing,
370 Updating,
371 Interrupted,
372 Installed,
373 Broken,
374}
375
376#[derive(Debug, Clone)]
378pub struct InstanceService {
379 root: PathBuf,
380 events: EventBus,
381 locks: LockManager,
382}
383
384impl InstanceService {
385 pub(crate) fn new(root: PathBuf, events: EventBus, locks: LockManager) -> Self {
386 Self {
387 root,
388 events,
389 locks,
390 }
391 }
392
393 #[must_use]
394 pub fn root(&self) -> &Path {
395 &self.root
396 }
397
398 pub async fn create(&self, spec: InstanceSpec) -> Result<Instance> {
400 spec.validate()?;
401 let _lock = self
402 .locks
403 .acquire_exclusive(format!("instance:{}", spec.id()))
404 .await?;
405 tokio::fs::create_dir_all(&self.root).await?;
406 let target = self.root.join(spec.id().as_str());
407 match tokio::fs::symlink_metadata(&target).await {
408 Ok(_) => {
409 return Err(Error::AlreadyExists {
410 kind: "instance",
411 id: spec.id().to_string(),
412 });
413 }
414 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
415 Err(error) => return Err(error.into()),
416 }
417
418 let nonce = std::time::SystemTime::now()
419 .duration_since(std::time::UNIX_EPOCH)
420 .map_err(|_| Error::InvalidConfig("system clock precedes Unix epoch".into()))?
421 .as_nanos();
422 let staging = self.root.join(format!(".{}.{}.creating", spec.id(), nonce));
423 tokio::fs::create_dir(&staging).await?;
424
425 let result = self.write_new_instance(&staging, &spec).await;
426 if let Err(error) = result {
427 let _ = tokio::fs::remove_dir_all(&staging).await;
428 return Err(error);
429 }
430 if let Err(error) = tokio::fs::rename(&staging, &target).await {
431 let _ = tokio::fs::remove_dir_all(&staging).await;
432 return Err(error.into());
433 }
434
435 self.events.emit(CoreEvent::InstanceCreated {
436 instance_id: spec.id().to_string(),
437 });
438 Ok(Instance { spec, path: target })
439 }
440
441 async fn write_new_instance(&self, directory: &Path, spec: &InstanceSpec) -> Result<()> {
442 for child in [".minecraft", "mods", "config", "logs", "runtime"] {
443 tokio::fs::create_dir(directory.join(child)).await?;
444 }
445 let document = InstanceDocument {
446 format_version: INSTANCE_FORMAT_VERSION,
447 instance: spec.clone(),
448 };
449 let bytes = serde_json::to_vec_pretty(&document)?;
450 tokio::fs::write(directory.join("instance.json"), bytes).await?;
451 Ok(())
452 }
453
454 pub async fn get(&self, id: impl Into<String>) -> Result<Instance> {
456 let id = InstanceId::new(id)?;
457 let path = self.root.join(id.as_str());
458 let metadata = tokio::fs::symlink_metadata(&path).await.map_err(|error| {
459 if error.kind() == std::io::ErrorKind::NotFound {
460 Error::NotFound {
461 kind: "instance",
462 id: id.to_string(),
463 }
464 } else {
465 error.into()
466 }
467 })?;
468 if metadata.file_type().is_symlink() || !metadata.is_dir() {
469 return Err(Error::UnsafeFilesystemEntry {
470 path,
471 reason: "instance root must be a real directory",
472 });
473 }
474 let metadata_path = path.join("instance.json");
475 let file_metadata = tokio::fs::symlink_metadata(&metadata_path).await?;
476 if file_metadata.file_type().is_symlink() || !file_metadata.is_file() {
477 return Err(Error::UnsafeFilesystemEntry {
478 path: metadata_path,
479 reason: "instance metadata must be a real file",
480 });
481 }
482 let bytes = tokio::fs::read(&metadata_path).await?;
483 let document: InstanceDocument = serde_json::from_slice(&bytes)?;
484 if document.format_version != INSTANCE_FORMAT_VERSION {
485 return Err(Error::UnsupportedFormat {
486 kind: "instance",
487 version: document.format_version,
488 });
489 }
490 if document.instance.id() != &id {
491 return Err(Error::InvalidConfig(
492 "instance directory and document identifiers differ".into(),
493 ));
494 }
495 document.instance.validate()?;
496 Ok(Instance {
497 spec: document.instance,
498 path,
499 })
500 }
501
502 pub(crate) async fn replace_spec_unlocked(
505 &self,
506 instance: &Instance,
507 spec: InstanceSpec,
508 ) -> Result<Instance> {
509 spec.validate()?;
510 if spec.id() != instance.id() {
511 return Err(Error::InvalidConfig(
512 "replacement instance specification changed the instance id".into(),
513 ));
514 }
515 let document = InstanceDocument {
516 format_version: INSTANCE_FORMAT_VERSION,
517 instance: spec.clone(),
518 };
519 let destination = instance.path().join("instance.json");
520 let temporary = instance.path().join("instance.json.tmp");
521 tokio::fs::write(&temporary, serde_json::to_vec_pretty(&document)?).await?;
522 if tokio::fs::try_exists(&destination).await? {
523 tokio::fs::remove_file(&destination).await?;
524 }
525 tokio::fs::rename(temporary, destination).await?;
526 Ok(Instance {
527 spec,
528 path: instance.path().to_path_buf(),
529 })
530 }
531
532 pub async fn list(&self) -> Result<Vec<Instance>> {
534 tokio::fs::create_dir_all(&self.root).await?;
535 let mut reader = tokio::fs::read_dir(&self.root).await?;
536 let mut ids = Vec::new();
537 while let Some(entry) = reader.next_entry().await? {
538 let name = match entry.file_name().into_string() {
539 Ok(name) => name,
540 Err(_) => continue,
541 };
542 if let Ok(id) = InstanceId::new(name) {
543 ids.push(id);
544 }
545 }
546 ids.sort();
547 let mut instances = Vec::with_capacity(ids.len());
548 for id in ids {
549 instances.push(self.get(id.to_string()).await?);
550 }
551 Ok(instances)
552 }
553
554 pub async fn delete(&self, id: impl Into<String>) -> Result<()> {
556 let id = InstanceId::new(id)?;
557 let _lock = self
558 .locks
559 .try_acquire_exclusive(format!("instance:{id}"))
560 .await?;
561 let path = self.root.join(id.as_str());
562 let metadata = tokio::fs::symlink_metadata(&path).await.map_err(|error| {
563 if error.kind() == std::io::ErrorKind::NotFound {
564 Error::NotFound {
565 kind: "instance",
566 id: id.to_string(),
567 }
568 } else {
569 error.into()
570 }
571 })?;
572 if metadata.file_type().is_symlink() || !metadata.is_dir() {
573 return Err(Error::UnsafeFilesystemEntry {
574 path,
575 reason: "refusing to recursively delete a non-directory or symbolic link",
576 });
577 }
578 tokio::fs::remove_dir_all(&path).await?;
579 self.events.emit(CoreEvent::InstanceDeleted {
580 instance_id: id.to_string(),
581 });
582 Ok(())
583 }
584
585 pub async fn status(&self, id: impl Into<String>) -> Result<InstanceStatus> {
587 let id = InstanceId::new(id)?;
588 let instance_root = self.root.join(id.as_str());
589 match tokio::fs::symlink_metadata(&instance_root).await {
590 Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {}
591 Ok(_) => Err(Error::UnsafeFilesystemEntry {
592 path: instance_root.clone(),
593 reason: "instance root must be a real directory",
594 })?,
595 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
596 return Ok(InstanceStatus::NotFound);
597 }
598 Err(error) => return Err(error.into()),
599 }
600 let state_path = instance_root.join("runtime").join("install-state.json");
601 let metadata = match tokio::fs::symlink_metadata(&state_path).await {
602 Ok(metadata) => metadata,
603 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
604 return Ok(InstanceStatus::NotInstalled);
605 }
606 Err(error) => return Err(error.into()),
607 };
608 if metadata.file_type().is_symlink() || !metadata.is_file() {
609 return Err(Error::UnsafeFilesystemEntry {
610 path: state_path,
611 reason: "installation state must be a real file",
612 });
613 }
614 let state: InstallStateDocument =
615 serde_json::from_slice(&tokio::fs::read(&state_path).await?)?;
616 if state.format_version != 1 {
617 return Err(Error::UnsupportedFormat {
618 kind: "installation state",
619 version: state.format_version,
620 });
621 }
622 Ok(match state.status {
623 PersistedInstallStatus::Installing => InstanceStatus::Installing,
624 PersistedInstallStatus::Updating => InstanceStatus::Updating,
625 PersistedInstallStatus::Interrupted => InstanceStatus::Recoverable,
626 PersistedInstallStatus::Installed => InstanceStatus::Installed,
627 PersistedInstallStatus::Broken => InstanceStatus::Broken,
628 })
629 }
630
631 pub(crate) async fn mark_installing(&self, instance: &Instance) -> Result<()> {
632 self.write_install_state(
633 instance,
634 PersistedInstallStatus::Installing,
635 instance.spec().minecraft().version(),
636 None,
637 )
638 .await
639 }
640
641 pub(crate) async fn mark_installed(&self, instance: &Instance) -> Result<()> {
642 self.write_install_state(
643 instance,
644 PersistedInstallStatus::Installed,
645 instance.spec().minecraft().version(),
646 None,
647 )
648 .await
649 }
650
651 pub(crate) async fn mark_updating(&self, instance: &Instance) -> Result<()> {
652 self.write_install_state(
653 instance,
654 PersistedInstallStatus::Updating,
655 instance.spec().minecraft().version(),
656 None,
657 )
658 .await
659 }
660
661 pub(crate) async fn mark_broken(&self, instance: &Instance, error: &str) -> Result<()> {
662 self.write_install_state(
663 instance,
664 PersistedInstallStatus::Broken,
665 instance.spec().minecraft().version(),
666 Some(error),
667 )
668 .await
669 }
670
671 pub(crate) async fn mark_interrupted(&self, instance: &Instance, error: &str) -> Result<()> {
672 self.write_install_state(
673 instance,
674 PersistedInstallStatus::Interrupted,
675 instance.spec().minecraft().version(),
676 Some(error),
677 )
678 .await
679 }
680
681 pub(crate) async fn installed_version(&self, instance: &Instance) -> Result<Option<String>> {
682 if self.status(instance.id().to_string()).await? != InstanceStatus::Installed {
683 return Ok(None);
684 }
685 let state_path = instance.path().join("runtime").join("install-state.json");
686 let state: InstallStateDocument =
687 serde_json::from_slice(&tokio::fs::read(state_path).await?)?;
688 Ok(Some(state.version_id))
689 }
690
691 async fn write_install_state(
692 &self,
693 instance: &Instance,
694 status: PersistedInstallStatus,
695 version_id: &str,
696 error: Option<&str>,
697 ) -> Result<()> {
698 let runtime = instance.path().join("runtime");
699 match tokio::fs::symlink_metadata(&runtime).await {
700 Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {}
701 Ok(_) => {
702 return Err(Error::UnsafeFilesystemEntry {
703 path: runtime,
704 reason: "instance runtime must be a real directory",
705 });
706 }
707 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
708 tokio::fs::create_dir(&runtime).await?;
709 }
710 Err(error) => return Err(error.into()),
711 }
712 let state_path = runtime.join("install-state.json");
713 let temporary = runtime.join("install-state.json.tmp");
714 let document = InstallStateDocument {
715 format_version: 1,
716 status,
717 version_id: version_id.to_owned(),
718 error: error.map(str::to_owned),
719 };
720 if tokio::fs::try_exists(&temporary).await? {
721 let metadata = tokio::fs::symlink_metadata(&temporary).await?;
722 if metadata.file_type().is_symlink() || !metadata.is_file() {
723 return Err(Error::UnsafeFilesystemEntry {
724 path: temporary,
725 reason: "temporary installation state must be a real file",
726 });
727 }
728 }
729 tokio::fs::write(&temporary, serde_json::to_vec_pretty(&document)?).await?;
730 if tokio::fs::try_exists(&state_path).await? {
731 let metadata = tokio::fs::symlink_metadata(&state_path).await?;
732 if metadata.file_type().is_symlink() || !metadata.is_file() {
733 return Err(Error::UnsafeFilesystemEntry {
734 path: state_path,
735 reason: "installation state must be a real file",
736 });
737 }
738 tokio::fs::remove_file(&state_path).await?;
739 }
740 tokio::fs::rename(temporary, state_path).await?;
741 Ok(())
742 }
743}
744
745#[cfg(test)]
746mod tests {
747 use super::*;
748
749 #[test]
750 fn validates_instance_ids() {
751 assert!(InstanceId::new("survival-01").is_ok());
752 for invalid in ["", "../escape", "with space", "slash/name"] {
753 assert!(InstanceId::new(invalid).is_err());
754 }
755 }
756
757 #[tokio::test]
758 async fn creates_loads_lists_and_deletes_an_instance() {
759 let temporary = tempfile::tempdir().expect("tempdir");
760 let events = EventBus::new(8);
761 let service = InstanceService::new(
762 temporary.path().join("instances"),
763 events,
764 LockManager::new(temporary.path().join("locks")),
765 );
766 let spec = InstanceSpec::vanilla("test", "Test", "1.21.1").expect("spec");
767
768 let created = service.create(spec).await.expect("create");
769 assert!(created.minecraft_dir().is_dir());
770 assert_eq!(service.get("test").await.expect("get").name(), "Test");
771 assert_eq!(service.list().await.expect("list").len(), 1);
772
773 service.delete("test").await.expect("delete");
774 assert_eq!(
775 service.status("test").await.expect("status"),
776 InstanceStatus::NotFound
777 );
778 }
779}