1use crate::automation::command::{lookup, Ctx, Envelope, Handler, Notice, NoticeKind, Outcome, Phase, Reply};
24use crate::automation::pointer::Pointer;
25use std::collections::VecDeque;
26use std::sync::mpsc::{channel, Receiver, Sender};
27use std::sync::{Arc, Mutex};
28
29pub struct Pending {
30 pub envelope: Envelope,
31 pub reply: Sender<Reply>,
32 deadline: Option<web_time::Instant>,
34 client: Option<u64>,
37}
38
39impl Pending {
40 fn expired(&self, frame: u64) -> bool {
41 if self.deadline.is_some_and(|d| web_time::Instant::now() >= d) {
42 let _ = self.reply.send(Reply::err(self.envelope.id, frame,
43 "host_deadline_expired: command expired before dispatch; no effects", vec![]));
44 true
45 } else { false }
46 }
47}
48
49struct Awaiting {
50 token: u64,
51 region: crate::automation::cmd_capture::Region,
52 document: Option<String>,
53 ppp: f32,
56 scale: f32,
57 pending: Pending,
58}
59
60struct Polling {
61 pending: Pending,
62 phase: Phase,
63 poller: crate::automation::command::Poller,
64 bound: Option<String>,
68}
69
70#[derive(Default)]
71struct Inner {
72 pending: VecDeque<Pending>,
73 awaiting: Vec<Awaiting>,
74 scaled: Vec<(u64, f32)>,
77 scaled_supported: bool,
79 pass_scale: Option<f32>,
81 polling: Vec<Polling>,
82 notices: Vec<Notice>,
83 notices_replied: usize,
86 pointer: Pointer,
87 next_token: u64,
88 frame: u64,
89 poisoned: Option<String>,
90 view: Option<(String, u64)>,
93 layout_at: Option<web_time::Instant>,
95 layout_dirty: bool,
98 input_this_pass: bool,
102 agent_input_passes: u64,
105}
106
107impl Inner {
108 fn layout_current(&self) -> bool {
110 !self.layout_dirty && self.layout_at.is_some_and(|at| at.elapsed() < LAYOUT_FRESH)
111 }
112
113 fn need_at(&self, index: usize) -> Need {
115 let p = &self.pending[index];
116 lookup(&p.envelope.cmd).map_or(Need::State, |spec| need(spec, &p.envelope.args))
117 }
118
119 fn dispatchable(&self, index: usize) -> bool {
121 match self.need_at(index) {
122 Need::State => true,
123 Need::Layout => self.layout_current(),
124 Need::Pass => false,
125 }
126 }
127
128 fn is_next(&self, index: usize) -> bool {
132 let Some(client) = self.pending[index].client else { return index == 0 };
133 self.pending.iter().take(index).all(|p| p.client.is_some_and(|other| other != client))
134 }
135
136 fn next_dispatchable(&self) -> Option<usize> {
140 (0..self.pending.len()).find(|&i| self.is_next(i) && self.dispatchable(i))
141 }
142
143 fn waits_for_pass(&self) -> bool {
145 (0..self.pending.len()).any(|i| self.is_next(i) && !self.dispatchable(i))
146 }
147}
148
149const MAX_NOTICES: usize = 256;
154
155impl Inner {
156 fn reply_notices(&mut self) -> Vec<Notice> {
168 let from = self.notices_replied.min(self.notices.len());
169 self.notices_replied = self.notices.len();
170 self.notices[from..].to_vec()
171 }
172}
173
174pub type Waker = Arc<dyn Fn() + Send + Sync>;
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
179pub enum Need {
180 State,
182 Layout,
187 Pass,
190}
191
192pub const PASS_BOUND: &[&str] = &["screenshot", "illustration_presentation", "ping"];
196
197pub const LAYOUT_BOUND: &[&str] = &["hit_rects", "state_list", "state_get", "state_schema", "locate", "pick", "camera_navigate"];
202
203pub const LAYOUT_FRESH: std::time::Duration = std::time::Duration::from_millis(16);
208
209pub fn need(spec: &crate::automation::command::CommandSpec, args: &serde_json::Value) -> Need {
211 match spec.handler {
212 Handler::Input(_) if spec.phase == Phase::Input && spec.annotations.read_only => Need::State,
216 Handler::Input(_) => Need::Pass,
217 Handler::App(_) if spec.phase == Phase::Input || PASS_BOUND.contains(&spec.name) => Need::Pass,
218 Handler::App(_) if matches!(spec.name, "state_get" | "state_schema") => {
219 let names = args.get("names").and_then(serde_json::Value::as_array);
220 let state = names.is_some_and(|names| {
221 names.iter().all(|n| n.as_str().is_some_and(crate::automation::state_blobs::is_state_blob))
222 });
223 if state { Need::State } else { Need::Layout }
224 }
225 Handler::App(_) if LAYOUT_BOUND.contains(&spec.name) => Need::Layout,
226 Handler::App(_) => Need::State,
227 }
228}
229
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233pub enum Withdrawn {
234 NotDispatched,
236 Accepted,
239}
240
241#[derive(Default)]
242pub struct AutomationQueue {
243 inner: Mutex<Inner>,
244 ctx: Mutex<Option<egui::Context>>,
245 waker: Mutex<Option<Waker>>,
246}
247
248fn session_pending(error: &str) -> bool {
250 error.contains(brep_render::engine_state::ASSEMBLY_SESSION_PENDING)
251}
252
253const SESSION_PENDING_LIMIT: std::time::Duration = std::time::Duration::from_secs(120);
256
257fn retry_while_session_pending(handler: crate::automation::command::AppHandler, args: serde_json::Value) -> Outcome {
262 let start = web_time::Instant::now();
264 Outcome::Poll(Box::new(move |ctx| {
265 let before = refused_counts(&ctx.app.docs);
266 let result = handler(ctx, args.clone());
267 let result = refused_by_lock(&ctx.app.docs, &before, result);
268 match result {
269 Err(error) if session_pending(&error) && start.elapsed() < SESSION_PENDING_LIMIT => None,
270 Ok(Outcome::Poll(_)) => Some(Err("a retried assembly action started polled work".into())),
271 other => Some(other),
272 }
273 }))
274}
275
276impl AutomationQueue {
277 pub fn new() -> Arc<Self> {
278 Arc::new(Self::default())
279 }
280
281 pub fn attach(&self, ctx: &egui::Context) {
283 *self.ctx.lock().unwrap() = Some(ctx.clone());
284 if self.has_pending() { ctx.request_repaint(); }
285 }
286
287 pub fn set_waker(&self, waker: Waker) {
290 *self.waker.lock().unwrap() = Some(waker.clone());
291 if self.has_pending() { waker(); }
292 }
293
294 fn wake(&self) {
295 let waker = self.waker.lock().unwrap().clone();
296 if let Some(waker) = waker { waker(); }
297 if let Some(ctx) = self.ctx.lock().unwrap().as_ref() {
298 ctx.request_repaint();
299 }
300 }
301
302 pub fn submit(&self, envelope: Envelope) -> Receiver<Reply> {
306 self.submit_before(envelope, None)
307 }
308
309 pub fn submit_before(&self, envelope: Envelope, deadline: Option<web_time::Instant>) -> Receiver<Reply> {
311 self.submit_for(envelope, deadline, None)
312 }
313
314 pub fn submit_for(&self, envelope: Envelope, deadline: Option<web_time::Instant>, client: Option<u64>) -> Receiver<Reply> {
320 let (tx, rx) = channel();
321 let mut inner = self.inner.lock().unwrap();
322 if let Some(why) = &inner.poisoned {
323 let _ = tx.send(Reply::err(envelope.id, inner.frame, format!("session poisoned: {why}"), vec![]));
324 return rx;
325 }
326 if lookup(&envelope.cmd).is_none() {
327 let _ = tx.send(Reply::err(envelope.id, inner.frame, format!("unknown command `{}`", envelope.cmd), vec![]));
328 return rx;
329 }
330 inner.pending.push_back(Pending { envelope, reply: tx, deadline, client });
331 drop(inner);
334 self.wake();
335 rx
336 }
337
338 pub fn withdraw(&self, id: u64) -> Withdrawn {
341 let mut inner = self.inner.lock().unwrap();
342 let frame = inner.frame;
343 if let Some(index) = inner.pending.iter().position(|p| p.envelope.id == id) {
344 let p = inner.pending.remove(index).expect("index from position");
345 let _ = p.reply.send(Reply::err(id, frame, "host_deadline_expired: command expired before dispatch; no effects", vec![]));
346 return Withdrawn::NotDispatched;
347 }
348 Withdrawn::Accepted
349 }
350
351 pub fn has_frameless_work(&self) -> bool {
354 let inner = self.inner.lock().unwrap();
355 !inner.polling.is_empty() || inner.next_dispatchable().is_some()
356 }
357
358 pub fn needs_pass(&self) -> bool {
362 self.inner.lock().unwrap().waits_for_pass()
363 }
364
365 pub fn agent_input_passes(&self) -> u64 {
368 self.inner.lock().unwrap().agent_input_passes
369 }
370
371 pub fn mark_layout_dirty(&self) {
374 self.inner.lock().unwrap().layout_dirty = true;
375 }
376
377 pub fn note_pass(&self) {
380 let mut inner = self.inner.lock().unwrap();
381 inner.layout_at = Some(web_time::Instant::now());
382 inner.layout_dirty = std::mem::take(&mut inner.input_this_pass);
383 }
384
385 pub fn push_notice(&self, kind: NoticeKind, text: impl Into<String>) {
389 let mut inner = self.inner.lock().unwrap();
390 let frame = inner.frame;
391 inner.notices.push(Notice { kind, frame, text: text.into() });
392 let overflow = inner.notices.len().saturating_sub(MAX_NOTICES);
393 if overflow > 0 {
394 inner.notices.drain(0..overflow);
395 inner.notices_replied = inner.notices_replied.saturating_sub(overflow);
396 }
397 }
398
399 pub fn take_notices(&self) -> Vec<Notice> {
403 let mut inner = self.inner.lock().unwrap();
404 inner.notices_replied = 0;
405 std::mem::take(&mut inner.notices)
406 }
407
408 pub fn pointer(&self) -> Pointer {
409 self.inner.lock().unwrap().pointer.clone()
410 }
411
412 pub fn frame(&self) -> u64 {
413 self.inner.lock().unwrap().frame
414 }
415
416 pub fn has_pending(&self) -> bool {
417 let inner = self.inner.lock().unwrap();
418 !inner.pending.is_empty() || !inner.awaiting.is_empty() || !inner.polling.is_empty()
419 }
420
421 pub fn is_polling(&self, id: u64) -> bool {
425 self.inner.lock().unwrap().polling.iter().any(|p| p.pending.envelope.id == id)
426 }
427
428 pub fn poison(&self, why: impl Into<String>) {
431 let why = why.into();
432 let mut inner = self.inner.lock().unwrap();
433 inner.poisoned = Some(why.clone());
434 let frame = inner.frame;
435 for p in inner.pending.drain(..) {
436 let _ = p.reply.send(Reply::err(p.envelope.id, frame, format!("session poisoned: {why}"), vec![]));
437 }
438 for a in inner.awaiting.drain(..) {
439 let _ = a.pending.reply.send(Reply::err(a.pending.envelope.id, frame, format!("session poisoned: {why}"), vec![]));
440 }
441 }
442
443 pub fn is_poisoned(&self) -> bool {
444 self.inner.lock().unwrap().poisoned.is_some()
445 }
446
447 pub fn drain_input(&self, raw: &mut egui::RawInput, frame: u64, ppp: f32, view: Option<egui::Rect>, ctx: &egui::Context) {
454 let mut inner = self.inner.lock().unwrap();
455 inner.frame = frame;
456 inner.pointer.now = raw.time.unwrap_or_else(|| ctx.input(|i| i.time) + f64::from(raw.predicted_dt));
457 inner.pointer.view = view;
458
459 if !inner.awaiting.is_empty() {
461 let mut done = Vec::new();
462 for event in &raw.events {
463 if let egui::Event::Screenshot { user_data, image, .. } = event {
464 let token = user_data.data.as_ref().and_then(|d| d.downcast_ref::<u64>()).copied();
465 if let Some(token) = token {
466 if let Some(pos) = inner.awaiting.iter().position(|a| a.token == token) {
467 let a = inner.awaiting.remove(pos);
468 done.push((a, image.clone()));
469 }
470 }
471 }
472 }
473 for (a, image) in done {
474 let notices = inner.reply_notices();
475 let shown = inner.view.clone();
476 let switched = match (&a.document, &shown) {
480 (Some(asked), Some((drawn, _))) => asked != drawn,
481 _ => false,
482 };
483 let result = if switched {
484 Err("document_not_active: the visible document changed between the request and the capture".to_string())
485 } else {
486 let encoded = if a.scale == 1.0 {
487 crate::automation::cmd_capture::encode_capture(&image, ppp, view, &a.region)
488 } else {
489 crate::automation::cmd_capture::encode_capture_scaled(&image, a.ppp, a.scale, view, &a.region)
490 };
491 encoded.map(|(mut json, png)| {
492 if let Some((handle, revision)) = &shown {
493 json["document"] = serde_json::json!({ "documentId": handle, "revision": revision.to_string() });
494 }
495 (json, png)
496 })
497 };
498 let reply = match result {
499 Ok((json, png)) => {
500 let mut r = Reply::ok(a.pending.envelope.id, frame, json, notices);
501 r.blob = Some(png);
502 r
503 }
504 Err(e) => Reply::err(a.pending.envelope.id, frame, e, notices),
505 };
506 let _ = a.pending.reply.send(reply);
507 }
508 }
509
510 let mut keep = VecDeque::new();
512 let mut events = Vec::new();
513 while let Some(p) = inner.pending.pop_front() {
514 if p.expired(frame) { continue; }
515 let Some(spec) = lookup(&p.envelope.cmd) else { continue };
516 match (&spec.handler, spec.phase) {
517 (Handler::Input(f), Phase::Input) => {
518 let result = f(&mut inner.pointer, p.envelope.args.clone(), &mut events);
519 let notices = inner.reply_notices();
520 let reply = match result {
521 Ok(v) => Reply::ok(p.envelope.id, frame, v, notices),
522 Err(e) => Reply::err(p.envelope.id, frame, e, notices),
523 };
524 let _ = p.reply.send(reply);
525 }
526 _ => keep.push_back(p),
527 }
528 }
529 inner.pending = keep;
530 if std::mem::take(&mut inner.pointer.reset_clicks) {
534 ctx.input_mut(|i| i.pointer = egui::PointerState::default());
535 }
536 let held = inner.pointer.egui_modifiers();
543 if held != egui::Modifiers::NONE {
544 raw.modifiers = held;
545 inner.pointer.modifiers_applied = true;
546 } else if std::mem::take(&mut inner.pointer.modifiers_applied) {
547 raw.modifiers = egui::Modifiers::NONE;
548 }
549 if let Some(platform) = inner.pointer.platform {
550 if ctx.os() != platform.os() {
551 ctx.set_os(platform.os());
552 }
553 }
554 inner.input_this_pass = !events.is_empty();
555 inner.agent_input_passes += u64::from(inner.input_this_pass);
556 raw.events.extend(events);
557 }
558
559 pub fn drain_app(&self, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) {
562 let batch: Vec<Pending> = {
563 let mut inner = self.inner.lock().unwrap();
564 inner.frame = frame;
565 let mut keep = VecDeque::new();
566 let mut batch = Vec::new();
567 while let Some(p) = inner.pending.pop_front() {
568 match lookup(&p.envelope.cmd) {
569 Some(spec) if spec.phase == phase => batch.push(p),
570 _ => keep.push_back(p),
571 }
572 }
573 inner.pending = keep;
574 batch
575 };
576 for p in batch {
577 self.dispatch(p, phase, ctx, frame);
578 }
579 if self.poll(phase, ctx, frame) {
580 ctx.egui.request_repaint();
581 }
582 }
583
584 pub fn drain_frameless(&self, ctx: &mut Ctx<'_>) -> bool {
592 let frame = self.frame();
593 loop {
594 let next = {
595 let mut inner = self.inner.lock().unwrap();
596 let ready = inner.next_dispatchable();
597 match ready.and_then(|i| lookup(&inner.pending[i].envelope.cmd).map(|spec| (i, spec))) {
598 Some((index, spec)) => {
599 let p = inner.pending.remove(index).expect("index from next_dispatchable");
600 if let Handler::Input(f) = &spec.handler {
601 if !p.expired(frame) {
604 let mut events = Vec::new();
605 let result = f(&mut inner.pointer, p.envelope.args.clone(), &mut events);
606 debug_assert!(events.is_empty(), "{} is read-only but emitted input", spec.name);
607 let notices = inner.reply_notices();
608 let reply = match result {
609 Ok(v) => Reply::ok(p.envelope.id, frame, v, notices),
610 Err(e) => Reply::err(p.envelope.id, frame, e, notices),
611 };
612 let _ = p.reply.send(reply);
613 }
614 continue;
615 }
616 Some((p, spec.phase))
617 }
618 _ => None,
619 }
620 };
621 let Some((p, phase)) = next else { break };
622 self.dispatch(p, phase, ctx, frame);
623 }
624 let mutate = self.poll(Phase::Mutate, ctx, frame);
625 let read = self.poll(Phase::Read, ctx, frame);
626 mutate || read
627 }
628
629 fn dispatch(&self, p: Pending, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) {
631 if p.expired(frame) { return; }
632 let spec = lookup(&p.envelope.cmd).expect("checked at submit");
633 let Handler::App(f) = &spec.handler else { return };
634 if !spec.annotations.read_only {
635 self.mark_layout_dirty();
638 }
639 let (args, bound) = match bind_context(&ctx.app.docs, phase, &p.envelope.cmd, p.envelope.args.clone()) {
643 Ok(bound) => bound,
644 Err(e) => {
645 let mut inner = self.inner.lock().unwrap();
646 let notices = inner.reply_notices();
647 let _ = p.reply.send(Reply::err(p.envelope.id, frame, e, notices));
648 return;
649 }
650 };
651 let before = refused_counts(&ctx.app.docs);
652 let route = bound.as_ref().and_then(|b| b.route).map(|index| ctx.app.docs.route_begin(index));
653 let retry_args = args.clone();
654 let result = f(ctx, args);
655 if let Some(visible) = route {
656 ctx.app.docs.route_end(visible);
657 }
658 let result = match result {
663 Err(error) if bound.is_none() && session_pending(&error) => Ok(retry_while_session_pending(*f, retry_args)),
664 other => other,
665 };
666 let result = refused_by_lock(&ctx.app.docs, &before, result);
667 let handle = bound.map(|b| b.handle);
668 let result = match &handle {
669 Some(handle) => tag_context(&ctx.app.docs, handle, result),
670 None => result,
671 };
672 let mut inner = self.inner.lock().unwrap();
673 answer(&mut inner, p, phase, frame, result, handle);
674 }
675
676 fn poll(&self, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) -> bool {
679 let polling: Vec<Polling> = {
680 let mut inner = self.inner.lock().unwrap();
681 let (mine, rest) = std::mem::take(&mut inner.polling).into_iter().partition(|p| p.phase == phase);
682 inner.polling = rest;
683 mine
684 };
685 let mut still = false;
686 for mut entry in polling {
687 match (entry.poller)(ctx) {
688 None => {
689 still = true;
690 self.inner.lock().unwrap().polling.push(entry);
691 }
692 Some(result) => {
693 self.mark_layout_dirty();
695 let result = match &entry.bound {
696 Some(handle) => tag_context(&ctx.app.docs, handle, result),
697 None => result,
698 };
699 let mut inner = self.inner.lock().unwrap();
700 answer(&mut inner, entry.pending, phase, frame, result, entry.bound);
701 still |= !inner.polling.is_empty();
702 }
703 }
704 }
705 still
706 }
707
708 pub fn publish_view(&self, handle: &str, revision: u64) {
711 let mut inner = self.inner.lock().unwrap();
712 if inner.view.as_ref().is_none_or(|(h, r)| h != handle || *r != revision) {
713 inner.view = Some((handle.to_string(), revision));
714 }
715 }
716
717 pub fn fail_captures(&self, error: &str) {
720 let mut inner = self.inner.lock().unwrap();
721 let frame = inner.frame;
722 for a in std::mem::take(&mut inner.awaiting) {
723 let notices = inner.reply_notices();
724 let _ = a.pending.reply.send(Reply::err(a.pending.envelope.id, frame, error.to_string(), notices));
725 }
726 }
727
728 pub fn set_scaled_capture(&self, supported: bool) {
731 self.inner.lock().unwrap().scaled_supported = supported;
732 }
733
734 pub fn request_scaled_capture(&self, token: u64, scale: f32) -> bool {
737 let mut inner = self.inner.lock().unwrap();
738 if inner.scaled_supported {
739 inner.scaled.push((token, scale));
740 }
741 inner.scaled_supported
742 }
743
744 pub fn take_scaled_capture(&self) -> Option<(u64, f32)> {
748 let mut inner = self.inner.lock().unwrap();
749 (!inner.scaled.is_empty()).then(|| inner.scaled.remove(0))
750 }
751
752 pub fn wants_scaled_capture(&self) -> bool {
754 !self.inner.lock().unwrap().scaled.is_empty()
755 }
756
757 pub fn set_pass_scale(&self, scale: Option<f32>) {
760 self.inner.lock().unwrap().pass_scale = scale;
761 }
762
763 pub fn pass_scale(&self) -> f32 {
765 self.inner.lock().unwrap().pass_scale.unwrap_or(1.0)
766 }
767
768 pub fn fail_capture(&self, token: u64, error: &str) {
770 let mut inner = self.inner.lock().unwrap();
771 let frame = inner.frame;
772 if let Some(pos) = inner.awaiting.iter().position(|a| a.token == token) {
773 let a = inner.awaiting.remove(pos);
774 let notices = inner.reply_notices();
775 let _ = a.pending.reply.send(Reply::err(a.pending.envelope.id, frame, error.to_string(), notices));
776 }
777 }
778
779 pub fn next_token(&self) -> u64 {
781 let mut inner = self.inner.lock().unwrap();
782 inner.next_token += 1;
783 inner.next_token
784 }
785}
786
787#[derive(serde::Deserialize)]
792#[serde(deny_unknown_fields, rename_all = "camelCase")]
793struct DocumentContext {
794 document_id: String,
795 expected_revision: String,
796}
797
798pub const ENGINE_ONLY: &[&str] = &[
804 "feature_stage",
805 "feature_stage_result",
806 "run_cancel",
807 "history_group_begin",
808 "history_group_end",
809 "feature_add_many",
810 "doc_import",
811 "doc_export",
812 "model_inspect",
813 "mass_properties",
814 "volume",
815 "weld_list",
816 "history_listing",
817 "frame_info",
818 "metadata_set",
819 "metadata_set_many",
820 "metadata_remove",
821];
822
823#[derive(Debug)]
826struct Bound {
827 handle: String,
828 route: Option<usize>,
829}
830
831fn bind_context(
842 docs: &crate::document::Documents,
843 phase: Phase,
844 cmd: &str,
845 mut args: serde_json::Value,
846) -> Result<(serde_json::Value, Option<Bound>), String> {
847 let Some(raw) = args.as_object_mut().and_then(|o| o.remove("context")) else {
848 return Ok((args, None));
849 };
850 let context: DocumentContext = serde_json::from_value(raw)
852 .map_err(|e| format!("invalid_arguments: context must be {{documentId, expectedRevision}}: {e}"))?;
853 let expected = parse_revision(&context.expected_revision)?;
854 match crate::handles::parse("doc", &context.document_id) {
855 crate::handles::Parsed::Current => {}
856 crate::handles::Parsed::OtherEpoch => {
857 return Err("handle_epoch_mismatch: the document handle is from another run of the app".into())
858 }
859 crate::handles::Parsed::Malformed => return Err("invalid_arguments: documentId is not a document handle".into()),
860 }
861 let Some(index) = docs.index_of_handle(&context.document_id) else {
862 return Err("document_unknown: no open document has that handle (closed, or never opened)".into());
863 };
864 if docs.work_part_in_place() {
865 return Err("document_busy: a Work part is edited in place; a document command would write the part".into());
866 }
867 let route = if index == docs.active_index() {
868 None
869 } else if ENGINE_ONLY.contains(&cmd) {
870 Some(index)
871 } else {
872 return Err("document_not_active: this command acts on the visible document; activate the named one first".into());
873 };
874 let current = docs.get(index).map_or(0, |d| d.committed_revision());
875 if phase == Phase::Mutate && current != expected {
876 return Err(format!(
877 "revision_conflict: the document is at revision {current}, not {expected}; read it again before writing"
878 ));
879 }
880 Ok((args, Some(Bound { handle: context.document_id, route })))
881}
882
883fn parse_revision(text: &str) -> Result<u64, String> {
885 let canonical = text == "0" || (!text.is_empty() && !text.starts_with('0') && text.bytes().all(|b| b.is_ascii_digit()));
886 text.parse::<u64>()
887 .ok()
888 .filter(|_| canonical)
889 .ok_or_else(|| "invalid_arguments: expectedRevision must be a canonical unsigned decimal string".into())
890}
891
892fn tag_context(
898 docs: &crate::document::Documents,
899 handle: &str,
900 result: Result<Outcome, String>,
901) -> Result<Outcome, String> {
902 let context = docs.index_of_handle(handle).and_then(|i| docs.get(i)).map(|doc| {
903 serde_json::json!({ "documentId": handle, "expectedRevision": doc.committed_revision().to_string() })
904 });
905 let tag = |v: &mut serde_json::Value| {
906 if let (Some(object), Some(context)) = (v.as_object_mut(), context.clone()) {
907 object.insert("context".into(), context);
908 }
909 };
910 match result {
911 Ok(Outcome::Done(mut v)) => {
912 tag(&mut v);
913 Ok(Outcome::Done(v))
914 }
915 Ok(Outcome::Blob { mut json, bytes }) => {
916 tag(&mut json);
917 Ok(Outcome::Blob { json, bytes })
918 }
919 other => other,
920 }
921}
922
923fn answer(inner: &mut Inner, p: Pending, phase: Phase, frame: u64, result: Result<Outcome, String>, bound: Option<String>) {
925 match result {
926 Ok(Outcome::Done(v)) => {
927 let notices = inner.reply_notices();
928 let _ = p.reply.send(Reply::ok(p.envelope.id, frame, v, notices));
929 }
930 Ok(Outcome::Blob { json, bytes }) => {
931 let notices = inner.reply_notices();
932 let mut r = Reply::ok(p.envelope.id, frame, json, notices);
933 r.blob = Some(bytes);
934 let _ = p.reply.send(r);
935 }
936 Ok(Outcome::AwaitScreenshot { token, region, document, ppp, scale }) => {
939 inner.awaiting.push(Awaiting { token, region, document, ppp, scale, pending: p });
940 }
941 Ok(Outcome::Poll(poller)) => inner.polling.push(Polling { pending: p, phase, poller, bound }),
942 Err(e) => {
943 let notices = inner.reply_notices();
944 let _ = p.reply.send(Reply::err(p.envelope.id, frame, e, notices));
945 }
946 }
947}
948
949fn refused_counts(docs: &crate::document::Documents) -> Vec<(u64, u64)> {
951 docs.iter().map(|d| (d.id(), d.engine.history.refused_user_edits())).collect()
952}
953
954fn refused_by_lock(
960 docs: &crate::document::Documents,
961 before: &[(u64, u64)],
962 result: Result<Outcome, String>,
963) -> Result<Outcome, String> {
964 if result.is_err() {
965 return result;
966 }
967 for doc in docs.iter() {
968 let was = before.iter().find(|(id, _)| *id == doc.id()).map(|(_, n)| *n);
969 if was.is_some_and(|was| doc.engine.history.refused_user_edits() > was) {
970 if let crate::document::Access::ReadOnly { reason } = doc.access() {
971 return Err(format!("{} is read-only: {reason}", doc.title()));
972 }
973 }
974 }
975 result
976}
977