mod.rs
cdk-rsx/crates/cdk-rsx-takt/src/inspector/mod.rs
1//! Read-only, authenticated inspection. Profiles do not contain business-service2//! capabilities and may be constructed in query scopes.3mod wire;4use crate::{5 EngineView, Failure, NodeSnapshot, PayloadContract, Phase, Snapshot, Status as EngineStatus,6};7use crate::{PayloadSize, Result};8use cdk_rsx::Principal;9use cdk_rsx::wire::{Int, Nat};10use cdk_rsx_store::Access;11pub use wire::*;1213pub trait Profile<D, E> {14 const ID: &'static str;15 const VERSION: u32;16 /// Exact executable identity, emitted with the generated graph. Handwritten17 /// local KEEP profiles can return their namespace-bound identity instead.18 const SIGNATURE: Option<[u8; 32]> = None;19 fn definition_signature(&self, _namespace: u64) -> Option<[u8; 32]> {20 Self::SIGNATURE21 }22 type Status: serde::Serialize;23 fn authorize(&self, caller: Principal, saved: &Snapshot<D, E>) -> bool;24 fn details(&self, data: &D) -> Vec<Field>;25 fn error(&self, error: &E) -> String;26 fn status(&self, saved: &Snapshot<D, E>) -> Self::Status;27 fn graph(&self) -> Option<GraphView>;28 fn authorize_archive(&self, _caller: Principal, _id: u64) -> Option<bool> {29 None30 }31 fn archive_access_current(&self) -> bool {32 false33 }34}35/// Bound UTF-8 text without splitting a character.36pub fn brief(mut text: String, max: usize) -> String {37 if text.len() > max {38 let mut boundary = max;39 while !text.is_char_boundary(boundary) {40 boundary -= 1;41 }42 text.truncate(boundary);43 }44 text45}46pub fn fields(values: Vec<Field>) -> Vec<Field> {47 values48 .into_iter()49 .take(16)50 .map(|field| Field {51 name: brief(field.name, 64),52 text: brief(field.text, 256),53 })54 .collect()55}56fn small(value: &Nat) -> Option<u64> {57 value.try_to_u64()58}59fn limit(value: &Nat, max: usize) -> usize {60 small(value).unwrap_or(max as u64).clamp(1, max as u64) as usize61}62fn key(k: crate::Key) -> Key {63 Key {64 namespace: k.namespace.into(),65 execution: k.execution.into(),66 node: k.node.into(),67 visit: k.visit.into(),68 version: k.version.into(),69 }70}71fn reason(r: crate::BlockReason) -> BlockReason {72 match r {73 crate::BlockReason::Unknown => BlockReason::Unknown,74 crate::BlockReason::Timeout => BlockReason::Timeout,75 crate::BlockReason::RetryExhausted => BlockReason::RetryExhausted,76 crate::BlockReason::StorageLimit => BlockReason::StorageLimit,77 }78}79fn failure<D, E, P: Profile<D, E>>(profile: &P, f: &Failure<E>) -> ErrorSummary {80 match f {81 Failure::App(e) => ErrorSummary {82 category: Category::App,83 text: brief(profile.error(e), 256),84 },85 Failure::Unknown => ErrorSummary {86 category: Category::Unknown,87 text: "Outcome unknown".into(),88 },89 Failure::Timeout => ErrorSummary {90 category: Category::Timeout,91 text: "Reply deadline passed".into(),92 },93 Failure::Capacity => ErrorSummary {94 category: Category::Capacity,95 text: "Workflow storage limit exceeded".into(),96 },97 }98}99fn status<D, E>(saved: &Snapshot<D, E>) -> Status {100 match saved.status {101 EngineStatus::Running102 if saved103 .nodes104 .iter()105 .any(|n| matches!(n.phase, Phase::Blocked(_))) =>106 {107 Status::Blocked108 }109 EngineStatus::Running => Status::Running,110 EngineStatus::DefinitionChanged => Status::DefinitionChanged,111 EngineStatus::Succeeded(_) => Status::Succeeded,112 EngineStatus::Failed(_) => Status::Failed,113 }114}115fn current<D, E, P: Profile<D, E>>(n: &NodeSnapshot<D, E>, profile: &P) -> Current {116 let certainty = if n.uncertain {117 Certainty::Unknown118 } else if n.confirmed_success {119 Certainty::ConfirmedSuccess120 } else if matches!(n.failure, Some(Failure::App(_))) {121 Certainty::ReportedFailure122 } else if matches!(n.failure, Some(Failure::Unknown | Failure::Timeout)) {123 Certainty::Unknown124 } else if n.attempt == 0 {125 Certainty::NotStarted126 } else if n.phase == Phase::Calling {127 Certainty::Pending128 } else {129 Certainty::NotStarted130 };131 let state = match n.phase {132 Phase::Ready => VisitStatus::Ready,133 Phase::QueuedCall => VisitStatus::Queued,134 Phase::Calling => VisitStatus::Running,135 Phase::Received => VisitStatus::Received,136 Phase::RetryWait => VisitStatus::Retrying,137 Phase::Waiting | Phase::Awaiting => VisitStatus::Waiting,138 Phase::Joining => VisitStatus::Joining,139 Phase::Blocked(r) => VisitStatus::Blocked(reason(r)),140 };141 Current {142 key: key(n.key),143 nodeId: Some(n.step.into()),144 parent: n.parent.map(|(node, branch)| Parent {145 node: node.into(),146 branch: branch.into(),147 }),148 status: state,149 operationKey: n.operation_key.map(key),150 attemptCount: n.attempt.into(),151 retryAt: if n.phase == Phase::RetryWait {152 n.wake_at.map(Int::from)153 } else {154 None155 },156 wakeAt: n.wake_at.map(Int::from),157 error: if n.phase == Phase::Blocked(crate::BlockReason::StorageLimit) {158 Some(failure(profile, &Failure::Capacity))159 } else {160 n.failure.as_ref().map(|e| failure(profile, e))161 },162 certainty,163 branchProgress: if n.children.is_empty() {164 None165 } else {166 Some(BranchProgress {167 total: n.children.len().into(),168 completed: n.children.len().saturating_sub(n.remaining as usize).into(),169 children: n.children.iter().copied().map(Nat::from).collect(),170 })171 },172 details: fields(profile.details(&n.data)),173 }174}175fn summary<D, E>(saved: &Snapshot<D, E>, workflow: &str, updated: u64) -> Summary {176 Summary {177 id: saved.id.into(),178 workflowId: workflow.into(),179 version: saved.version.into(),180 status: status(saved),181 createdAt: saved.created_at.into(),182 updatedAt: updated.into(),183 finishedAt: saved.finished_at.map(Int::from),184 }185}186187/// A visit is identified by its retained Entered event's stored sequence. A188/// per-node key.visit is not a global trace ID. Without that actual association189/// we export current state only, never invent an invocation or historical step.190fn visits<D, E, P: Profile<D, E>>(191 saved: &Snapshot<D, E>,192 events: &[crate::TraceEvent],193 profile: &P,194) -> (Vec<Visit>, Vec<Nat>, bool) {195 use std::collections::BTreeMap;196 let mut rows = Vec::<Visit>::new();197 let mut indices = BTreeMap::new();198 let mut known = Vec::new();199 for event in events {200 if event.kind == crate::EventKind::Entered {201 indices.insert(event.key, rows.len());202 rows.push(Visit {203 instructions: None,204 id: event.sequence.into(),205 key: key(event.key),206 operationKey: None,207 nodeId: None,208 parent: None,209 status: VisitStatus::Ready,210 enteredAt: event.at.into(),211 updatedAt: event.at.into(),212 finishedAt: None,213 attemptCount: event.attempt.into(),214 attempts: vec![],215 attemptsTruncated: false,216 retryAt: None,217 wakeAt: None,218 error: None,219 certainty: Certainty::NotStarted,220 branchProgress: None,221 details: vec![],222 });223 known.push(true);224 }225 let Some(&index) = indices.get(&event.key) else {226 continue;227 };228 let visit = &mut rows[index];229 visit.updatedAt = event.at.into();230 visit.attemptCount = event.attempt.into();231 match event.kind {232 crate::EventKind::AttemptStarted => {233 visit.status = VisitStatus::Running;234 visit.certainty = Certainty::Pending;235 visit.attempts.push(Attempt {236 metrics: None,237 attempt: event.attempt.into(),238 startedAt: event.at.into(),239 finishedAt: None,240 certainty: Certainty::Pending,241 error: None,242 });243 known[index] = true;244 }245 crate::EventKind::Received => {246 visit.status = VisitStatus::Received;247 // Compact events retain no response payload or outcome certainty.248 visit.certainty = Certainty::Unknown;249 if let Some(attempt) = visit250 .attempts251 .last_mut()252 .filter(|a| small(&a.attempt) == Some(u64::from(event.attempt)))253 {254 attempt.finishedAt = Some(event.at.into());255 attempt.certainty = Certainty::Unknown;256 }257 known[index] = true;258 }259 crate::EventKind::Waiting => {260 visit.status = VisitStatus::Waiting;261 known[index] = true;262 }263 crate::EventKind::RetryScheduled => {264 visit.status = VisitStatus::Retrying;265 visit.certainty = Certainty::Unknown;266 known[index] = true;267 }268 crate::EventKind::Completed | crate::EventKind::Failed => {269 visit.status = if event.kind == crate::EventKind::Completed {270 VisitStatus::Completed271 } else {272 VisitStatus::Failed273 };274 visit.finishedAt = Some(event.at.into());275 if event.attempt != 0 {276 visit.certainty = Certainty::Unknown;277 }278 known[index] = true;279 }280 // The saved event does not retain a block reason. Current nodes can281 // supply it; historical visits lacking that fact remain unavailable.282 crate::EventKind::Blocked => {283 known[index] = false;284 }285 _ => {}286 }287 }288 let mut active = Vec::new();289 for node in &saved.nodes {290 let Some(&index) = indices.get(&node.key) else {291 continue;292 };293 let current = current(node, profile);294 let parent = node.parent.and_then(|(parent, branch)| {295 saved296 .nodes297 .iter()298 .find(|candidate| candidate.key.node == parent)299 .and_then(|parent| indices.get(&parent.key))300 .map(|&parent| VisitParent {301 visit: rows[parent].id.clone(),302 branch: branch.into(),303 })304 });305 let visit = &mut rows[index];306 active.push(visit.id.clone());307 visit.nodeId = current.nodeId;308 visit.operationKey = current.operationKey;309 visit.status = current.status;310 visit.attemptCount = current.attemptCount;311 visit.retryAt = current.retryAt;312 visit.wakeAt = current.wakeAt;313 visit.error = current.error;314 visit.certainty = current.certainty;315 visit.branchProgress = current.branchProgress;316 visit.details = current.details;317 visit.parent = parent;318 known[index] = true;319 }320 let truncated = active.len() != saved.nodes.len() || known.iter().any(|known| !known);321 for visit in &mut rows {322 visit.attemptsTruncated =323 small(&visit.attemptCount).unwrap_or(u64::MAX) > visit.attempts.len() as u64;324 }325 (326 rows.into_iter()327 .zip(known)328 .filter_map(|(row, known)| known.then_some(row))329 .collect(),330 active,331 truncated,332 )333}334/// Query routing scans at most 127 records and returns at most 64 authorized335/// executions. Invalid oversized client cursors return an empty result.336pub fn route<337 A: Access,338 D: PayloadContract + PayloadSize + Clone,339 E: PayloadContract + PayloadSize + Clone,340 P: Profile<D, E>,341>(342 engine: &EngineView<'_, A, D, E>,343 profile: &P,344 caller: Principal,345 request: Request,346 now: u64,347) -> Result<Response<P::Status>> {348 let workflow = P::ID;349 match request {350 Request::Definition => Ok(Response::Definition(profile.graph())),351 Request::Executions(query) => {352 let size = limit(&query.limit, 64);353 let from = match query.from {354 Some(ref value) => match small(value) {355 Some(v) => Some(v),356 None => {357 return Ok(Response::Executions(Page {358 items: vec![],359 nextFrom: None,360 limit: size.into(),361 }));362 }363 },364 None => None,365 };366 let page = engine.execution_page(from, 127)?;367 let mut items = Vec::new();368 let mut next = page.next_from;369 let mut rows = page.entries.into_iter().peekable();370 while let Some(saved) = rows.next() {371 if saved.expires_at.is_some_and(|at| now >= at)372 || !profile.authorize(caller, &saved)373 {374 continue;375 }376 let metadata = engine.history_metadata(saved.id)?;377 items.push(summary(378 &saved,379 workflow,380 saved381 .finished_at382 .or(metadata.last_at)383 .unwrap_or(saved.created_at),384 ));385 if items.len() == size {386 next = rows.peek().map(|s| s.id).or(next);387 break;388 }389 }390 Ok(Response::Executions(Page {391 items,392 nextFrom: next.map(Nat::from),393 limit: size.into(),394 }))395 }396 Request::Status(id) => {397 let saved = match small(&id) {398 Some(id) => engine.status(id, now)?,399 None => None,400 };401 Ok(Response::Status(402 saved403 .filter(|s| profile.authorize(caller, s))404 .map(|s| profile.status(&s)),405 ))406 }407 Request::Snapshot(query) => {408 let Some(saved) = small(&query.id)409 .map(|id| engine.status(id, now))410 .transpose()?411 .flatten()412 else {413 return Ok(Response::Snapshot(None));414 };415 if query416 .version417 .as_ref()418 .is_some_and(|v| small(v) != Some(u64::from(saved.version)))419 || !profile.authorize(caller, &saved)420 {421 return Ok(Response::Snapshot(None));422 }423 let events = if let Some(page) = query.history.as_ref() {424 engine.history(saved.id, small(&page.from).unwrap_or(u64::MAX), 128)?425 } else {426 vec![]427 };428 let metadata = engine.history_metadata(saved.id)?;429 let trace = engine.tracing(saved.id)?.unwrap_or((false, 0));430 // A bounded, recent projection of existing records. Normal workflow431 // execution records exactly the same data with this inspector absent.432 let recent_from = metadata.next_sequence.saturating_sub(128);433 let (visits, active_visit_ids, visits_truncated) = if trace.0 {434 visits(435 &saved,436 &engine.history(saved.id, recent_from, 128)?,437 profile,438 )439 } else {440 (vec![], vec![], false)441 };442 let expected_signature = profile.definition_signature(engine.namespace()?);443 let definition_differs = saved.version != P::VERSION444 || expected_signature.is_some_and(|expected| saved.signature != Some(expected));445 let first = metadata.first_sequence;446 let next = metadata.next_sequence;447 let history = query448 .history449 .as_ref()450 .map(|page| history_page(&events, metadata, trace, page));451 let execution = Execution {452 id: saved.id.into(),453 workflowId: workflow.into(),454 version: saved.version.into(),455 status: if definition_differs && matches!(saved.status, EngineStatus::Running) {456 Status::DefinitionChanged457 } else {458 status(&saved)459 },460 createdAt: saved.created_at.into(),461 updatedAt: saved462 .finished_at463 .or(metadata.last_at)464 .unwrap_or(saved.created_at)465 .into(),466 finishedAt: saved.finished_at.map(Int::from),467 current: saved.nodes.iter().map(|n| current(n, profile)).collect(),468 tracing: if trace.0 {469 Tracing::On(Trace {470 session: trace.1.into(),471 since: metadata.first_at.unwrap_or(saved.created_at).into(),472 partial: true,473 })474 } else {475 Tracing::Off476 },477 visits,478 activeVisitIds: active_visit_ids,479 progress: vec![],480 visitsTruncated: trace.0 && (visits_truncated || first != 0 || recent_from != 0),481 details: fields(profile.details(&saved.input)),482 error: match &saved.status {483 EngineStatus::Failed(e) => Some(failure(profile, e)),484 _ => None,485 },486 history: HistorySummary {487 firstSequence: first.into(),488 nextSequence: next.into(),489 truncated: first != 0,490 retained: metadata.retained.into(),491 limit: metadata.capacity.into(),492 },493 };494 Ok(Response::Snapshot(Some(Bundle {495 snapshot: SnapshotView {496 graph: if saved.version == P::VERSION497 && expected_signature.is_some()498 && expected_signature == saved.signature499 {500 profile.graph()501 } else {502 None503 },504 execution,505 },506 history,507 status: Some(profile.status(&saved)),508 boundary: None,509 })))510 }511 Request::History(query) => {512 let Some(saved) = small(&query.id)513 .map(|id| engine.status(id, now))514 .transpose()?515 .flatten()516 else {517 return Ok(Response::History(None));518 };519 if small(&query.version) != Some(u64::from(saved.version))520 || !profile.authorize(caller, &saved)521 {522 return Ok(Response::History(None));523 }524 let events =525 engine.history(saved.id, small(&query.page.from).unwrap_or(u64::MAX), 128)?;526 Ok(Response::History(Some(history_page(527 &events,528 engine.history_metadata(saved.id)?,529 engine.tracing(saved.id)?.unwrap_or((false, 0)),530 &query.page,531 ))))532 }533 Request::Revisions(id) => {534 let saved = match small(&id) {535 Some(id) => engine.status(id, now)?,536 None => None,537 };538 Ok(Response::Revisions(539 saved540 .filter(|s| profile.authorize(caller, s))541 .map(|s| Revisions {542 versions: vec![s.version.into()],543 truncated: false,544 activeVersion: Some(s.version.into()),545 }),546 ))547 }548 Request::Archives(query) => Ok(Response::Archives(ArchivePage {549 items: vec![],550 nextFrom: None,551 limit: limit(&query.limit, 64).into(),552 })),553 }554}555// Compact engine events do not contain historical payloads, deadlines or556// instruction scopes. This projection reports only recorded facts. Snapshot557// tracing explicitly marks its incomplete historical visit view as partial.558fn history_page(559 events: &[crate::TraceEvent],560 metadata: crate::HistoryMetadata,561 trace: (bool, u64),562 page: &PageRequest,563) -> HistoryPage {564 let start = small(&page.from).unwrap_or(u64::MAX);565 let size = limit(&page.limit, 128);566 let first = metadata.first_sequence;567 let next = metadata.next_sequence;568 let mut retained = events569 .iter()570 .filter(|e| e.sequence >= start)571 .take(size + 1)572 .collect::<Vec<_>>();573 let next_from = if retained.len() > size {574 retained.pop().map(|e| Nat::from(e.sequence))575 } else {576 retained577 .last()578 .and_then(|e| (e.sequence.saturating_add(1) < next).then(|| Nat::from(e.sequence + 1)))579 };580 let projected = retained581 .into_iter()582 .map(|event| {583 use crate::EventKind as K;584 let kind = match event.kind {585 K::Entered => EventKind::Entered,586 K::AttemptStarted => EventKind::AttemptStarted(AttemptStarted {587 attempt: event.attempt.into(),588 }),589 K::Completed => EventKind::Completed(Completed { ok: true }),590 K::Failed => EventKind::Completed(Completed { ok: false }),591 K::Restored => EventKind::Restored,592 _ => EventKind::Observed,593 };594 Event {595 sequence: event.sequence.into(),596 at: event.at.into(),597 visit: events598 .iter()599 .find(|entered| {600 entered.key == event.key && entered.kind == crate::EventKind::Entered601 })602 .map(|entered| entered.sequence.into()),603 key: Some(key(event.key)),604 operationKey: None,605 nodeId: None,606 kind,607 error: None,608 context: None,609 }610 })611 .collect();612 HistoryPage {613 session: trace.0.then(|| trace.1.into()),614 events: projected,615 firstSequence: first.into(),616 nextSequence: next.into(),617 nextFrom: next_from,618 truncated: first != 0,619 limit: size.into(),620 }621}