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 pending: Pending,
54}
55
56struct Polling {
57 pending: Pending,
58 phase: Phase,
59 poller: crate::automation::command::Poller,
60 bound: Option<String>,
64}
65
66#[derive(Default)]
67struct Inner {
68 pending: VecDeque<Pending>,
69 awaiting: Vec<Awaiting>,
70 polling: Vec<Polling>,
71 notices: Vec<Notice>,
72 notices_replied: usize,
75 pointer: Pointer,
76 next_token: u64,
77 frame: u64,
78 poisoned: Option<String>,
79 view: Option<(String, u64)>,
82 layout_at: Option<web_time::Instant>,
84 layout_dirty: bool,
87 input_this_pass: bool,
91}
92
93impl Inner {
94 fn layout_current(&self) -> bool {
96 !self.layout_dirty && self.layout_at.is_some_and(|at| at.elapsed() < LAYOUT_FRESH)
97 }
98
99 fn need_at(&self, index: usize) -> Need {
101 let p = &self.pending[index];
102 lookup(&p.envelope.cmd).map_or(Need::State, |spec| need(spec, &p.envelope.args))
103 }
104
105 fn dispatchable(&self, index: usize) -> bool {
107 match self.need_at(index) {
108 Need::State => true,
109 Need::Layout => self.layout_current(),
110 Need::Pass => false,
111 }
112 }
113
114 fn is_next(&self, index: usize) -> bool {
118 let Some(client) = self.pending[index].client else { return index == 0 };
119 self.pending.iter().take(index).all(|p| p.client.is_some_and(|other| other != client))
120 }
121
122 fn next_dispatchable(&self) -> Option<usize> {
126 (0..self.pending.len()).find(|&i| self.is_next(i) && self.dispatchable(i))
127 }
128
129 fn waits_for_pass(&self) -> bool {
131 (0..self.pending.len()).any(|i| self.is_next(i) && !self.dispatchable(i))
132 }
133}
134
135const MAX_NOTICES: usize = 256;
140
141impl Inner {
142 fn reply_notices(&mut self) -> Vec<Notice> {
154 let from = self.notices_replied.min(self.notices.len());
155 self.notices_replied = self.notices.len();
156 self.notices[from..].to_vec()
157 }
158}
159
160pub type Waker = Arc<dyn Fn() + Send + Sync>;
162
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub enum Need {
166 State,
168 Layout,
173 Pass,
176}
177
178pub const PASS_BOUND: &[&str] = &["screenshot", "illustration_presentation", "ping"];
182
183pub const LAYOUT_BOUND: &[&str] = &["hit_rects", "state_list", "state_get", "state_schema", "locate", "pick"];
187
188pub const LAYOUT_FRESH: std::time::Duration = std::time::Duration::from_millis(16);
193
194pub fn need(spec: &crate::automation::command::CommandSpec, args: &serde_json::Value) -> Need {
196 match spec.handler {
197 Handler::Input(_) if spec.phase == Phase::Input && spec.annotations.read_only => Need::State,
201 Handler::Input(_) => Need::Pass,
202 Handler::App(_) if spec.phase == Phase::Input || PASS_BOUND.contains(&spec.name) => Need::Pass,
203 Handler::App(_) if matches!(spec.name, "state_get" | "state_schema") => {
204 let names = args.get("names").and_then(serde_json::Value::as_array);
205 let state = names.is_some_and(|names| {
206 names.iter().all(|n| n.as_str().is_some_and(crate::automation::state_blobs::is_state_blob))
207 });
208 if state { Need::State } else { Need::Layout }
209 }
210 Handler::App(_) if LAYOUT_BOUND.contains(&spec.name) => Need::Layout,
211 Handler::App(_) => Need::State,
212 }
213}
214
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum Withdrawn {
219 NotDispatched,
221 Accepted,
224}
225
226#[derive(Default)]
227pub struct AutomationQueue {
228 inner: Mutex<Inner>,
229 ctx: Mutex<Option<egui::Context>>,
230 waker: Mutex<Option<Waker>>,
231}
232
233fn session_pending(error: &str) -> bool {
235 error.contains(brep_render::engine_state::ASSEMBLY_SESSION_PENDING)
236}
237
238const SESSION_PENDING_LIMIT: std::time::Duration = std::time::Duration::from_secs(120);
241
242fn retry_while_session_pending(handler: crate::automation::command::AppHandler, args: serde_json::Value) -> Outcome {
247 let start = web_time::Instant::now();
249 Outcome::Poll(Box::new(move |ctx| {
250 let before = refused_counts(&ctx.app.docs);
251 let result = handler(ctx, args.clone());
252 let result = refused_by_lock(&ctx.app.docs, &before, result);
253 match result {
254 Err(error) if session_pending(&error) && start.elapsed() < SESSION_PENDING_LIMIT => None,
255 Ok(Outcome::Poll(_)) => Some(Err("a retried assembly action started polled work".into())),
256 other => Some(other),
257 }
258 }))
259}
260
261impl AutomationQueue {
262 pub fn new() -> Arc<Self> {
263 Arc::new(Self::default())
264 }
265
266 pub fn attach(&self, ctx: &egui::Context) {
268 *self.ctx.lock().unwrap() = Some(ctx.clone());
269 if self.has_pending() { ctx.request_repaint(); }
270 }
271
272 pub fn set_waker(&self, waker: Waker) {
275 *self.waker.lock().unwrap() = Some(waker.clone());
276 if self.has_pending() { waker(); }
277 }
278
279 fn wake(&self) {
280 let waker = self.waker.lock().unwrap().clone();
281 if let Some(waker) = waker { waker(); }
282 if let Some(ctx) = self.ctx.lock().unwrap().as_ref() {
283 ctx.request_repaint();
284 }
285 }
286
287 pub fn submit(&self, envelope: Envelope) -> Receiver<Reply> {
291 self.submit_before(envelope, None)
292 }
293
294 pub fn submit_before(&self, envelope: Envelope, deadline: Option<web_time::Instant>) -> Receiver<Reply> {
296 self.submit_for(envelope, deadline, None)
297 }
298
299 pub fn submit_for(&self, envelope: Envelope, deadline: Option<web_time::Instant>, client: Option<u64>) -> Receiver<Reply> {
305 let (tx, rx) = channel();
306 let mut inner = self.inner.lock().unwrap();
307 if let Some(why) = &inner.poisoned {
308 let _ = tx.send(Reply::err(envelope.id, inner.frame, format!("session poisoned: {why}"), vec![]));
309 return rx;
310 }
311 if lookup(&envelope.cmd).is_none() {
312 let _ = tx.send(Reply::err(envelope.id, inner.frame, format!("unknown command `{}`", envelope.cmd), vec![]));
313 return rx;
314 }
315 inner.pending.push_back(Pending { envelope, reply: tx, deadline, client });
316 drop(inner);
319 self.wake();
320 rx
321 }
322
323 pub fn withdraw(&self, id: u64) -> Withdrawn {
326 let mut inner = self.inner.lock().unwrap();
327 let frame = inner.frame;
328 if let Some(index) = inner.pending.iter().position(|p| p.envelope.id == id) {
329 let p = inner.pending.remove(index).expect("index from position");
330 let _ = p.reply.send(Reply::err(id, frame, "host_deadline_expired: command expired before dispatch; no effects", vec![]));
331 return Withdrawn::NotDispatched;
332 }
333 Withdrawn::Accepted
334 }
335
336 pub fn has_frameless_work(&self) -> bool {
339 let inner = self.inner.lock().unwrap();
340 !inner.polling.is_empty() || inner.next_dispatchable().is_some()
341 }
342
343 pub fn needs_pass(&self) -> bool {
347 self.inner.lock().unwrap().waits_for_pass()
348 }
349
350 pub fn mark_layout_dirty(&self) {
353 self.inner.lock().unwrap().layout_dirty = true;
354 }
355
356 pub fn note_pass(&self) {
359 let mut inner = self.inner.lock().unwrap();
360 inner.layout_at = Some(web_time::Instant::now());
361 inner.layout_dirty = std::mem::take(&mut inner.input_this_pass);
362 }
363
364 pub fn push_notice(&self, kind: NoticeKind, text: impl Into<String>) {
368 let mut inner = self.inner.lock().unwrap();
369 let frame = inner.frame;
370 inner.notices.push(Notice { kind, frame, text: text.into() });
371 let overflow = inner.notices.len().saturating_sub(MAX_NOTICES);
372 if overflow > 0 {
373 inner.notices.drain(0..overflow);
374 inner.notices_replied = inner.notices_replied.saturating_sub(overflow);
375 }
376 }
377
378 pub fn take_notices(&self) -> Vec<Notice> {
382 let mut inner = self.inner.lock().unwrap();
383 inner.notices_replied = 0;
384 std::mem::take(&mut inner.notices)
385 }
386
387 pub fn pointer(&self) -> Pointer {
388 self.inner.lock().unwrap().pointer.clone()
389 }
390
391 pub fn frame(&self) -> u64 {
392 self.inner.lock().unwrap().frame
393 }
394
395 pub fn has_pending(&self) -> bool {
396 let inner = self.inner.lock().unwrap();
397 !inner.pending.is_empty() || !inner.awaiting.is_empty() || !inner.polling.is_empty()
398 }
399
400 pub fn is_polling(&self, id: u64) -> bool {
404 self.inner.lock().unwrap().polling.iter().any(|p| p.pending.envelope.id == id)
405 }
406
407 pub fn poison(&self, why: impl Into<String>) {
410 let why = why.into();
411 let mut inner = self.inner.lock().unwrap();
412 inner.poisoned = Some(why.clone());
413 let frame = inner.frame;
414 for p in inner.pending.drain(..) {
415 let _ = p.reply.send(Reply::err(p.envelope.id, frame, format!("session poisoned: {why}"), vec![]));
416 }
417 for a in inner.awaiting.drain(..) {
418 let _ = a.pending.reply.send(Reply::err(a.pending.envelope.id, frame, format!("session poisoned: {why}"), vec![]));
419 }
420 }
421
422 pub fn is_poisoned(&self) -> bool {
423 self.inner.lock().unwrap().poisoned.is_some()
424 }
425
426 pub fn drain_input(&self, raw: &mut egui::RawInput, frame: u64, ppp: f32, view: Option<egui::Rect>, ctx: &egui::Context) {
433 let mut inner = self.inner.lock().unwrap();
434 inner.frame = frame;
435 inner.pointer.now = raw.time.unwrap_or_else(|| ctx.input(|i| i.time) + f64::from(raw.predicted_dt));
436
437 if !inner.awaiting.is_empty() {
439 let mut done = Vec::new();
440 for event in &raw.events {
441 if let egui::Event::Screenshot { user_data, image, .. } = event {
442 let token = user_data.data.as_ref().and_then(|d| d.downcast_ref::<u64>()).copied();
443 if let Some(token) = token {
444 if let Some(pos) = inner.awaiting.iter().position(|a| a.token == token) {
445 let a = inner.awaiting.remove(pos);
446 done.push((a, image.clone()));
447 }
448 }
449 }
450 }
451 for (a, image) in done {
452 let notices = inner.reply_notices();
453 let shown = inner.view.clone();
454 let switched = match (&a.document, &shown) {
458 (Some(asked), Some((drawn, _))) => asked != drawn,
459 _ => false,
460 };
461 let result = if switched {
462 Err("document_not_active: the visible document changed between the request and the capture".to_string())
463 } else {
464 crate::automation::cmd_capture::encode_capture(&image, ppp, view, &a.region).map(|(mut json, png)| {
465 if let Some((handle, revision)) = &shown {
466 json["document"] = serde_json::json!({ "documentId": handle, "revision": revision.to_string() });
467 }
468 (json, png)
469 })
470 };
471 let reply = match result {
472 Ok((json, png)) => {
473 let mut r = Reply::ok(a.pending.envelope.id, frame, json, notices);
474 r.blob = Some(png);
475 r
476 }
477 Err(e) => Reply::err(a.pending.envelope.id, frame, e, notices),
478 };
479 let _ = a.pending.reply.send(reply);
480 }
481 }
482
483 let mut keep = VecDeque::new();
485 let mut events = Vec::new();
486 while let Some(p) = inner.pending.pop_front() {
487 if p.expired(frame) { continue; }
488 let Some(spec) = lookup(&p.envelope.cmd) else { continue };
489 match (&spec.handler, spec.phase) {
490 (Handler::Input(f), Phase::Input) => {
491 let result = f(&mut inner.pointer, p.envelope.args.clone(), &mut events);
492 let notices = inner.reply_notices();
493 let reply = match result {
494 Ok(v) => Reply::ok(p.envelope.id, frame, v, notices),
495 Err(e) => Reply::err(p.envelope.id, frame, e, notices),
496 };
497 let _ = p.reply.send(reply);
498 }
499 _ => keep.push_back(p),
500 }
501 }
502 inner.pending = keep;
503 if std::mem::take(&mut inner.pointer.reset_clicks) {
507 ctx.input_mut(|i| i.pointer = egui::PointerState::default());
508 }
509 let held = inner.pointer.egui_modifiers();
516 if held != egui::Modifiers::NONE {
517 raw.modifiers = held;
518 inner.pointer.modifiers_applied = true;
519 } else if std::mem::take(&mut inner.pointer.modifiers_applied) {
520 raw.modifiers = egui::Modifiers::NONE;
521 }
522 if let Some(platform) = inner.pointer.platform {
523 if ctx.os() != platform.os() {
524 ctx.set_os(platform.os());
525 }
526 }
527 inner.input_this_pass = !events.is_empty();
528 raw.events.extend(events);
529 }
530
531 pub fn drain_app(&self, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) {
534 let batch: Vec<Pending> = {
535 let mut inner = self.inner.lock().unwrap();
536 inner.frame = frame;
537 let mut keep = VecDeque::new();
538 let mut batch = Vec::new();
539 while let Some(p) = inner.pending.pop_front() {
540 match lookup(&p.envelope.cmd) {
541 Some(spec) if spec.phase == phase => batch.push(p),
542 _ => keep.push_back(p),
543 }
544 }
545 inner.pending = keep;
546 batch
547 };
548 for p in batch {
549 self.dispatch(p, phase, ctx, frame);
550 }
551 if self.poll(phase, ctx, frame) {
552 ctx.egui.request_repaint();
553 }
554 }
555
556 pub fn drain_frameless(&self, ctx: &mut Ctx<'_>) -> bool {
564 let frame = self.frame();
565 loop {
566 let next = {
567 let mut inner = self.inner.lock().unwrap();
568 let ready = inner.next_dispatchable();
569 match ready.and_then(|i| lookup(&inner.pending[i].envelope.cmd).map(|spec| (i, spec))) {
570 Some((index, spec)) => {
571 let p = inner.pending.remove(index).expect("index from next_dispatchable");
572 if let Handler::Input(f) = &spec.handler {
573 if !p.expired(frame) {
576 let mut events = Vec::new();
577 let result = f(&mut inner.pointer, p.envelope.args.clone(), &mut events);
578 debug_assert!(events.is_empty(), "{} is read-only but emitted input", spec.name);
579 let notices = inner.reply_notices();
580 let reply = match result {
581 Ok(v) => Reply::ok(p.envelope.id, frame, v, notices),
582 Err(e) => Reply::err(p.envelope.id, frame, e, notices),
583 };
584 let _ = p.reply.send(reply);
585 }
586 continue;
587 }
588 Some((p, spec.phase))
589 }
590 _ => None,
591 }
592 };
593 let Some((p, phase)) = next else { break };
594 self.dispatch(p, phase, ctx, frame);
595 }
596 let mutate = self.poll(Phase::Mutate, ctx, frame);
597 let read = self.poll(Phase::Read, ctx, frame);
598 mutate || read
599 }
600
601 fn dispatch(&self, p: Pending, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) {
603 if p.expired(frame) { return; }
604 let spec = lookup(&p.envelope.cmd).expect("checked at submit");
605 let Handler::App(f) = &spec.handler else { return };
606 if !spec.annotations.read_only {
607 self.mark_layout_dirty();
610 }
611 let (args, bound) = match bind_context(&ctx.app.docs, phase, &p.envelope.cmd, p.envelope.args.clone()) {
615 Ok(bound) => bound,
616 Err(e) => {
617 let mut inner = self.inner.lock().unwrap();
618 let notices = inner.reply_notices();
619 let _ = p.reply.send(Reply::err(p.envelope.id, frame, e, notices));
620 return;
621 }
622 };
623 let before = refused_counts(&ctx.app.docs);
624 let route = bound.as_ref().and_then(|b| b.route).map(|index| ctx.app.docs.route_begin(index));
625 let retry_args = args.clone();
626 let result = f(ctx, args);
627 if let Some(visible) = route {
628 ctx.app.docs.route_end(visible);
629 }
630 let result = match result {
635 Err(error) if bound.is_none() && session_pending(&error) => Ok(retry_while_session_pending(*f, retry_args)),
636 other => other,
637 };
638 let result = refused_by_lock(&ctx.app.docs, &before, result);
639 let handle = bound.map(|b| b.handle);
640 let result = match &handle {
641 Some(handle) => tag_context(&ctx.app.docs, handle, result),
642 None => result,
643 };
644 let mut inner = self.inner.lock().unwrap();
645 answer(&mut inner, p, phase, frame, result, handle);
646 }
647
648 fn poll(&self, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) -> bool {
651 let polling: Vec<Polling> = {
652 let mut inner = self.inner.lock().unwrap();
653 let (mine, rest) = std::mem::take(&mut inner.polling).into_iter().partition(|p| p.phase == phase);
654 inner.polling = rest;
655 mine
656 };
657 let mut still = false;
658 for mut entry in polling {
659 match (entry.poller)(ctx) {
660 None => {
661 still = true;
662 self.inner.lock().unwrap().polling.push(entry);
663 }
664 Some(result) => {
665 self.mark_layout_dirty();
667 let result = match &entry.bound {
668 Some(handle) => tag_context(&ctx.app.docs, handle, result),
669 None => result,
670 };
671 let mut inner = self.inner.lock().unwrap();
672 answer(&mut inner, entry.pending, phase, frame, result, entry.bound);
673 still |= !inner.polling.is_empty();
674 }
675 }
676 }
677 still
678 }
679
680 pub fn publish_view(&self, handle: &str, revision: u64) {
683 let mut inner = self.inner.lock().unwrap();
684 if inner.view.as_ref().is_none_or(|(h, r)| h != handle || *r != revision) {
685 inner.view = Some((handle.to_string(), revision));
686 }
687 }
688
689 pub fn fail_captures(&self, error: &str) {
692 let mut inner = self.inner.lock().unwrap();
693 let frame = inner.frame;
694 for a in std::mem::take(&mut inner.awaiting) {
695 let notices = inner.reply_notices();
696 let _ = a.pending.reply.send(Reply::err(a.pending.envelope.id, frame, error.to_string(), notices));
697 }
698 }
699
700 pub fn next_token(&self) -> u64 {
702 let mut inner = self.inner.lock().unwrap();
703 inner.next_token += 1;
704 inner.next_token
705 }
706}
707
708#[derive(serde::Deserialize)]
713#[serde(deny_unknown_fields, rename_all = "camelCase")]
714struct DocumentContext {
715 document_id: String,
716 expected_revision: String,
717}
718
719pub const ENGINE_ONLY: &[&str] = &[
725 "feature_stage",
726 "feature_stage_result",
727 "run_cancel",
728 "history_group_begin",
729 "history_group_end",
730 "feature_add_many",
731 "doc_import",
732 "doc_export",
733 "model_inspect",
734 "mass_properties",
735 "volume",
736 "weld_list",
737 "history_listing",
738 "frame_info",
739 "metadata_set",
740 "metadata_set_many",
741 "metadata_remove",
742];
743
744#[derive(Debug)]
747struct Bound {
748 handle: String,
749 route: Option<usize>,
750}
751
752fn bind_context(
763 docs: &crate::document::Documents,
764 phase: Phase,
765 cmd: &str,
766 mut args: serde_json::Value,
767) -> Result<(serde_json::Value, Option<Bound>), String> {
768 let Some(raw) = args.as_object_mut().and_then(|o| o.remove("context")) else {
769 return Ok((args, None));
770 };
771 let context: DocumentContext = serde_json::from_value(raw)
773 .map_err(|e| format!("invalid_arguments: context must be {{documentId, expectedRevision}}: {e}"))?;
774 let expected = parse_revision(&context.expected_revision)?;
775 match crate::handles::parse("doc", &context.document_id) {
776 crate::handles::Parsed::Current => {}
777 crate::handles::Parsed::OtherEpoch => {
778 return Err("handle_epoch_mismatch: the document handle is from another run of the app".into())
779 }
780 crate::handles::Parsed::Malformed => return Err("invalid_arguments: documentId is not a document handle".into()),
781 }
782 let Some(index) = docs.index_of_handle(&context.document_id) else {
783 return Err("document_unknown: no open document has that handle (closed, or never opened)".into());
784 };
785 if docs.work_part_in_place() {
786 return Err("document_busy: a Work part is edited in place; a document command would write the part".into());
787 }
788 let route = if index == docs.active_index() {
789 None
790 } else if ENGINE_ONLY.contains(&cmd) {
791 Some(index)
792 } else {
793 return Err("document_not_active: this command acts on the visible document; activate the named one first".into());
794 };
795 let current = docs.get(index).map_or(0, |d| d.committed_revision());
796 if phase == Phase::Mutate && current != expected {
797 return Err(format!(
798 "revision_conflict: the document is at revision {current}, not {expected}; read it again before writing"
799 ));
800 }
801 Ok((args, Some(Bound { handle: context.document_id, route })))
802}
803
804fn parse_revision(text: &str) -> Result<u64, String> {
806 let canonical = text == "0" || (!text.is_empty() && !text.starts_with('0') && text.bytes().all(|b| b.is_ascii_digit()));
807 text.parse::<u64>()
808 .ok()
809 .filter(|_| canonical)
810 .ok_or_else(|| "invalid_arguments: expectedRevision must be a canonical unsigned decimal string".into())
811}
812
813fn tag_context(
819 docs: &crate::document::Documents,
820 handle: &str,
821 result: Result<Outcome, String>,
822) -> Result<Outcome, String> {
823 let context = docs.index_of_handle(handle).and_then(|i| docs.get(i)).map(|doc| {
824 serde_json::json!({ "documentId": handle, "expectedRevision": doc.committed_revision().to_string() })
825 });
826 let tag = |v: &mut serde_json::Value| {
827 if let (Some(object), Some(context)) = (v.as_object_mut(), context.clone()) {
828 object.insert("context".into(), context);
829 }
830 };
831 match result {
832 Ok(Outcome::Done(mut v)) => {
833 tag(&mut v);
834 Ok(Outcome::Done(v))
835 }
836 Ok(Outcome::Blob { mut json, bytes }) => {
837 tag(&mut json);
838 Ok(Outcome::Blob { json, bytes })
839 }
840 other => other,
841 }
842}
843
844fn answer(inner: &mut Inner, p: Pending, phase: Phase, frame: u64, result: Result<Outcome, String>, bound: Option<String>) {
846 match result {
847 Ok(Outcome::Done(v)) => {
848 let notices = inner.reply_notices();
849 let _ = p.reply.send(Reply::ok(p.envelope.id, frame, v, notices));
850 }
851 Ok(Outcome::Blob { json, bytes }) => {
852 let notices = inner.reply_notices();
853 let mut r = Reply::ok(p.envelope.id, frame, json, notices);
854 r.blob = Some(bytes);
855 let _ = p.reply.send(r);
856 }
857 Ok(Outcome::AwaitScreenshot { token, region, document }) => {
860 inner.awaiting.push(Awaiting { token, region, document, pending: p });
861 }
862 Ok(Outcome::Poll(poller)) => inner.polling.push(Polling { pending: p, phase, poller, bound }),
863 Err(e) => {
864 let notices = inner.reply_notices();
865 let _ = p.reply.send(Reply::err(p.envelope.id, frame, e, notices));
866 }
867 }
868}
869
870fn refused_counts(docs: &crate::document::Documents) -> Vec<(u64, u64)> {
872 docs.iter().map(|d| (d.id(), d.engine.history.refused_user_edits())).collect()
873}
874
875fn refused_by_lock(
881 docs: &crate::document::Documents,
882 before: &[(u64, u64)],
883 result: Result<Outcome, String>,
884) -> Result<Outcome, String> {
885 if result.is_err() {
886 return result;
887 }
888 for doc in docs.iter() {
889 let was = before.iter().find(|(id, _)| *id == doc.id()).map(|(_, n)| *n);
890 if was.is_some_and(|was| doc.engine.history.refused_user_edits() > was) {
891 if let crate::document::Access::ReadOnly { reason } = doc.access() {
892 return Err(format!("{} is read-only: {reason}", doc.title()));
893 }
894 }
895 }
896 result
897}
898