use crate::async_client::AsyncClient;
use crate::client::Client;
use crate::constants::{BodyFormat, ErrorCode, QueryFormat};
use crate::error::RepeError;
use crate::message::{Message, create_error_message};
use crate::server::{Execution, HandlerErased, Router};
use beve::Complex;
use beve::from_slice as beve_from_slice;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
use std::sync::{Arc, Mutex};
use std::thread;
pub const SVS_VERSION: u8 = 1;
pub const ROUTE_OPEN: &str = "/_svs/open";
pub const ROUTE_NEXT: &str = "/_svs/next";
pub const ROUTE_CANCEL: &str = "/_svs/cancel";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Compression {
None = 0,
Zstd = 1,
}
impl Compression {
fn from_u8(v: u8) -> Option<Self> {
match v {
0 => Some(Compression::None),
1 => Some(Compression::Zstd),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct StreamOpts {
pub chunk_bytes: usize,
pub compression: Compression,
pub zstd_level: i32,
pub session_depth: usize,
}
impl Default for StreamOpts {
fn default() -> Self {
Self {
chunk_bytes: 1 << 20,
compression: Compression::Zstd,
zstd_level: 3,
session_depth: 4,
}
}
}
#[derive(Serialize, Deserialize)]
struct OpenRequest {
resource: String,
}
#[derive(Serialize, Deserialize)]
struct OpenResponse {
version: u8,
stream_id: u64,
format: u16,
compression: u8,
}
#[derive(Serialize, Deserialize)]
struct NextRequest {
stream_id: u64,
}
#[derive(Serialize, Deserialize)]
struct CancelRequest {
stream_id: u64,
reason: String,
}
enum Msg {
Chunk(Vec<u8>),
End,
Fail(String),
}
struct ChunkSink {
tx: SyncSender<Msg>,
buf: Vec<u8>,
chunk_bytes: usize,
}
impl ChunkSink {
fn new(tx: SyncSender<Msg>, chunk_bytes: usize) -> Self {
Self {
tx,
buf: Vec::with_capacity(chunk_bytes),
chunk_bytes,
}
}
fn send_chunk(&mut self) -> io::Result<()> {
let chunk = std::mem::replace(&mut self.buf, Vec::with_capacity(self.chunk_bytes));
self.tx
.send(Msg::Chunk(chunk))
.map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "svs stream cancelled"))
}
fn flush_remaining(&mut self) -> io::Result<()> {
if self.buf.is_empty() {
Ok(())
} else {
self.send_chunk()
}
}
}
impl Write for ChunkSink {
fn write(&mut self, mut data: &[u8]) -> io::Result<usize> {
let total = data.len();
while !data.is_empty() {
let space = self.chunk_bytes - self.buf.len();
let take = space.min(data.len());
self.buf.extend_from_slice(&data[..take]);
data = &data[take..];
if self.buf.len() >= self.chunk_bytes {
self.send_chunk()?;
}
}
Ok(total)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
type BodyWriter = Box<dyn FnOnce(&mut dyn Write) -> io::Result<()> + Send>;
fn beve_to_io(e: beve::Error) -> io::Error {
io::Error::other(e.to_string())
}
fn produce(body: BodyWriter, tx: SyncSender<Msg>, opts: StreamOpts) {
let mut sink = ChunkSink::new(tx.clone(), opts.chunk_bytes);
let result = (|| -> io::Result<()> {
match opts.compression {
Compression::None => body(&mut sink)?,
Compression::Zstd => {
let mut enc = zstd::stream::write::Encoder::new(&mut sink, opts.zstd_level)?;
body(&mut enc)?;
enc.finish()?;
}
}
sink.flush_remaining()
})();
let _ = match result {
Ok(()) => tx.send(Msg::End),
Err(e) => tx.send(Msg::Fail(e.to_string())),
};
}
struct Session {
rx: Receiver<Msg>,
lookahead: Option<Vec<u8>>,
done: bool,
}
impl Session {
fn recv(&self) -> Msg {
self.rx.recv().unwrap_or_else(|_| {
Msg::Fail("svs producer ended without completing".to_string())
})
}
fn pull(&mut self) -> Result<(Vec<u8>, bool), String> {
let current = match self.lookahead.take() {
Some(c) => c,
None => match self.recv() {
Msg::Chunk(c) => c,
Msg::End => return Ok((Vec::new(), true)),
Msg::Fail(e) => return Err(e),
},
};
match self.recv() {
Msg::Chunk(next) => {
self.lookahead = Some(next);
Ok((current, false))
}
Msg::End => Ok((current, true)),
Msg::Fail(e) => Err(e),
}
}
}
struct SessionTable {
next_id: AtomicU64,
sessions: Mutex<HashMap<u64, Arc<Mutex<Session>>>>,
}
impl SessionTable {
fn new() -> Self {
Self {
next_id: AtomicU64::new(1),
sessions: Mutex::new(HashMap::new()),
}
}
fn get(&self, stream_id: u64) -> Option<Arc<Mutex<Session>>> {
self.sessions.lock().unwrap().get(&stream_id).cloned()
}
fn remove(&self, stream_id: u64) {
self.sessions.lock().unwrap().remove(&stream_id);
}
}
struct OpenHandler<F> {
table: Arc<SessionTable>,
make_body: F,
opts: StreamOpts,
format: u16,
}
impl<F> HandlerErased for OpenHandler<F>
where
F: Fn(&str) -> Option<BodyWriter> + Send + Sync + 'static,
{
fn handle(&self, req: &Message) -> Result<Message, RepeError> {
let open: OpenRequest = match beve_from_slice(&req.body) {
Ok(v) => v,
Err(_) => {
return Ok(error_like(
req,
ErrorCode::InvalidBody,
"svs open: expected BEVE { resource: string }",
));
}
};
let Some(body) = (self.make_body)(&open.resource) else {
return Ok(error_like(
req,
ErrorCode::MethodNotFound,
format!("svs open: unknown resource '{}'", open.resource),
));
};
let stream_id = self.table.next_id.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = sync_channel::<Msg>(self.opts.session_depth);
let opts = self.opts;
thread::spawn(move || produce(body, tx, opts));
self.table.sessions.lock().unwrap().insert(
stream_id,
Arc::new(Mutex::new(Session {
rx,
lookahead: None,
done: false,
})),
);
let resp = OpenResponse {
version: SVS_VERSION,
stream_id,
format: self.format,
compression: self.opts.compression as u8,
};
beve_response(req, &resp)
}
}
struct NextHandler {
table: Arc<SessionTable>,
}
impl HandlerErased for NextHandler {
fn execution(&self) -> Execution {
Execution::OffReader
}
fn handle(&self, req: &Message) -> Result<Message, RepeError> {
let next: NextRequest = match beve_from_slice(&req.body) {
Ok(v) => v,
Err(_) => {
return Ok(error_like(
req,
ErrorCode::InvalidBody,
"svs next: expected BEVE { stream_id: u64 }",
));
}
};
let Some(session) = self.table.get(next.stream_id) else {
return Ok(error_like(
req,
ErrorCode::InvalidQuery,
format!("svs next: unknown stream_id {}", next.stream_id),
));
};
let outcome = {
let mut guard = session.lock().unwrap();
if guard.done {
Err("svs next: stream already finished".to_string())
} else {
let pulled = guard.pull();
if matches!(pulled, Ok((_, true)) | Err(_)) {
guard.done = true;
}
pulled
}
};
match outcome {
Ok((chunk, last)) => {
if last {
self.table.remove(next.stream_id);
}
Ok(chunk_response(req, chunk, last))
}
Err(msg) => {
self.table.remove(next.stream_id);
Ok(error_like(req, ErrorCode::InternalError, msg))
}
}
}
}
struct CancelHandler {
table: Arc<SessionTable>,
}
impl HandlerErased for CancelHandler {
fn handle(&self, req: &Message) -> Result<Message, RepeError> {
if let Ok(cancel) = beve_from_slice::<CancelRequest>(&req.body) {
self.table.remove(cancel.stream_id);
}
beve_response(req, &CancelAck { ok: true })
}
}
#[derive(Serialize, Deserialize)]
struct CancelAck {
ok: bool,
}
fn register_svs<F>(router: Router, make_body: F, format: u16, opts: StreamOpts) -> Router
where
F: Fn(&str) -> Option<BodyWriter> + Send + Sync + 'static,
{
let table = Arc::new(SessionTable::new());
let open: Arc<dyn HandlerErased> = Arc::new(OpenHandler {
table: Arc::clone(&table),
make_body,
opts,
format,
});
let next: Arc<dyn HandlerErased> = Arc::new(NextHandler {
table: Arc::clone(&table),
});
let cancel: Arc<dyn HandlerErased> = Arc::new(CancelHandler {
table: Arc::clone(&table),
});
router
.with_erased_handler(ROUTE_OPEN, open)
.with_erased_handler(ROUTE_NEXT, next)
.with_erased_handler(ROUTE_CANCEL, cancel)
}
pub trait RouterValueStreamExt: Sized {
fn with_value_stream<T, F>(self, resolve: F, opts: StreamOpts) -> Self
where
T: Serialize + Send + 'static,
F: Fn(&str) -> Option<T> + Send + Sync + 'static;
fn with_typed_value_stream<T, F>(self, resolve: F, opts: StreamOpts) -> Self
where
T: beve::BeveTypedSlice + Send + 'static,
F: Fn(&str) -> Option<Vec<T>> + Send + Sync + 'static;
fn with_complex_value_stream<T, F>(self, resolve: F, opts: StreamOpts) -> Self
where
T: beve::BeveTypedSlice + Send + 'static,
F: Fn(&str) -> Option<Vec<Complex<T>>> + Send + Sync + 'static;
fn with_reader_stream<R, F>(self, resolve: F, opts: StreamOpts) -> Self
where
R: Read + Send + 'static,
F: Fn(&str) -> Option<R> + Send + Sync + 'static;
fn with_writer_stream<W, F>(self, format: BodyFormat, resolve: F, opts: StreamOpts) -> Self
where
W: FnOnce(&mut dyn Write) -> io::Result<()> + Send + 'static,
F: Fn(&str) -> Option<W> + Send + Sync + 'static;
}
impl RouterValueStreamExt for Router {
fn with_value_stream<T, F>(self, resolve: F, opts: StreamOpts) -> Self
where
T: Serialize + Send + 'static,
F: Fn(&str) -> Option<T> + Send + Sync + 'static,
{
register_svs(
self,
move |resource| {
resolve(resource).map(|value| {
Box::new(move |w: &mut dyn Write| {
beve::to_writer_streaming(w, &value).map_err(beve_to_io)
}) as BodyWriter
})
},
BodyFormat::Beve as u16,
opts,
)
}
fn with_typed_value_stream<T, F>(self, resolve: F, opts: StreamOpts) -> Self
where
T: beve::BeveTypedSlice + Send + 'static,
F: Fn(&str) -> Option<Vec<T>> + Send + Sync + 'static,
{
register_svs(
self,
move |resource| {
resolve(resource).map(|values| {
Box::new(move |w: &mut dyn Write| {
beve::to_writer_typed_slice(w, &values).map_err(beve_to_io)
}) as BodyWriter
})
},
BodyFormat::Beve as u16,
opts,
)
}
fn with_complex_value_stream<T, F>(self, resolve: F, opts: StreamOpts) -> Self
where
T: beve::BeveTypedSlice + Send + 'static,
F: Fn(&str) -> Option<Vec<Complex<T>>> + Send + Sync + 'static,
{
register_svs(
self,
move |resource| {
resolve(resource).map(|values| {
Box::new(move |w: &mut dyn Write| {
beve::to_writer_complex_slice(w, &values).map_err(beve_to_io)
}) as BodyWriter
})
},
BodyFormat::Beve as u16,
opts,
)
}
fn with_reader_stream<R, F>(self, resolve: F, opts: StreamOpts) -> Self
where
R: Read + Send + 'static,
F: Fn(&str) -> Option<R> + Send + Sync + 'static,
{
register_svs(
self,
move |resource| {
resolve(resource).map(|mut reader| {
Box::new(move |w: &mut dyn Write| io::copy(&mut reader, w).map(|_| ()))
as BodyWriter
})
},
BodyFormat::RawBinary as u16,
opts,
)
}
fn with_writer_stream<W, F>(self, format: BodyFormat, resolve: F, opts: StreamOpts) -> Self
where
W: FnOnce(&mut dyn Write) -> io::Result<()> + Send + 'static,
F: Fn(&str) -> Option<W> + Send + Sync + 'static,
{
register_svs(
self,
move |resource| resolve(resource).map(|writer| Box::new(writer) as BodyWriter),
format as u16,
opts,
)
}
}
fn error_like(req: &Message, code: ErrorCode, msg: impl AsRef<str>) -> Message {
let mut err = create_error_message(code, msg.as_ref());
err.header.id = req.header.id;
err
}
fn beve_response<T: Serialize>(req: &Message, value: &T) -> Result<Message, RepeError> {
Ok(Message::builder()
.id(req.header.id)
.body_bytes(beve::to_vec(value)?)
.body_format(BodyFormat::Beve)
.build())
}
fn chunk_response(req: &Message, chunk: Vec<u8>, last: bool) -> Message {
Message::builder()
.id(req.header.id)
.query_format(QueryFormat::RawBinary)
.query_bytes(vec![last as u8])
.body_format(BodyFormat::RawBinary)
.body_bytes(chunk)
.build()
}
#[derive(Debug, Clone, Copy)]
pub enum StreamOutput<'a> {
BeveZstdFile(&'a Path),
BeveFile(&'a Path),
Value,
RawFile(&'a Path),
}
pub fn pull_stream<T: DeserializeOwned>(
client: &Client,
resource: &str,
out: StreamOutput<'_>,
) -> Result<Option<T>, RepeError> {
let open = open_stream(client, resource)?;
if let Err(e) = check_output(out, &open) {
let _ = cancel_stream(
client,
open.stream_id,
"output incompatible with stream tags",
);
return Err(e);
}
match out {
StreamOutput::BeveZstdFile(path) => {
write_file(client, open.stream_id, path, |reader, file| {
io::copy(reader, file)?;
Ok(())
})?;
Ok(None)
}
StreamOutput::BeveFile(path) => {
write_file(client, open.stream_id, path, |reader, file| {
let mut dec = zstd::stream::read::Decoder::new(reader).map_err(RepeError::Io)?;
io::copy(&mut dec, file)?;
Ok(())
})?;
Ok(None)
}
StreamOutput::Value => {
let reader = ChunkReader::new(client, open.stream_id);
let value = match open.compression {
Compression::None => beve::from_reader_streaming::<_, T>(reader)?,
Compression::Zstd => {
let dec = zstd::stream::read::Decoder::new(reader).map_err(RepeError::Io)?;
beve::from_reader_streaming::<_, T>(dec)?
}
};
let _ = cancel_stream(client, open.stream_id, "value fully decoded");
Ok(Some(value))
}
StreamOutput::RawFile(path) => {
let compression = open.compression;
write_file(client, open.stream_id, path, |reader, file| {
match compression {
Compression::None => {
io::copy(reader, file)?;
}
Compression::Zstd => {
let mut dec =
zstd::stream::read::Decoder::new(reader).map_err(RepeError::Io)?;
io::copy(&mut dec, file)?;
}
}
Ok(())
})?;
Ok(None)
}
}
}
pub fn pull_value<T: DeserializeOwned>(client: &Client, resource: &str) -> Result<T, RepeError> {
pull_stream::<T>(client, resource, StreamOutput::Value)
.map(|v| v.expect("StreamOutput::Value always yields Some"))
}
pub fn pull_to_beve_zst_file(
client: &Client,
resource: &str,
path: &Path,
) -> Result<(), RepeError> {
pull_stream::<()>(client, resource, StreamOutput::BeveZstdFile(path)).map(|_| ())
}
pub fn pull_to_beve_file(client: &Client, resource: &str, path: &Path) -> Result<(), RepeError> {
pull_stream::<()>(client, resource, StreamOutput::BeveFile(path)).map(|_| ())
}
pub fn pull_to_file(client: &Client, resource: &str, path: &Path) -> Result<(), RepeError> {
pull_stream::<()>(client, resource, StreamOutput::RawFile(path)).map(|_| ())
}
pub fn pull_consume<V, F>(client: &Client, resource: &str, consume: F) -> Result<V, RepeError>
where
F: FnOnce(&mut dyn Read) -> Result<V, RepeError>,
{
let open = open_stream(client, resource)?;
let reader = ChunkReader::new(client, open.stream_id);
let result = match open.compression {
Compression::None => {
let mut reader = reader;
consume(&mut reader)
}
Compression::Zstd => match zstd::stream::read::Decoder::new(reader) {
Ok(mut dec) => consume(&mut dec),
Err(e) => Err(RepeError::Io(e)),
},
};
let _ = cancel_stream(client, open.stream_id, "consume complete");
result
}
pub fn pull_to_vec(client: &Client, resource: &str) -> Result<Vec<u8>, RepeError> {
pull_consume(client, resource, |reader| {
let mut buf = Vec::new();
reader.read_to_end(&mut buf)?;
Ok(buf)
})
}
pub fn pull_to_file_trailer_verified<D, F>(
client: &Client,
resource: &str,
path: &Path,
trailer_len: usize,
digest: D,
verify: F,
) -> Result<(), RepeError>
where
D: Write,
F: FnOnce(D, &[u8]) -> Result<(), RepeError>,
{
let tmp_path = temp_sibling(path);
let (guard, digest, trailer) = pull_consume(client, resource, |reader| {
let mut digest = digest;
let mut guard = TempFile::create(&tmp_path)?;
let trailer = {
let tee = TeeWriter {
file: guard.file_mut(),
digest: &mut digest,
};
let mut hold = TrailerHold::new(tee, trailer_len);
io::copy(reader, &mut hold)?;
hold.into_trailer()?
};
guard.file_mut().flush()?;
guard.file_mut().sync_all()?;
Ok((guard, digest, trailer))
})?;
verify(digest, &trailer)?;
guard.commit(path)
}
pub fn pull_typed_slice<T: beve::BeveTypedSlice>(
client: &Client,
resource: &str,
) -> Result<Vec<T>, RepeError> {
let open = open_stream(client, resource)?;
if let Err(e) = require_beve(&open) {
let _ = cancel_stream(
client,
open.stream_id,
"format incompatible with bulk decode",
);
return Err(e);
}
let reader = ChunkReader::new(client, open.stream_id);
let result: Result<Vec<T>, RepeError> = match open.compression {
Compression::None => {
beve::read_typed_slice_from_reader::<T, _>(reader).map_err(RepeError::from)
}
Compression::Zstd => match zstd::stream::read::Decoder::new(reader) {
Ok(dec) => beve::read_typed_slice_from_reader::<T, _>(dec).map_err(RepeError::from),
Err(e) => Err(RepeError::Io(e)),
},
};
let _ = cancel_stream(client, open.stream_id, "bulk typed slice complete");
result
}
pub fn pull_complex_slice<T: beve::BeveTypedSlice>(
client: &Client,
resource: &str,
) -> Result<Vec<Complex<T>>, RepeError> {
let open = open_stream(client, resource)?;
if let Err(e) = require_beve(&open) {
let _ = cancel_stream(
client,
open.stream_id,
"format incompatible with bulk decode",
);
return Err(e);
}
let reader = ChunkReader::new(client, open.stream_id);
let result: Result<Vec<Complex<T>>, RepeError> = match open.compression {
Compression::None => {
beve::read_complex_slice_from_reader::<T, _>(reader).map_err(RepeError::from)
}
Compression::Zstd => match zstd::stream::read::Decoder::new(reader) {
Ok(dec) => beve::read_complex_slice_from_reader::<T, _>(dec).map_err(RepeError::from),
Err(e) => Err(RepeError::Io(e)),
},
};
let _ = cancel_stream(client, open.stream_id, "bulk complex slice complete");
result
}
fn require_beve(open: &OpenInfo) -> Result<(), RepeError> {
if open.format != BodyFormat::Beve as u16 {
return Err(RepeError::Io(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"svs: bulk slice decode needs format=BEVE, got format {}",
open.format
),
)));
}
Ok(())
}
struct OpenInfo {
stream_id: u64,
format: u16,
compression: Compression,
}
fn open_request_body(resource: &str) -> Result<Vec<u8>, RepeError> {
Ok(beve::to_vec(&OpenRequest {
resource: resource.to_string(),
})?)
}
fn next_request_body(stream_id: u64) -> Result<Vec<u8>, RepeError> {
Ok(beve::to_vec(&NextRequest { stream_id })?)
}
fn cancel_request_body(stream_id: u64, reason: &str) -> Result<Vec<u8>, RepeError> {
Ok(beve::to_vec(&CancelRequest {
stream_id,
reason: reason.to_string(),
})?)
}
fn parse_open_response(resp: &Message) -> Result<OpenInfo, RepeError> {
let open: OpenResponse = resp.beve_body()?;
if open.version != SVS_VERSION {
return Err(RepeError::Io(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"svs open: server contract version {} != supported {}",
open.version, SVS_VERSION
),
)));
}
let Some(compression) = Compression::from_u8(open.compression) else {
return Err(RepeError::Io(io::Error::new(
io::ErrorKind::InvalidData,
format!("svs open: unknown compression tag {}", open.compression),
)));
};
Ok(OpenInfo {
stream_id: open.stream_id,
format: open.format,
compression,
})
}
fn open_stream(client: &Client, resource: &str) -> Result<OpenInfo, RepeError> {
let body = open_request_body(resource)?;
let resp = client.call_with_formats(
ROUTE_OPEN,
QueryFormat::JsonPointer as u16,
Some(&body),
BodyFormat::Beve as u16,
)?;
parse_open_response(&resp)
}
fn check_output(out: StreamOutput<'_>, open: &OpenInfo) -> Result<(), RepeError> {
let beve = BodyFormat::Beve as u16;
let mismatch = |msg: String| {
Err(RepeError::Io(io::Error::new(
io::ErrorKind::InvalidData,
msg,
)))
};
match out {
StreamOutput::BeveZstdFile(_) => {
if open.compression != Compression::Zstd {
return mismatch(
"svs: .beve.zst output needs a zstd-compressed stream".to_string(),
);
}
}
StreamOutput::BeveFile(_) => {
if open.compression != Compression::Zstd {
return mismatch("svs: .beve output needs a zstd-compressed stream".to_string());
}
if open.format != beve {
return mismatch(format!(
"svs: .beve output needs format=BEVE, got format {}",
open.format
));
}
}
StreamOutput::Value => {
if open.format != beve {
return mismatch(format!(
"svs: value decode needs format=BEVE, got format {}",
open.format
));
}
}
StreamOutput::RawFile(_) => {}
}
Ok(())
}
fn write_file<Fill>(
client: &Client,
stream_id: u64,
final_path: &Path,
fill: Fill,
) -> Result<(), RepeError>
where
Fill: FnOnce(&mut ChunkReader<'_>, &mut std::fs::File) -> Result<(), RepeError>,
{
let tmp_path = temp_sibling(final_path);
let mut guard = TempFile::create(&tmp_path)?;
let mut reader = ChunkReader::new(client, stream_id);
let result = (|| {
fill(&mut reader, guard.file_mut())?;
if !reader.last_seen {
return Err(RepeError::Io(io::Error::new(
io::ErrorKind::UnexpectedEof,
"svs: stream ended without a final chunk",
)));
}
guard.file_mut().flush()?;
guard.file_mut().sync_all()?;
Ok(())
})();
match result {
Ok(()) => guard.commit(final_path),
Err(e) => {
let _ = cancel_stream(client, stream_id, "receiver aborted");
Err(e)
}
}
}
fn temp_sibling(final_path: &Path) -> PathBuf {
let mut name = final_path
.file_name()
.map(|s| s.to_os_string())
.unwrap_or_default();
name.push(".svspart");
final_path.with_file_name(name)
}
struct TempFile {
path: PathBuf,
file: Option<std::fs::File>,
}
impl TempFile {
fn create(path: &Path) -> Result<Self, RepeError> {
let file = std::fs::File::create(path)?;
Ok(Self {
path: path.to_path_buf(),
file: Some(file),
})
}
fn file_mut(&mut self) -> &mut std::fs::File {
self.file.as_mut().expect("temp file open until commit")
}
fn commit(mut self, final_path: &Path) -> Result<(), RepeError> {
self.file = None; match std::fs::rename(&self.path, final_path) {
Ok(()) => {
self.path = final_path.to_path_buf(); Ok(())
}
Err(e) => {
let _ = std::fs::remove_file(&self.path);
Err(RepeError::Io(e))
}
}
}
}
impl Drop for TempFile {
fn drop(&mut self) {
if self.file.is_some() {
self.file = None;
let _ = std::fs::remove_file(&self.path);
}
}
}
struct ChunkReader<'a> {
client: &'a Client,
stream_id: u64,
buf: Vec<u8>,
pos: usize,
finished: bool,
last_seen: bool,
}
impl<'a> ChunkReader<'a> {
fn new(client: &'a Client, stream_id: u64) -> Self {
Self {
client,
stream_id,
buf: Vec::new(),
pos: 0,
finished: false,
last_seen: false,
}
}
fn fetch(&mut self) -> io::Result<()> {
let body = beve::to_vec(&NextRequest {
stream_id: self.stream_id,
})
.map_err(|e| io::Error::other(e.to_string()))?;
let resp = self
.client
.call_with_formats(
ROUTE_NEXT,
QueryFormat::JsonPointer as u16,
Some(&body),
BodyFormat::Beve as u16,
)
.map_err(|e| io::Error::other(e.to_string()))?;
let last = resp.query.first().copied() == Some(1);
self.buf = resp.body;
self.pos = 0;
if last {
self.last_seen = true;
self.finished = true;
}
Ok(())
}
}
impl Read for ChunkReader<'_> {
fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
loop {
if self.pos < self.buf.len() {
let n = out.len().min(self.buf.len() - self.pos);
out[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]);
self.pos += n;
return Ok(n);
}
if self.finished {
return Ok(0);
}
self.fetch()?;
}
}
}
fn cancel_stream(client: &Client, stream_id: u64, reason: &str) -> Result<(), RepeError> {
let body = cancel_request_body(stream_id, reason)?;
client.notify_with_formats(
ROUTE_CANCEL,
QueryFormat::JsonPointer as u16,
Some(&body),
BodyFormat::Beve as u16,
)
}
mod sealed {
pub trait Sealed {}
impl Sealed for crate::async_client::AsyncClient {}
#[cfg(feature = "websocket")]
impl Sealed for crate::websocket_client::WebSocketClient {}
}
#[allow(async_fn_in_trait)]
pub trait AsyncSvsClient: sealed::Sealed {
async fn svs_call(
&self,
path: &str,
query_format: u16,
body: Option<&[u8]>,
body_format: u16,
) -> Result<Message, RepeError>;
async fn svs_notify(
&self,
path: &str,
query_format: u16,
body: Option<&[u8]>,
body_format: u16,
) -> Result<(), RepeError>;
}
impl AsyncSvsClient for AsyncClient {
async fn svs_call(
&self,
path: &str,
query_format: u16,
body: Option<&[u8]>,
body_format: u16,
) -> Result<Message, RepeError> {
self.call_with_formats(path, query_format, body, body_format)
.await
}
async fn svs_notify(
&self,
path: &str,
query_format: u16,
body: Option<&[u8]>,
body_format: u16,
) -> Result<(), RepeError> {
self.notify_with_formats(path, query_format, body, body_format)
.await
}
}
#[cfg(feature = "websocket")]
impl AsyncSvsClient for crate::websocket_client::WebSocketClient {
async fn svs_call(
&self,
path: &str,
query_format: u16,
body: Option<&[u8]>,
body_format: u16,
) -> Result<Message, RepeError> {
self.call_with_formats(path, query_format, body, body_format)
.await
}
async fn svs_notify(
&self,
path: &str,
query_format: u16,
body: Option<&[u8]>,
body_format: u16,
) -> Result<(), RepeError> {
self.notify_with_formats(path, query_format, body, body_format)
.await
}
}
const ASYNC_PULL_DEPTH: usize = 4;
struct ChannelReader {
rx: tokio::sync::mpsc::Receiver<Vec<u8>>,
buf: Vec<u8>,
pos: usize,
}
impl ChannelReader {
fn new(rx: tokio::sync::mpsc::Receiver<Vec<u8>>) -> Self {
Self {
rx,
buf: Vec::new(),
pos: 0,
}
}
}
impl Read for ChannelReader {
fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
loop {
if self.pos < self.buf.len() {
let n = out.len().min(self.buf.len() - self.pos);
out[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]);
self.pos += n;
return Ok(n);
}
match self.rx.blocking_recv() {
Some(chunk) => {
self.buf = chunk;
self.pos = 0;
}
None => return Ok(0),
}
}
}
}
async fn pull_loop_async<C: AsyncSvsClient>(
client: &C,
stream_id: u64,
tx: tokio::sync::mpsc::Sender<Vec<u8>>,
) -> Result<(), RepeError> {
let body = next_request_body(stream_id)?;
loop {
let resp = client
.svs_call(
ROUTE_NEXT,
QueryFormat::JsonPointer as u16,
Some(&body),
BodyFormat::Beve as u16,
)
.await?;
let last = resp.query.first().copied() == Some(1);
if !resp.body.is_empty() && tx.send(resp.body).await.is_err() {
return Ok(());
}
if last {
return Ok(());
}
}
}
async fn cancel_stream_async<C: AsyncSvsClient>(
client: &C,
stream_id: u64,
reason: &str,
) -> Result<(), RepeError> {
let body = cancel_request_body(stream_id, reason)?;
client
.svs_notify(
ROUTE_CANCEL,
QueryFormat::JsonPointer as u16,
Some(&body),
BodyFormat::Beve as u16,
)
.await
}
async fn open_async<C: AsyncSvsClient>(client: &C, resource: &str) -> Result<OpenInfo, RepeError> {
let body = open_request_body(resource)?;
let resp = client
.svs_call(
ROUTE_OPEN,
QueryFormat::JsonPointer as u16,
Some(&body),
BodyFormat::Beve as u16,
)
.await?;
parse_open_response(&resp)
}
async fn run_pull<V, F, C: AsyncSvsClient>(
client: &C,
open: OpenInfo,
consume: F,
) -> Result<V, RepeError>
where
V: Send + 'static,
F: FnOnce(Box<dyn Read>) -> Result<V, RepeError> + Send + 'static,
{
let (tx, rx) = tokio::sync::mpsc::channel::<Vec<u8>>(ASYNC_PULL_DEPTH);
let compression = open.compression;
let consume_task = tokio::task::spawn_blocking(move || -> Result<V, RepeError> {
let reader: Box<dyn Read> = match compression {
Compression::None => Box::new(ChannelReader::new(rx)),
Compression::Zstd => Box::new(
zstd::stream::read::Decoder::new(ChannelReader::new(rx)).map_err(RepeError::Io)?,
),
};
consume(reader)
});
let pull_res = pull_loop_async(client, open.stream_id, tx).await;
let consume_res = consume_task.await;
let _ = cancel_stream_async(client, open.stream_id, "pull complete").await;
pull_res?;
match consume_res {
Ok(v) => v,
Err(join_err) => Err(RepeError::Io(io::Error::other(format!(
"svs consume task failed: {join_err}"
)))),
}
}
async fn pull_beve_async<V, F, C: AsyncSvsClient>(
client: &C,
resource: &str,
decode: F,
) -> Result<V, RepeError>
where
V: Send + 'static,
F: FnOnce(Box<dyn Read>) -> Result<V, RepeError> + Send + 'static,
{
let open = open_async(client, resource).await?;
if let Err(e) = require_beve(&open) {
let _ = cancel_stream_async(client, open.stream_id, "format incompatible").await;
return Err(e);
}
run_pull(client, open, decode).await
}
pub async fn pull_value_async<T: DeserializeOwned + Send + 'static, C: AsyncSvsClient>(
client: &C,
resource: &str,
) -> Result<T, RepeError> {
pull_beve_async(client, resource, |reader| {
beve::from_reader_streaming::<_, T>(reader).map_err(RepeError::from)
})
.await
}
pub async fn pull_typed_slice_async<T: beve::BeveTypedSlice + Send + 'static, C: AsyncSvsClient>(
client: &C,
resource: &str,
) -> Result<Vec<T>, RepeError> {
pull_beve_async(client, resource, |reader| {
beve::read_typed_slice_from_reader::<T, _>(reader).map_err(RepeError::from)
})
.await
}
pub async fn pull_complex_slice_async<
T: beve::BeveTypedSlice + Send + 'static,
C: AsyncSvsClient,
>(
client: &C,
resource: &str,
) -> Result<Vec<Complex<T>>, RepeError> {
pull_beve_async(client, resource, |reader| {
beve::read_complex_slice_from_reader::<T, _>(reader).map_err(RepeError::from)
})
.await
}
pub async fn pull_consume_async<V, F, C: AsyncSvsClient>(
client: &C,
resource: &str,
consume: F,
) -> Result<V, RepeError>
where
V: Send + 'static,
F: FnOnce(Box<dyn Read>) -> Result<V, RepeError> + Send + 'static,
{
let open = open_async(client, resource).await?;
run_pull(client, open, consume).await
}
struct TeeWriter<'a, A: Write, B: Write> {
file: &'a mut A,
digest: &'a mut B,
}
impl<A: Write, B: Write> Write for TeeWriter<'_, A, B> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.file.write_all(buf)?;
self.digest.write_all(buf)?;
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
self.file.flush()?;
self.digest.flush()
}
}
struct TrailerHold<W: Write> {
inner: W,
hold: Vec<u8>,
trailer_len: usize,
}
impl<W: Write> TrailerHold<W> {
fn new(inner: W, trailer_len: usize) -> Self {
Self {
inner,
hold: Vec::with_capacity(trailer_len),
trailer_len,
}
}
fn into_trailer(self) -> io::Result<Vec<u8>> {
if self.hold.len() < self.trailer_len {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
format!(
"svs: stream of {} logical byte(s) is shorter than the {}-byte trailer",
self.hold.len(),
self.trailer_len
),
));
}
Ok(self.hold)
}
}
impl<W: Write> Write for TrailerHold<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let n = self.trailer_len;
if buf.len() >= n {
if !self.hold.is_empty() {
self.inner.write_all(&self.hold)?;
self.hold.clear();
}
let split = buf.len() - n;
self.inner.write_all(&buf[..split])?;
self.hold.extend_from_slice(&buf[split..]);
} else {
self.hold.extend_from_slice(buf);
if self.hold.len() > n {
let overflow = self.hold.len() - n;
self.inner.write_all(&self.hold[..overflow])?;
self.hold.drain(..overflow);
}
}
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
}
pub async fn pull_to_file_async<C: AsyncSvsClient>(
client: &C,
resource: &str,
path: &Path,
) -> Result<u64, RepeError> {
let tmp_path = temp_sibling(path);
let (guard, bytes) = pull_consume_async(client, resource, move |mut reader| {
let mut guard = TempFile::create(&tmp_path)?;
let bytes = io::copy(&mut reader, guard.file_mut())?;
guard.file_mut().flush()?;
guard.file_mut().sync_all()?;
Ok((guard, bytes))
})
.await?;
guard.commit(path)?;
Ok(bytes)
}
pub async fn pull_to_file_verified_async<C, D, V>(
client: &C,
resource: &str,
path: &Path,
digest: D,
verify: V,
) -> Result<(), RepeError>
where
C: AsyncSvsClient,
D: Write + Send + 'static,
V: FnOnce(D) -> Result<(), RepeError>,
{
let tmp_path = temp_sibling(path);
let (guard, digest) = pull_consume_async(client, resource, move |mut reader| {
let mut guard = TempFile::create(&tmp_path)?;
let mut digest = digest;
{
let mut tee = TeeWriter {
file: guard.file_mut(),
digest: &mut digest,
};
io::copy(&mut reader, &mut tee)?;
}
guard.file_mut().flush()?;
guard.file_mut().sync_all()?;
Ok((guard, digest))
})
.await?;
verify(digest)?;
guard.commit(path)
}
pub async fn pull_to_vec_async<C: AsyncSvsClient>(
client: &C,
resource: &str,
) -> Result<Vec<u8>, RepeError> {
pull_consume_async(client, resource, |mut reader| {
let mut buf = Vec::new();
reader.read_to_end(&mut buf)?;
Ok(buf)
})
.await
}
pub async fn pull_to_file_trailer_verified_async<C, D, F>(
client: &C,
resource: &str,
path: &Path,
trailer_len: usize,
digest: D,
verify: F,
) -> Result<(), RepeError>
where
C: AsyncSvsClient,
D: Write + Send + 'static,
F: FnOnce(D, &[u8]) -> Result<(), RepeError>,
{
let tmp_path = temp_sibling(path);
let (guard, digest, trailer) = pull_consume_async(client, resource, move |mut reader| {
let mut digest = digest;
let mut guard = TempFile::create(&tmp_path)?;
let trailer = {
let tee = TeeWriter {
file: guard.file_mut(),
digest: &mut digest,
};
let mut hold = TrailerHold::new(tee, trailer_len);
io::copy(&mut reader, &mut hold)?;
hold.into_trailer()?
};
guard.file_mut().flush()?;
guard.file_mut().sync_all()?;
Ok((guard, digest, trailer))
})
.await?;
verify(digest, &trailer)?;
guard.commit(path)
}
#[cfg(test)]
mod tests {
use super::*;
fn drain(rx: &Receiver<Msg>) -> Vec<Vec<u8>> {
let mut out = Vec::new();
while let Ok(msg) = rx.recv() {
match msg {
Msg::Chunk(c) => out.push(c),
Msg::End | Msg::Fail(_) => break,
}
}
out
}
#[test]
fn chunk_sink_splits_on_size_and_flushes_remainder() {
let (tx, rx) = sync_channel::<Msg>(64);
let mut sink = ChunkSink::new(tx, 4);
sink.write_all(&[0u8; 10]).unwrap();
sink.flush_remaining().unwrap();
drop(sink);
let chunks = drain(&rx);
assert_eq!(
chunks.iter().map(|c| c.len()).collect::<Vec<_>>(),
vec![4, 4, 2]
);
assert_eq!(chunks.concat().len(), 10);
}
#[test]
fn chunk_sink_intermediate_flush_does_not_emit_short_chunk() {
let (tx, rx) = sync_channel::<Msg>(64);
let mut sink = ChunkSink::new(tx, 8);
sink.write_all(&[1u8; 3]).unwrap();
sink.flush().unwrap(); sink.write_all(&[2u8; 7]).unwrap(); sink.flush_remaining().unwrap();
drop(sink);
let chunks = drain(&rx);
assert_eq!(
chunks.iter().map(|c| c.len()).collect::<Vec<_>>(),
vec![8, 2]
);
}
fn session_from(msgs: Vec<Msg>) -> Session {
let (tx, rx) = sync_channel::<Msg>(msgs.len().max(1));
for m in msgs {
tx.send(m).unwrap();
}
drop(tx);
Session {
rx,
lookahead: None,
done: false,
}
}
#[test]
fn pull_marks_only_the_final_chunk_last() {
let mut s = session_from(vec![
Msg::Chunk(vec![1]),
Msg::Chunk(vec![2]),
Msg::Chunk(vec![3]),
Msg::End,
]);
assert_eq!(s.pull().unwrap(), (vec![1], false));
assert_eq!(s.pull().unwrap(), (vec![2], false));
assert_eq!(s.pull().unwrap(), (vec![3], true));
}
#[test]
fn pull_single_chunk_is_last() {
let mut s = session_from(vec![Msg::Chunk(vec![9, 9]), Msg::End]);
assert_eq!(s.pull().unwrap(), (vec![9, 9], true));
}
#[test]
fn pull_zero_chunk_stream_is_empty_last() {
let mut s = session_from(vec![Msg::End]);
assert_eq!(s.pull().unwrap(), (Vec::<u8>::new(), true));
}
#[test]
fn pull_surfaces_producer_failure_instead_of_clean_end() {
let mut s = session_from(vec![Msg::Chunk(vec![1]), Msg::Fail("boom".into())]);
assert_eq!(s.pull().unwrap_err(), "boom");
}
#[test]
fn pull_dropped_producer_is_an_error_not_a_terminus() {
let (tx, rx) = sync_channel::<Msg>(1);
tx.send(Msg::Chunk(vec![7])).unwrap();
drop(tx); let mut s = Session {
rx,
lookahead: None,
done: false,
};
assert!(s.pull().is_err());
}
#[test]
fn trailer_hold_splits_payload_from_trailer_one_byte_at_a_time() {
let mut sink = Vec::new();
{
let mut hold = TrailerHold::new(&mut sink, 4);
for b in 0u8..10 {
hold.write_all(&[b]).unwrap();
}
assert_eq!(hold.into_trailer().unwrap(), vec![6, 7, 8, 9]);
}
assert_eq!(sink, vec![0, 1, 2, 3, 4, 5]);
}
#[test]
fn trailer_hold_splits_across_mixed_write_sizes() {
let mut sink = Vec::new();
{
let mut hold = TrailerHold::new(&mut sink, 4);
hold.write_all(&[0, 1, 2, 3, 4, 5]).unwrap();
hold.write_all(&[6]).unwrap();
hold.write_all(&[7]).unwrap();
hold.write_all(&[8, 9, 10, 11, 12]).unwrap();
assert_eq!(hold.into_trailer().unwrap(), vec![9, 10, 11, 12]);
}
assert_eq!(sink, (0u8..=8).collect::<Vec<_>>());
}
#[test]
fn trailer_hold_exact_length_yields_empty_payload() {
let mut sink = Vec::new();
{
let mut hold = TrailerHold::new(&mut sink, 4);
hold.write_all(&[1, 2, 3, 4]).unwrap();
assert_eq!(hold.into_trailer().unwrap(), vec![1, 2, 3, 4]);
}
assert!(sink.is_empty(), "an all-trailer stream leaves no payload");
}
#[test]
fn trailer_hold_shorter_than_trailer_errors() {
let mut sink = Vec::new();
let mut hold = TrailerHold::new(&mut sink, 8);
hold.write_all(&[1, 2, 3]).unwrap();
assert_eq!(
hold.into_trailer().unwrap_err().kind(),
io::ErrorKind::UnexpectedEof
);
}
#[test]
fn tempfile_commit_cleans_up_on_rename_failure() {
let base = std::env::temp_dir().join(format!("svs-tf-commit-{}", std::process::id()));
std::fs::create_dir_all(&base).unwrap();
let tmp = base.join("payload.svspart");
let target = base.join("target");
std::fs::create_dir_all(target.join("occupant")).unwrap();
let mut guard = TempFile::create(&tmp).unwrap();
guard.file_mut().write_all(b"complete payload").unwrap();
assert!(
guard.commit(&target).is_err(),
"renaming onto a non-empty directory must fail"
);
assert!(
!tmp.exists(),
"a rename failure must not orphan the temp file"
);
std::fs::remove_dir_all(&base).ok();
}
}