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
use std::{
ffi::c_void,
pin::Pin,
task::{Context, Poll},
};
use futures::FutureExt;
use crate::{
Result,
librados::{
rados_aio_create_completion, rados_aio_get_return_value, rados_aio_is_complete,
rados_aio_is_safe, rados_aio_release, rados_completion_t,
},
};
#[derive(Debug)]
pub struct RadosCompletion<T, F>
where
T: 'static,
{
f: F,
resolve_on_safe: bool,
state: T,
}
unsafe impl<T, F> Send for RadosCompletion<T, F> {}
impl<T, F> RadosCompletion<T, F>
where
T: 'static,
F: FnOnce(rados_completion_t, Pin<&mut T>) -> Result<()>,
{
/// Create a new [`RadosCompletion`].
///
/// The `resolve_on_safe` argument controls the stage at which the
/// the created [`RadosCompletion`] is considered to be
/// "done": on the `complete` callback if `!resolve_on_safe`, and
/// on the `safe` callback if `resolve_on_safe`.
///
/// It is important to note that some librados async operations
/// _never_ call the `safe` callback, so restricting the inputs
/// to this value appropriatly is important to avoid memory leaks.
///
/// The `f` function is responsible for creating the actual operation
/// that this completion will track: it must return a boolean indicating
/// success.
///
/// The lifetime of the [`rados_completion_t`] passed to `F` is exactly equal
/// to the lifetime of the returned [`RadosCompletion`], but you _must not_
/// use it outside of the closure.
///
/// For more information about the respective callbacks, see: [`rados_aio_create_completion`][0]
///
/// # Safety
/// Calling `f` _must only_ return `Err(_)` if creation of the underlying completion
/// operation has failed. If `Err(_)` is returned, but the `complete` or `safe`
/// callback of this [`RadosCompletion`] are called anyways, a double-free will occur.
///
/// Always returning `Ok(())` is allowed and does not cause UB. However, it does
/// cause memory to leak.
///
/// ## State ownership
/// All of the data that the completion attached to this [`RadosCompletion`] stores
/// results in _must_ be part of `state`. Examples of such data are output buffers,
/// output lengths, and read/write operation return values.
///
/// This restriction applies because there is no easy way to directly cancel the
/// underlying completion and to guarantee that it stops modifying buffers immediately.
///
/// TODO: this section is probably untrue. We can likely `wait_for_complete_and_cb`
/// in `Drop`. Doing that will make misusing this a lot harder.
///
/// [0]: https://docs.ceph.com/en/latest/rados/api/librados/#c.rados_aio_create_completion
pub unsafe fn new_with(resolve_on_safe: bool, state: T, f: F) -> Result<Self> {
Ok(Self {
f,
resolve_on_safe,
state,
})
}
pub async fn wait_for(self) -> Result<(usize, T)> {
let mut completion = None;
let mut create_completion = Some(|| unsafe {
RadosCompletionInner::new_with(self.resolve_on_safe, self.state, self.f)
});
core::future::poll_fn(|cx| {
let completion = completion.get_or_insert_with(|| {
let create = create_completion
.take()
.expect("Tried to construct completion multiple times");
create()
});
match completion {
Ok(v) => v.poll(cx).map(|(res, state)| {
if let Ok(len) = usize::try_from(res) {
Ok((len, state))
} else {
Err(res.into())
}
}),
Err(e) => Poll::Ready(Err(e.clone())),
}
})
.await
}
}
#[derive(Debug)]
struct RadosCompletionInner<T>
where
T: 'static,
{
safe: bool,
completion: rados_completion_t,
rx: futures::channel::oneshot::Receiver<T>,
}
impl<T> RadosCompletionInner<T>
where
T: 'static,
{
/// # Safety
/// See [`RadosCompletion::new_with`].
unsafe fn new_with<F>(resolve_on_safe: bool, state: T, f: F) -> Result<Self>
where
F: FnOnce(rados_completion_t, Pin<&mut T>) -> Result<()>,
{
type Tx<T> = futures::channel::oneshot::Sender<T>;
let (tx, rx): (Tx<T>, _) = futures::channel::oneshot::channel();
struct State<T> {
generic: T,
channel: Tx<T>,
}
/// The callback function used to indicate completion.
unsafe extern "C" fn wake_waker_and_drop_box<T>(_: rados_completion_t, arg: *mut c_void) {
// SAFETY: `arg` is a type-erased pointer to a `State<Tx>` that
// is constructed by calling `Box::into_raw`, and `from_raw`
// is called exactly once for the passed-in value.
let boxed = unsafe { Box::from_raw(arg as *mut State<T>) };
let arg = *boxed;
arg.channel.send(arg.generic).ok();
}
let mut completion = std::ptr::null_mut();
let callback = wake_waker_and_drop_box::<T> as _;
let (complete, safe) = if resolve_on_safe {
(None, Some(callback))
} else {
(Some(callback), None)
};
let state = State {
generic: state,
channel: tx,
};
let state = Box::leak(Box::new(state));
// SAFETY: `tx` is valid for the duration of the completion's existence,
// and the function pointers are valid.
let completion_created = unsafe {
rados_aio_create_completion(state as *mut _ as _, complete, safe, &mut completion)
};
let generic_state = unsafe { Pin::new_unchecked(&mut state.generic) };
assert!(
completion_created == 0,
"rados_aio_create_completion returned undocumented return code"
);
let start = f(completion, generic_state);
if let Err(e) = start {
// Creation of completion operation failed, so the wake-and-drop
// callback will never be called.
//
// To prevent memory leaks, recreate the box containing the
// sender and drop it.
// SAFETY: `arg` is a pointer that is constructed by calling
// `Box::into_raw`, and `from_raw` is called exactly once
// for the pointer.
drop(unsafe { Box::from_raw(state) });
return Err(e);
}
Ok(Self {
safe: resolve_on_safe,
completion,
rx,
})
}
pub fn poll(&mut self, cx: &mut Context<'_>) -> Poll<(i32, T)> {
if let Poll::Ready(state) = self.rx.poll_unpin(cx) {
let Ok(state) = state else {
panic!("Re-polled completed future")
};
if self.safe && unsafe { rados_aio_is_safe(self.completion) } != 0 {
let value = unsafe { rados_aio_get_return_value(self.completion) };
Poll::Ready((value, state))
} else if unsafe { rados_aio_is_complete(self.completion) } != 0 {
let value = unsafe { rados_aio_get_return_value(self.completion) };
Poll::Ready((value, state))
} else {
unreachable!()
}
} else {
Poll::Pending
}
}
}
impl<T> Drop for RadosCompletionInner<T> {
fn drop(&mut self) {
unsafe { rados_aio_release(self.completion) }
}
}