use crate::error::{ServiceError, ERROR_BAD_CHUNK, ERROR_REQUEST_TOO_LARGE};
use serde_json::{json, Value};
use std::time::{Duration, Instant};
pub const METHOD_UPLOAD: &str = "rk.upload";
pub const METHOD_FETCH: &str = "rk.fetch";
pub const RESERVED_PREFIX: &str = "rk.";
pub const CHUNK_TEXT_BYTES: usize = 1024 * 1024;
pub const DEFAULT_MAX_MESSAGE: usize = 0;
pub const SUGGESTED_MAX_MESSAGE: usize = 64 * 1024 * 1024;
pub(crate) fn chunk_bytes_for(frame_limit: usize) -> usize {
(frame_limit / 4).clamp(16, CHUNK_TEXT_BYTES)
}
pub(crate) fn boundaries(text: &str, chunk: usize) -> Vec<usize> {
let chunk = chunk.max(4);
let mut ends = Vec::new();
let mut start = 0;
while start < text.len() {
let mut end = (start + chunk).min(text.len());
while !text.is_char_boundary(end) {
end += 1;
}
ends.push(end);
start = end;
}
if ends.is_empty() {
ends.push(0);
}
ends
}
fn bad(message: impl Into<String>) -> ServiceError {
ServiceError::new(ERROR_BAD_CHUNK, message)
}
pub const MAX_ASSEMBLIES_PER_CONNECTION: usize = 1;
pub const UPLOAD_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
pub const MAX_JSON_DEPTH: usize = 64;
pub const MAX_JSON_NODES: usize = 1 << 20;
pub(crate) fn check_shape(text: &str) -> Result<(), ServiceError> {
let (mut depth, mut nodes) = (0usize, 1usize);
let (mut in_string, mut escaped) = (false, false);
for &b in text.as_bytes() {
if in_string {
if escaped {
escaped = false;
} else if b == b'\\' {
escaped = true;
} else if b == b'"' {
in_string = false;
}
continue;
}
match b {
b'"' => in_string = true,
b'[' | b'{' => {
depth += 1;
nodes += 1;
if depth > MAX_JSON_DEPTH {
return Err(bad(format!(
"the assembled params nest deeper than {MAX_JSON_DEPTH} levels"
)));
}
}
b']' | b'}' => depth = depth.saturating_sub(1),
b',' => nodes += 1,
_ => {}
}
if nodes > MAX_JSON_NODES {
return Err(ServiceError::new(
ERROR_REQUEST_TOO_LARGE,
format!("the assembled params hold more than {MAX_JSON_NODES} values"),
));
}
}
Ok(())
}
#[derive(Debug)]
struct Upload {
id: String,
method: String,
next: u64,
text: String,
touched: Instant,
}
#[derive(Debug, PartialEq)]
pub(crate) enum UploadStep {
More { received: u64 },
Done { method: String, params: Value },
}
#[derive(Debug, Default)]
pub(crate) struct Uploads {
current: Option<Upload>,
}
impl Uploads {
pub(crate) fn expire(&mut self) {
if self
.current
.as_ref()
.is_some_and(|u| u.touched.elapsed() > UPLOAD_IDLE_TIMEOUT)
{
self.current = None;
}
}
pub(crate) fn accept_with(
&mut self,
params: &Value,
max: usize,
authorize: &dyn Fn(&str) -> Result<(), ServiceError>,
) -> Result<UploadStep, ServiceError> {
self.expire();
let result = self.accept_inner(params, max, authorize);
if result.is_err() {
self.current = None;
}
result
}
fn accept_inner(
&mut self,
params: &Value,
max: usize,
authorize: &dyn Fn(&str) -> Result<(), ServiceError>,
) -> Result<UploadStep, ServiceError> {
let id = params["id"]
.as_str()
.filter(|s| !s.is_empty() && s.len() <= 64)
.ok_or_else(|| bad("an upload piece needs an id of 1 to 64 characters"))?;
let seq = params["seq"]
.as_u64()
.ok_or_else(|| bad("an upload piece needs a numeric seq"))?;
let last = params["last"].as_bool().unwrap_or(false);
let text = params["text"]
.as_str()
.ok_or_else(|| bad("an upload piece needs a text"))?;
if seq == 0 {
let method = params["method"]
.as_str()
.filter(|m| !m.is_empty() && !m.starts_with(RESERVED_PREFIX))
.ok_or_else(|| bad("the first piece must name a method outside the rk. prefix"))?;
self.current = None;
authorize(method)?;
if text.len() > max {
return Err(ServiceError::new(
ERROR_REQUEST_TOO_LARGE,
format!("the message is larger than the {max}-byte message limit"),
));
}
self.current = Some(Upload {
id: id.to_string(),
method: method.to_string(),
next: 0,
text: String::new(),
touched: Instant::now(),
});
}
let up = match self.current.as_mut() {
Some(up) if up.id == id && up.next == seq => up,
_ => {
return Err(bad(
"upload piece out of order, repeated, or for another upload",
))
}
};
if up.text.len().saturating_add(text.len()) > max {
return Err(ServiceError::new(
ERROR_REQUEST_TOO_LARGE,
format!("the message is larger than the {max}-byte message limit"),
));
}
up.text.push_str(text);
up.next += 1;
up.touched = Instant::now();
if !last {
return Ok(UploadStep::More { received: seq });
}
let up = self.current.take().expect("the upload was just extended");
check_shape(&up.text)?;
let params = serde_json::from_str::<Value>(&up.text)
.map_err(|e| bad(format!("the assembled params are not JSON: {e}")))?;
Ok(UploadStep::Done {
method: up.method,
params,
})
}
}
#[derive(Debug)]
pub(crate) struct Download {
id: String,
text: String,
ends: Vec<usize>,
}
impl Download {
pub(crate) fn new(id: String, text: String, chunk: usize) -> Self {
let ends = boundaries(&text, chunk);
Self { id, text, ends }
}
pub(crate) fn descriptor(&self) -> Value {
json!({"id": self.id, "bytes": self.text.len(), "count": self.ends.len()})
}
pub(crate) fn fetch(&self, params: &Value) -> Result<Value, ServiceError> {
if params["id"].as_str() != Some(self.id.as_str()) {
return Err(bad(
"no such result on this connection (it was replaced or released)",
));
}
let seq = params["seq"]
.as_u64()
.and_then(|n| usize::try_from(n).ok())
.filter(|n| *n < self.ends.len())
.ok_or_else(|| bad("fetch seq is out of range"))?;
let start = if seq == 0 { 0 } else { self.ends[seq - 1] };
Ok(json!({"seq": seq, "text": &self.text[start..self.ends[seq]]}))
}
}