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
extern crate capnp;
extern crate capnp_futures;
extern crate futures;
use std::pin::Pin;
use std::task::{Context, Poll};
use futures::{Future, FutureExt, TryFutureExt};
use futures::channel::oneshot;
use capnp::Error;
use capnp::capability::Promise;
use capnp::private::capability::{ClientHook};
use std::cell::{RefCell};
use std::rc::{Rc};
use crate::task_set::TaskSet;
pub use crate::rpc::Disconnector;
pub mod rpc_capnp;
pub mod rpc_twoparty_capnp;
#[macro_export]
macro_rules! pry {
($expr:expr) => (
match $expr {
::std::result::Result::Ok(val) => val,
::std::result::Result::Err(err) => {
return ::capnp::capability::Promise::err(::std::convert::From::from(err))
}
})
}
mod broken;
mod local;
mod queued;
mod rpc;
mod attach;
mod sender_queue;
mod split;
mod task_set;
pub mod twoparty;
pub trait OutgoingMessage {
fn get_body<'a>(&'a mut self) -> ::capnp::Result<::capnp::any_pointer::Builder<'a>>;
fn get_body_as_reader<'a>(&'a self) -> ::capnp::Result<::capnp::any_pointer::Reader<'a>>;
fn send(self: Box<Self>)
-> (Promise<Rc<::capnp::message::Builder<::capnp::message::HeapAllocator>>, ::capnp::Error>,
Rc<::capnp::message::Builder<::capnp::message::HeapAllocator>>);
fn take(self: Box<Self>) -> ::capnp::message::Builder<::capnp::message::HeapAllocator>;
}
pub trait IncomingMessage {
fn get_body<'a>(&'a self) -> ::capnp::Result<::capnp::any_pointer::Reader<'a>>;
}
pub trait Connection<VatId> {
fn get_peer_vat_id(&self) -> VatId;
fn new_outgoing_message(&mut self, first_segment_word_size: u32) -> Box<dyn OutgoingMessage>;
fn receive_incoming_message(&mut self) -> Promise<Option<Box<dyn IncomingMessage>>, Error>;
fn shutdown(&mut self, result: ::capnp::Result<()>) -> Promise<(), Error>;
}
pub trait VatNetwork<VatId> {
fn connect(&mut self, host_id: VatId) -> Option<Box<dyn Connection<VatId>>>;
fn accept(&mut self) -> Promise<Box<dyn Connection<VatId>>, ::capnp::Error>;
fn drive_until_shutdown(&mut self) -> Promise<(), Error>;
}
#[must_use = "futures do nothing unless polled"]
pub struct RpcSystem<VatId> where VatId: 'static {
network: Box<dyn crate::VatNetwork<VatId>>,
bootstrap_cap: Box<dyn ClientHook>,
connection_state: Rc<RefCell<Option<Rc<rpc::ConnectionState<VatId>>>>>,
tasks: TaskSet<Error>,
handle: crate::task_set::TaskSetHandle<Error>
}
impl <VatId> RpcSystem <VatId> {
pub fn new(
mut network: Box<dyn crate::VatNetwork<VatId>>,
bootstrap: Option<::capnp::capability::Client>) -> RpcSystem<VatId>
{
let bootstrap_cap = match bootstrap {
Some(cap) => cap.hook,
None => broken::new_cap(Error::failed("no bootstrap capabiity".to_string())),
};
let (mut handle, tasks) = TaskSet::new(Box::new(SystemTaskReaper));
let mut handle1 = handle.clone();
handle.add(network.drive_until_shutdown().then(move |r| {
let r = match r {
Ok(()) => Ok(()),
Err(e) => {
if e.kind != ::capnp::ErrorKind::Disconnected {
Err(e)
} else {
Ok(())
}
}
};
handle1.terminate(r);
Promise::ok(())
}));
let mut result = RpcSystem {
network: network,
bootstrap_cap: bootstrap_cap,
connection_state: Rc::new(RefCell::new(None)),
tasks: tasks,
handle: handle.clone(),
};
let accept_loop = result.accept_loop();
handle.add(accept_loop);
result
}
pub fn bootstrap<T>(&mut self, vat_id: VatId) -> T
where T: ::capnp::capability::FromClientHook
{
let connection = match self.network.connect(vat_id) {
Some(connection) => connection,
None => {
return T::new(self.bootstrap_cap.clone());
}
};
let connection_state =
RpcSystem::get_connection_state(self.connection_state.clone(),
self.bootstrap_cap.clone(),
connection, self.handle.clone());
let hook = rpc::ConnectionState::bootstrap(connection_state.clone());
T::new(hook)
}
fn accept_loop(&mut self) -> Promise<(), Error> {
let connection_state_ref = self.connection_state.clone();
let bootstrap_cap = self.bootstrap_cap.clone();
let handle = self.handle.clone();
Promise::from_future(self.network.accept().map_ok(move |connection| {
RpcSystem::get_connection_state(connection_state_ref,
bootstrap_cap,
connection,
handle);
}))
}
fn get_connection_state(connection_state_ref: Rc<RefCell<Option<Rc<rpc::ConnectionState<VatId>>>>>,
bootstrap_cap: Box<dyn ClientHook>,
connection: Box<dyn crate::Connection<VatId>>,
mut handle: crate::task_set::TaskSetHandle<Error>)
-> Rc<rpc::ConnectionState<VatId>>
{
let (tasks, result) = match *connection_state_ref.borrow() {
Some(ref connection_state) => {
return connection_state.clone()
}
None => {
let (on_disconnect_fulfiller, on_disconnect_promise) =
oneshot::channel::<Promise<(), Error>>();
let connection_state_ref1 = connection_state_ref.clone();
handle.add(on_disconnect_promise.then(move |shutdown_promise| {
*connection_state_ref1.borrow_mut() = None;
match shutdown_promise {
Ok(s) => s,
Err(e) => Promise::err(Error::failed(format!("{}", e))),
}
}));
rpc::ConnectionState::new(bootstrap_cap, connection, on_disconnect_fulfiller)
}
};
*connection_state_ref.borrow_mut() = Some(result.clone());
handle.add(tasks);
result
}
pub fn get_disconnector(&self) -> rpc::Disconnector<VatId> {
rpc::Disconnector::new(self.connection_state.clone())
}
}
impl <VatId> Future for RpcSystem<VatId> where VatId: 'static {
type Output = Result<(),Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
Pin::new(&mut self.tasks).poll(cx)
}
}
pub fn new_client<C, S>(s: S) -> C where C: capnp::capability::FromServer<S> {
capnp::capability::FromClientHook::new(Box::new(
local::Client::new(Box::new(<C as capnp::capability::FromServer::<S>>::from_server(s)))))
}
pub fn new_promise_client<T, F>(client_promise: F) -> T
where T: ::capnp::capability::FromClientHook,
F: ::futures::Future<Output=Result<capnp::capability::Client,Error>>,
F: 'static + Unpin
{
let mut queued_client = crate::queued::Client::new(None);
let weak_client = Rc::downgrade(&queued_client.inner);
queued_client.drive(client_promise.then(move |r| {
if let Some(queued_inner) = weak_client.upgrade() {
crate::queued::ClientInner::resolve(&queued_inner, r.map(|c| c.hook));
}
Promise::ok(())
}));
T::new(Box::new(queued_client))
}
struct SystemTaskReaper;
impl crate::task_set::TaskReaper<Error> for SystemTaskReaper {
fn task_failed(&mut self, error: Error) {
println!("ERROR: {}", error);
}
}
pub struct ImbuedMessageBuilder<A> where A: ::capnp::message::Allocator {
builder: ::capnp::message::Builder<A>,
cap_table: Vec<Option<Box<dyn (::capnp::private::capability::ClientHook)>>>,
}
impl <A> ImbuedMessageBuilder<A> where A: ::capnp::message::Allocator {
pub fn new(allocator: A) -> Self {
ImbuedMessageBuilder {
builder: ::capnp::message::Builder::new(allocator),
cap_table: Vec::new(),
}
}
pub fn get_root<'a, T>(&'a mut self) -> ::capnp::Result<T>
where T: ::capnp::traits::FromPointerBuilder<'a>
{
use capnp::traits::ImbueMut;
let mut root: ::capnp::any_pointer::Builder = self.builder.get_root()?;
root.imbue_mut(&mut self.cap_table);
root.get_as()
}
pub fn set_root<To, From>(&mut self, value: From) -> ::capnp::Result<()>
where From: ::capnp::traits::SetPointerBuilder<To>
{
use capnp::traits::ImbueMut;
let mut root: ::capnp::any_pointer::Builder = self.builder.get_root()?;
root.imbue_mut(&mut self.cap_table);
root.set_as(value)
}
}
fn canceled_to_error(_e: futures::channel::oneshot::Canceled) -> Error {
Error::failed(format!("oneshot was canceled"))
}