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
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
use crate::io::stream::StreamContext;
use crate::io::PartBuffer;
use crate::io::PartStream;
use crate::io::SizeHint;
use crate::io::PartData;
use std::task::Poll;
use pin_project_lite::pin_project;
pin_project! {
/// A wrapper that implements [`PartStream`] trait for an inner type
/// that implements Tokio's IO traits.
///
/// The adapter acquires one part-sized envelope from the transfer manager's
/// shared memory pool. Partial bytes and their reservation remain live
/// across `Poll::Pending`; a completed part is published without copying.
///
/// The inner reader must fill the [`ReadBuf`](tokio::io::ReadBuf) it is
/// given. A read that fills a different buffer fails the upload. The first
/// read that returns no data ends the stream, and the reader is not polled
/// after it.
///
/// # Examples
///
/// ```
/// use aws_s3_transfer::io::adapters::TokioIo;
/// use aws_s3_transfer::io::{InputStream, SizeHint};
/// use tokio::io::AsyncRead;
///
/// fn into_input_stream<T: AsyncRead + Send + Sync + 'static>(inner: T, content_length: u64) -> InputStream {
/// InputStream::from_part_stream(TokioIo::new(inner, SizeHint::exact(content_length)))
/// }
/// ```
#[derive(Debug)]
pub struct TokioIo<T> {
#[pin]
inner: T,
size_hint: SizeHint,
buffer: Option<PartBuffer>,
next_part: u64,
// Set by the first zero-byte read. The reader is not polled again after it, so data a
// source produces after end-of-file is never uploaded.
eof: bool,
}
}
impl<T> TokioIo<T> {
/// Wrap a type implementing Tokio's IO traits.
pub fn new(inner: T, size_hint: SizeHint) -> Self {
Self {
inner,
size_hint,
buffer: None,
next_part: 1,
eof: false,
}
}
/// Borrow the inner type
pub fn inner(&self) -> &T {
&self.inner
}
/// Mutably borrow the inner type
pub fn inner_mut(&mut self) -> &mut T {
&mut self.inner
}
}
impl<T> PartStream for TokioIo<T>
where
T: tokio::io::AsyncRead,
{
fn poll_part(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
stream_cx: &StreamContext,
) -> std::task::Poll<Option<std::io::Result<PartData>>> {
let mut this = self.project();
if *this.eof {
return Poll::Ready(None);
}
let part_buffer = this.buffer.get_or_insert_with(|| stream_cx.part_buffer());
match part_buffer.poll_acquire(cx, stream_cx.part_size()) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(())) => {}
Poll::Ready(Err(error)) => {
*this.buffer = None;
return Poll::Ready(Some(Err(error)));
}
}
loop {
let part_buffer = this
.buffer
.as_mut()
.expect("part buffer disappeared while reading");
// SAFETY: `ReadBuf` and `poll_read` promise not to set any uninitialized bytes into `dst`.
let dst = unsafe { part_buffer.chunk_mut().as_uninit_slice_mut() };
let mut buf = tokio::io::ReadBuf::uninit(dst);
let lent_ptr = buf.filled().as_ptr();
match this.inner.as_mut().poll_read(cx, &mut buf) {
Poll::Ready(result) => match result {
Ok(_) => {
let n = buf.filled().len();
// A reader can only fill the `ReadBuf` it was lent, which holds at most
// `dst`, so comparing the filled pointer is enough. A reader that assigns
// another `ReadBuf` to `*buf` reports bytes that were never written to
// `dst`; advancing by them would publish pooled memory. tokio's `read_buf`
// makes the same check.
if buf.filled().as_ptr() != lent_ptr {
*this.buffer = None;
return Poll::Ready(Some(Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"TokioIo reader replaced the ReadBuf it was given",
))));
}
if n == 0 {
*this.eof = true;
} else {
// SAFETY: the filled region is the first `n` bytes of `dst`.
// `ReadBuf::uninit` marked none of `dst` initialized, and `ReadBuf`
// only marks initialized bytes as filled, so this read wrote them.
unsafe {
part_buffer.advance_mut(n);
}
}
// full part available or EOF with partial data already buffered
if part_buffer.len() == stream_cx.part_size()
|| (n == 0 && !part_buffer.is_empty())
{
let data = this
.buffer
.take()
.expect("completed part lost its buffer")
.freeze();
let part_number = *this.next_part;
*this.next_part += 1;
// A full part is returned without reading ahead: the next poll
// reports the end of the stream by returning `None`.
let part = PartData::from_segmented(part_number, data);
return Poll::Ready(Some(Ok(part)));
} else if n == 0 {
// EOF
*this.buffer = None;
return Poll::Ready(None);
}
}
Err(err) => {
*this.buffer = None;
return Poll::Ready(Some(Err(err)));
}
},
Poll::Pending => return Poll::Pending,
}
}
}
fn size_hint(&self) -> crate::io::SizeHint {
self.size_hint
}
}
#[cfg(test)]
mod tests {
use super::TokioIo;
use crate::config::MemoryBudgetConfig;
use crate::io::stream::StreamContext;
use crate::io::PartData;
use crate::io::PartStream;
use crate::io::SizeHint;
use crate::memory::BufferPool;
use crate::types::ByteSize;
use futures_test::task::new_count_waker;
use std::pin::{pin, Pin};
use std::task::{Context, Poll};
use tokio::io::ReadBuf;
use tokio_test::io::Builder;
use tokio_test::{assert_pending, assert_ready};
fn test_stream_cx(part_size: usize) -> (StreamContext, BufferPool) {
let buffer_pool = BufferPool::builder()
.memory_budget(MemoryBudgetConfig::Limit(ByteSize::new(1024 * 1024)))
.build()
.unwrap();
(
StreamContext::new(
part_size,
buffer_pool.clone(),
false,
std::sync::Arc::new(crate::transfer::MetricsState::new()),
std::sync::Arc::new(crate::telemetry::Telemetry::new(
std::time::Duration::from_secs(1),
)),
),
buffer_pool,
)
}
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn test_tokio_adapter_e2e() {
let (mock, mut handle) = Builder::new().build_with_handle();
let part_size = 5;
let mut io = pin!(TokioIo::new(mock, SizeHint::exact(10)));
let (waker, awoken_cnt) = new_count_waker();
let mut task_cx = Context::from_waker(&waker);
let (stream_cx, pool) = test_stream_cx(part_size);
assert_pending!(io.as_mut().poll_part(&mut task_cx, &stream_cx));
assert_eq!(pool.metrics().in_use_bytes(), pool.carrier_size() as u64);
handle.read(b"hello");
assert_eq!(awoken_cnt.get(), 1);
let result = assert_ready!(io.as_mut().poll_part(&mut task_cx, &stream_cx))
.unwrap()
.unwrap();
let expected = PartData::new(1, "hello");
assert_eq!(expected, result);
assert_eq!(pool.metrics().in_use_bytes(), pool.carrier_size() as u64);
drop(result);
assert_eq!(pool.metrics().in_use_bytes(), 0);
assert_pending!(io.as_mut().poll_part(&mut task_cx, &stream_cx));
handle.read(b"world");
assert_eq!(awoken_cnt.get(), 2);
let result = assert_ready!(io.as_mut().poll_part(&mut task_cx, &stream_cx))
.unwrap()
.unwrap();
let expected = PartData::new(2, "world");
assert_eq!(expected, result);
drop(result);
drop(handle);
let result = assert_ready!(io.as_mut().poll_part(&mut task_cx, &stream_cx));
assert!(result.is_none());
assert_eq!(pool.metrics().in_use_bytes(), 0);
}
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn test_tokio_adapter_partial_reads() {
let (mock, mut handle) = Builder::new().build_with_handle();
let part_size = 10;
let mut io = pin!(TokioIo::new(mock, SizeHint::exact(16)));
let (waker, awoken_cnt) = new_count_waker();
let mut task_cx = Context::from_waker(&waker);
let (stream_cx, pool) = test_stream_cx(part_size);
// partial read
handle.read(b"hello");
assert_pending!(io.as_mut().poll_part(&mut task_cx, &stream_cx));
assert_eq!(pool.metrics().in_use_bytes(), pool.carrier_size() as u64);
handle.read(b"world"); // full part available
handle.read(b"second"); // last part less than part size
drop(handle);
assert_eq!(awoken_cnt.get(), 1);
// we have a full part available at this point so it should be yielded
let result = assert_ready!(io.as_mut().poll_part(&mut task_cx, &stream_cx))
.unwrap()
.unwrap();
let expected = PartData::new(1, "helloworld");
assert_eq!(expected, result);
drop(result);
// should hit EOF and get the last part less than configured part size
let result = assert_ready!(io.as_mut().poll_part(&mut task_cx, &stream_cx))
.unwrap()
.unwrap();
let expected = PartData::new(2, "second");
assert_eq!(expected, result);
drop(result);
// one final poll to actual get done signal
let result = assert_ready!(io.as_mut().poll_part(&mut task_cx, &stream_cx));
assert!(result.is_none());
assert_eq!(pool.metrics().in_use_bytes(), 0);
}
/// A reader that, on its first read, replaces the `ReadBuf` it was given with one over a
/// buffer of its own and marks `claim` bytes filled there. Later reads report end-of-file.
///
/// A reader written in safe code can do the same with `Box::leak`. This one frees its buffer
/// when it is dropped, so the tests leak nothing.
struct ReplacingReader {
claim: usize,
/// The replacement buffer, once the first read has swapped it in. `Drop` frees it.
replacement: Option<std::ptr::NonNull<[u8]>>,
}
impl tokio::io::AsyncRead for ReplacingReader {
fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
if self.replacement.is_none() {
let raw = Box::into_raw(vec![b'B'; self.claim].into_boxed_slice());
self.replacement = std::ptr::NonNull::new(raw);
// SAFETY: `raw` is a live allocation that nothing else references. It stays
// valid until `Drop`, and the reader outlives the `ReadBuf` this read assigns,
// which `poll_part` drops before it returns.
*buf = ReadBuf::new(unsafe { &mut *raw });
buf.set_filled(self.claim);
}
Poll::Ready(Ok(()))
}
}
impl Drop for ReplacingReader {
fn drop(&mut self) {
if let Some(raw) = self.replacement {
// SAFETY: `raw` came from `Box::into_raw` in `poll_read`, and the `ReadBuf` that
// borrowed it is gone.
drop(unsafe { Box::from_raw(raw.as_ptr()) });
}
}
}
/// A reader that replaces the `ReadBuf` it was given fails the read with `InvalidData` and
/// returns the part's pooled storage, whether its claim fits the lent slice or runs past it.
#[test]
fn test_tokio_adapter_rejects_replaced_read_buf() {
let carrier_size = test_stream_cx(1).1.carrier_size();
let cases = [
// The claim fits the lent slice.
(10, 3),
// The adapter lends one carrier at a time, so a part spanning several carriers
// leaves room in the part for a claim larger than the lent slice.
(4 * carrier_size, 2 * carrier_size),
];
for (part_size, claim) in cases {
let case = format!("part size {part_size}, claim {claim}");
let (stream_cx, pool) = test_stream_cx(part_size);
let reader = ReplacingReader {
claim,
replacement: None,
};
let mut io = pin!(TokioIo::new(reader, SizeHint::default()));
let (waker, _) = new_count_waker();
let mut task_cx = Context::from_waker(&waker);
let result = assert_ready!(io.as_mut().poll_part(&mut task_cx, &stream_cx));
let Some(Err(error)) = result else {
panic!("{case}: a replaced buffer must fail the read, got {result:?}");
};
assert_eq!(std::io::ErrorKind::InvalidData, error.kind(), "{case}");
assert_eq!(pool.metrics().in_use_bytes(), 0, "{case}");
}
}
/// A reader that plays back a script of reads, where `Some(bytes)` returns those bytes and
/// `None` reports end-of-file, and counts how often it is polled.
struct ScriptedReader {
script: std::collections::VecDeque<Option<&'static [u8]>>,
polls: usize,
}
impl tokio::io::AsyncRead for ScriptedReader {
fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
self.polls += 1;
if let Some(Some(bytes)) = self.script.pop_front() {
buf.put_slice(bytes);
}
Poll::Ready(Ok(()))
}
}
/// The adapter stops at the reader's first end-of-file, as tokio-util's `ReaderStream` does,
/// so data the source produces afterwards is not uploaded.
#[cfg_attr(miri, ignore)]
#[test]
fn test_tokio_adapter_stops_at_first_end_of_file() {
let (stream_cx, pool) = test_stream_cx(10);
let reader = ScriptedReader {
script: [Some(&b"abc"[..]), None, Some(&b"def"[..]), None].into(),
polls: 0,
};
let mut io = pin!(TokioIo::new(reader, SizeHint::default()));
let (waker, _) = new_count_waker();
let mut task_cx = Context::from_waker(&waker);
let part = assert_ready!(io.as_mut().poll_part(&mut task_cx, &stream_cx))
.unwrap()
.unwrap();
assert_eq!(PartData::new(1, "abc"), part);
drop(part);
let result = assert_ready!(io.as_mut().poll_part(&mut task_cx, &stream_cx));
assert!(result.is_none(), "expected end-of-stream, got {result:?}");
assert_eq!(
2,
io.inner().polls,
"the reader must not be read after end-of-file"
);
assert_eq!(pool.metrics().in_use_bytes(), 0);
}
}