Stream entries (#2582)
* Add entry streaming option * Fix tests * Remove obsolete comment * Move entry stream functionality to struct w/ trait in order to test without i/o
This commit is contained in:
57
src/entry_stream.rs
Normal file
57
src/entry_stream.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
//! The `entry_stream` module provides a method for streaming entries out via a
|
||||
//! local unix socket, to provide client services such as a block explorer with
|
||||
//! real-time access to entries.
|
||||
|
||||
use crate::entry::Entry;
|
||||
use crate::result::Result;
|
||||
use std::io::prelude::*;
|
||||
use std::net::Shutdown;
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::path::Path;
|
||||
|
||||
pub trait EntryStreamHandler {
|
||||
fn stream_entries(&mut self, entries: &[Entry]) -> Result<()>;
|
||||
}
|
||||
|
||||
pub struct EntryStream {
|
||||
pub socket: String,
|
||||
}
|
||||
|
||||
impl EntryStream {
|
||||
pub fn new(socket: String) -> Self {
|
||||
EntryStream { socket }
|
||||
}
|
||||
}
|
||||
|
||||
impl EntryStreamHandler for EntryStream {
|
||||
fn stream_entries(&mut self, entries: &[Entry]) -> Result<()> {
|
||||
let mut socket = UnixStream::connect(Path::new(&self.socket))?;
|
||||
for entry in entries {
|
||||
let result = serde_json::to_string(&entry)?;
|
||||
socket.write_all(result.as_bytes())?;
|
||||
}
|
||||
socket.shutdown(Shutdown::Write)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MockEntryStream {
|
||||
pub socket: Vec<String>,
|
||||
}
|
||||
|
||||
impl MockEntryStream {
|
||||
#[allow(clippy::needless_pass_by_value)]
|
||||
pub fn new(_socket: String) -> Self {
|
||||
MockEntryStream { socket: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl EntryStreamHandler for MockEntryStream {
|
||||
fn stream_entries(&mut self, entries: &[Entry]) -> Result<()> {
|
||||
for entry in entries {
|
||||
let result = serde_json::to_string(&entry)?;
|
||||
self.socket.push(result);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user