-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathhandler.rs
More file actions
176 lines (164 loc) · 6.15 KB
/
Copy pathhandler.rs
File metadata and controls
176 lines (164 loc) · 6.15 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
use crate::FieldMap;
use crate::p3::bindings::http::client::{Host, HostWithStore};
use crate::p3::bindings::http::types::{Request, Response};
use crate::p3::body::{Body, BodyExt as _};
use crate::p3::{HttpError, HttpResult};
use crate::{Error, WasiHttp, WasiHttpCtxView};
use core::task::{Context, Poll, Waker};
use http_body_util::BodyExt as _;
use std::sync::Arc;
use tokio::sync::oneshot;
use tokio::task::{self, JoinHandle};
use tracing::debug;
use wasmtime::component::{Accessor, Resource};
use wasmtime::error::Context as _;
/// A wrapper around [`JoinHandle`], which will [`JoinHandle::abort`] the task
/// when dropped
struct AbortOnDropJoinHandle(JoinHandle<()>);
impl Drop for AbortOnDropJoinHandle {
fn drop(&mut self) {
self.0.abort();
}
}
const DROPPED_FUTURE_ERROR: &str =
"Future indicating transmission result dropped without being resolved.";
async fn io_task_result(
rx: oneshot::Receiver<(
Option<Arc<AbortOnDropJoinHandle>>,
oneshot::Receiver<Result<(), Error>>,
)>,
) -> Result<(), Error> {
let Ok((_io, io_result_rx)) = rx.await else {
return Err(Error::InternalError(Some(DROPPED_FUTURE_ERROR.to_string())));
};
io_result_rx
.await
.unwrap_or_else(|_| Err(Error::InternalError(Some(DROPPED_FUTURE_ERROR.to_string()))))
}
fn send_dummy_io(
result: Result<(), Error>,
io_result_tx: oneshot::Sender<(
Option<Arc<AbortOnDropJoinHandle>>,
oneshot::Receiver<Result<(), Error>>,
)>,
) {
let (tx, rx) = oneshot::channel();
let _ = tx.send(result);
let _ = io_result_tx.send((None, rx));
}
fn send_dummy_io_err<T>(
store: &Accessor<T, WasiHttp>,
e: Error,
io_result_tx: oneshot::Sender<(
Option<Arc<AbortOnDropJoinHandle>>,
oneshot::Receiver<Result<(), Error>>,
)>,
) -> HttpError {
let err_code = store.with(|mut store| store.get().error_to_p3(&e));
send_dummy_io(Err(e), io_result_tx);
err_code.into()
}
impl<T> HostWithStore<T> for WasiHttp {
async fn send(
store: &Accessor<T, Self>,
req: Resource<Request>,
) -> HttpResult<Resource<Response>> {
// A handle to the I/O task, if spawned, will be sent on this channel
// and kept as part of request body state
let (io_task_tx, io_task_rx) = oneshot::channel();
// A handle to the I/O task, if spawned, will be sent on this channel
// along with the result receiver
let (io_result_tx, io_result_rx) = oneshot::channel();
// Response processing result will be sent on this channel
let (res_result_tx, res_result_rx) = oneshot::channel();
let getter = store.getter();
let fut = store.with(|mut store| {
let WasiHttpCtxView { table, .. } = store.get();
let req = table
.delete(req)
.context("failed to delete request from table")
.map_err(HttpError::trap)?;
let (req, options) =
req.into_http_with_getter(&mut store, io_task_result(io_result_rx), getter)?;
HttpResult::Ok(store.get().hooks.send_request(
// Attach a reference to the io task to the body so that it
// isn't cancelled if the body is dropped.
req.map(|body| body.with_state(io_task_rx).boxed_unsync()),
options.as_deref().copied(),
Box::new(async {
// Forward the response processing result to `WasiHttpCtx` implementation
let Ok(fut) = res_result_rx.await else {
return Ok(());
};
Box::into_pin(fut).await
}),
))
});
let fut = match fut {
Ok(fut) => fut,
Err(e) => match e.downcast() {
Ok(err_code) => {
send_dummy_io(Err(err_code.clone().into()), io_result_tx);
return Err(err_code.into());
}
Err(e) => {
let e = Error::InternalError(Some(format!("{e}")));
return Err(send_dummy_io_err(store, e, io_result_tx));
}
},
};
let (res, io) = match Box::into_pin(fut).await {
Ok(r) => r,
Err(e) => {
return Err(send_dummy_io_err(store, e, io_result_tx));
}
};
let (
http::response::Parts {
status, headers, ..
},
body,
) = res.into_parts();
let mut io = Box::into_pin(io);
let body = match io.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
Poll::Ready(Ok(())) => {
send_dummy_io(Ok(()), io_result_tx);
body
}
Poll::Ready(Err(e)) => {
return Err(send_dummy_io_err(store, e, io_result_tx));
}
Poll::Pending => {
// I/O driver still needs to be polled, spawn a task and send handles to it
let (tx, rx) = oneshot::channel();
let io = Arc::new(AbortOnDropJoinHandle(task::spawn(async move {
let res = io.await;
debug!(?res, "`send_request` I/O future finished");
_ = tx.send(res);
})));
_ = io_result_tx.send((Some(Arc::clone(&io)), rx));
_ = io_task_tx.send(Arc::clone(&io));
// Attach a reference to the io task to the body so that it
// isn't cancelled if the body is dropped.
body.with_state(io).boxed_unsync()
}
};
store.with(|mut store| {
let res = Response {
status,
headers: FieldMap::new_immutable(store.get().hooks, headers),
body: Body::Host {
body,
result_tx: res_result_tx,
},
};
store
.get()
.table
.push(res)
.context("failed to push response to table")
.map_err(HttpError::trap)
})
}
}
impl Host for WasiHttpCtxView<'_> {}