viaduct 0.4.0

A duplex communication channel between a parent and child process, using unnamed pipes
Documentation
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
use crate::{
	serde::{ViaductDeserialize, ViaductSerialize},
	ViaductEvent,
};
use interprocess::unnamed_pipe::{UnnamedPipeReader, UnnamedPipeWriter};
use parking_lot::{Condvar, Mutex};
use std::{
	collections::BTreeSet,
	io::{Read, Write},
	marker::PhantomData,
	mem::size_of,
	sync::Arc,
	time::{Duration, Instant},
};
use uuid::Uuid;

const RPC: u8 = 0;
const REQUEST: u8 = 1;
const SOME_RESPONSE: u8 = 2;
const NONE_RESPONSE: u8 = 3;

pub(super) const HELLO: &[u8] = b"Read this if you are a beautiful strong unnamed pipe who don't need no handles";

/// A channel pair for sending and receiving data across the viaduct.
pub type Viaduct<RpcTx, RequestTx, RpcRx, RequestRx> = (
	ViaductTx<RpcTx, RequestTx, RpcRx, RequestRx>,
	ViaductRx<RpcTx, RequestTx, RpcRx, RequestRx>,
);
/// Use [`ViaductRequestResponder::respond`] to send a response to the other side.
pub struct ViaductRequestResponder<RpcTx, RequestTx, RpcRx, RequestRx>
where
	RpcTx: ViaductSerialize,
	RequestTx: ViaductSerialize,
	RpcRx: ViaductDeserialize,
	RequestRx: ViaductDeserialize,
{
	tx: ViaductTx<RpcTx, RequestTx, RpcRx, RequestRx>,
	request_id: Uuid,
}
impl<RpcTx, RequestTx, RpcRx, RequestRx> ViaductRequestResponder<RpcTx, RequestTx, RpcRx, RequestRx>
where
	RpcTx: ViaductSerialize,
	RequestTx: ViaductSerialize,
	RpcRx: ViaductDeserialize,
	RequestRx: ViaductDeserialize,
{
	/// Sends a response to the other side.
	///
	/// You can send whatever type you want, as long as it implements [`ViaductSerialize`].
	///
	/// # Panics
	///
	/// This function won't panic, but the peer process will panic if you send a different type to what it was expecting.
	///
	/// # Example
	///
	/// ```no_run
	/// # use viaduct::{ViaductEvent, ViaductChild, doctest::*};
	/// # let rx = unsafe { ViaductChild::<ExampleRpc, ExampleRequest, ExampleRpc, ExampleRequest>::new().build() }.unwrap().1;
	/// rx.run(|event| match event {
	///     ViaductEvent::Rpc(rpc) => match rpc {
	///         ExampleRpc::Cow => println!("Moo"),
	///         ExampleRpc::Pig => println!("Oink"),
	///         ExampleRpc::Horse => println!("Neigh"),
	///     },
	///
	///     ViaductEvent::Request { request, responder } => match request {
	///         ExampleRequest::DoAFrontflip => {
	///             println!("Doing a frontflip!");
	///             responder.respond(Ok::<_, FrontflipError>(())).unwrap();
	///         },
	///
	///         ExampleRequest::DoABackflip => {
	///             println!("Doing a backflip!");
	///             responder.respond(Ok::<_, BackflipError>(())).unwrap();
	///         },
	///     }
	/// }).unwrap();
	/// ```
	pub fn respond(self, response: impl ViaductSerialize) -> Result<(), std::io::Error> {
		{
			let mut state = self.tx.0.state.lock();
			let ViaductTxState { tx, buf, .. } = &mut *state;

			response
				.to_pipeable({
					buf.clear();
					buf
				})
				.expect("Failed to serialize response");

			tx.write_all(&[2])?;
			tx.write_all(self.request_id.as_bytes())?;
			tx.write_all(&u64::to_ne_bytes(buf.len() as _))?;
			tx.write_all(buf)?;
		}

		std::mem::forget(self);

		Ok(())
	}
}
impl<RpcTx, RequestTx, RpcRx, RequestRx> Drop for ViaductRequestResponder<RpcTx, RequestTx, RpcRx, RequestRx>
where
	RpcTx: ViaductSerialize,
	RequestTx: ViaductSerialize,
	RpcRx: ViaductDeserialize,
	RequestRx: ViaductDeserialize,
{
	fn drop(&mut self) {
		let mut state = self.tx.0.state.lock();
		let ViaductTxState { tx, .. } = &mut *state;

		(|| {
			tx.write_all(&[3])?;
			tx.write_all(self.request_id.as_bytes())?;
			Ok::<_, std::io::Error>(())
		})()
		.unwrap();
	}
}

