gpt4 book ai didi

stream - 如何通过 io::Write 特性写入通过 future 流发送数据?

转载 作者:行者123 更新时间:2023-11-29 08:17:57 24 4
gpt4 key购买 nike

我有一个采用&mut io::Write 的函数,我想用它从actix-web 服务器发送流式响应,而不必缓冲整个响应。该函数正在“推送”数据,我无法更改该函数(这是这个问题的全部前提)以使用异步流或其他类型的轮询。

目前我被迫使用&mut Vec(它实现了io::Write)来缓冲整个结果然后发送Vec 作为响应主体。但是,响应可能很大,所以我宁愿在没有缓冲的情况下流式传输它。

是否有某种类型的适配器可以实现 io::Write,在必要时阻塞写入以响应背压,并与 actix-web 可用于响应的类型兼容(例如 future ::流)?

fn generate(output: &mut io::Write) {
// ...
}

fn request_handler() -> Result<HttpResponse> {
thread::spawn(|| generate(/*???*/));
Ok(HttpResponse::Ok().body(/*???*/))
}

std::sync::mpscfutures::mpsc 要么两端异步,要么两端阻塞,因此如何将它们用作同步端和异步端之间的适配器。

最佳答案

这是可能的。关键部分是futures::sink::Wait :

A sink combinator which converts an asynchronous sink to a blocking sink.

Created by the Sink::wait method, this function transforms any sink into a blocking version. This is implemented by blocking the current thread when a sink is otherwise unable to make progress.

所需要做的就是将此类型包装在一个实现io::Write的结构中:

use futures::{
sink::{Sink, Wait},
sync::mpsc,
}; // 0.1.26
use std::{io, thread};

fn generate(_output: &mut io::Write) {
// ...
}

struct MyWrite<T>(Wait<mpsc::Sender<T>>);

impl<T> io::Write for MyWrite<T>
where
T: for<'a> From<&'a [u8]> + Send + Sync + 'static,
{
fn write(&mut self, d: &[u8]) -> io::Result<usize> {
let len = d.len();
self.0
.send(d.into())
.map(|()| len)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
}

fn flush(&mut self) -> io::Result<()> {
self.0
.flush()
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
}
}

fn foo() -> impl futures::Stream<Item = Vec<u8>, Error = ()> {
let (tx, rx) = mpsc::channel(5);

let mut w = MyWrite(tx.wait());

thread::spawn(move || generate(&mut w));

rx
}

关于stream - 如何通过 io::Write 特性写入通过 future 流发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55708392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com