275 lines
10 KiB
Rust
275 lines
10 KiB
Rust
//! The call surface the wasm facade and the tools expose (review III.3): one operation
|
|
//! name, one JSON text in, one JSON text out, closed outcome kinds, never a panic on
|
|
//! content. The envelope is `{"ok":true,"value":…}` or `{"ok":false,"kind":…,"detail":…}`,
|
|
//! plus `"found":<number>` when a failure names a document version.
|
|
|
|
use serde::Serialize;
|
|
use serde::de::DeserializeOwned;
|
|
use serde_json::{Map, Value};
|
|
|
|
use crate::domain::js::{JsonReadError, parse_json};
|
|
use crate::domain::sheet::{BundledSheetData, LoadError, LoadedSheet};
|
|
use crate::domain::{ReportZone, SheetRef};
|
|
use crate::json::{pretty_js_round_trip, to_js_compact};
|
|
|
|
/// A closed failure of an operation.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct Failure {
|
|
pub kind: &'static str,
|
|
pub detail: String,
|
|
/// The document version a reader refused, as the JavaScript number it was.
|
|
pub found: Option<f64>,
|
|
}
|
|
|
|
impl Failure {
|
|
pub fn new(kind: &'static str, detail: impl std::fmt::Display) -> Self {
|
|
Self {
|
|
kind,
|
|
detail: detail.to_string(),
|
|
found: None,
|
|
}
|
|
}
|
|
}
|
|
|
|
type Outcome = Result<Value, Failure>;
|
|
|
|
/// Runs the free operation `op` on the JSON text `input` and returns the outcome envelope.
|
|
pub fn call(op: &str, input: &str) -> String {
|
|
let outcome = match op {
|
|
"core_version" => Ok(Value::String(crate::CORE_VERSION.to_owned())),
|
|
"pretty_json" => pretty_js_round_trip(input)
|
|
.map(Value::String)
|
|
.map_err(|error| Failure::new("invalid_json", error)),
|
|
"sheet_ref" => echo::<SheetRef>(input),
|
|
"report_zone" => echo::<ReportZone>(input),
|
|
_ => crate::ops::free(op, input).unwrap_or_else(|| Err(unknown(op))),
|
|
};
|
|
render(outcome)
|
|
}
|
|
|
|
/// Reads the bundled sheet payload (`BundledSheetData` JSON) into a loaded, indexed sheet.
|
|
pub fn load_sheet(bundle: &str) -> Result<LoadedSheet, Failure> {
|
|
let data: BundledSheetData = parse_input(bundle)?;
|
|
LoadedSheet::from_bundle(data).map_err(|error| match error {
|
|
LoadError::Shape(error) => Failure::new("invalid_sheet", error),
|
|
LoadError::NoMainView => Failure::new("invalid_sheet", "the sheet has no main view"),
|
|
})
|
|
}
|
|
|
|
/// Runs the operation `op` that needs the session's sheet.
|
|
pub fn call_with_sheet(sheet: &LoadedSheet, op: &str, input: &str) -> String {
|
|
render(crate::ops::on_sheet(sheet, op, input).unwrap_or_else(|| Err(unknown(op))))
|
|
}
|
|
|
|
/// Reads `bytes` as a Faunosteo PDF and imports its attachment onto the session's sheet
|
|
/// (R4, plan §B.1.4): the envelope of `archive.import`, plus the reader's kinds
|
|
/// `invalid_pdf`, `no_attachment`, `attachment_stripped` (`PdfImportKind`).
|
|
#[cfg(feature = "pdf-read")]
|
|
pub fn import_pdf(sheet: &LoadedSheet, bytes: &[u8]) -> String {
|
|
use crate::pdf::import::{PdfImportFailure, PdfImportKind, import_pdf};
|
|
use crate::pdf::read::probe::ProbeLimits;
|
|
let outcome = import_pdf(sheet, bytes, ProbeLimits::PRODUCTION)
|
|
.map_err(|failure| match failure {
|
|
PdfImportFailure::Import(failure) => crate::ops::import_failure(failure),
|
|
read => Failure::new(PdfImportKind::from(&read).as_str(), ""),
|
|
})
|
|
.and_then(|import| to_value(&import));
|
|
render(outcome)
|
|
}
|
|
|
|
/// A rescue copy picked as a file (R4.3, plan §B.1.5 item 4), read as the bytes the worker
|
|
/// streamed: strict UTF-8 as `TextDecoder('utf-8', { fatal: true })` read it, one leading
|
|
/// BOM dropped, then `draft.restore` with no archive, including its OD-3 value budget. The
|
|
/// kinds are `draft.restore`'s; a text that is not UTF-8 is `invalid`, as the application
|
|
/// already called it (`error_invalid_copy`). Takes the bytes by value: the copy lives once.
|
|
#[cfg(feature = "pdf-read")]
|
|
pub fn restore_copy(sheet: &LoadedSheet, bytes: Vec<u8>) -> String {
|
|
use crate::domain::session::restore_draft;
|
|
use crate::ops::{over_value_budget, restore_failure};
|
|
let outcome = Ok(bytes)
|
|
.and_then(|bytes: Vec<u8>| {
|
|
if bytes.len() > crate::pdf::read::MAX_ATTACHMENT_BYTES {
|
|
return Err(Failure::new("invalid", "the copy is over the size cap"));
|
|
}
|
|
String::from_utf8(bytes).map_err(|_| Failure::new("invalid", "not valid UTF-8"))
|
|
})
|
|
.and_then(|text| {
|
|
let text = text.strip_prefix('\u{FEFF}').map_or(text.as_str(), |t| t);
|
|
if over_value_budget(text) {
|
|
return Err(Failure::new("invalid", "json value budget exceeded"));
|
|
}
|
|
restore_draft(sheet, text, None).map_err(restore_failure)
|
|
})
|
|
.and_then(|restore| to_value(&restore));
|
|
render(outcome)
|
|
}
|
|
|
|
/// The export session behind the wasm facade (R4.6, plan §B.1.4): the same envelopes as
|
|
/// the calls, the session's closed kinds (`unknown_key`, `duplicate_key`, `out_of_order`)
|
|
/// and the export's (`ExportErrorKind`).
|
|
#[cfg(feature = "pdf-write")]
|
|
pub mod export {
|
|
use super::{Failure, parse_input, render, to_value};
|
|
use crate::pdf::write::input::{ExportError, ExportInput};
|
|
use crate::pdf::write::session::{ExportSession, SessionError};
|
|
|
|
fn export_failure(error: ExportError) -> Failure {
|
|
Failure::new(error.kind.as_str(), error.detail)
|
|
}
|
|
|
|
fn session_failure(error: SessionError) -> Failure {
|
|
match error {
|
|
SessionError::Refused(refusal) => Failure::new(refusal.as_str(), ""),
|
|
SessionError::Export(error) => export_failure(error),
|
|
}
|
|
}
|
|
|
|
/// Opens a session on the `ExportInput` JSON; the failure names today's export kinds,
|
|
/// or `invalid_shape` / `invalid_json` / `lone_surrogate` for a text that is not one.
|
|
pub fn open(input: &str) -> Result<ExportSession, Failure> {
|
|
let input: ExportInput = parse_input(input)?;
|
|
ExportSession::new(input).map_err(export_failure)
|
|
}
|
|
|
|
/// `next()`: the `ExportStep` as the value.
|
|
pub fn next_step(session: &mut ExportSession) -> String {
|
|
render(
|
|
session
|
|
.next_step()
|
|
.map_err(session_failure)
|
|
.and_then(|step| to_value(&step)),
|
|
)
|
|
}
|
|
|
|
pub fn add_raster(session: &mut ExportSession, key: &str, png: &[u8]) -> String {
|
|
render(
|
|
session
|
|
.add_raster(key, png)
|
|
.map(|()| serde_json::Value::Null)
|
|
.map_err(session_failure),
|
|
)
|
|
}
|
|
|
|
pub fn raster_failed(session: &mut ExportSession, key: &str) -> String {
|
|
render(
|
|
session
|
|
.raster_failed(key)
|
|
.map(|()| serde_json::Value::Null)
|
|
.map_err(session_failure),
|
|
)
|
|
}
|
|
|
|
/// `finish()`: the number of parts the file comes in, or the failure (`out_of_order`,
|
|
/// `self_check_failed`, …).
|
|
pub fn finish(session: &mut ExportSession) -> Result<usize, Failure> {
|
|
session.finish().map_err(session_failure)?;
|
|
Ok(session.parts_left())
|
|
}
|
|
|
|
/// The warnings so far, as a JSON array (`ExportWarning`).
|
|
pub fn warnings(session: &ExportSession) -> String {
|
|
render(to_value(&session.warnings()))
|
|
}
|
|
}
|
|
|
|
fn unknown(op: &str) -> Failure {
|
|
Failure::new("unknown_op", format!("no operation named {op}"))
|
|
}
|
|
|
|
/// A JSON text the core cannot read: `lone_surrogate` when reading it would alter a string
|
|
/// (L1, refused whole), `invalid_json` otherwise.
|
|
impl From<JsonReadError> for Failure {
|
|
fn from(error: JsonReadError) -> Self {
|
|
let kind = match error {
|
|
JsonReadError::LoneSurrogate { .. } => "lone_surrogate",
|
|
JsonReadError::Syntax(_) => "invalid_json",
|
|
};
|
|
Self::new(kind, error)
|
|
}
|
|
}
|
|
|
|
/// Parses the JSON text of an operation input into its contract type.
|
|
pub(crate) fn parse_input<T: DeserializeOwned>(input: &str) -> Result<T, Failure> {
|
|
let value = parse_json(input)?;
|
|
T::deserialize(&value).map_err(|error| Failure::new("invalid_shape", error))
|
|
}
|
|
|
|
pub(crate) fn to_value<T: Serialize>(value: &T) -> Outcome {
|
|
serde_json::to_value(value).map_err(|error| Failure::new("internal", error))
|
|
}
|
|
|
|
fn echo<T: DeserializeOwned + Serialize>(input: &str) -> Outcome {
|
|
let parsed: T = parse_input(input)?;
|
|
to_value(&parsed)
|
|
}
|
|
|
|
fn render(outcome: Outcome) -> String {
|
|
let mut envelope = Map::new();
|
|
match outcome {
|
|
Ok(value) => {
|
|
envelope.insert("ok".to_owned(), Value::Bool(true));
|
|
envelope.insert("value".to_owned(), value);
|
|
}
|
|
Err(failure) => {
|
|
envelope.insert("ok".to_owned(), Value::Bool(false));
|
|
envelope.insert("kind".to_owned(), Value::from(failure.kind));
|
|
envelope.insert("detail".to_owned(), Value::from(failure.detail));
|
|
if let Some(found) = failure.found.and_then(serde_json::Number::from_f64) {
|
|
envelope.insert("found".to_owned(), Value::Number(found));
|
|
}
|
|
}
|
|
}
|
|
to_js_compact(&Value::Object(envelope)).unwrap_or_else(|_| {
|
|
r#"{"ok":false,"kind":"internal","detail":"outcome serialisation failed"}"#.to_owned()
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::{Failure, call, render};
|
|
|
|
#[test]
|
|
fn unknown_operation_is_a_closed_kind() {
|
|
let outcome = call("nope", "{}");
|
|
assert!(outcome.contains(r#""ok":false"#));
|
|
assert!(outcome.contains(r#""kind":"unknown_op""#));
|
|
}
|
|
|
|
#[test]
|
|
fn invalid_json_never_panics() {
|
|
let outcome = call("pretty_json", "{ not json");
|
|
assert!(outcome.contains(r#""kind":"invalid_json""#));
|
|
}
|
|
|
|
#[test]
|
|
fn a_lone_surrogate_input_is_a_closed_kind_never_a_replacement() {
|
|
let outcome = call("report_zone", r#"{"annotationId":"a\ud800","viewId":"v"}"#);
|
|
assert!(outcome.contains(r#""kind":"lone_surrogate""#), "{outcome}");
|
|
assert!(!outcome.contains('\u{FFFD}'));
|
|
}
|
|
|
|
#[test]
|
|
fn report_zone_round_trip_keeps_the_declared_order() {
|
|
let outcome = call(
|
|
"report_zone",
|
|
r#"{"viewId":"v","side":"left","annotationId":"a"}"#,
|
|
);
|
|
assert_eq!(
|
|
outcome,
|
|
r#"{"ok":true,"value":{"annotationId":"a","viewId":"v","side":"left"}}"#
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_found_version_is_printed_as_a_javascript_number() {
|
|
let failure = Failure {
|
|
found: Some(4.0),
|
|
..Failure::new("incompatible_version", "v4")
|
|
};
|
|
assert_eq!(
|
|
render(Err(failure)),
|
|
r#"{"ok":false,"kind":"incompatible_version","detail":"v4","found":4}"#
|
|
);
|
|
}
|
|
}
|