/// The receiving side of a viaduct.
pub struct ViaductRx<RpcTx, RequestTx, RpcRx, RequestRx>
where
	RpcTx: ViaductSerialize,
	RequestTx: ViaductSerialize,
	RpcRx: ViaductDeserialize,
	RequestRx: ViaductDeserialize,
{
	pub(super) buf: Vec<u8>,
	pub(super) tx: ViaductTx<RpcTx, RequestTx, RpcRx, RequestRx>,
	pub(super) rx: UnnamedPipeReader,
	pub(super) _phantom: PhantomData<RequestRx>,
}
impl<RpcTx, RequestTx, RpcRx, RequestRx> ViaductRx<RpcTx, RequestTx, RpcRx, RequestRx>
where
	RpcTx: ViaductSerialize,
	RpcRx: ViaductDeserialize,
	RequestTx: ViaductSerialize,
	RequestRx: ViaductDeserialize,
{
	/// Runs the event loop. This function will never return unless an error occurs.
	///
	/// # Panics
	///
	/// This function will panic if the peer process sends some data (RPC or request) and this process fails to deserialize it.
	///
	/// # Example
	///
	/// ```no_run
	/// # use viaduct::{ViaductEvent, ViaductChild, doctest::*};
	/// # let rx = unsafe { ViaductChild::<ExampleRpc, ExampleRequest, ExampleRpc, ExampleRequest>::new().build() }.unwrap().1;
	/// rx.run(|event| match event {
	///     ViaductEvent::Rpc(rpc) => match rpc {
	///         ExampleRpc::Cow => println!("Moo"),
	///         ExampleRpc::Pig => println!("Oink"),
	///         ExampleRpc::Horse => println!("Neigh"),
	///     },
	///
	///     ViaductEvent::Request { request, responder } => match request {
	///         ExampleRequest::DoAFrontflip => {
	///             println!("Doing a frontflip!");
	///             responder.respond(Ok::<_, FrontflipError>(())).unwrap();
	///         },
	///
	///         ExampleRequest::DoABackflip => {
	///             println!("Doing a backflip!");
	///             responder.respond(Ok::<_, BackflipError>(())).unwrap();
	///         },
	///     }
	/// }).unwrap();
	/// ```
	pub fn run<EventHandler>(mut self, mut event_handler: EventHandler) -> Result<(), std::io::Error>
	where
		EventHandler: FnMut(ViaductEvent<RpcTx, RequestTx, RpcRx, RequestRx>),
	{
		let recv_into_buf = |rx: &mut UnnamedPipeReader, buf: &mut Vec<u8>| -> Result<(), std::io::Error> {
			let len = {
				let mut len = [0u8; size_of::<u64>()];
				rx.read_exact(&mut len)?;
				usize::try_from(u64::from_ne_bytes(len)).expect("Viaduct packet was larger than what this architecture can handle")
			};
			buf.resize(len, 0);
			rx.read_exact(buf)?;
			Ok(())
		};

		loop {
			let packet_type = {
				let mut packet_type = [0u8];
				self.rx.read_exact(&mut packet_type)?;
				packet_type[0]
			};
			match packet_type {
				RPC => {
					recv_into_buf(&mut self.rx, &mut self.buf)?;

					let rpc = RpcRx::from_pipeable(&self.buf).expect("Failed to deserialize RpcRx");
					event_handler(ViaductEvent::Rpc(rpc));
				}

				REQUEST => {
					let request_id = {
						let mut request_id = [0u8; 16];
						self.rx.read_exact(&mut request_id)?;
						Uuid::from_bytes(request_id)
					};

					recv_into_buf(&mut self.rx, &mut self.buf)?;

					event_handler(ViaductEvent::Request {
						request: RequestRx::from_pipeable(&self.buf).expect("Failed to deserialize RequestRx"),
						responder: ViaductRequestResponder {
							tx: self.tx.clone(),
							request_id,
						},
					});
				}

				SOME_RESPONSE => {
					let mut response = self.tx.0.response.lock();
					self.tx
						.0
						.response_condvar
						.wait_while(&mut response, |response| response.for_request_id.is_some());

					let request_id = {
						let mut request_id = [0u8; 16];
						self.rx.read_exact(&mut request_id)?;
						Uuid::from_bytes(request_id)
					};

					// Receive the response into the sender's buffer
					response.buf.clear();
					recv_into_buf(&mut self.rx, &mut response.buf)?;

					if !response.pending.remove(&request_id) {
						// The request was cancelled. Discard.
						continue;
					}

					response.for_request_id = Some((request_id, true));

					// Tell the sender that the response is ready and in their buffer!
					self.tx.0.response_condvar.notify_all();
				}

				NONE_RESPONSE => {
					let mut response = self.tx.0.response.lock();
					self.tx
						.0
						.response_condvar
						.wait_while(&mut response, |response| response.for_request_id.is_some());

					let request_id = {
						let mut request_id = [0u8; 16];
						self.rx.read_exact(&mut request_id)?;
						Uuid::from_bytes(request_id)
					};

					if !response.pending.remove(&request_id) {
						// The request was cancelled. Discard.
						continue;
					}

					response.for_request_id = Some((request_id, false));

					// Tell the sender that the response is ready and in their buffer!
					self.tx.0.response_condvar.notify_all();
				}

				_ => unreachable!(),
			}
		}
	}
}

