如何使用Serde Zero-copy反序列化Futures-enabled Hyper Chunk并存储结果?

4

我正在使用 futures、tokio、hyper 和 serde_json 请求和反序列化一些数据,这些数据需要保留直到我的下一个请求。我的初始想法是创建一个包含hyper::Chunk和从Chunk中借用的反序列化数据的结构体,但是无法正确处理生命周期。我尝试使用rental crate,但也无法使其正常工作。也许我在声明缓冲区Vec之前就使用了'buffer生命周期,但也可能我搞砸了其他东西:

#[rental]
pub struct ChunkJson<T: serde::de::Deserialize<'buffer>> {
    buffer: Vec<u8>,
    json: T
}

有没有办法使生命周期正确,或者我应该只使用DeserializeOwned并放弃零拷贝?

更多背景信息,请参考以下代码(定期从两个URL反序列化JSON,保留结果以便我们可以对它们进行操作)。我想将我的XY类型更改为使用Cow<'a,str>作为它们的字段,从DeserializeOwned更改为Deserialize<'a>。为了实现这一点,我需要存储已经被反序列化的切片,但我不知道如何做到这一点。我正在寻找使用Serde的零拷贝反序列化并保留结果的示例,或者某种可以工作的重构代码的想法。

#[macro_use]
extern crate serde_derive;

extern crate serde;
extern crate serde_json;
extern crate futures;
extern crate tokio_core;
extern crate tokio_periodic;
extern crate hyper;

use std::collections::HashMap;
use std::error::Error;

use futures::future;
use futures::Future;
use futures::stream::Stream;
use hyper::Client;


fn stream_json<'a, T: serde::de::DeserializeOwned + Send + 'a>
    (handle: &tokio_core::reactor::Handle,
     url: String,
     period: u64)
     -> Box<Stream<Item = T, Error = Box<Error>> + 'a> {
    let client = Client::new(handle);
    let timer = tokio_periodic::PeriodicTimer::new(handle).unwrap();
    timer
        .reset(::std::time::Duration::new(period, 0))
        .unwrap();
    Box::new(futures::Stream::zip(timer.from_err::<Box<Error>>(), futures::stream::unfold( (), move |_| {
            let uri = url.parse::<hyper::Uri>().unwrap();
            let get = client.get(uri).from_err::<Box<Error>>().and_then(|res| {
                res.body().concat().from_err::<Box<Error>>().and_then(|chunks| {
                    let p: Result<T, Box<Error>> = serde_json::from_slice::<T>(chunks.as_ref()).map_err(|e| Box::new(e) as Box<Error>);
                    match p {
                        Ok(json) => future::ok((json, ())),
                        Err(err) => future::err(err)
                    }
                })
            });
            Some(get)
        })).map(|x| { x.1 }))
}

#[derive(Serialize, Deserialize, Debug)]
pub struct X {
    foo: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Y {
    bar: String,
}

fn main() {

    let mut core = tokio_core::reactor::Core::new().unwrap();
    let handle = core.handle();

    let x_stream = stream_json::<HashMap<String, X>>(&handle, "http://localhost/X".to_string(), 2);
    let y_stream = stream_json::<HashMap<String, Y>>(&handle, "http://localhost/Y".to_string(), 5);
    let mut xy_stream = x_stream.merge(y_stream);

    let mut last_x = HashMap::new();
    let mut last_y = HashMap::new();

    loop {
        match core.run(futures::Stream::into_future(xy_stream)) {
            Ok((Some(item), stream)) => {
                match item {
                    futures::stream::MergedItem::First(x) => last_x = x,
                    futures::stream::MergedItem::Second(y) => last_y = y,
                    futures::stream::MergedItem::Both(x, y) => {
                        last_x = x;
                        last_y = y;
                    }
                }
                println!("\nx = {:?}", &last_x);
                println!("y = {:?}", &last_y);
                // Do more stuff with &last_x and &last_y

                xy_stream = stream;
            }
            Ok((None, stream)) => xy_stream = stream,
            Err(_) => {
                panic!("error");
            }
        }
    }
}

1
欢迎来到Stack Overflow!这里期望问题展示出很多努力,并且在可能的情况下提供一个[MCVE]。你的问题介绍了futures/hyper/tokio/serde,但是所呈现的代码只使用了serde和rental;这是试图缩小复制吗?如果是这样,你应该展示它的使用方式。你是否阅读过为什么我不能在同一个结构体中存储值和对该值的引用?以了解关于具有自引用限制的限制? - Shepmaster
1个回答

9

当尝试解决复杂的编程问题时,尽可能地减少代码是非常有用的。将你的代码精简并删除能够使问题消失的部分。微调你的代码并继续删除,直到无法再删除为止。然后,将问题反过来,从最小的部分开始构建,并逐渐追溯到错误。这两种方法都可以帮助你找出问题所在。

首先,让我们确保正确反序列化:

extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;

use std::borrow::Cow;

#[derive(Debug, Deserialize)]
pub struct Example<'a> {
    #[serde(borrow)]
    name: Cow<'a, str>,
    key: bool,
}

