-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathjsonrpc.rs
More file actions
2181 lines (1954 loc) · 78.5 KB
/
jsonrpc.rs
File metadata and controls
2181 lines (1954 loc) · 78.5 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use crate::find::find_and_report_envs;
use crate::find::find_python_environments_in_workspace_folder_recursive;
use crate::find::identify_python_executables_using_locators;
use crate::find::SearchScope;
use crate::locators::create_locators;
use log::{error, info, trace, warn};
use pet::initialize_tracing;
use pet::resolve::resolve_environment;
use pet_conda::Conda;
use pet_conda::CondaLocator;
use pet_core::python_environment::PythonEnvironment;
use pet_core::python_environment::PythonEnvironmentKind;
use pet_core::telemetry::refresh_performance::RefreshPerformance;
use pet_core::telemetry::TelemetryEvent;
use pet_core::{
os_environment::{Environment, EnvironmentApi},
reporter::Reporter,
Configuration, Locator, RefreshStatePersistence, RefreshStateSyncScope,
};
use pet_env_var_path::get_search_paths_from_env_variables;
use pet_fs::glob::expand_glob_patterns;
use pet_fs::path::norm_case;
use pet_jsonrpc::{
send_error, send_reply,
server::{start_server, HandlersKeyedByMethodName},
};
use pet_poetry::Poetry;
use pet_poetry::PoetryLocator;
use pet_python_utils::cache::clear_cache;
use pet_python_utils::cache::set_cache_directory;
use pet_reporter::collect;
use pet_reporter::{cache::CacheReporter, jsonrpc};
use pet_telemetry::report_inaccuracies_identified_after_resolving;
use serde::{Deserialize, Serialize};
use serde_json::json;
use serde_json::{self, Value};
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use std::{
ops::Deref,
panic::{self, AssertUnwindSafe},
path::PathBuf,
sync::{Arc, Condvar, Mutex, RwLock},
thread,
time::{Instant, SystemTime},
};
use tracing::info_span;
#[derive(Debug, Clone, Default)]
struct ConfigurationState {
generation: u64,
config: Configuration,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct RefreshKey {
options: RefreshOptions,
config_generation: u64,
}
impl RefreshKey {
fn new(options: &RefreshOptions, config_generation: u64) -> Self {
Self {
options: options.clone(),
config_generation,
}
}
}
#[derive(Debug)]
struct ActiveRefresh {
key: RefreshKey,
request_ids: Vec<u32>,
}
#[derive(Debug, Default)]
enum RefreshCoordinatorState {
#[default]
Idle,
Running(ActiveRefresh),
Completing(ActiveRefresh),
}
#[derive(Debug, Default)]
struct RefreshCoordinator {
state: Mutex<RefreshCoordinatorState>,
changed: Condvar,
}
enum RefreshRegistration {
Start,
Joined,
Wait,
}
impl RefreshCoordinator {
fn register_request(&self, request_id: u32, key: RefreshKey) -> RefreshRegistration {
let mut state = self
.state
.lock()
.expect("refresh coordinator mutex poisoned");
match &mut *state {
RefreshCoordinatorState::Idle => {
*state = RefreshCoordinatorState::Running(ActiveRefresh {
key,
request_ids: vec![request_id],
});
RefreshRegistration::Start
}
RefreshCoordinatorState::Running(active) if active.key == key => {
active.request_ids.push(request_id);
RefreshRegistration::Joined
}
RefreshCoordinatorState::Completing(active) if active.key == key => {
active.request_ids.push(request_id);
RefreshRegistration::Joined
}
RefreshCoordinatorState::Running(_) | RefreshCoordinatorState::Completing(_) => {
RefreshRegistration::Wait
}
}
}
fn wait_until_idle(&self) {
let state = self
.state
.lock()
.expect("refresh coordinator mutex poisoned");
let _guard = self
.changed
.wait_while(state, |state| {
!matches!(state, RefreshCoordinatorState::Idle)
})
.expect("refresh coordinator condvar poisoned");
}
fn begin_completion(&self, key: &RefreshKey) {
let mut state = self
.state
.lock()
.expect("refresh coordinator mutex poisoned");
match std::mem::replace(&mut *state, RefreshCoordinatorState::Idle) {
RefreshCoordinatorState::Running(active) if active.key == *key => {
*state = RefreshCoordinatorState::Completing(active);
}
RefreshCoordinatorState::Running(active) => {
*state = RefreshCoordinatorState::Running(active);
panic!("attempted to finish refresh with unexpected key");
}
RefreshCoordinatorState::Completing(active) => {
*state = RefreshCoordinatorState::Completing(active);
panic!("attempted to begin refresh completion while already completing")
}
RefreshCoordinatorState::Idle => {
panic!("attempted to finish refresh while coordinator was idle")
}
}
}
fn drain_completing_request_ids(&self, key: &RefreshKey) -> Vec<u32> {
let mut state = self
.state
.lock()
.expect("refresh coordinator mutex poisoned");
match &mut *state {
RefreshCoordinatorState::Completing(active) if active.key == *key => {
std::mem::take(&mut active.request_ids)
}
RefreshCoordinatorState::Completing(_) => {
panic!("attempted to drain completion requests with unexpected key")
}
RefreshCoordinatorState::Running(_) => {
panic!("attempted to drain completion requests before beginning completion")
}
RefreshCoordinatorState::Idle => Vec::new(),
}
}
fn complete_request(&self, key: &RefreshKey) -> bool {
let mut state = self
.state
.lock()
.expect("refresh coordinator mutex poisoned");
match &mut *state {
RefreshCoordinatorState::Completing(active) if active.key == *key => {
if active.request_ids.is_empty() {
*state = RefreshCoordinatorState::Idle;
self.changed.notify_all();
true
} else {
false
}
}
RefreshCoordinatorState::Completing(_) => {
panic!("attempted to complete refresh with unexpected key")
}
RefreshCoordinatorState::Running(_) => {
panic!("attempted to complete refresh before beginning completion")
}
RefreshCoordinatorState::Idle => {
panic!("attempted to complete refresh while coordinator was idle")
}
}
}
fn force_complete_request(&self, key: &RefreshKey) {
let mut state = self
.state
.lock()
.expect("refresh coordinator mutex poisoned");
match &*state {
RefreshCoordinatorState::Completing(active) if active.key == *key => {
*state = RefreshCoordinatorState::Idle;
self.changed.notify_all();
}
RefreshCoordinatorState::Running(active) if active.key == *key => {
// Recovery path: if begin_completion() panicked, the state was
// restored to Running before the unwind. Transition to Idle so
// waiters are not stuck forever.
*state = RefreshCoordinatorState::Idle;
self.changed.notify_all();
}
RefreshCoordinatorState::Idle => {}
RefreshCoordinatorState::Completing(active) => {
// Mismatched key — another refresh owns this state. Log and
// leave it alone; the owning refresh will clean up.
error!(
"force_complete_request called with mismatched key while coordinator was Completing; caller key: {:?}, active key: {:?}",
key,
active.key
);
}
RefreshCoordinatorState::Running(active) => {
// Mismatched key — another refresh owns this state. Log and
// leave it alone; the owning refresh will clean up.
error!(
"force_complete_request called with mismatched key while coordinator was Running; caller key: {:?}, active key: {:?}",
key,
active.key
);
}
}
}
}
/// Safety guard created when a refresh thread takes ownership of the `Running`
/// state. If the thread exits the `Start` arm without ever constructing a
/// `RefreshCompletionGuard` (e.g., because `begin_completion` panics), this
/// guard calls `force_complete_request` to transition the coordinator back to
/// `Idle`, preventing a permanent deadlock.
struct RefreshSafetyGuard<'a> {
coordinator: &'a RefreshCoordinator,
key: RefreshKey,
disarmed: bool,
}
impl<'a> RefreshSafetyGuard<'a> {
fn new(coordinator: &'a RefreshCoordinator, key: RefreshKey) -> Self {
Self {
coordinator,
key,
disarmed: false,
}
}
/// Disarm the safety guard once a `RefreshCompletionGuard` takes over
/// responsibility for the state transition.
fn disarm(&mut self) {
self.disarmed = true;
}
}
impl Drop for RefreshSafetyGuard<'_> {
fn drop(&mut self) {
if !self.disarmed {
self.coordinator.force_complete_request(&self.key);
}
}
}
struct RefreshLocators {
locators: Arc<Vec<Arc<dyn Locator>>>,
conda_locator: Arc<Conda>,
poetry_locator: Arc<Poetry>,
}
struct RefreshExecution {
result: RefreshResult,
perf: RefreshPerformance,
reporter: Arc<CacheReporter>,
configuration: Arc<RwLock<ConfigurationState>>,
refresh_generation: u64,
conda_locator: Arc<Conda>,
poetry_locator: Arc<Poetry>,
conda_executable: Option<PathBuf>,
poetry_executable: Option<PathBuf>,
}
struct RefreshCompletionGuard<'a> {
coordinator: &'a RefreshCoordinator,
key: RefreshKey,
completed: bool,
}
impl<'a> RefreshCompletionGuard<'a> {
fn begin(coordinator: &'a RefreshCoordinator, key: &RefreshKey) -> Self {
coordinator.begin_completion(key);
Self {
coordinator,
key: key.clone(),
completed: false,
}
}
fn drain_request_ids(&self) -> Vec<u32> {
self.coordinator.drain_completing_request_ids(&self.key)
}
fn finish_if_no_pending(&mut self) -> bool {
let completed = self.coordinator.complete_request(&self.key);
if completed {
self.completed = true;
}
completed
}
}
impl Drop for RefreshCompletionGuard<'_> {
fn drop(&mut self) {
if !self.completed {
self.coordinator.force_complete_request(&self.key);
}
}
}
fn send_refresh_replies_for_waiters(
completion_guard: &RefreshCompletionGuard<'_>,
result: &RefreshResult,
) {
for request_id in completion_guard.drain_request_ids() {
send_reply(request_id, Some(result.clone()));
}
}
fn send_refresh_errors_for_waiters(completion_guard: &RefreshCompletionGuard<'_>, message: &str) {
for request_id in completion_guard.drain_request_ids() {
send_error(Some(request_id), -4, message.to_string());
}
}
fn finish_refresh_replies(
completion_guard: &mut RefreshCompletionGuard<'_>,
result: &RefreshResult,
) {
loop {
send_refresh_replies_for_waiters(completion_guard, result);
if completion_guard.finish_if_no_pending() {
return;
}
}
}
fn finish_refresh_errors(completion_guard: &mut RefreshCompletionGuard<'_>, message: &str) {
loop {
send_refresh_errors_for_waiters(completion_guard, message);
if completion_guard.finish_if_no_pending() {
return;
}
}
}
fn sync_refresh_locator_state_if_current<F>(
configuration: &RwLock<ConfigurationState>,
refresh_generation: u64,
sync: F,
) -> Result<(), u64>
where
F: FnOnce(),
{
let state = configuration.read().unwrap();
if state.generation != refresh_generation {
return Err(state.generation);
}
sync();
Ok(())
}
struct GenerationGuardedReporter {
reporter: Arc<dyn Reporter>,
configuration: Arc<RwLock<ConfigurationState>>,
refresh_generation: u64,
}
impl GenerationGuardedReporter {
fn new(
reporter: Arc<dyn Reporter>,
configuration: Arc<RwLock<ConfigurationState>>,
refresh_generation: u64,
) -> Self {
Self {
reporter,
configuration,
refresh_generation,
}
}
fn report_if_current<F, S>(&self, report: F, on_stale: S)
where
F: FnOnce(&dyn Reporter),
S: FnOnce(),
{
let state = self.configuration.read().unwrap();
if state.generation == self.refresh_generation {
report(self.reporter.as_ref());
return;
}
drop(state);
on_stale();
}
}
impl Reporter for GenerationGuardedReporter {
fn report_manager(&self, manager: &pet_core::manager::EnvManager) {
self.report_if_current(
|reporter| reporter.report_manager(manager),
|| {
trace!(
"Skipping manager notification for stale generation {}",
self.refresh_generation
)
},
);
}
fn report_environment(&self, env: &PythonEnvironment) {
self.report_if_current(
|reporter| reporter.report_environment(env),
|| {
trace!(
"Skipping environment notification for stale generation {}: {:?}",
self.refresh_generation,
env.executable
.clone()
.unwrap_or(env.prefix.clone().unwrap_or_default())
)
},
);
}
fn report_telemetry(&self, event: &TelemetryEvent) {
self.report_if_current(
|reporter| reporter.report_telemetry(event),
|| {
trace!(
"Skipping telemetry notification for stale generation {}: {:?}",
self.refresh_generation,
event
)
},
);
}
}
pub struct Context {
configuration: Arc<RwLock<ConfigurationState>>,
locators: Arc<Vec<Arc<dyn Locator>>>,
conda_locator: Arc<Conda>,
os_environment: Arc<dyn Environment>,
refresh_coordinator: RefreshCoordinator,
}
const MISSING_ENVS_AVAILABLE: u64 = u64::MAX;
const MISSING_ENVS_COMPLETED: u64 = u64::MAX - 1;
static MISSING_ENVS_REPORTING_STATE: AtomicU64 = AtomicU64::new(MISSING_ENVS_AVAILABLE);
pub fn start_jsonrpc_server() {
// Initialize tracing for performance profiling (controlled by RUST_LOG env var)
// Note: This includes log compatibility, so we don't call jsonrpc::initialize_logger
initialize_tracing(false);
// These are globals for the the lifetime of the server.
// Hence passed around as Arcs via the context.
let environment = EnvironmentApi::new();
let conda_locator = Arc::new(Conda::from(&environment));
let poetry_locator = Arc::new(Poetry::from(&environment));
let context = Context {
locators: create_locators(conda_locator.clone(), poetry_locator.clone(), &environment),
conda_locator,
configuration: Arc::new(RwLock::new(ConfigurationState::default())),
os_environment: Arc::new(environment),
refresh_coordinator: RefreshCoordinator::default(),
};
let mut handlers = HandlersKeyedByMethodName::new(Arc::new(context));
handlers.add_request_handler("configure", handle_configure);
handlers.add_request_handler("refresh", handle_refresh);
handlers.add_request_handler("resolve", handle_resolve);
handlers.add_request_handler("find", handle_find);
handlers.add_request_handler("condaInfo", handle_conda_telemetry);
handlers.add_request_handler("clear", handle_clear_cache);
start_server(&handlers)
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConfigureOptions {
/// These are paths like workspace folders, where we can look for environments.
/// Glob patterns are supported (e.g., "/home/user/projects/*").
pub workspace_directories: Option<Vec<PathBuf>>,
pub conda_executable: Option<PathBuf>,
pub pipenv_executable: Option<PathBuf>,
pub poetry_executable: Option<PathBuf>,
/// Custom locations where environments can be found. Generally global locations where virtualenvs & the like can be found.
/// Workspace directories should not be included into this list.
/// Glob patterns are supported (e.g., "/home/user/envs/*").
pub environment_directories: Option<Vec<PathBuf>>,
/// Directory to cache the Python environment details.
pub cache_directory: Option<PathBuf>,
}
/// Threshold for glob expansion duration before emitting a warning.
/// The client has a 30-second timeout for configure requests.
const GLOB_EXPANSION_WARN_THRESHOLD: Duration = Duration::from_secs(5);
pub fn handle_configure(context: Arc<Context>, id: u32, params: Value) {
match serde_json::from_value::<ConfigureOptions>(params.clone()) {
Ok(configure_options) => {
info!("Received configure request");
// Start in a new thread, we can have multiple requests.
thread::spawn(move || {
let now = Instant::now();
// Expand glob patterns before acquiring the write lock so we
// don't block readers/writers while traversing the filesystem.
let workspace_directories = configure_options.workspace_directories.map(|dirs| {
let start = Instant::now();
let result: Vec<PathBuf> = expand_glob_patterns(&dirs)
.into_iter()
.filter(|p| p.is_dir())
.collect();
trace!(
"Expanded workspace directory patterns ({:?}) in {:?}",
dirs,
start.elapsed()
);
result
});
let environment_directories =
configure_options.environment_directories.map(|dirs| {
let start = Instant::now();
let result: Vec<PathBuf> = expand_glob_patterns(&dirs)
.into_iter()
.filter(|p| p.is_dir())
.collect();
trace!(
"Expanded environment directory patterns ({:?}) in {:?}",
dirs,
start.elapsed()
);
result
});
let glob_elapsed = now.elapsed();
trace!("Glob expansion completed in {:?}", glob_elapsed);
if glob_elapsed >= GLOB_EXPANSION_WARN_THRESHOLD {
warn!(
"Glob expansion took {:?}, this may cause client timeouts",
glob_elapsed
);
}
let config = {
let mut state = context.configuration.write().unwrap();
state.config.workspace_directories = workspace_directories;
state.config.conda_executable = configure_options.conda_executable;
state.config.environment_directories = environment_directories;
state.config.pipenv_executable = configure_options.pipenv_executable;
state.config.poetry_executable = configure_options.poetry_executable;
// We will not support changing the cache directories once set.
// No point, supporting such a use case.
if let Some(cache_directory) = configure_options.cache_directory {
set_cache_directory(cache_directory.clone());
state.config.cache_directory = Some(cache_directory);
}
state.generation += 1;
// Reset missing-env reporting so that the next refresh
// after reconfiguration can trigger it again (Fixes #395).
// Done inside the write lock to avoid a TOCTOU window with
// concurrent refresh threads reading the generation.
MISSING_ENVS_REPORTING_STATE.store(MISSING_ENVS_AVAILABLE, Ordering::Release);
trace!(
"Configuring locators with generation {}: {:?}",
state.generation,
state.config
);
state.config.clone()
};
configure_locators(&context.locators, &config);
info!("Configure completed in {:?}", now.elapsed());
send_reply(id, None::<()>);
});
}
Err(e) => {
send_reply(id, None::<u128>);
error!("Failed to parse configure options {:?}: {}", params, e);
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefreshOptions {
/// If provided, then limit the search to this kind of environments.
pub search_kind: Option<PythonEnvironmentKind>,
/// If provided, then limit the search paths to these.
/// Note: Search paths can also include Python exes or Python env folders.
/// Traditionally, search paths are workspace folders.
/// Glob patterns are supported (e.g., "/home/user/*/venv", "**/.venv").
pub search_paths: Option<Vec<PathBuf>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RefreshResult {
duration: u128,
}
impl RefreshResult {
pub fn new(duration: Duration) -> RefreshResult {
RefreshResult {
duration: duration.as_millis(),
}
}
}
fn normalize_refresh_params(params: Value) -> Value {
match params {
Value::Null => json!({}),
Value::Array(values) if values.is_empty() => json!({}),
_ => params,
}
}
fn canonicalize_refresh_options(mut options: RefreshOptions) -> RefreshOptions {
if let Some(search_paths) = options.search_paths.take() {
let mut expanded = expand_glob_patterns(&search_paths)
.into_iter()
.map(norm_case)
.collect::<Vec<PathBuf>>();
expanded.sort();
expanded.dedup();
options.search_paths = Some(expanded);
}
options
}
fn parse_refresh_options(params: Value) -> Result<RefreshOptions, serde_json::Error> {
serde_json::from_value::<Option<RefreshOptions>>(normalize_refresh_params(params))
.map(|options| canonicalize_refresh_options(options.unwrap_or_default()))
}
fn configure_locators(locators: &Arc<Vec<Arc<dyn Locator>>>, config: &Configuration) {
for locator in locators.iter() {
locator.configure(config);
}
}
fn create_refresh_locators(environment: &dyn Environment) -> RefreshLocators {
let conda_locator = Arc::new(Conda::from(environment));
let poetry_locator = Arc::new(Poetry::from(environment));
let locators = create_locators(conda_locator.clone(), poetry_locator.clone(), environment);
RefreshLocators {
locators,
conda_locator,
poetry_locator,
}
}
fn sync_refresh_locator_state(
target_locators: &[Arc<dyn Locator>],
source_locators: &[Arc<dyn Locator>],
search_scope: Option<&SearchScope>,
) {
let sync_scope = refresh_state_sync_scope(search_scope);
assert_eq!(
target_locators.len(),
source_locators.len(),
"refresh locator graphs drifted"
);
for (target, source) in target_locators.iter().zip(source_locators.iter()) {
assert_eq!(
target.get_kind(),
source.get_kind(),
"refresh locator order drifted"
);
if !matches!(target.refresh_state(), RefreshStatePersistence::Stateless) {
trace!(
"Applying refresh state contract for locator {:?}: {:?}",
target.get_kind(),
target.refresh_state()
);
}
target.sync_refresh_state_from(source.as_ref(), &sync_scope);
}
}
fn refresh_state_sync_scope(search_scope: Option<&SearchScope>) -> RefreshStateSyncScope {
match search_scope {
Some(SearchScope::Workspace) => RefreshStateSyncScope::Workspace,
Some(SearchScope::Global(kind)) => RefreshStateSyncScope::GlobalFiltered(*kind),
None => RefreshStateSyncScope::Full,
}
}
fn is_current_generation(
configuration: &RwLock<ConfigurationState>,
refresh_generation: u64,
) -> bool {
configuration.read().unwrap().generation == refresh_generation
}
fn try_begin_missing_env_reporting(
configuration: &RwLock<ConfigurationState>,
refresh_generation: u64,
) -> bool {
loop {
let current_state = MISSING_ENVS_REPORTING_STATE.load(Ordering::Acquire);
if current_state == MISSING_ENVS_COMPLETED {
return false;
}
if current_state != MISSING_ENVS_AVAILABLE && current_state >= refresh_generation {
return false;
}
if MISSING_ENVS_REPORTING_STATE
.compare_exchange(
current_state,
refresh_generation,
Ordering::AcqRel,
Ordering::Acquire,
)
.is_ok()
{
if is_current_generation(configuration, refresh_generation) {
return true;
}
release_missing_env_reporting_if_stale(configuration, refresh_generation);
return false;
}
}
}
fn release_missing_env_reporting_if_stale(
configuration: &RwLock<ConfigurationState>,
refresh_generation: u64,
) {
if !is_current_generation(configuration, refresh_generation) {
let _ = MISSING_ENVS_REPORTING_STATE.compare_exchange(
refresh_generation,
MISSING_ENVS_AVAILABLE,
Ordering::AcqRel,
Ordering::Acquire,
);
}
}
fn complete_missing_env_reporting(refresh_generation: u64) {
let _ = MISSING_ENVS_REPORTING_STATE.compare_exchange(
refresh_generation,
MISSING_ENVS_COMPLETED,
Ordering::AcqRel,
Ordering::Acquire,
);
}
fn execute_refresh(
context: &Context,
refresh_options: &RefreshOptions,
configuration_state: &ConfigurationState,
) -> RefreshExecution {
let refresh_locators = create_refresh_locators(context.os_environment.deref());
let reporter = Arc::new(CacheReporter::new(Arc::new(
GenerationGuardedReporter::new(
Arc::new(jsonrpc::create_reporter(refresh_options.search_kind)),
context.configuration.clone(),
configuration_state.generation,
),
)));
let (config, search_scope) =
build_refresh_config(refresh_options, configuration_state.config.clone());
if refresh_options.search_paths.is_some() {
trace!(
"Expanded search paths to {} workspace dirs, {} executables",
config
.workspace_directories
.as_ref()
.map(|v| v.len())
.unwrap_or(0),
config.executables.as_ref().map(|v| v.len()).unwrap_or(0)
);
}
configure_locators(&refresh_locators.locators, &config);
trace!(
"Start refreshing environments, generation: {}, config: {:?}",
configuration_state.generation,
config
);
let summary = find_and_report_envs(
reporter.as_ref(),
config,
&refresh_locators.locators,
context.os_environment.deref(),
search_scope.clone(),
);
let summary = summary.lock().expect("summary mutex poisoned");
for locator in summary.locators.iter() {
info!("Locator {:?} took {:?}", locator.0, locator.1);
}
for item in summary.breakdown.iter() {
info!("Locator {} took {:?}", item.0, item.1);
}
trace!("Finished refreshing environments in {:?}", summary.total);
// Refresh runs on a transient locator graph, so apply each locator's refresh-state
// contract back into the long-lived shared locator graph only if the generation
// still matches the configuration snapshot this refresh started with.
if let Err(current_generation) = sync_refresh_locator_state_if_current(
context.configuration.as_ref(),
configuration_state.generation,
|| {
sync_refresh_locator_state(
context.locators.as_ref(),
refresh_locators.locators.as_ref(),
search_scope.as_ref(),
);
},
) {
warn!(
"Skipping refresh state sync for stale generation {} because current generation is {}",
configuration_state.generation, current_generation
);
}
let perf = RefreshPerformance {
total: summary.total.as_millis(),
locators: summary
.locators
.clone()
.iter()
.map(|(k, v)| (format!("{k:?}"), v.as_millis()))
.collect::<BTreeMap<String, u128>>(),
breakdown: summary
.breakdown
.clone()
.iter()
.map(|(k, v)| (k.to_string(), v.as_millis()))
.collect::<BTreeMap<String, u128>>(),
};
RefreshExecution {
result: RefreshResult::new(summary.total),
perf,
reporter,
configuration: context.configuration.clone(),
refresh_generation: configuration_state.generation,
conda_locator: refresh_locators.conda_locator,
poetry_locator: refresh_locators.poetry_locator,
conda_executable: configuration_state.config.conda_executable.clone(),
poetry_executable: configuration_state.config.poetry_executable.clone(),
}
}
fn report_refresh_follow_up(execution: RefreshExecution) {
execution
.reporter
.report_telemetry(&TelemetryEvent::RefreshPerformance(execution.perf));
if try_begin_missing_env_reporting(
execution.configuration.as_ref(),
execution.refresh_generation,
) {
let conda_locator = execution.conda_locator.clone();
let conda_executable = execution.conda_executable.clone();
let poetry_locator = execution.poetry_locator.clone();
let poetry_executable = execution.poetry_executable.clone();
let reporter_ref = execution.reporter.clone();
let configuration = execution.configuration.clone();
let refresh_generation = execution.refresh_generation;
thread::spawn(move || {
if !is_current_generation(configuration.as_ref(), refresh_generation) {
release_missing_env_reporting_if_stale(configuration.as_ref(), refresh_generation);
return Some(());
}
conda_locator.find_and_report_missing_envs(reporter_ref.as_ref(), conda_executable);
if !is_current_generation(configuration.as_ref(), refresh_generation) {
release_missing_env_reporting_if_stale(configuration.as_ref(), refresh_generation);
return Some(());
}
poetry_locator.find_and_report_missing_envs(reporter_ref.as_ref(), poetry_executable);
if is_current_generation(configuration.as_ref(), refresh_generation) {
complete_missing_env_reporting(refresh_generation);
} else {
release_missing_env_reporting_if_stale(configuration.as_ref(), refresh_generation);
}
Some(())
});
}
}
pub fn handle_refresh(context: Arc<Context>, id: u32, params: Value) {
match parse_refresh_options(params.clone()) {
Ok(refresh_options) => {
// Start in a new thread, we can have multiple requests.
thread::spawn(move || {
let _span = info_span!("handle_refresh",
search_kind = ?refresh_options.search_kind,
has_search_paths = refresh_options.search_paths.is_some()
)
.entered();
loop {
let configuration_state = context.configuration.read().unwrap().clone();
let refresh_key =
RefreshKey::new(&refresh_options, configuration_state.generation);
match context
.refresh_coordinator
.register_request(id, refresh_key.clone())
{
RefreshRegistration::Joined => return,
RefreshRegistration::Wait => {
context.refresh_coordinator.wait_until_idle();
}
RefreshRegistration::Start => {
// Safety guard: if anything in this arm panics
// (including begin_completion), force the
// coordinator back to Idle so waiters are not
// stuck forever.
// Move refresh_key into the guard to avoid an
// extra clone of potentially large search_paths.
let mut safety_guard =
RefreshSafetyGuard::new(&context.refresh_coordinator, refresh_key);
let refresh_result = panic::catch_unwind(AssertUnwindSafe(|| {
execute_refresh(
context.as_ref(),
&refresh_options,
&configuration_state,
)
}));
match refresh_result {
Ok(execution) => {
let refresh_result = execution.result.clone();
let mut completion_guard = RefreshCompletionGuard::begin(
&context.refresh_coordinator,
&safety_guard.key,
);
safety_guard.disarm();
finish_refresh_replies(&mut completion_guard, &refresh_result);
report_refresh_follow_up(execution);
}
Err(_) => {
error!(
"Refresh panicked for generation {} and options {:?}",
configuration_state.generation, refresh_options
);
let mut completion_guard = RefreshCompletionGuard::begin(
&context.refresh_coordinator,
&safety_guard.key,
);
safety_guard.disarm();
finish_refresh_errors(
&mut completion_guard,
"Refresh failed unexpectedly",
);
}
}
return;
}
}
}