#[derive(Default)]
pub(super) struct ViaductResponseState {
	pending: BTreeSet<Uuid>,
	for_request_id: Option<(Uuid, bool)>,
	buf: Vec<u8>,
}
impl ViaductResponseState {
	#[inline]
	fn request_id(&self) -> Option<&Uuid> {
		self.for_request_id.as_ref().map(|(id, _)| id)
	}
}

/// The sending side of a viaduct.
///
/// This handle can be freely cloned and sent across threads.
pub struct ViaductTx<RpcTx, RequestTx, RpcRx, RequestRx>(pub(super) Arc<ViaductTxInner<RpcTx, RequestTx, RpcRx, RequestRx>>)
where
	RpcTx: ViaductSerialize,
	RequestTx: ViaductSerialize,
	RpcRx: ViaductDeserialize,
	RequestRx: ViaductDeserialize;

pub(super) struct ViaductTxInner<RpcTx, RequestTx, RpcRx, RequestRx> {
	pub(super) state: Mutex<ViaductTxState<RpcTx, RequestTx, RpcRx, RequestRx>>,
	pub(super) response: Mutex<ViaductResponseState>,
	pub(super) response_condvar: Condvar,
}

pub(super) struct ViaductTxState<RpcTx, RequestTx, RpcRx, RequestRx> {
	pub(super) tx: UnnamedPipeWriter,
	buf: Vec<u8>,
	_phantom: PhantomData<(RpcTx, RequestTx, RpcRx, RequestRx)>,
}
impl<RpcTx, RequestTx, RpcRx, RequestRx> ViaductTxState<RpcTx, RequestTx, RpcRx, RequestRx>
where
	RpcTx: ViaductSerialize,
	RpcRx: ViaductDeserialize,
	RequestTx: ViaductSerialize,
	RequestRx: ViaductDeserialize,
{
	#[inline]
	pub(super) fn new(tx: UnnamedPipeWriter) -> Self {
		Self {
			buf: Vec::new(),
			tx,
			_phantom: Default::default(),
		}
	}
}

