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
//! Decoders which implement `tokio_util::codec::Decoder`
//! and are able to extract (path, bytes) items for `AsyncRead`
//!

use bytes::{Bytes, BytesMut};
use std::{
    io,
    sync::{Arc, Mutex},
};
use streamson_lib::{
    error, handler, matcher,
    strategy::{self, Strategy},
};
use tokio_util::codec::Decoder;

/// This struct uses `streamson_lib::matcher` to decode data.
///
/// # Examples
/// ```
/// use std::io;
/// use streamson_lib::{error, matcher};
/// use streamson_tokio::decoder::Extractor;
/// use tokio::{fs, stream::StreamExt};
/// use tokio_util::codec::FramedRead;
///
/// async fn process() -> Result<(), error::General> {
///     let mut file = fs::File::open("/tmp/large.json").await?;
///     let matcher = matcher::Combinator::new(matcher::Simple::new(r#"{"users"}[]"#).unwrap())
///         | matcher::Combinator::new(matcher::Simple::new(r#"{"groups"}[]"#).unwrap());
///     let extractor = Extractor::new(matcher, true);
///     let mut output = FramedRead::new(file, extractor);
///     while let Some(item) = output.next().await {
///         let (path, data) = item?;
///         // Do something with extracted data
///     }
///     Ok(())
/// }
/// ```
pub struct Extractor {
    trigger: strategy::Trigger,
    handler: Arc<Mutex<handler::Buffer>>,
}

impl Extractor {
    /// Creates a new `Extractor`
    ///
    /// # Arguments
    /// * `matcher` - matcher to be used for extractions (see `streamson_lib::matcher`)
    /// * `include_path` - will path be included in output
    pub fn new(matcher: impl matcher::Matcher + 'static, include_path: bool) -> Self {
        // TODO limit max length and fail when reached
        let handler = Arc::new(Mutex::new(
            handler::Buffer::new().set_use_path(include_path),
        ));
        let mut trigger = strategy::Trigger::new();
        trigger.add_matcher(Box::new(matcher), handler.clone());
        Self { trigger, handler }
    }
}

impl Decoder for Extractor {
    type Item = (Option<String>, Bytes);
    type Error = error::General;

    fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        loop {
            {
                // pop if necessary
                let mut handler = self.handler.lock().unwrap();
                if let Some((path, bytes)) = handler.pop() {
                    return Ok(Some((path, Bytes::from(bytes))));
                }
                // handler is unlocked here so it can be used later withing `process` method
            }
            if buf.is_empty() {
                // end has been reached
                return Ok(None);
            }
            let data = buf.split_to(buf.len());
            self.trigger.process(&data[..])?;
        }
    }

    fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        self.trigger.terminate()?;
        match self.decode(buf)? {
            Some(frame) => Ok(Some(frame)),
            None => {
                if buf.is_empty() {
                    Ok(None)
                } else {
                    Err(io::Error::new(io::ErrorKind::Other, "bytes remaining on stream").into())
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Extractor;
    use bytes::Bytes;
    use std::io::Cursor;
    use streamson_lib::matcher;
    use tokio::stream::StreamExt;
    use tokio_util::codec::FramedRead;

    #[tokio::test]
    async fn with_included_path() {
        let cursor =
            Cursor::new(br#"{"users": ["mike","john"], "groups": ["admin", "staff"]}"#.to_vec());
        let matcher = matcher::Combinator::new(matcher::Simple::new(r#"{"users"}[]"#).unwrap())
            | matcher::Combinator::new(matcher::Simple::new(r#"{"groups"}[]"#).unwrap());
        let extractor = Extractor::new(matcher, true);
        let mut output = FramedRead::new(cursor, extractor);

        assert_eq!(
            output.next().await.unwrap().unwrap(),
            (
                Some(r#"{"users"}[0]"#.to_string()),
                Bytes::from_static(br#""mike""#)
            )
        );

        assert_eq!(
            output.next().await.unwrap().unwrap(),
            (
                Some(r#"{"users"}[1]"#.to_string()),
                Bytes::from_static(br#""john""#)
            )
        );

        assert_eq!(
            output.next().await.unwrap().unwrap(),
            (
                Some(r#"{"groups"}[0]"#.to_string()),
                Bytes::from_static(br#""admin""#)
            )
        );

        assert_eq!(
            output.next().await.unwrap().unwrap(),
            (
                Some(r#"{"groups"}[1]"#.to_string()),
                Bytes::from_static(br#""staff""#)
            )
        );

        assert!(output.next().await.is_none());
    }

    #[tokio::test]
    async fn without_included_path() {
        let cursor =
            Cursor::new(br#"{"users": ["mike","john"], "groups": ["admin", "staff"]}"#.to_vec());
        let matcher = matcher::Combinator::new(matcher::Simple::new(r#"{"users"}[]"#).unwrap())
            | matcher::Combinator::new(matcher::Simple::new(r#"{"groups"}[]"#).unwrap());
        let extractor = Extractor::new(matcher, false);
        let mut output = FramedRead::new(cursor, extractor);

        assert_eq!(
            output.next().await.unwrap().unwrap(),
            (None, Bytes::from_static(br#""mike""#))
        );

        assert_eq!(
            output.next().await.unwrap().unwrap(),
            (None, Bytes::from_static(br#""john""#))
        );

        assert_eq!(
            output.next().await.unwrap().unwrap(),
            (None, Bytes::from_static(br#""admin""#))
        );

        assert_eq!(
            output.next().await.unwrap().unwrap(),
            (None, Bytes::from_static(br#""staff""#))
        );

        assert!(output.next().await.is_none());
    }

    #[tokio::test]
    async fn multiple_json_input() {
        let cursor = Cursor::new(
            br#"{"users": ["user1","user2", "user3"]} {"users": ["user4","user5"]}"#.to_vec(),
        );
        let matcher = matcher::Simple::new(r#"{"users"}[]"#).unwrap();
        let extractor = Extractor::new(matcher, true);

        let mut output = FramedRead::new(cursor, extractor);

        assert_eq!(
            output.next().await.unwrap().unwrap(),
            (
                Some(r#"{"users"}[0]"#.to_string()),
                Bytes::from_static(br#""user1""#)
            )
        );
        assert_eq!(
            output.next().await.unwrap().unwrap(),
            (
                Some(r#"{"users"}[1]"#.to_string()),
                Bytes::from_static(br#""user2""#)
            )
        );
        assert_eq!(
            output.next().await.unwrap().unwrap(),
            (
                Some(r#"{"users"}[2]"#.to_string()),
                Bytes::from_static(br#""user3""#)
            )
        );
        assert_eq!(
            output.next().await.unwrap().unwrap(),
            (
                Some(r#"{"users"}[0]"#.to_string()),
                Bytes::from_static(br#""user4""#)
            )
        );
        assert_eq!(
            output.next().await.unwrap().unwrap(),
            (
                Some(r#"{"users"}[1]"#.to_string()),
                Bytes::from_static(br#""user5""#)
            )
        );

        assert!(output.next().await.is_none());
    }
}