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}
103
104impl Inner {
105 fn layout_current(&self) -> bool {
107 !self.layout_dirty && self.layout_at.is_some_and(|at| at.elapsed() < LAYOUT_FRESH)
108 }
109
110 fn need_at(&self, index: usize) -> Need {
112 let p = &self.pending[index];
113 lookup(&p.envelope.cmd).map_or(Need::State, |spec| need(spec, &p.envelope.args))
114 }
115
116 fn dispatchable(&self, index: usize) -> bool {
118 match self.need_at(index) {
119 Need::State => true,
120 Need::Layout => self.layout_current(),
121 Need::Pass => false,
122 }
123 }
124
125 fn is_next(&self, index: usize) -> bool {
129 let Some(client) = self.pending[index].client else { return index == 0 };
130 self.pending.iter().take(index).all(|p| p.client.is_some_and(|other| other != client))
131 }
132
133 fn next_dispatchable(&self) -> Option<usize> {
137 (0..self.pending.len()).find(|&i| self.is_next(i) && self.dispatchable(i))
138 }
139
140 fn waits_for_pass(&self) -> bool {
142 (0..self.pending.len()).any(|i| self.is_next(i) && !self.dispatchable(i))
143 }
144}
145
146const MAX_NOTICES: usize = 256;
151
152impl Inner {
153 fn reply_notices(&mut self) -> Vec<Notice> {
165 let from = self.notices_replied.min(self.notices.len());
166 self.notices_replied = self.notices.len();
167 self.notices[from..].to_vec()
168 }
169}
170
171pub type Waker = Arc<dyn Fn() + Send + Sync>;
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176pub enum Need {
177 State,
179 Layout,
184 Pass,
187}
188
189pub const PASS_BOUND: &[&str] = &["screenshot", "illustration_presentation", "ping"];
193
194pub const LAYOUT_BOUND: &[&str] = &["hit_rects", "state_list", "state_get", "state_schema", "locate", "pick", "camera_navigate"];
199
200pub const LAYOUT_FRESH: std::time::Duration = std::time::Duration::from_millis(16);
205
206pub fn need(spec: &crate::automation::command::CommandSpec, args: &serde_json::Value) -> Need {
208 match spec.handler {
209 Handler::Input(_) if spec.phase == Phase::Input && spec.annotations.read_only => Need::State,
213 Handler::Input(_) => Need::Pass,
214 Handler::App(_) if spec.phase == Phase::Input || PASS_BOUND.contains(&spec.name) => Need::Pass,
215 Handler::App(_) if matches!(spec.name, "state_get" | "state_schema") => {
216 let names = args.get("names").and_then(serde_json::Value::as_array);
217 let state = names.is_some_and(|names| {
218 names.iter().all(|n| n.as_str().is_some_and(crate::automation::state_blobs::is_state_blob))
219 });
220 if state { Need::State } else { Need::Layout }
221 }
222 Handler::App(_) if LAYOUT_BOUND.contains(&spec.name) => Need::Layout,
223 Handler::App(_) => Need::State,
224 }
225}
226
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
230pub enum Withdrawn {
231 NotDispatched,
233 Accepted,
236}
237
238#[derive(Default)]
239pub struct AutomationQueue {
240 inner: Mutex<Inner>,
241 ctx: Mutex<Option<egui::Context>>,
242 waker: Mutex<Option<Waker>>,
243}
244
245fn session_pending(error: &str) -> bool {
247 error.contains(brep_render::engine_state::ASSEMBLY_SESSION_PENDING)
248}
249
250const SESSION_PENDING_LIMIT: std::time::Duration = std::time::Duration::from_secs(120);
253
254fn retry_while_session_pending(handler: crate::automation::command::AppHandler, args: serde_json::Value) -> Outcome {
259 let start = web_time::Instant::now();
261 Outcome::Poll(Box::new(move |ctx| {
262 let before = refused_counts(&ctx.app.docs);
263 let result = handler(ctx, args.clone());
264 let result = refused_by_lock(&ctx.app.docs, &before, result);
265 match result {
266 Err(error) if session_pending(&error) && start.elapsed() < SESSION_PENDING_LIMIT => None,
267 Ok(Outcome::Poll(_)) => Some(Err("a retried assembly action started polled work".into())),
268 other => Some(other),
269 }
270 }))
271}
272
273impl AutomationQueue {
274 pub fn new() -> Arc<Self> {
275 Arc::new(Self::default())
276 }
277
278 pub fn attach(&self, ctx: &egui::Context) {
280 *self.ctx.lock().unwrap() = Some(ctx.clone());
281 if self.has_pending() { ctx.request_repaint(); }
282 }
283
284 pub fn set_waker(&self, waker: Waker) {
287 *self.waker.lock().unwrap() = Some(waker.clone());
288 if self.has_pending() { waker(); }
289 }
290
291 fn wake(&self) {
292 let waker = self.waker.lock().unwrap().clone();
293 if let Some(waker) = waker { waker(); }
294 if let Some(ctx) = self.ctx.lock().unwrap().as_ref() {
295 ctx.request_repaint();
296 }
297 }
298
299 pub fn submit(&self, envelope: Envelope) -> Receiver<Reply> {
303 self.submit_before(envelope, None)
304 }
305
306 pub fn submit_before(&self, envelope: Envelope, deadline: Option<web_time::Instant>) -> Receiver<Reply> {
308 self.submit_for(envelope, deadline, None)
309 }
310
311 pub fn submit_for(&self, envelope: Envelope, deadline: Option<web_time::Instant>, client: Option<u64>) -> Receiver<Reply> {
317 let (tx, rx) = channel();
318 let mut inner = self.inner.lock().unwrap();
319 if let Some(why) = &inner.poisoned {
320 let _ = tx.send(Reply::err(envelope.id, inner.frame, format!("session poisoned: {why}"), vec![]));
321 return rx;
322 }
323 if lookup(&envelope.cmd).is_none() {
324 let _ = tx.send(Reply::err(envelope.id, inner.frame, format!("unknown command `{}`", envelope.cmd), vec![]));
325 return rx;
326 }
327 inner.pending.push_back(Pending { envelope, reply: tx, deadline, client });
328 drop(inner);
331 self.wake();
332 rx
333 }
334
335 pub fn withdraw(&self, id: u64) -> Withdrawn {
338 let mut inner = self.inner.lock().unwrap();
339 let frame = inner.frame;
340 if let Some(index) = inner.pending.iter().position(|p| p.envelope.id == id) {
341 let p = inner.pending.remove(index).expect("index from position");
342 let _ = p.reply.send(Reply::err(id, frame, "host_deadline_expired: command expired before dispatch; no effects", vec![]));
343 return Withdrawn::NotDispatched;
344 }
345 Withdrawn::Accepted
346 }
347
348 pub fn has_frameless_work(&self) -> bool {
351 let inner = self.inner.lock().unwrap();
352 !inner.polling.is_empty() || inner.next_dispatchable().is_some()
353 }
354
355 pub fn needs_pass(&self) -> bool {
359 self.inner.lock().unwrap().waits_for_pass()
360 }
361
362 pub fn mark_layout_dirty(&self) {
365 self.inner.lock().unwrap().layout_dirty = true;
366 }
367
368 pub fn note_pass(&self) {
371 let mut inner = self.inner.lock().unwrap();
372 inner.layout_at = Some(web_time::Instant::now());
373 inner.layout_dirty = std::mem::take(&mut inner.input_this_pass);
374 }
375
376 pub fn push_notice(&self, kind: NoticeKind, text: impl Into<String>) {
380 let mut inner = self.inner.lock().unwrap();
381 let frame = inner.frame;
382 inner.notices.push(Notice { kind, frame, text: text.into() });
383 let overflow = inner.notices.len().saturating_sub(MAX_NOTICES);
384 if overflow > 0 {
385 inner.notices.drain(0..overflow);
386 inner.notices_replied = inner.notices_replied.saturating_sub(overflow);
387 }
388 }
389
390 pub fn take_notices(&self) -> Vec<Notice> {
394 let mut inner = self.inner.lock().unwrap();
395 inner.notices_replied = 0;
396 std::mem::take(&mut inner.notices)
397 }
398
399 pub fn pointer(&self) -> Pointer {
400 self.inner.lock().unwrap().pointer.clone()
401 }
402
403 pub fn frame(&self) -> u64 {
404 self.inner.lock().unwrap().frame
405 }
406
407 pub fn has_pending(&self) -> bool {
408 let inner = self.inner.lock().unwrap();
409 !inner.pending.is_empty() || !inner.awaiting.is_empty() || !inner.polling.is_empty()
410 }
411
412 pub fn is_polling(&self, id: u64) -> bool {
416 self.inner.lock().unwrap().polling.iter().any(|p| p.pending.envelope.id == id)
417 }
418
419 pub fn poison(&self, why: impl Into<String>) {
422 let why = why.into();
423 let mut inner = self.inner.lock().unwrap();
424 inner.poisoned = Some(why.clone());
425 let frame = inner.frame;
426 for p in inner.pending.drain(..) {
427 let _ = p.reply.send(Reply::err(p.envelope.id, frame, format!("session poisoned: {why}"), vec![]));
428 }
429 for a in inner.awaiting.drain(..) {
430 let _ = a.pending.reply.send(Reply::err(a.pending.envelope.id, frame, format!("session poisoned: {why}"), vec![]));
431 }
432 }
433
434 pub fn is_poisoned(&self) -> bool {
435 self.inner.lock().unwrap().poisoned.is_some()
436 }
437
438 pub fn drain_input(&self, raw: &mut egui::RawInput, frame: u64, ppp: f32, view: Option<egui::Rect>, ctx: &egui::Context) {
445 let mut inner = self.inner.lock().unwrap();
446 inner.frame = frame;
447 inner.pointer.now = raw.time.unwrap_or_else(|| ctx.input(|i| i.time) + f64::from(raw.predicted_dt));
448 inner.pointer.view = view;
449
450 if !inner.awaiting.is_empty() {
452 let mut done = Vec::new();
453 for event in &raw.events {
454 if let egui::Event::Screenshot { user_data, image, .. } = event {
455 let token = user_data.data.as_ref().and_then(|d| d.downcast_ref::<u64>()).copied();
456 if let Some(token) = token {
457 if let Some(pos) = inner.awaiting.iter().position(|a| a.token == token) {
458 let a = inner.awaiting.remove(pos);
459 done.push((a, image.clone()));
460 }
461 }
462 }
463 }
464 for (a, image) in done {
465 let notices = inner.reply_notices();
466 let shown = inner.view.clone();
467 let switched = match (&a.document, &shown) {
471 (Some(asked), Some((drawn, _))) => asked != drawn,
472 _ => false,
473 };
474 let result = if switched {
475 Err("document_not_active: the visible document changed between the request and the capture".to_string())
476 } else {
477 let encoded = if a.scale == 1.0 {
478 crate::automation::cmd_capture::encode_capture(&image, ppp, view, &a.region)
479 } else {
480 crate::automation::cmd_capture::encode_capture_scaled(&image, a.ppp, a.scale, view, &a.region)
481 };
482 encoded.map(|(mut json, png)| {
483 if let Some((handle, revision)) = &shown {
484 json["document"] = serde_json::json!({ "documentId": handle, "revision": revision.to_string() });
485 }
486 (json, png)
487 })
488 };
489 let reply = match result {
490 Ok((json, png)) => {
491 let mut r = Reply::ok(a.pending.envelope.id, frame, json, notices);
492 r.blob = Some(png);
493 r
494 }
495 Err(e) => Reply::err(a.pending.envelope.id, frame, e, notices),
496 };
497 let _ = a.pending.reply.send(reply);
498 }
499 }
500
501 let mut keep = VecDeque::new();
503 let mut events = Vec::new();
504 while let Some(p) = inner.pending.pop_front() {
505 if p.expired(frame) { continue; }
506 let Some(spec) = lookup(&p.envelope.cmd) else { continue };
507 match (&spec.handler, spec.phase) {
508 (Handler::Input(f), Phase::Input) => {
509 let result = f(&mut inner.pointer, p.envelope.args.clone(), &mut events);
510 let notices = inner.reply_notices();
511 let reply = match result {
512 Ok(v) => Reply::ok(p.envelope.id, frame, v, notices),
513 Err(e) => Reply::err(p.envelope.id, frame, e, notices),
514 };
515 let _ = p.reply.send(reply);
516 }
517 _ => keep.push_back(p),
518 }
519 }
520 inner.pending = keep;
521 if std::mem::take(&mut inner.pointer.reset_clicks) {
525 ctx.input_mut(|i| i.pointer = egui::PointerState::default());
526 }
527 let held = inner.pointer.egui_modifiers();
534 if held != egui::Modifiers::NONE {
535 raw.modifiers = held;
536 inner.pointer.modifiers_applied = true;
537 } else if std::mem::take(&mut inner.pointer.modifiers_applied) {
538 raw.modifiers = egui::Modifiers::NONE;
539 }
540 if let Some(platform) = inner.pointer.platform {
541 if ctx.os() != platform.os() {
542 ctx.set_os(platform.os());
543 }
544 }
545 inner.input_this_pass = !events.is_empty();
546 raw.events.extend(events);
547 }
548
549 pub fn drain_app(&self, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) {
552 let batch: Vec<Pending> = {
553 let mut inner = self.inner.lock().unwrap();
554 inner.frame = frame;
555 let mut keep = VecDeque::new();
556 let mut batch = Vec::new();
557 while let Some(p) = inner.pending.pop_front() {
558 match lookup(&p.envelope.cmd) {
559 Some(spec) if spec.phase == phase => batch.push(p),
560 _ => keep.push_back(p),
561 }
562 }
563 inner.pending = keep;
564 batch
565 };
566 for p in batch {
567 self.dispatch(p, phase, ctx, frame);
568 }
569 if self.poll(phase, ctx, frame) {
570 ctx.egui.request_repaint();
571 }
572 }
573
574 pub fn drain_frameless(&self, ctx: &mut Ctx<'_>) -> bool {
582 let frame = self.frame();
583 loop {
584 let next = {
585 let mut inner = self.inner.lock().unwrap();
586 let ready = inner.next_dispatchable();
587 match ready.and_then(|i| lookup(&inner.pending[i].envelope.cmd).map(|spec| (i, spec))) {
588 Some((index, spec)) => {
589 let p = inner.pending.remove(index).expect("index from next_dispatchable");
590 if let Handler::Input(f) = &spec.handler {
591 if !p.expired(frame) {
594 let mut events = Vec::new();
595 let result = f(&mut inner.pointer, p.envelope.args.clone(), &mut events);
596 debug_assert!(events.is_empty(), "{} is read-only but emitted input", spec.name);
597 let notices = inner.reply_notices();
598 let reply = match result {
599 Ok(v) => Reply::ok(p.envelope.id, frame, v, notices),
600 Err(e) => Reply::err(p.envelope.id, frame, e, notices),
601 };
602 let _ = p.reply.send(reply);
603 }
604 continue;
605 }
606 Some((p, spec.phase))
607 }
608 _ => None,
609 }
610 };
611 let Some((p, phase)) = next else { break };
612 self.dispatch(p, phase, ctx, frame);
613 }
614 let mutate = self.poll(Phase::Mutate, ctx, frame);
615 let read = self.poll(Phase::Read, ctx, frame);
616 mutate || read
617 }
618
619 fn dispatch(&self, p: Pending, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) {
621 if p.expired(frame) { return; }
622 let spec = lookup(&p.envelope.cmd).expect("checked at submit");
623 let Handler::App(f) = &spec.handler else { return };
624 if !spec.annotations.read_only {
625 self.mark_layout_dirty();
628 }
629 let (args, bound) = match bind_context(&ctx.app.docs, phase, &p.envelope.cmd, p.envelope.args.clone()) {
633 Ok(bound) => bound,
634 Err(e) => {
635 let mut inner = self.inner.lock().unwrap();
636 let notices = inner.reply_notices();
637 let _ = p.reply.send(Reply::err(p.envelope.id, frame, e, notices));
638 return;
639 }
640 };
641 let before = refused_counts(&ctx.app.docs);
642 let route = bound.as_ref().and_then(|b| b.route).map(|index| ctx.app.docs.route_begin(index));
643 let retry_args = args.clone();
644 let result = f(ctx, args);
645 if let Some(visible) = route {
646 ctx.app.docs.route_end(visible);
647 }
648 let result = match result {
653 Err(error) if bound.is_none() && session_pending(&error) => Ok(retry_while_session_pending(*f, retry_args)),
654 other => other,
655 };
656 let result = refused_by_lock(&ctx.app.docs, &before, result);
657 let handle = bound.map(|b| b.handle);
658 let result = match &handle {
659 Some(handle) => tag_context(&ctx.app.docs, handle, result),
660 None => result,
661 };
662 let mut inner = self.inner.lock().unwrap();
663 answer(&mut inner, p, phase, frame, result, handle);
664 }
665
666 fn poll(&self, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) -> bool {
669 let polling: Vec<Polling> = {
670 let mut inner = self.inner.lock().unwrap();
671 let (mine, rest) = std::mem::take(&mut inner.polling).into_iter().partition(|p| p.phase == phase);
672 inner.polling = rest;
673 mine
674 };
675 let mut still = false;
676 for mut entry in polling {
677 match (entry.poller)(ctx) {
678 None => {
679 still = true;
680 self.inner.lock().unwrap().polling.push(entry);
681 }
682 Some(result) => {
683 self.mark_layout_dirty();
685 let result = match &entry.bound {
686 Some(handle) => tag_context(&ctx.app.docs, handle, result),
687 None => result,
688 };
689 let mut inner = self.inner.lock().unwrap();
690 answer(&mut inner, entry.pending, phase, frame, result, entry.bound);
691 still |= !inner.polling.is_empty();
692 }
693 }
694 }
695 still
696 }
697
698 pub fn publish_view(&self, handle: &str, revision: u64) {
701 let mut inner = self.inner.lock().unwrap();
702 if inner.view.as_ref().is_none_or(|(h, r)| h != handle || *r != revision) {
703 inner.view = Some((handle.to_string(), revision));
704 }
705 }
706
707 pub fn fail_captures(&self, error: &str) {
710 let mut inner = self.inner.lock().unwrap();
711 let frame = inner.frame;
712 for a in std::mem::take(&mut inner.awaiting) {
713 let notices = inner.reply_notices();
714 let _ = a.pending.reply.send(Reply::err(a.pending.envelope.id, frame, error.to_string(), notices));
715 }
716 }
717
718 pub fn set_scaled_capture(&self, supported: bool) {
721 self.inner.lock().unwrap().scaled_supported = supported;
722 }
723
724 pub fn request_scaled_capture(&self, token: u64, scale: f32) -> bool {
727 let mut inner = self.inner.lock().unwrap();
728 if inner.scaled_supported {
729 inner.scaled.push((token, scale));
730 }
731 inner.scaled_supported
732 }
733
734 pub fn take_scaled_capture(&self) -> Option<(u64, f32)> {
738 let mut inner = self.inner.lock().unwrap();
739 (!inner.scaled.is_empty()).then(|| inner.scaled.remove(0))
740 }
741
742 pub fn wants_scaled_capture(&self) -> bool {
744 !self.inner.lock().unwrap().scaled.is_empty()
745 }
746
747 pub fn set_pass_scale(&self, scale: Option<f32>) {
750 self.inner.lock().unwrap().pass_scale = scale;
751 }
752
753 pub fn pass_scale(&self) -> f32 {
755 self.inner.lock().unwrap().pass_scale.unwrap_or(1.0)
756 }
757
758 pub fn fail_capture(&self, token: u64, error: &str) {
760 let mut inner = self.inner.lock().unwrap();
761 let frame = inner.frame;
762 if let Some(pos) = inner.awaiting.iter().position(|a| a.token == token) {
763 let a = inner.awaiting.remove(pos);
764 let notices = inner.reply_notices();
765 let _ = a.pending.reply.send(Reply::err(a.pending.envelope.id, frame, error.to_string(), notices));
766 }
767 }
768
769 pub fn next_token(&self) -> u64 {
771 let mut inner = self.inner.lock().unwrap();
772 inner.next_token += 1;
773 inner.next_token
774 }
775}
776
777#[derive(serde::Deserialize)]
782#[serde(deny_unknown_fields, rename_all = "camelCase")]
783struct DocumentContext {
784 document_id: String,
785 expected_revision: String,
786}
787
788pub const ENGINE_ONLY: &[&str] = &[
794 "feature_stage",
795 "feature_stage_result",
796 "run_cancel",
797 "history_group_begin",
798 "history_group_end",
799 "feature_add_many",
800 "doc_import",
801 "doc_export",
802 "model_inspect",
803 "mass_properties",
804 "volume",
805 "weld_list",
806 "history_listing",
807 "frame_info",
808 "metadata_set",
809 "metadata_set_many",
810 "metadata_remove",
811];
812
813#[derive(Debug)]
816struct Bound {
817 handle: String,
818 route: Option<usize>,
819}
820
821fn bind_context(
832 docs: &crate::document::Documents,
833 phase: Phase,
834 cmd: &str,
835 mut args: serde_json::Value,
836) -> Result<(serde_json::Value, Option<Bound>), String> {
837 let Some(raw) = args.as_object_mut().and_then(|o| o.remove("context")) else {
838 return Ok((args, None));
839 };
840 let context: DocumentContext = serde_json::from_value(raw)
842 .map_err(|e| format!("invalid_arguments: context must be {{documentId, expectedRevision}}: {e}"))?;
843 let expected = parse_revision(&context.expected_revision)?;
844 match crate::handles::parse("doc", &context.document_id) {
845 crate::handles::Parsed::Current => {}
846 crate::handles::Parsed::OtherEpoch => {
847 return Err("handle_epoch_mismatch: the document handle is from another run of the app".into())
848 }
849 crate::handles::Parsed::Malformed => return Err("invalid_arguments: documentId is not a document handle".into()),
850 }
851 let Some(index) = docs.index_of_handle(&context.document_id) else {
852 return Err("document_unknown: no open document has that handle (closed, or never opened)".into());
853 };
854 if docs.work_part_in_place() {
855 return Err("document_busy: a Work part is edited in place; a document command would write the part".into());
856 }
857 let route = if index == docs.active_index() {
858 None
859 } else if ENGINE_ONLY.contains(&cmd) {
860 Some(index)
861 } else {
862 return Err("document_not_active: this command acts on the visible document; activate the named one first".into());
863 };
864 let current = docs.get(index).map_or(0, |d| d.committed_revision());
865 if phase == Phase::Mutate && current != expected {
866 return Err(format!(
867 "revision_conflict: the document is at revision {current}, not {expected}; read it again before writing"
868 ));
869 }
870 Ok((args, Some(Bound { handle: context.document_id, route })))
871}
872
873fn parse_revision(text: &str) -> Result<u64, String> {
875 let canonical = text == "0" || (!text.is_empty() && !text.starts_with('0') && text.bytes().all(|b| b.is_ascii_digit()));
876 text.parse::<u64>()
877 .ok()
878 .filter(|_| canonical)
879 .ok_or_else(|| "invalid_arguments: expectedRevision must be a canonical unsigned decimal string".into())
880}
881
882fn tag_context(
888 docs: &crate::document::Documents,
889 handle: &str,
890 result: Result<Outcome, String>,
891) -> Result<Outcome, String> {
892 let context = docs.index_of_handle(handle).and_then(|i| docs.get(i)).map(|doc| {
893 serde_json::json!({ "documentId": handle, "expectedRevision": doc.committed_revision().to_string() })
894 });
895 let tag = |v: &mut serde_json::Value| {
896 if let (Some(object), Some(context)) = (v.as_object_mut(), context.clone()) {
897 object.insert("context".into(), context);
898 }
899 };
900 match result {
901 Ok(Outcome::Done(mut v)) => {
902 tag(&mut v);
903 Ok(Outcome::Done(v))
904 }
905 Ok(Outcome::Blob { mut json, bytes }) => {
906 tag(&mut json);
907 Ok(Outcome::Blob { json, bytes })
908 }
909 other => other,
910 }
911}
912
913fn answer(inner: &mut Inner, p: Pending, phase: Phase, frame: u64, result: Result<Outcome, String>, bound: Option<String>) {
915 match result {
916 Ok(Outcome::Done(v)) => {
917 let notices = inner.reply_notices();
918 let _ = p.reply.send(Reply::ok(p.envelope.id, frame, v, notices));
919 }
920 Ok(Outcome::Blob { json, bytes }) => {
921 let notices = inner.reply_notices();
922 let mut r = Reply::ok(p.envelope.id, frame, json, notices);
923 r.blob = Some(bytes);
924 let _ = p.reply.send(r);
925 }
926 Ok(Outcome::AwaitScreenshot { token, region, document, ppp, scale }) => {
929 inner.awaiting.push(Awaiting { token, region, document, ppp, scale, pending: p });
930 }
931 Ok(Outcome::Poll(poller)) => inner.polling.push(Polling { pending: p, phase, poller, bound }),
932 Err(e) => {
933 let notices = inner.reply_notices();
934 let _ = p.reply.send(Reply::err(p.envelope.id, frame, e, notices));
935 }
936 }
937}
938
939fn refused_counts(docs: &crate::document::Documents) -> Vec<(u64, u64)> {
941 docs.iter().map(|d| (d.id(), d.engine.history.refused_user_edits())).collect()
942}
943
944fn refused_by_lock(
950 docs: &crate::document::Documents,
951 before: &[(u64, u64)],
952 result: Result<Outcome, String>,
953) -> Result<Outcome, String> {
954 if result.is_err() {
955 return result;
956 }
957 for doc in docs.iter() {
958 let was = before.iter().find(|(id, _)| *id == doc.id()).map(|(_, n)| *n);
959 if was.is_some_and(|was| doc.engine.history.refused_user_edits() > was) {
960 if let crate::document::Access::ReadOnly { reason } = doc.access() {
961 return Err(format!("{} is read-only: {reason}", doc.title()));
962 }
963 }
964 }
965 result
966}
967