impl<RpcTx, RequestTx, RpcRx, RequestRx> ViaductTx<RpcTx, RequestTx, RpcRx, RequestRx>
where
	RpcTx: ViaductSerialize,
	RpcRx: ViaductDeserialize,
	RequestTx: ViaductSerialize,
	RequestRx: ViaductDeserialize,
{
	/// Sends an RPC to the peer process.
	///
	/// # Panics
	///
	/// This function won't panic, but the peer process will panic if the RPC is unable to be deserialized.
	pub fn rpc(&self, rpc: RpcTx) -> Result<(), std::io::Error> {
		let mut state = self.0.state.lock();

		let ViaductTxState { buf, tx, .. } = &mut *state;

		rpc.to_pipeable({
			buf.clear();
			buf
		})
		.expect("Failed to serialize RpcTx");

		tx.write_all(&[0])?;
		tx.write_all(&u64::to_ne_bytes(buf.len() as _))?;
		tx.write_all(&*buf)?;

		Ok(())
	}

	/// Sends a request to the peer process and awaits a response.
	///
	/// This will block the current thread.
	///
	/// # Panics
	///
	/// This function will panic if the peer process doesn't send the expected type (`Response`) as the response.
	pub fn request<Response: ViaductDeserialize>(&self, request: RequestTx) -> Result<Option<Response>, std::io::Error> {
		let mut response = self.0.response.lock();

		// Get a request ID
		let request_id = Uuid::new_v4();

		response.pending.insert(request_id);

		// Send the request down the wire
		{
			let mut state = self.0.state.lock();
			let ViaductTxState { buf, tx, .. } = &mut *state;

			request
				.to_pipeable({
					buf.clear();
					buf
				})
				.expect("Failed to serialize RequestTx");

			tx.write_all(&[1])?;
			tx.write_all(request_id.as_bytes())?;
			tx.write_all(&u64::to_ne_bytes(buf.len() as _))?;
			tx.write_all(&*buf)?;
		}

		self.0
			.response_condvar
			.wait_while(&mut response, |response| response.request_id() != Some(&request_id));

		let (for_request_id, some) = response.for_request_id.take().unwrap();
		debug_assert_eq!(for_request_id, request_id);

		// Notify the condvar because the writer half might be waiting for the request ID to become None
		self.0.response_condvar.notify_all();

		// Deserialize the response and return it
		Ok(if some {
			Some(Response::from_pipeable(&response.buf).expect("Failed to deserialize Response"))
		} else {
			None
		})
	}

	/// Sends a request to the peer process and awaits a response, timing out after an [`Instant`](std::time::Instant) has passed.
	///
	/// This will block the current thread.
	///
	/// # Panics
	///
	/// This function will panic if the peer process doesn't send the expected type (`Response`) as the response.
	pub fn request_timeout_at<Response: ViaductDeserialize>(
		&self,
		timeout_at: Instant,
		request: RequestTx,
	) -> Result<Option<Response>, std::io::Error> {
		let mut response = self
			.0
			.response
			.try_lock_until(timeout_at)
			.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::TimedOut))?;

		// Get a request ID
		let request_id = Uuid::new_v4();

		response.pending.insert(request_id);

		// Send the request down the wire
		{
			let mut state = self
				.0
				.state
				.try_lock_until(timeout_at)
				.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::TimedOut))?;
			let ViaductTxState { buf, tx, .. } = &mut *state;

			request
				.to_pipeable({
					buf.clear();
					buf
				})
				.expect("Failed to serialize RequestTx");

			tx.write_all(&[1])?;
			tx.write_all(request_id.as_bytes())?;
			tx.write_all(&u64::to_ne_bytes(buf.len() as _))?;
			tx.write_all(&*buf)?;
		}

		if self
			.0
			.response_condvar
			.wait_while_until(&mut response, |response| response.request_id() != Some(&request_id), timeout_at)
			.timed_out()
		{
			response.pending.remove(&request_id);
			return Err(std::io::Error::from(std::io::ErrorKind::TimedOut));
		}

		let (for_request_id, some) = response.for_request_id.take().unwrap();
		debug_assert_eq!(for_request_id, request_id);

		// Notify the condvar because the writer half might be waiting for the request ID to become None
		self.0.response_condvar.notify_all();

		// Deserialize the response and return it
		Ok(if some {
			Some(Response::from_pipeable(&response.buf).expect("Failed to deserialize Response"))
		} else {
			None
		})
	}

	/// Sends a request to the peer process and awaits a response, timing out after the given duration.
	///
	/// This will block the current thread.
	///
	/// # Panics
	///
	/// This function will panic if the peer process doesn't send the expected type (`Response`) as the response.
	#[inline]
	pub fn request_timeout<Response: ViaductDeserialize>(&self, timeout: Duration, request: RequestTx) -> Result<Option<Response>, std::io::Error> {
		self.request_timeout_at(Instant::now() + timeout, request)
	}
}
impl<RpcTx, RequestTx, RpcRx, RequestRx> Clone for ViaductTx<RpcTx, RequestTx, RpcRx, RequestRx>
where
	RpcTx: ViaductSerialize,
	RpcRx: ViaductDeserialize,
	RequestTx: ViaductSerialize,
	RequestRx: ViaductDeserialize,
{
	#[inline]
	fn clone(&self) -> Self {
		Self(self.0.clone())
	}
}