1use crate::{
4 auth,
5 db::{self, Db, State},
6 model::{Lifecycle, User},
7 scripting, Error,
8};
9use serde::{Deserialize, Serialize};
10use serde_json::{json, Map, Value};
11use std::collections::{BTreeMap, BTreeSet};
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
14#[serde(default, deny_unknown_fields)]
15pub struct Field {
16 pub key: String,
17 pub label: String,
18 pub kind: String,
19 pub choices: Vec<String>,
20 pub required_at: Vec<String>,
21 pub readers: Vec<String>,
22 pub writers: Vec<String>,
23}
24impl Default for Field {
25 fn default() -> Self {
26 Self {
27 key: String::new(),
28 label: String::new(),
29 kind: "text".into(),
30 choices: vec![],
31 required_at: vec![],
32 readers: vec!["*".into()],
33 writers: vec!["initiator".into()],
34 }
35 }
36}
37#[derive(Debug, Clone, Serialize, Deserialize)]
38#[serde(default, deny_unknown_fields)]
39pub struct Node {
40 pub id: String,
41 pub label: String,
42 pub kind: String,
43 pub x: f64,
44 pub y: f64,
45 pub assignees: Vec<String>,
46 pub approvals: usize,
48 pub allow_self_review: bool,
49 pub code: String,
50 pub status: Option<Lifecycle>,
51}
52impl Default for Node {
53 fn default() -> Self {
54 Self {
55 id: String::new(),
56 label: String::new(),
57 kind: "form".into(),
58 x: 0.,
59 y: 0.,
60 assignees: vec![],
61 approvals: 0,
62 allow_self_review: false,
63 code: String::new(),
64 status: None,
65 }
66 }
67}
68#[derive(Debug, Clone, Serialize, Deserialize)]
69#[serde(deny_unknown_fields)]
70pub struct Edge {
71 pub from: String,
72 pub to: String,
73 #[serde(default = "always")]
74 pub on: String,
75}
76fn always() -> String {
77 "always".into()
78}
79#[derive(Debug, Clone, Default, Serialize, Deserialize)]
80#[serde(default, deny_unknown_fields)]
81pub struct Definition {
82 pub id: String,
83 pub name: String,
84 pub description: String,
85 pub active: bool,
86 pub require_for_release: bool,
87 pub part_types: Vec<String>,
88 pub start_groups: Vec<String>,
89 pub fields: Vec<Field>,
90 pub nodes: Vec<Node>,
91 pub edges: Vec<Edge>,
92 pub version: u64,
93 pub updated_by: String,
94 pub updated_at: u64,
95}
96#[derive(Debug, Clone, Serialize, Deserialize)]
97pub struct Decision {
98 pub user_id: String,
99 pub username: String,
100 pub outcome: String,
101 pub comment: String,
102 pub at: u64,
103}
104#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct Step {
106 pub state: String,
107 pub outcome: String,
108 pub assignees: Vec<String>,
109 pub decisions: Vec<Decision>,
110 pub attempt: u64,
111}
112impl Default for Step {
113 fn default() -> Self {
114 Self {
115 state: "pending".into(),
116 outcome: String::new(),
117 assignees: vec![],
118 decisions: vec![],
119 attempt: 0,
120 }
121 }
122}
123#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct Event {
125 pub at: u64,
126 pub node: String,
127 pub action: String,
128 pub user_id: String,
129 pub username: String,
130 pub message: String,
131}
132#[derive(Debug, Clone, Serialize, Deserialize)]
133pub struct Run {
134 pub id: String,
135 pub title: String,
136 pub definition: Definition,
137 pub state: String,
138 pub part: String,
139 pub revision: String,
140 pub model_hash: String,
141 pub initiator: String,
142 pub initiator_name: String,
143 pub created_at: u64,
144 pub fields: Map<String, Value>,
145 pub steps: BTreeMap<String, Step>,
146 pub log: Vec<Event>,
147}
148fn event(run: &mut Run, node: &str, action: &str, user: &User, message: impl Into<String>) {
149 run.log.push(Event {
150 at: db::now(),
151 node: node.into(),
152 action: action.into(),
153 user_id: user.id.clone(),
154 username: user.username.clone(),
155 message: message.into(),
156 });
157}
158fn terminal(step: &Step) -> bool {
159 matches!(step.state.as_str(), "done" | "skipped")
160}
161fn selected(edge: &Edge, step: &Step) -> bool {
162 step.state == "done" && (edge.on == "always" || edge.on == step.outcome)
163}
164fn matches_user(selectors: &[String], user: &User, initiator: &str, assignees: &[String]) -> bool {
165 selectors.iter().any(|s| {
166 s == "*"
167 || s == &format!("user:{}", user.id)
168 || s == &format!("user:{}", user.username)
169 || (s == "initiator" && user.id == initiator)
170 || (s == "assignee" && assignees.contains(&user.id))
171 || s.strip_prefix("group:")
172 .is_some_and(|g| user.groups.iter().any(|s| s == g))
173 })
174}
175fn visible(run: &Run, user: &User) -> bool {
176 user.is_admin()
177 || run.initiator == user.id
178 || run.steps.values().any(|s| s.assignees.contains(&user.id))
179}
180fn field_allowed(field: &Field, run: &Run, user: &User, write: bool, assignees: &[String]) -> bool {
181 user.is_admin()
182 || matches_user(
183 if write {
184 &field.writers
185 } else {
186 &field.readers
187 },
188 user,
189 &run.initiator,
190 assignees,
191 )
192}
193fn check_value(field: &Field, value: &Value) -> Result<(), Error> {
194 if value.is_null() {
195 return Ok(());
196 }
197 let valid = match field.kind.as_str() {
198 "text" | "textarea" => value.as_str().is_some_and(|s| s.len() <= 20000),
199 "number" => value.as_f64().is_some_and(f64::is_finite),
200 "boolean" => value.is_boolean(),
201 "choice" => value
202 .as_str()
203 .is_some_and(|s| field.choices.iter().any(|c| c == s)),
204 _ => false,
205 };
206 if valid {
207 Ok(())
208 } else {
209 Err(Error::bad_request(format!(
210 "invalid value for {}",
211 field.label
212 )))
213 }
214}
215fn fields_patch(
216 run: &mut Run,
217 user: &User,
218 node: &str,
219 patch: &Map<String, Value>,
220 trusted: bool,
221) -> Result<(), Error> {
222 let assignees = run
223 .steps
224 .get(node)
225 .map(|s| s.assignees.clone())
226 .unwrap_or_default();
227 for (key, value) in patch {
228 let field = run
229 .definition
230 .fields
231 .iter()
232 .find(|f| &f.key == key)
233 .ok_or_else(|| Error::bad_request(format!("unknown workflow field {key}")))?;
234 if !trusted
235 && (!field_allowed(field, run, user, true, &assignees)
236 || !field_allowed(field, run, user, false, &assignees))
237 {
238 return Err(Error::forbidden(format!(
239 "you cannot edit workflow field {key}"
240 )));
241 }
242 check_value(field, value)?;
243 }
244 for (key, value) in patch {
245 run.fields.insert(key.clone(), value.clone());
246 }
247 Ok(())
248}
249fn required(run: &Run, node: &str) -> Result<(), Error> {
250 for field in run
251 .definition
252 .fields
253 .iter()
254 .filter(|f| f.required_at.iter().any(|n| n == node))
255 {
256 if run
257 .fields
258 .get(&field.key)
259 .is_none_or(|v| v.is_null() || v.as_str().is_some_and(|s| s.trim().is_empty()))
260 {
261 return Err(Error::bad_request(format!(
262 "{} is required at this step",
263 field.label
264 )));
265 }
266 }
267 Ok(())
268}
269fn identifier(id: &str) -> bool {
270 !id.is_empty()
271 && id.len() <= 80
272 && id
273 .chars()
274 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
275}
276fn check_selectors(state: &State, selectors: &[String], special: bool) -> Result<(), Error> {
277 for selector in selectors {
278 if special && matches!(selector.as_str(), "*" | "initiator" | "assignee") {
279 continue;
280 }
281 if let Some(id) = selector.strip_prefix("user:") {
282 if state.users.iter().any(|u| u.id == id || u.username == id) {
283 continue;
284 }
285 }
286 if selector
287 .strip_prefix("group:")
288 .is_some_and(|g| !g.trim().is_empty())
289 {
290 continue;
291 }
292 if selector == "initiator" {
293 continue;
294 }
295 return Err(Error::bad_request(format!(
296 "invalid workflow selector {selector}"
297 )));
298 }
299 Ok(())
300}
301fn validate(state: &State, definition: &Definition) -> Result<(), Error> {
302 if definition.name.trim().is_empty()
303 || definition.name.len() > 200
304 || definition.nodes.len() > 100
305 || definition.edges.len() > 300
306 || definition.fields.len() > 100
307 {
308 return Err(Error::bad_request(
309 "workflow needs a name; maximum 100 nodes, 300 paths and 100 fields",
310 ));
311 }
312 for kind in &definition.part_types {
313 if state.part_type(kind).is_none() {
314 return Err(Error::bad_request("unknown workflow part type"));
315 }
316 }
317 check_selectors(state, &definition.start_groups, true)?;
318 let mut ids = BTreeSet::new();
319 for node in &definition.nodes {
320 if !identifier(&node.id)
321 || !ids.insert(node.id.clone())
322 || node.label.trim().is_empty()
323 || !node.x.is_finite()
324 || !node.y.is_finite()
325 || node.x.abs() > 100000.
326 || node.y.abs() > 100000.
327 {
328 return Err(Error::bad_request(
329 "nodes need unique IDs, labels and finite positions",
330 ));
331 }
332 if !matches!(
333 node.kind.as_str(),
334 "start" | "end" | "form" | "review" | "decision" | "script" | "check" | "decision-script" | "status" | "fork" | "join"
335 ) {
336 return Err(Error::bad_request("unknown workflow node kind"));
337 }
338 if matches!(node.kind.as_str(), "form" | "review" | "decision") && node.assignees.is_empty() {
339 return Err(Error::bad_request("human steps need assignees"));
340 }
341 check_selectors(state, &node.assignees, false)?;
342 if matches!(node.kind.as_str(), "script" | "check" | "decision-script")
343 && (node.code.trim().is_empty() || node.code.len() > 64000)
344 {
345 return Err(Error::bad_request(
346 "script steps need JavaScript (maximum 64 KB)",
347 ));
348 }
349 if node.kind == "status"
350 && (node.status.is_none() || node.status == Some(Lifecycle::Superseded))
351 {
352 return Err(Error::bad_request(
353 "choose a lifecycle status for the status step",
354 ));
355 }
356 }
357 let starts: Vec<_> = definition
358 .nodes
359 .iter()
360 .filter(|n| n.kind == "start")
361 .collect();
362 if starts.len() != 1 || !definition.nodes.iter().any(|n| n.kind == "end") {
363 return Err(Error::bad_request(
364 "workflow needs one Start and at least one End",
365 ));
366 }
367 let mut links = BTreeSet::new();
368 for edge in &definition.edges {
369 if !ids.contains(&edge.from)
370 || !ids.contains(&edge.to)
371 || edge.from == edge.to
372 || edge.on.trim().is_empty()
373 || edge.on.len() > 80
374 || !links.insert((&edge.from, &edge.to, &edge.on))
375 {
376 return Err(Error::bad_request(
377 "paths need valid, distinct nodes and outcome names",
378 ));
379 }
380 }
381 for node in &definition.nodes {
382 if node.kind == "start" && definition.edges.iter().any(|e| e.to == node.id) {
383 return Err(Error::bad_request("Start cannot have incoming paths"));
384 }
385 if node.kind == "end" && definition.edges.iter().any(|e| e.from == node.id) {
386 return Err(Error::bad_request("End cannot have outgoing paths"));
387 }
388 if node.kind != "end" && !definition.edges.iter().any(|e| e.from == node.id) {
389 return Err(Error::bad_request(
390 "each non-End step needs an outgoing path",
391 ));
392 }
393 }
394 for node in definition.nodes.iter().filter(|n| matches!(n.kind.as_str(), "decision" | "decision-script")) {
395 let paths: Vec<_> = definition.edges.iter().filter(|e| e.from == node.id).collect();
396 let outcomes: BTreeSet<_> = paths.iter().map(|e| e.on.as_str()).collect();
397 if paths.len() < 2 || paths.len() != outcomes.len() || outcomes.contains("always") {
398 return Err(Error::bad_request("decisions need at least two uniquely named outgoing paths; always is not a decision outcome"));
399 }
400 }
401 let mut seen = BTreeSet::new();
403 for _ in 0..definition.nodes.len() {
404 for node in &definition.nodes {
405 if (node.id == starts[0].id || definition.edges.iter().any(|e| e.to == node.id))
406 && definition
407 .edges
408 .iter()
409 .filter(|e| e.to == node.id)
410 .all(|e| seen.contains(&e.from))
411 {
412 seen.insert(node.id.clone());
413 }
414 }
415 }
416 if seen.len() != ids.len() {
417 return Err(Error::bad_request(
418 "all steps must connect to Start, without cycles",
419 ));
420 }
421 let mut keys = BTreeSet::new();
422 for field in &definition.fields {
423 if !identifier(&field.key)
424 || !keys.insert(&field.key)
425 || field.label.trim().is_empty()
426 || !matches!(
427 field.kind.as_str(),
428 "text" | "textarea" | "number" | "boolean" | "choice"
429 )
430 {
431 return Err(Error::bad_request(
432 "fields need unique keys, labels and a supported type",
433 ));
434 }
435 if field.kind == "choice" && field.choices.is_empty() {
436 return Err(Error::bad_request("choice fields need options"));
437 }
438 for node in &field.required_at {
439 if node != "start" && !ids.contains(node) {
440 return Err(Error::bad_request(
441 "required fields must name a workflow step or start",
442 ));
443 }
444 }
445 check_selectors(state, &field.readers, true)?;
446 check_selectors(state, &field.writers, true)?;
447 }
448 Ok(())
449}
450impl Db {
451 pub fn save_workflow(
452 &self,
453 user: &User,
454 mut definition: Definition,
455 ) -> Result<Definition, Error> {
456 if !user.is_admin() {
457 return Err(Error::forbidden("workflow editing needs admin"));
458 }
459 if definition.id.is_empty() {
460 definition.id = auth::new_id();
461 }
462 definition.name = definition.name.trim().into();
463 self.mutate(|state| {
464 validate(state,&definition)?;
465 if self.security().config.lock_script_editor || !state.settings.script_editor_enabled {
466 let previous=state.workflows.iter().find(|d|d.id==definition.id);
467 for node in definition.nodes.iter().filter(|n|matches!(n.kind.as_str(),"script"|"check"|"decision-script")) {
468 if !previous.is_some_and(|d|d.nodes.iter().any(|n|n.id==node.id && n.code==node.code && matches!(n.kind.as_str(),"script"|"check"|"decision-script"))) {
469 return Err(Error::forbidden("workflow JavaScript editing is disabled by server script-editor policy"));
470 }
471 }
472 }
473 if let Some(old)=state.workflows.iter().find(|d|d.id==definition.id) {
474 if definition.version!=old.version{return Err(Error::conflict("workflow changed; reload before saving"));}
475 } else if definition.version!=0 {return Err(Error::conflict("workflow version does not exist"));}
476 definition.version+=1;definition.updated_by=user.id.clone();definition.updated_at=db::now();
477 state.workflows.retain(|d|d.id!=definition.id);state.workflows.push(definition.clone());Ok(definition)
478 })
479 }
480 pub fn start_workflow(
481 &self,
482 user: &User,
483 key: &str,
484 title: &str,
485 part: &str,
486 revision: &str,
487 fields: Map<String, Value>,
488 ) -> Result<String, Error> {
489 if title.len() > 200 {
490 return Err(Error::bad_request("workflow title is too long"));
491 }
492 let id = auth::new_id();
493 self.mutate(|state| {
494 let definition = state
495 .workflows
496 .iter()
497 .find(|d| d.id == key && d.active)
498 .cloned()
499 .ok_or_else(|| Error::not_found("active workflow"))?;
500 if !user.is_admin()
501 && if definition.start_groups.is_empty() {
502 !user.can_author()
503 } else {
504 !matches_user(&definition.start_groups, user, &user.id, &[])
505 }
506 {
507 return Err(Error::forbidden("you cannot start this workflow"));
508 }
509 let mut part_id = String::new();
510 let mut rev_id = String::new();
511 let mut model_hash = String::new();
512 if !part.is_empty() {
513 let part = state
514 .part_by_id_or_number(part)
515 .ok_or_else(|| Error::not_found("workflow part"))?;
516 if !definition.part_types.is_empty()
517 && !definition.part_types.contains(&part.part_type)
518 {
519 return Err(Error::forbidden(
520 "workflow is not available for this part type",
521 ));
522 }
523 let revision = if revision.is_empty() {
524 part.latest()
525 } else {
526 part.revision(revision)
527 }
528 .ok_or_else(|| Error::not_found("workflow revision"))?;
529 part_id = part.id.clone();
530 rev_id = revision.id.clone();
531 model_hash = revision.content_hash.clone();
532 } else if !definition.part_types.is_empty()
533 || definition.nodes.iter().any(|n| n.kind == "status")
534 {
535 return Err(Error::bad_request(
536 "this workflow requires a part and revision",
537 ));
538 }
539 let mut run = Run {
540 id: id.clone(),
541 title: if title.trim().is_empty() {
542 definition.name.clone()
543 } else {
544 title.trim().into()
545 },
546 definition,
547 state: "active".into(),
548 part: part_id,
549 revision: rev_id,
550 model_hash,
551 initiator: user.id.clone(),
552 initiator_name: user.username.clone(),
553 created_at: db::now(),
554 fields: Map::new(),
555 steps: BTreeMap::new(),
556 log: vec![],
557 };
558 for node in &run.definition.nodes {
559 let assignees: Vec<_> = state
560 .users
561 .iter()
562 .filter(|u| {
563 u.active
564 && matches_user(&node.assignees, u, &run.initiator, &[])
565 && (node.kind != "review"
566 || node.allow_self_review
567 || u.id != run.initiator)
568 })
569 .map(|u| u.id.clone())
570 .collect();
571 if matches!(node.kind.as_str(), "form" | "review" | "decision")
572 && (assignees.is_empty() || node.approvals > assignees.len())
573 {
574 return Err(Error::bad_request(format!(
575 "{} needs eligible assignees (self-review is disabled unless configured)",
576 node.label
577 )));
578 }
579 run.steps.insert(
580 node.id.clone(),
581 Step {
582 assignees,
583 ..Step::default()
584 },
585 );
586 }
587 fields_patch(&mut run, user, "start", &fields, false)?;
588 required(&run, "start")?;
589 let version = run.definition.version;
590 event(
591 &mut run,
592 "",
593 "started",
594 user,
595 format!("Workflow version {version}"),
596 );
597 state.workflow_runs.push(run);
598 Ok(())
599 })?;
600 self.drive_workflow(&id)?;
601 Ok(id)
602 }
603 pub fn workflow_view(&self, user: &User, id: &str) -> Result<Value, Error> {
605 self.read(|state| {
606 let run = state
607 .workflow_runs
608 .iter()
609 .find(|r| r.id == id)
610 .ok_or_else(|| Error::not_found("workflow run"))?;
611 if !visible(run, user) {
612 return Err(Error::forbidden("this workflow is not assigned to you"));
613 }
614 let assignees: Vec<_> = run
615 .steps
616 .values()
617 .flat_map(|s| s.assignees.clone())
618 .collect();
619 let mut output = serde_json::to_value(run).map_err(Error::internal)?;
620 let readable: BTreeSet<_> = run
621 .definition
622 .fields
623 .iter()
624 .filter(|f| field_allowed(f, run, user, false, &assignees))
625 .map(|f| f.key.clone())
626 .collect();
627 output["fields"]
628 .as_object_mut()
629 .unwrap()
630 .retain(|k, _| readable.contains(k));
631 output["definition"]["fields"]
632 .as_array_mut()
633 .unwrap()
634 .retain(|f| readable.contains(f["key"].as_str().unwrap_or("")));
635 for field in output["definition"]["fields"].as_array_mut().unwrap() {
636 let f = run
637 .definition
638 .fields
639 .iter()
640 .find(|f| f.key == field["key"])
641 .unwrap();
642 field["can_edit"] = json!(field_allowed(f, run, user, true, &assignees));
643 }
644 for node in output["definition"]["nodes"].as_array_mut().unwrap() {
645 node.as_object_mut().unwrap().remove("code");
646 }
647 if !user.is_admin() {
648 for entry in output["log"].as_array_mut().unwrap() {
649 if matches!(entry["action"].as_str(), Some("failed" | "script_log")) {
650 entry["message"] =
651 json!("Automation detail is available to administrators.");
652 }
653 }
654 }
655 Ok(output)
656 })
657 }
658 pub fn workflow_action(
659 &self,
660 user: &User,
661 id: &str,
662 node_id: &str,
663 outcome: &str,
664 comment: &str,
665 fields: Map<String, Value>,
666 ) -> Result<(), Error> {
667 if comment.len() > 20000 {
668 return Err(Error::bad_request("comment is too long"));
669 }
670 self.mutate(|state| {
671 let current = state
672 .workflow_runs
673 .iter()
674 .find(|r| r.id == id)
675 .ok_or_else(|| Error::not_found("workflow run"))?;
676 if current
677 .definition
678 .nodes
679 .iter()
680 .any(|n| n.id == node_id && n.kind == "review")
681 && !current.part.is_empty()
682 && state
683 .part(¤t.part)
684 .and_then(|p| p.revision(¤t.revision))
685 .is_none_or(|r| r.content_hash != current.model_hash)
686 {
687 return Err(Error::conflict(
688 "the model changed; start a new workflow to review its current content",
689 ));
690 }
691 let run = state.workflow_runs.iter_mut().find(|r| r.id == id).unwrap();
692 if run.state != "active" {
693 return Err(Error::conflict("workflow is not active"));
694 }
695 let node = run
696 .definition
697 .nodes
698 .iter()
699 .find(|n| n.id == node_id)
700 .cloned()
701 .ok_or_else(|| Error::not_found("workflow step"))?;
702 if node.kind == "decision" {
703 if !run.definition.edges.iter().any(|e| e.from == node_id && e.on == outcome) {
704 return Err(Error::bad_request("choose one of this decision's outgoing paths"));
705 }
706 } else if !matches!(node.kind.as_str(), "form" | "review") || !matches!(outcome, "success" | "reject") {
707 return Err(Error::bad_request("choose success or reject for a human form or review step"));
708 }
709 let step = run.steps.get(node_id).unwrap();
710 if step.state != "waiting" || !step.assignees.contains(&user.id) {
711 return Err(Error::forbidden("this step is not waiting on you"));
712 }
713 if step.decisions.iter().any(|d| d.user_id == user.id) {
714 return Err(Error::conflict("you already completed this step"));
715 }
716 fields_patch(run, user, node_id, &fields, false)?;
717 if outcome == "success" || node.kind == "decision" {
718 required(run, node_id)?;
719 }
720 let step = run.steps.get_mut(node_id).unwrap();
721 step.decisions.push(Decision {
722 user_id: user.id.clone(),
723 username: user.username.clone(),
724 outcome: outcome.into(),
725 comment: comment.into(),
726 at: db::now(),
727 });
728 let threshold = if node.kind == "review" {
729 if node.approvals == 0 {
730 step.assignees.len()
731 } else {
732 node.approvals
733 }
734 } else {
735 1
736 };
737 if node.kind == "decision" || outcome == "reject"
738 || step
739 .decisions
740 .iter()
741 .filter(|d| d.outcome == "success")
742 .count()
743 >= threshold
744 {
745 step.state = "done".into();
746 step.outcome = outcome.into();
747 }
748 event(
749 run,
750 node_id,
751 if node.kind == "decision" {
752 "path_chosen_by_user"
753 } else if outcome == "success" {
754 "completed_by_user"
755 } else {
756 "rejected_by_user"
757 },
758 user,
759 comment,
760 );
761 if !fields.is_empty() {
762 event(
763 run,
764 node_id,
765 "fields_updated",
766 user,
767 fields.keys().cloned().collect::<Vec<_>>().join(", "),
768 );
769 }
770 Ok(())
771 })?;
772 self.drive_workflow(id)
773 }
774 pub fn control_workflow(
775 &self,
776 user: &User,
777 id: &str,
778 action: &str,
779 node: &str,
780 ) -> Result<(), Error> {
781 self.mutate(|state| {
782 let run=state.workflow_runs.iter_mut().find(|r|r.id==id).ok_or_else(||Error::not_found("workflow run"))?;
783 if action=="cancel" {
784 if !user.is_admin() && user.id!=run.initiator{return Err(Error::forbidden("only the initiator or admin can cancel"));}
785 if matches!(run.state.as_str(),"completed"|"cancelled"|"rejected"){return Err(Error::conflict("workflow has ended"));}
786 if run.steps.values().any(|s|s.state=="running"){return Err(Error::conflict("an automatic step is executing; wait for its result before cancelling"));}
787 run.state="cancelled".into();event(run,"","cancelled",user,"");
788 } else if action=="retry" {
789 if !user.is_admin(){return Err(Error::forbidden("retry needs admin"));}
790 if matches!(run.state.as_str(),"completed"|"cancelled"|"rejected"){return Err(Error::conflict("workflow has ended"));}
791 let step=run.steps.get_mut(node).ok_or_else(||Error::not_found("workflow step"))?;
792 if step.state!="failed"{return Err(Error::conflict("only a failed step can be retried"));}
793 step.state="pending".into();run.state="active".into();event(run,node,"retry_requested",user,"Review any external side effects before retrying; scripts receive a stable idempotencyKey.");
794 } else {return Err(Error::bad_request("unknown workflow control action"));}
795 Ok(())
796 })?;
797 if action == "retry" {
798 self.drive_workflow(id)?;
799 }
800 Ok(())
801 }
802 pub fn drive_workflow(&self, id: &str) -> Result<(), Error> {
803 for _ in 0..101 {
806 let job=self.mutate(|state| {
807 let definition=state.workflow_runs.iter().find(|r|r.id==id).ok_or_else(||Error::not_found("workflow run"))?.definition.clone();
808 let executor=state.user(&definition.updated_by).filter(|u|u.is_admin()).cloned().ok_or_else(||Error::conflict("workflow owner must be an active administrator; update the definition for new runs"))?;
809 let names:BTreeMap<_,_>=state.users.iter().map(|u|(u.id.clone(),u.username.clone())).collect();
810 let run=state.workflow_runs.iter_mut().find(|r|r.id==id).unwrap();
811 if run.state!="active" {return Ok(None);}
812 for _ in 0..definition.nodes.len()+1 {
813 let mut changed=false;
814 for node in &definition.nodes {
815 if run.steps[&node.id].state!="pending"{continue;}
816 let incoming:Vec<_>=definition.edges.iter().filter(|e|e.to==node.id).collect();
817 if !incoming.iter().all(|e|terminal(&run.steps[&e.from])){continue;}
818 let reached=node.kind=="start" || if node.kind=="join" { !incoming.is_empty() && incoming.iter().all(|e|selected(e,&run.steps[&e.from])) } else { incoming.iter().any(|e|selected(e,&run.steps[&e.from])) };
819 if !reached {
820 run.steps.get_mut(&node.id).unwrap().state="skipped".into();
821 event(run,&node.id,"skipped",&executor,"No selected incoming path");changed=true;continue;
822 }
823 if matches!(node.kind.as_str(),"form"|"review"|"decision") {
824 run.steps.get_mut(&node.id).unwrap().state="waiting".into();
825 let assigned=run.steps[&node.id].assignees.iter().filter_map(|id|names.get(id)).cloned().collect::<Vec<_>>().join(", ");
826 event(run,&node.id,"assigned",&executor,assigned);changed=true;continue;
827 }
828 if let Err(error)=if matches!(node.kind.as_str(),"script"|"check"|"decision-script") {Ok(())}else{required(run,&node.id)} {
829 run.steps.get_mut(&node.id).unwrap().state="failed".into();run.state="blocked".into();
830 event(run,&node.id,"failed",&executor,error.to_string());return Ok(None);
831 }
832 if matches!(node.kind.as_str(),"start"|"end"|"fork"|"join") {
833 let outcome=if node.kind=="end" && incoming.iter().any(|e|selected(e,&run.steps[&e.from]) && run.steps[&e.from].outcome=="reject"){"reject"}else{"success"};
834 let step=run.steps.get_mut(&node.id).unwrap();step.state="done".into();step.outcome=outcome.into();
835 event(run,&node.id,"completed",&executor,outcome);changed=true;continue;
836 }
837 let step=run.steps.get_mut(&node.id).unwrap();step.state="running".into();step.attempt+=1;
838 event(run,&node.id,"dispatched",&executor,format!("Idempotency key {}:{}",run.id,node.id));
839 return Ok(Some((run.clone(),node.clone(),executor)));
840 }
841 if !changed{break;}
842 }
843 if run.steps.values().all(terminal) {
844 if !definition.nodes.iter().any(|n|n.kind=="end" && run.steps[&n.id].state=="done") {
845 run.state="blocked".into();event(run,"","failed",&executor,"No End was reached; check outcome paths.");
846 } else {
847 run.state=if definition.nodes.iter().any(|n|n.kind=="end" && run.steps[&n.id].outcome=="reject"){"rejected"}else{"completed"}.into();
848 event(run,"","finished",&executor,run.state.clone());
849 }
850 }
851 Ok(None)
852 })?;
853 let Some((snapshot, node, executor)) = job else {
854 return Ok(());
855 };
856 let result = self.execute_workflow_node(&snapshot, &node, &executor);
857 self.mutate(|state| {
858 let run = state
859 .workflow_runs
860 .iter_mut()
861 .find(|r| r.id == id)
862 .ok_or_else(|| Error::not_found("workflow run"))?;
863 if run.steps[&node.id].state != "running"
864 || run.steps[&node.id].attempt != snapshot.steps[&node.id].attempt
865 {
866 return Err(Error::conflict("workflow claim changed"));
867 }
868 match result {
869 Ok((outcome, fields, logs)) => {
870 let applied = fields_patch(run, &executor, &node.id, &fields, true)
871 .and_then(|_| required(run, &node.id));
872 if let Err(error) = applied {
873 run.steps.get_mut(&node.id).unwrap().state = "failed".into();
874 run.state = "blocked".into();
875 event(run, &node.id, "failed", &executor, error.to_string());
876 } else {
877 let step = run.steps.get_mut(&node.id).unwrap();
878 step.state = "done".into();
879 step.outcome = outcome.clone();
880 event(run, &node.id, "completed", &executor, outcome);
881 for line in logs {
882 event(run, &node.id, "script_log", &executor, line);
883 }
884 if !fields.is_empty() {
885 event(
886 run,
887 &node.id,
888 "fields_updated",
889 &executor,
890 fields.keys().cloned().collect::<Vec<_>>().join(", "),
891 );
892 }
893 }
894 }
895 Err(error) => {
896 run.steps.get_mut(&node.id).unwrap().state = "failed".into();
897 run.state = "blocked".into();
898 event(run, &node.id, "failed", &executor, error.to_string());
899 }
900 }
901 Ok(())
902 })?;
903 }
904 Err(Error::conflict("workflow dispatch limit reached"))
905 }
906 fn execute_workflow_node(
907 &self,
908 run: &Run,
909 node: &Node,
910 executor: &User,
911 ) -> Result<(String, Map<String, Value>, Vec<String>), Error> {
912 if node.kind == "status" {
913 let warnings = self.transition_workflow(
914 executor,
915 &run.part,
916 &run.revision,
917 node.status.unwrap(),
918 &run.model_hash,
919 &run.id,
920 )?;
921 return Ok(("success".into(), Map::new(), warnings));
922 }
923 let input = json!({"runId":run.id,"nodeId":node.id,"idempotencyKey":format!("{}:{}",run.id,node.id),"fields":run.fields,"partId":run.part,"revisionId":run.revision,"modelHash":run.model_hash,"initiator":run.initiator_name,"attempt":run.steps[&node.id].attempt});
924 match scripting::run_source(self, executor, &node.code, "workflow.js", "step", &input) {
925 scripting::HookResult::Returned(success) => {
926 if success.value == Value::Bool(false) && node.kind != "decision-script" {
927 return Ok(("reject".into(), Map::new(), success.logs));
928 }
929 if node.kind == "decision-script" && success.value.get("outcome").and_then(Value::as_str).is_none() {
930 return Err(Error::bad_request("decision script must return an explicit outcome naming an outgoing path"));
931 }
932 let outcome = success
933 .value
934 .get("outcome")
935 .and_then(Value::as_str)
936 .unwrap_or("success")
937 .to_string();
938 if outcome.trim().is_empty() || outcome.len() > 80 {
939 return Err(Error::bad_request(
940 "script outcome needs a nonempty name up to 80 bytes",
941 ));
942 }
943 if node.kind == "decision-script" && !run.definition.edges.iter().any(|e| e.from == node.id && e.on == outcome) {
944 return Err(Error::bad_request("decision script must return the name of an outgoing path in outcome"));
945 }
946 let fields = match success.value.get("fields") {
947 Some(Value::Object(map)) => map.clone(),
948 Some(_) => return Err(Error::bad_request("script fields must be an object")),
949 None => Map::new(),
950 };
951 Ok((outcome, fields, success.logs))
952 }
953 scripting::HookResult::Refused(failure) => Err(Error::conflict(failure.message)),
954 scripting::HookResult::Absent => {
955 Err(Error::conflict("workflow step function is missing"))
956 }
957 }
958 }
959 pub fn recover_workflows(&self) -> Result<(), Error> {
961 let interrupted = self.read(|s| {
962 s.workflow_runs
963 .iter()
964 .any(|r| r.steps.values().any(|step| step.state == "running"))
965 });
966 if interrupted {
967 self.mutate(|state| {
968 for run in &mut state.workflow_runs {
969 let nodes:Vec<_>=run.steps.iter().filter(|(_,s)|s.state=="running").map(|(id,_)|id.clone()).collect();
970 for id in nodes {
971 run.steps.get_mut(&id).unwrap().state="failed".into();run.state="blocked".into();
972 run.log.push(Event {at:db::now(),node:id,action:"interrupted".into(),user_id:String::new(),username:"server".into(),message:"Server stopped during dispatch; administrator must verify external effects before retrying.".into()});
973 }
974 }
975 Ok(())
976 })?;
977 }
978 let active = self.read(|s| {
979 s.workflow_runs
980 .iter()
981 .filter(|r| r.state == "active")
982 .map(|r| r.id.clone())
983 .collect::<Vec<_>>()
984 });
985 for id in active {
986 if let Err(error) = self.drive_workflow(&id) {
987 self.mutate(|state| {
988 let run = state.workflow_runs.iter_mut().find(|r| r.id == id).unwrap();
989 run.state = "blocked".into();
990 run.log.push(Event {
991 at: db::now(),
992 node: String::new(),
993 action: "failed".into(),
994 user_id: String::new(),
995 username: "server".into(),
996 message: error.to_string(),
997 });
998 Ok(())
999 })?;
1000 }
1001 }
1002 Ok(())
1003 }
1004}
1005
1006pub fn inbox(state: &State, user: &User) -> Vec<Value> {
1007 state.workflow_runs.iter().filter(|r|visible(r,user) && matches!(r.state.as_str(),"active"|"blocked")).flat_map(|run| {
1008 run.definition.nodes.iter().filter_map(|node| {
1009 let step=&run.steps[&node.id];
1010 let waiting=step.state=="waiting" && step.assignees.contains(&user.id) && !step.decisions.iter().any(|d|d.user_id==user.id);
1011 let failed=user.is_admin() && step.state=="failed";
1012 if !waiting && !failed {return None;}
1013 Some(json!({"kind":"workflow","target":run.id,"node":node.id,"title":run.title,"name":node.label,"state":step.state,"approvals":step.decisions.iter().filter(|d|d.outcome=="success").count(),"required_approvals":if node.kind!="review"{1}else if node.approvals==0{step.assignees.len()}else{node.approvals},"initiator":run.initiator,"due":0,"overdue":false}))
1014 }).collect::<Vec<_>>()
1015 }).collect()
1016}
1017pub fn definition_view(definition: &Definition, user: &User) -> Value {
1018 let mut output = serde_json::to_value(definition).unwrap();
1019 if !user.is_admin() {
1020 output["can_start"] = json!(if definition.start_groups.is_empty() {
1021 user.can_author()
1022 } else {
1023 matches_user(&definition.start_groups, user, &user.id, &[])
1024 });
1025 for node in output["nodes"].as_array_mut().unwrap() {
1026 node.as_object_mut().unwrap().remove("code");
1027 }
1028 output["fields"].as_array_mut().unwrap().retain(|f| {
1029 let field = definition
1030 .fields
1031 .iter()
1032 .find(|v| v.key == f["key"])
1033 .unwrap();
1034 matches_user(&field.readers, user, &user.id, &[])
1035 && matches_user(&field.writers, user, &user.id, &[])
1036 });
1037 }
1038 output
1039}
1040pub fn run_list(state: &State, user: &User) -> Vec<Value> {
1041 state.workflow_runs.iter().filter(|r|visible(r,user)).rev().map(|r|json!({"id":r.id,"title":r.title,"state":r.state,"part":r.part,"revision":r.revision,"workflow":r.definition.name,"version":r.definition.version,"initiator":r.initiator_name,"created_at":r.created_at})).collect()
1042}
1043
1044pub fn release_gate(
1046 state: &State,
1047 part_id: &str,
1048 revision_id: &str,
1049 run_id: Option<&str>,
1050) -> Result<(), Error> {
1051 let part = state
1052 .part(part_id)
1053 .ok_or_else(|| Error::not_found("part"))?;
1054 let applicable: Vec<_> = state
1055 .workflows
1056 .iter()
1057 .filter(|d| {
1058 d.active
1059 && d.require_for_release
1060 && (d.part_types.is_empty() || d.part_types.contains(&part.part_type))
1061 })
1062 .collect();
1063 if applicable.is_empty() {
1064 return Ok(());
1065 }
1066 let authorized = run_id
1067 .and_then(|id| state.workflow_runs.iter().find(|r| r.id == id))
1068 .is_some_and(|r| {
1069 r.state == "active"
1070 && r.part == part_id
1071 && r.revision == revision_id
1072 && applicable.iter().any(|d| d.id == r.definition.id)
1073 && r.definition.nodes.iter().any(|n| {
1074 n.kind == "status"
1075 && n.status == Some(Lifecycle::Released)
1076 && r.steps[&n.id].state == "running"
1077 })
1078 });
1079 if authorized {
1080 Ok(())
1081 } else {
1082 Err(Error::conflict(
1083 "this part type requires release through an approved workflow",
1084 ))
1085 }
1086}