impl<'a> Example<'a> {
    fn info(&self) {
        println!("{:?}", self);
        match self.name {
            Cow::Borrowed(_) => println!("Is borrowed"),
            Cow::Owned(_) => println!("Is owned"),
        }
    }
}

fn main() {
    let data: Vec<_> = br#"{"key": true, "name": "alice"}"#.to_vec();

    let decoded: Example = serde_json::from_slice(&data).expect("Couldn't deserialize");
    decoded.info();
}

这里,我忘记添加#[serde(borrow)]属性,所以很高兴进行了这个测试!

接下来,我们可以介绍rental crate:

#[macro_use]
extern crate rental;

rental! {
    mod holding {
        use super::*;

        #[rental]
        pub struct VecHolder {
            data: Vec<u8>,
            parsed: Example<'data>,
        }
    }
}

fn main() {
    let data: Vec<_> = br#"{"key": true, "name": "alice"}"#.to_vec();

    let holder = holding::VecHolder::try_new(data, |data| {
        serde_json::from_slice(data)
    });
    let holder = match holder {
        Ok(holder) => holder,
        Err(_) => panic!("Unable to construct rental"),
    };

    holder.rent(|example| example.info());

    // Make sure we can move the data and it's still valid
    let holder2 = { holder };
    holder2.rent(|example| example.info());
}

接下来我们尝试创建一个Chunk的租赁:

#[rental]
pub struct ChunkHolder {
    data: Chunk,
    parsed: Example<'data>,
}

不幸的是,这个失败了:

  --> src/main.rs:29:1
   |
29 | rental! {
   | ^
   |
   = help: message: Field `data` must have an angle-bracketed type parameter or be `String`.

糟糕!查看rental文档后,我们可以在data字段中添加#[target_ty_hack="[u8]"]。这将导致:

error[E0277]: the trait bound `hyper::Chunk: rental::__rental_prelude::StableDeref` is not satisfied
  --> src/main.rs:29:1
   |
29 | rental! {
   | ^ the trait `rental::__rental_prelude::StableDeref` is not implemented for `hyper::Chunk`
   |
   = note: required by `rental::__rental_prelude::static_assert_stable_deref`

这很烦人;由于我们无法为Chunk实现该特性,所以我们只需要给Chunk打包装盒,证明它具有稳定的地址:

#[rental]
pub struct ChunkHolder {
    data: Box<Chunk>,
    parsed: Example<'data>,
}

我还尝试着去寻找一种方法来从Chunk中取回一个Vec<u8>,但是似乎没有这样的方法存在。如果有的话,这将是使用更少的分配和间接引用的另一种解决方案。

现在,"所有"还剩下的就是将其整合到未来代码中。除了你以外,任何人都需要付出很多努力才能够重新创造它,但我预见不会出现任何明显的问题。


太棒了!我没有想到可以退后一步,为我的ChunkHolder创建一个特定类型;这使得生命周期参数更有意义。另外,感谢您指出#[serde(borrow)]。现在我有了这个,它运行得很好:https://gist.github.com/anonymous/6e1fadd47ff1b8df4f84975334749095 - Evin Robertson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接