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
//! Integration of futures::stream with streamson
//!

use std::{
    marker::Unpin,
    pin::Pin,
    sync::{Arc, Mutex},
};

use bytes::Bytes;
use futures::{
    task::{Context, Poll},
    Stream,
};
use streamson_lib::{
    error::General as StreamsonError,
    handler, matcher,
    strategy::{self, Strategy},
};

/// This struct is used to wrap Bytes input stream to
/// (Path, Bytes) - the matched path and matched bytes in json stream
/// # Examples
/// ```
/// # futures::executor::block_on(async {
///
/// use bytes::Bytes;
/// use futures::stream::{self, StreamExt};
/// use streamson_lib::matcher;
/// use streamson_futures::stream::BufferStream;
///
/// let stream = stream::iter(
///     vec![r#"{"users": ["#, r#"{"name": "carl", "id": 1}"#, r#"]}"#]
///         .drain(..)
///         .map(Bytes::from)
///         .collect::<Vec<Bytes>>()
/// );
/// let matcher = matcher::Simple::new(r#"{"users"}[]{"name"}"#).unwrap();
/// let wrapped_stream = BufferStream::new(stream, Box::new(matcher));
/// # });
/// ```
pub struct BufferStream<I>
where
    I: Stream<Item = Bytes> + Unpin,
{
    input: I,
    trigger: Arc<Mutex<strategy::Trigger>>,
    buffer: Arc<Mutex<handler::Buffer>>,
    terminated: bool,
}

impl<I> BufferStream<I>
where
    I: Stream<Item = Bytes> + Unpin,
{
    /// Wraps stream to extracts json paths defined by the matcher
    ///
    /// # Arguments
    /// * `input` - input stram to be matched
    /// * `matcher` - matcher which will be used for the extraction
    pub fn new(input: I, matcher: Box<dyn matcher::Matcher>) -> Self {
        let trigger = Arc::new(Mutex::new(strategy::Trigger::new()));
        let buffer = Arc::new(Mutex::new(handler::Buffer::new().set_use_path(true)));
        trigger.lock().unwrap().add_matcher(matcher, buffer.clone());
        Self {
            input,
            trigger,
            buffer,
            terminated: false,
        }
    }
}

impl<I> Stream for BufferStream<I>
where
    I: Stream<Item = Bytes> + Unpin,
{
    type Item = Result<(String, Bytes), StreamsonError>;
    fn poll_next(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Option<Self::Item>> {
        loop {
            if self.terminated {
                return Poll::Ready(None);
            }
            // Check whether there are data in the buffer
            if let Some((path, data)) = self.buffer.lock().unwrap().pop() {
                return Poll::Ready(Some(Ok((path.unwrap(), Bytes::from(data)))));
            }
            // Try to process new data with the trigger
            match Pin::new(&mut self.input).poll_next(ctx) {
                Poll::Ready(Some(bytes)) => {
                    self.trigger.lock().unwrap().process(&bytes)?;
                }
                Poll::Ready(None) => {
                    self.terminated = true;
                    if let Err(err) = self.trigger.lock().unwrap().terminate() {
                        return Poll::Ready(Some(Err(err)));
                    }
                    continue;
                }
                Poll::Pending => return Poll::Pending,
            }
        }
    }
}

#[cfg(test)]
mod test {
    use bytes::Bytes;
    use futures::stream::{self, StreamExt};
    use streamson_lib::matcher;

    use super::BufferStream;

    #[tokio::test]
    async fn test_basic() {
        let stream = stream::iter(
            vec![
                r#"{"users": ["#,
                r#"{"name": "carl",
                "id": 1}"#,
                r#"]}"#,
            ]
            .drain(..)
            .map(Bytes::from)
            .collect::<Vec<Bytes>>(),
        );
        let matcher = matcher::Simple::new(r#"{"users"}[]{"name"}"#).unwrap();
        let wrapped_stream = BufferStream::new(stream, Box::new(matcher));
        let mut collected = wrapped_stream
            .collect::<Vec<Result<(String, Bytes), _>>>()
            .await;

        assert_eq!(
            vec![(
                String::from(r#"{"users"}[0]{"name"}"#),
                Bytes::from(r#""carl""#)
            )],
            collected
                .drain(..)
                .map(|e| e.unwrap())
                .collect::<Vec<(String, Bytes)>>()
        );
    }

    #[tokio::test]
    async fn test_error() {
        let stream = stream::iter(
            vec![
                r#"{"users": ["#,
                r#"{"name": "carl",
                "id": 1}"#,
                r#"}]}"#,
            ]
            .drain(..)
            .map(Bytes::from)
            .collect::<Vec<Bytes>>(),
        );
        let matcher = matcher::Simple::new(r#"{"users"}[]{"name"}"#).unwrap();
        let wrapped_stream = BufferStream::new(stream, Box::new(matcher));
        let collected = wrapped_stream
            .collect::<Vec<Result<(String, Bytes), _>>>()
            .await;
        assert!(collected[0].is_ok());
        assert!(collected[1].is_err());
    }
}