1use std::collections::{HashMap, HashSet, VecDeque};
72use std::sync::Arc;
73
74use serde::Deserialize;
75
76use crate::dsl::ErrorStrategy;
77use crate::event::Event;
78use crate::graph::{FAIL_BRANCH, Graph, NodeIx};
79use crate::node::NodeRole;
80use crate::pool::{Selector, VariablePool};
81use crate::snapshot::{EdgeStatus, FrameSnapshot, NodeStatus};
82use crate::template::{Part, Template};
83use crate::value::Value;
84
85#[derive(Clone, Debug, PartialEq, Eq)]
87pub struct ResponseChunk {
88 pub node_id: Arc<str>,
92 pub text: String,
93 pub is_final: bool,
96}
97
98impl ResponseChunk {
99 fn text(node_id: &Arc<str>, text: String) -> Self {
100 Self { node_id: Arc::clone(node_id), text, is_final: false }
101 }
102
103 fn done(node_id: &Arc<str>) -> Self {
104 Self { node_id: Arc::clone(node_id), text: String::new(), is_final: true }
105 }
106}
107
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109enum Status {
110 Unknown,
111 Started,
112 Succeeded,
113 Handled,
115 Failed,
117 Skipped,
118}
119
120impl Status {
121 fn finished(self) -> bool {
122 matches!(self, Status::Succeeded | Status::Handled | Status::Failed | Status::Skipped)
123 }
124}
125
126#[derive(Debug)]
127struct Response {
128 node: NodeIx,
129 id: Arc<str>,
130 parts: Vec<Part>,
131 queued: bool,
132 done: bool,
133}
134
135#[derive(Debug, Default)]
136struct StreamBuf {
137 text: String,
138}
139
140type Streams = HashMap<Arc<str>, Vec<(Arc<str>, StreamBuf)>>;
142
143fn stream_buf<'a>(streams: &'a Streams, node: &str, field: &str) -> Option<&'a StreamBuf> {
144 streams.get(node)?.iter().find(|(f, _)| f.as_ref() == field).map(|(_, buf)| buf)
145}
146
147#[derive(Debug)]
148struct Active {
149 response: usize,
150 part: usize,
151 offset: usize,
153}
154
155#[derive(Deserialize)]
156struct EndOutput {
157 value_selector: Selector,
158}
159
160#[derive(Debug)]
162pub struct ResponseAssembler {
163 graph: Arc<Graph>,
164 responses: Vec<Response>,
165 status: Vec<Status>,
166 branch: Vec<Option<String>>,
167 deferred: Vec<bool>,
169 edge_state: Vec<Option<EdgeStatus>>,
171 rendered: Vec<bool>,
173 streams: Streams,
176 referenced: HashSet<Arc<str>>,
178 pool: VariablePool,
179 queue: VecDeque<usize>,
180 active: Option<Active>,
181 emitted: String,
182 segments: Vec<(usize, usize)>,
185 pass_through: bool,
186 include_end: bool,
187 finished: bool,
188 certain: Vec<bool>,
190 certain_valid: bool,
192 changed: Vec<NodeIx>,
194}
195
196impl ResponseAssembler {
197 pub fn new(graph: &Arc<Graph>) -> Self {
199 let mut this = Self {
200 graph: Arc::clone(graph),
201 responses: Vec::new(),
202 status: vec![Status::Unknown; graph.nodes().len()],
203 branch: vec![None; graph.nodes().len()],
204 deferred: graph
205 .nodes()
206 .iter()
207 .map(|n| n.policy.retry.max_retries > 0 || !matches!(n.policy.on_error, ErrorStrategy::Fail))
208 .collect(),
209 edge_state: vec![None; graph.edges().len()],
210 rendered: vec![false; graph.nodes().len()],
211 streams: Streams::new(),
212 referenced: HashSet::new(),
213 pool: VariablePool::new(),
214 queue: VecDeque::new(),
215 active: None,
216 emitted: String::new(),
217 segments: Vec::new(),
218 pass_through: false,
219 include_end: false,
220 finished: false,
221 certain: vec![false; graph.nodes().len()],
222 certain_valid: false,
223 changed: Vec::new(),
224 };
225 this.rebuild_responses();
226 this
227 }
228
229 pub fn pass_through_unreferenced(mut self, enabled: bool) -> Self {
231 self.pass_through = enabled;
232 self
233 }
234
235 pub fn include_end(mut self, enabled: bool) -> Self {
237 self.include_end = enabled;
238 self.rebuild_responses();
239 self
240 }
241
242 pub fn with_value(mut self, selector: &Selector, value: Value) -> Self {
244 self.pool.set(selector, value);
245 self
246 }
247
248 pub fn with_pool(mut self, pool: VariablePool) -> Self {
250 for (ns, name, value) in pool.iter() {
251 self.pool.insert(ns, name, value.clone());
252 }
253 self
254 }
255
256 pub fn resume_from(mut self, snapshot: &FrameSnapshot) -> Self {
266 let restored = VariablePool::from_snapshot(snapshot.pool.clone());
267 for (ns, name, value) in restored.iter() {
268 self.pool.insert(ns, name, value.clone());
269 }
270 for (ix, edge) in self.graph.edges().iter().enumerate() {
271 if let (Some(state), Some(slot)) = (snapshot.edges.get(edge.id.as_ref()), self.edge_state.get_mut(ix)) {
272 *slot = Some(*state);
273 }
274 }
275 for (node_id, node) in &snapshot.nodes {
276 let Some(ix) = self.root_node(node_id) else { continue };
277 let status = match node.status {
278 NodeStatus::Succeeded => Status::Succeeded,
279 NodeStatus::Skipped => Status::Skipped,
280 NodeStatus::Failed if self.has_taken_outgoing(ix) => Status::Handled,
281 NodeStatus::Failed => Status::Failed,
282 NodeStatus::Paused => Status::Started,
283 NodeStatus::Pending => Status::Unknown,
284 };
285 if let Some(slot) = self.status.get_mut(ix) {
286 *slot = status;
287 }
288 if let Some(slot) = self.rendered.get_mut(ix) {
289 *slot = status == Status::Succeeded;
290 }
291 }
292 self.certain_valid = false;
293 self.rebuild_responses();
294 self
295 }
296
297 fn has_taken_outgoing(&self, ix: NodeIx) -> bool {
298 self.graph.outgoing(ix).iter().any(|&ex| self.edge_state.get(ex).copied().flatten() == Some(EdgeStatus::Taken))
299 }
300
301 pub fn text_so_far(&self) -> &str {
303 &self.emitted
304 }
305
306 pub fn push(&mut self, event: &Event) -> Vec<ResponseChunk> {
308 let mut out = Vec::new();
309 self.push_into(event, &mut out);
310 out
311 }
312
313 pub fn push_into(&mut self, event: &Event, out: &mut Vec<ResponseChunk>) {
331 if self.finished {
332 return;
333 }
334 match event {
335 Event::NodeStarted { frame, node_id, .. } if frame.is_empty() => {
336 self.set_status(node_id, Status::Started);
337 }
338 Event::NodeChunk { frame, node_id, field, chunk, .. } => {
339 let buf = match self.streams.get_mut(node_id.as_ref()) {
340 Some(fields) if frame.is_empty() => fields.iter_mut().find(|(f, _)| f == field),
341 _ => None,
342 };
343 let buffered = match buf {
344 Some((_, buf)) => {
345 buf.text.push_str(chunk);
346 true
347 }
348 None => {
349 if self.pass_through && !chunk.is_empty() {
350 out.push(ResponseChunk::text(node_id, chunk.clone()));
351 }
352 false
353 }
354 };
355 if self.certain_valid {
356 if buffered {
358 self.drain(false, out);
359 }
360 return;
361 }
362 }
363 Event::NodeSucceeded { frame, node_id, outputs, branch, .. } if frame.is_empty() => {
364 if self.referenced.contains(node_id.as_ref()) {
365 self.pool.set_outputs(node_id, outputs);
366 }
367 if let Some(ix) = self.root_node(node_id)
368 && let Some(b) = self.branch.get_mut(ix)
369 {
370 b.clone_from(branch);
371 }
372 self.set_status(node_id, Status::Succeeded);
373 }
374 Event::NodeFailed { frame, node_id, handled, outputs, .. } if frame.is_empty() => {
375 if *handled && self.referenced.contains(node_id.as_ref()) {
376 self.pool.set_outputs(node_id, outputs);
377 }
378 self.set_status(node_id, if *handled { Status::Handled } else { Status::Failed });
379 }
380 Event::NodeSkipped { frame, node_id } if frame.is_empty() => {
381 self.set_status(node_id, Status::Skipped);
382 }
383 Event::NodeRetry { frame, node_id, .. } if frame.is_empty() => {
384 if let Some(fields) = self.streams.get_mut(node_id.as_ref()) {
386 fields.iter_mut().for_each(|(_, buf)| buf.text.clear());
387 }
388 return;
389 }
390 Event::RunSucceeded { .. } | Event::RunAborted { .. } => {
391 self.finish_into(out);
392 return;
393 }
394 Event::RunFailed { .. } => {
395 self.keep_text_of_nodes_that_ran();
397 self.finished = true;
398 return;
399 }
400 _ => return,
401 }
402 self.refresh_certainty();
403 self.drain(false, out);
404 }
405
406 pub fn finish(&mut self) -> Vec<ResponseChunk> {
409 let mut out = Vec::new();
410 self.finish_into(&mut out);
411 out
412 }
413
414 fn finish_into(&mut self, out: &mut Vec<ResponseChunk>) {
415 if self.finished {
416 return;
417 }
418 self.refresh_certainty();
419 self.drain(true, out);
420 self.finished = true;
421 }
422
423 fn keep_text_of_nodes_that_ran(&mut self) {
426 let mut kept = String::with_capacity(self.emitted.len());
427 let mut segments = Vec::with_capacity(self.segments.len());
428 let mut start = 0;
429 for &(response, len) in &self.segments {
430 let end = start + len;
431 let ran = self
432 .responses
433 .get(response)
434 .and_then(|r| self.status.get(r.node))
435 .is_some_and(|status| matches!(status, Status::Succeeded | Status::Handled));
436 if ran && let Some(text) = self.emitted.get(start..end) {
437 kept.push_str(text);
438 segments.push((response, len));
439 }
440 start = end;
441 }
442 self.emitted = kept;
443 self.segments = segments;
444 }
445
446 fn rebuild_responses(&mut self) {
447 let Some(scope) = self.graph.root_scope() else {
448 return;
449 };
450 let mut responses = Vec::new();
451 for &ix in &scope.nodes {
452 let Some(node) = self.graph.node(ix) else { continue };
453 if node.role != NodeRole::Response {
454 continue;
455 }
456 let parts = match &*node.kind {
457 "answer" => node
458 .doc
459 .config
460 .get("answer")
461 .and_then(serde_json::Value::as_str)
462 .map(|s| Template::parse(s).parts().to_vec())
463 .unwrap_or_default(),
464 "end" if self.include_end => end_parts(&node.doc.config),
465 _ => continue,
466 };
467 let rendered = self.rendered.get(ix).copied().unwrap_or(false);
468 responses.push(Response { node: ix, id: node.id.clone(), parts, queued: rendered, done: rendered });
469 }
470 let mut old = std::mem::take(&mut self.streams);
471 self.referenced.clear();
472 for sel in responses.iter().flat_map(|r| r.parts.iter()).filter_map(|p| match p {
473 Part::Var(sel) => Some(sel),
474 Part::Text(_) => None,
475 }) {
476 let node: Arc<str> = Arc::from(sel.namespace());
477 self.referenced.insert(Arc::clone(&node));
478 if !sel.path().is_empty() {
479 continue;
480 }
481 let fields = self.streams.entry(node).or_default();
482 if fields.iter().any(|(f, _)| f.as_ref() == sel.name()) {
483 continue;
484 }
485 let buf = old
487 .get_mut(sel.namespace())
488 .and_then(|v| v.iter_mut().find(|(f, _)| f.as_ref() == sel.name()))
489 .map(|(_, buf)| std::mem::take(buf))
490 .unwrap_or_default();
491 fields.push((Arc::from(sel.name()), buf));
492 }
493 self.responses = responses;
494 }
495
496 fn root_node(&self, id: &str) -> Option<NodeIx> {
497 self.graph.index_of(id).filter(|&ix| self.graph.node(ix).is_some_and(|n| n.parent.is_none()))
498 }
499
500 fn set_status(&mut self, node_id: &str, status: Status) {
501 if let Some(ix) = self.root_node(node_id)
502 && let Some(s) = self.status.get_mut(ix)
503 {
504 if !(s.finished() && status == Status::Started) {
506 if *s != status {
507 self.changed.push(ix);
508 }
509 *s = status;
510 }
511 }
512 }
513
514 fn status_of(&self, ix: NodeIx) -> Status {
515 self.status.get(ix).copied().unwrap_or(Status::Unknown)
516 }
517
518 fn compute_certain(&self, ix: NodeIx, entry: NodeIx, certain: &[bool]) -> bool {
520 match self.status_of(ix) {
521 Status::Skipped => false,
522 Status::Unknown => ix == entry || self.has_certain_edge(ix, certain),
523 _ => true,
524 }
525 }
526
527 fn refresh_certainty(&mut self) {
534 let Some(scope) = self.graph.root_scope() else {
535 return;
536 };
537 let entry = scope.entry;
538 let mut certain = std::mem::take(&mut self.certain);
539 certain.resize(self.graph.nodes().len(), false);
540 let mut work = std::mem::take(&mut self.changed);
542 let mut full = !self.certain_valid;
543 if !full {
544 while let Some(ix) = work.pop() {
545 let now = self.compute_certain(ix, entry, &certain);
546 let before = certain.get(ix).copied().unwrap_or(false);
547 if before && !now {
548 full = true;
549 break;
550 }
551 if now != before
552 && let Some(c) = certain.get_mut(ix)
553 {
554 *c = now;
555 }
556 if now {
559 for &ex in self.graph.outgoing(ix) {
560 if let Some(edge) = self.graph.edge(ex)
561 && !certain.get(edge.target).copied().unwrap_or(false)
562 && self.compute_certain(edge.target, entry, &certain)
563 {
564 if let Some(c) = certain.get_mut(edge.target) {
565 *c = true;
566 }
567 work.push(edge.target);
568 }
569 }
570 }
571 }
572 }
573 work.clear();
574 self.changed = work;
575 if full {
576 certain.iter_mut().for_each(|c| *c = false);
577 for &ix in &scope.nodes {
578 let is_certain = self.compute_certain(ix, entry, &certain);
579 if let Some(c) = certain.get_mut(ix) {
580 *c = is_certain;
581 }
582 }
583 }
584 for (i, r) in self.responses.iter_mut().enumerate() {
585 if !r.queued && certain.get(r.node).copied().unwrap_or(false) {
586 r.queued = true;
587 self.queue.push_back(i);
588 }
589 }
590 self.certain = certain;
591 self.certain_valid = true;
592 }
593
594 fn has_certain_edge(&self, ix: NodeIx, certain: &[bool]) -> bool {
596 self.graph.incoming(ix).iter().filter_map(|&ex| self.graph.edge(ex).map(|e| (ex, e))).any(|(ex, edge)| {
597 if !certain.get(edge.source).copied().unwrap_or(false) {
598 return false;
599 }
600 match self.edge_state.get(ex).copied().flatten() {
602 Some(EdgeStatus::Taken) => return true,
603 Some(EdgeStatus::Skipped) => return false,
604 Some(EdgeStatus::Unknown) | None => {}
605 }
606 let Some(src) = self.graph.node(edge.source) else { return false };
607 let status = self.status_of(edge.source);
608 let fail_branch = matches!(src.policy.on_error, ErrorStrategy::FailBranch);
609 match status {
610 Status::Failed | Status::Skipped => false,
611 Status::Handled if fail_branch => edge.handle.as_ref() == FAIL_BRANCH,
612 Status::Handled if src.role == NodeRole::Branch => {
613 default_branch(&src.policy.on_error).as_deref() == Some(edge.handle.as_ref())
614 }
615 Status::Handled => edge.handle.as_ref() != FAIL_BRANCH,
616 Status::Succeeded if src.role == NodeRole::Branch => {
617 self.branch.get(edge.source).and_then(Option::as_deref) == Some(edge.handle.as_ref())
618 }
619 _ if src.role == NodeRole::Branch => false,
620 _ if fail_branch => false,
622 _ => edge.handle.as_ref() != FAIL_BRANCH,
623 }
624 })
625 }
626
627 fn drain(&mut self, flush: bool, out: &mut Vec<ResponseChunk>) {
629 loop {
630 if self.active.is_none() {
631 match self.queue.pop_front() {
632 Some(response) => self.active = Some(Active { response, part: 0, offset: 0 }),
633 None => return,
634 }
635 }
636 let Some(active) = self.active.as_mut() else { return };
637 let Some(response) = self.responses.get(active.response) else {
638 self.active = None;
639 continue;
640 };
641 if self.status.get(response.node).copied() == Some(Status::Skipped) {
643 self.finish_active(None, out);
644 continue;
645 }
646 match response.parts.get(active.part) {
648 None => {
649 let id = Arc::clone(&response.id);
650 self.finish_active(Some(&id), out);
651 }
652 Some(Part::Text(text)) => {
653 let piece = Piece { response: active.response, id: &response.id };
654 emit(&mut self.emitted, &mut self.segments, out, &piece, text.clone());
655 active.part += 1;
656 active.offset = 0;
657 }
658 Some(Part::Var(sel)) => {
659 let sources = Sources {
660 graph: &self.graph,
661 status: &self.status,
662 deferred: &self.deferred,
663 streams: &self.streams,
664 pool: &self.pool,
665 };
666 let step = resolve_var(&sources, sel, active.offset, flush);
667 if !step.text.is_empty() {
668 let piece = Piece { response: active.response, id: &response.id };
669 emit(&mut self.emitted, &mut self.segments, out, &piece, step.text);
670 }
671 active.offset = step.offset;
672 if step.complete {
673 active.part += 1;
674 active.offset = 0;
675 } else {
676 return;
677 }
678 }
679 }
680 }
681 }
682
683 fn finish_active(&mut self, id: Option<&Arc<str>>, out: &mut Vec<ResponseChunk>) {
684 if let Some(active) = self.active.take() {
685 if let Some(r) = self.responses.get_mut(active.response) {
686 r.done = true;
687 }
688 if let Some(id) = id {
689 out.push(ResponseChunk::done(id));
690 }
691 }
692 }
693}
694
695struct Step {
696 text: String,
697 offset: usize,
698 complete: bool,
699}
700
701struct Sources<'a> {
703 graph: &'a Graph,
704 status: &'a [Status],
705 deferred: &'a [bool],
706 streams: &'a Streams,
707 pool: &'a VariablePool,
708}
709
710fn resolve_var(sources: &Sources<'_>, sel: &Selector, offset: usize, flush: bool) -> Step {
711 let Sources { graph, status, deferred, streams, pool } = *sources;
712 let node_ix = graph.index_of(sel.namespace()).filter(|&ix| graph.node(ix).is_some_and(|n| n.parent.is_none()));
713 let Some(ix) = node_ix else {
714 return Step { text: pool.get(sel).map(|v| v.to_text()).unwrap_or_default(), offset: 0, complete: true };
716 };
717 let node_status = status.get(ix).copied().unwrap_or(Status::Unknown);
718
719 let is_deferred = deferred.get(ix).copied().unwrap_or(false);
720 let buffered = if sel.path().is_empty() {
721 stream_buf(streams, sel.namespace(), sel.name()).filter(|b| !b.text.is_empty())
722 } else {
723 None
724 };
725
726 if is_deferred {
727 let text = match node_status {
729 Status::Succeeded => match buffered {
730 Some(buf) => buf.text.clone(),
731 None => pool.get(sel).map(|v| v.to_text()).unwrap_or_default(),
732 },
733 Status::Handled => pool.get(sel).map(|v| v.to_text()).unwrap_or_default(),
735 _ => String::new(),
736 };
737 return Step { text, offset: 0, complete: node_status.finished() || flush };
738 }
739
740 let mut text = String::new();
742 let mut new_offset = offset;
743 let streamed = buffered.is_some();
744 if let Some(buf) = buffered
745 && let Some(rest) = buf.text.get(offset..)
746 {
747 text.push_str(rest);
748 new_offset = buf.text.len();
749 }
750
751 let complete = match node_status {
752 Status::Skipped | Status::Failed => true,
753 Status::Succeeded | Status::Handled => {
754 if !streamed && let Some(v) = pool.get(sel) {
755 text.push_str(&v.to_text());
756 }
757 true
758 }
759 Status::Unknown | Status::Started => {
760 if flush
761 && !streamed
762 && let Some(v) = pool.get(sel)
763 {
764 text.push_str(&v.to_text());
765 }
766 flush
767 }
768 };
769 Step { text, offset: new_offset, complete }
770}
771
772fn default_branch(strategy: &ErrorStrategy) -> Option<String> {
774 match strategy {
775 ErrorStrategy::DefaultValue { values } => values.get("branch").and_then(Value::as_str).map(str::to_owned),
776 _ => None,
777 }
778}
779
780struct Piece<'a> {
782 response: usize,
784 id: &'a Arc<str>,
785}
786
787fn emit(
788 emitted: &mut String,
789 segments: &mut Vec<(usize, usize)>,
790 out: &mut Vec<ResponseChunk>,
791 piece: &Piece<'_>,
792 text: String,
793) {
794 if text.is_empty() {
795 return;
796 }
797 emitted.push_str(&text);
798 match segments.last_mut() {
799 Some((response, len)) if *response == piece.response => *len += text.len(),
800 _ => segments.push((piece.response, text.len())),
801 }
802 out.push(ResponseChunk::text(piece.id, text));
803}
804
805fn end_parts(config: &serde_json::Map<String, serde_json::Value>) -> Vec<Part> {
806 let outputs: Vec<EndOutput> = config
807 .get("outputs")
808 .cloned()
809 .and_then(|v| serde_json::from_value::<Vec<serde_json::Value>>(v).ok())
810 .unwrap_or_default()
811 .into_iter()
812 .filter_map(|v| serde_json::from_value(v).ok())
813 .collect();
814 let mut parts = Vec::with_capacity(outputs.len() * 2);
815 for (i, o) in outputs.into_iter().enumerate() {
816 if i > 0 {
817 parts.push(Part::Text("\n".to_owned()));
818 }
819 parts.push(Part::Var(o.value_selector));
820 }
821 parts
822}