Repository navigation
Expand file tree
/
Copy pathclient.rs
More file actions
2845 lines (2429 loc) · 92.6 KB
/
Copy pathclient.rs
File metadata and controls
2845 lines (2429 loc) · 92.6 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
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod dist {
pub use crate::config::dist::Keepalive;
pub use crate::config::dist::client::*;
}
use crate::{
config::{
Loadable, Valid,
cache::{Azure, AzureAuth, Cache, Caches},
utils::{deserialize_basedirs, deserialize_bool, serialize_basedirs},
},
errors::*,
};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeSet, HashMap},
ffi::{OsStr, OsString},
fmt,
path::PathBuf,
sync::{LazyLock, Mutex},
};
use typed_path::Utf8TypedPathBuf;
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct Config {
/// Object cache configs
#[serde(default)]
pub cache: Caches,
/// Base directory (or directories) to strip from paths for cache key computation.
/// Similar to ccache's CCACHE_BASEDIR.
#[serde(
default,
deserialize_with = "deserialize_basedirs",
serialize_with = "serialize_basedirs"
)]
pub basedirs: Basedirs,
/// Distributed compilation configuration
#[serde(default)]
pub dist: dist::Config,
/// The number of milliseconds to wait for server startup.
#[serde(default = "defaults::default_server_startup_timeout")]
pub server_startup_timeout_ms: u64,
#[serde(default, deserialize_with = "deserialize_bool")]
pub client_side_mode: bool,
}
impl Config {
pub fn load() -> crate::errors::Result<Self> {
Self::from_envs_and_path::<_, _, _, PathBuf>(std::env::vars_os(), None)
}
pub fn load_from_envs<I, S>(vars: I) -> crate::errors::Result<Self>
where
I: IntoIterator<Item = (S, S)>,
S: AsRef<OsStr> + Clone,
{
Self::from_envs_and_path::<I, S, _, PathBuf>(vars, None)
}
fn ensure_default_disk_cache(mut self) -> Result<Self> {
if !self.cache.configs.iter().any(|(_, c)| c.enabled()) {
if let Some((disk_cache_name, disk_cache)) =
self.cache
.configs
.iter_mut()
.find_map(|(name, cache)| match cache {
Cache::Disk(cache) => Some((name, cache)),
_ => None,
})
{
disk_cache.enabled = true;
self.cache.multilevel.chain = Some(vec![disk_cache_name.clone()]);
} else {
self.cache
.configs
.insert("disk".into(), crate::config::cache::Disk::default().into());
self.cache.multilevel.chain = Some(vec!["disk".into()]);
}
}
Ok(self)
}
}
impl_add_for_config! { Config }
// Delegate Default to #[serde(default)]
impl Default for Config {
fn default() -> Self {
serde_json::from_str("{}").unwrap()
}
}
impl AsRef<Config> for Config {
fn as_ref(&self) -> &Config {
self
}
}
impl Valid for Config {
fn validate_merged(mut self, orig: &Self) -> Result<Self> {
for (name, orig_cache) in orig.cache.configs.iter() {
if !self.cache.configs.contains_key(name) {
self.cache.configs.insert(name.clone(), orig_cache.clone());
}
}
self.cache.validate_storage_levels(
if self.cache.multilevel.chain.as_deref() == orig.cache.multilevel.chain.as_deref() {
"cache.multilevel.chain"
} else {
"SCCACHE_CACHE_MULTILEVEL_CHAIN"
},
)?;
self.ensure_default_disk_cache()
}
fn validate_file(self) -> Result<Self> {
self.cache
.validate_storage_levels("cache.multilevel.chain")?;
self.ensure_default_disk_cache()
}
fn validate_vars(self) -> Result<Self> {
self.cache
.validate_storage_levels("SCCACHE_CACHE_MULTILEVEL_CHAIN")?;
self.ensure_default_disk_cache()
}
}
impl Loadable<Self> for Config {
fn env_prefix<'a>() -> Option<&'a str> {
Some("SCCACHE")
}
fn from_vars<I, S>(vars: I) -> Result<Self>
where
I: IntoIterator<Item = (S, S)>,
S: AsRef<OsStr>,
{
let mut conf = Self::from_vars_impl(vars)?;
// Remove Azure configs that don't have an auth mechanism
conf.cache.configs.retain(|name, cache| match cache {
Cache::Azure(Azure { auth, .. }) => {
if matches!(auth, AzureAuth::None) {
if let Some(chain) = conf.cache.multilevel.chain.as_mut()
&& let Ok(idx) = chain.binary_search(name)
{
chain.remove(idx);
}
false
} else {
true
}
}
_ => true,
});
Ok(conf)
}
fn select_vars<Iter, S>(vars: Iter) -> Result<impl IntoIterator<Item = (String, String)>>
where
Iter: IntoIterator<Item = (S, S)>,
S: AsRef<OsStr>,
{
use crate::util::os_str_to_str;
// Rewrite env vars to match this struct:
// * SCCACHE_BUCKET/SCCACHE_REGION map to an S3 cache:
// SCCACHE_BUCKET -> SCCACHE_CACHE_S3_BUCKET
// SCCACHE_REGION -> SCCACHE_CACHE_S3_REGION
// * Other S3 fields are prefixed with `SCCACHE_S3_`
// SCCACHE_S3_KEY_PREFIX -> SCCACHE_CACHE_S3_KEY_PREFIX
// * Other cache types are available as top-level envvars:
// SCCACHE_GCS_BUCKET -> SCCACHE_CACHE_GCS_BUCKET
let prefix_ = Self::env_prefix().map_or_else(
|| "SCCACHE_".into(),
|prefix| {
if prefix.ends_with("_") {
prefix.into()
} else {
format!("{prefix}_")
}
},
);
let caches_ = [
"AZURE_",
"DISK_",
"GCS_",
"GHA_",
"MEMCACHED_",
"REDIS_",
"S3_",
"WEBDAV_",
"OSS_",
"COS_",
"MULTILEVEL_",
];
let vars = vars
.into_iter()
.map(|(key, val)| -> Result<Vec<(String, String)>> {
let key = os_str_to_str(key.as_ref())?;
let val = os_str_to_str(val.as_ref())?;
// Only take vars that start with `SCCACHE_`
let key = if let Some(key) = key.strip_prefix(&prefix_) {
key
} else {
return Ok(vec![]);
};
let key = match key {
// SCCACHE_DIR -> SCCACHE_CACHE_DISK_DIR
"DIR" => "DISK_DIR",
// SCCACHE_LOCAL_RW_MODE -> SCCACHE_CACHE_DISK_RW_MODE
"LOCAL_RW_MODE" => "DISK_RW_MODE",
// SCCACHE_CACHE_SIZE -> SCCACHE_CACHE_DISK_SIZE
"CACHE_SIZE" => "DISK_SIZE",
// SCCACHE_BUCKET -> SCCACHE_CACHE_S3_BUCKET
"BUCKET" => "S3_BUCKET",
// SCCACHE_ENDPOINT -> SCCACHE_CACHE_S3_ENDPOINT
"ENDPOINT" => "S3_ENDPOINT",
// SCCACHE_REGION -> SCCACHE_CACHE_S3_REGION
"REGION" => "S3_REGION",
// SCCACHE_REDIS -> SCCACHE_CACHE_REDIS_URL
"REDIS" => "REDIS_URL",
// SCCACHE_MEMCACHED -> SCCACHE_CACHE_MEMCACHED_URL
"MEMCACHED" => "MEMCACHED_URL",
_ => key,
};
if key == "SKIP_CACHE_CHECK" {
// SCCACHE_SKIP_CACHE_CHECK -> SCCACHE_CACHE_SKIP_CHECK
let key = "CACHE_SKIP_CHECK".to_owned();
return Ok(vec![(key, val.into_owned())]);
}
if key == "SERVER_STARTUP_TIMEOUT" {
// SCCACHE_SERVER_STARTUP_TIMEOUT -> SCCACHE_SERVER_STARTUP_TIMEOUT_SECS
let key = "SERVER_STARTUP_TIMEOUT_MS".to_owned();
return Ok(vec![(key, val.into_owned())]);
}
if let Some(suf) = key.strip_prefix("DIST_") {
if matches!(
suf,
"CONNECT_TIMEOUT"
| "REQUEST_TIMEOUT"
| "CONNECTION_POOL"
| "MAX_CONNECTIONS"
) {
// SCCACHE_DIST_CONNECT_TIMEOUT -> SCCACHE_DIST_NET_CONNECT_TIMEOUT
// SCCACHE_DIST_REQUEST_TIMEOUT -> SCCACHE_DIST_NET_REQUEST_TIMEOUT
// SCCACHE_DIST_CONNECTION_POOL -> SCCACHE_DIST_NET_CONNECTION_POOL
// SCCACHE_DIST_MAX_CONNECTIONS -> SCCACHE_DIST_NET_MAX_CONNECTIONS
let key = format!("DIST_NET_{suf}");
return Ok(vec![(key, val.into_owned())]);
}
if let Some(key) = suf.strip_prefix("KEEPALIVE_") {
// SCCACHE_DIST_KEEPALIVE_ENABLED -> SCCACHE_DIST_NET_KEEPALIVE_ENABLED
let key = format!("DIST_NET_KEEPALIVE_{key}");
return Ok(vec![(key, val.into_owned())]);
}
if matches!(suf, "SCHEDULER_URL") {
// SCCACHE_DIST_SCHEDULER_URL -> SCCACHE_DIST_URL
let key = "DIST_URL".to_owned();
return Ok(vec![(key, val.into_owned())]);
}
return Ok(vec![(key.into(), val.into_owned())]);
}
if matches!(key, "CACHE_READ_TIMEOUT" | "CACHE_WRITE_TIMEOUT") {
// SCCACHE_CACHE_READ_TIMEOUT -> SCCACHE_CACHE_READ_TIMEOUT_SECS
// SCCACHE_CACHE_WRITE_TIMEOUT -> SCCACHE_CACHE_WRITE_TIMEOUT_SECS
let key = format!("{key}_SECS");
return Ok(vec![(key, val.into_owned())]);
}
if let Some((kind, mut key)) = caches_.iter().find_map(|kind_| {
if let Some(key) = key.strip_prefix(kind_) {
kind_.strip_suffix("_").map(|kind| (kind, key))
} else {
None
}
}) {
if kind == "AZURE" && key == "BLOB_CONTAINER" {
// SCCACHE_AZURE_BLOB_CONTAINER -> SCCACHE_AZURE_CONTAINER
key = "CONTAINER";
}
// SCCACHE_AZURE_CONNECTION_STRING -> SCCACHE_CACHE_AZURE_CONNECTION_STRING
// SCCACHE_S3_KEY_PREFIX -> SCCACHE_CACHE_S3_KEY_PREFIX
// SCCACHE_GCS_BUCKET -> SCCACHE_CACHE_GCS_BUCKET
// SCCACHE_MULTILEVEL_CHAIN -> SCCACHE_CACHE_MULTILEVEL_CHAIN
// etc.
let key = format!("CACHE_{kind}_{key}");
return Ok(vec![(key, val.into_owned())]);
}
Ok(vec![(key.into(), val.into_owned())])
})
.flatten_ok()
.try_collect::<_, Vec<_>, _>()?;
if !vars.is_empty() {
// trace! because envvars might include secrets.
// SCCACHE_LOG=debug is the lowest recommended log level in CI.
trace!(
"Building client config from env:\n{}",
vars.iter()
.map(|(k, v)| format!("{prefix_}{k} = \"{v}\""))
.join("\n")
);
}
Ok(vars)
}
}
#[derive(Clone, Default, PartialEq, Deserialize, Serialize)]
pub struct Basedirs(Option<Vec<PathBuf>>, #[serde(skip)] Option<Vec<Vec<u8>>>);
impl Basedirs {
pub fn empty() -> Self {
Self(Some(vec![]), Some(vec![]))
}
pub fn is_none(&self) -> bool {
self.0.is_none()
}
pub fn is_some(&self) -> bool {
self.0.is_some()
}
pub fn is_empty(&self) -> bool {
self.1.as_deref().unwrap_or_default().is_empty()
}
}
impl From<Basedirs> for Vec<PathBuf> {
fn from(basedirs: Basedirs) -> Self {
basedirs.0.unwrap_or_default()
}
}
impl From<Basedirs> for Vec<Vec<u8>> {
fn from(basedirs: Basedirs) -> Self {
basedirs.1.unwrap_or_default()
}
}
impl AsRef<[PathBuf]> for Basedirs {
#[inline]
fn as_ref(&self) -> &[PathBuf] {
self.0.as_deref().unwrap_or_default()
}
}
impl AsRef<[Vec<u8>]> for Basedirs {
#[inline]
fn as_ref(&self) -> &[Vec<u8>] {
self.1.as_deref().unwrap_or_default()
}
}
impl std::ops::Deref for Basedirs {
type Target = [Vec<u8>];
#[inline]
fn deref(&self) -> &[Vec<u8>] {
self.1.as_deref().unwrap_or_default()
}
}
impl fmt::Debug for Basedirs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"[{}]",
self.0
.as_deref()
.unwrap_or_default()
.iter()
.map(|p| format!("{p:?}"))
.join(", ")
)
}
}
impl fmt::Display for Basedirs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"[{}]",
self.0
.as_deref()
.unwrap_or_default()
.iter()
.map(|p| format!("{}", p.display()))
.join(", ")
)
}
}
impl PartialEq<Vec<Vec<u8>>> for Basedirs {
fn eq(&self, rhs: &Vec<Vec<u8>>) -> bool {
self.1.as_deref().unwrap_or_default() == rhs
}
}
impl From<Vec<Vec<u8>>> for Basedirs {
fn from(basedirs: Vec<Vec<u8>>) -> Self {
Basedirs::try_from(
basedirs
.into_iter()
.map(|b| String::from_utf8(b).map(PathBuf::from).unwrap())
.collect::<Vec<_>>(),
)
.unwrap()
}
}
impl From<Vec<String>> for Basedirs {
fn from(basedirs: Vec<String>) -> Self {
Basedirs::try_from(basedirs.into_iter().map(PathBuf::from).collect::<Vec<_>>()).unwrap()
}
}
impl From<Vec<OsString>> for Basedirs {
fn from(basedirs: Vec<OsString>) -> Self {
Basedirs::try_from(basedirs.into_iter().map(PathBuf::from).collect::<Vec<_>>()).unwrap()
}
}
impl<'a> From<Vec<&'a str>> for Basedirs {
fn from(basedirs: Vec<&'a str>) -> Self {
Basedirs::try_from(basedirs.into_iter().map(PathBuf::from).collect::<Vec<_>>()).unwrap()
}
}
impl<'a> From<Vec<&'a OsStr>> for Basedirs {
fn from(basedirs: Vec<&'a OsStr>) -> Self {
Basedirs::try_from(basedirs.into_iter().map(PathBuf::from).collect::<Vec<_>>()).unwrap()
}
}
impl<const N: usize> From<[&str; N]> for Basedirs {
fn from(basedirs: [&str; N]) -> Self {
Basedirs::try_from(basedirs.into_iter().map(PathBuf::from).collect::<Vec<_>>()).unwrap()
}
}
impl<'a> From<&'a [&'a str]> for Basedirs {
fn from(basedirs: &'a [&'a str]) -> Self {
Basedirs::try_from(basedirs.iter().map(PathBuf::from).collect::<Vec<_>>()).unwrap()
}
}
impl<'a> From<&'a [&'a OsStr]> for Basedirs {
fn from(basedirs: &'a [&'a OsStr]) -> Self {
Basedirs::try_from(basedirs.iter().map(PathBuf::from).collect::<Vec<_>>()).unwrap()
}
}
impl TryFrom<Vec<PathBuf>> for Basedirs {
type Error = anyhow::Error;
fn try_from(basedirs: Vec<PathBuf>) -> Result<Self> {
basedirs
.into_iter()
.filter(|path| !path.as_os_str().is_empty())
.map(|orig| {
if !orig.is_absolute() {
bail!("Basedir path must be absolute: {orig:?}");
}
let path = crate::util::path_to_str(&orig)?;
// Normalize basedir:
// remove double separators, cur_dirs, parent_dirs, trailing slashes
let path = Utf8TypedPathBuf::from(path.as_ref()).normalize();
let path = path.as_str().as_bytes();
#[cfg(not(target_os = "windows"))]
let mut path = path.to_vec();
#[cfg(target_os = "windows")]
// normalize windows paths: use slashes and lowercase
let mut path = crate::util::normalize_win_path(path);
// Always add a trailing `/` to basedirs to ensure we only match complete path
// components
if !matches!(path.last(), Some(b'/')) {
path.push(b'/');
}
Ok((crate::util::bytes_to_path(&path)?.to_path_buf(), path))
})
// Only take unique paths
.try_collect::<_, (BTreeSet<_>, BTreeSet<_>), _>()
.map(|(orig, bufs)| {
Self(
Some(orig.into_iter().collect()),
Some(bufs.into_iter().collect()),
)
})
}
}
static CACHED_CONFIG_PATH: LazyLock<PathBuf> = LazyLock::new(CachedConfig::file_config_path);
static CACHED_CONFIG: Mutex<Option<CachedFileConfig>> = Mutex::new(None);
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct CachedDistConfig {
pub auth_tokens: HashMap<String, String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct CachedFileConfig {
pub dist: CachedDistConfig,
}
#[derive(Debug, Default, PartialEq, Eq)]
pub struct CachedConfig(());
impl CachedConfig {
pub fn load() -> Result<Self> {
let mut cached_file_config = CACHED_CONFIG.lock().unwrap();
if cached_file_config.is_none() {
let cfg = Self::load_file_config().context("Unable to initialise cached config")?;
*cached_file_config = Some(cfg);
}
Ok(CachedConfig(()))
}
pub fn reload() -> Result<Self> {
{
let mut cached_file_config = CACHED_CONFIG.lock().unwrap();
*cached_file_config = None;
};
Self::load()
}
pub fn with<F: FnOnce(&CachedFileConfig) -> T, T>(&self, f: F) -> T {
let cached_file_config = CACHED_CONFIG.lock().unwrap();
let cached_file_config = cached_file_config.as_ref().unwrap();
f(cached_file_config)
}
pub fn with_mut<F: FnOnce(&mut CachedFileConfig)>(&self, f: F) -> Result<()> {
let mut cached_file_config = CACHED_CONFIG.lock().unwrap();
let cached_file_config = cached_file_config.as_mut().unwrap();
let mut new_config = cached_file_config.clone();
f(&mut new_config);
Self::save_file_config(&new_config)?;
*cached_file_config = new_config;
Ok(())
}
pub fn file_config_path() -> PathBuf {
crate::config::utils::config_file("SCCACHE_CACHED_CONF", "cached-config")
}
fn load_file_config() -> Result<CachedFileConfig> {
use fs_err as fs;
let file_conf_path = &*CACHED_CONFIG_PATH;
if !file_conf_path.exists() {
let file_conf_dir = file_conf_path
.parent()
.expect("Cached conf file has no parent directory");
if !file_conf_dir.is_dir() {
fs::create_dir_all(file_conf_dir)
.context("Failed to create dir to hold cached config")?;
}
Self::save_file_config(&Default::default()).with_context(|| {
format!(
"Unable to create cached config file at {}",
file_conf_path.display()
)
})?;
}
crate::config::utils::try_read_config_file(file_conf_path)
.context("Failed to load cached config file")?
.with_context(|| format!("Failed to load from {}", file_conf_path.display()))
}
fn save_file_config(c: &CachedFileConfig) -> Result<()> {
use fs_err::File;
use std::io::Write;
let file_conf_path = &*CACHED_CONFIG_PATH;
let mut file = File::create(file_conf_path).context("Could not open config for writing")?;
file.write_all(toml::to_string(c).unwrap().as_bytes())
.map_err(Into::into)
}
}
pub mod defaults {
pub use crate::config::defaults::default_disk_cache_size;
pub fn default_server_startup_timeout() -> u64 {
10_000
}
}
#[cfg(test)]
mod test {
use super::*;
#[cfg(any(feature = "dist-client", feature = "dist-server"))]
use crate::config::utils::HTTPUrl;
use crate::config::{
WriteErrorPolicy,
cache::{
Azure, AzureAuth, COS, Cache, CacheMode, Disk, GCS, GHA, Memcached, MultiLevel, OSS,
Redis, S3, Webdav,
},
};
use serial_test::serial;
use std::{collections::BTreeMap, ffi::OsString, str::FromStr};
#[test]
fn config_from_vars() -> Result<()> {
drop(env_logger::try_init());
#[cfg(not(target_os = "windows"))]
let (basedirs, dirs_delim) = { (["/home/user/project", "/home/user/workspace"], ":") };
#[cfg(target_os = "windows")]
let (basedirs, dirs_delim) = { (["C:/home/user/project", "C:/home/user/workspace"], ";") };
let mut config = Config {
basedirs: basedirs.into(),
cache: vec![
COS::from_bucket("cos").into(),
OSS::from_bucket("oss").into(),
Webdav::from_endpoint("http://webdav:1234").into(),
Azure {
auth: AzureAuth::SharedKey {
connection_string: "connection-string".into(),
},
..Azure::from_container("azure")
}
.into(),
GHA::from_version("").into(),
GCS::from_bucket("gcs").into(),
Memcached::from_url("memcached://memcached:1234").into(),
Redis::from_url("redis://redis:1234").into(),
S3::from_bucket("s3").into(),
Disk::default().into(),
]
.into(),
dist: dist::Config {
auth: dist::Auth::Token {
token: "hello-world".into(),
},
cache_dir: "/home/user/.cache/sccache/dist".into(),
fallback_to_local_compile: false,
max_retries: f64::INFINITY.into(),
net: dist::Networking {
connect_timeout: 60,
request_timeout: 1200,
connection_pool: false,
max_connections: 100,
keepalive: dist::Keepalive {
enabled: true,
interval: 10,
timeout: 1200,
},
},
#[cfg(any(feature = "dist-client", feature = "dist-server"))]
url: HTTPUrl::from_str("http://sccache.my-company.com").ok(),
#[cfg(not(any(feature = "dist-client", feature = "dist-server")))]
url: Some("http://sccache.my-company.com".into()),
toolchains: vec![],
toolchain_cache_size: 10_000,
},
server_startup_timeout_ms: 10000,
client_side_mode: true,
};
config.cache.read_timeout_secs = 120;
config.cache.write_timeout_secs = Some(300);
config.cache.skip_check = true;
config.cache.multilevel.write_error_policy = WriteErrorPolicy::All;
config.cache.rate_limit.on_error_count = Some(5);
config.cache.rate_limit.on_error_window_size_secs = Some(5);
let vars = std::iter::empty()
.chain([
("SCCACHE_BASEDIRS", basedirs.join(dirs_delim).as_str()),
("SCCACHE_SKIP_CACHE_CHECK", "true"),
("SCCACHE_CACHE_READ_TIMEOUT_SECS", "120"),
("SCCACHE_CACHE_WRITE_TIMEOUT_SECS", "300"),
("SCCACHE_CACHE_RATE_LIMIT_ON_ERROR_COUNT", "5"),
("SCCACHE_CACHE_RATE_LIMIT_ON_ERROR_WINDOW_SIZE_SECS", "5"),
(
"SCCACHE_MULTILEVEL_CHAIN",
" cos, oss , webdav,azure,gha,gcs,memcached,redis,s3 ,disk",
),
("SCCACHE_MULTILEVEL_WRITE_ERROR_POLICY", "all"),
])
.chain(config.cache.configs.values().flat_map(|cache| match cache {
Cache::Disk(c) => vec![("SCCACHE_DIR", c.dir.to_str().unwrap())],
Cache::S3(c) => vec![("SCCACHE_BUCKET", c.bucket.as_str())],
Cache::Redis(c) => vec![("SCCACHE_REDIS", c.url.as_deref().unwrap())],
Cache::Memcached(c) => vec![("SCCACHE_MEMCACHED", c.url.as_str())],
Cache::GCS(c) => vec![("SCCACHE_GCS_BUCKET", c.bucket.as_str())],
Cache::GHA(_) => vec![("SCCACHE_GHA_ENABLED", "true")],
Cache::Azure(Azure {
container,
auth: AzureAuth::SharedKey { connection_string },
..
}) => {
vec![
("SCCACHE_AZURE_CONTAINER", container.as_str()),
(
"SCCACHE_AZURE_CONNECTION_STRING",
connection_string.as_str(),
),
]
}
Cache::Webdav(c) => {
vec![("SCCACHE_WEBDAV_ENDPOINT", c.endpoint.as_str())]
}
Cache::OSS(c) => vec![("SCCACHE_OSS_BUCKET", c.bucket.as_str())],
Cache::COS(c) => vec![("SCCACHE_COS_BUCKET", c.bucket.as_str())],
_ => vec![],
}))
.chain([
("SCCACHE_DIST_AUTH_TYPE", "token"),
("SCCACHE_DIST_AUTH_TOKEN", "hello-world"),
(
"SCCACHE_DIST_CACHE_DIR",
config.dist.cache_dir.as_path().to_string_lossy().as_ref(),
),
(
"SCCACHE_CACHE_MULTILEVEL_CHAIN",
config
.cache
.multilevel
.chain
.as_deref()
.map(|chain| chain.join(","))
.unwrap_or_default()
.as_str(),
),
("SCCACHE_DIST_FALLBACK_TO_LOCAL_COMPILE", "false"),
("SCCACHE_DIST_MAX_RETRIES", "inf"),
("SCCACHE_DIST_CONNECT_TIMEOUT", "60"),
("SCCACHE_DIST_REQUEST_TIMEOUT", "1200"),
("SCCACHE_DIST_CONNECTION_POOL", "false"),
("SCCACHE_DIST_MAX_CONNECTIONS", "100"),
("SCCACHE_DIST_KEEPALIVE_ENABLED", "true"),
("SCCACHE_DIST_KEEPALIVE_INTERVAL", "10"),
("SCCACHE_DIST_KEEPALIVE_TIMEOUT", "1200"),
("SCCACHE_DIST_URL", "http://sccache.my-company.com"),
("SCCACHE_DIST_TOOLCHAINS", ""),
("SCCACHE_DIST_TOOLCHAIN_CACHE_SIZE", "10000"),
("SCCACHE_SERVER_STARTUP_TIMEOUT_MS", "10000"),
("SCCACHE_CLIENT_SIDE_MODE", "true"),
])
.map(|(key, val)| (key.into(), val.into()))
.collect::<Vec<(OsString, OsString)>>();
let env_conf = Config::from_vars(vars).and_then(|conf| conf.validate_vars())?;
assert_eq!(config.basedirs, env_conf.basedirs);
assert_eq!(config.cache.configs, env_conf.cache.configs);
assert_eq!(config.cache.multilevel, env_conf.cache.multilevel);
assert_eq!(
config.cache.read_timeout_secs,
env_conf.cache.read_timeout_secs
);
assert_eq!(
config.cache.write_timeout_secs,
env_conf.cache.write_timeout_secs
);
assert_eq!(config.cache.skip_check, env_conf.cache.skip_check);
assert_eq!(config.dist, env_conf.dist);
assert_eq!(
config.server_startup_timeout_ms,
env_conf.server_startup_timeout_ms
);
assert_eq!(config.client_side_mode, env_conf.client_side_mode);
Ok(())
}
#[test]
fn config_from_toml() -> Result<()> {
drop(env_logger::try_init());
let config = Config::from_toml(
r#"
server_startup_timeout_ms = 10000
[cache.azure]
container = "azurecontainer"
key_prefix = "azureprefix"
storage_account = "azureaccount"
[cache.disk]
dir = "/tmp/.cache/sccache"
size = 7516192768 # 7 GiBytes
[cache.gcs]
rw_mode = "READ_ONLY"
# rw_mode = "READ_WRITE"
cred_path = "/psst/secret/cred"
bucket = "bucket"
key_prefix = "prefix"
service_account = "example_service_account"
[cache.gha]
enabled = true
version = "sccache"
[cache.memcached]
# Deprecated alias for `endpoint`
# url = "127.0.0.1:11211"
endpoint = "tcp://127.0.0.1:11211"
# Username and password for authentication
username = "user"
password = "passwd"
expiration = 90000
key_prefix = "/custom/prefix/if/need"
[cache.redis]
# Deprecated in favor of `endpoint`.
url = "redis://user:[email protected]:6379/?db=1"
endpoint = "redis://127.0.0.1:6379"
cluster_endpoints = "tcp://10.0.0.1:6379,redis://10.0.0.2:6379"
reader_endpoints = "tcp://10.0.0.1:6380,redis://10.0.0.2:6380"
username = "another_user"
password = "new_passwd"
db = 12
expiration = 86400
key_prefix = "/my/redis/cache"
[cache.s3]
bucket = "name"
region = "us-east-2"
endpoint = "s3-us-east-1.amazonaws.com"
use_ssl = true
key_prefix = "s3prefix"
no_credentials = false
server_side_encryption = false
rw_mode = "READ_WRITE"
[cache.webdav]
endpoint = "http://127.0.0.1:8080"
key_prefix = "webdavprefix"
username = "webdavusername"
password = "webdavpassword"
token = "webdavtoken"
[cache.oss]
bucket = "name"
endpoint = "oss-us-east-1.aliyuncs.com"
key_prefix = "ossprefix"
no_credentials = true
rw_mode = "READ_ONLY"
[cache.cos]
bucket = "name"
endpoint = "cos.na-siliconvalley.myqcloud.com"
key_prefix = "cosprefix"
[cache.custom-1]
type = "cos"
bucket = "name"
endpoint = "cos.na-siliconvalley.myqcloud.com"
key_prefix = "cosprefix"
[cache.configs.custom-2]
type = "cos"
bucket = "name"
endpoint = "cos.na-siliconvalley.myqcloud.com"
key_prefix = "cosprefix"
[cache.multilevel]
chain = ["disk", "s3", "redis", "memcached", "gcs", "gha", "azure", "webdav", "oss", "cos", "custom-1", "custom-2"]
[dist]
# where to find the scheduler
scheduler_url = "http://1.2.3.4:10600"
# the maximum size of the toolchain cache in bytes
toolchain_cache_size = 5368709120
cache_dir = "/home/user/.cache/sccache-dist-client"
[dist.auth]
type = "token"
token = "secrettoken"
# a set of prepackaged toolchains
[[dist.toolchains]]
type = "path_override"
archive = "/toolchains/cc.tar.gz"
compiler_executable = "/usr/bin/cc"
archive_compiler_executable = "/usr/bin/cc"
[[dist.toolchains]]
type = "path_override"
archive = "/toolchains/rust.tar.gz"
compiler_executable = "/usr/bin/rustc"
archive_compiler_executable = "/usr/bin/rustc"
"#,
)?;
let mut cache_configs = [
Azure {
auth: AzureAuth::StorageAccount {
storage_account: "azureaccount".into(),
},
key_prefix: "azureprefix".into(),
..Azure::from_container("azurecontainer")
}
.into(),
Disk {
dir: PathBuf::from("/tmp/.cache/sccache"),
size: 7 * 1024 * 1024 * 1024,
rw_mode: CacheMode::ReadWrite,
..Default::default()
}
.into(),
GCS {
key_path: Some("/psst/secret/cred".into()),
service_account: Some("example_service_account".into()),
rw_mode: CacheMode::ReadOnly,
key_prefix: "prefix".into(),
credentials_url: None,
..GCS::from_bucket("bucket")
}
.into(),
GHA::from_version("sccache").into(),
Redis {
endpoint: Some("redis://127.0.0.1:6379".into()),
cluster_endpoints: Some("tcp://10.0.0.1:6379,redis://10.0.0.2:6379".into()),
reader_endpoints: Some("tcp://10.0.0.1:6380,redis://10.0.0.2:6380".into()),
username: Some("another_user".into()),
password: Some("new_passwd".into()),
db: 12,
ttl: 24 * 3600,
key_prefix: "/my/redis/cache".into(),
..Redis::from_url("redis://user:[email protected]:6379/?db=1")
}
.into(),
Memcached {
username: Some("user".into()),
password: Some("passwd".into()),
expiration: 25 * 3600,
key_prefix: "/custom/prefix/if/need".into(),
rw_mode: CacheMode::ReadWrite,
..Memcached::from_url("tcp://127.0.0.1:11211")
}
.into(),
S3 {
region: Some("us-east-2".into()),
endpoint: Some("s3-us-east-1.amazonaws.com".into()),
use_ssl: Some(true),
key_prefix: "s3prefix".into(),
no_credentials: false,
server_side_encryption: Some(false),
..S3::from_bucket("name")