1use std::{
2 future::Future,
3 pin::Pin,
4 task::{Context as TaskContext, Poll},
5};
6
7use serde::{Deserialize, Serialize};
8use serde_json::{json, Value};
9
10use super::{
11 command_mismatch, decode_wire_avro_value, encode_typed_envelope, invalid_recorded_history,
12 payload_string, AvroValue, CancellationCallKind, Error, HistoryEvent, RecordedCommand, Result,
13 WorkflowContext, WorkflowIdentity,
14};
15
16pub(super) fn installed_cooperation(capabilities: &Value) -> bool {
17 capabilities["cooperative_cancellation"] == true
18 && capabilities["nexus_cooperative_cancellation"] == true
19 && capabilities["nexus_cooperative_cancellation_binding_kinds"]
20 .as_array()
21 .is_some_and(|kinds| kinds.iter().any(|kind| kind == "workflow_run"))
22}
23
24#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(rename_all = "snake_case")]
27pub enum NexusOperationMode {
28 #[default]
29 Sync,
30 Async,
31}
32
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum NexusWaitFor {
37 Accepted,
38 #[default]
39 Completed,
40}
41
42#[derive(Clone, Debug, Default)]
44pub struct NexusServiceOptions {
45 pub target_namespace: Option<String>,
46 pub idempotency_key: Option<String>,
47 pub mode: NexusOperationMode,
48 pub wait_for: NexusWaitFor,
49}
50
51impl NexusServiceOptions {
52 pub fn new() -> Self {
53 Self::default()
54 }
55
56 fn completion_wait(&self) -> bool {
57 self.mode == NexusOperationMode::Sync && self.wait_for == NexusWaitFor::Completed
58 }
59}
60
61#[derive(Clone, Debug, PartialEq)]
63pub struct NexusOperationResult {
64 pub service_call_id: String,
65 pub status: String,
66 pub target_namespace: Option<String>,
67 pub linked_workflow_instance_id: Option<String>,
68 pub linked_workflow_run_id: Option<String>,
69 pub result: AvroValue,
70}
71
72#[derive(Clone, Debug, PartialEq, Error)]
74#[error("Nexus service operation {status}: {message}")]
75pub struct NexusOperationFailure {
76 pub service_call_id: Option<String>,
77 pub status: String,
78 pub exception_type: String,
79 pub message: String,
80 pub exception: Value,
81}
82
83#[derive(Clone, Debug)]
84pub(super) struct RecordedServiceCall {
85 pub endpoint_name: String,
86 pub service_name: String,
87 pub operation_name: String,
88 pub mode: NexusOperationMode,
89 pub wait_for: NexusWaitFor,
90 pub idempotency_key: Option<String>,
91 pub target_namespace: Option<String>,
92 pub request: Option<AvroValue>,
93 pub admission: Option<NexusOperationResult>,
94 pub outcome: Option<std::result::Result<NexusOperationResult, NexusOperationFailure>>,
95}
96
97fn history_error(sequence: u64, detail: &str) -> Error {
98 invalid_recorded_history(
99 "nexus_service_history_invalid",
100 sequence,
101 "one original service admission and terminal delivery",
102 "invalid service history",
103 detail,
104 )
105}
106
107fn service_text(payload: &Value, field: &str) -> Option<String> {
108 payload_string(payload, field).or_else(|| payload_string(&payload["service_call"], field))
109}
110
111fn identity_text(payload: &Value, field: &str, sequence: u64) -> Result<Option<String>> {
112 let mut result = None;
113 for source in [payload, &payload["service_call"]] {
114 let Some(value) = source.get(field).filter(|value| !value.is_null()) else {
115 continue;
116 };
117 let text = value
118 .as_str()
119 .filter(|text| !text.trim().is_empty())
120 .ok_or_else(|| {
121 history_error(sequence, &format!("{field} must be a non-empty string"))
122 })?;
123 if result.as_deref().is_some_and(|original| original != text) {
124 return Err(history_error(
125 sequence,
126 &format!("{field} has conflicting projections"),
127 ));
128 }
129 result = Some(text.to_owned());
130 }
131 Ok(result)
132}
133
134fn validate_caller(event: &HistoryEvent, sequence: u64, parent: &WorkflowIdentity) -> Result<()> {
135 for (field, expected) in [
136 ("caller_workflow_instance_id", parent.workflow_id.as_deref()),
137 ("workflow_instance_id", parent.workflow_id.as_deref()),
138 ("caller_workflow_run_id", parent.run_id.as_deref()),
139 ("workflow_run_id", parent.run_id.as_deref()),
140 ] {
141 if let Some(actual) = identity_text(&event.payload, field, sequence)? {
142 if expected.is_some_and(|expected| expected != actual) {
143 return Err(history_error(
144 sequence,
145 &format!("{field} does not identify this caller"),
146 ));
147 }
148 }
149 }
150 Ok(())
151}
152
153fn service_result(
154 payload: &Value,
155 codec: &str,
156 sequence: u64,
157 status: &str,
158) -> Result<NexusOperationResult> {
159 let service_call_id = service_text(payload, "service_call_id")
160 .ok_or_else(|| history_error(sequence, "service_call_id is missing"))?;
161 let result = if status == "completed" {
162 let envelope = payload
163 .get("response_payload")
164 .filter(|value| !value.is_null())
165 .or_else(|| payload["service_call"].get("result_envelope"))
166 .unwrap_or(&Value::Null);
167 decode_wire_avro_value(envelope, codec)?
168 } else {
169 AvroValue::Null
170 };
171 Ok(NexusOperationResult {
172 service_call_id,
173 status: status.to_string(),
174 result,
175 target_namespace: service_text(payload, "target_namespace"),
176 linked_workflow_instance_id: service_text(payload, "linked_workflow_instance_id"),
177 linked_workflow_run_id: service_text(payload, "linked_workflow_run_id"),
178 })
179}
180
181pub(super) fn is_service_event(event: &HistoryEvent) -> bool {
182 matches!(
183 event.event_type.as_str(),
184 "ServiceCallStarted"
185 | "ServiceCallCompleted"
186 | "ServiceCallFailed"
187 | "ServiceCallCancelled"
188 )
189}
190
191pub(super) fn recorded_call(
192 events: &[&HistoryEvent],
193 sequence: u64,
194 codec: &str,
195 parent: &WorkflowIdentity,
196) -> Result<RecordedServiceCall> {
197 let starts: Vec<_> = events
198 .iter()
199 .filter(|event| event.event_type == "ServiceCallStarted")
200 .collect();
201 if events.is_empty() || starts.len() > 1 || (starts.is_empty() && events.len() != 1) {
202 return Err(history_error(
203 sequence,
204 "service history must contain one original admission",
205 ));
206 }
207 let start = events[0];
208 if !starts.is_empty()
209 && events
210 .first()
211 .is_none_or(|event| event.event_type != "ServiceCallStarted")
212 {
213 return Err(history_error(
214 sequence,
215 "terminal delivery precedes original admission",
216 ));
217 }
218 for event in events {
219 validate_caller(event, sequence, parent)?;
220 for field in [
221 "service_call_id",
222 "endpoint_name",
223 "service_name",
224 "operation_name",
225 "target_namespace",
226 "caller_namespace",
227 "idempotency_key",
228 "operation_mode",
229 "wait_for",
230 "linked_workflow_instance_id",
231 "linked_workflow_run_id",
232 "call_deadline_at",
233 ] {
234 let original = identity_text(&start.payload, field, sequence)?;
235 let observed = identity_text(&event.payload, field, sequence)?;
236 if matches!((&original, &observed), (Some(original), Some(observed)) if original != observed)
237 {
238 return Err(history_error(
239 sequence,
240 &format!("terminal delivery changes original {field}"),
241 ));
242 }
243 }
244 }
245 let required = |field| {
246 service_text(&start.payload, field)
247 .ok_or_else(|| history_error(sequence, &format!("original {field} is missing")))
248 };
249 let mode = serde_json::from_value(
250 start
251 .payload
252 .get("operation_mode")
253 .cloned()
254 .or_else(|| start.payload["service_call"].get("operation_mode").cloned())
255 .unwrap_or(json!("sync")),
256 )
257 .map_err(|_| history_error(sequence, "original operation mode is invalid"))?;
258 let wait_for = serde_json::from_value(
259 start
260 .payload
261 .get("wait_for")
262 .cloned()
263 .or_else(|| start.payload["service_call"].get("wait_for").cloned())
264 .unwrap_or(json!("completed")),
265 )
266 .map_err(|_| history_error(sequence, "original waiting policy is invalid"))?;
267 let admission = if starts.is_empty() {
268 None
269 } else {
270 Some(service_result(&start.payload, codec, sequence, "started")?)
271 };
272 let target_namespace = service_text(&start.payload, "target_namespace");
273 let request = start
274 .payload
275 .get("request_payload")
276 .filter(|value| !value.is_null())
277 .map(|value| decode_wire_avro_value(value, codec))
278 .transpose()?;
279 let terminals: Vec<_> = events
280 .iter()
281 .filter(|event| event.event_type != "ServiceCallStarted")
282 .collect();
283 if terminals.len() > 1 {
284 return Err(history_error(
285 sequence,
286 "service history contains more than one terminal delivery",
287 ));
288 }
289 let outcome = terminals
290 .first()
291 .map(|event| {
292 if admission.as_ref().is_some_and(|admission| {
293 service_text(&event.payload, "service_call_id").as_deref()
294 != Some(&admission.service_call_id)
295 }) {
296 return Err(history_error(
297 sequence,
298 "terminal delivery changes the original service identity",
299 ));
300 }
301 if event.event_type == "ServiceCallCompleted" {
302 let mut result = service_result(&event.payload, codec, sequence, "completed")?;
303 if let Some(admission) = &admission {
304 result.target_namespace = result
305 .target_namespace
306 .or_else(|| admission.target_namespace.clone());
307 result.linked_workflow_instance_id = result
308 .linked_workflow_instance_id
309 .or_else(|| admission.linked_workflow_instance_id.clone());
310 result.linked_workflow_run_id = result
311 .linked_workflow_run_id
312 .or_else(|| admission.linked_workflow_run_id.clone());
313 }
314 return Ok(Ok(result));
315 }
316 let status = if event.event_type == "ServiceCallCancelled" {
317 "cancelled"
318 } else {
319 "failed"
320 };
321 let exception_type = service_text(&event.payload, "caller_observed_error_type")
322 .or_else(|| service_text(&event.payload, "exception_type"))
323 .unwrap_or_else(|| format!("service_call_{status}"));
324 Ok(Err(NexusOperationFailure {
325 service_call_id: service_text(&event.payload, "service_call_id"),
326 status: status.to_string(),
327 exception_type,
328 message: service_text(&event.payload, "message")
329 .unwrap_or_else(|| format!("service call {status}")),
330 exception: event
331 .payload
332 .get("exception")
333 .cloned()
334 .unwrap_or(Value::Null),
335 }))
336 })
337 .transpose()?;
338 Ok(RecordedServiceCall {
339 endpoint_name: required("endpoint_name")?,
340 service_name: required("service_name")?,
341 operation_name: required("operation_name")?,
342 mode,
343 wait_for,
344 idempotency_key: service_text(&start.payload, "idempotency_key"),
345 target_namespace,
346 request,
347 admission,
348 outcome,
349 })
350}
351
352pub struct NexusServiceCall {
354 ctx: WorkflowContext,
355 endpoint_name: String,
356 service_name: String,
357 operation_name: String,
358 options: NexusServiceOptions,
359 arguments: Option<Result<AvroValue>>,
360 suspended: bool,
361}
362
363impl WorkflowContext {
364 pub fn call_nexus_service<T: Serialize>(
366 &self,
367 endpoint_name: impl Into<String>,
368 service_name: impl Into<String>,
369 operation_name: impl Into<String>,
370 arguments: T,
371 ) -> NexusServiceCall {
372 self.call_nexus_service_with_options(
373 endpoint_name,
374 service_name,
375 operation_name,
376 NexusServiceOptions::default(),
377 arguments,
378 )
379 }
380
381 pub fn call_nexus_service_with_options<T: Serialize>(
382 &self,
383 endpoint_name: impl Into<String>,
384 service_name: impl Into<String>,
385 operation_name: impl Into<String>,
386 options: NexusServiceOptions,
387 arguments: T,
388 ) -> NexusServiceCall {
389 NexusServiceCall {
390 ctx: self.clone(),
391 endpoint_name: endpoint_name.into(),
392 service_name: service_name.into(),
393 operation_name: operation_name.into(),
394 options,
395 arguments: Some(AvroValue::from_serialize(&arguments)),
396 suspended: false,
397 }
398 }
399}
400
401impl NexusServiceCall {
402 fn validate_recorded_call(&mut self, call: &RecordedServiceCall, sequence: u64) -> Result<()> {
403 for (field, expected, actual) in [
404 (
405 "endpoint_name",
406 call.endpoint_name.as_str(),
407 self.endpoint_name.as_str(),
408 ),
409 (
410 "service_name",
411 call.service_name.as_str(),
412 self.service_name.as_str(),
413 ),
414 (
415 "operation_name",
416 call.operation_name.as_str(),
417 self.operation_name.as_str(),
418 ),
419 ] {
420 if expected != actual {
421 return Err(invalid_recorded_history(
422 &format!("nexus_{field}_changed"),
423 sequence,
424 expected,
425 actual,
426 "original service intent changed",
427 ));
428 }
429 }
430 if self
431 .options
432 .target_namespace
433 .as_ref()
434 .is_some_and(|target| call.target_namespace.as_ref() != Some(target))
435 || self.options.idempotency_key.as_ref().is_some_and(|key| {
436 call.idempotency_key
437 .as_ref()
438 .is_some_and(|original| original != key)
439 })
440 || self.options.mode != call.mode
441 || self.options.wait_for != call.wait_for
442 {
443 return Err(history_error(
444 sequence,
445 "original service routing, idempotency or waiting policy changed",
446 ));
447 }
448 if let Some(original) = &call.request {
449 let arguments = self.arguments.take().unwrap_or(Ok(AvroValue::Null))?;
450 if &arguments != original {
451 return Err(history_error(sequence, "original service request changed"));
452 }
453 }
454 Ok(())
455 }
456}
457
458impl Future for NexusServiceCall {
459 type Output = Result<NexusOperationResult>;
460
461 fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
462 if self.suspended {
463 return Poll::Pending;
464 }
465 let ctx = self.ctx.clone();
466 let mut state = match ctx.state.lock() {
467 Ok(state) => state,
468 Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
469 };
470 if ctx.cancellation_scope_id != "root" {
471 return Poll::Ready(Err(Error::CancellationScopeExecutionUnavailable));
472 }
473 let cursor = state.command_cursor;
474 let recorded = match state
475 .cancellation_replay_command(cursor, CancellationCallKind::ServiceOperation)
476 {
477 Ok(recorded) => recorded,
478 Err(error) => return Poll::Ready(Err(error)),
479 };
480 if let Some(recorded) = recorded {
481 let RecordedCommand::ServiceOperation { sequence, call } = recorded else {
482 return Poll::Ready(Err(command_mismatch(&recorded, "service operation")));
483 };
484 if let Err(error) = self.validate_recorded_call(&call, sequence) {
485 return Poll::Ready(Err(error));
486 }
487 if self.options.completion_wait() {
488 if let Err(error) =
489 state.replay_cancellation_at(cursor, CancellationCallKind::ServiceOperation)
490 {
491 return Poll::Ready(Err(error));
492 }
493 match state.prepare_scalar_cancellation(
494 cursor,
495 CancellationCallKind::ServiceOperation,
496 &[],
497 ) {
498 Ok(true) => {
499 self.suspended = true;
500 return Poll::Pending;
501 }
502 Ok(false) => {}
503 Err(error) => return Poll::Ready(Err(error)),
504 }
505 }
506 state.replay_clock.unavailable();
507 state.command_cursor += 1;
508 if !self.options.completion_wait() {
509 if let Some(admission) = call.admission {
510 state.advance_cancellation_sequence(sequence, &[]);
511 return Poll::Ready(Ok(admission));
512 }
513 }
514 if let Some(outcome) = call.outcome {
515 state.advance_cancellation_sequence(sequence, &[]);
516 return Poll::Ready(
517 outcome.map_err(|error| Error::NexusOperationFailed(Box::new(error))),
518 );
519 }
520 state.matched_recorded_pending = true;
521 state.observation_pending = true;
522 self.suspended = true;
523 return Poll::Pending;
524 }
525 if [
526 self.endpoint_name.as_str(),
527 self.service_name.as_str(),
528 self.operation_name.as_str(),
529 ]
530 .iter()
531 .any(|name| name.trim().is_empty())
532 || self
533 .options
534 .target_namespace
535 .as_ref()
536 .is_some_and(|value| value.trim().is_empty())
537 || self
538 .options
539 .idempotency_key
540 .as_ref()
541 .is_some_and(|value| value.trim().is_empty())
542 {
543 return Poll::Ready(Err(Error::WorkerLoop(
544 "Nexus service identity must be non-empty".into(),
545 )));
546 }
547 if self.options.completion_wait() {
548 match state.prepare_scalar_cancellation(
549 cursor,
550 CancellationCallKind::ServiceOperation,
551 &[],
552 ) {
553 Ok(true) => {
554 self.suspended = true;
555 return Poll::Pending;
556 }
557 Ok(false) => {}
558 Err(error) => return Poll::Ready(Err(error)),
559 }
560 }
561 let arguments = match self.arguments.take().unwrap_or(Ok(AvroValue::Null)) {
562 Ok(arguments) => arguments,
563 Err(error) => return Poll::Ready(Err(error)),
564 };
565 let request_payload = match encode_typed_envelope(&arguments, &state.payload_codec) {
566 Ok(payload) => payload,
567 Err(error) => return Poll::Ready(Err(error)),
568 };
569 let payload_codec = state.payload_codec.clone();
570 state.commands.push(json!({
571 "type": "start_service_operation", "endpoint_name": self.endpoint_name,
572 "service_name": self.service_name, "operation_name": self.operation_name,
573 "namespace": self.options.target_namespace, "idempotency_key": self.options.idempotency_key,
574 "mode_override": self.options.mode, "wait_for": self.options.wait_for,
575 "payload_codec": payload_codec, "request_payload": request_payload,
576 "metadata": {"caller_sdk_language": "sdk-rust"},
577 }));
578 self.suspended = true;
579 Poll::Pending
580 }
581}