ostrya_remote/proto/frame.rs
1//! The frame codec, the chunked object stream, and the pull bodies.
2
3use std::future::poll_fn;
4use std::io;
5use std::pin::Pin;
6use std::task::{Context, Poll, ready};
7
8use futures_io::{AsyncRead, AsyncWrite};
9use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
10
11use super::message::{get_reply_frame, object_header_frame};
12use super::{
13 ABANDON, ErrorMessage, GetReply, Kind, MAX_FRAME_LIMIT, MIN_FRAME_LIMIT, Message, protocol,
14};
15use crate::error::{Error, Result};
16
17fn clamp_limit(limit: u32) -> u32 {
18 limit.clamp(MIN_FRAME_LIMIT, MAX_FRAME_LIMIT)
19}
20
21fn eof() -> Error {
22 Error::Io(io::ErrorKind::UnexpectedEof.into())
23}
24
25fn limit_exceeded(what: &str, len: u32, limit: u32) -> Error {
26 Error::LimitExceeded(format!("{what} of {len} bytes is over the limit {limit}"))
27}
28
29/// The kind of a body. It sets the message that must follow the abandon
30/// marker.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub(crate) enum BodyKind {
33 /// An object of the push, after an `ObjectHeader`. An `Abort` message
34 /// follows the marker.
35 Object,
36 /// A body of the pull, after a `GetReply` whose `found` is `true`. An
37 /// `Error` message follows the marker.
38 Pull,
39}
40
41impl BodyKind {
42 /// Returns the kind of body that follows `msg`, or `None` if no body
43 /// follows.
44 fn after(msg: &Message) -> Option<BodyKind> {
45 match msg {
46 Message::ObjectHeader(_) => Some(BodyKind::Object),
47 Message::GetReply(GetReply { found: true, .. }) => Some(BodyKind::Pull),
48 _ => None,
49 }
50 }
51}
52
53#[derive(Debug)]
54enum ReadState {
55 Frames,
56 /// Inside a body of `kind`. `remaining` is the number of bytes of the
57 /// current chunk that are not read. If it is 0, the next read starts
58 /// with the chunk length, and `prefix` holds the `got` bytes of it that
59 /// are read.
60 Body {
61 kind: BodyKind,
62 remaining: u32,
63 prefix: [u8; 4],
64 got: u8,
65 },
66}
67
68impl ReadState {
69 fn body(kind: BodyKind) -> ReadState {
70 ReadState::Body {
71 kind,
72 remaining: 0,
73 prefix: [0; 4],
74 got: 0,
75 }
76 }
77}
78
79/// One step of the object stream.
80pub(crate) enum Step {
81 Data(usize),
82 End,
83 /// The abandon marker in a body of this kind. The message that must
84 /// follow the marker is not read.
85 Marker(BodyKind),
86}
87
88/// The result of one [`FrameReader::read_object_data`] call.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum ObjectRead {
91 /// The number of body bytes at the start of the buffer.
92 Data(usize),
93 /// The end of the body, after which frames follow.
94 End,
95 /// An object of the push that the sender abandoned.
96 ///
97 /// The call read the `Abort` message that must follow the marker. If the
98 /// sender abandons a body of the pull, the call returns the [`Error`]
99 /// variant of the code in the `Error` message.
100 Abandoned,
101}
102
103/// A reader of frames, object chunks, and pull bodies on a stream.
104///
105/// A frame takes three reads and a chunk takes two, so a caller wraps a raw
106/// socket or pipe in a buffered reader. A buffered reader that passes a large
107/// read through to the stream does not copy the object bytes a second time.
108///
109/// The futures of the reader are not cancel-safe. A call that is dropped
110/// before it completes can leave part of a frame or of a chunk length read.
111/// The next call then reads from the middle of it. After a canceled call,
112/// the caller must drop the reader.
113#[derive(Debug)]
114pub struct FrameReader<R> {
115 inner: R,
116 limit: u32,
117 state: ReadState,
118}
119
120impl<R: AsyncRead + Unpin> FrameReader<R> {
121 /// Creates a reader with the limit [`MIN_FRAME_LIMIT`].
122 pub fn new(inner: R) -> Self {
123 FrameReader {
124 inner,
125 limit: MIN_FRAME_LIMIT,
126 state: ReadState::Frames,
127 }
128 }
129
130 /// Sets the frame and chunk limit of the reader.
131 ///
132 /// The value is clamped to [`MIN_FRAME_LIMIT`]`..=`[`MAX_FRAME_LIMIT`].
133 /// A client sets a read limit of its own here, for example
134 /// [`MAX_FRAME`], and gives the `max-frame` of the server to its
135 /// [`FrameWriter`] alone. The [frame rules](crate::proto#frames) give
136 /// the reason.
137 ///
138 /// [`MAX_FRAME`]: super::MAX_FRAME
139 pub fn set_limit(&mut self, limit: u32) {
140 self.limit = clamp_limit(limit);
141 }
142
143 /// Returns the frame and chunk limit.
144 pub fn limit(&self) -> u32 {
145 self.limit
146 }
147
148 /// Reads the next message.
149 ///
150 /// `Ok(None)` is an end of file at a frame boundary. After an
151 /// `ObjectHeader`, and after a `GetReply` whose `found` is `true`, the
152 /// caller must read the body to its end before the next message. It reads
153 /// the body with [`read_object_data`](Self::read_object_data) or
154 /// [`object_body`](Self::object_body).
155 ///
156 /// # Errors
157 ///
158 /// - [`Error::Protocol`] if the body of the previous message is not read to
159 /// its end.
160 /// - [`Error::Protocol`] if the frame length is 0, if the kind byte is not
161 /// a known kind, or if the body does not decode.
162 /// - [`Error::LimitExceeded`] if the frame length is more than the limit.
163 /// The reader checks the length before it reads or allocates the body.
164 /// - [`Error::Io`] of kind `UnexpectedEof` if the stream ends inside a
165 /// frame.
166 /// - [`Error::Io`] if a read of the stream fails.
167 pub async fn read_message(&mut self) -> Result<Option<Message>> {
168 if let ReadState::Body { .. } = self.state {
169 return Err(protocol("object data not read to its end"));
170 }
171 let mut prefix = [0u8; 4];
172 let mut got = 0;
173 while got < prefix.len() {
174 let n = self.inner.read(&mut prefix[got..]).await?;
175 if n == 0 {
176 return if got == 0 { Ok(None) } else { Err(eof()) };
177 }
178 got += n;
179 }
180 let len = u32::from_be_bytes(prefix);
181 if len == 0 {
182 return Err(protocol("frame of length 0"));
183 }
184 if len > self.limit {
185 return Err(limit_exceeded("frame", len, self.limit));
186 }
187 let mut kind = [0u8; 1];
188 self.inner.read_exact(&mut kind).await?;
189 let kind = Kind::from_u8(kind[0])?;
190 let mut body = vec![0u8; len as usize - 1];
191 self.inner.read_exact(&mut body).await?;
192 let msg = Message::decode(kind, &body)?;
193 if let Some(kind) = BodyKind::after(&msg) {
194 self.state = ReadState::body(kind);
195 }
196 Ok(Some(msg))
197 }
198
199 /// Returns an [`ObjectBody`] that reads the current object or pull body.
200 pub fn object_body(&mut self) -> ObjectBody<'_, R> {
201 ObjectBody {
202 reader: self,
203 state: BodyState::Reading,
204 error: None,
205 }
206 }
207
208 /// Reads bytes of the current object or pull body into `buf`.
209 ///
210 /// A chunk longer than `buf` arrives over several calls, so `buf` bounds
211 /// the memory. Inside a body, an empty `buf` reads nothing and gives
212 /// `ObjectRead::Data(0)`.
213 ///
214 /// If the call meets the abandon marker, it reads the message that must
215 /// follow the marker. In an object of the push, an `Abort` message gives
216 /// [`ObjectRead::Abandoned`].
217 ///
218 /// # Errors
219 ///
220 /// - [`Error::Protocol`] if the reader is not inside a body.
221 /// - [`Error::LimitExceeded`] if a chunk length is more than the limit.
222 /// - In a body of the pull, the [`Error`] variant of the code in the
223 /// `Error` message after the marker, for example [`Error::Internal`].
224 /// - [`Error::Protocol`] if a message of another kind follows the
225 /// marker.
226 /// - [`Error::Io`] of kind `UnexpectedEof` if the stream ends inside a
227 /// chunk, or after the marker and before the next message.
228 /// - [`Error::Io`] if a read of the stream fails.
229 /// - The errors of [`read_message`](Self::read_message) for the message
230 /// after the marker.
231 pub async fn read_object_data(&mut self, buf: &mut [u8]) -> Result<ObjectRead> {
232 match poll_fn(|cx| self.poll_step(cx, buf)).await? {
233 Step::Data(n) => Ok(ObjectRead::Data(n)),
234 Step::End => Ok(ObjectRead::End),
235 Step::Marker(kind) => self
236 .read_after_marker(kind)
237 .await
238 .map(|()| ObjectRead::Abandoned),
239 }
240 }
241
242 /// Reads the message that must follow the abandon marker in a body of
243 /// `kind`. After an object, an `Abort` message gives `Ok`. After a pull
244 /// body, an `Error` message gives the [`Error`] variant of its code.
245 /// Another message gives [`Error::Protocol`].
246 async fn read_after_marker(&mut self, kind: BodyKind) -> Result<()> {
247 match (kind, self.read_message().await?) {
248 (BodyKind::Object, Some(Message::Abort)) => Ok(()),
249 (BodyKind::Pull, Some(Message::Error(e))) => Err(e.into()),
250 (_, Some(other)) => {
251 // An ObjectHeader or a GetReply whose `found` is `true` sets
252 // the body state. This reset leaves the reader between frames.
253 self.state = ReadState::Frames;
254 Err(protocol(format!(
255 "{:?} after the abandon marker",
256 other.kind()
257 )))
258 }
259 (_, None) => Err(eof()),
260 }
261 }
262
263 /// Reads the next step of the object stream into `buf`. The state keeps
264 /// a partial chunk length, so a pending read loses no byte.
265 pub(crate) fn poll_step(&mut self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<Step>> {
266 let FrameReader {
267 inner,
268 limit,
269 state,
270 } = self;
271 let ReadState::Body {
272 kind,
273 remaining,
274 prefix,
275 got,
276 } = state
277 else {
278 return Poll::Ready(Err(protocol("no object to read")));
279 };
280 if buf.is_empty() {
281 return Poll::Ready(Ok(Step::Data(0)));
282 }
283 if *remaining == 0 {
284 while usize::from(*got) < prefix.len() {
285 let n =
286 ready!(Pin::new(&mut *inner).poll_read(cx, &mut prefix[usize::from(*got)..]))?;
287 if n == 0 {
288 return Poll::Ready(Err(eof()));
289 }
290 *got += n as u8;
291 }
292 *got = 0;
293 match u32::from_be_bytes(*prefix) {
294 0 => {
295 *state = ReadState::Frames;
296 return Poll::Ready(Ok(Step::End));
297 }
298 ABANDON => {
299 let kind = *kind;
300 *state = ReadState::Frames;
301 return Poll::Ready(Ok(Step::Marker(kind)));
302 }
303 len if len > *limit => {
304 return Poll::Ready(Err(limit_exceeded("chunk", len, *limit)));
305 }
306 len => *remaining = len,
307 }
308 }
309 let want = buf.len().min(*remaining as usize);
310 let n = ready!(Pin::new(&mut *inner).poll_read(cx, &mut buf[..want]))?;
311 if n == 0 {
312 return Poll::Ready(Err(eof()));
313 }
314 *remaining -= n as u32;
315 Poll::Ready(Ok(Step::Data(n)))
316 }
317
318 /// Returns a reference to the underlying stream.
319 ///
320 /// If the stream is a buffered reader, a caller can look at the bytes in
321 /// the buffer with no read. An example is a check for a whole frame in
322 /// the buffer.
323 pub fn get_ref(&self) -> &R {
324 &self.inner
325 }
326
327 /// Returns the underlying stream.
328 pub fn into_inner(self) -> R {
329 self.inner
330 }
331}
332
333#[derive(Debug, Clone, Copy, PartialEq, Eq)]
334enum BodyState {
335 Reading,
336 Finished,
337 Abandoned(BodyKind),
338 /// A read failed with an error of this kind. Every later read fails with
339 /// the same kind.
340 Failed(io::ErrorKind),
341}
342
343/// One object or pull body of a [`FrameReader`], read as an `AsyncRead`.
344///
345/// A read returns body bytes until the chunk of length 0, and then end of
346/// file. A read that meets the abandon marker, a codec error, or an error of
347/// the stream fails with an `io::Error`, and every later read fails too.
348///
349/// - After the abandon marker, [`is_abandoned`](Self::is_abandoned) returns
350/// `true`, and [`finish_abandon`](Self::finish_abandon) reads the message
351/// that must follow the marker.
352/// - After another failure, [`take_error`](Self::take_error) returns the
353/// [`Error`] of the reader. The `io::Error` of the read does not keep the
354/// variant or its wire code.
355///
356/// The body keeps a partial chunk length in the reader, so a read that returns
357/// `Pending` loses no byte. A read that is dropped before it completes leaves
358/// the reader in a consistent state.
359#[derive(Debug)]
360pub struct ObjectBody<'a, R> {
361 reader: &'a mut FrameReader<R>,
362 state: BodyState,
363 error: Option<Error>,
364}
365
366impl<R: AsyncRead + Unpin> ObjectBody<'_, R> {
367 /// Returns `true` if the body ended with the chunk of length 0.
368 pub fn is_finished(&self) -> bool {
369 self.state == BodyState::Finished
370 }
371
372 /// Returns `true` if the sender abandoned the body with the abandon
373 /// marker.
374 pub fn is_abandoned(&self) -> bool {
375 matches!(self.state, BodyState::Abandoned(_))
376 }
377
378 /// Takes the [`Error`] of the read that failed.
379 ///
380 /// The error is a codec error, for example [`Error::LimitExceeded`] for a
381 /// chunk over the limit, or an [`Error::Io`] from the stream. The call
382 /// returns `None` if no read failed, if the abandon marker is the only
383 /// failure, or if an earlier call took the error.
384 pub fn take_error(&mut self) -> Option<Error> {
385 self.error.take()
386 }
387
388 /// Reads the message that must follow the abandon marker.
389 ///
390 /// In an object of the push, an `Abort` message gives `Ok`. In a body of
391 /// the pull, an `Error` message gives the [`Error`] variant of its code.
392 ///
393 /// # Errors
394 ///
395 /// - [`Error::Protocol`] if no read met the abandon marker.
396 /// - In a body of the pull, the [`Error`] variant of the code in the
397 /// `Error` message, for example [`Error::Internal`].
398 /// - [`Error::Protocol`] if a message of another kind follows the
399 /// marker.
400 /// - [`Error::Io`] of kind `UnexpectedEof` if the stream ends before the
401 /// message.
402 /// - The errors of [`FrameReader::read_message`] for the message.
403 pub async fn finish_abandon(self) -> Result<()> {
404 let BodyState::Abandoned(kind) = self.state else {
405 return Err(protocol("the object was not abandoned"));
406 };
407 self.reader.read_after_marker(kind).await
408 }
409}
410
411impl<R: AsyncRead + Unpin> AsyncRead for ObjectBody<'_, R> {
412 fn poll_read(
413 self: Pin<&mut Self>,
414 cx: &mut Context<'_>,
415 buf: &mut [u8],
416 ) -> Poll<io::Result<usize>> {
417 let me = self.get_mut();
418 match me.state {
419 BodyState::Reading => {}
420 BodyState::Finished => return Poll::Ready(Ok(0)),
421 BodyState::Abandoned(_) => {
422 return Poll::Ready(Err(io::Error::other("object abandoned")));
423 }
424 BodyState::Failed(kind) => {
425 return Poll::Ready(Err(io::Error::new(kind, "object stream failed")));
426 }
427 }
428 if buf.is_empty() {
429 return Poll::Ready(Ok(0));
430 }
431 // The loop fills `buf` across chunk boundaries while the stream has
432 // bytes ready, so small chunks do not make small reads. If `buf` holds
433 // bytes at a pending read, the end, the marker, or an error, the read
434 // returns those bytes. The next read reports the end, the marker, or
435 // the error.
436 let mut filled = 0;
437 loop {
438 let step = match me.reader.poll_step(cx, &mut buf[filled..]) {
439 Poll::Ready(step) => step,
440 Poll::Pending if filled > 0 => return Poll::Ready(Ok(filled)),
441 Poll::Pending => return Poll::Pending,
442 };
443 match step {
444 Ok(Step::Data(n)) => {
445 filled += n;
446 if filled == buf.len() {
447 return Poll::Ready(Ok(filled));
448 }
449 }
450 Ok(Step::End) => {
451 me.state = BodyState::Finished;
452 return Poll::Ready(Ok(filled));
453 }
454 Ok(Step::Marker(kind)) => {
455 me.state = BodyState::Abandoned(kind);
456 if filled > 0 {
457 return Poll::Ready(Ok(filled));
458 }
459 return Poll::Ready(Err(io::Error::other("object abandoned")));
460 }
461 Err(e) => {
462 let io = match &e {
463 Error::Io(io) => io::Error::new(io.kind(), io.to_string()),
464 other => io::Error::other(other.to_string()),
465 };
466 me.error = Some(e);
467 me.state = BodyState::Failed(io.kind());
468 if filled > 0 {
469 return Poll::Ready(Ok(filled));
470 }
471 return Poll::Ready(Err(io));
472 }
473 }
474 }
475 }
476}
477
478/// Returns the frame of `msg`: the length, the kind, and the body. A frame
479/// over `limit` is [`Error::LimitExceeded`]. A caller that sends the frame as
480/// one buffer takes it from here with no copy of its own.
481pub(crate) fn encode_frame(msg: &Message, limit: u32) -> Result<Vec<u8>> {
482 let body = msg.encode_body()?;
483 let len = u32::try_from(body.len() + 1)
484 .ok()
485 .filter(|len| *len <= limit)
486 .ok_or_else(|| {
487 Error::LimitExceeded(format!(
488 "frame of {} bytes is over the limit {limit}",
489 body.len() + 1
490 ))
491 })?;
492 let mut frame = Vec::with_capacity(4 + len as usize);
493 frame.extend_from_slice(&len.to_be_bytes());
494 frame.push(msg.kind().as_u8());
495 frame.extend_from_slice(&body);
496 Ok(frame)
497}
498
499/// A writer of frames, object chunks, and pull bodies on a stream.
500///
501/// The writer enters the body state when it writes an `ObjectHeader`, or a
502/// `GetReply` whose `found` is `true`.
503///
504/// - [`write_object_data`](Self::write_object_data) and
505/// [`end_object`](Self::end_object) serve both body kinds.
506/// - [`abandon_object`](Self::abandon_object) abandons an object of the
507/// push.
508/// - [`abandon_body`](Self::abandon_body) abandons a body of the pull.
509///
510/// The writer holds no object bytes and does not flush. The caller flushes
511/// with [`flush`](Self::flush), or wraps the stream in a buffered writer.
512/// A frame is one write, and a chunk is two: the length and the data. A
513/// caller wraps a raw socket or pipe in a buffered writer.
514///
515/// The futures of the writer are not cancel-safe. A call that is dropped
516/// before it completes can leave part of a frame or a chunk written. After a
517/// canceled call, the caller must drop the writer.
518#[derive(Debug)]
519pub struct FrameWriter<W> {
520 inner: W,
521 limit: u32,
522 body: Option<BodyKind>,
523}
524
525impl<W: AsyncWrite + Unpin> FrameWriter<W> {
526 /// Creates a writer with the limit [`MIN_FRAME_LIMIT`].
527 pub fn new(inner: W) -> Self {
528 FrameWriter {
529 inner,
530 limit: MIN_FRAME_LIMIT,
531 body: None,
532 }
533 }
534
535 /// Sets the frame and chunk limit to the `max-frame` that the peer
536 /// announced.
537 ///
538 /// The value is clamped to [`MIN_FRAME_LIMIT`]`..=`[`MAX_FRAME_LIMIT`].
539 /// [`HelloReply::max_frame`](super::HelloReply::max_frame) holds the
540 /// announced value. The writer applies the limit to each frame and each
541 /// chunk that it writes after the call.
542 pub fn set_limit(&mut self, limit: u32) {
543 self.limit = clamp_limit(limit);
544 }
545
546 /// Writes one message as a frame.
547 ///
548 /// After an `ObjectHeader`, and after a `GetReply` whose `found` is
549 /// `true`, the writer is in the body state.
550 ///
551 /// # Errors
552 ///
553 /// If the call returns [`Error::Protocol`] or [`Error::LimitExceeded`],
554 /// it writes nothing.
555 ///
556 /// - [`Error::Protocol`] if the writer is inside an object or a pull
557 /// body.
558 /// - [`Error::Protocol`] if `msg` holds a value that its kind cannot
559 /// carry, for example a `GetReply` whose `found` is `false` with a
560 /// length.
561 /// - [`Error::LimitExceeded`] if the frame is over the limit.
562 /// - [`Error::Io`] if a write to the stream fails.
563 pub async fn write_message(&mut self, msg: &Message) -> Result<()> {
564 if self.body.is_some() {
565 return Err(protocol("message inside an object"));
566 }
567 // An object stream writes one `ObjectHeader` for each object, and a
568 // pull session one `GetReply` for each path, so the writer builds
569 // their frames on the stack. Each of these frames is shorter than
570 // `MIN_FRAME_LIMIT`.
571 if let Message::ObjectHeader(header) = msg {
572 let frame = object_header_frame(header)?;
573 self.inner.write_all(&frame).await?;
574 } else if let Message::GetReply(reply) = msg {
575 let (frame, used) = get_reply_frame(reply)?;
576 self.inner.write_all(&frame[..used]).await?;
577 } else {
578 let frame = encode_frame(msg, self.limit)?;
579 self.inner.write_all(&frame).await?;
580 }
581 self.body = BodyKind::after(msg);
582 Ok(())
583 }
584
585 /// Writes `frame`, which [`encode_frame`] built for a message that opens
586 /// no body. If the writer is inside an object or a pull body, the call
587 /// returns [`Error::Protocol`].
588 pub(crate) async fn write_frame(&mut self, frame: &[u8]) -> Result<()> {
589 if self.body.is_some() {
590 return Err(protocol("message inside an object"));
591 }
592 self.inner.write_all(frame).await?;
593 Ok(())
594 }
595
596 /// Writes bytes of the current object or pull body as chunks.
597 ///
598 /// Each chunk holds at most the limit. Inside a body, an empty `data`
599 /// writes nothing. Each call with data writes one chunk or more, and each
600 /// chunk costs 4 bytes of framing and one read call on the peer. A caller
601 /// gives the object bytes in pieces of 64 KiB or more.
602 ///
603 /// # Errors
604 ///
605 /// - [`Error::Protocol`] if the writer is not inside a body.
606 /// - [`Error::Io`] if a write to the stream fails.
607 pub async fn write_object_data(&mut self, data: &[u8]) -> Result<()> {
608 if self.body.is_none() {
609 return Err(protocol("object data outside an object"));
610 }
611 for chunk in data.chunks(self.limit as usize) {
612 self.inner
613 .write_all(&(chunk.len() as u32).to_be_bytes())
614 .await?;
615 self.inner.write_all(chunk).await?;
616 }
617 Ok(())
618 }
619
620 /// Ends the current object or pull body with a chunk of length 0.
621 ///
622 /// # Errors
623 ///
624 /// - [`Error::Protocol`] if the writer is not inside a body.
625 /// - [`Error::Io`] if a write to the stream fails.
626 pub async fn end_object(&mut self) -> Result<()> {
627 if self.body.is_none() {
628 return Err(protocol("no object to end"));
629 }
630 self.inner.write_all(&0u32.to_be_bytes()).await?;
631 self.body = None;
632 Ok(())
633 }
634
635 /// Abandons the current object of the push.
636 ///
637 /// The call writes the marker [`ABANDON`] and then an `Abort` message.
638 ///
639 /// # Errors
640 ///
641 /// - [`Error::Protocol`] if the writer is not inside an object of the
642 /// push, for example if it is inside a body of the pull.
643 /// - [`Error::Io`] if a write to the stream fails.
644 pub async fn abandon_object(&mut self) -> Result<()> {
645 if self.body != Some(BodyKind::Object) {
646 return Err(protocol("no object to abandon"));
647 }
648 self.inner.write_all(&ABANDON.to_be_bytes()).await?;
649 self.body = None;
650 self.write_message(&Message::Abort).await
651 }
652
653 /// Abandons the current body of the pull.
654 ///
655 /// The call writes the marker [`ABANDON`] and then `error` as an `Error`
656 /// message. The caller gives the code, for example `internal` for a
657 /// failed read of the file.
658 ///
659 /// # Errors
660 ///
661 /// - [`Error::Protocol`] if the writer is not inside a body of the pull,
662 /// for example if it is inside an object of the push.
663 /// - [`Error::Protocol`] if `error` does not encode. The call writes
664 /// nothing.
665 /// - [`Error::LimitExceeded`] if the frame of `error` is over the limit.
666 /// The call writes nothing.
667 /// - [`Error::Io`] if a write to the stream fails.
668 pub async fn abandon_body(&mut self, error: &ErrorMessage) -> Result<()> {
669 if self.body != Some(BodyKind::Pull) {
670 return Err(protocol("no pull body to abandon"));
671 }
672 let frame = encode_frame(&Message::Error(error.clone()), self.limit)?;
673 self.inner.write_all(&ABANDON.to_be_bytes()).await?;
674 self.body = None;
675 self.inner.write_all(&frame).await?;
676 Ok(())
677 }
678
679 /// Flushes the underlying stream.
680 ///
681 /// # Errors
682 ///
683 /// [`Error::Io`] if the flush of the stream fails.
684 pub async fn flush(&mut self) -> Result<()> {
685 self.inner.flush().await?;
686 Ok(())
687 }
688
689 /// Returns the underlying stream.
690 pub fn into_inner(self) -> W {
691 self.inner
692 }
693}