Resolver.vala 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  1. using Invercargill;
  2. using Invercargill.DataStructures;
  3. namespace Usm {
  4. /**
  5. * Errors thrown while resolving a package set.
  6. *
  7. * Every member's message is a fully itemised report safe to print
  8. * verbatim by a CLI.
  9. */
  10. public errordomain ResolverError {
  11. /** A required resource ref could not be satisfied; the message itemises every failing ref and why. */
  12. UNSATISFIABLE,
  13. /** No candidate group in a grouped dependency phase is satisfiable; the message carries a per-group itemised report. */
  14. NO_VIABLE_GROUP,
  15. /** The resolved package graph contains a dependency cycle; the message names the packages in the cycle. */
  16. CYCLE,
  17. /** The configured system package manager query failed. */
  18. SYSTEM_QUERY_FAILED
  19. }
  20. /**
  21. * Why one {@link ResourceRef} could not be satisfied during resolution:
  22. * it was neither present locally nor provided by any system or USM
  23. * package candidate.
  24. */
  25. public class RefFailure : Object {
  26. /** The ref that could not be satisfied. */
  27. public ResourceRef resource { get; set; }
  28. /** The name of the package whose dependency phase required it. */
  29. public string origin { get; set; }
  30. /** Whether a system package manager was consulted for this ref. */
  31. public bool spm_configured { get; set; }
  32. /**
  33. * One-line description used in itemised reports, e.g.
  34. * `bin:foo (required by "app") — not present locally; no system package provides it; no USM package provides it`.
  35. */
  36. public string describe(string reported_for) {
  37. var origin_note = origin != reported_for ? @" (required by \"$origin\")" : "";
  38. var spm_reason = spm_configured ? "no system package provides it" : "no system package manager is configured";
  39. return @"$(resource.to_string())$origin_note — not present locally; $spm_reason; no USM package provides it";
  40. }
  41. }
  42. /**
  43. * One candidate group that could not be satisfied during group selection,
  44. * carrying the failure for each unresolvable member.
  45. */
  46. public class GroupFailure : Object {
  47. /** The 1-based position of the group within its phase. */
  48. public uint group_index { get; set; }
  49. /** The members of the group, deterministically ordered. */
  50. public Vector<ResourceRef> members { get; set; }
  51. /** Why each unresolvable member failed. */
  52. public Vector<RefFailure> failures { get; set; }
  53. /** Indented multi-line description used in itemised reports. */
  54. public string describe(string reported_for) {
  55. var builder = new StringBuilder();
  56. builder.append_printf(" Group %u (%s):\n", group_index, members.to_string(r => r.to_string(), ", "));
  57. foreach(var failure in failures) {
  58. builder.append_printf(" %s\n", failure.describe(reported_for));
  59. }
  60. return builder.str;
  61. }
  62. }
  63. /**
  64. * The outcome of a successful {@link Resolver.resolve}: the resolved
  65. * package set, the chosen system packages and the topological
  66. * install/removal orders derived from the resolved package graph.
  67. */
  68. public class ResolutionResult : Object {
  69. /** Every chosen USM package: the roots plus their transitive provider closure. */
  70. public PackageSet packages { get; set; }
  71. /** System packages chosen to satisfy missing resources, ordered by name; install them as one transaction before any USM package. */
  72. public Vector<SystemPackageCandidate> system_packages { get; set; }
  73. /** The chosen USM packages ordered dependencies-before-dependents (Kahn's algorithm, package-name tie-break). */
  74. public Vector<AbstractPackage> install_order { get; set; }
  75. /** The exact reverse of {@link install_order}: dependents are removed before their providers. */
  76. public Vector<AbstractPackage> removal_order { get; set; }
  77. }
  78. /**
  79. * Mutable working state for one resolution run.
  80. *
  81. * Snapshots are deep (packages, processed markers, chosen system
  82. * packages and per-package chosen refs are all copied) so a group
  83. * evaluation can be rolled back by restoring a snapshot without sharing
  84. * any mutable collection with the state it was taken from.
  85. */
  86. internal class ResolutionState {
  87. public PackageSet chosen = new PackageSet();
  88. public HashSet<AbstractPackage> processed = new HashSet<AbstractPackage>();
  89. public Dictionary<string, SystemPackageCandidate> spm_chosen = new Dictionary<string, SystemPackageCandidate>();
  90. public Dictionary<string, Set<ResourceRef>> refs_by_package = new Dictionary<string, Set<ResourceRef>>();
  91. /**
  92. * The refs the walk satisfied through SPM candidates — the repair
  93. * pass ({@link Resolver.resolve}) re-selects providers for exactly
  94. * these when the greedy set turns out not to co-install.
  95. */
  96. public Vector<ResourceRef> spm_refs = new Vector<ResourceRef>();
  97. public ResolutionState snapshot() {
  98. var copy = new ResolutionState();
  99. copy.chosen.union_with(chosen);
  100. copy.processed.union_with(processed);
  101. foreach(var pair in spm_chosen) {
  102. copy.spm_chosen.set(pair.key, pair.value);
  103. }
  104. foreach(var pair in refs_by_package) {
  105. var refs = new HashSet<ResourceRef>();
  106. refs.union_with(pair.value);
  107. copy.refs_by_package.set(pair.key, refs);
  108. }
  109. copy.spm_refs = new Vector<ResourceRef>();
  110. copy.spm_refs.add_all(spm_refs);
  111. return copy;
  112. }
  113. }
  114. public class Resolver {
  115. private Dictionary<Repository, RepositoryListing> listings = new Dictionary<Repository, RepositoryListing>();
  116. private Set<AbstractPackage> supplied = new HashSet<AbstractPackage>();
  117. private ResourceFinder resource_finder;
  118. private Vector<AbstractPackage>? catalog_cache = null;
  119. // Per-resolution state, reset at the start of every {@link resolve} call
  120. private ResolutionState state = new ResolutionState();
  121. private Dictionary<string, Vector<SystemPackageCandidate>> spm_index = new Dictionary<string, Vector<SystemPackageCandidate>>();
  122. private Dictionary<string, bool> local_presence = new Dictionary<string, bool>();
  123. private bool spm_configured = false;
  124. /**
  125. * The last batched SPM query result — kept so the post-walk
  126. * repair pass can re-select providers from the full candidate
  127. * pool without a second helper spawn.
  128. */
  129. private SystemQueryResult? spm_query_result = null;
  130. /**
  131. * Optional progress callback fired once per resolved package as
  132. * `resolved_count / estimated_total`, where the estimate is the
  133. * number of roots times two (a rough dependency multiplier) and
  134. * the final report is clamped to 1.0 when resolution completes.
  135. * Null (the default) disables reporting.
  136. */
  137. public owned ProgressDelegate? resolution_progress { get; set; }
  138. /** Estimated package count for {@link resolution_progress}: roots x 2, at least 1. */
  139. private uint resolution_estimated_total = 1;
  140. /** The lifecycle phases resolution considers, in processing order. */
  141. private const string[] PHASES = { "manage", "build", "runtime" };
  142. public Resolver(ResourceFinder local_resource_finder) {
  143. this.resource_finder = local_resource_finder;
  144. }
  145. public void load_listing(Repository repo, RepositoryListing listing) {
  146. listings.set(repo, listing);
  147. catalog_cache = null;
  148. }
  149. public void supply_package(string path) throws Error {
  150. supplied.add(new AbstractPackage.from_package(path));
  151. catalog_cache = null;
  152. }
  153. /**
  154. * Adds every readable cached package as a supplied package so the
  155. * cache can satisfy resources during resolution. Unreadable cache
  156. * entries (for example a half-finished download) are skipped with a
  157. * warning.
  158. */
  159. public void load_cache(Paths paths) throws Error {
  160. var cache_state = new SystemState(paths);
  161. foreach (var package in cache_state.get_cached_packages()) {
  162. if(!File.new_for_path(package.package_path).query_exists()) {
  163. continue;
  164. }
  165. try {
  166. supply_package(package.package_path);
  167. }
  168. catch(Error e) {
  169. warning(@"[Usm] Skipping unreadable cached package \"$(package.package_name)\": $(e.message)");
  170. }
  171. }
  172. }
  173. /**
  174. * Finds a package by exact name, preferring repository packages over
  175. * supplied (cached) ones so installs pull a fresh copy. Deterministic:
  176. * repository packages are preferred, then the highest version, then
  177. * repository name.
  178. */
  179. public AbstractPackage? find_package(string search) {
  180. AbstractPackage? match = null;
  181. foreach(var package in catalog()) {
  182. if(package.manifest.name != search) {
  183. continue;
  184. }
  185. if(package.repository != null) {
  186. match = package;
  187. }
  188. else if(match == null) {
  189. match = package;
  190. }
  191. }
  192. return match;
  193. }
  194. /**
  195. * Finds a package providing the given resource, deterministically
  196. * choosing the best provider: alphabetically-first package name,
  197. * then the HIGHEST version (a stale cached copy of an older
  198. * release must never win over a newer one), then a repository
  199. * package over a supplied/cached one so installs pull a fresh
  200. * copy, then repository name and package path.
  201. */
  202. public AbstractPackage? find_resource(ResourceRef resource) {
  203. AbstractPackage? match = null;
  204. foreach(var package in catalog()) {
  205. if(!package.manifest.satisfies(resource)) {
  206. continue;
  207. }
  208. if(match == null) {
  209. match = package;
  210. continue;
  211. }
  212. if(better_provider(package, match)) {
  213. match = package;
  214. }
  215. }
  216. return match;
  217. }
  218. /**
  219. * Whether {@link candidate} beats {@link incumbent} as a provider:
  220. * alphabetically-first name, then highest version, then repository
  221. * over supplied/cache, then repository name and package path.
  222. */
  223. private static bool better_provider(AbstractPackage candidate, AbstractPackage incumbent) {
  224. var by_name = candidate.manifest.name.collate(incumbent.manifest.name);
  225. if(by_name != 0) {
  226. return by_name < 0;
  227. }
  228. var by_version = candidate.manifest.version.compare(incumbent.manifest.version);
  229. if(by_version != 0) {
  230. return by_version > 0;
  231. }
  232. if((candidate.repository == null) != (incumbent.repository == null)) {
  233. return candidate.repository != null;
  234. }
  235. var by_repository = (candidate.repository?.name ?? "").collate(incumbent.repository?.name ?? "");
  236. if(by_repository != 0) {
  237. return by_repository < 0;
  238. }
  239. return (candidate.package_path ?? "").collate(incumbent.package_path ?? "") < 0;
  240. }
  241. /**
  242. * Resolves the full dependency closure for the given root packages.
  243. *
  244. * A missing resource resolves in order: (a) already present locally,
  245. * (b) system packages — via ONE batched query covering every ref any
  246. * candidate group could need, choosing per ref the candidate
  247. * minimising new installs (dependency-count − installed-dependency-count),
  248. * deduplicating packages chosen for multiple resources — then (c) USM
  249. * packages from repositories, the cache or supplied packages. Without
  250. * a configured manager (b) is skipped. Grouped phases select, in
  251. * manifest order, the viable group minimising total new installs
  252. * (USM packages count with their transitive closure; resources
  253. * already satisfied cost 0); ties keep manifest order.
  254. *
  255. * Throws {@link ResolverError} with an itemised report when a flat
  256. * ref is unsatisfiable, when no group is viable, or when the resolved
  257. * graph contains a cycle.
  258. */
  259. public ResolutionResult resolve(Lot<AbstractPackage> roots, SystemPackageManager? spm = null) throws Error {
  260. state = new ResolutionState();
  261. spm_index = new Dictionary<string, Vector<SystemPackageCandidate>>();
  262. local_presence = new Dictionary<string, bool>();
  263. spm_configured = spm != null && spm.enabled;
  264. spm_query_result = null;
  265. resolution_estimated_total = roots.length * 2;
  266. if(resolution_estimated_total < 1) {
  267. resolution_estimated_total = 1;
  268. }
  269. var ordered_roots = roots.sort(compare_packages).to_vector();
  270. foreach(var root in ordered_roots) {
  271. state.chosen.add(root);
  272. }
  273. if(spm_configured) {
  274. batch_query(roots, (!)spm);
  275. }
  276. foreach(var root in ordered_roots) {
  277. process_package(root);
  278. }
  279. var install_order = topological_order(state.chosen, state.refs_by_package);
  280. var removal_order = new Vector<AbstractPackage>();
  281. for(uint index = install_order.length; index > 0; index--) {
  282. removal_order.add(install_order[index - 1]);
  283. }
  284. var system_packages = new Vector<SystemPackageCandidate>();
  285. foreach(var pair in state.spm_chosen) {
  286. system_packages.add(pair.value);
  287. }
  288. system_packages = system_packages.sort((a, b) => a.name.collate(b.name)).to_vector();
  289. // The walk chose SPM candidates greedily with conflict
  290. // METADATA only. The SPM's own solver is the final arbiter:
  291. // when the finished set does not co-install, re-select the
  292. // whole SPM-assigned ref set through the shared
  293. // provider-selection pass (planner-verified, minimal
  294. // cumulative closure). Zero extra helper spawns in the
  295. // common case — one plan call.
  296. if(spm != null && ((SystemPackageManager)spm).enabled && system_packages.length > 0
  297. && spm_query_result != null && state.spm_refs.length > 0) {
  298. var chosen_names = new Vector<string>();
  299. foreach(var system_package in system_packages) {
  300. chosen_names.add(system_package.name);
  301. }
  302. if(((SystemPackageManager)spm).try_plan_install(chosen_names) == null) {
  303. SystemProviderPlan plan = names => ((SystemPackageManager)spm).try_plan_install(names);
  304. var selection = ProviderSelection.select(state.spm_refs, (!)spm_query_result, plan);
  305. if(selection.planner_succeeded && selection.unresolved.length > 0) {
  306. var listing = new StringBuilder();
  307. foreach(var reference in selection.unresolved) {
  308. if(listing.len > 0) {
  309. listing.append(", ");
  310. }
  311. listing.append(reference.to_string());
  312. }
  313. throw new ResolverError.UNSATISFIABLE(
  314. "The system package manager cannot co-install a provider set for: %s — the covering providers conflict with each other"
  315. .printf(listing.str));
  316. }
  317. var by_name = new Dictionary<string, SystemPackageCandidate>();
  318. foreach(var candidate in ((!)spm_query_result).packages) {
  319. if(!by_name.has(candidate.name)) {
  320. by_name.set(candidate.name, candidate);
  321. }
  322. }
  323. var repaired = new Vector<SystemPackageCandidate>();
  324. foreach(var name in selection.chosen) {
  325. SystemPackageCandidate candidate;
  326. if(by_name.try_get(name, out candidate)) {
  327. repaired.add(candidate);
  328. }
  329. }
  330. // A planner that never succeeded is a helper without
  331. // a working plan mode, not a conflict verdict: keep
  332. // the walk's greedy set rather than discarding it on
  333. // unusable evidence.
  334. if(repaired.length > 0 && (selection.planner_succeeded || repaired.length < system_packages.length)) {
  335. system_packages = repaired.sort((a, b) => a.name.collate(b.name)).to_vector();
  336. }
  337. }
  338. }
  339. var packages = new PackageSet();
  340. packages.union_with(state.chosen);
  341. if(resolution_progress != null) {
  342. resolution_progress(1.0f);
  343. }
  344. return new ResolutionResult() {
  345. packages = packages,
  346. system_packages = system_packages,
  347. install_order = install_order,
  348. removal_order = removal_order
  349. };
  350. }
  351. /**
  352. * Resolves the dependency closure of a LOCAL manifest — a git
  353. * checkout or build directory — rather than a repository package:
  354. * the entry point `usm manifest install`/`usm manifest build`
  355. * and usmrad's ensure-deps share, so provider selection (SPM
  356. * conflict awareness, minimal closures, planner verification)
  357. * behaves identically everywhere. The root contributes its
  358. * dependency phases; its own provides are NOT installed (it is
  359. * the thing being built, not a dependency).
  360. */
  361. public ResolutionResult resolve_manifest(Manifest manifest, SystemPackageManager? spm = null) throws Error {
  362. var roots = new Vector<AbstractPackage>();
  363. roots.add(new AbstractPackage.from_manifest(manifest));
  364. return resolve(roots, spm);
  365. }
  366. /**
  367. * Orders packages dependencies-before-dependents with Kahn's
  368. * algorithm and a deterministic package-name tie-break; a cycle is a
  369. * hard error naming the packages in it.
  370. *
  371. * {@link chosen_refs} maps a package name to the refs chosen for it
  372. * during resolution (flat refs plus the chosen group's members); when
  373. * null the requirements are derived from each manifest's flat
  374. * phases plus every candidate group's refs. Only refs provided by
  375. * another package in the set create ordering edges.
  376. */
  377. public static Vector<AbstractPackage> topological_order(Enumerable<AbstractPackage> packages, ReadOnlyAssociative<string, Set<ResourceRef>>? chosen_refs = null) throws ResolverError {
  378. var nodes = packages.sort(compare_packages).to_vector();
  379. var by_name = new Dictionary<string, Vector<AbstractPackage>>();
  380. foreach(var node in nodes) {
  381. var name = node.manifest.name;
  382. Vector<AbstractPackage> named;
  383. if(!by_name.try_get(name, out named)) {
  384. named = new Vector<AbstractPackage>();
  385. by_name.set(name, named);
  386. }
  387. named.add(node);
  388. }
  389. var required = new Dictionary<string, Vector<ResourceRef>>();
  390. foreach(var node in nodes) {
  391. var refs = new Vector<ResourceRef>();
  392. Set<ResourceRef>? chosen = null;
  393. if(chosen_refs != null && chosen_refs.try_get(node.manifest.name, out chosen)) {
  394. foreach(var resource in chosen) {
  395. refs.add(resource);
  396. }
  397. }
  398. else {
  399. foreach(var phase in resolution_phases(node.manifest)) {
  400. foreach(var resource in phase.ordered_all_refs()) {
  401. refs.add(resource);
  402. }
  403. }
  404. }
  405. required.set(node.manifest.name, refs.sort((a, b) => a.to_string().collate(b.to_string())).to_vector());
  406. }
  407. // Edges provider → dependent; one edge per (provider, dependent) pair
  408. var dependents = new Dictionary<string, Vector<string>>();
  409. var indegree = new Dictionary<string, uint>();
  410. foreach(var node in nodes) {
  411. indegree.set(node.manifest.name, 0);
  412. }
  413. foreach(var dependent in nodes) {
  414. var dependent_name = dependent.manifest.name;
  415. var linked_providers = new HashSet<string>();
  416. Vector<ResourceRef> dependent_refs;
  417. if(!required.try_get(dependent_name, out dependent_refs)) {
  418. continue;
  419. }
  420. foreach(var resource in dependent_refs) {
  421. foreach(var provider in nodes) {
  422. var provider_name = provider.manifest.name;
  423. if(provider_name == dependent_name || linked_providers.has(provider_name)) {
  424. continue;
  425. }
  426. if(provider.manifest.satisfies(resource)) {
  427. linked_providers.add(provider_name);
  428. Vector<string> follower_names;
  429. if(!dependents.try_get(provider_name, out follower_names)) {
  430. follower_names = new Vector<string>();
  431. dependents.set(provider_name, follower_names);
  432. }
  433. follower_names.add(dependent_name);
  434. uint degree;
  435. indegree.try_get(dependent_name, out degree);
  436. indegree.set(dependent_name, degree + 1);
  437. }
  438. }
  439. }
  440. }
  441. var order = new Vector<AbstractPackage>();
  442. var remaining = new HashSet<string>();
  443. foreach(var node in nodes) {
  444. remaining.add(node.manifest.name);
  445. }
  446. while(remaining.any()) {
  447. string? next = null;
  448. foreach(var name in remaining) {
  449. uint degree;
  450. if(indegree.try_get(name, out degree) && degree == 0) {
  451. if(next == null || name.collate(next) < 0) {
  452. next = name;
  453. }
  454. }
  455. }
  456. if(next == null) {
  457. throw new ResolverError.CYCLE(
  458. @"The resolved package graph contains a dependency cycle: $(describe_cycle(remaining, required, nodes))"
  459. );
  460. }
  461. remaining.remove(next);
  462. Vector<AbstractPackage> named;
  463. if(by_name.try_get(next, out named)) {
  464. foreach(var package in named) {
  465. order.add(package);
  466. }
  467. }
  468. Vector<string> follower_names;
  469. if(dependents.try_get(next, out follower_names)) {
  470. foreach(var follower in follower_names) {
  471. if(remaining.has(follower)) {
  472. uint degree;
  473. indegree.try_get(follower, out degree);
  474. indegree.set(follower, degree - 1);
  475. }
  476. }
  477. }
  478. }
  479. return order;
  480. }
  481. /** Deterministic catalog order: (name, version, repository name, package path). */
  482. private static int compare_packages(AbstractPackage a, AbstractPackage b) {
  483. var by_name = a.manifest.name.collate(b.manifest.name);
  484. if(by_name != 0) {
  485. return by_name;
  486. }
  487. var by_version = a.manifest.version.compare(b.manifest.version);
  488. if(by_version != 0) {
  489. return by_version;
  490. }
  491. var by_repository = (a.repository?.name ?? "").collate(b.repository?.name ?? "");
  492. if(by_repository != 0) {
  493. return by_repository;
  494. }
  495. return (a.package_path ?? "").collate(b.package_path ?? "");
  496. }
  497. /** The lifecycle phases resolution considers, in processing order. */
  498. private static Vector<DependencyPhase> resolution_phases(Manifest manifest) {
  499. var phases = new Vector<DependencyPhase>();
  500. phases.add(manifest.dependencies.manage);
  501. phases.add(manifest.dependencies.build);
  502. phases.add(manifest.dependencies.runtime);
  503. return phases;
  504. }
  505. private static Vector<AbstractPackage> catalog_of(Set<AbstractPackage> supplied, Dictionary<Repository, RepositoryListing> listings) {
  506. return supplied.concat(
  507. listings.select_many<Pair<Repository, RepositoryListingEntry>>(l => l.value.entries.select_pairs<Repository, RepositoryListingEntry>(e => l.key, e => e))
  508. .select<AbstractPackage>(p => new AbstractPackage.from_repository(p.value1, p.value2)))
  509. .sort(compare_packages)
  510. .to_vector();
  511. }
  512. private Vector<AbstractPackage> catalog() {
  513. if(catalog_cache == null) {
  514. catalog_cache = catalog_of(supplied, listings);
  515. }
  516. return catalog_cache;
  517. }
  518. /**
  519. * Collects every ref resolution could possibly consult — all refs of
  520. * all candidate groups of every package reachable through USM
  521. * providers — then asks the system package manager about the locally
  522. * missing ones in ONE batched query.
  523. */
  524. private void batch_query(Lot<AbstractPackage> roots, SystemPackageManager spm) throws Error {
  525. var refs = new HashSet<ResourceRef>();
  526. var visited = new HashSet<AbstractPackage>();
  527. var pending = new Series<AbstractPackage>();
  528. foreach(var root in roots) {
  529. pending.add(root);
  530. }
  531. while(pending.length > 0) {
  532. var package = pending.pop_start();
  533. if(visited.has(package)) {
  534. continue;
  535. }
  536. visited.add(package);
  537. foreach(var phase in resolution_phases(package.manifest)) {
  538. foreach(var resource in phase.ordered_all_refs()) {
  539. refs.add(resource);
  540. if(!has_local(resource)) {
  541. var provider = find_resource(resource);
  542. if(provider != null) {
  543. pending.add(provider);
  544. }
  545. }
  546. }
  547. }
  548. }
  549. var missing = new Vector<ResourceRef>();
  550. foreach(var resource in refs.sort((a, b) => a.to_string().collate(b.to_string()))) {
  551. // Version-constrained refs have no SPM translation yet:
  552. // shims match names exactly, so querying them would only
  553. // yield misleading not-founds. They resolve from local
  554. // presence or USM packages.
  555. if(resource.constraint != null) {
  556. continue;
  557. }
  558. if(!has_local(resource)) {
  559. missing.add(resource);
  560. }
  561. }
  562. if(missing.length == 0) {
  563. return;
  564. }
  565. SystemQueryResult? result = null;
  566. try {
  567. result = spm.query_sync(missing);
  568. spm_query_result = result;
  569. }
  570. catch(Error e) {
  571. throw new ResolverError.SYSTEM_QUERY_FAILED(@"$(e.message)");
  572. }
  573. if(result == null) {
  574. spm_configured = false;
  575. return;
  576. }
  577. foreach(var candidate in result.packages) {
  578. foreach(var resource in candidate.resources) {
  579. var key = resource.to_string();
  580. Vector<SystemPackageCandidate> candidates;
  581. if(!spm_index.try_get(key, out candidates)) {
  582. candidates = new Vector<SystemPackageCandidate>();
  583. spm_index.set(key, candidates);
  584. }
  585. candidates.add(candidate);
  586. }
  587. }
  588. }
  589. private bool has_local(ResourceRef resource) {
  590. var key = resource.to_string();
  591. bool present;
  592. if(local_presence.try_get(key, out present)) {
  593. return present;
  594. }
  595. present = resource_finder.has_resource(resource);
  596. local_presence.set(key, present);
  597. return present;
  598. }
  599. /** Cost ordering for system package candidates: new installs first, then name. */
  600. private static int compare_spm_candidates(SystemPackageCandidate a, SystemPackageCandidate b) {
  601. var by_cost = (a.dependency_count - a.installed_dependency_count) - (b.dependency_count - b.installed_dependency_count);
  602. if(by_cost != 0) {
  603. return by_cost;
  604. }
  605. return a.name.collate(b.name);
  606. }
  607. /**
  608. * The best candidate providing the resource: one already chosen for
  609. * another resource (cost 0, smallest name) when possible, otherwise
  610. * the cheapest by (new installs, name). Candidates whose conflicts
  611. * metadata names a chosen package — in EITHER direction, since
  612. * blockers are declared asymmetrically (dropbear declares
  613. * `!openssh-client`; the openssh packages declare nothing) — are
  614. * skipped: alternative providers of one ref routinely cannot
  615. * coexist, and the walk must never pick such a mix. The post-walk
  616. * repair pass in {@link resolve} re-checks the finished set with
  617. * the SPM's own solver, catching pairs the metadata missed.
  618. */
  619. private SystemPackageCandidate? best_spm_candidate(ResourceRef resource) {
  620. Vector<SystemPackageCandidate> candidates;
  621. if(!spm_index.try_get(resource.to_string(), out candidates)) {
  622. return null;
  623. }
  624. SystemPackageCandidate? already_chosen = null;
  625. SystemPackageCandidate? best = null;
  626. foreach(var candidate in candidates) {
  627. if(conflicts_with_chosen(candidate)) {
  628. continue;
  629. }
  630. if(state.spm_chosen.has(candidate.name)) {
  631. if(already_chosen == null || candidate.name.collate(already_chosen.name) < 0) {
  632. already_chosen = candidate;
  633. }
  634. }
  635. else if(best == null || compare_spm_candidates(candidate, best) < 0) {
  636. best = candidate;
  637. }
  638. }
  639. return already_chosen ?? best;
  640. }
  641. /**
  642. * Symmetric conflict test against the walk's chosen SPM set: the
  643. * candidate's own metadata naming a chosen package, or a chosen
  644. * package's metadata naming the candidate.
  645. */
  646. private bool conflicts_with_chosen(SystemPackageCandidate candidate) {
  647. foreach(var name in candidate.conflicts) {
  648. if(state.spm_chosen.has(name)) {
  649. return true;
  650. }
  651. }
  652. foreach(var pair in state.spm_chosen) {
  653. foreach(var name in pair.value.conflicts) {
  654. if(name == candidate.name) {
  655. return true;
  656. }
  657. }
  658. }
  659. return false;
  660. }
  661. /**
  662. * Resolves one resource ref for {@link origin} under the
  663. * local → system-package → USM-package precedence, mutating the
  664. * current {@link state}; returns the failure when unsatisfiable.
  665. */
  666. private RefFailure? resolve_ref(AbstractPackage origin, ResourceRef resource) throws Error {
  667. if(state.chosen.provides(resource) || has_local(resource)) {
  668. return null;
  669. }
  670. if(spm_configured) {
  671. var candidate = best_spm_candidate(resource);
  672. if(candidate != null) {
  673. state.spm_chosen.set(candidate.name, candidate);
  674. if(!state.spm_refs.any(r => r.to_string() == resource.to_string())) {
  675. state.spm_refs.add(resource);
  676. }
  677. return null;
  678. }
  679. }
  680. var provider = find_resource(resource);
  681. if(provider != null) {
  682. if(!state.chosen.has(provider)) {
  683. state.chosen.add(provider);
  684. }
  685. process_package(provider);
  686. return null;
  687. }
  688. return new RefFailure() {
  689. resource = resource,
  690. origin = origin.manifest.name,
  691. spm_configured = spm_configured
  692. };
  693. }
  694. private void process_package(AbstractPackage package) throws Error {
  695. if(state.processed.has(package)) {
  696. return;
  697. }
  698. state.processed.add(package);
  699. report_resolution_progress();
  700. var manifest = package.manifest;
  701. for(int phase_index = 0; phase_index < PHASES.length; phase_index++) {
  702. var phase_name = PHASES[phase_index];
  703. var phase = manifest_phase(manifest, phase_name);
  704. if(phase.is_grouped) {
  705. select_group(package, phase_name, phase);
  706. }
  707. else {
  708. var failures = new Vector<RefFailure>();
  709. foreach(var resource in phase.ordered_required()) {
  710. var failure = resolve_ref(package, resource);
  711. if(failure != null) {
  712. failures.add(failure);
  713. }
  714. }
  715. if(failures.any()) {
  716. var builder = new StringBuilder();
  717. builder.append_printf(
  718. "Could not resolve package \"%s\" (phase \"%s\"): %u unresolvable dependenc%s:\n",
  719. manifest.name, phase_name, failures.length, failures.length == 1 ? "y" : "ies"
  720. );
  721. foreach(var failure in failures) {
  722. builder.append_printf(" %s\n", failure.describe(manifest.name));
  723. }
  724. throw new ResolverError.UNSATISFIABLE(builder.str);
  725. }
  726. record_refs(package, phase.ordered_required());
  727. }
  728. }
  729. }
  730. /**
  731. * Fires {@link resolution_progress} for the packages processed
  732. * so far, clamped to 1.0; the estimate deliberately
  733. * over-counts shallow closures so the bar never sits full
  734. * before resolution is done.
  735. */
  736. private void report_resolution_progress() {
  737. if(resolution_progress == null) {
  738. return;
  739. }
  740. var fraction = (float)state.processed.count() / (float)resolution_estimated_total;
  741. resolution_progress(fraction > 1.0f ? 1.0f : fraction);
  742. }
  743. private static DependencyPhase manifest_phase(Manifest manifest, string phase_name) {
  744. switch(phase_name) {
  745. case "manage":
  746. return manifest.dependencies.manage;
  747. case "build":
  748. return manifest.dependencies.build;
  749. case "runtime":
  750. return manifest.dependencies.runtime;
  751. default:
  752. assert_not_reached();
  753. }
  754. }
  755. /**
  756. * Evaluates the phase's candidate groups in manifest order on a
  757. * snapshot of the choices already made: a group is viable when every
  758. * member resolves. The viable group minimising total new installs
  759. * (USM packages with their transitive closure plus system packages by
  760. * their cost fields) is committed; ties keep manifest order. When no
  761. * group is viable an itemised per-group report is thrown.
  762. */
  763. private void select_group(AbstractPackage package, string phase_name, DependencyPhase phase) throws Error {
  764. var base_state = state.snapshot();
  765. var groups = phase.ordered_groups();
  766. var group_failures = new Vector<GroupFailure>();
  767. ResolutionState? best_state = null;
  768. uint best_index = 0;
  769. int best_cost = 0;
  770. for(uint index = 0; index < groups.length; index++) {
  771. // A fresh copy per evaluation: state must never alias
  772. // base_state, or every group's additions would look
  773. // pre-existing and cost nothing
  774. state = base_state.snapshot();
  775. var failures = new Vector<RefFailure>();
  776. foreach(var resource in groups[index]) {
  777. var failure = resolve_ref(package, resource);
  778. if(failure != null) {
  779. failures.add(failure);
  780. }
  781. }
  782. if(failures.any()) {
  783. group_failures.add(new GroupFailure() {
  784. group_index = index + 1,
  785. members = groups[index],
  786. failures = failures
  787. });
  788. continue;
  789. }
  790. var cost = new_install_cost(base_state);
  791. if(best_state == null || cost < best_cost) {
  792. best_cost = cost;
  793. best_index = index;
  794. best_state = state.snapshot();
  795. }
  796. }
  797. if(best_state == null) {
  798. var builder = new StringBuilder();
  799. builder.append_printf(
  800. "Could not resolve package \"%s\" (phase \"%s\"): no candidate dependency group is satisfiable.\n",
  801. package.manifest.name, phase_name
  802. );
  803. foreach(var failure in group_failures) {
  804. builder.append(failure.describe(package.manifest.name));
  805. }
  806. throw new ResolverError.NO_VIABLE_GROUP(builder.str);
  807. }
  808. state = best_state;
  809. record_refs(package, groups[best_index]);
  810. }
  811. /** Total new installs the current state adds over {@link base_state}: new USM packages plus system-package new-install costs. */
  812. private int new_install_cost(ResolutionState base_state) {
  813. var cost = (int)(state.chosen.count() - base_state.chosen.count());
  814. foreach(var pair in state.spm_chosen) {
  815. if(!base_state.spm_chosen.has(pair.key)) {
  816. cost += pair.value.dependency_count - pair.value.installed_dependency_count;
  817. }
  818. }
  819. return cost;
  820. }
  821. private void record_refs(AbstractPackage package, Vector<ResourceRef> refs) {
  822. Set<ResourceRef> recorded;
  823. if(!state.refs_by_package.try_get(package.manifest.name, out recorded)) {
  824. recorded = new HashSet<ResourceRef>();
  825. state.refs_by_package.set(package.manifest.name, recorded);
  826. }
  827. foreach(var resource in refs) {
  828. recorded.add(resource);
  829. }
  830. }
  831. /** Walks provider edges among {@link remaining} from its smallest name until a node repeats, naming the cycle found. */
  832. private static string describe_cycle(HashSet<string> remaining, Dictionary<string, Vector<ResourceRef>> required, Vector<AbstractPackage> nodes) {
  833. var providers_of = new Dictionary<string, Vector<string>>();
  834. foreach(var dependent in nodes) {
  835. var dependent_name = dependent.manifest.name;
  836. foreach(var provider in nodes) {
  837. var provider_name = provider.manifest.name;
  838. if(provider_name == dependent_name || !remaining.has(provider_name)) {
  839. continue;
  840. }
  841. Vector<ResourceRef> refs;
  842. if(!required.try_get(dependent_name, out refs)) {
  843. continue;
  844. }
  845. var provided = false;
  846. foreach(var resource in refs) {
  847. if(provider.manifest.satisfies(resource)) {
  848. provided = true;
  849. break;
  850. }
  851. }
  852. if(provided) {
  853. Vector<string> providers;
  854. if(!providers_of.try_get(dependent_name, out providers)) {
  855. providers = new Vector<string>();
  856. providers_of.set(dependent_name, providers);
  857. }
  858. providers.add(provider_name);
  859. }
  860. }
  861. }
  862. string? smallest = null;
  863. foreach(var name in remaining) {
  864. if(smallest == null || name.collate(smallest) < 0) {
  865. smallest = name;
  866. }
  867. }
  868. var path = new Series<string>();
  869. var seen = new HashSet<string>();
  870. var current = smallest;
  871. while(current != null && !seen.has(current)) {
  872. seen.add(current);
  873. path.add(current);
  874. string? next = null;
  875. Vector<string> providers;
  876. if(providers_of.try_get(current, out providers)) {
  877. foreach(var provider in providers) {
  878. if(next == null || provider.collate(next) < 0) {
  879. next = provider;
  880. }
  881. }
  882. }
  883. current = next;
  884. }
  885. if(current == null) {
  886. return remaining.to_string(n => n, " -> ");
  887. }
  888. var cycle = new Series<string>();
  889. var started = false;
  890. foreach(var name in path) {
  891. if(name == current) {
  892. started = true;
  893. }
  894. if(started) {
  895. cycle.add(name);
  896. }
  897. }
  898. cycle.add(current);
  899. return cycle.to_string(n => n, " -> ");
  900. }
  901. }
  902. public class PackageSet : HashSet<AbstractPackage> {
  903. public void add_from_file(string path) throws Error {
  904. add(new AbstractPackage.from_package(path));
  905. }
  906. public void add_from_repo(Repository repository, RepositoryListingEntry entry) throws Error {
  907. add(new AbstractPackage.from_repository(repository, entry));
  908. }
  909. /**
  910. * Whether every package's required phases hold: flat phases need all
  911. * refs present (provided by the set or locally), grouped phases need
  912. * one fully-satisfied group.
  913. */
  914. public bool is_satisfied(ResourceFinder local_resource_finder) {
  915. return all(package => {
  916. foreach(var phase_name in new string[] { "manage", "build", "runtime" }) {
  917. var phase = manifest_phase_of(package.manifest, phase_name);
  918. if(!phase.is_satisfied(d => provides(d) || local_resource_finder.has_resource(d))) {
  919. return false;
  920. }
  921. }
  922. return true;
  923. });
  924. }
  925. public bool provides(ResourceRef resource) {
  926. return any(p => p.manifest.satisfies(resource));
  927. }
  928. private static DependencyPhase manifest_phase_of(Manifest manifest, string phase_name) {
  929. switch(phase_name) {
  930. case "manage":
  931. return manifest.dependencies.manage;
  932. case "build":
  933. return manifest.dependencies.build;
  934. case "runtime":
  935. return manifest.dependencies.runtime;
  936. default:
  937. assert_not_reached();
  938. }
  939. }
  940. }
  941. public class AbstractPackage {
  942. public Manifest manifest { get; set; }
  943. public Repository? repository { get; set; }
  944. public RepositoryListingEntry? repository_entry { get; set; }
  945. public string? package_path { get; set; }
  946. public CachedPackage? cached_package { get; set; }
  947. public AbstractPackage.from_package(string path) throws Error {
  948. package_path = path;
  949. manifest = new Manifest.from_package(path);
  950. }
  951. public AbstractPackage.from_repository(Repository repository, RepositoryListingEntry entry) {
  952. this.repository = repository;
  953. this.repository_entry = entry;
  954. this.manifest = entry.manifest;
  955. }
  956. /** Wraps an already-parsed {@link Manifest} with no repository or package source behind it; used by tooling and tests. */
  957. public AbstractPackage.from_manifest(Manifest manifest) {
  958. this.manifest = manifest;
  959. }
  960. }
  961. }