1use std::cell::RefCell;
9use std::collections::{BTreeMap, BTreeSet};
10use std::rc::Rc;
11
12use semver::Version;
13use serde::{Deserialize, Deserializer, Serialize};
14use serde_bytes::ByteBuf;
15
16use super::{
17 Answer, Answers, Bounds, BoundsLimit, Dependency, Diagnostic, Engine, EngineFailure,
18 FailedFetch, Failure, Identity, Level, LockedDependency, Mode, Need, Outcome, PathRequest,
19 PathSource, PluginDetail, Request, Spec, SubpathDetail, Tag, locked_dependency,
20};
21use crate::dependency::Dependencies;
22use crate::diagnostic::SchemaDiagnostic;
23use crate::names::SourceSubpath;
24use crate::tree::{FileTree, TreeSource};
25use crate::version::Constraint;
26
27const ROOT_CORE: &str = "mars.toml";
29const ROOT: &str = "root";
30
31#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
33#[error("{0}")]
34pub struct InputError(String);
35
36impl InputError {
37 pub fn code(&self) -> &'static str {
38 "input.invalid"
39 }
40}
41
42#[derive(Debug, Deserialize)]
43#[serde(deny_unknown_fields)]
44pub struct Input {
45 root: RootInput,
46 #[serde(default)]
49 supplied: BTreeMap<String, SuppliedInput>,
50 #[serde(default)]
51 locked: BTreeMap<String, LockedDependency>,
52 #[serde(default)]
53 refresh: Refresh,
54 engine: EngineInput,
55 #[serde(default)]
56 bounds: BoundsInput,
57 answers: Vec<AnswerInput>,
58}
59
60#[derive(Debug, Deserialize)]
61#[serde(deny_unknown_fields)]
62struct RootInput {
63 manifest: String,
64}
65
66#[derive(Debug, Deserialize)]
67#[serde(deny_unknown_fields)]
68struct SuppliedInput {
69 #[allow(dead_code)]
70 manifest: String,
71}
72
73#[derive(Debug, Default, Deserialize)]
74#[serde(untagged)]
75enum Refresh {
76 #[default]
77 None,
78 All(RefreshAll),
79 Names(Vec<String>),
80}
81
82#[derive(Debug, Deserialize)]
83enum RefreshAll {
84 #[serde(rename = "all")]
85 All,
86}
87
88#[derive(Debug, Deserialize)]
89#[serde(deny_unknown_fields)]
90struct EngineInput {
91 mars: String,
92 #[serde(default)]
93 meridian: Option<String>,
94}
95
96#[derive(Debug, Default, Deserialize)]
97#[serde(deny_unknown_fields)]
98struct BoundsInput {
99 #[serde(default)]
100 packages: Option<usize>,
101 #[serde(default)]
102 bytes: Option<u64>,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(tag = "kind", rename_all = "lowercase")]
108pub enum NeedWire {
109 Tags {
110 url: String,
111 },
112 Ref {
113 url: String,
114 #[serde(rename = "ref")]
115 name: String,
116 },
117 Tree {
118 url: String,
119 commit: String,
120 path: Option<String>,
121 },
122}
123
124impl From<Need> for NeedWire {
125 fn from(need: Need) -> Self {
126 match need {
127 Need::Tags { url } => Self::Tags { url },
128 Need::Ref { url, name } => Self::Ref { url, name },
129 Need::Tree { url, commit, path } => Self::Tree { url, commit, path },
130 }
131 }
132}
133
134#[derive(Debug, Deserialize)]
135struct TagInput {
136 tag: String,
137 commit: String,
138}
139
140#[derive(Debug, Deserialize)]
143struct AnswerInput {
144 need: Option<NeedWire>,
145 tags: Option<Vec<TagInput>>,
146 commit: Option<String>,
147 url: Option<String>,
148 #[serde(default, deserialize_with = "present")]
149 path: Option<Option<String>>,
150 files: Option<BTreeMap<String, ByteBuf>>,
151 missing: Option<bool>,
152 failed: Option<String>,
153}
154
155fn present<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Option<String>>, D::Error> {
157 Option::<String>::deserialize(deserializer).map(Some)
158}
159
160#[derive(Debug, Serialize)]
162#[serde(untagged)]
163pub enum Output {
164 Needs {
165 needs: Vec<NeedWire>,
166 },
167 Resolved {
168 resolved: ResolvedOutput,
169 diagnostics: Vec<DiagnosticOutput>,
170 },
171 Failed {
172 failed: FailureOutput,
173 diagnostics: Vec<DiagnosticOutput>,
174 },
175}
176
177#[derive(Debug, Serialize)]
178pub struct ResolvedOutput {
179 lock: BTreeMap<String, LockedDependency>,
180 dependencies: BTreeMap<String, DependencyOutput>,
181}
182
183#[derive(Debug, Serialize)]
184struct DependencyOutput {
185 url: String,
186 commit: String,
187 subpath: Option<SourceSubpath>,
188 version: Option<String>,
189 #[serde(skip_serializing_if = "Option::is_none")]
190 content: Option<ContentOutput>,
191 required_by: Vec<RequesterOutput>,
192}
193
194#[derive(Debug, Serialize)]
196struct ContentOutput {
197 url: String,
198 subpath: Option<SourceSubpath>,
199 commit: String,
200}
201
202#[derive(Debug, Serialize)]
203struct RequesterOutput {
204 by: String,
205 constraint: Option<String>,
206}
207
208#[derive(Debug, Serialize)]
209pub struct DiagnosticOutput {
210 level: &'static str,
211 code: String,
212 message: String,
213}
214
215#[derive(Debug, Serialize)]
216pub struct FailureOutput {
217 #[serde(flatten)]
218 body: FailureBody,
219 message: String,
220}
221
222#[derive(Debug, Serialize)]
223struct ExcludedOutput {
224 version: String,
225 requirement: String,
226 engine: &'static str,
227}
228
229#[derive(Debug, Serialize)]
230struct StepOutput {
231 version: Option<String>,
232 commit: Option<String>,
233}
234
235#[derive(Debug, Serialize)]
236#[serde(tag = "kind", rename_all = "kebab-case")]
237enum FailureBody {
238 Conflict {
239 name: String,
240 requesters: Vec<RequesterOutput>,
241 },
242 Identity {
243 detail: &'static str,
244 names: Vec<String>,
245 source: String,
246 #[serde(skip_serializing_if = "Option::is_none")]
248 existing: Option<String>,
249 },
250 EngineIncompatible {
251 name: String,
252 requirement: Option<String>,
253 engine: Option<&'static str>,
254 },
255 EngineUnsatisfiable {
256 name: String,
257 excluded: Vec<ExcludedOutput>,
258 },
259 EngineRequirementInvalid {
260 name: String,
261 requirement: String,
262 engine: String,
263 },
264 EngineVersionInvalid {
265 engine: String,
266 version: String,
267 },
268 Plugin {
269 name: String,
270 detail: &'static str,
271 #[serde(skip_serializing_if = "Option::is_none")]
272 plugin: Option<String>,
273 },
274 Subpath {
275 name: String,
276 subpath: String,
277 detail: &'static str,
278 },
279 Unreadable {
280 name: String,
281 diagnostics: Vec<SchemaDiagnostic>,
282 },
283 Path {
284 name: String,
285 declared_in: String,
286 },
287 Unavailable {
288 need: NeedWire,
289 reason: String,
290 },
291 Bounds {
292 limit: &'static str,
293 at: String,
294 },
295 Oscillation {
296 name: String,
297 steps: Vec<StepOutput>,
298 },
299 Frozen,
301}
302
303enum Reply<T> {
305 Found(T),
306 Missing,
307 Failed(String),
308}
309
310type TreeKey = (String, String, Option<String>);
312
313type View = Result<Rc<FileTree>, SubpathDetail>;
315
316struct MapAnswers {
320 tags: BTreeMap<String, Reply<Vec<Tag>>>,
321 refs: BTreeMap<(String, String), Reply<String>>,
322 trees: BTreeMap<TreeKey, Reply<Rc<FileTree>>>,
323 views: RefCell<BTreeMap<(TreeKey, String), View>>,
325}
326
327fn invalid(message: impl Into<String>) -> InputError {
328 InputError(message.into())
329}
330
331impl MapAnswers {
332 fn new(answers: Vec<AnswerInput>) -> Result<Self, InputError> {
333 let mut map = Self {
334 tags: BTreeMap::new(),
335 refs: BTreeMap::new(),
336 trees: BTreeMap::new(),
337 views: RefCell::default(),
338 };
339 for (index, answer) in answers.into_iter().enumerate() {
340 map.add(answer)
341 .map_err(|error| invalid(format!("answers[{index}]: {error}")))?;
342 }
343 Ok(map)
344 }
345
346 fn add(&mut self, answer: AnswerInput) -> Result<(), InputError> {
347 if let Some(files) = answer.files {
348 if answer.need.is_some()
349 || answer.tags.is_some()
350 || answer.missing.is_some()
351 || answer.failed.is_some()
352 {
353 return Err(invalid(
354 "a tree answer carries only url, commit, path and files",
355 ));
356 }
357 let (Some(url), Some(commit), Some(path)) = (answer.url, answer.commit, answer.path)
358 else {
359 return Err(invalid("a tree answer needs url, commit and path"));
360 };
361 let tree = FileTree::from_files(
362 files
363 .into_iter()
364 .map(|(path, bytes)| (path, bytes.into_vec())),
365 )
366 .map_err(|error| invalid(error.to_string()))?;
367 self.trees
368 .insert((url, commit, path), Reply::Found(Rc::new(tree)));
369 return Ok(());
370 }
371 let Some(need) = answer.need else {
372 return Err(invalid(
373 "an answer names its `need`, or carries a tree's `files`",
374 ));
375 };
376 let missing = answer.missing == Some(true);
377 let given = [
378 answer.tags.is_some(),
379 answer.commit.is_some(),
380 missing,
381 answer.failed.is_some(),
382 ]
383 .into_iter()
384 .filter(|given| *given)
385 .count();
386 if given != 1 || answer.missing == Some(false) {
387 return Err(invalid(
388 "an answer carries exactly one of `tags`, `commit`, `missing: true` or `failed`",
389 ));
390 }
391 match need {
392 NeedWire::Tags { url } => {
393 let reply = match (answer.tags, answer.failed) {
394 (Some(tags), _) => Reply::Found(
395 tags.into_iter()
396 .map(|tag| Tag {
397 tag: tag.tag,
398 commit: tag.commit,
399 })
400 .collect(),
401 ),
402 (None, Some(reason)) => Reply::Failed(reason),
403 _ if missing => Reply::Missing,
404 _ => return Err(invalid("a tags need is answered with `tags`")),
405 };
406 self.tags.insert(url, reply);
407 }
408 NeedWire::Ref { url, name } => {
409 let reply = match (answer.commit, answer.failed) {
410 (Some(commit), _) => Reply::Found(commit),
411 (None, Some(reason)) => Reply::Failed(reason),
412 _ if missing => Reply::Missing,
413 _ => return Err(invalid("a ref need is answered with a `commit`")),
414 };
415 self.refs.insert((url, name), reply);
416 }
417 NeedWire::Tree { url, commit, path } => {
418 let reply = match answer.failed {
419 Some(reason) => Reply::Failed(reason),
420 None if missing => Reply::Missing,
421 None => {
422 return Err(invalid(
423 "a tree need is answered with `files`, `missing` or `failed`",
424 ));
425 }
426 };
427 self.trees.insert((url, commit, path), reply);
428 }
429 }
430 Ok(())
431 }
432
433 fn covering(
437 &self,
438 url: &str,
439 commit: &str,
440 path: Option<&str>,
441 ) -> Option<(&TreeKey, &Reply<Rc<FileTree>>)> {
442 let mut at = path.map(str::to_string);
443 loop {
444 let key = (url.to_string(), commit.to_string(), at.clone());
445 if let Some(found) = self.trees.get_key_value(&key) {
446 return Some(found);
447 }
448 at = at?.rsplit_once('/').map(|(parent, _)| parent.to_string());
449 }
450 }
451
452 fn view(&self, key: &TreeKey, tree: &FileTree, path: &str) -> View {
454 let cached = (key.clone(), path.to_string());
455 if let Some(view) = self.views.borrow().get(&cached) {
456 return view.clone();
457 }
458 let prefix = format!("{path}/");
459 let view = if tree.is_file(path) {
460 Err(SubpathDetail::NotADirectory)
461 } else if !tree.is_dir(path) {
462 Err(SubpathDetail::Missing)
463 } else {
464 let files = tree.files().iter().filter_map(|(file, bytes)| {
465 file.strip_prefix(&prefix)
466 .map(|relative| (relative.to_string(), bytes.clone()))
467 });
468 Ok(Rc::new(
469 FileTree::from_files(files).expect("paths of a tree stay valid below a folder"),
470 ))
471 };
472 self.views.borrow_mut().insert(cached, view.clone());
473 view
474 }
475}
476
477impl<T: Clone> Reply<T> {
478 fn answer(&self) -> Answer<T> {
479 match self {
480 Self::Found(value) => Answer::Found(value.clone()),
481 Self::Missing => Answer::Missing,
482 Self::Failed(reason) => Answer::Failed(FailedFetch::Fetch(reason.clone())),
483 }
484 }
485}
486
487impl Answers for MapAnswers {
488 fn tags(&self, url: &str) -> Option<Answer<Vec<Tag>>> {
489 self.tags.get(url).map(Reply::answer)
490 }
491
492 fn reference(&self, url: &str, name: &str) -> Option<Answer<String>> {
493 self.refs
494 .get(&(url.to_string(), name.to_string()))
495 .map(Reply::answer)
496 }
497
498 fn tree(
499 &self,
500 url: &str,
501 commit: &str,
502 path: Option<&str>,
503 ) -> Option<Answer<Rc<dyn TreeSource>>> {
504 let (key, reply) = self.covering(url, commit, path)?;
505 Some(match (reply, path) {
506 (Reply::Found(tree), None) => Answer::Found(Rc::clone(tree) as Rc<dyn TreeSource>),
507 (Reply::Found(tree), Some(path)) => match self.view(key, tree, path) {
508 Ok(view) => Answer::Found(view as Rc<dyn TreeSource>),
509 Err(detail) => Answer::Failed(FailedFetch::Subpath(detail)),
510 },
511 (Reply::Missing, _) => Answer::Missing,
512 (Reply::Failed(reason), _) => Answer::Failed(FailedFetch::Fetch(reason.clone())),
513 })
514 }
515
516 fn path(&self, _request: &PathRequest<'_>) -> Answer<PathSource> {
518 Answer::Failed(FailedFetch::Fetch("path refused".to_string()))
519 }
520}
521
522fn root_dependencies(manifest: &str) -> Result<Vec<Dependency>, InputError> {
523 let document = manifest
524 .parse::<toml_edit::DocumentMut>()
525 .map_err(|error| invalid(format!("root.manifest is not TOML: {error}")))?;
526 let mut diagnostics = Vec::new();
527 let dependencies = Dependencies::read(&document, &mut diagnostics);
528 if let Some(error) = diagnostics.iter().find(|diagnostic| diagnostic.is_error()) {
529 return Err(invalid(format!("root.manifest: {}", error.message)));
530 }
531 Ok(dependencies
532 .dependencies
533 .into_iter()
534 .map(|(name, entry)| {
535 let spec = Spec::of(&entry);
536 Dependency {
537 name,
538 constraint: spec.constraint(),
539 declared: spec.clone(),
540 spec,
541 subpath: entry.subpath,
542 plugin: entry.plugin,
543 required_by: ROOT_CORE.to_string(),
544 declared_in: None,
545 dialect: entry.dialect,
546 namespace: None,
547 }
548 })
549 .collect())
550}
551
552pub fn run(input: Input) -> Result<Output, InputError> {
554 if !input.supplied.is_empty() {
555 return Err(invalid(
556 "`supplied` is not supported yet: resolve prepares every package from its fetched tree",
557 ));
558 }
559 let root = root_dependencies(&input.root.manifest)?;
560 let answers = MapAnswers::new(input.answers)?;
561 let mars = match Version::parse(&input.engine.mars) {
562 Ok(mars) => mars,
563 Err(error) => {
564 let failure = Failure::EngineVersionInvalid {
565 engine: "mars".to_string(),
566 version: input.engine.mars,
567 message: error.to_string(),
568 };
569 return Ok(failed(failure, &[]));
570 }
571 };
572 let request = Request {
573 root,
574 supplied: BTreeMap::new(),
575 overrides: BTreeMap::new(),
576 locked: input.locked,
577 mode: match input.refresh {
578 Refresh::None => Mode::Sync,
579 Refresh::All(_) => Mode::Upgrade {
580 targets: BTreeSet::new(),
581 },
582 Refresh::Names(names) if names.is_empty() => Mode::Sync,
583 Refresh::Names(names) => Mode::Upgrade {
584 targets: names.into_iter().collect(),
585 },
586 },
587 engine: Engine {
588 mars,
589 meridian: input.engine.meridian.map(|version| {
590 Version::parse(&version).map_err(|error| super::BadVersion {
591 version,
592 message: error.to_string(),
593 })
594 }),
595 ignore_requires_mars: false,
596 ignore_requires_meridian: false,
597 },
598 bounds: Bounds {
599 packages: input.bounds.packages,
600 bytes: input.bounds.bytes,
601 },
602 };
603 Ok(match super::resolve(&request, &answers) {
604 Outcome::Needs(needs) => Output::Needs {
605 needs: needs.into_iter().map(NeedWire::from).collect(),
606 },
607 Outcome::Failed(error) => failed(error.failure, &error.diagnostics),
608 Outcome::Resolved(resolved) => Output::Resolved {
609 resolved: ResolvedOutput {
610 lock: resolved
611 .nodes
612 .iter()
613 .map(|(name, node)| {
614 (
615 name.clone(),
616 locked_dependency(
617 &node.id,
618 node.resolved.tag.as_deref(),
619 node.resolved.commit.as_deref(),
620 node.plugin.as_ref(),
621 ),
622 )
623 })
624 .collect(),
625 dependencies: dependencies(&resolved),
626 },
627 diagnostics: diagnostics(&resolved.diagnostics),
628 },
629 })
630}
631
632fn dependencies(resolved: &super::Resolved) -> BTreeMap<String, DependencyOutput> {
633 resolved
634 .nodes
635 .iter()
636 .filter_map(|(name, node)| {
637 let lock = locked_dependency(
638 &node.id,
639 node.resolved.tag.as_deref(),
640 node.resolved.commit.as_deref(),
641 node.plugin.as_ref(),
642 );
643 let (url, commit) = (lock.url?, lock.commit?);
645 let required_by = resolved
646 .constraints
647 .get(name)
648 .into_iter()
649 .flatten()
650 .map(|(by, constraint)| RequesterOutput {
651 by: requester(by),
652 constraint: constraint_text(constraint),
653 })
654 .collect();
655 Some((
656 name.clone(),
657 DependencyOutput {
658 url,
659 commit,
660 subpath: lock.subpath,
661 version: node.resolved.version.as_ref().and(lock.version),
662 content: lock.content.and_then(|content| {
663 Some(ContentOutput {
664 url: content.url?,
665 subpath: content.subpath,
666 commit: content.commit?,
667 })
668 }),
669 required_by,
670 },
671 ))
672 })
673 .collect()
674}
675
676fn requester(by: &str) -> String {
677 if by == ROOT_CORE { ROOT } else { by }.to_string()
678}
679
680fn constraint_text(constraint: &Constraint) -> Option<String> {
681 match constraint {
682 Constraint::Latest => None,
683 other => Some(other.to_string()),
684 }
685}
686
687fn diagnostics(notes: &[Diagnostic]) -> Vec<DiagnosticOutput> {
688 let mut seen = BTreeSet::new();
689 notes
690 .iter()
691 .filter_map(|note| {
692 let Diagnostic::Note {
693 level,
694 code,
695 message,
696 once,
697 } = note
698 else {
699 return None;
700 };
701 if *once && !seen.insert((code.clone(), message.clone())) {
702 return None;
703 }
704 Some(DiagnosticOutput {
705 level: match level {
706 Level::Warning => "warning",
707 Level::Advisory => "advisory",
708 Level::Info => "info",
709 },
710 code: code.clone(),
711 message: message.clone(),
712 })
713 })
714 .collect()
715}
716
717fn failed(failure: Failure, notes: &[Diagnostic]) -> Output {
718 let message = failure.message();
719 let body = match failure {
720 Failure::Conflict {
721 name, requesters, ..
722 } => FailureBody::Conflict {
723 name,
724 requesters: requesters
725 .into_iter()
726 .map(|found| RequesterOutput {
727 by: requester(&found.by),
728 constraint: (found.constraint != "latest").then_some(found.constraint),
729 })
730 .collect(),
731 },
732 Failure::Identity(Identity::OneSourceTwoNames {
733 existing,
734 duplicate,
735 source,
736 }) => FailureBody::Identity {
737 detail: "one-source-two-names",
738 names: vec![existing, duplicate],
739 source,
740 existing: None,
741 },
742 Failure::Identity(Identity::OneNameTwoSources {
743 name,
744 existing,
745 incoming,
746 }) => FailureBody::Identity {
747 detail: "one-name-two-sources",
748 names: vec![name],
749 source: incoming,
750 existing: Some(existing),
751 },
752 Failure::EngineIncompatible { name, failures, .. } => {
753 let first = failures.first();
754 FailureBody::EngineIncompatible {
755 name,
756 requirement: first.map(|failure| failure.requirement.clone()),
757 engine: first.map(|failure| failure.engine),
758 }
759 }
760 Failure::EngineUnsatisfiable { name, excluded } => FailureBody::EngineUnsatisfiable {
761 name,
762 excluded: excluded
763 .into_iter()
764 .flat_map(|(version, failures)| {
765 failures.into_iter().map(
766 move |EngineFailure {
767 engine,
768 requirement,
769 ..
770 }| ExcludedOutput {
771 version: version.to_string(),
772 requirement,
773 engine,
774 },
775 )
776 })
777 .collect(),
778 },
779 Failure::EngineRequirementInvalid {
780 name,
781 engine,
782 requirement,
783 ..
784 } => FailureBody::EngineRequirementInvalid {
785 name,
786 requirement,
787 engine,
788 },
789 Failure::EngineVersionInvalid {
790 engine, version, ..
791 } => FailureBody::EngineVersionInvalid { engine, version },
792 Failure::Plugin {
793 name,
794 detail,
795 plugin,
796 ..
797 } => FailureBody::Plugin {
798 name,
799 detail: match detail {
800 PluginDetail::NotAMarketplace => "not-a-marketplace",
801 PluginDetail::NotListed => "not-listed",
802 PluginDetail::Refused => "refused",
803 PluginDetail::ChoiceNeeded => "choice-needed",
804 PluginDetail::NotOnePackage => "not-one-package",
805 PluginDetail::UnusablePath => "unusable-path",
806 },
807 plugin,
808 },
809 Failure::Subpath {
810 name,
811 subpath,
812 detail,
813 } => FailureBody::Subpath {
814 name,
815 subpath,
816 detail: subpath_detail(detail),
817 },
818 Failure::Unreadable {
819 name, diagnostics, ..
820 } => FailureBody::Unreadable { name, diagnostics },
821 Failure::Path { name, declared_in } => FailureBody::Path {
822 name,
823 declared_in: requester(&declared_in),
824 },
825 Failure::Unavailable { need, reason, .. } => FailureBody::Unavailable {
826 need: need.into(),
827 reason,
828 },
829 Failure::Bounds { limit, at } => FailureBody::Bounds {
830 limit: match limit {
831 BoundsLimit::Packages => "packages",
832 BoundsLimit::Bytes => "bytes",
833 },
834 at,
835 },
836 Failure::Oscillation { name, steps } => FailureBody::Oscillation {
837 name,
838 steps: steps
839 .into_iter()
840 .map(|step| StepOutput {
841 version: step.version,
842 commit: step.commit,
843 })
844 .collect(),
845 },
846 Failure::Frozen { .. } => FailureBody::Frozen,
847 };
848 Output::Failed {
849 failed: FailureOutput { body, message },
850 diagnostics: diagnostics(notes),
851 }
852}
853
854fn subpath_detail(detail: SubpathDetail) -> &'static str {
855 match detail {
856 SubpathDetail::Missing => "missing",
857 SubpathDetail::NotADirectory => "not-a-directory",
858 SubpathDetail::Traversal => "traversal",
859 }
860}