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
//! Holding startup's background work back until the first frame is up.
//!
//! A launch starts a dozen jobs the first frame never shows: the syntax
//! highlight prewarm (hundreds of milliseconds of CPU on its own), the
//! Cmd+P file index, git status, the file watcher, the extension index
//! download, the activity-bar icon bake. Started at once, they outnumbered
//! the cores and the UI thread spent most of its way to the first frame
//! runnable but not running: five milliseconds of work took tens. Each such
//! job now calls [`wait`] first, which returns at once except during a
//! launch [`arm`]ed by `app::run` whose first frame has not been flushed
//! yet; `main_loop` calls [`open`] when it has.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Condvar, Mutex};
use std::time::Duration;
/// The longest a held-back job waits: a first frame that never comes (a
/// start that fails, a frame loop that errors) must not strand the work.
const CAP: Duration = Duration::from_secs(1);
struct Gate {
armed: AtomicBool,
open: Mutex<bool>,
opened: Condvar,
}
impl Gate {
const fn new() -> Self {
Self {
armed: AtomicBool::new(false),
open: Mutex::new(false),
opened: Condvar::new(),
}
}
/// Closed again first: returning from a remote workspace runs a second
/// launch in the same process, after the first one opened the gate.
fn arm(&self) {
if let Ok(mut open) = self.open.lock() {
*open = false;
}
self.armed.store(true, Ordering::Release);
}
fn open(&self) {
if let Ok(mut open) = self.open.lock() {
*open = true;
}
self.opened.notify_all();
self.armed.store(false, Ordering::Release);
}
fn wait(&self, cap: Duration) {
if !self.armed.load(Ordering::Acquire) {
return;
}
if let Ok(open) = self.open.lock() {
let _ = self.opened.wait_timeout_while(open, cap, |open| !*open);
}
}
}
static GATE: Gate = Gate::new();
/// Hold background work back from now until [`open`]. `app::run` calls this
/// before it starts any, on every launch, a return from a remote workspace's
/// included; nothing else does, so outside a launch, and under test, [`wait`]
/// never waits.
pub fn arm() {
GATE.arm();
}
/// The first frame is on screen: release everything waiting, and every
/// later [`wait`].
pub fn open() {
GATE.open();
}
/// Whether a launch is still drawing its first frame. Work the first frame
/// does not show can be put off while this holds. False outside a launch and
/// under test, where nothing arms the gate.
pub fn first_frame_pending() -> bool {
GATE.armed.load(Ordering::Acquire)
}
/// Wait until the first frame is up, if a launch is still drawing it. Call
/// at the top of a background job the first frame does not need.
pub fn wait() {
GATE.wait(CAP);
}
/// [`wait`] for async code. The wait itself runs on the runtime's blocking
/// pool, so no worker thread is held while the first frame is drawn.
pub async fn wait_async() {
if !GATE.armed.load(Ordering::Acquire) {
return;
}
let _ = tokio::task::spawn_blocking(wait).await;
}
/// `job` on a thread of its own, once the first frame is up.
pub fn spawn_after_first_frame<F>(job: F) -> std::thread::JoinHandle<()>
where
F: FnOnce() + Send + 'static,
{
std::thread::spawn(move || {
wait();
job();
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::time::Instant;
/// Unarmed, as everywhere but a launch's first frame, a job never waits.
#[test]
fn an_unarmed_gate_never_holds_a_job() {
let gate = Gate::new();
let started = Instant::now();
gate.wait(Duration::from_secs(5));
assert!(started.elapsed() < Duration::from_secs(1));
}
#[test]
fn an_armed_gate_holds_a_job_until_it_opens() {
let gate = Arc::new(Gate::new());
gate.arm();
let (tx, rx) = std::sync::mpsc::channel();
let waiter = gate.clone();
std::thread::spawn(move || {
waiter.wait(Duration::from_secs(30));
let _ = tx.send(());
});
assert!(
rx.recv_timeout(Duration::from_millis(100)).is_err(),
"the job ran before the first frame"
);
gate.open();
assert!(rx.recv_timeout(Duration::from_secs(10)).is_ok());
// Opened, it holds no job until the next launch arms it.
let started = Instant::now();
gate.wait(Duration::from_secs(5));
assert!(started.elapsed() < Duration::from_secs(1));
}
/// Back from a remote workspace, `run` launches again in the same
/// process: the gate holds that launch's jobs as it did the first's.
#[test]
fn a_second_launch_in_the_same_process_is_held_again() {
let gate = Gate::new();
gate.arm();
gate.open();
gate.arm();
let started = Instant::now();
gate.wait(Duration::from_millis(50));
assert!(started.elapsed() >= Duration::from_millis(50));
}
/// A first frame that never comes does not strand the work.
#[test]
fn an_armed_gate_lets_a_job_go_after_its_cap() {
let gate = Gate::new();
gate.arm();
let started = Instant::now();
gate.wait(Duration::from_millis(50));
assert!(started.elapsed() >= Duration::from_millis(50));
}
}