1use vlo_types::{
10 Command, Completion, ContinueAsNew, Emit, Envelope, KernelState, Kind, NewSpawn, NewTask,
11 NewTimer, RunRef, RunStatus, SignalWait, Status, StepState, TaskUpdate, Transition,
12};
13
14use crate::canonical;
15use crate::classify::{timeout_step_id, COMPLETE_STEP_ID, CONTINUE_STEP_ID};
16use crate::error::{code, err, err_step, KResult};
17use crate::events::{self, LifecycleEvent};
18use crate::ids;
19
20pub const DEFAULT_LEASE_TTL_MS: u64 = 60_000;
22pub const DEFAULT_QUEUE: &str = "default";
24
25pub struct Builder<'a> {
27 pub run: &'a RunRef,
28 ts_ms: u64,
29 random: &'a str,
30 pub kernel_state: KernelState,
31 seq: u64,
32 pub events: Vec<Envelope>,
33 pub tasks: Vec<NewTask>,
34 pub task_updates: Vec<TaskUpdate>,
35 pub timers: Vec<NewTimer>,
36 pub spawns: Vec<NewSpawn>,
37 pub signal_waits: Vec<SignalWait>,
38 pub emits: Vec<Emit>,
39 pub completion: Option<Completion>,
40 pub continue_as_new: Option<ContinueAsNew>,
41}
42
43impl<'a> Builder<'a> {
44 pub fn new(run: &'a RunRef, kernel_state: KernelState, ts_ms: u64, random: &'a str) -> Self {
46 Builder {
47 run,
48 ts_ms,
49 random,
50 kernel_state,
51 seq: run.last_seq,
52 events: Vec::new(),
53 tasks: Vec::new(),
54 task_updates: Vec::new(),
55 timers: Vec::new(),
56 spawns: Vec::new(),
57 signal_waits: Vec::new(),
58 emits: Vec::new(),
59 completion: None,
60 continue_as_new: None,
61 }
62 }
63
64 pub fn push_event(&mut self, input: vlo_types::EventInput) {
66 self.seq += 1;
67 self.events
68 .push(events::envelope(input, self.seq, self.run));
69 }
70
71 fn push_lifecycle(&mut self, event: LifecycleEvent<'_>) {
72 let input = events::lifecycle_input(&self.run.run_id, self.ts_ms, self.random, event);
73 self.push_event(input);
74 }
75
76 fn reserve_step_id(&mut self, prefix: &str, id: Option<&String>) -> KResult<String> {
79 self.kernel_state.step_no += 1;
80 let step_id = match id {
81 Some(id) if id.is_empty() => {
82 return Err(err(code::INVALID_COMMAND, "explicit step id is empty"))
83 }
84 Some(id) => id.clone(),
85 None => format!("{prefix}#{}", self.kernel_state.step_no),
86 };
87 if self.kernel_state.steps.contains_key(&step_id) {
88 return Err(err_step(
89 code::DUPLICATE_STEP_ID,
90 "a step with this id is already open",
91 &step_id,
92 ));
93 }
94 Ok(step_id)
95 }
96
97 fn open_timer(&mut self, step_id: String, fire_at: u64) {
100 self.kernel_state.steps.insert(
101 step_id.clone(),
102 StepState {
103 kind: Kind::Timer,
104 status: Status::Scheduled,
105 attempt: 0,
106 activity: None,
107 queue: None,
108 retry: None,
109 child_run_id: None,
110 signal: None,
111 fire_at_ms: Some(fire_at),
112 },
113 );
114 self.timers.push(NewTimer {
115 step_id: step_id.clone(),
116 fire_at_ms: fire_at,
117 });
118 self.push_lifecycle(LifecycleEvent {
119 step_id: &step_id,
120 attempt: 0,
121 kind: Kind::Timer,
122 status: Status::Scheduled,
123 schema_ref: None,
124 payload: None,
125 });
126 }
127
128 pub fn apply(&mut self, command: &Command) -> KResult<()> {
130 match command {
131 Command::Task {
132 activity,
133 schema_ref,
134 input,
135 queue,
136 retry,
137 lease_ttl_ms,
138 timeout_ms,
139 id,
140 } => {
141 if activity.is_empty() {
142 return Err(err(code::INVALID_COMMAND, "task activity is empty"));
143 }
144 let step_id = self.reserve_step_id("task", id.as_ref())?;
145 let queue = queue.clone().unwrap_or_else(|| DEFAULT_QUEUE.to_string());
146 let retry = retry.clone().unwrap_or_default();
147 let attempt = 1;
148
149 self.kernel_state.steps.insert(
150 step_id.clone(),
151 StepState {
152 kind: Kind::Task,
153 status: Status::Scheduled,
154 attempt,
155 activity: Some(activity.clone()),
156 queue: Some(queue.clone()),
157 retry: Some(retry.clone()),
158 child_run_id: None,
159 signal: None,
160 fire_at_ms: None,
161 },
162 );
163 self.tasks.push(NewTask {
164 task_id: ids::task_id(&self.run.run_id, &step_id),
165 step_id: step_id.clone(),
166 attempt,
167 activity: activity.clone(),
168 queue,
169 schema_ref: schema_ref.clone(),
170 input: input.clone(),
171 idempotency_key: ids::idempotency_key(&self.run.run_id, &step_id, attempt),
172 retry,
173 lease_ttl_ms: lease_ttl_ms.unwrap_or(DEFAULT_LEASE_TTL_MS),
174 timeout_ms: *timeout_ms,
175 });
176 self.push_lifecycle(LifecycleEvent {
177 step_id: &step_id,
178 attempt,
179 kind: Kind::Task,
180 status: Status::Scheduled,
181 schema_ref: schema_ref.clone(),
182 payload: Some(canonical::to_string(input)?),
183 });
184 }
185
186 Command::Timer {
187 fire_in_ms,
188 fire_at_ms,
189 id,
190 } => {
191 let fire_at = match (fire_at_ms, fire_in_ms) {
192 (Some(at), _) => *at,
193 (None, Some(delay)) => self.ts_ms.saturating_add(*delay),
194 (None, None) => {
195 return Err(err(
196 code::INVALID_COMMAND,
197 "timer needs fire_at_ms or fire_in_ms",
198 ))
199 }
200 };
201 let step_id = self.reserve_step_id("timer", id.as_ref())?;
202 self.open_timer(step_id, fire_at);
203 }
204
205 Command::Spawn {
206 workflow,
207 input,
208 id,
209 } => {
210 if workflow.is_empty() {
211 return Err(err(code::INVALID_COMMAND, "spawn workflow is empty"));
212 }
213 let step_id = self.reserve_step_id("child", id.as_ref())?;
214 let child_run_id = ids::child_run_id(&self.run.run_id, &step_id);
215 self.kernel_state.steps.insert(
216 step_id.clone(),
217 StepState {
218 kind: Kind::Child,
219 status: Status::Scheduled,
220 attempt: 0,
221 activity: None,
222 queue: None,
223 retry: None,
224 child_run_id: Some(child_run_id.clone()),
225 signal: None,
226 fire_at_ms: None,
227 },
228 );
229 self.spawns.push(NewSpawn {
230 step_id: step_id.clone(),
231 child_run_id,
232 workflow: workflow.clone(),
233 input: input.clone(),
234 });
235 self.push_lifecycle(LifecycleEvent {
236 step_id: &step_id,
237 attempt: 0,
238 kind: Kind::Child,
239 status: Status::Scheduled,
240 schema_ref: None,
241 payload: Some(canonical::to_string(input)?),
242 });
243 }
244
245 Command::AwaitSignal {
246 name,
247 schema_ref,
248 timeout_ms,
249 id,
250 } => {
251 if name.is_empty() {
252 return Err(err(code::INVALID_COMMAND, "signal name is empty"));
253 }
254 let step_id = self.reserve_step_id("signal", id.as_ref())?;
255 self.kernel_state.steps.insert(
256 step_id.clone(),
257 StepState {
258 kind: Kind::Signal,
259 status: Status::AwaitingSignal,
260 attempt: 0,
261 activity: None,
262 queue: None,
263 retry: None,
264 child_run_id: None,
265 signal: Some(name.clone()),
266 fire_at_ms: None,
267 },
268 );
269 self.signal_waits.push(SignalWait {
270 step_id: step_id.clone(),
271 name: name.clone(),
272 schema_ref: schema_ref.clone(),
273 expires_at_ms: timeout_ms.map(|t| self.ts_ms.saturating_add(t)),
274 });
275 self.push_lifecycle(LifecycleEvent {
276 step_id: &step_id,
277 attempt: 0,
278 kind: Kind::Signal,
279 status: Status::AwaitingSignal,
280 schema_ref: schema_ref.clone(),
281 payload: None,
282 });
283 if let Some(timeout) = timeout_ms {
287 let timer_id =
288 self.reserve_step_id("timer", Some(&timeout_step_id(&step_id)))?;
289 self.open_timer(timer_id, self.ts_ms.saturating_add(*timeout));
290 }
291 }
292
293 Command::Emit { channel, data } => {
294 if channel.is_empty() {
295 return Err(err(code::INVALID_COMMAND, "emit channel is empty"));
296 }
297 self.emits.push(Emit {
298 channel: channel.clone(),
299 data: data.clone(),
300 });
301 }
302
303 Command::Complete { output } => {
304 self.completion = Some(Completion {
305 status: RunStatus::Completed,
306 output: Some(output.clone()),
307 });
308 self.push_lifecycle(LifecycleEvent {
309 step_id: COMPLETE_STEP_ID,
310 attempt: 0,
311 kind: Kind::Marker,
312 status: Status::Succeeded,
313 schema_ref: None,
314 payload: Some(canonical::to_string(output)?),
315 });
316 }
317
318 Command::ContinueAsNew { input } => {
319 self.completion = Some(Completion {
320 status: RunStatus::Continued,
321 output: None,
322 });
323 self.continue_as_new = Some(ContinueAsNew {
324 input: input.clone(),
325 });
326 self.push_lifecycle(LifecycleEvent {
327 step_id: CONTINUE_STEP_ID,
328 attempt: 0,
329 kind: Kind::Marker,
330 status: Status::Succeeded,
331 schema_ref: None,
332 payload: Some(canonical::to_string(input)?),
333 });
334 }
335 }
336 Ok(())
337 }
338
339 pub fn finish(
342 mut self,
343 state: String,
344 state_hash: String,
345 state_inline: bool,
346 run_status: RunStatus,
347 ) -> Transition {
348 for event in &mut self.events {
349 event.state_hash = state_hash.clone();
350 }
351 Transition {
352 run: vlo_types::RunPatch {
353 status: run_status,
354 last_seq: self.seq,
355 },
356 kernel_state: self.kernel_state,
357 state,
358 state_hash,
359 state_inline,
360 events: self.events,
361 tasks: self.tasks,
362 task_updates: self.task_updates,
363 timers: self.timers,
364 spawns: self.spawns,
365 signal_waits: self.signal_waits,
366 emits: self.emits,
367 completion: self.completion,
368 continue_as_new: self.continue_as_new,
369 }
370 }
371}