Compare commits

..
6 changed files with 36 additions and 89 deletions
+2 -2
View File
File diff suppressed because one or more lines are too long
+1 -17
View File
@@ -132,23 +132,7 @@ impl Server {
if batch.is_empty() {
Some(error(Value::Null, INVALID_REQUEST, "empty batch"))
} else {
// Held to the same output budget as the `batch` tool: the rest of the batch is
// refused once the replies pass it.
let mut replies: Vec<Value> = Vec::new();
let mut size = 0usize;
for m in batch {
if size > crate::tools::MAX_BATCH_OUTPUT {
// Notifications get no reply, run or not.
if let Some(id) = m.get("id").cloned() {
replies.push(error(id, INTERNAL_ERROR, "the batch's replies passed the output limit; not run"));
}
continue;
}
if let Some(r) = self.handle(m) {
size = size.saturating_add(crate::tools::json_len(&r));
replies.push(r);
}
}
let replies: Vec<Value> = batch.into_iter().filter_map(|m| self.handle(m)).collect();
(!replies.is_empty()).then_some(Value::Array(replies))
}
}
+4 -68
View File
@@ -202,26 +202,6 @@ fn with_active_id(b: &mut dyn Backend, r: Result<Value, String>) -> Result<Value
Ok(v)
}
/// Most bytes of results one `batch` (or one legacy JSON-RPC batch) keeps for its reply.
pub const MAX_BATCH_OUTPUT: usize = 64 << 20;
/// Length of `v` written as JSON, counted without keeping the text.
pub(crate) fn json_len(v: &Value) -> usize {
struct Count(usize);
impl std::io::Write for Count {
fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
self.0 = self.0.saturating_add(b.len());
Ok(b.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut n = Count(0);
let _ = serde_json::to_writer(&mut n, v);
n.0
}
fn wrap(r: Result<Value, String>) -> ToolResult {
match r {
Ok(v) => ToolResult::json(&v),
@@ -261,25 +241,15 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, a: &Value) -> ToolResult {
"batch" => {
let keep = a.get("keepGoing").and_then(Value::as_bool).unwrap_or(false);
let mut out = Vec::new();
// What the results hold so far: past MAX_BATCH_OUTPUT the batch stops, rather than
// keeping copies of a document command after command until the reply is written.
let mut size = 0usize;
for c in a.get("commands").and_then(Value::as_array).cloned().unwrap_or_default() {
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
let r = exec(b, id, c.get("params").cloned().unwrap_or(json!({})), doc);
let mut failed = r.is_err();
let entry = match r {
let failed = r.is_err();
out.push(match r {
Ok(v) => json!({"command": id, "ok": true, "result": v}),
Err(e) => json!({"command": id, "ok": false, "error": e}),
};
size = size.saturating_add(json_len(&entry));
if size > MAX_BATCH_OUTPUT {
out.push(json!({"command": id, "ok": false, "error": format!("the batch's results passed {MAX_BATCH_OUTPUT} bytes; this command's result and the commands after it are left out")}));
failed = true;
} else {
out.push(entry);
}
if failed && (!keep || size > MAX_BATCH_OUTPUT) {
});
if failed && !keep {
return ToolResult { content: vec![json!({"type": "text", "text": Value::Array(out).to_string()})], is_error: true };
}
}
@@ -414,40 +384,6 @@ mod tests {
assert!(b.seen.take().expect("called").1.get("doc").is_none());
}
/// A backend whose every result is 1 MiB of text (a whole document, say).
struct Big {
calls: usize,
}
impl Backend for Big {
fn call(&mut self, _: &str, _: Value) -> Result<Value, String> {
self.calls += 1;
Ok(json!("x".repeat(1 << 20)))
}
fn has_ui(&self) -> bool {
false
}
fn describe(&self) -> String {
"big".into()
}
}
#[test]
fn a_batch_stops_once_its_results_pass_the_output_budget() {
// 200 commands of 1 MiB results each kept 200 MiB until the reply; it stops at 64 MiB.
let commands: Vec<Value> = (0..200).map(|_| json!({"command": "edit.copy"})).collect();
let mut b = Big { calls: 0 };
let r = call_tool(&mut b, "batch", &json!({"commands": commands, "keepGoing": true}));
assert!(r.is_error);
assert!(b.calls <= (MAX_BATCH_OUTPUT >> 20) + 1, "{} commands ran", b.calls);
let text = r.content[0]["text"].as_str().unwrap_or_default();
assert!(text.len() <= MAX_BATCH_OUTPUT + 1024, "{}", text.len());
assert!(text.contains("left out"));
// A small batch is untouched.
let r = call_tool(&mut b, "batch", &json!({"commands": [{"command": "edit.copy"}]}));
assert!(!r.is_error);
}
/// The password has to be in the schema, or a client has no way to know it can be sent.
#[test]
fn the_schema_advertises_the_password_as_optional() {
+13 -1
View File
@@ -836,10 +836,22 @@ fn draw_image(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
}
}
/// Widest path drawn, in device pixels a side: 64 times the largest canvas. The rasteriser
/// flattens a curve into as many points as its size asks for, before clipping, so a path with
/// coordinates of 1e15 (file data in a native document) would take it forever or run out of
/// memory; one this far past every canvas shows nothing a real drawing would.
const MAX_PATH_PIXELS: f64 = 1_048_576.0;
/// Whether `path` under `view` is small enough to draw ([`MAX_PATH_PIXELS`]) and finite.
fn path_extent_ok(view: Affine, path: &kurbo::BezPath) -> bool {
let b = view.transform_rect_bbox(path.bounding_box());
path.is_finite() && [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_PATH_PIXELS)
}
fn draw_path(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
let Draw::Path { segs, fill, stroke, stroke_width, dash, cap } = it else { return };
let path = wordcraft_layout::display::seg_path(segs);
if path.elements().is_empty() {
if path.elements().is_empty() || !path_extent_ok(fr.view, &path) {
return;
}
ctx.set_transform(fr.view);
+15
View File
@@ -1318,3 +1318,18 @@ fn a_line_runs_from_top_left_to_bottom_right() {
let p = shape_path(ShapeKind::Line, kurbo::Rect::new(10.0, 20.0, 30.0, 60.0), None);
assert_eq!(p.elements(), &[kurbo::PathEl::MoveTo((10.0, 20.0).into()), kurbo::PathEl::LineTo((30.0, 60.0).into())]);
}
#[test]
fn paths_far_past_every_canvas_are_not_flattened() {
let line = |x: f64| {
let mut p = kurbo::BezPath::new();
p.move_to((0.0, 0.0));
p.curve_to((x, 0.0), (x, x), (0.0, x));
p
};
assert!(path_extent_ok(Affine::IDENTITY, &line(500.0)));
assert!(path_extent_ok(Affine::scale(4.0), &line(200_000.0)), "a large page at a high zoom");
assert!(!path_extent_ok(Affine::IDENTITY, &line(1e15)));
assert!(!path_extent_ok(Affine::scale(1e12), &line(10.0)));
assert!(!path_extent_ok(Affine::IDENTITY, &line(f64::NAN)));
}
+1 -1
View File
File diff suppressed because one or more lines are too long