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 raw.modifiers = inner.pointer.modifiers.egui();
510 inner.input_this_pass = !events.is_empty();
511 raw.events.extend(events);
512 }
513
514 pub fn drain_app(&self, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) {
517 let batch: Vec<Pending> = {
518 let mut inner = self.inner.lock().unwrap();
519 inner.frame = frame;
520 let mut keep = VecDeque::new();
521 let mut batch = Vec::new();
522 while let Some(p) = inner.pending.pop_front() {
523 match lookup(&p.envelope.cmd) {
524 Some(spec) if spec.phase == phase => batch.push(p),
525 _ => keep.push_back(p),
526 }
527 }
528 inner.pending = keep;
529 batch
530 };
531 for p in batch {
532 self.dispatch(p, phase, ctx, frame);
533 }
534 if self.poll(phase, ctx, frame) {
535 ctx.egui.request_repaint();
536 }
537 }
538
539 pub fn drain_frameless(&self, ctx: &mut Ctx<'_>) -> bool {
547 let frame = self.frame();
548 loop {
549 let next = {
550 let mut inner = self.inner.lock().unwrap();
551 let ready = inner.next_dispatchable();
552 match ready.and_then(|i| lookup(&inner.pending[i].envelope.cmd).map(|spec| (i, spec))) {
553 Some((index, spec)) => {
554 let p = inner.pending.remove(index).expect("index from next_dispatchable");
555 if let Handler::Input(f) = &spec.handler {
556 if !p.expired(frame) {
559 let mut events = Vec::new();
560 let result = f(&mut inner.pointer, p.envelope.args.clone(), &mut events);
561 debug_assert!(events.is_empty(), "{} is read-only but emitted input", spec.name);
562 let notices = inner.reply_notices();
563 let reply = match result {
564 Ok(v) => Reply::ok(p.envelope.id, frame, v, notices),
565 Err(e) => Reply::err(p.envelope.id, frame, e, notices),
566 };
567 let _ = p.reply.send(reply);
568 }
569 continue;
570 }
571 Some((p, spec.phase))
572 }
573 _ => None,
574 }
575 };
576 let Some((p, phase)) = next else { break };
577 self.dispatch(p, phase, ctx, frame);
578 }
579 let mutate = self.poll(Phase::Mutate, ctx, frame);
580 let read = self.poll(Phase::Read, ctx, frame);
581 mutate || read
582 }
583
584 fn dispatch(&self, p: Pending, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) {
586 if p.expired(frame) { return; }
587 let spec = lookup(&p.envelope.cmd).expect("checked at submit");
588 let Handler::App(f) = &spec.handler else { return };
589 if !spec.annotations.read_only {
590 self.mark_layout_dirty();
593 }
594 let (args, bound) = match bind_context(&ctx.app.docs, phase, &p.envelope.cmd, p.envelope.args.clone()) {
598 Ok(bound) => bound,
599 Err(e) => {
600 let mut inner = self.inner.lock().unwrap();
601 let notices = inner.reply_notices();
602 let _ = p.reply.send(Reply::err(p.envelope.id, frame, e, notices));
603 return;
604 }
605 };
606 let before = refused_counts(&ctx.app.docs);
607 let route = bound.as_ref().and_then(|b| b.route).map(|index| ctx.app.docs.route_begin(index));
608 let retry_args = args.clone();
609 let result = f(ctx, args);
610 if let Some(visible) = route {
611 ctx.app.docs.route_end(visible);
612 }
613 let result = match result {
618 Err(error) if bound.is_none() && session_pending(&error) => Ok(retry_while_session_pending(*f, retry_args)),
619 other => other,
620 };
621 let result = refused_by_lock(&ctx.app.docs, &before, result);
622 let handle = bound.map(|b| b.handle);
623 let result = match &handle {
624 Some(handle) => tag_context(&ctx.app.docs, handle, result),
625 None => result,
626 };
627 let mut inner = self.inner.lock().unwrap();
628 answer(&mut inner, p, phase, frame, result, handle);
629 }
630
631 fn poll(&self, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) -> bool {
634 let polling: Vec<Polling> = {
635 let mut inner = self.inner.lock().unwrap();
636 let (mine, rest) = std::mem::take(&mut inner.polling).into_iter().partition(|p| p.phase == phase);
637 inner.polling = rest;
638 mine
639 };
640 let mut still = false;
641 for mut entry in polling {
642 match (entry.poller)(ctx) {
643 None => {
644 still = true;
645 self.inner.lock().unwrap().polling.push(entry);
646 }
647 Some(result) => {
648 self.mark_layout_dirty();
650 let result = match &entry.bound {
651 Some(handle) => tag_context(&ctx.app.docs, handle, result),
652 None => result,
653 };
654 let mut inner = self.inner.lock().unwrap();
655 answer(&mut inner, entry.pending, phase, frame, result, entry.bound);
656 still |= !inner.polling.is_empty();
657 }
658 }
659 }
660 still
661 }
662
663 pub fn publish_view(&self, handle: &str, revision: u64) {
666 let mut inner = self.inner.lock().unwrap();
667 if inner.view.as_ref().is_none_or(|(h, r)| h != handle || *r != revision) {
668 inner.view = Some((handle.to_string(), revision));
669 }
670 }
671
672 pub fn fail_captures(&self, error: &str) {
675 let mut inner = self.inner.lock().unwrap();
676 let frame = inner.frame;
677 for a in std::mem::take(&mut inner.awaiting) {
678 let notices = inner.reply_notices();
679 let _ = a.pending.reply.send(Reply::err(a.pending.envelope.id, frame, error.to_string(), notices));
680 }
681 }
682
683 pub fn next_token(&self) -> u64 {
685 let mut inner = self.inner.lock().unwrap();
686 inner.next_token += 1;
687 inner.next_token
688 }
689}
690
691#[derive(serde::Deserialize)]
696#[serde(deny_unknown_fields, rename_all = "camelCase")]
697struct DocumentContext {
698 document_id: String,
699 expected_revision: String,
700}
701
702pub const ENGINE_ONLY: &[&str] = &[
708 "feature_stage",
709 "feature_stage_result",
710 "run_cancel",
711 "history_group_begin",
712 "history_group_end",
713 "feature_add_many",
714 "doc_import",
715 "doc_export",
716 "model_inspect",
717 "mass_properties",
718 "weld_list",
719 "history_listing",
720 "frame_info",
721 "metadata_set",
722 "metadata_set_many",
723 "metadata_remove",
724];
725
726#[derive(Debug)]
729struct Bound {
730 handle: String,
731 route: Option<usize>,
732}
733
734fn bind_context(
745 docs: &crate::document::Documents,
746 phase: Phase,
747 cmd: &str,
748 mut args: serde_json::Value,
749) -> Result<(serde_json::Value, Option<Bound>), String> {
750 let Some(raw) = args.as_object_mut().and_then(|o| o.remove("context")) else {
751 return Ok((args, None));
752 };
753 let context: DocumentContext = serde_json::from_value(raw)
755 .map_err(|e| format!("invalid_arguments: context must be {{documentId, expectedRevision}}: {e}"))?;
756 let expected = parse_revision(&context.expected_revision)?;
757 match crate::handles::parse("doc", &context.document_id) {
758 crate::handles::Parsed::Current => {}
759 crate::handles::Parsed::OtherEpoch => {
760 return Err("handle_epoch_mismatch: the document handle is from another run of the app".into())
761 }
762 crate::handles::Parsed::Malformed => return Err("invalid_arguments: documentId is not a document handle".into()),
763 }
764 let Some(index) = docs.index_of_handle(&context.document_id) else {
765 return Err("document_unknown: no open document has that handle (closed, or never opened)".into());
766 };
767 if docs.work_part_in_place() {
768 return Err("document_busy: a Work part is edited in place; a document command would write the part".into());
769 }
770 let route = if index == docs.active_index() {
771 None
772 } else if ENGINE_ONLY.contains(&cmd) {
773 Some(index)
774 } else {
775 return Err("document_not_active: this command acts on the visible document; activate the named one first".into());
776 };
777 let current = docs.get(index).map_or(0, |d| d.committed_revision());
778 if phase == Phase::Mutate && current != expected {
779 return Err(format!(
780 "revision_conflict: the document is at revision {current}, not {expected}; read it again before writing"
781 ));
782 }
783 Ok((args, Some(Bound { handle: context.document_id, route })))
784}
785
786fn parse_revision(text: &str) -> Result<u64, String> {
788 let canonical = text == "0" || (!text.is_empty() && !text.starts_with('0') && text.bytes().all(|b| b.is_ascii_digit()));
789 text.parse::<u64>()
790 .ok()
791 .filter(|_| canonical)
792 .ok_or_else(|| "invalid_arguments: expectedRevision must be a canonical unsigned decimal string".into())
793}
794
795fn tag_context(
801 docs: &crate::document::Documents,
802 handle: &str,
803 result: Result<Outcome, String>,
804) -> Result<Outcome, String> {
805 let context = docs.index_of_handle(handle).and_then(|i| docs.get(i)).map(|doc| {
806 serde_json::json!({ "documentId": handle, "expectedRevision": doc.committed_revision().to_string() })
807 });
808 let tag = |v: &mut serde_json::Value| {
809 if let (Some(object), Some(context)) = (v.as_object_mut(), context.clone()) {
810 object.insert("context".into(), context);
811 }
812 };
813 match result {
814 Ok(Outcome::Done(mut v)) => {
815 tag(&mut v);
816 Ok(Outcome::Done(v))
817 }
818 Ok(Outcome::Blob { mut json, bytes }) => {
819 tag(&mut json);
820 Ok(Outcome::Blob { json, bytes })
821 }
822 other => other,
823 }
824}
825
826fn answer(inner: &mut Inner, p: Pending, phase: Phase, frame: u64, result: Result<Outcome, String>, bound: Option<String>) {
828 match result {
829 Ok(Outcome::Done(v)) => {
830 let notices = inner.reply_notices();
831 let _ = p.reply.send(Reply::ok(p.envelope.id, frame, v, notices));
832 }
833 Ok(Outcome::Blob { json, bytes }) => {
834 let notices = inner.reply_notices();
835 let mut r = Reply::ok(p.envelope.id, frame, json, notices);
836 r.blob = Some(bytes);
837 let _ = p.reply.send(r);
838 }
839 Ok(Outcome::AwaitScreenshot { token, region, document }) => {
842 inner.awaiting.push(Awaiting { token, region, document, pending: p });
843 }
844 Ok(Outcome::Poll(poller)) => inner.polling.push(Polling { pending: p, phase, poller, bound }),
845 Err(e) => {
846 let notices = inner.reply_notices();
847 let _ = p.reply.send(Reply::err(p.envelope.id, frame, e, notices));
848 }
849 }
850}
851
852fn refused_counts(docs: &crate::document::Documents) -> Vec<(u64, u64)> {
854 docs.iter().map(|d| (d.id(), d.engine.history.refused_user_edits())).collect()
855}
856
857fn refused_by_lock(
863 docs: &crate::document::Documents,
864 before: &[(u64, u64)],
865 result: Result<Outcome, String>,
866) -> Result<Outcome, String> {
867 if result.is_err() {
868 return result;
869 }
870 for doc in docs.iter() {
871 let was = before.iter().find(|(id, _)| *id == doc.id()).map(|(_, n)| *n);
872 if was.is_some_and(|was| doc.engine.history.refused_user_edits() > was) {
873 if let crate::document::Access::ReadOnly { reason } = doc.access() {
874 return Err(format!("{} is read-only: {reason}", doc.title()));
875 }
876 }
877 }
878 result
879}
880