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<std::time::Instant>,
33 client: Option<u64>,
36}
37
38impl Pending {
39 fn expired(&self, frame: u64) -> bool {
40 if self.deadline.is_some_and(|d| std::time::Instant::now() >= d) {
41 let _ = self.reply.send(Reply::err(self.envelope.id, frame,
42 "host_deadline_expired: command expired before dispatch; no effects", vec![]));
43 true
44 } else { false }
45 }
46}
47
48struct Awaiting {
49 token: u64,
50 region: crate::automation::cmd_capture::Region,
51 document: Option<String>,
52 pending: Pending,
53}
54
55struct Polling {
56 pending: Pending,
57 phase: Phase,
58 poller: crate::automation::command::Poller,
59 bound: Option<String>,
63}
64
65#[derive(Default)]
66struct Inner {
67 pending: VecDeque<Pending>,
68 awaiting: Vec<Awaiting>,
69 polling: Vec<Polling>,
70 notices: Vec<Notice>,
71 notices_replied: usize,
74 pointer: Pointer,
75 next_token: u64,
76 frame: u64,
77 poisoned: Option<String>,
78 view: Option<(String, u64)>,
81 layout_at: Option<web_time::Instant>,
83 layout_dirty: bool,
86 input_this_pass: bool,
90}
91
92impl Inner {
93 fn layout_current(&self) -> bool {
95 !self.layout_dirty && self.layout_at.is_some_and(|at| at.elapsed() < LAYOUT_FRESH)
96 }
97
98 fn need_at(&self, index: usize) -> Need {
100 let p = &self.pending[index];
101 lookup(&p.envelope.cmd).map_or(Need::State, |spec| need(spec, &p.envelope.args))
102 }
103
104 fn dispatchable(&self, index: usize) -> bool {
106 match self.need_at(index) {
107 Need::State => true,
108 Need::Layout => self.layout_current(),
109 Need::Pass => false,
110 }
111 }
112
113 fn is_next(&self, index: usize) -> bool {
117 let Some(client) = self.pending[index].client else { return index == 0 };
118 self.pending.iter().take(index).all(|p| p.client.is_some_and(|other| other != client))
119 }
120
121 fn next_dispatchable(&self) -> Option<usize> {
125 (0..self.pending.len()).find(|&i| self.is_next(i) && self.dispatchable(i))
126 }
127
128 fn waits_for_pass(&self) -> bool {
130 (0..self.pending.len()).any(|i| self.is_next(i) && !self.dispatchable(i))
131 }
132}
133
134const MAX_NOTICES: usize = 256;
139
140impl Inner {
141 fn reply_notices(&mut self) -> Vec<Notice> {
153 let from = self.notices_replied.min(self.notices.len());
154 self.notices_replied = self.notices.len();
155 self.notices[from..].to_vec()
156 }
157}
158
159pub type Waker = Arc<dyn Fn() + Send + Sync>;
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
164pub enum Need {
165 State,
167 Layout,
172 Pass,
175}
176
177pub const PASS_BOUND: &[&str] = &["screenshot", "illustration_presentation", "ping"];
181
182pub const LAYOUT_BOUND: &[&str] = &["hit_rects", "state_list", "state_get", "state_schema", "locate", "pick"];
186
187pub const LAYOUT_FRESH: std::time::Duration = std::time::Duration::from_millis(16);
192
193pub fn need(spec: &crate::automation::command::CommandSpec, args: &serde_json::Value) -> Need {
195 match spec.handler {
196 Handler::Input(_) if spec.phase == Phase::Input && spec.annotations.read_only => Need::State,
200 Handler::Input(_) => Need::Pass,
201 Handler::App(_) if spec.phase == Phase::Input || PASS_BOUND.contains(&spec.name) => Need::Pass,
202 Handler::App(_) if matches!(spec.name, "state_get" | "state_schema") => {
203 let names = args.get("names").and_then(serde_json::Value::as_array);
204 let state = names.is_some_and(|names| {
205 names.iter().all(|n| n.as_str().is_some_and(crate::automation::state_blobs::is_state_blob))
206 });
207 if state { Need::State } else { Need::Layout }
208 }
209 Handler::App(_) if LAYOUT_BOUND.contains(&spec.name) => Need::Layout,
210 Handler::App(_) => Need::State,
211 }
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub enum Withdrawn {
218 NotDispatched,
220 Accepted,
223}
224
225#[derive(Default)]
226pub struct AutomationQueue {
227 inner: Mutex<Inner>,
228 ctx: Mutex<Option<egui::Context>>,
229 waker: Mutex<Option<Waker>>,
230}
231
232fn session_pending(error: &str) -> bool {
234 error.contains(brep_render::engine_state::ASSEMBLY_SESSION_PENDING)
235}
236
237const SESSION_PENDING_LIMIT: std::time::Duration = std::time::Duration::from_secs(120);
240
241fn retry_while_session_pending(handler: crate::automation::command::AppHandler, args: serde_json::Value) -> Outcome {
246 let start = std::time::Instant::now();
247 Outcome::Poll(Box::new(move |ctx| {
248 let before = refused_counts(&ctx.app.docs);
249 let result = handler(ctx, args.clone());
250 let result = refused_by_lock(&ctx.app.docs, &before, result);
251 match result {
252 Err(error) if session_pending(&error) && start.elapsed() < SESSION_PENDING_LIMIT => None,
253 Ok(Outcome::Poll(_)) => Some(Err("a retried assembly action started polled work".into())),
254 other => Some(other),
255 }
256 }))
257}
258
259impl AutomationQueue {
260 pub fn new() -> Arc<Self> {
261 Arc::new(Self::default())
262 }
263
264 pub fn attach(&self, ctx: &egui::Context) {
266 *self.ctx.lock().unwrap() = Some(ctx.clone());
267 if self.has_pending() { ctx.request_repaint(); }
268 }
269
270 pub fn set_waker(&self, waker: Waker) {
273 *self.waker.lock().unwrap() = Some(waker.clone());
274 if self.has_pending() { waker(); }
275 }
276
277 fn wake(&self) {
278 let waker = self.waker.lock().unwrap().clone();
279 if let Some(waker) = waker { waker(); }
280 if let Some(ctx) = self.ctx.lock().unwrap().as_ref() {
281 ctx.request_repaint();
282 }
283 }
284
285 pub fn submit(&self, envelope: Envelope) -> Receiver<Reply> {
289 self.submit_before(envelope, None)
290 }
291
292 pub fn submit_before(&self, envelope: Envelope, deadline: Option<std::time::Instant>) -> Receiver<Reply> {
294 self.submit_for(envelope, deadline, None)
295 }
296
297 pub fn submit_for(&self, envelope: Envelope, deadline: Option<std::time::Instant>, client: Option<u64>) -> Receiver<Reply> {
303 let (tx, rx) = channel();
304 let mut inner = self.inner.lock().unwrap();
305 if let Some(why) = &inner.poisoned {
306 let _ = tx.send(Reply::err(envelope.id, inner.frame, format!("session poisoned: {why}"), vec![]));
307 return rx;
308 }
309 if lookup(&envelope.cmd).is_none() {
310 let _ = tx.send(Reply::err(envelope.id, inner.frame, format!("unknown command `{}`", envelope.cmd), vec![]));
311 return rx;
312 }
313 inner.pending.push_back(Pending { envelope, reply: tx, deadline, client });
314 drop(inner);
317 self.wake();
318 rx
319 }
320
321 pub fn withdraw(&self, id: u64) -> Withdrawn {
324 let mut inner = self.inner.lock().unwrap();
325 let frame = inner.frame;
326 if let Some(index) = inner.pending.iter().position(|p| p.envelope.id == id) {
327 let p = inner.pending.remove(index).expect("index from position");
328 let _ = p.reply.send(Reply::err(id, frame, "host_deadline_expired: command expired before dispatch; no effects", vec![]));
329 return Withdrawn::NotDispatched;
330 }
331 Withdrawn::Accepted
332 }
333
334 pub fn has_frameless_work(&self) -> bool {
337 let inner = self.inner.lock().unwrap();
338 !inner.polling.is_empty() || inner.next_dispatchable().is_some()
339 }
340
341 pub fn needs_pass(&self) -> bool {
345 self.inner.lock().unwrap().waits_for_pass()
346 }
347
348 pub fn mark_layout_dirty(&self) {
351 self.inner.lock().unwrap().layout_dirty = true;
352 }
353
354 pub fn note_pass(&self) {
357 let mut inner = self.inner.lock().unwrap();
358 inner.layout_at = Some(web_time::Instant::now());
359 inner.layout_dirty = std::mem::take(&mut inner.input_this_pass);
360 }
361
362 pub fn push_notice(&self, kind: NoticeKind, text: impl Into<String>) {
366 let mut inner = self.inner.lock().unwrap();
367 let frame = inner.frame;
368 inner.notices.push(Notice { kind, frame, text: text.into() });
369 let overflow = inner.notices.len().saturating_sub(MAX_NOTICES);
370 if overflow > 0 {
371 inner.notices.drain(0..overflow);
372 inner.notices_replied = inner.notices_replied.saturating_sub(overflow);
373 }
374 }
375
376 pub fn take_notices(&self) -> Vec<Notice> {
380 let mut inner = self.inner.lock().unwrap();
381 inner.notices_replied = 0;
382 std::mem::take(&mut inner.notices)
383 }
384
385 pub fn pointer(&self) -> Pointer {
386 self.inner.lock().unwrap().pointer.clone()
387 }
388
389 pub fn frame(&self) -> u64 {
390 self.inner.lock().unwrap().frame
391 }
392
393 pub fn has_pending(&self) -> bool {
394 let inner = self.inner.lock().unwrap();
395 !inner.pending.is_empty() || !inner.awaiting.is_empty() || !inner.polling.is_empty()
396 }
397
398 pub fn is_polling(&self, id: u64) -> bool {
402 self.inner.lock().unwrap().polling.iter().any(|p| p.pending.envelope.id == id)
403 }
404
405 pub fn poison(&self, why: impl Into<String>) {
408 let why = why.into();
409 let mut inner = self.inner.lock().unwrap();
410 inner.poisoned = Some(why.clone());
411 let frame = inner.frame;
412 for p in inner.pending.drain(..) {
413 let _ = p.reply.send(Reply::err(p.envelope.id, frame, format!("session poisoned: {why}"), vec![]));
414 }
415 for a in inner.awaiting.drain(..) {
416 let _ = a.pending.reply.send(Reply::err(a.pending.envelope.id, frame, format!("session poisoned: {why}"), vec![]));
417 }
418 }
419
420 pub fn is_poisoned(&self) -> bool {
421 self.inner.lock().unwrap().poisoned.is_some()
422 }
423
424 pub fn drain_input(&self, raw: &mut egui::RawInput, frame: u64, ppp: f32, view: Option<egui::Rect>, ctx: &egui::Context) {
431 let mut inner = self.inner.lock().unwrap();
432 inner.frame = frame;
433 inner.pointer.now = raw.time.unwrap_or_else(|| ctx.input(|i| i.time) + f64::from(raw.predicted_dt));
434
435 if !inner.awaiting.is_empty() {
437 let mut done = Vec::new();
438 for event in &raw.events {
439 if let egui::Event::Screenshot { user_data, image, .. } = event {
440 let token = user_data.data.as_ref().and_then(|d| d.downcast_ref::<u64>()).copied();
441 if let Some(token) = token {
442 if let Some(pos) = inner.awaiting.iter().position(|a| a.token == token) {
443 let a = inner.awaiting.remove(pos);
444 done.push((a, image.clone()));
445 }
446 }
447 }
448 }
449 for (a, image) in done {
450 let notices = inner.reply_notices();
451 let shown = inner.view.clone();
452 let switched = match (&a.document, &shown) {
456 (Some(asked), Some((drawn, _))) => asked != drawn,
457 _ => false,
458 };
459 let result = if switched {
460 Err("document_not_active: the visible document changed between the request and the capture".to_string())
461 } else {
462 crate::automation::cmd_capture::encode_capture(&image, ppp, view, &a.region).map(|(mut json, png)| {
463 if let Some((handle, revision)) = &shown {
464 json["document"] = serde_json::json!({ "documentId": handle, "revision": revision.to_string() });
465 }
466 (json, png)
467 })
468 };
469 let reply = match result {
470 Ok((json, png)) => {
471 let mut r = Reply::ok(a.pending.envelope.id, frame, json, notices);
472 r.blob = Some(png);
473 r
474 }
475 Err(e) => Reply::err(a.pending.envelope.id, frame, e, notices),
476 };
477 let _ = a.pending.reply.send(reply);
478 }
479 }
480
481 let mut keep = VecDeque::new();
483 let mut events = Vec::new();
484 while let Some(p) = inner.pending.pop_front() {
485 if p.expired(frame) { continue; }
486 let Some(spec) = lookup(&p.envelope.cmd) else { continue };
487 match (&spec.handler, spec.phase) {
488 (Handler::Input(f), Phase::Input) => {
489 let result = f(&mut inner.pointer, p.envelope.args.clone(), &mut events);
490 let notices = inner.reply_notices();
491 let reply = match result {
492 Ok(v) => Reply::ok(p.envelope.id, frame, v, notices),
493 Err(e) => Reply::err(p.envelope.id, frame, e, notices),
494 };
495 let _ = p.reply.send(reply);
496 }
497 _ => keep.push_back(p),
498 }
499 }
500 inner.pending = keep;
501 if std::mem::take(&mut inner.pointer.reset_clicks) {
505 ctx.input_mut(|i| i.pointer = egui::PointerState::default());
506 }
507 raw.modifiers = inner.pointer.modifiers.egui();
508 inner.input_this_pass = !events.is_empty();
509 raw.events.extend(events);
510 }
511
512 pub fn drain_app(&self, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) {
515 let batch: Vec<Pending> = {
516 let mut inner = self.inner.lock().unwrap();
517 inner.frame = frame;
518 let mut keep = VecDeque::new();
519 let mut batch = Vec::new();
520 while let Some(p) = inner.pending.pop_front() {
521 match lookup(&p.envelope.cmd) {
522 Some(spec) if spec.phase == phase => batch.push(p),
523 _ => keep.push_back(p),
524 }
525 }
526 inner.pending = keep;
527 batch
528 };
529 for p in batch {
530 self.dispatch(p, phase, ctx, frame);
531 }
532 if self.poll(phase, ctx, frame) {
533 ctx.egui.request_repaint();
534 }
535 }
536
537 pub fn drain_frameless(&self, ctx: &mut Ctx<'_>) -> bool {
545 let frame = self.frame();
546 loop {
547 let next = {
548 let mut inner = self.inner.lock().unwrap();
549 let ready = inner.next_dispatchable();
550 match ready.and_then(|i| lookup(&inner.pending[i].envelope.cmd).map(|spec| (i, spec))) {
551 Some((index, spec)) => {
552 let p = inner.pending.remove(index).expect("index from next_dispatchable");
553 if let Handler::Input(f) = &spec.handler {
554 if !p.expired(frame) {
557 let mut events = Vec::new();
558 let result = f(&mut inner.pointer, p.envelope.args.clone(), &mut events);
559 debug_assert!(events.is_empty(), "{} is read-only but emitted input", spec.name);
560 let notices = inner.reply_notices();
561 let reply = match result {
562 Ok(v) => Reply::ok(p.envelope.id, frame, v, notices),
563 Err(e) => Reply::err(p.envelope.id, frame, e, notices),
564 };
565 let _ = p.reply.send(reply);
566 }
567 continue;
568 }
569 Some((p, spec.phase))
570 }
571 _ => None,
572 }
573 };
574 let Some((p, phase)) = next else { break };
575 self.dispatch(p, phase, ctx, frame);
576 }
577 let mutate = self.poll(Phase::Mutate, ctx, frame);
578 let read = self.poll(Phase::Read, ctx, frame);
579 mutate || read
580 }
581
582 fn dispatch(&self, p: Pending, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) {
584 if p.expired(frame) { return; }
585 let spec = lookup(&p.envelope.cmd).expect("checked at submit");
586 let Handler::App(f) = &spec.handler else { return };
587 if !spec.annotations.read_only {
588 self.mark_layout_dirty();
591 }
592 let (args, bound) = match bind_context(&ctx.app.docs, phase, &p.envelope.cmd, p.envelope.args.clone()) {
596 Ok(bound) => bound,
597 Err(e) => {
598 let mut inner = self.inner.lock().unwrap();
599 let notices = inner.reply_notices();
600 let _ = p.reply.send(Reply::err(p.envelope.id, frame, e, notices));
601 return;
602 }
603 };
604 let before = refused_counts(&ctx.app.docs);
605 let route = bound.as_ref().and_then(|b| b.route).map(|index| ctx.app.docs.route_begin(index));
606 let retry_args = args.clone();
607 let result = f(ctx, args);
608 if let Some(visible) = route {
609 ctx.app.docs.route_end(visible);
610 }
611 let result = match result {
616 Err(error) if bound.is_none() && session_pending(&error) => Ok(retry_while_session_pending(*f, retry_args)),
617 other => other,
618 };
619 let result = refused_by_lock(&ctx.app.docs, &before, result);
620 let handle = bound.map(|b| b.handle);
621 let result = match &handle {
622 Some(handle) => tag_context(&ctx.app.docs, handle, result),
623 None => result,
624 };
625 let mut inner = self.inner.lock().unwrap();
626 answer(&mut inner, p, phase, frame, result, handle);
627 }
628
629 fn poll(&self, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) -> bool {
632 let polling: Vec<Polling> = {
633 let mut inner = self.inner.lock().unwrap();
634 let (mine, rest) = std::mem::take(&mut inner.polling).into_iter().partition(|p| p.phase == phase);
635 inner.polling = rest;
636 mine
637 };
638 let mut still = false;
639 for mut entry in polling {
640 match (entry.poller)(ctx) {
641 None => {
642 still = true;
643 self.inner.lock().unwrap().polling.push(entry);
644 }
645 Some(result) => {
646 self.mark_layout_dirty();
648 let result = match &entry.bound {
649 Some(handle) => tag_context(&ctx.app.docs, handle, result),
650 None => result,
651 };
652 let mut inner = self.inner.lock().unwrap();
653 answer(&mut inner, entry.pending, phase, frame, result, entry.bound);
654 still |= !inner.polling.is_empty();
655 }
656 }
657 }
658 still
659 }
660
661 pub fn publish_view(&self, handle: &str, revision: u64) {
664 let mut inner = self.inner.lock().unwrap();
665 if inner.view.as_ref().is_none_or(|(h, r)| h != handle || *r != revision) {
666 inner.view = Some((handle.to_string(), revision));
667 }
668 }
669
670 pub fn fail_captures(&self, error: &str) {
673 let mut inner = self.inner.lock().unwrap();
674 let frame = inner.frame;
675 for a in std::mem::take(&mut inner.awaiting) {
676 let notices = inner.reply_notices();
677 let _ = a.pending.reply.send(Reply::err(a.pending.envelope.id, frame, error.to_string(), notices));
678 }
679 }
680
681 pub fn next_token(&self) -> u64 {
683 let mut inner = self.inner.lock().unwrap();
684 inner.next_token += 1;
685 inner.next_token
686 }
687}
688
689#[derive(serde::Deserialize)]
694#[serde(deny_unknown_fields, rename_all = "camelCase")]
695struct DocumentContext {
696 document_id: String,
697 expected_revision: String,
698}
699
700pub const ENGINE_ONLY: &[&str] = &[
706 "feature_stage",
707 "feature_stage_result",
708 "run_cancel",
709 "history_group_begin",
710 "history_group_end",
711 "feature_add_many",
712 "doc_import",
713 "doc_export",
714 "model_inspect",
715 "mass_properties",
716 "history_listing",
717 "frame_info",
718 "metadata_set",
719 "metadata_set_many",
720 "metadata_remove",
721];
722
723#[derive(Debug)]
726struct Bound {
727 handle: String,
728 route: Option<usize>,
729}
730
731fn bind_context(
742 docs: &crate::document::Documents,
743 phase: Phase,
744 cmd: &str,
745 mut args: serde_json::Value,
746) -> Result<(serde_json::Value, Option<Bound>), String> {
747 let Some(raw) = args.as_object_mut().and_then(|o| o.remove("context")) else {
748 return Ok((args, None));
749 };
750 let context: DocumentContext = serde_json::from_value(raw)
752 .map_err(|e| format!("invalid_arguments: context must be {{documentId, expectedRevision}}: {e}"))?;
753 let expected = parse_revision(&context.expected_revision)?;
754 match crate::handles::parse("doc", &context.document_id) {
755 crate::handles::Parsed::Current => {}
756 crate::handles::Parsed::OtherEpoch => {
757 return Err("handle_epoch_mismatch: the document handle is from another run of the app".into())
758 }
759 crate::handles::Parsed::Malformed => return Err("invalid_arguments: documentId is not a document handle".into()),
760 }
761 let Some(index) = docs.index_of_handle(&context.document_id) else {
762 return Err("document_unknown: no open document has that handle (closed, or never opened)".into());
763 };
764 if docs.work_part_in_place() {
765 return Err("document_busy: a Work part is edited in place; a document command would write the part".into());
766 }
767 let route = if index == docs.active_index() {
768 None
769 } else if ENGINE_ONLY.contains(&cmd) {
770 Some(index)
771 } else {
772 return Err("document_not_active: this command acts on the visible document; activate the named one first".into());
773 };
774 let current = docs.get(index).map_or(0, |d| d.committed_revision());
775 if phase == Phase::Mutate && current != expected {
776 return Err(format!(
777 "revision_conflict: the document is at revision {current}, not {expected}; read it again before writing"
778 ));
779 }
780 Ok((args, Some(Bound { handle: context.document_id, route })))
781}
782
783fn parse_revision(text: &str) -> Result<u64, String> {
785 let canonical = text == "0" || (!text.is_empty() && !text.starts_with('0') && text.bytes().all(|b| b.is_ascii_digit()));
786 text.parse::<u64>()
787 .ok()
788 .filter(|_| canonical)
789 .ok_or_else(|| "invalid_arguments: expectedRevision must be a canonical unsigned decimal string".into())
790}
791
792fn tag_context(
798 docs: &crate::document::Documents,
799 handle: &str,
800 result: Result<Outcome, String>,
801) -> Result<Outcome, String> {
802 let context = docs.index_of_handle(handle).and_then(|i| docs.get(i)).map(|doc| {
803 serde_json::json!({ "documentId": handle, "expectedRevision": doc.committed_revision().to_string() })
804 });
805 let tag = |v: &mut serde_json::Value| {
806 if let (Some(object), Some(context)) = (v.as_object_mut(), context.clone()) {
807 object.insert("context".into(), context);
808 }
809 };
810 match result {
811 Ok(Outcome::Done(mut v)) => {
812 tag(&mut v);
813 Ok(Outcome::Done(v))
814 }
815 Ok(Outcome::Blob { mut json, bytes }) => {
816 tag(&mut json);
817 Ok(Outcome::Blob { json, bytes })
818 }
819 other => other,
820 }
821}
822
823fn answer(inner: &mut Inner, p: Pending, phase: Phase, frame: u64, result: Result<Outcome, String>, bound: Option<String>) {
825 match result {
826 Ok(Outcome::Done(v)) => {
827 let notices = inner.reply_notices();
828 let _ = p.reply.send(Reply::ok(p.envelope.id, frame, v, notices));
829 }
830 Ok(Outcome::Blob { json, bytes }) => {
831 let notices = inner.reply_notices();
832 let mut r = Reply::ok(p.envelope.id, frame, json, notices);
833 r.blob = Some(bytes);
834 let _ = p.reply.send(r);
835 }
836 Ok(Outcome::AwaitScreenshot { token, region, document }) => {
839 inner.awaiting.push(Awaiting { token, region, document, pending: p });
840 }
841 Ok(Outcome::Poll(poller)) => inner.polling.push(Polling { pending: p, phase, poller, bound }),
842 Err(e) => {
843 let notices = inner.reply_notices();
844 let _ = p.reply.send(Reply::err(p.envelope.id, frame, e, notices));
845 }
846 }
847}
848
849fn refused_counts(docs: &crate::document::Documents) -> Vec<(u64, u64)> {
851 docs.iter().map(|d| (d.id(), d.engine.history.refused_user_edits())).collect()
852}
853
854fn refused_by_lock(
860 docs: &crate::document::Documents,
861 before: &[(u64, u64)],
862 result: Result<Outcome, String>,
863) -> Result<Outcome, String> {
864 if result.is_err() {
865 return result;
866 }
867 for doc in docs.iter() {
868 let was = before.iter().find(|(id, _)| *id == doc.id()).map(|(_, n)| *n);
869 if was.is_some_and(|was| doc.engine.history.refused_user_edits() > was) {
870 if let crate::document::Access::ReadOnly { reason } = doc.access() {
871 return Err(format!("{} is read-only: {reason}", doc.title()));
872 }
873 }
874 }
875 result
876}
877