-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvocation.ex
More file actions
1751 lines (1506 loc) · 66.1 KB
/
invocation.ex
File metadata and controls
1751 lines (1506 loc) · 66.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule Restate.Server.Invocation do
@moduledoc """
One process per HTTP invocation. Implements the V5/V6 state machine:
`:replaying` while there are recorded journal commands to consume,
`:processing` once the handler has caught up to the head of the journal.
V5 and V6 share the same command/notification wire shape; V6 adds
`StartMessage.random_seed` (used to seed `:rand` in the handler
process for `Restate.Context.random_*`) and an official
`Failure.metadata` field (already supported under V5).
## Lifecycle
Endpoint → Invocation.start_link({start, input, replay_journal, mfa, dispatch_meta})
├─ Invocation partitions the post-Input replay frames:
│ • recorded_commands (Set/Sleep/Output/...) — in order
│ • notifications — %{completion_id => :void | term}
├─ Invocation spawns the user handler in a linked process,
│ passing it a `Restate.Context` whose pid is the Invocation
├─ Each Context call (`get_state`, `set_state`, `sleep`) is a
│ synchronous GenServer.call:
│ • In :replaying — pop the next recorded command, validate
│ its type, do NOT re-emit. For completable commands
│ (Sleep): if the matching completion is in the table,
│ reply :ok. Otherwise, suspend.
│ • In :processing — emit a fresh command. For completable
│ commands without local completion, suspend immediately
│ (REQUEST_RESPONSE mode — no completions arrive on this
│ stream).
└─ Handler returns / raises / process is killed → finalize the
framed response (Output|Error|Suspension + optional End)
## Suspension
When the handler blocks on a completable command whose result we don't
have, we emit a `SuspensionMessage{ waiting_completions: [id] }`,
terminate the handler process, and close the response without an
`EndMessage`. The runtime persists the journal so far and re-invokes
later when the completion arrives.
"""
use GenServer
alias Dev.Restate.Service.Protocol, as: Pb
alias Restate.Protocol.{Frame, Framer}
@doc """
Start an invocation.
`replay_journal` is the list of `%Restate.Protocol.Frame{}` entries
after the leading `StartMessage` and `InputCommandMessage` — i.e. the
recorded journal the runtime is replaying.
`mfa` is `{module, function, arity}` — the function is called with
`(%Restate.Context{}, input_value)`.
`dispatch_meta` is a `%{service: binary(), handler: binary()}` map
used as `:telemetry` metadata. Pass `%{}` from non-HTTP contexts
(tests) when the values aren't meaningful.
"""
@spec start_link(
{Pb.StartMessage.t(), term(), [Frame.t()], {module(), atom(), arity()}, map()}
) :: GenServer.on_start()
def start_link(
{%Pb.StartMessage{}, _input, replay_journal, _mfa, dispatch_meta} = arg
)
when is_list(replay_journal) and is_map(dispatch_meta) do
GenServer.start_link(__MODULE__, arg)
end
@typedoc """
Outcome tag returned by `await_response/2`. `:value` and
`:terminal_failure` are normal handler completions (the latter with
an `OutputCommandMessage{failure}` body); `:error` is a generic
exception that escaped the handler; `:suspended` means the runtime
must re-invoke us when a completion arrives; `:journal_mismatch` is
protocol code 570.
"""
@type outcome ::
:value | :terminal_failure | :error | :suspended | :journal_mismatch
@doc """
Block until the handler completes (or suspends, or raises) and return
`{outcome, framed_response_body}`. Stops the invocation process on
return.
"""
@spec await_response(pid(), timeout()) :: {outcome(), binary()}
def await_response(pid, timeout \\ 30_000) do
GenServer.call(pid, :await_response, timeout)
end
# --- GenServer ---
@impl true
def init({%Pb.StartMessage{} = start, input, replay_journal, mfa, dispatch_meta}) do
%Pb.StartMessage{
id: start_message_id,
state_map: state_entries,
key: object_key,
partial_state: partial_state?,
# `random_seed` is a V6 addition (`uint64`, field 9). Under V5
# the runtime leaves it at the default 0; under V6 it carries
# a stable per-invocation seed used to seed the handler
# process's `:rand` state so `Restate.Context.random_*` is
# deterministic across replays.
random_seed: random_seed
} = start
state_map =
for %Pb.StartMessage.StateEntry{key: k, value: v} <- state_entries, into: %{} do
{k, v}
end
{recorded_commands, notifications, signal_notifications, cancelled?} =
partition_journal(replay_journal)
initial_completion_id = max_completion_id_seen(replay_journal) + 1
# Signal ids are allocator-deterministic: every replay must reproduce
# the same signal_id sequence as the first execution. Java's
# Journal.signalIndex resets to 17 on every invocation; we do the
# same. (1–16 are reserved for built-in signals like cancel.)
# Don't seed from the journal — the journal's signal notifications
# are the *result* of allocations, not their source of truth.
initial_signal_id = 17
# Register with the DrainCoordinator so SIGTERM-triggered drain can
# wait for us to finish before stopping the BEAM. No-op when the
# coordinator isn't running (e.g. in test envs that don't boot it).
Restate.Server.DrainCoordinator.register(self())
parent = self()
handler_pid =
spawn_link(fn ->
# Seed `:rand` in the handler process so `Restate.Context.random_*`
# produces the same stream on every replay (`random_seed` is
# the same in every StartMessage for this invocation under V6).
# Under V5 the seed is 0 and we skip seeding — `Context.random_*`
# callers will still get *a* number, but it'll be the BEAM's
# default non-deterministic seed and replays will diverge. The
# SDK README documents that `Context.random_*` requires V6.
if is_integer(random_seed) and random_seed > 0 do
:rand.seed(:exsss, random_seed)
end
ctx = %Restate.Context{pid: parent, key: object_key || ""}
{mod, fun, _arity} = mfa
result =
try do
{:ok, apply(mod, fun, [ctx, input])}
rescue
e -> {:error, e, __STACKTRACE__}
end
send(parent, {:handler_result, result})
end)
phase = if recorded_commands == [], do: :processing, else: :replaying
{:ok,
%{
phase: phase,
# Snapshotted at init so `:replay_complete` can report how many
# recorded commands existed when this invocation started.
replay_journal_size: length(recorded_commands),
# Flipped to true the one time `advance_phase/1` transitions us
# from `:replaying` to `:processing`. Reported in the `:stop`
# event metadata so dashboards can distinguish first-run from
# resumption invocations.
replay_phase_completed?: false,
# `%{service: binary, handler: binary}` for telemetry metadata.
# Endpoint populates it; tests may pass `%{}` when service /
# handler don't matter.
dispatch_meta: dispatch_meta,
# Set at every `finalize/3` site to one of the values in the
# `outcome` typedoc. Returned alongside the wire body from
# `await_response/2` and reported in `:stop` event metadata.
outcome: nil,
state_map: state_map,
# `StartMessage.partial_state` true means the runtime did not
# bundle every state value into the eager `state_map` —
# missing keys must be fetched via `GetLazyStateCommandMessage`.
# `nil` in `state_map` is the "fetched and absent" / "cleared"
# sentinel; `Map.fetch/2` distinguishes it from missing-from-map.
partial_state?: partial_state?,
state_keys_cache: nil,
start_id: start_message_id,
recorded_commands: recorded_commands,
notifications: notifications,
signal_notifications: signal_notifications,
next_completion_id: initial_completion_id,
next_signal_id: initial_signal_id,
# Built-in CANCEL signal (signal_id = 1, per BuiltInSignal in
# protocol.proto:670). Once true, every subsequent suspending
# Context op raises Restate.TerminalError{code: 409}. Mirrors
# Java's `AsyncResultsState` reserving NotificationHandle 1 for
# the cancel signal.
cancelled?: cancelled?,
emitted: [],
# Tracking for ErrorMessage.related_command_* fields (mirrors
# Java's Journal.lastCommandMetadata). Index starts at -1
# meaning "no command processed yet"; advances on each
# consume_command/2 call (replay or fresh emit).
current_command: %{index: -1, name: nil, type: nil},
awaiting_response: nil,
result_body: nil,
handler_pid: handler_pid
}}
end
@impl true
def handle_call({:get_state, key}, from, state) do
case Map.fetch(state.state_map, key) do
{:ok, nil} ->
# Sentinel: explicitly cleared in this invocation, OR previously
# lazy-fetched and confirmed absent.
{:reply, nil, state}
{:ok, bytes} when is_binary(bytes) ->
{:reply, bytes, state}
:error ->
if state.partial_state? do
do_lazy_get_state(state, key, from)
else
# Eager state is the source of truth — missing means absent.
{:reply, nil, state}
end
end
end
@impl true
def handle_call({:set_state, key, value_bytes}, from, state) do
cmd = %Pb.SetStateCommandMessage{key: key, value: %Pb.Value{content: value_bytes}}
state = %{state | state_map: Map.put(state.state_map, key, value_bytes)}
case state.phase do
:replaying ->
# In replay we do NOT re-emit; we only consume the next recorded
# command and validate it's a SetStateCommandMessage.
with {:ok, {recorded, rest}} <- pop_recorded(state.recorded_commands, Pb.SetStateCommandMessage) do
state = state |> Map.put(:recorded_commands, rest) |> track_command(recorded)
{:reply, :ok, advance_phase(state)}
else
{:error, exc} -> finalize_journal_mismatch(state, exc, from)
end
:processing ->
state = state |> Map.update!(:emitted, &[cmd | &1]) |> track_command(cmd)
{:reply, :ok, state}
end
end
def handle_call(:clear_all_state, from, state) do
cmd = %Pb.ClearAllStateCommandMessage{}
# After clear_all the runtime has nothing — flip partial_state? to
# false so subsequent get_state returns nil locally without a wasted
# GetLazyStateCommand round-trip.
state = %{state | state_map: %{}, state_keys_cache: [], partial_state?: false}
case state.phase do
:replaying ->
with {:ok, {recorded, rest}} <- pop_recorded(state.recorded_commands, Pb.ClearAllStateCommandMessage) do
state = state |> Map.put(:recorded_commands, rest) |> track_command(recorded)
{:reply, :ok, advance_phase(state)}
else
{:error, exc} -> finalize_journal_mismatch(state, exc, from)
end
:processing ->
state = state |> Map.update!(:emitted, &[cmd | &1]) |> track_command(cmd)
{:reply, :ok, state}
end
end
def handle_call(:state_keys, from, state) do
cond do
state.partial_state? and state.state_keys_cache == nil ->
do_lazy_state_keys(state, from)
true ->
{:reply, current_state_keys(state), state}
end
end
def handle_call({:clear_state, key}, from, state) do
cmd = %Pb.ClearStateCommandMessage{key: key}
# nil sentinel = "explicitly cleared" — survives subsequent
# `get_state` without re-fetching from the runtime.
state = %{state | state_map: Map.put(state.state_map, key, nil)}
case state.phase do
:replaying ->
with {:ok, {recorded, rest}} <- pop_recorded(state.recorded_commands, Pb.ClearStateCommandMessage) do
state = state |> Map.put(:recorded_commands, rest) |> track_command(recorded)
{:reply, :ok, advance_phase(state)}
else
{:error, exc} -> finalize_journal_mismatch(state, exc, from)
end
:processing ->
state = state |> Map.update!(:emitted, &[cmd | &1]) |> track_command(cmd)
{:reply, :ok, state}
end
end
def handle_call({:call, target}, from, state) do
case state.phase do
:replaying ->
with {:ok, {recorded, rest}} <- pop_recorded(state.recorded_commands, Pb.CallCommandMessage) do
state = state |> Map.put(:recorded_commands, rest) |> track_command(recorded) |> advance_phase()
handle_call_result(state, recorded, from)
else
{:error, exc} -> finalize_journal_mismatch(state, exc, from)
end
:processing ->
cid_invok = state.next_completion_id
cid_result = cid_invok + 1
cmd = %Pb.CallCommandMessage{
service_name: target.service,
handler_name: target.handler,
parameter: target.parameter,
key: target.key || "",
idempotency_key: target.idempotency_key,
invocation_id_notification_idx: cid_invok,
result_completion_id: cid_result
}
state =
state
|> Map.update!(:emitted, &[cmd | &1])
|> Map.put(:next_completion_id, cid_result + 1)
|> track_command(cmd)
if state.cancelled? do
# No invocation_id available yet (the runtime hasn't started
# the callee), so we can't propagate cancel to it from here.
# The callee will appear on the next replay's journal; that
# replay won't re-emit this CallCommand though, so we'll
# never get the chance. Restate's runtime is responsible for
# not spawning callees of an already-failed invocation.
{:reply, {:terminal_error, cancellation_error()}, state}
else
# REQUEST_RESPONSE: the result notification arrives on a
# subsequent invocation, so we suspend on cid_result.
suspend(state, cid_result, from)
end
end
end
def handle_call({:send_async, target}, from, state) do
case state.phase do
:replaying ->
with {:ok, {recorded, rest}} <- pop_recorded(state.recorded_commands, Pb.OneWayCallCommandMessage) do
state = state |> Map.put(:recorded_commands, rest) |> track_command(recorded) |> advance_phase()
{:reply, :ok, state}
else
{:error, exc} -> finalize_journal_mismatch(state, exc, from)
end
:processing ->
cid_invok = state.next_completion_id
cmd = %Pb.OneWayCallCommandMessage{
service_name: target.service,
handler_name: target.handler,
parameter: target.parameter,
key: target.key || "",
idempotency_key: target.idempotency_key,
invoke_time: target.invoke_at_ms || 0,
invocation_id_notification_idx: cid_invok
}
state =
state
|> Map.update!(:emitted, &[cmd | &1])
|> Map.put(:next_completion_id, cid_invok + 1)
|> track_command(cmd)
# Fire-and-forget: do NOT suspend on the invocation_id
# notification. The notification will arrive in some future
# journal but we won't observe it. This is what makes
# high-concurrency fan-out viable — N send_asyncs cost N
# journal entries, not N HTTP round-trips.
{:reply, :ok, state}
end
end
def handle_call({:send, target}, from, state) do
case state.phase do
:replaying ->
with {:ok, {recorded, rest}} <- pop_recorded(state.recorded_commands, Pb.OneWayCallCommandMessage) do
state = state |> Map.put(:recorded_commands, rest) |> track_command(recorded) |> advance_phase()
handle_send_invocation_id(state, recorded.invocation_id_notification_idx, from)
else
{:error, exc} -> finalize_journal_mismatch(state, exc, from)
end
:processing ->
cid_invok = state.next_completion_id
cmd = %Pb.OneWayCallCommandMessage{
service_name: target.service,
handler_name: target.handler,
parameter: target.parameter,
key: target.key || "",
idempotency_key: target.idempotency_key,
invoke_time: target.invoke_at_ms || 0,
invocation_id_notification_idx: cid_invok
}
state =
state
|> Map.update!(:emitted, &[cmd | &1])
|> Map.put(:next_completion_id, cid_invok + 1)
|> track_command(cmd)
if state.cancelled? do
{:reply, {:terminal_error, cancellation_error()}, state}
else
# We block on the invocation_id notification so callers can
# use the spawned invocation's id (e.g. Proxy.oneWayCall
# returns it). REQUEST_RESPONSE mode: arrives on next replay.
suspend(state, cid_invok, from)
end
end
end
def handle_call(:awakeable, _from, state) do
# No journal entry — awakeables are pure signal_id allocations on
# the SDK side. The id encodes (start_message_id, signal_id) so
# external completers can route to us; we just need to remember
# which signal_id we allocated for the await.
signal_id = state.next_signal_id
awakeable_id = encode_awakeable_id(state.start_id, signal_id)
{:reply, {:ok, {awakeable_id, signal_id}},
%{state | next_signal_id: signal_id + 1}}
end
def handle_call({:await_awakeable, signal_id}, from, state) do
case Map.fetch(state.signal_notifications, signal_id) do
{:ok, {:value, %Pb.Value{content: bytes}}} ->
{:reply, {:ok, decode_response(bytes)}, state}
{:ok, {:failure, %Pb.Failure{code: code, message: message, metadata: meta}}} ->
exc = %Restate.TerminalError{
code: code,
message: message,
metadata: decode_failure_metadata(meta)
}
{:reply, {:terminal_error, exc}, state}
{:ok, _other} ->
# Void or other shapes — return nil to mirror "completed without payload".
{:reply, {:ok, nil}, state}
:error ->
# Awaiting a signal that hasn't fired. If we're cancelled, this
# is the await site that picks up the cancellation — mirrors
# Java's "cancel raises at the next blocking op." A handler
# that's already past every blocking op (or whose every blocking
# op already has a completion in the journal) is allowed to
# finish normally.
if state.cancelled? do
{:reply, {:terminal_error, cancellation_error()}, state}
else
# Suspend on the signal_id; SuspensionMessage carries it in
# `waiting_signals` rather than `waiting_completions`.
suspend_signal(state, signal_id, from)
end
end
end
def handle_call({:send_signal, target_invocation_id, signal_id}, from, state)
when is_binary(target_invocation_id) and is_integer(signal_id) do
cmd = %Pb.SendSignalCommandMessage{
target_invocation_id: target_invocation_id,
signal_id: {:idx, signal_id},
result: {:void, %Pb.Void{}}
}
case state.phase do
:replaying ->
with {:ok, {recorded, rest}} <-
pop_recorded(state.recorded_commands, Pb.SendSignalCommandMessage) do
state = state |> Map.put(:recorded_commands, rest) |> track_command(recorded)
{:reply, :ok, advance_phase(state)}
else
{:error, exc} -> finalize_journal_mismatch(state, exc, from)
end
:processing ->
# SendSignal is "Completable: No" per protocol.proto:482 — fire
# and forget, no completion ever arrives. We do not check
# cancellation here: a handler that's been cancelled mid-tree
# may still want to issue cancels to its children before
# exiting.
state = state |> Map.update!(:emitted, &[cmd | &1]) |> track_command(cmd)
{:reply, :ok, state}
end
end
def handle_call({:complete_awakeable, awakeable_id, completion}, from, state)
when is_binary(awakeable_id) do
cmd = build_complete_awakeable(awakeable_id, completion)
case state.phase do
:replaying ->
with {:ok, {recorded, rest}} <-
pop_recorded(state.recorded_commands, Pb.CompleteAwakeableCommandMessage) do
state = state |> Map.put(:recorded_commands, rest) |> track_command(recorded)
{:reply, :ok, advance_phase(state)}
else
{:error, exc} -> finalize_journal_mismatch(state, exc, from)
end
:processing ->
state = state |> Map.update!(:emitted, &[cmd | &1]) |> track_command(cmd)
{:reply, :ok, state}
end
end
def handle_call(:start_run, from, state) do
case state.phase do
:replaying ->
with {:ok, {recorded, rest}} <- pop_recorded(state.recorded_commands, Pb.RunCommandMessage) do
state = state |> Map.put(:recorded_commands, rest) |> track_command(recorded) |> advance_phase()
case Map.fetch(state.notifications, recorded.result_completion_id) do
{:ok, {:value, %Pb.Value{content: bytes}}} ->
# Replayed values stand even if cancel arrived this
# cycle — the side effect already happened in a previous
# invocation, the journal is the truth.
{:reply, {:replay_value, decode_response(bytes)}, state}
{:ok, {:failure, %Pb.Failure{code: code, message: message, metadata: meta}}} ->
metadata_map = decode_failure_metadata(meta)
exc = %Restate.TerminalError{code: code, message: message, metadata: metadata_map}
{:reply, {:replay_failure, exc}, state}
:error ->
# Run command in journal but no notification yet — the
# propose from a previous invocation didn't commit. Skip
# re-execution if cancelled so the side-effect doesn't
# run after the user asked us to stop.
if state.cancelled? do
{:reply, {:terminal_error, cancellation_error()}, state}
else
{:reply, {:execute, recorded.result_completion_id}, state}
end
end
else
{:error, exc} -> finalize_journal_mismatch(state, exc, from)
end
:processing ->
cid = state.next_completion_id
cmd = %Pb.RunCommandMessage{result_completion_id: cid}
state =
state
|> Map.update!(:emitted, &[cmd | &1])
|> Map.put(:next_completion_id, cid + 1)
|> track_command(cmd)
if state.cancelled? do
# Don't run the side-effecting function. The journal
# carries the RunCommand but no completion will arrive,
# which is fine — the invocation is terminating with
# OutputCommandMessage{failure} on the next pass.
{:reply, {:terminal_error, cancellation_error()}, state}
else
{:reply, {:execute, cid}, state}
end
end
end
# --- Workflow durable promises ---
#
# `promise_get` blocks the workflow on a named durable promise (the
# promise is keyed by the workflow's StartMessage.key implicitly;
# `name` here is the promise label within that key's namespace).
# `promise_peek` is a non-blocking probe — the runtime always
# responds, with Void if the promise is unresolved or Value/Failure
# if it is. `promise_complete` resolves the promise from another
# handler (typically a @Shared handler running on the same workflow
# key). All three follow the same suspend-on-completion shape as
# ctx.sleep / ctx.call in REQUEST_RESPONSE mode.
def handle_call({:promise_get, name}, from, state) when is_binary(name) do
case state.phase do
:replaying ->
with {:ok, {recorded, rest}} <-
pop_recorded(state.recorded_commands, Pb.GetPromiseCommandMessage) do
state = state |> Map.put(:recorded_commands, rest) |> track_command(recorded) |> advance_phase()
handle_promise_value_result(state, recorded.result_completion_id, from)
else
{:error, exc} -> finalize_journal_mismatch(state, exc, from)
end
:processing ->
cid = state.next_completion_id
cmd = %Pb.GetPromiseCommandMessage{key: name, result_completion_id: cid}
state =
state
|> Map.update!(:emitted, &[cmd | &1])
|> Map.put(:next_completion_id, cid + 1)
|> track_command(cmd)
if state.cancelled? do
{:reply, {:terminal_error, cancellation_error()}, state}
else
suspend(state, cid, from)
end
end
end
def handle_call({:promise_peek, name}, from, state) when is_binary(name) do
case state.phase do
:replaying ->
with {:ok, {recorded, rest}} <-
pop_recorded(state.recorded_commands, Pb.PeekPromiseCommandMessage) do
state = state |> Map.put(:recorded_commands, rest) |> track_command(recorded) |> advance_phase()
handle_promise_peek_result(state, recorded.result_completion_id, from)
else
{:error, exc} -> finalize_journal_mismatch(state, exc, from)
end
:processing ->
cid = state.next_completion_id
cmd = %Pb.PeekPromiseCommandMessage{key: name, result_completion_id: cid}
state =
state
|> Map.update!(:emitted, &[cmd | &1])
|> Map.put(:next_completion_id, cid + 1)
|> track_command(cmd)
if state.cancelled? do
{:reply, {:terminal_error, cancellation_error()}, state}
else
suspend(state, cid, from)
end
end
end
def handle_call({:promise_complete, name, completion}, from, state) when is_binary(name) do
cmd_for = fn cid ->
base = %Pb.CompletePromiseCommandMessage{key: name, result_completion_id: cid}
case completion do
{:value, bytes} when is_binary(bytes) ->
%{base | completion: {:completion_value, %Pb.Value{content: bytes}}}
{:failure, code, message} when is_integer(code) and is_binary(message) ->
%{base | completion: {:completion_failure, %Pb.Failure{code: code, message: message}}}
end
end
case state.phase do
:replaying ->
with {:ok, {recorded, rest}} <-
pop_recorded(state.recorded_commands, Pb.CompletePromiseCommandMessage) do
state = state |> Map.put(:recorded_commands, rest) |> track_command(recorded) |> advance_phase()
handle_promise_complete_result(state, recorded.result_completion_id, from)
else
{:error, exc} -> finalize_journal_mismatch(state, exc, from)
end
:processing ->
cid = state.next_completion_id
cmd = cmd_for.(cid)
state =
state
|> Map.update!(:emitted, &[cmd | &1])
|> Map.put(:next_completion_id, cid + 1)
|> track_command(cmd)
if state.cancelled? do
{:reply, {:terminal_error, cancellation_error()}, state}
else
suspend(state, cid, from)
end
end
end
# `propose_run_and_suspend` is the run-flush primitive. The SDK
# proposes the value/failure and immediately suspends on the run's
# `result_completion_id` — Restate stores the proposal as a
# `RunCompletionNotification`, then re-invokes us. On the next
# invocation the journal contains both the RunCommand and its
# completion, so the replay path returns `{:replay_value, _}` and
# the handler proceeds to the next op.
#
# This costs one HTTP round-trip per `ctx.run` in REQUEST_RESPONSE
# mode but is what the protocol requires — see `RunFlush` in the
# conformance suite, which asserts side effects do NOT execute on
# the final invocation (because every prior propose was journaled).
def handle_call({:propose_run_and_suspend, cid, {:value, value}}, from, state) do
propose = %Pb.ProposeRunCompletionMessage{
result_completion_id: cid,
result: {:value, encode_run_value(value)}
}
state = %{state | emitted: [propose | state.emitted]}
suspend(state, cid, from)
end
def handle_call(
{:propose_run_and_suspend, cid, {:failure, %Restate.TerminalError{} = exc}},
from,
state
) do
metadata =
Enum.map(exc.metadata || %{}, fn {k, v} ->
%Pb.FailureMetadata{key: to_string(k), value: to_string(v)}
end)
propose = %Pb.ProposeRunCompletionMessage{
result_completion_id: cid,
result:
{:failure, %Pb.Failure{code: exc.code, message: exc.message || "", metadata: metadata}}
}
state = %{state | emitted: [propose | state.emitted]}
suspend(state, cid, from)
end
# --- Deferred-emit primitives for awaitable combinators ---
#
# `start_timer` and `start_call` emit the journal entry without
# blocking. They return a handle (just the completion ids) which the
# caller can later pass to `Restate.Awaitable.await/any/all`. The
# existing :sleep / :call / :send handlers stay as the
# blocking-convenience path used by `Context.sleep` etc.
def handle_call({:start_timer, duration_ms}, from, state) do
case state.phase do
:replaying ->
with {:ok, {recorded, rest}} <- pop_recorded(state.recorded_commands, Pb.SleepCommandMessage) do
state = state |> Map.put(:recorded_commands, rest) |> track_command(recorded) |> advance_phase()
{:reply, {:timer_handle, recorded.result_completion_id}, state}
else
{:error, exc} -> finalize_journal_mismatch(state, exc, from)
end
:processing ->
cid = state.next_completion_id
cmd = %Pb.SleepCommandMessage{
wake_up_time: :os.system_time(:millisecond) + duration_ms,
result_completion_id: cid
}
state =
state
|> Map.update!(:emitted, &[cmd | &1])
|> Map.put(:next_completion_id, cid + 1)
|> track_command(cmd)
{:reply, {:timer_handle, cid}, state}
end
end
def handle_call({:start_call, target}, from, state) do
case state.phase do
:replaying ->
with {:ok, {recorded, rest}} <- pop_recorded(state.recorded_commands, Pb.CallCommandMessage) do
state = state |> Map.put(:recorded_commands, rest) |> track_command(recorded) |> advance_phase()
{:reply,
{:call_handle, recorded.result_completion_id, recorded.invocation_id_notification_idx},
state}
else
{:error, exc} -> finalize_journal_mismatch(state, exc, from)
end
:processing ->
cid_invok = state.next_completion_id
cid_result = cid_invok + 1
cmd = %Pb.CallCommandMessage{
service_name: target.service,
handler_name: target.handler,
parameter: target.parameter,
key: target.key || "",
idempotency_key: target.idempotency_key,
invocation_id_notification_idx: cid_invok,
result_completion_id: cid_result
}
state =
state
|> Map.update!(:emitted, &[cmd | &1])
|> Map.put(:next_completion_id, cid_result + 1)
|> track_command(cmd)
{:reply, {:call_handle, cid_result, cid_invok}, state}
end
end
def handle_call({:await_handles, mode, handles}, from, state)
when mode in [:one, :any, :all] and is_list(handles) do
do_await_handles(state, mode, handles, from)
end
# Surface the callee's invocation id for a deferred call_async handle.
# Mirrors `handle_send_invocation_id/3` (the blocking `Context.send/5`
# path) — same notification, same wire shape, just exposed via a
# different SDK surface so callers who started the call with
# `call_async` (no round-trip) can opt into the round-trip later when
# they actually need the id (e.g. to cancel the callee out-of-band).
#
# Replay-safe: on the second call within the same handler, the
# CallInvocationIdCompletionNotificationMessage is already in
# state.notifications, so we return synchronously without re-suspending.
# No new journal entry is emitted either way — this op rides the
# CallCommand's existing invocation_id_notification_idx.
def handle_call({:await_invocation_id, invok_cid}, from, state) when is_integer(invok_cid) do
case Map.fetch(state.notifications, invok_cid) do
{:ok, {:invocation_id, id}} when is_binary(id) ->
{:reply, {:ok, id}, state}
:error ->
if state.cancelled? do
# Notification not yet here, parent cancelled — raise 409.
# We can't propagate cancel to the callee because we don't
# know its id (that's literally what we're awaiting). The
# callee will be torn down by the runtime when it observes
# the parent's terminal failure.
{:reply, {:terminal_error, cancellation_error()}, state}
else
suspend(state, invok_cid, from)
end
end
end
def handle_call({:sleep, duration_ms}, from, state) do
case state.phase do
:replaying ->
with {:ok, {recorded, rest}} <- pop_recorded(state.recorded_commands, Pb.SleepCommandMessage) do
state = state |> Map.put(:recorded_commands, rest) |> track_command(recorded) |> advance_phase()
cond do
Map.has_key?(state.notifications, recorded.result_completion_id) ->
# Completion already in the replay journal — sleep returns now.
{:reply, :ok, state}
state.cancelled? ->
# Sleep would block, but cancel preempts.
{:reply, {:terminal_error, cancellation_error()}, state}
true ->
# Recorded sleep, completion not yet stored. Suspend on this id.
suspend(state, recorded.result_completion_id, from)
end
else
{:error, exc} -> finalize_journal_mismatch(state, exc, from)
end
:processing ->
cid = state.next_completion_id
cmd = %Pb.SleepCommandMessage{
wake_up_time: :os.system_time(:millisecond) + duration_ms,
result_completion_id: cid
}
state =
state
|> Map.update!(:emitted, &[cmd | &1])
|> Map.put(:next_completion_id, cid + 1)
|> track_command(cmd)
if state.cancelled? do
{:reply, {:terminal_error, cancellation_error()}, state}
else
# REQUEST_RESPONSE mode: no completion will arrive on this stream,
# so we suspend immediately on the freshly-emitted sleep id.
suspend(state, cid, from)
end
end
end
# The endpoint and the handler run concurrently — either could complete
# first. We resolve the race by stashing whatever's missing.
def handle_call(:await_response, _from, %{result_body: body, outcome: outcome} = state)
when is_binary(body) do
{:stop, :normal, {outcome, body}, state}
end
def handle_call(:await_response, from, state) do
{:noreply, %{state | awaiting_response: from}}
end
@impl true
def handle_info({:handler_result, {:ok, value}}, state) do
output = %Pb.OutputCommandMessage{
result: {:value, %Pb.Value{content: Restate.Serde.encode(value)}}
}
finalize(encode_response(state.emitted, [output, %Pb.EndMessage{}]), :value, state)
end
def handle_info({:handler_result, {:error, %Restate.TerminalError{} = e, _stack}}, state) do
# Handler-raised business failure: lands in the journal as an
# OutputCommandMessage{failure}, terminating the invocation
# successfully (no runtime retry).
metadata =
Enum.map(e.metadata || %{}, fn {k, v} ->
%Pb.FailureMetadata{key: to_string(k), value: to_string(v)}
end)
output = %Pb.OutputCommandMessage{
result:
{:failure,
%Pb.Failure{code: e.code, message: e.message || "", metadata: metadata}}
}
finalize(
encode_response(state.emitted, [output, %Pb.EndMessage{}]),
:terminal_failure,
state
)
end
def handle_info({:handler_result, {:error, exception, stacktrace}}, state) do
code =
case exception do
%Restate.ProtocolError{code: code} -> code
_ -> 500
end
err =
%Pb.ErrorMessage{
code: code,
message: Exception.message(exception),
stacktrace: Exception.format_stacktrace(stacktrace)
}
|> with_related_command(state.current_command)
# ErrorMessage on its own is a terminal frame (per V5 spec it
# replaces EndMessage). State-mutating commands emitted before the
# failure are still part of the journal and remain in
# `state.emitted`. Codes:
# * 500 — generic handler failure; runtime retries.
# * 570 — JOURNAL_MISMATCH; runtime stops, surfaces to operator.
# * 571 — PROTOCOL_VIOLATION; same.
finalize(encode_response(state.emitted, [err]), :error, state)
end
# --- helpers ---
# Built-in cancel signal index. `BuiltInSignal.CANCEL = 1` in
# protocol.proto:670. Java mirrors this as `CANCEL_SIGNAL_ID = 1` in
# `StateMachineImpl.java`.
@cancel_signal_id 1
# Canonical exception raised when a suspending op is hit on a
# cancelled invocation. 409 matches Restate's ABORTED convention
# used by the runtime when it propagates cancellation.
defp cancellation_error,
do: %Restate.TerminalError{code: 409, message: "cancelled"}
# Partition a post-Input replay journal into ordered commands, a
# completion-id-keyed notifications map, a (user) signal-id-keyed
# notifications map, and a cancellation flag. Entry-name commands like
# OutputCommandMessage shouldn't appear in a replay (an Output ends the
# invocation), but we tolerate them by keeping them in the command list.
#
# Signal id 1 is the built-in CANCEL signal — extracted into a flag
# rather than the user signal map so awakeable lookups (which use ids
# ≥ 17) never see it, and so the per-op cancel check is a single bool.
defp partition_journal(frames) do
Enum.reduce(frames, {[], %{}, %{}, false}, fn %Frame{message: msg}, {cmds, notes, sigs, cancelled?} ->
cond do
signal_notification?(msg) ->
case signal_notification_id(msg) do
@cancel_signal_id ->
{cmds, notes, sigs, true}
id when is_integer(id) ->
{cmds, notes, Map.put(sigs, id, signal_notification_result(msg)), cancelled?}
nil ->
# Named-signal notification (signal_name oneof) — out of
# v0.2 scope. Drop defensively rather than crashing.
{cmds, notes, sigs, cancelled?}
end
notification?(msg) ->
{cmds, Map.put(notes, msg.completion_id, notification_result(msg)), sigs, cancelled?}