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
use crate::LOG_TARGET;
use async_std::{
io,
os::unix::net::{UnixListener, UnixStream},
path::{Path, PathBuf},
};
use futures::{
never::Never, AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _, FutureExt as _,
};
use futures_timer::Delay;
use pin_project::pin_project;
use rand::Rng;
use std::{
fmt, mem,
pin::Pin,
task::{Context, Poll},
time::Duration,
};
#[doc(hidden)]
pub async fn spawn_with_program_path(
debug_id: &'static str,
program_path: impl Into<PathBuf>,
extra_args: &'static [&'static str],
spawn_timeout: Duration,
) -> Result<(IdleWorker, WorkerHandle), SpawnErr> {
let program_path = program_path.into();
with_transient_socket_path(debug_id, |socket_path| {
let socket_path = socket_path.to_owned();
async move {
let listener = UnixListener::bind(&socket_path).await.map_err(|err| {
gum::warn!(
target: LOG_TARGET,
%debug_id,
"cannot bind unix socket: {:?}",
err,
);
SpawnErr::Bind
})?;
let handle =
WorkerHandle::spawn(program_path, extra_args, socket_path).map_err(|err| {
gum::warn!(
target: LOG_TARGET,
%debug_id,
"cannot spawn a worker: {:?}",
err,
);
SpawnErr::ProcessSpawn
})?;
futures::select! {
accept_result = listener.accept().fuse() => {
let (stream, _) = accept_result.map_err(|err| {
gum::warn!(
target: LOG_TARGET,
%debug_id,
"cannot accept a worker: {:?}",
err,
);
SpawnErr::Accept
})?;
Ok((IdleWorker { stream, pid: handle.id() }, handle))
}
_ = Delay::new(spawn_timeout).fuse() => {
Err(SpawnErr::AcceptTimeout)
}
}
}
})
.await
}
async fn with_transient_socket_path<T, F, Fut>(debug_id: &'static str, f: F) -> Result<T, SpawnErr>
where
F: FnOnce(&Path) -> Fut,
Fut: futures::Future<Output = Result<T, SpawnErr>> + 'static,
{
let socket_path = tmpfile(&format!("pvf-host-{}", debug_id))
.await
.map_err(|_| SpawnErr::TmpFile)?;
let result = f(&socket_path).await;
let _ = async_std::fs::remove_file(socket_path).await;
result
}
pub async fn tmpfile_in(prefix: &str, dir: &Path) -> io::Result<PathBuf> {
fn tmppath(prefix: &str, dir: &Path) -> PathBuf {
use rand::distributions::Alphanumeric;
const DESCRIMINATOR_LEN: usize = 10;
let mut buf = Vec::with_capacity(prefix.len() + DESCRIMINATOR_LEN);
buf.extend(prefix.as_bytes());
buf.extend(rand::thread_rng().sample_iter(&Alphanumeric).take(DESCRIMINATOR_LEN));
let s = std::str::from_utf8(&buf)
.expect("the string is collected from a valid utf-8 sequence; qed");
let mut file = dir.to_owned();
file.push(s);
file
}
const NUM_RETRIES: usize = 50;
for _ in 0..NUM_RETRIES {
let candidate_path = tmppath(prefix, dir);
if !candidate_path.exists().await {
return Ok(candidate_path)
}
}
Err(io::Error::new(io::ErrorKind::Other, "failed to create a temporary file"))
}
pub async fn tmpfile(prefix: &str) -> io::Result<PathBuf> {
let temp_dir = PathBuf::from(std::env::temp_dir());
tmpfile_in(prefix, &temp_dir).await
}
pub fn worker_event_loop<F, Fut>(debug_id: &'static str, socket_path: &str, mut event_loop: F)
where
F: FnMut(UnixStream) -> Fut,
Fut: futures::Future<Output = io::Result<Never>>,
{
let err = async_std::task::block_on::<_, io::Result<Never>>(async move {
let stream = UnixStream::connect(socket_path).await?;
let _ = async_std::fs::remove_file(socket_path).await;
event_loop(stream).await
})
.unwrap_err(); gum::debug!(
target: LOG_TARGET,
worker_pid = %std::process::id(),
"pvf worker ({}): {:?}",
debug_id,
err,
);
}
#[derive(Debug)]
pub struct IdleWorker {
pub stream: UnixStream,
pub pid: u32,
}
#[derive(Clone, Debug)]
pub enum SpawnErr {
TmpFile,
Bind,
Accept,
ProcessSpawn,
AcceptTimeout,
}
#[pin_project]
pub struct WorkerHandle {
child: async_process::Child,
#[pin]
stdout: async_process::ChildStdout,
drop_box: Box<[u8]>,
}
impl WorkerHandle {
fn spawn(
program: impl AsRef<Path>,
extra_args: &[&str],
socket_path: impl AsRef<Path>,
) -> io::Result<Self> {
let mut child = async_process::Command::new(program.as_ref())
.args(extra_args)
.arg(socket_path.as_ref().as_os_str())
.stdout(async_process::Stdio::piped())
.kill_on_drop(true)
.spawn()?;
let stdout = child
.stdout
.take()
.expect("the process spawned with piped stdout should have the stdout handle");
Ok(WorkerHandle {
child,
stdout,
drop_box: vec![0; 8192].into_boxed_slice(),
})
}
pub fn id(&self) -> u32 {
self.child.id()
}
}
impl futures::Future for WorkerHandle {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let me = self.project();
match futures::ready!(AsyncRead::poll_read(me.stdout, cx, &mut *me.drop_box)) {
Ok(0) => {
Poll::Ready(())
},
Ok(_bytes_read) => {
cx.waker().wake_by_ref();
Poll::Pending
},
Err(_) => {
Poll::Ready(())
},
}
}
}
impl fmt::Debug for WorkerHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "WorkerHandle(pid={})", self.id())
}
}
pub fn path_to_bytes(path: &Path) -> &[u8] {
path.to_str().expect("non-UTF-8 path").as_bytes()
}
pub fn bytes_to_path(bytes: &[u8]) -> Option<PathBuf> {
std::str::from_utf8(bytes).ok().map(PathBuf::from)
}
pub async fn framed_send(w: &mut (impl AsyncWrite + Unpin), buf: &[u8]) -> io::Result<()> {
let len_buf = buf.len().to_le_bytes();
w.write_all(&len_buf).await?;
w.write_all(buf).await?;
Ok(())
}
pub async fn framed_recv(r: &mut (impl AsyncRead + Unpin)) -> io::Result<Vec<u8>> {
let mut len_buf = [0u8; mem::size_of::<usize>()];
r.read_exact(&mut len_buf).await?;
let len = usize::from_le_bytes(len_buf);
let mut buf = vec![0; len];
r.read_exact(&mut buf).await?;
Ok(buf)
}