Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
2381 lines (2188 loc) · 87.2 KB
/
Copy pathlib.rs
File metadata and controls
2381 lines (2188 loc) · 87.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Top-level API for minimal tooling.
#![recursion_limit = "256"]
use std::{
collections::{BTreeMap, HashSet},
fmt,
path::{Path, PathBuf},
sync::Arc,
time::SystemTime,
};
use anyhow::anyhow;
use checkouts::{Manager as VcsManager, ManagerHandle as VcsManagerHandle};
use common::fetchers::{AnyBackend, AnyRespError, AnyUrl};
use common::{SpecOrigin, Target};
use google_cloud_storage::client::Storage as GcsStorage;
use lcache::CacheBinProvider;
use ot::OpTracker;
use rcache::{Error as RemoteError, RemoteBinProvider, RemoteCache, RemoteCacheWriter};
mod error;
pub use error::{Error, remote_cache_setup_error};
mod config;
pub use config::{Config, ConfigBuilder, ConfigError, DEFAULT_REMOTE_CACHE_BUCKET};
mod env;
use graph::Error as GraphError;
use graph::{BinProvider, BuildSpecRef, Graph, MaskingBinProvider, Transitives};
use mfile::{EnvPatches, EnvVarValue, LinkConfig, Task};
pub use sandbox::config::Invocation;
mod mfile_search_strategy;
pub use mfile_search_strategy::MFileSearchStrategy;
mod project_setup;
pub use project_setup::ProjectSetup;
pub use env::{Env, PatchHome, WdLayout, interpolate_task_strings, task_arg_env};
use tokio::sync::Semaphore;
use toml_edit::{Array, DocumentMut, Item, TableLike, Value};
use crate::env::EnvArgs;
/// The local cache.
pub type Cache = lcache::Cache<lcache::LocalDir>;
/// Anything which represents a set of packages.
///
/// Anywhere you see this as a parameter, you can pass:
///
/// - `Vec<String>`
/// - `Vec<BuildSpecRef>`
/// - `HashSet<BuildSpecRef>`
/// - `["literal strings"]`
/// - `[String]`
pub trait PackageSelection {
type NameIter<'a>: Iterator<Item = &'a str>
where
Self: 'a;
type RefIter<'a>: Iterator<Item = &'a BuildSpecRef>
where
Self: 'a;
fn as_names(&self) -> Option<Self::NameIter<'_>>;
fn as_refs(&self) -> Option<Self::RefIter<'_>> {
None
}
fn as_bsrs(&self, g: &Graph) -> Result<Vec<BuildSpecRef>, Error> {
if let Some(bsrs) = self.as_refs() {
Ok(bsrs.copied().collect())
} else {
self.as_names()
.unwrap()
.map(|n| match g.by_name(n) {
Some(bsr) => Ok(*bsr),
None => Err(Error::Other(anyhow!(package_not_found_message(g, n)))),
})
.collect::<Result<_, _>>()
}
}
}
/// Builds the `No such package` error message, suggesting close package
/// names when any exist.
fn package_not_found_message(g: &Graph, input: &str) -> String {
let suggestions = package_suggestions(g, input);
// Show the name the suggestions were computed from, not stray padding.
let input = input.trim();
if suggestions.is_empty() {
format!(
"No such package: {} (try 'min package search {}')",
input, input
)
} else {
format!(
"No such package: {} (did you mean: {}?)",
input,
suggestions.join(", ")
)
}
}
/// Collects up to three package names close to `input`, preferring names
/// that share a prefix with the input before fuzzier matches.
fn package_suggestions(g: &Graph, input: &str) -> Vec<String> {
use common::fuzzy_search::fuzzy_match;
let input = input.trim().to_lowercase();
// An empty name is a prefix of every package, so it has no close match.
if input.is_empty() {
return Vec::new();
}
let mut exact: Vec<&str> = Vec::new();
let mut prefix_of_input: Vec<&str> = Vec::new();
let mut input_prefix_of: Vec<&str> = Vec::new();
let mut fuzzy: Vec<(&str, common::fuzzy_search::SearchMatch)> = Vec::new();
for name in g.names() {
let lower = name.to_lowercase();
if lower == input {
exact.push(name);
} else if input.starts_with(&lower) {
prefix_of_input.push(name);
} else if lower.starts_with(&input) {
input_prefix_of.push(name);
} else if let Some(m) = fuzzy_match(&input, name) {
fuzzy.push((name, m));
}
}
exact.sort_unstable();
prefix_of_input.sort_by_key(|n| (n.len(), *n));
input_prefix_of.sort_by_key(|n| (n.len(), *n));
fuzzy.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(b.0)));
let mut candidates: Vec<String> = Vec::with_capacity(3);
candidates.extend(exact.into_iter().map(str::to_string));
candidates.extend(prefix_of_input.into_iter().map(str::to_string));
candidates.extend(input_prefix_of.into_iter().map(str::to_string));
candidates.extend(fuzzy.into_iter().map(|(n, _)| n.to_string()));
candidates.truncate(3);
candidates
}
impl PackageSelection for Vec<String> {
type NameIter<'a>
= std::iter::Map<std::slice::Iter<'a, String>, fn(&'a String) -> &'a str>
where
Self: 'a;
type RefIter<'a> = std::slice::Iter<'a, BuildSpecRef>;
fn as_names(&self) -> Option<Self::NameIter<'_>> {
Some(self.iter().map(|s| s.as_str()))
}
}
impl PackageSelection for HashSet<String> {
type NameIter<'a>
= std::iter::Map<std::collections::hash_set::Iter<'a, String>, fn(&'a String) -> &'a str>
where
Self: 'a;
type RefIter<'a> = std::slice::Iter<'a, BuildSpecRef>;
fn as_names(&self) -> Option<Self::NameIter<'_>> {
Some(self.iter().map(|s| s.as_str()))
}
}
impl PackageSelection for Vec<BuildSpecRef> {
type NameIter<'a>
= std::iter::Map<std::slice::Iter<'a, String>, fn(&'a String) -> &'a str>
where
Self: 'a;
type RefIter<'a> = std::slice::Iter<'a, BuildSpecRef>;
fn as_names(&self) -> Option<Self::NameIter<'_>> {
None
}
fn as_refs(&self) -> Option<Self::RefIter<'_>> {
Some(self.iter())
}
}
impl PackageSelection for HashSet<BuildSpecRef> {
type NameIter<'a>
= std::iter::Map<std::slice::Iter<'a, String>, fn(&'a String) -> &'a str>
where
Self: 'a;
type RefIter<'a> = std::collections::hash_set::Iter<'a, BuildSpecRef>;
fn as_names(&self) -> Option<Self::NameIter<'_>> {
None
}
fn as_refs(&self) -> Option<Self::RefIter<'_>> {
Some(self.iter())
}
}
impl<const N: usize> PackageSelection for [&str; N] {
type NameIter<'a>
= std::iter::Copied<std::slice::Iter<'a, &'a str>>
where
Self: 'a;
type RefIter<'a>
= std::iter::Empty<&'a BuildSpecRef>
where
Self: 'a;
fn as_names(&self) -> Option<Self::NameIter<'_>> {
Some(self.iter().copied())
}
}
impl<const N: usize> PackageSelection for [String; N] {
type NameIter<'a>
= std::iter::Map<std::slice::Iter<'a, String>, fn(&'a String) -> &'a str>
where
Self: 'a;
type RefIter<'a>
= std::iter::Empty<&'a BuildSpecRef>
where
Self: 'a;
fn as_names(&self) -> Option<Self::NameIter<'_>> {
Some(self.iter().map(|s| s.as_str()))
}
}
/// Describes where a task came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TaskSource {
MFile,
Stack(String),
}
/// Daemon-scoped context state that is independent of any particular
/// project's `minimal.toml`. Built once at daemon startup and shared
/// as `Arc<DaemonContext>` across sessions.
///
/// Sessions and other per-invocation callers hold this behind an `Arc`
/// so the daemon-level setup work (dir upsert, VCS init, cache init,
/// standard-library materialization) is amortized across every context
/// that uses it. CLI callers that only build one context per
/// invocation don't share, but pay only the negligible `Arc` overhead.
#[derive(Debug)]
pub struct DaemonContext {
pub(crate) config: Config,
pub(crate) stdlib_dir: PathBuf,
pub(crate) vcs: VcsManagerHandle,
pub(crate) cache: Cache,
}
/// A top-level context for operations in a minimal-configured repo.
///
/// Internally holds an `Arc<DaemonContext>` — daemon-scoped state that
/// can be shared across many `Context`s — plus a per-project
/// `mfile::File`. Existing `Context::new` callers continue to work
/// unchanged; daemon-side code that wants to build multiple sessions
/// against the same daemon-scoped state should use
/// [`DaemonContext::init`] + [`Context::from_daemon`] instead.
///
/// `Clone` is cheap: an `Arc` bump on the daemon state plus a
/// clone of the parsed mfile (a modest allocation). Callers that
/// need to reuse a fully-built context across repeated operations
/// clone rather than rebuild.
#[derive(Debug, Clone)]
pub struct Context {
pub(crate) daemon: Arc<DaemonContext>,
pub(crate) mfile: mfile::File,
/// The classifier leaf of the box this context builds for, if any
/// (NET-155). Every package build the context starts runs in it, so the
/// box's egress verdict decides the build's connections. `None` for a
/// context that builds as its caller's own traffic.
pub(crate) classifier_leaf: Option<sandbox::config::ClassifierLeaf>,
/// The network of the own-address box this context builds for, if any
/// (NET-155). Every package build the context starts that needs the
/// network attaches to it, so the box's egress verdict decides the
/// build's connections.
pub(crate) box_network: Option<op::BuildNetwork>,
}
impl fmt::Display for Context {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "mctx{{")?;
if let Some(p) = self.mfile.dir_path().map(|p| p.to_path_buf()) {
write!(f, " mfile repo at {} ", p.display())?;
} else {
write!(f, "{:?}", self.daemon.config)?;
}
write!(f, "}}")
}
}
impl DaemonContext {
/// Initializes daemon-scoped state: upserts working directories,
/// initializes the VCS manager (respecting `--offline`), initializes
/// the local cache, and materializes the standard library. Callers
/// typically wrap the returned value in an `Arc` and share it
/// across many `Context`s.
///
/// # Errors
///
/// Any I/O or setup failure surfaced from the underlying subsystems.
pub fn init(config: Config) -> Result<Self, Error> {
let (vcs, cache, stdlib_dir) = Self::sub_setup(&config)?;
Ok(Self {
config,
stdlib_dir,
vcs,
cache,
})
}
/// Returns the daemon's `Config`.
pub fn config(&self) -> &Config {
&self.config
}
/// Returns a path to the standard library.
pub fn stdlib_dir(&self) -> &PathBuf {
&self.stdlib_dir
}
/// Returns the VCS manager.
pub fn vcs_manager(&self) -> VcsManagerHandle {
self.vcs.clone()
}
/// Returns a handle to the local cache.
pub fn local_cache(&self) -> Cache {
self.cache.clone()
}
/// Returns the daemon ID.
pub fn daemon_id(&self) -> Option<String> {
self.config().daemon_id()
}
/// Returns the base directory for build sandboxes.
pub fn builds_base_dir(&self) -> PathBuf {
self.config.builds_base_dir()
}
/// Returns the base directory for task sandboxes.
pub fn tasks_base_dir(&self) -> PathBuf {
self.config.task_base_dir()
}
/// Returns the base directory for the artifact/binary cache.
///
/// DO NOT USE unless you really know what you are doing — prefer
/// [`DaemonContext::local_cache`]. Daemon-scoped twins of the
/// [`Context`] accessors of the same name, for callers (housekeeping,
/// diagnostics) that have no project mfile to hang a [`Context`] off.
pub fn cache_base_dir(&self) -> PathBuf {
self.config.built_cache_dir()
}
/// Releases the local cache's read tracker (its held-open append-log fd).
/// Called on daemon shutdown before unmounting the filesystem that holds
/// the cache; harmless otherwise (read tracking is best-effort).
pub fn release_cache_read_tracker(&self) {
self.cache.release_read_tracker();
}
/// Initializes a bunch of internals and returns them. Use
/// [`DaemonContext::init`] instead unless you are `minimal init`,
/// which needs to use these before a full context can be built.
pub fn sub_setup(config: &Config) -> Result<(VcsManagerHandle, Cache, PathBuf), Error> {
// Upsert dirs
use std::fs::create_dir_all;
create_dir_all(config.downloads_dir())
.map_err(|e| Error::setup_dirs(e, config.downloads_dir()))?;
create_dir_all(config.builds_base_dir())
.map_err(|e| Error::setup_dirs(e, config.builds_base_dir()))?;
create_dir_all(config.built_cache_dir())
.map_err(|e| Error::setup_dirs(e, config.built_cache_dir()))?;
create_dir_all(config.state_base_dir())
.map_err(|e| Error::setup_dirs(e, config.state_base_dir()))?;
create_dir_all(config.task_base_dir())
.map_err(|e| Error::setup_dirs(e, config.task_base_dir()))?;
create_dir_all(config.vcs_dir()).map_err(|e| Error::setup_dirs(e, config.vcs_dir()))?;
create_dir_all(config.index_dir()).map_err(|e| Error::setup_dirs(e, config.index_dir()))?;
create_dir_all(config.stdlib_dir())
.map_err(|e| Error::setup_dirs(e, config.stdlib_dir()))?;
create_dir_all(config.layer_cache_dir())
.map_err(|e| Error::setup_dirs(e, config.layer_cache_dir()))?;
// Initialize subsystems that are always present/used
let vcs = if let Some(vcs_manager) = config.vcs_manager_override() {
vcs_manager
} else {
// `--offline` flips the VcsManager into offline mode: any clone or fetch
// surfaces as Error::OfflineCacheMiss instead of attempting the network
// operation. Pre-populate `vcs_dir()` for the workflow that needs this.
VcsManager::new_in_dir_with_offline(config.vcs_dir(), config.is_offline())?
};
let cache = Cache::at_dir(config.built_cache_dir())
.map_err(|e| Error::Other(anyhow!("initializing local cache: {}", e)))?;
// Figure out a path to the standard library. Roughly speaking this is loaded from:
// - Any override in the config
// - The version embedded in the binary, stamped to disk
let stdlib_dir = {
if let Some(dir) = config.stdlib_dir_override() {
dir.to_path_buf()
} else {
stdlib::upsert_stdlib_to_disk(config.stdlib_dir()).map_err(|e| {
Error::Other(anyhow!("loading embedded standard library: {}", e))
})?
}
};
Ok((vcs, cache, stdlib_dir))
}
}
impl Context {
/// Initializes a new context using the given configuration.
pub fn new(config: Config) -> Result<Self, Error> {
let strategy = {
match config.repo_dir_override() {
Some(path) => MFileSearchStrategy::Override(path.to_path_buf()),
_ => MFileSearchStrategy::CurrentDirRecursive,
}
};
Self::new_with_strategy(config, strategy)
}
/// Initializes a new context using the given configuration and `strategy` for finding the mfile
/// This is useful when a given command needs to override the behaviour for finding the mfile
pub fn new_with_strategy(config: Config, strategy: MFileSearchStrategy) -> Result<Self, Error> {
let daemon = Arc::new(DaemonContext::init(config)?);
let mfile = strategy.find_mfile()?;
Ok(Self {
daemon,
mfile,
classifier_leaf: None,
box_network: None,
})
}
/// Constructs a new context using the lower-level primitives.
///
/// DO NOT USE unless you know what you are doing - use [Context::new] instead.
pub fn new_from_parts(
config: Config,
mfile: mfile::File,
vcs: VcsManagerHandle,
cache: Cache,
stdlib_dir: PathBuf,
) -> Self {
let daemon = Arc::new(DaemonContext {
config,
stdlib_dir,
vcs,
cache,
});
Self {
daemon,
mfile,
classifier_leaf: None,
box_network: None,
}
}
/// Constructs a `Context` from a shared `DaemonContext` and an
/// already-parsed mfile. Used by daemon-side callers to build
/// per-session contexts against one shared daemon-scoped setup,
/// without repeating the (moderately expensive)
/// [`DaemonContext::init`] work per session.
pub fn from_daemon(daemon: Arc<DaemonContext>, mfile: mfile::File) -> Self {
Self {
daemon,
mfile,
classifier_leaf: None,
box_network: None,
}
}
/// Places every package build this context starts in `leaf`, the
/// classifier leaf of the box the builds run for (NET-155).
#[must_use]
pub fn with_classifier_leaf(mut self, leaf: sandbox::config::ClassifierLeaf) -> Self {
self.classifier_leaf = Some(leaf);
self
}
/// The classifier leaf this context's package builds run in, if any.
pub fn classifier_leaf(&self) -> Option<&sandbox::config::ClassifierLeaf> {
self.classifier_leaf.as_ref()
}
/// Runs every package build this context starts that needs the network
/// on `network`, the network of the own-address box the builds run for
/// (NET-155).
#[must_use]
pub fn with_box_network(mut self, network: op::BuildNetwork) -> Self {
self.box_network = Some(network);
self
}
/// The box network this context's package builds attach to, if any.
pub fn box_network(&self) -> Option<&op::BuildNetwork> {
self.box_network.as_ref()
}
/// Returns a clone of the shared daemon-scoped context. Cheap —
/// just an `Arc` clone. Useful when a caller needs to hand the
/// same daemon-scoped state to another `Context` or subsystem
/// without going through the mfile-loaded superstructure.
pub fn daemon_context(&self) -> Arc<DaemonContext> {
Arc::clone(&self.daemon)
}
}
/// Low-level API
impl Context {
/// Re-reads the minimal file and returns a fresh `Context` on the
/// same shared `Arc<DaemonContext>`. Intended for callers that
/// have mutated the on-disk mfile and want the in-memory copy
/// refreshed; daemon-scoped state (`Config`, `stdlib_dir`, `vcs`,
/// `cache`) is preserved and shared, not rebuilt.
///
/// The reload path mirrors [`Self::repo_dir`]'s resolution order:
/// the currently-loaded mfile's own directory takes precedence
/// (correct for daemon-side callers whose shared `Config` has no
/// per-session repo override), then any config-provided override,
/// then a recursive search from the daemon's cwd as a last-ditch
/// fallback for CLI-style callers that constructed via
/// [`Self::new`].
pub fn cloned_reinit(&self) -> Result<Self, Error> {
let strategy = if let Some(path) = self.mfile.repo_path() {
MFileSearchStrategy::Override(path.to_path_buf())
} else if let Some(path) = self.daemon.config.repo_dir_override() {
MFileSearchStrategy::Override(path.to_path_buf())
} else {
MFileSearchStrategy::CurrentDirRecursive
};
let mfile = strategy.find_mfile()?;
Ok(Self {
classifier_leaf: self.classifier_leaf.clone(),
box_network: self.box_network.clone(),
..Self::from_daemon(Arc::clone(&self.daemon), mfile)
})
}
/// Builds a [`ProjectSetup`] from this context, for running project-setup
/// operations (e.g. [`op::UpdateProject`]) that refresh the `minimal.toml`.
pub fn project_setup(&self) -> Result<ProjectSetup, Error> {
Ok(ProjectSetup::from_parts(
self.daemon.config.clone(),
self.daemon.vcs.clone(),
self.daemon.stdlib_dir.clone(),
self.mfile.clone(),
self.repo_dir()?.to_path_buf(),
))
}
/// Returns a handle to the local cache.
pub fn local_cache(&self) -> Cache {
self.daemon.cache.clone()
}
/// Returns the vcs manager.
pub fn vcs_manager(&self) -> VcsManagerHandle {
self.daemon.vcs.clone()
}
/// Returns the daemon ID, if one was configured.
pub fn daemon_id(&self) -> Option<String> {
self.daemon.config.daemon_id()
}
/// Returns true if the context is configured to use the local cache.
pub fn use_local_cache(&self) -> bool {
self.daemon.config.use_local_cache()
}
/// Returns true if the context is configured to use a remote cache.
pub fn use_remote_cache(&self) -> bool {
self.daemon.config.use_remote_cache()
}
/// Returns the base directory for build sandboxes.
pub fn builds_base_dir(&self) -> PathBuf {
self.daemon.config.builds_base_dir()
}
/// Returns the base directory for task sandboxes.
pub fn tasks_base_dir(&self) -> PathBuf {
self.daemon.config.task_base_dir()
}
/// Returns the base directory for the artifact/binary cache.
///
/// DO NOT USE unless you really know what you
/// are doing - prefer [Context::local_cache] instead.
pub fn cache_base_dir(&self) -> PathBuf {
self.daemon.config.built_cache_dir()
}
/// Returns the base directory where source checkouts are stored.
pub fn vcs_dir(&self) -> PathBuf {
self.daemon.config.vcs_dir()
}
/// Returns the base directory where the remote index is cached.
pub fn index_dir(&self) -> PathBuf {
self.daemon.config.index_dir()
}
/// Returns the directory where compiled layers are cached.
pub fn layer_cache_dir(&self) -> PathBuf {
self.daemon.config.layer_cache_dir()
}
/// Returns the path to the root of the repo.
///
/// The repo root is the minimal file's own directory when it has an on-disk
/// location, else the configured `-C` override. When neither is available —
/// the minimal file was decoded without a path and no override is set —
/// there is no repo root to name, so this reports it rather than panicking.
pub fn repo_dir(&self) -> Result<&Path, Error> {
self.mfile
.repo_path()
.or_else(|| self.daemon.config.repo_dir_override())
.ok_or_else(|| {
Error::Other(anyhow!(
"cannot determine the repository directory: the location of \
the minimal file on disk is unknown and no repository \
directory override is set"
))
})
}
/// Returns a path to the standard library.
pub fn stdlib_dir(&self) -> &PathBuf {
&self.daemon.stdlib_dir
}
/// Returns the minimal file configuring this context.
///
/// This usually maps to a `minimal.toml` read from disk,
/// but not always. Methods like [`mfile::File::repo_path`]
/// return None if not read from disk.
pub fn minimal_file(&self) -> &mfile::File {
&self.mfile
}
/// Builds and returns a remote cache reader for the configured cache
/// location. [Config] has already resolved where artifacts come from — a GCS
/// bucket (the default) or an HTTPS mirror (honouring
/// `MINIMAL_REMOTE_CACHE_URL`) — and the minimal file resolves *which index
/// object* to read ([`mfile::File::cache_config`], overridable via
/// `MINIMAL_INDEX_SOURCE`), so this just wires up the matching backend and
/// follows those instructions.
///
/// `auth` selects authenticated vs. anonymous GCS access (the buildbot / mip
/// upload path reads authed; anonymous CI reads use the public path). It's
/// ignored for an HTTPS mirror, whose objects are fetched with unauthenticated
/// public GETs.
pub async fn remote_cache(
&self,
auth: bool,
force_fresh: bool,
) -> Result<RemoteCache<AnyBackend>, RemoteError<AnyRespError>> {
let start = SystemTime::now();
let index_dir = if force_fresh {
None
} else {
Some(self.daemon.config.index_dir())
};
// A GCS location needs a Storage client (authed or anonymous per `auth`);
// an HTTPS mirror (e.g. a Cloudflare R2 custom domain) needs none —
// new_any builds a reqwest client internally. Note it's reading from R2
// that avoids GCS egress cost: an https:// URL still pointed at GCS would
// egress just the same.
let url = self.daemon.config.remote_cache_url();
let gcs_storage = if matches!(url, AnyUrl::Gcs(_)) {
let backend = if auth {
GcsStorage::builder()
.build()
.await
.map_err(|e| RemoteError::Config(format!("initializing GCS storage: {e}")))?
} else {
GcsStorage::builder()
.with_credentials(
google_cloud_auth::credentials::anonymous::Builder::new().build(),
)
.build()
.await
.map_err(|e| RemoteError::Config(format!("initializing GCS storage: {e}")))?
};
Some(backend)
} else {
None
};
// Rollout lever: overrides the file setting while per-commit reads
// bed in. Retire (env var first, then likely the file setting) once
// snapshot reads are the settled default.
let override_mode = match std::env::var("MINIMAL_INDEX_SOURCE") {
Ok(v) => Some(
v.parse::<mfile::IndexSourceMode>()
.map_err(|e| RemoteError::Config(format!("MINIMAL_INDEX_SOURCE: {e}")))?,
),
Err(std::env::VarError::NotPresent) => None,
// A set-but-garbled override must be loud, like any other bad value.
Err(e) => return Err(RemoteError::Config(format!("MINIMAL_INDEX_SOURCE: {e}"))),
};
let config = self
.mfile
.cache_config(override_mode)
.map_err(RemoteError::Config)?;
let res = RemoteCache::new_any_configured(
url,
gcs_storage,
index_dir,
self.daemon.config.ot.clone(),
&config,
)
.await;
let fetch_retries = match std::env::var("MINIMAL_FETCH_RETRIES") {
Ok(v) => v
.parse::<u32>()
.map_err(|e| RemoteError::Config(format!("MINIMAL_FETCH_RETRIES: {e}")))?,
Err(std::env::VarError::NotPresent) => self
.mfile
.cache
.fetch_retries
.unwrap_or(rcache::DEFAULT_FETCH_RETRIES),
// A set-but-garbled override must be loud, like any other bad value.
Err(e) => return Err(RemoteError::Config(format!("MINIMAL_FETCH_RETRIES: {e}"))),
};
let res = res.map(|rc| rc.with_fetch_retries(fetch_retries));
tracing::trace!("remote cache init took {:?}", start.elapsed());
res
}
/// Builds a writer for the shared cache. Always uses authenticated GCS
/// access and always fetches the index fresh (no local-cache fast path) —
/// the writer's compare-and-swap on commit requires the GCS generation
/// it observed, which a stale local index can't provide.
///
/// Errors if the cache is configured as an HTTPS read mirror: a mirror (e.g.
/// R2 via a custom domain) has no writable bucket, so there's nowhere to
/// upload. Writes require a `gs://` bucket location.
pub async fn remote_cache_writer(&self) -> anyhow::Result<RemoteCacheWriter> {
let start = SystemTime::now();
let bucket = self
.daemon
.config
.remote_cache_write_bucket()
.ok_or_else(|| {
anyhow!(
"remote cache is configured as an HTTPS read mirror; writes \
require a gs:// bucket — set the cache location to a gs:// URL \
or a bare bucket name"
)
})?;
let backend = GcsStorage::builder()
.build()
.await
.map_err(|e| anyhow::anyhow!("initializing GCS storage: {e}"))?;
let res = RemoteCacheWriter::new(backend, bucket, self.daemon.config.ot.clone()).await?;
tracing::trace!("remote cache writer init took {:?}", start.elapsed());
Ok(res)
}
pub async fn remote_storage(&self) -> Result<common::RemoteStorage, Error> {
let start = SystemTime::now();
// `--offline` flips the underlying FileCache into offline mode so any
// source-URL cache miss surfaces as FileCacheError::OfflineCacheMiss
// rather than a silent network fetch.
let rs = common::RemoteStorage::new_with_offline(
self.daemon.config.downloads_dir(),
false,
self.daemon.config.is_offline(),
)
.await
.map_err(|e| Error::Other(anyhow!("initializing remote storage: {}", e)))?;
tracing::trace!("remote storage init took {:?}", start.elapsed());
Ok(rs)
}
/// Returns a [SpecOrigin] representing the top-level repository.
pub fn repo_origin(&self) -> Result<SpecOrigin, Error> {
Ok(SpecOrigin::from_dir(self.repo_dir()?))
}
/// Returns the [OpTracker] to be used as the root for tracking long-running operations.
pub fn op_tracker(&self) -> Option<OpTracker> {
self.daemon.config.ot.clone()
}
/// Builds & returns the graph with the given packages specified as top levels.
pub fn graph_from_package_names<S: PackageSelection>(
&mut self,
pkgs: S,
) -> Result<Graph, Error> {
let mut graph = self.graph_from_all_packages()?;
graph.top_levels = pkgs.as_bsrs(&graph)?;
Ok(graph)
}
/// Builds & returns a graph of all packages.
pub fn graph_from_all_packages(&mut self) -> Result<Graph, Error> {
self.graph_from_all_packages_with_target(Target::host())
}
/// Builds & returns a graph of all packages for a specific target.
pub fn graph_from_all_packages_with_target(&mut self, target: Target) -> Result<Graph, Error> {
let start = SystemTime::now();
let repo_dir = self.repo_dir()?;
let res = Graph::new_from_chain(
self.vcs_manager(),
&mut graph::LayerCacheDir(self.daemon.config.layer_cache_dir()),
LinkConfig::Dir {
dir: repo_dir
.to_str()
.ok_or_else(|| {
Error::Other(anyhow!(
"repo path is not valid UTF-8: {}",
repo_dir.display()
))
})?
.to_string(),
},
self.daemon.stdlib_dir.clone(),
target,
)
.map_err(|e| e.into());
tracing::trace!("graph parse/load took {:?}", start.elapsed());
res
}
/// Builds & returns the graph with the given packages for a specific target.
pub fn graph_from_package_names_with_target<S: PackageSelection>(
&mut self,
pkgs: S,
target: Target,
) -> Result<Graph, Error> {
let mut graph = self.graph_from_all_packages_with_target(target)?;
graph.top_levels = pkgs.as_bsrs(&graph)?;
Ok(graph)
}
}
/// Outcome-oriented API
impl Context {
/// Ensures the top-level packages of the given graph are built and available locally.
///
/// Use [Context::download_if_available] if you want to only fetch packages.
pub async fn build_graph(
&mut self,
graph: &Graph,
rebuild_top_level: bool,
log_sink: Option<futures::channel::mpsc::UnboundedSender<orchestrator::BuildEvent>>,
) -> Result<(), Error> {
self.build_graph_with_cancel(
graph,
rebuild_top_level,
log_sink,
tokio_util::sync::CancellationToken::new(),
)
.await
}
/// The orchestrator this context builds `graph` with. It carries the
/// context's classifier leaf (NET-155), so every spec build it schedules
/// runs in the leaf of the box the context was made for.
async fn local_orchestrator(
&self,
graph: &Graph,
rc: Option<RemoteCache<common::fetchers::AnyBackend>>,
log_sink: Option<futures::channel::mpsc::UnboundedSender<orchestrator::BuildEvent>>,
cancel: tokio_util::sync::CancellationToken,
) -> Result<orchestrator::Orchestrator<orchestrator::LocalBackend<common::RemoteStorage>>, Error>
{
Ok(orchestrator::LocalBackend::new_orchestrator(
self.daemon.config.builds_base_dir(),
rc,
self.remote_storage().await?,
self.daemon.config.num_parallel_builds(),
graph.clone(),
self.local_cache(),
self.daemon_id(),
log_sink,
self.daemon.config.ot.clone(),
cancel,
self.classifier_leaf.clone(),
self.box_network.clone(),
)?)
}
pub async fn build_graph_with_cancel(
&mut self,
graph: &Graph,
rebuild_top_level: bool,
log_sink: Option<futures::channel::mpsc::UnboundedSender<orchestrator::BuildEvent>>,
cancel: tokio_util::sync::CancellationToken,
) -> Result<(), Error> {
let cache = self.local_cache();
let rc = if self.daemon.config.use_remote_cache() {
Some(self.remote_cache(false, false).await?)
} else {
None
};
// Specs the remote index lists but whose artifact the store no longer
// has (a dangling hit, inbox#535). The planner trusts the index, so
// such a spec is planned as a cache fill with no build behind it; the
// fill reports the miss and the graph is planned again with the spec
// masked out of every cache, which makes it a build like any other
// miss. Each pass masks one more spec, so the loop is bounded by the
// graph.
let mut dangling: Vec<BuildSpecRef> = Vec::new();
loop {
use orchestrator::LocalBackend;
let orchestrator = self
.local_orchestrator(graph, rc.clone(), log_sink.clone(), cancel.clone())
.await?;
let mut bin_provider: Box<dyn BinProvider> = match (
self.daemon.config.use_local_cache(),
self.daemon.config.use_remote_cache(),
) {
// No local or remote cache
(false, false) => Box::new(()),
// Both caches
(true, true) => {
let local_adapter = CacheBinProvider::new(graph, cache.clone());
let remote_adapter = RemoteBinProvider::new(graph, rc.as_ref().unwrap());
Box::new((local_adapter, remote_adapter))
}
// Only remote cache
(false, true) => Box::new(RemoteBinProvider::new(graph, rc.as_ref().unwrap())),
// Only local cache
(true, false) => Box::new(CacheBinProvider::new(graph, cache.clone())),
};
if rebuild_top_level {
// Forcing a rebuild of named packages was requested. To do this, we wrap the BinProvider
// with one that pretends the named packages are never in any cache, resulting in a build for them.
bin_provider = Box::new(MaskingBinProvider::new(
bin_provider,
graph.top_levels.clone(),
));
}
if !dangling.is_empty() {
bin_provider = Box::new(MaskingBinProvider::new(
bin_provider,
dangling.iter().copied(),
));
}
let (built, result) = LocalBackend::run_local_build(orchestrator, bin_provider).await;
// commit all built artifacts to the local cache
for (pending_dir, meta) in built {
pending_dir
.finalize(meta)
.map_err(|e| Error::Other(e.into()))?;
}
match result {
Ok(()) => return Ok(()),
Err(orchestrator::Error::DanglingCacheHit(hits))
if hits.iter().all(|b| !dangling.contains(b)) =>
{
for bsr in hits {
let spec = graph.get(&bsr).map(|b| b.name.as_str()).unwrap_or("?");
tracing::warn!(
kind = "dangling_replan",
spec,
"the remote cache lists a package the store no longer has; building it locally"
);
dangling.push(bsr);
}
}
// propagate any other error (a dangling hit on a spec already
// masked cannot happen: a masked spec is never a cache fill)
Err(e) => return Err(e.into()),
}
}
}
pub fn iter_tasks(&self, graph: &Graph) -> Vec<(String, TaskSource)> {
let mut out: Vec<_> = self
.mfile
.iter_tasks()
.map(|(name, _t)| (name.clone(), TaskSource::MFile))
.collect();
if let Some(h_conf) = &self.mfile.stack
&& let Some(stack) = graph.stack(&h_conf.name)
{
out.extend(stack.task_names().into_iter().filter_map(|name| {
if self.mfile.task(&name).is_some() {
// Already capture by iter_tasks() above
None
} else {
Some((name.to_string(), TaskSource::Stack(h_conf.name.clone())))
}
}));
}
out
}