restate_sdk_shared_core/vm/
mod.rs

1use crate::headers::HeaderMap;
2use crate::service_protocol::messages::{
3    attach_invocation_command_message, complete_awakeable_command_message,
4    complete_promise_command_message, get_invocation_output_command_message,
5    output_command_message, send_signal_command_message, AttachInvocationCommandMessage,
6    CallCommandMessage, ClearAllStateCommandMessage, ClearStateCommandMessage,
7    CompleteAwakeableCommandMessage, CompletePromiseCommandMessage,
8    GetInvocationOutputCommandMessage, GetPromiseCommandMessage, IdempotentRequestTarget,
9    OneWayCallCommandMessage, OutputCommandMessage, PeekPromiseCommandMessage,
10    SendSignalCommandMessage, SetStateCommandMessage, SleepCommandMessage, WorkflowTarget,
11};
12use crate::service_protocol::{Decoder, NotificationId, RawMessage, Version, CANCEL_SIGNAL_ID};
13use crate::vm::errors::{
14    ClosedError, UnexpectedStateError, UnsupportedFeatureForNegotiatedVersion,
15    EMPTY_IDEMPOTENCY_KEY, SUSPENDED,
16};
17use crate::vm::transitions::*;
18use crate::{
19    AttachInvocationTarget, CallHandle, CommandRelationship, DoProgressResponse, Error, Header,
20    ImplicitCancellationOption, Input, NonDeterministicChecksOption, NonEmptyValue,
21    NotificationHandle, ResponseHead, RetryPolicy, RunExitResult, SendHandle, TakeOutputResult,
22    Target, TerminalFailure, VMOptions, VMResult, Value, CANCEL_NOTIFICATION_HANDLE,
23};
24use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
25use base64::{alphabet, Engine};
26use bytes::{Buf, BufMut, Bytes, BytesMut};
27use context::{AsyncResultsState, Context, Output, RunState};
28use std::borrow::Cow;
29use std::collections::{HashMap, VecDeque};
30use std::mem::size_of;
31use std::time::Duration;
32use std::{fmt, mem};
33use strum::IntoStaticStr;
34use tracing::{debug, enabled, instrument, Level};
35
36mod context;
37pub(crate) mod errors;
38mod transitions;
39
40const CONTENT_TYPE: &str = "content-type";
41
42#[derive(Debug, IntoStaticStr)]
43pub(crate) enum State {
44    WaitingStart,
45    WaitingReplayEntries {
46        received_entries: u32,
47        commands: VecDeque<RawMessage>,
48        async_results: AsyncResultsState,
49    },
50    Replaying {
51        commands: VecDeque<RawMessage>,
52        run_state: RunState,
53        async_results: AsyncResultsState,
54    },
55    Processing {
56        processing_first_entry: bool,
57        run_state: RunState,
58        async_results: AsyncResultsState,
59    },
60    Closed,
61}
62
63impl State {
64    fn as_unexpected_state(&self, event: &'static str) -> Error {
65        if matches!(self, State::Closed) {
66            return ClosedError::new(event).into();
67        }
68        UnexpectedStateError::new(self.into(), event).into()
69    }
70}
71
72struct TrackedInvocationId {
73    handle: NotificationHandle,
74    invocation_id: Option<String>,
75}
76
77impl TrackedInvocationId {
78    fn is_resolved(&self) -> bool {
79        self.invocation_id.is_some()
80    }
81}
82
83pub struct CoreVM {
84    version: Version,
85    options: VMOptions,
86
87    // Input decoder
88    decoder: Decoder,
89
90    // State machine
91    context: Context,
92    last_transition: Result<State, Error>,
93
94    // Implicit cancellation tracking
95    tracked_invocation_ids: Vec<TrackedInvocationId>,
96
97    // Run names, useful for debugging
98    sys_run_names: HashMap<NotificationHandle, String>,
99}
100
101impl CoreVM {
102    // Returns empty string if the invocation id is not present
103    fn debug_invocation_id(&self) -> &str {
104        if let Some(start_info) = self.context.start_info() {
105            &start_info.debug_id
106        } else {
107            ""
108        }
109    }
110
111    fn debug_state(&self) -> &'static str {
112        match &self.last_transition {
113            Ok(s) => s.into(),
114            Err(_) => "Failed",
115        }
116    }
117
118    fn verify_feature_support(
119        &mut self,
120        feature: &'static str,
121        minimum_required_protocol: Version,
122    ) -> VMResult<()> {
123        if self.version < minimum_required_protocol {
124            return self.do_transition(HitError(
125                UnsupportedFeatureForNegotiatedVersion::new(
126                    feature,
127                    self.version,
128                    minimum_required_protocol,
129                )
130                .into(),
131            ));
132        }
133        Ok(())
134    }
135
136    fn _is_completed(&self, handle: NotificationHandle) -> bool {
137        match &self.last_transition {
138            Ok(State::Replaying { async_results, .. })
139            | Ok(State::Processing { async_results, .. }) => {
140                async_results.is_handle_completed(handle)
141            }
142            _ => false,
143        }
144    }
145
146    fn _do_progress(
147        &mut self,
148        any_handle: Vec<NotificationHandle>,
149    ) -> Result<DoProgressResponse, Error> {
150        match self.do_transition(DoProgress(any_handle)) {
151            Ok(Ok(do_progress_response)) => Ok(do_progress_response),
152            Ok(Err(_)) => Err(SUSPENDED),
153            Err(e) => Err(e),
154        }
155    }
156
157    fn is_implicit_cancellation_enabled(&self) -> bool {
158        matches!(
159            self.options.implicit_cancellation,
160            ImplicitCancellationOption::Enabled { .. }
161        )
162    }
163}
164
165impl fmt::Debug for CoreVM {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        let mut s = f.debug_struct("CoreVM");
168        s.field("version", &self.version);
169
170        if let Some(start_info) = self.context.start_info() {
171            s.field("invocation_id", &start_info.debug_id);
172        }
173
174        match &self.last_transition {
175            Ok(state) => s.field("last_transition", &<&'static str>::from(state)),
176            Err(_) => s.field("last_transition", &"Errored"),
177        };
178
179        s.field("command_index", &self.context.journal.command_index())
180            .field(
181                "notification_index",
182                &self.context.journal.notification_index(),
183            )
184            .finish()
185    }
186}
187
188// --- Bound checks
189#[allow(unused)]
190const fn is_send<T: Send>() {}
191const _: () = is_send::<CoreVM>();
192
193// Macro used for informative debug logs
194macro_rules! invocation_debug_logs {
195    ($this:expr, $($arg:tt)*) => {
196        if ($this.is_processing()) {
197            tracing::debug!($($arg)*)
198        }
199    };
200}
201
202impl super::VM for CoreVM {
203    #[instrument(level = "trace", skip(request_headers), ret)]
204    fn new(request_headers: impl HeaderMap, options: VMOptions) -> Result<Self, Error> {
205        let version = request_headers
206            .extract(CONTENT_TYPE)
207            .map_err(|e| {
208                Error::new(
209                    errors::codes::BAD_REQUEST,
210                    format!("cannot read '{CONTENT_TYPE}' header: {e:?}"),
211                )
212            })?
213            .ok_or(errors::MISSING_CONTENT_TYPE)?
214            .parse::<Version>()?;
215
216        if version < Version::minimum_supported_version()
217            || version > Version::maximum_supported_version()
218        {
219            return Err(Error::new(
220                errors::codes::UNSUPPORTED_MEDIA_TYPE,
221                format!(
222                    "Unsupported protocol version {:?}, not within [{:?} to {:?}]. \
223                    You might need to rediscover the service, check https://docs.restate.dev/references/errors/#RT0015",
224                    version,
225                    Version::minimum_supported_version(),
226                    Version::maximum_supported_version()
227                ),
228            ));
229        }
230        let non_deterministic_checks_ignore_payload_equality = matches!(
231            options.non_determinism_checks,
232            NonDeterministicChecksOption::PayloadChecksDisabled
233        );
234
235        Ok(Self {
236            version,
237            options,
238            decoder: Decoder::new(version),
239            context: Context {
240                input_is_closed: false,
241                output: Output::new(version),
242                start_info: None,
243                journal: Default::default(),
244                eager_state: Default::default(),
245                non_deterministic_checks_ignore_payload_equality,
246            },
247            last_transition: Ok(State::WaitingStart),
248            tracked_invocation_ids: vec![],
249            sys_run_names: HashMap::with_capacity(0),
250        })
251    }
252
253    #[instrument(
254        level = "trace",
255        skip(self),
256        fields(
257            restate.invocation.id = self.debug_invocation_id(),
258            restate.protocol.state = self.debug_state(),
259            restate.journal.command_index = self.context.journal.command_index(),
260            restate.protocol.version = %self.version
261        ),
262        ret
263    )]
264    fn get_response_head(&self) -> ResponseHead {
265        ResponseHead {
266            status_code: 200,
267            headers: vec![Header {
268                key: Cow::Borrowed(CONTENT_TYPE),
269                value: Cow::Borrowed(self.version.content_type()),
270            }],
271            version: self.version,
272        }
273    }
274
275    #[instrument(
276        level = "trace",
277        skip(self),
278        fields(
279            restate.invocation.id = self.debug_invocation_id(),
280            restate.protocol.state = self.debug_state(),
281            restate.journal.command_index = self.context.journal.command_index(),
282            restate.protocol.version = %self.version
283        ),
284        ret
285    )]
286    fn notify_input(&mut self, buffer: Bytes) {
287        self.decoder.push(buffer);
288        loop {
289            match self.decoder.consume_next() {
290                Ok(Some(msg)) => {
291                    if self.do_transition(NewMessage(msg)).is_err() {
292                        return;
293                    }
294                }
295                Ok(None) => {
296                    return;
297                }
298                Err(e) => {
299                    if self.do_transition(HitError(e.into())).is_err() {
300                        return;
301                    }
302                }
303            }
304        }
305    }
306
307    #[instrument(
308        level = "trace",
309        skip(self),
310        fields(
311            restate.invocation.id = self.debug_invocation_id(),
312            restate.protocol.state = self.debug_state(),
313            restate.journal.command_index = self.context.journal.command_index(),
314            restate.protocol.version = %self.version
315        ),
316        ret
317    )]
318    fn notify_input_closed(&mut self) {
319        self.context.input_is_closed = true;
320        let _ = self.do_transition(NotifyInputClosed);
321    }
322
323    #[instrument(
324        level = "trace",
325        skip(self),
326        fields(
327            restate.invocation.id = self.debug_invocation_id(),
328            restate.protocol.state = self.debug_state(),
329            restate.journal.command_index = self.context.journal.command_index(),
330            restate.protocol.version = %self.version
331        ),
332        ret
333    )]
334    fn notify_error(
335        &mut self,
336        mut error: Error,
337        command_relationship: Option<CommandRelationship>,
338    ) {
339        if let Some(command_relationship) = command_relationship {
340            error = error.with_related_command_metadata(
341                self.context
342                    .journal
343                    .resolve_related_command(command_relationship),
344            );
345        }
346
347        let _ = self.do_transition(HitError(error));
348    }
349
350    #[instrument(
351        level = "trace",
352        skip(self),
353        fields(
354            restate.invocation.id = self.debug_invocation_id(),
355            restate.protocol.state = self.debug_state(),
356            restate.journal.command_index = self.context.journal.command_index(),
357            restate.protocol.version = %self.version
358        ),
359        ret
360    )]
361    fn take_output(&mut self) -> TakeOutputResult {
362        if self.context.output.buffer.has_remaining() {
363            TakeOutputResult::Buffer(
364                self.context
365                    .output
366                    .buffer
367                    .copy_to_bytes(self.context.output.buffer.remaining()),
368            )
369        } else if !self.context.output.is_closed() {
370            TakeOutputResult::Buffer(Bytes::default())
371        } else {
372            TakeOutputResult::EOF
373        }
374    }
375
376    #[instrument(
377        level = "trace",
378        skip(self),
379        fields(
380            restate.invocation.id = self.debug_invocation_id(),
381            restate.protocol.state = self.debug_state(),
382            restate.journal.command_index = self.context.journal.command_index(),
383            restate.protocol.version = %self.version
384        ),
385        ret
386    )]
387    fn is_ready_to_execute(&self) -> Result<bool, Error> {
388        match &self.last_transition {
389            Ok(State::WaitingStart) | Ok(State::WaitingReplayEntries { .. }) => Ok(false),
390            Ok(State::Processing { .. }) | Ok(State::Replaying { .. }) => Ok(true),
391            Ok(s) => Err(s.as_unexpected_state("IsReadyToExecute")),
392            Err(e) => Err(e.clone()),
393        }
394    }
395
396    #[instrument(
397        level = "trace",
398        skip(self),
399        fields(
400            restate.invocation.id = self.debug_invocation_id(),
401            restate.protocol.state = self.debug_state(),
402            restate.journal.command_index = self.context.journal.command_index(),
403            restate.protocol.version = %self.version
404        ),
405        ret
406    )]
407    fn is_completed(&self, handle: NotificationHandle) -> bool {
408        self._is_completed(handle)
409    }
410
411    #[instrument(
412        level = "trace",
413        skip(self),
414        fields(
415            restate.invocation.id = self.debug_invocation_id(),
416            restate.protocol.state = self.debug_state(),
417            restate.journal.command_index = self.context.journal.command_index(),
418            restate.protocol.version = %self.version
419        ),
420        ret
421    )]
422    fn do_progress(
423        &mut self,
424        mut any_handle: Vec<NotificationHandle>,
425    ) -> VMResult<DoProgressResponse> {
426        if self.is_implicit_cancellation_enabled() {
427            // We want the runtime to wake us up in case cancel notification comes in.
428            any_handle.insert(0, CANCEL_NOTIFICATION_HANDLE);
429
430            match self._do_progress(any_handle) {
431                Ok(DoProgressResponse::AnyCompleted) => {
432                    // If it's cancel signal, then let's go on with the cancellation logic
433                    if self._is_completed(CANCEL_NOTIFICATION_HANDLE) {
434                        // Loop once over the tracked invocation ids to resolve the unresolved ones
435                        for i in 0..self.tracked_invocation_ids.len() {
436                            if self.tracked_invocation_ids[i].is_resolved() {
437                                continue;
438                            }
439
440                            let handle = self.tracked_invocation_ids[i].handle;
441
442                            // Try to resolve it
443                            match self._do_progress(vec![handle]) {
444                                Ok(DoProgressResponse::AnyCompleted) => {
445                                    let invocation_id = match self.do_transition(CopyNotification(handle)) {
446                                        Ok(Ok(Some(Value::InvocationId(invocation_id)))) => Ok(invocation_id),
447                                        Ok(Err(_)) => Err(SUSPENDED),
448                                        _ => panic!("Unexpected variant! If the id handle is completed, it must be an invocation id handle!")
449                                    }?;
450
451                                    // This handle is resolved
452                                    self.tracked_invocation_ids[i].invocation_id =
453                                        Some(invocation_id);
454                                }
455                                res => return res,
456                            }
457                        }
458
459                        // Now we got all the invocation IDs, let's cancel!
460                        for tracked_invocation_id in mem::take(&mut self.tracked_invocation_ids) {
461                            self.sys_cancel_invocation(
462                                tracked_invocation_id
463                                    .invocation_id
464                                    .expect("We resolved before all the invocation ids"),
465                            )?;
466                        }
467
468                        // Flip the cancellation
469                        let _ = self.take_notification(CANCEL_NOTIFICATION_HANDLE);
470
471                        // Done
472                        Ok(DoProgressResponse::CancelSignalReceived)
473                    } else {
474                        Ok(DoProgressResponse::AnyCompleted)
475                    }
476                }
477                res => res,
478            }
479        } else {
480            self._do_progress(any_handle)
481        }
482    }
483
484    #[instrument(
485        level = "trace",
486        skip(self),
487        fields(
488            restate.invocation.id = self.debug_invocation_id(),
489            restate.protocol.state = self.debug_state(),
490            restate.journal.command_index = self.context.journal.command_index(),
491            restate.protocol.version = %self.version
492        ),
493        ret
494    )]
495    fn take_notification(&mut self, handle: NotificationHandle) -> VMResult<Option<Value>> {
496        match self.do_transition(TakeNotification(handle)) {
497            Ok(Ok(Some(value))) => {
498                if self.is_implicit_cancellation_enabled() {
499                    // Let's check if that's one of the tracked invocation ids
500                    // We can do binary search here because we assume tracked_invocation_ids is ordered, as handles are incremental numbers
501                    if let Ok(found) = self
502                        .tracked_invocation_ids
503                        .binary_search_by(|tracked| tracked.handle.cmp(&handle))
504                    {
505                        let Value::InvocationId(invocation_id) = &value else {
506                            panic!("Expecting an invocation id here, but got {value:?}");
507                        };
508                        // Keep track of this invocation id
509                        self.tracked_invocation_ids
510                            .get_mut(found)
511                            .unwrap()
512                            .invocation_id = Some(invocation_id.clone());
513                    }
514                }
515
516                Ok(Some(value))
517            }
518            Ok(Ok(None)) => Ok(None),
519            Ok(Err(_)) => Err(SUSPENDED),
520            Err(e) => Err(e),
521        }
522    }
523
524    #[instrument(
525        level = "trace",
526        skip(self),
527        fields(
528            restate.invocation.id = self.debug_invocation_id(),
529            restate.protocol.state = self.debug_state(),
530            restate.journal.command_index = self.context.journal.command_index(),
531            restate.protocol.version = %self.version
532        ),
533        ret
534    )]
535    fn sys_input(&mut self) -> Result<Input, Error> {
536        self.do_transition(SysInput)
537    }
538
539    #[instrument(
540        level = "trace",
541        skip(self),
542        fields(
543            restate.invocation.id = self.debug_invocation_id(),
544            restate.protocol.state = self.debug_state(),
545            restate.journal.command_index = self.context.journal.command_index(),
546            restate.protocol.version = %self.version
547        ),
548        ret
549    )]
550    fn sys_state_get(&mut self, key: String) -> Result<NotificationHandle, Error> {
551        invocation_debug_logs!(self, "Executing 'Get state {key}'");
552        self.do_transition(SysStateGet(key))
553    }
554
555    #[instrument(
556        level = "trace",
557        skip(self),
558        fields(
559            restate.invocation.id = self.debug_invocation_id(),
560            restate.protocol.state = self.debug_state(),
561            restate.journal.command_index = self.context.journal.command_index(),
562            restate.protocol.version = %self.version
563        ),
564        ret
565    )]
566    fn sys_state_get_keys(&mut self) -> VMResult<NotificationHandle> {
567        invocation_debug_logs!(self, "Executing 'Get state keys'");
568        self.do_transition(SysStateGetKeys)
569    }
570
571    #[instrument(
572        level = "trace",
573        skip(self, value),
574        fields(
575            restate.invocation.id = self.debug_invocation_id(),
576            restate.protocol.state = self.debug_state(),
577            restate.journal.command_index = self.context.journal.command_index(),
578            restate.protocol.version = %self.version
579        ),
580        ret
581    )]
582    fn sys_state_set(&mut self, key: String, value: Bytes) -> Result<(), Error> {
583        invocation_debug_logs!(self, "Executing 'Set state {key}'");
584        self.context.eager_state.set(key.clone(), value.clone());
585        self.do_transition(SysNonCompletableEntry(
586            "SysStateSet",
587            SetStateCommandMessage {
588                key: Bytes::from(key.into_bytes()),
589                value: Some(value.into()),
590                ..SetStateCommandMessage::default()
591            },
592        ))
593    }
594
595    #[instrument(
596        level = "trace",
597        skip(self),
598        fields(
599            restate.invocation.id = self.debug_invocation_id(),
600            restate.protocol.state = self.debug_state(),
601            restate.journal.command_index = self.context.journal.command_index(),
602            restate.protocol.version = %self.version
603        ),
604        ret
605    )]
606    fn sys_state_clear(&mut self, key: String) -> Result<(), Error> {
607        invocation_debug_logs!(self, "Executing 'Clear state {key}'");
608        self.context.eager_state.clear(key.clone());
609        self.do_transition(SysNonCompletableEntry(
610            "SysStateClear",
611            ClearStateCommandMessage {
612                key: Bytes::from(key.into_bytes()),
613                ..ClearStateCommandMessage::default()
614            },
615        ))
616    }
617
618    #[instrument(
619        level = "trace",
620        skip(self),
621        fields(
622            restate.invocation.id = self.debug_invocation_id(),
623            restate.protocol.state = self.debug_state(),
624            restate.journal.command_index = self.context.journal.command_index(),
625            restate.protocol.version = %self.version
626        ),
627        ret
628    )]
629    fn sys_state_clear_all(&mut self) -> Result<(), Error> {
630        invocation_debug_logs!(self, "Executing 'Clear all state'");
631        self.context.eager_state.clear_all();
632        self.do_transition(SysNonCompletableEntry(
633            "SysStateClearAll",
634            ClearAllStateCommandMessage::default(),
635        ))
636    }
637
638    #[instrument(
639        level = "trace",
640        skip(self),
641        fields(
642            restate.invocation.id = self.debug_invocation_id(),
643            restate.protocol.state = self.debug_state(),
644            restate.journal.command_index = self.context.journal.command_index(),
645            restate.protocol.version = %self.version
646        ),
647        ret
648    )]
649    fn sys_sleep(
650        &mut self,
651        name: String,
652        wake_up_time_since_unix_epoch: Duration,
653        now_since_unix_epoch: Option<Duration>,
654    ) -> VMResult<NotificationHandle> {
655        if self.is_processing() {
656            match (&name, now_since_unix_epoch) {
657                (name, Some(now_since_unix_epoch)) if name.is_empty() => {
658                    debug!(
659                        "Executing 'Timer with duration {:?}'",
660                        wake_up_time_since_unix_epoch - now_since_unix_epoch
661                    );
662                }
663                (name, Some(now_since_unix_epoch)) => {
664                    debug!(
665                        "Executing 'Timer {name} with duration {:?}'",
666                        wake_up_time_since_unix_epoch - now_since_unix_epoch
667                    );
668                }
669                (name, None) if name.is_empty() => {
670                    debug!("Executing 'Timer'");
671                }
672                (name, None) => {
673                    debug!("Executing 'Timer named {name}'");
674                }
675            }
676        }
677
678        let completion_id = self.context.journal.next_completion_notification_id();
679
680        self.do_transition(SysSimpleCompletableEntry(
681            "SysSleep",
682            SleepCommandMessage {
683                wake_up_time: u64::try_from(wake_up_time_since_unix_epoch.as_millis())
684                    .expect("millis since Unix epoch should fit in u64"),
685                result_completion_id: completion_id,
686                name,
687            },
688            completion_id,
689        ))
690    }
691
692    #[instrument(
693        level = "trace",
694        skip(self, input),
695        fields(
696            restate.invocation.id = self.debug_invocation_id(),
697            restate.protocol.state = self.debug_state(),
698            restate.journal.command_index = self.context.journal.command_index(),
699            restate.protocol.version = %self.version
700        ),
701        ret
702    )]
703    fn sys_call(&mut self, target: Target, input: Bytes) -> VMResult<CallHandle> {
704        invocation_debug_logs!(
705            self,
706            "Executing 'Call {}/{}'",
707            target.service,
708            target.handler
709        );
710        if let Some(idempotency_key) = &target.idempotency_key {
711            self.verify_feature_support("attach idempotency key to call", Version::V3)?;
712            if idempotency_key.is_empty() {
713                self.do_transition(HitError(EMPTY_IDEMPOTENCY_KEY))?;
714                unreachable!();
715            }
716        }
717
718        let call_invocation_id_completion_id =
719            self.context.journal.next_completion_notification_id();
720        let result_completion_id = self.context.journal.next_completion_notification_id();
721
722        let handles = self.do_transition(SysCompletableEntryWithMultipleCompletions(
723            "SysCall",
724            CallCommandMessage {
725                service_name: target.service,
726                handler_name: target.handler,
727                key: target.key.unwrap_or_default(),
728                idempotency_key: target.idempotency_key,
729                headers: target
730                    .headers
731                    .into_iter()
732                    .map(crate::service_protocol::messages::Header::from)
733                    .collect(),
734                parameter: input,
735                invocation_id_notification_idx: call_invocation_id_completion_id,
736                result_completion_id,
737                ..Default::default()
738            },
739            vec![call_invocation_id_completion_id, result_completion_id],
740        ))?;
741
742        if matches!(
743            self.options.implicit_cancellation,
744            ImplicitCancellationOption::Enabled {
745                cancel_children_calls: true,
746                ..
747            }
748        ) {
749            self.tracked_invocation_ids.push(TrackedInvocationId {
750                handle: handles[0],
751                invocation_id: None,
752            })
753        }
754
755        Ok(CallHandle {
756            invocation_id_notification_handle: handles[0],
757            call_notification_handle: handles[1],
758        })
759    }
760
761    #[instrument(
762        level = "trace",
763        skip(self, input),
764        fields(
765            restate.invocation.id = self.debug_invocation_id(),
766            restate.protocol.state = self.debug_state(),
767            restate.journal.command_index = self.context.journal.command_index(),
768            restate.protocol.version = %self.version
769        ),
770        ret
771    )]
772    fn sys_send(
773        &mut self,
774        target: Target,
775        input: Bytes,
776        delay: Option<Duration>,
777    ) -> VMResult<SendHandle> {
778        invocation_debug_logs!(
779            self,
780            "Executing 'Send to {}/{}'",
781            target.service,
782            target.handler
783        );
784        if let Some(idempotency_key) = &target.idempotency_key {
785            self.verify_feature_support("attach idempotency key to one way call", Version::V3)?;
786            if idempotency_key.is_empty() {
787                self.do_transition(HitError(EMPTY_IDEMPOTENCY_KEY))?;
788                unreachable!();
789            }
790        }
791        let call_invocation_id_completion_id =
792            self.context.journal.next_completion_notification_id();
793        let invocation_id_notification_handle = self.do_transition(SysSimpleCompletableEntry(
794            "SysOneWayCall",
795            OneWayCallCommandMessage {
796                service_name: target.service,
797                handler_name: target.handler,
798                key: target.key.unwrap_or_default(),
799                idempotency_key: target.idempotency_key,
800                headers: target
801                    .headers
802                    .into_iter()
803                    .map(crate::service_protocol::messages::Header::from)
804                    .collect(),
805                parameter: input,
806                invoke_time: delay
807                    .map(|d| {
808                        u64::try_from(d.as_millis())
809                            .expect("millis since Unix epoch should fit in u64")
810                    })
811                    .unwrap_or_default(),
812                invocation_id_notification_idx: call_invocation_id_completion_id,
813                ..Default::default()
814            },
815            call_invocation_id_completion_id,
816        ))?;
817
818        if matches!(
819            self.options.implicit_cancellation,
820            ImplicitCancellationOption::Enabled {
821                cancel_children_one_way_calls: true,
822                ..
823            }
824        ) {
825            self.tracked_invocation_ids.push(TrackedInvocationId {
826                handle: invocation_id_notification_handle,
827                invocation_id: None,
828            })
829        }
830
831        Ok(SendHandle {
832            invocation_id_notification_handle,
833        })
834    }
835
836    #[instrument(
837        level = "trace",
838        skip(self),
839        fields(
840            restate.invocation.id = self.debug_invocation_id(),
841            restate.protocol.state = self.debug_state(),
842            restate.journal.command_index = self.context.journal.command_index(),
843            restate.protocol.version = %self.version
844        ),
845        ret
846    )]
847    fn sys_awakeable(&mut self) -> VMResult<(String, NotificationHandle)> {
848        invocation_debug_logs!(self, "Executing 'Create awakeable'");
849
850        let signal_id = self.context.journal.next_signal_notification_id();
851
852        let handle = self.do_transition(CreateSignalHandle(
853            "SysAwakeable",
854            NotificationId::SignalId(signal_id),
855        ))?;
856
857        Ok((
858            awakeable_id_str(&self.context.expect_start_info().id, signal_id),
859            handle,
860        ))
861    }
862
863    #[instrument(
864        level = "trace",
865        skip(self, value),
866        fields(
867            restate.invocation.id = self.debug_invocation_id(),
868            restate.protocol.state = self.debug_state(),
869            restate.journal.command_index = self.context.journal.command_index(),
870            restate.protocol.version = %self.version
871        ),
872        ret
873    )]
874    fn sys_complete_awakeable(&mut self, id: String, value: NonEmptyValue) -> VMResult<()> {
875        invocation_debug_logs!(self, "Executing 'Complete awakeable {id}'");
876        self.do_transition(SysNonCompletableEntry(
877            "SysCompleteAwakeable",
878            CompleteAwakeableCommandMessage {
879                awakeable_id: id,
880                result: Some(match value {
881                    NonEmptyValue::Success(s) => {
882                        complete_awakeable_command_message::Result::Value(s.into())
883                    }
884                    NonEmptyValue::Failure(f) => {
885                        complete_awakeable_command_message::Result::Failure(f.into())
886                    }
887                }),
888                ..Default::default()
889            },
890        ))
891    }
892
893    #[instrument(
894        level = "trace",
895        skip(self),
896        fields(
897            restate.invocation.id = self.debug_invocation_id(),
898            restate.protocol.state = self.debug_state(),
899            restate.journal.command_index = self.context.journal.command_index(),
900            restate.protocol.version = %self.version
901        ),
902        ret
903    )]
904    fn create_signal_handle(&mut self, signal_name: String) -> VMResult<NotificationHandle> {
905        invocation_debug_logs!(self, "Executing 'Create named signal'");
906
907        self.do_transition(CreateSignalHandle(
908            "SysCreateNamedSignal",
909            NotificationId::SignalName(signal_name),
910        ))
911    }
912
913    #[instrument(
914        level = "trace",
915        skip(self, value),
916        fields(
917            restate.invocation.id = self.debug_invocation_id(),
918            restate.protocol.state = self.debug_state(),
919            restate.journal.command_index = self.context.journal.command_index(),
920            restate.protocol.version = %self.version
921        ),
922        ret
923    )]
924    fn sys_complete_signal(
925        &mut self,
926        target_invocation_id: String,
927        signal_name: String,
928        value: NonEmptyValue,
929    ) -> VMResult<()> {
930        invocation_debug_logs!(self, "Executing 'Complete named signal {signal_name}'");
931        self.do_transition(SysNonCompletableEntry(
932            "SysCompleteAwakeable",
933            SendSignalCommandMessage {
934                target_invocation_id,
935                signal_id: Some(send_signal_command_message::SignalId::Name(signal_name)),
936                result: Some(match value {
937                    NonEmptyValue::Success(s) => {
938                        send_signal_command_message::Result::Value(s.into())
939                    }
940                    NonEmptyValue::Failure(f) => {
941                        send_signal_command_message::Result::Failure(f.into())
942                    }
943                }),
944                ..Default::default()
945            },
946        ))
947    }
948
949    #[instrument(
950        level = "trace",
951        skip(self),
952        fields(
953            restate.invocation.id = self.debug_invocation_id(),
954            restate.protocol.state = self.debug_state(),
955            restate.journal.command_index = self.context.journal.command_index(),
956            restate.protocol.version = %self.version
957        ),
958        ret
959    )]
960    fn sys_get_promise(&mut self, key: String) -> VMResult<NotificationHandle> {
961        invocation_debug_logs!(self, "Executing 'Await promise {key}'");
962
963        let result_completion_id = self.context.journal.next_completion_notification_id();
964        self.do_transition(SysSimpleCompletableEntry(
965            "SysGetPromise",
966            GetPromiseCommandMessage {
967                key,
968                result_completion_id,
969                ..Default::default()
970            },
971            result_completion_id,
972        ))
973    }
974
975    #[instrument(
976        level = "trace",
977        skip(self),
978        fields(
979            restate.invocation.id = self.debug_invocation_id(),
980            restate.protocol.state = self.debug_state(),
981            restate.journal.command_index = self.context.journal.command_index(),
982            restate.protocol.version = %self.version
983        ),
984        ret
985    )]
986    fn sys_peek_promise(&mut self, key: String) -> VMResult<NotificationHandle> {
987        invocation_debug_logs!(self, "Executing 'Peek promise {key}'");
988
989        let result_completion_id = self.context.journal.next_completion_notification_id();
990        self.do_transition(SysSimpleCompletableEntry(
991            "SysPeekPromise",
992            PeekPromiseCommandMessage {
993                key,
994                result_completion_id,
995                ..Default::default()
996            },
997            result_completion_id,
998        ))
999    }
1000
1001    #[instrument(
1002        level = "trace",
1003        skip(self, value),
1004        fields(
1005            restate.invocation.id = self.debug_invocation_id(),
1006            restate.protocol.state = self.debug_state(),
1007            restate.journal.command_index = self.context.journal.command_index(),
1008            restate.protocol.version = %self.version
1009        ),
1010        ret
1011    )]
1012    fn sys_complete_promise(
1013        &mut self,
1014        key: String,
1015        value: NonEmptyValue,
1016    ) -> VMResult<NotificationHandle> {
1017        invocation_debug_logs!(self, "Executing 'Complete promise {key}'");
1018
1019        let result_completion_id = self.context.journal.next_completion_notification_id();
1020        self.do_transition(SysSimpleCompletableEntry(
1021            "SysCompletePromise",
1022            CompletePromiseCommandMessage {
1023                key,
1024                completion: Some(match value {
1025                    NonEmptyValue::Success(s) => {
1026                        complete_promise_command_message::Completion::CompletionValue(s.into())
1027                    }
1028                    NonEmptyValue::Failure(f) => {
1029                        complete_promise_command_message::Completion::CompletionFailure(f.into())
1030                    }
1031                }),
1032                result_completion_id,
1033                ..Default::default()
1034            },
1035            result_completion_id,
1036        ))
1037    }
1038
1039    #[instrument(
1040        level = "trace",
1041        skip(self),
1042        fields(
1043            restate.invocation.id = self.debug_invocation_id(),
1044            restate.protocol.state = self.debug_state(),
1045            restate.journal.command_index = self.context.journal.command_index(),
1046            restate.protocol.version = %self.version
1047        ),
1048        ret
1049    )]
1050    fn sys_run(&mut self, name: String) -> VMResult<NotificationHandle> {
1051        match self.do_transition(SysRun(name.clone())) {
1052            Ok(handle) => {
1053                if enabled!(Level::DEBUG) {
1054                    // Store the name, we need it later when completing
1055                    self.sys_run_names.insert(handle, name);
1056                }
1057                Ok(handle)
1058            }
1059            Err(e) => Err(e),
1060        }
1061    }
1062
1063    #[instrument(
1064        level = "trace",
1065        skip(self, value, retry_policy),
1066        fields(
1067            restate.invocation.id = self.debug_invocation_id(),
1068            restate.protocol.state = self.debug_state(),
1069            restate.journal.command_index = self.context.journal.command_index(),
1070            restate.protocol.version = %self.version
1071        ),
1072        ret
1073    )]
1074    fn propose_run_completion(
1075        &mut self,
1076        notification_handle: NotificationHandle,
1077        value: RunExitResult,
1078        retry_policy: RetryPolicy,
1079    ) -> VMResult<()> {
1080        if enabled!(Level::DEBUG) {
1081            let name: &str = self
1082                .sys_run_names
1083                .get(&notification_handle)
1084                .map(String::as_str)
1085                .unwrap_or_default();
1086            match &value {
1087                RunExitResult::Success(_) => {
1088                    invocation_debug_logs!(self, "Journaling run '{name}' success result");
1089                }
1090                RunExitResult::TerminalFailure(TerminalFailure { code, .. }) => {
1091                    invocation_debug_logs!(
1092                        self,
1093                        "Journaling run '{name}' terminal failure {code} result"
1094                    );
1095                }
1096                RunExitResult::RetryableFailure { .. } => {
1097                    invocation_debug_logs!(self, "Propagating run '{name}' retryable failure");
1098                }
1099            }
1100        }
1101
1102        self.do_transition(ProposeRunCompletion(
1103            notification_handle,
1104            value,
1105            retry_policy,
1106        ))
1107    }
1108
1109    #[instrument(
1110        level = "trace",
1111        skip(self),
1112        fields(
1113            restate.invocation.id = self.debug_invocation_id(),
1114            restate.protocol.state = self.debug_state(),
1115            restate.journal.command_index = self.context.journal.command_index(),
1116            restate.protocol.version = %self.version
1117        ),
1118        ret
1119    )]
1120    fn sys_cancel_invocation(&mut self, target_invocation_id: String) -> VMResult<()> {
1121        invocation_debug_logs!(
1122            self,
1123            "Executing 'Cancel invocation' of {target_invocation_id}"
1124        );
1125        self.verify_feature_support("cancel invocation", Version::V3)?;
1126        self.do_transition(SysNonCompletableEntry(
1127            "SysCancelInvocation",
1128            SendSignalCommandMessage {
1129                target_invocation_id,
1130                signal_id: Some(send_signal_command_message::SignalId::Idx(CANCEL_SIGNAL_ID)),
1131                result: Some(send_signal_command_message::Result::Void(Default::default())),
1132                ..Default::default()
1133            },
1134        ))
1135    }
1136
1137    #[instrument(
1138        level = "trace",
1139        skip(self),
1140        fields(
1141            restate.invocation.id = self.debug_invocation_id(),
1142            restate.protocol.state = self.debug_state(),
1143            restate.journal.command_index = self.context.journal.command_index(),
1144            restate.protocol.version = %self.version
1145        ),
1146        ret
1147    )]
1148    fn sys_attach_invocation(
1149        &mut self,
1150        target: AttachInvocationTarget,
1151    ) -> VMResult<NotificationHandle> {
1152        invocation_debug_logs!(self, "Executing 'Attach invocation'");
1153        self.verify_feature_support("attach invocation", Version::V3)?;
1154
1155        let result_completion_id = self.context.journal.next_completion_notification_id();
1156        self.do_transition(SysSimpleCompletableEntry(
1157            "SysAttachInvocation",
1158            AttachInvocationCommandMessage {
1159                target: Some(match target {
1160                    AttachInvocationTarget::InvocationId(id) => {
1161                        attach_invocation_command_message::Target::InvocationId(id)
1162                    }
1163                    AttachInvocationTarget::WorkflowId { name, key } => {
1164                        attach_invocation_command_message::Target::WorkflowTarget(WorkflowTarget {
1165                            workflow_name: name,
1166                            workflow_key: key,
1167                        })
1168                    }
1169                    AttachInvocationTarget::IdempotencyId {
1170                        service_name,
1171                        service_key,
1172                        handler_name,
1173                        idempotency_key,
1174                    } => attach_invocation_command_message::Target::IdempotentRequestTarget(
1175                        IdempotentRequestTarget {
1176                            service_name,
1177                            service_key,
1178                            handler_name,
1179                            idempotency_key,
1180                        },
1181                    ),
1182                }),
1183                result_completion_id,
1184                ..Default::default()
1185            },
1186            result_completion_id,
1187        ))
1188    }
1189
1190    #[instrument(
1191        level = "trace",
1192        skip(self),
1193        fields(
1194            restate.invocation.id = self.debug_invocation_id(),
1195            restate.protocol.state = self.debug_state(),
1196            restate.journal.command_index = self.context.journal.command_index(),
1197            restate.protocol.version = %self.version
1198        ),
1199        ret
1200    )]
1201    fn sys_get_invocation_output(
1202        &mut self,
1203        target: AttachInvocationTarget,
1204    ) -> VMResult<NotificationHandle> {
1205        invocation_debug_logs!(self, "Executing 'Get invocation output'");
1206        self.verify_feature_support("get invocation output", Version::V3)?;
1207
1208        let result_completion_id = self.context.journal.next_completion_notification_id();
1209        self.do_transition(SysSimpleCompletableEntry(
1210            "SysGetInvocationOutput",
1211            GetInvocationOutputCommandMessage {
1212                target: Some(match target {
1213                    AttachInvocationTarget::InvocationId(id) => {
1214                        get_invocation_output_command_message::Target::InvocationId(id)
1215                    }
1216                    AttachInvocationTarget::WorkflowId { name, key } => {
1217                        get_invocation_output_command_message::Target::WorkflowTarget(
1218                            WorkflowTarget {
1219                                workflow_name: name,
1220                                workflow_key: key,
1221                            },
1222                        )
1223                    }
1224                    AttachInvocationTarget::IdempotencyId {
1225                        service_name,
1226                        service_key,
1227                        handler_name,
1228                        idempotency_key,
1229                    } => get_invocation_output_command_message::Target::IdempotentRequestTarget(
1230                        IdempotentRequestTarget {
1231                            service_name,
1232                            service_key,
1233                            handler_name,
1234                            idempotency_key,
1235                        },
1236                    ),
1237                }),
1238                result_completion_id,
1239                ..Default::default()
1240            },
1241            result_completion_id,
1242        ))
1243    }
1244
1245    #[instrument(
1246        level = "trace",
1247        skip(self, value),
1248        fields(
1249            restate.invocation.id = self.debug_invocation_id(),
1250            restate.protocol.state = self.debug_state(),
1251            restate.journal.command_index = self.context.journal.command_index(),
1252            restate.protocol.version = %self.version
1253        ),
1254        ret
1255    )]
1256    fn sys_write_output(&mut self, value: NonEmptyValue) -> Result<(), Error> {
1257        match &value {
1258            NonEmptyValue::Success(_) => {
1259                invocation_debug_logs!(self, "Writing invocation result success value");
1260            }
1261            NonEmptyValue::Failure(_) => {
1262                invocation_debug_logs!(self, "Writing invocation result failure value");
1263            }
1264        }
1265        self.do_transition(SysNonCompletableEntry(
1266            "SysWriteOutput",
1267            OutputCommandMessage {
1268                result: Some(match value {
1269                    NonEmptyValue::Success(b) => output_command_message::Result::Value(b.into()),
1270                    NonEmptyValue::Failure(f) => output_command_message::Result::Failure(f.into()),
1271                }),
1272                ..OutputCommandMessage::default()
1273            },
1274        ))
1275    }
1276
1277    #[instrument(
1278        level = "trace",
1279        skip(self),
1280        fields(
1281            restate.invocation.id = self.debug_invocation_id(),
1282            restate.protocol.state = self.debug_state(),
1283            restate.journal.command_index = self.context.journal.command_index(),
1284            restate.protocol.version = %self.version
1285        ),
1286        ret
1287    )]
1288    fn sys_end(&mut self) -> Result<(), Error> {
1289        invocation_debug_logs!(self, "End of the invocation");
1290        self.do_transition(SysEnd)
1291    }
1292
1293    fn is_waiting_preflight(&self) -> bool {
1294        matches!(
1295            &self.last_transition,
1296            Ok(State::WaitingStart) | Ok(State::WaitingReplayEntries { .. })
1297        )
1298    }
1299
1300    fn is_replaying(&self) -> bool {
1301        matches!(&self.last_transition, Ok(State::Replaying { .. }))
1302    }
1303
1304    fn is_processing(&self) -> bool {
1305        matches!(&self.last_transition, Ok(State::Processing { .. }))
1306    }
1307
1308    fn last_command_index(&self) -> i64 {
1309        self.context.journal.command_index()
1310    }
1311}
1312
1313const INDIFFERENT_PAD: GeneralPurposeConfig = GeneralPurposeConfig::new()
1314    .with_decode_padding_mode(DecodePaddingMode::Indifferent)
1315    .with_encode_padding(false);
1316const URL_SAFE: GeneralPurpose = GeneralPurpose::new(&alphabet::URL_SAFE, INDIFFERENT_PAD);
1317
1318const AWAKEABLE_PREFIX: &str = "sign_1";
1319
1320fn awakeable_id_str(id: &[u8], completion_index: u32) -> String {
1321    let mut input_buf = BytesMut::with_capacity(id.len() + size_of::<u32>());
1322    input_buf.put_slice(id);
1323    input_buf.put_u32(completion_index);
1324    format!("{AWAKEABLE_PREFIX}{}", URL_SAFE.encode(input_buf.freeze()))
1325}