forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkflow.rs
More file actions
361 lines (336 loc) · 12.8 KB
/
Copy pathworkflow.rs
File metadata and controls
361 lines (336 loc) · 12.8 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
//! Durable workflow execution: event journaling, checkpointing, recovery,
//! signal routing, and timer scheduling.
//!
//! All functions in this module take `&Runtime` or `&mut Runtime` to access
//! the runtime's public fields. They live here instead of on `impl Runtime`
//! to keep the god-object at a manageable size.
use crate::bytecode::Constant;
use crate::runtime::actor::Actor;
use crate::runtime::persistence::{EventEntry, PersistedValue, WorkflowEvent};
use crate::runtime::{BytecodeDistributedCallbacks, BytecodeRuntimeCallbacks, Runtime, StateModel};
use crate::vm::{Frame, Value, VM};
// ---------------------------------------------------------------------------
// Utility predicates
// ---------------------------------------------------------------------------
pub(crate) fn next_sequence(rt: &Runtime, actor_id: u64) -> u64 {
rt.persistence.latest_sequence(actor_id) + 1
}
pub(crate) fn actor_is_workflow(rt: &Runtime, actor_id: u64) -> bool {
rt.actors
.get(&actor_id)
.map(|a| a.is_workflow)
.unwrap_or(false)
}
// ---------------------------------------------------------------------------
// Checkpoint
// ---------------------------------------------------------------------------
/// Snapshot the durable and CRDT state of a persistent actor.
pub(crate) fn checkpoint_actor(rt: &mut Runtime, actor_id: u64) {
let actor = match rt.actors.get(&actor_id) {
Some(a) => a,
None => return,
};
if !actor.persistent {
return;
}
let seq = next_sequence(rt, actor_id);
let mut state = std::collections::HashMap::new();
for (name, value) in &actor.state_data {
let model = actor
.state_models
.get(name)
.copied()
.unwrap_or(StateModel::Local);
if model == StateModel::Durable || model.is_crdt() {
let persisted = if name == "semantic_memory" || name == "procedural_memory" {
vm_value_to_string_in_actor(value, actor)
.map(PersistedValue::String)
.unwrap_or_else(|| {
PersistedValue::from_value_resolved(value, actor.bytecode_module.as_ref())
})
} else {
PersistedValue::from_value_resolved(value, actor.bytecode_module.as_ref())
};
state.insert(name.clone(), persisted);
}
}
// Snapshot the global CRDT state alongside durable actor fields.
let crdt_snapshot = rt.crdt_manager.as_ref().map(|m| {
m.snapshot()
.into_iter()
.map(|(id, (ty, bytes))| (id.0, ty.to_u8(), bytes))
.collect()
});
let snapshot = crate::runtime::persistence::ActorSnapshot {
actor_id,
sequence: seq,
state,
waiting_signal: actor.waiting_signal.clone(),
crdt_snapshot,
};
let _ = rt.persistence.save_snapshot(snapshot);
if let Some(actor) = rt.actors.get_mut(&actor_id) {
actor.sequence = seq;
actor.dirty_fields.clear();
}
}
// ---------------------------------------------------------------------------
// Event emission
// ---------------------------------------------------------------------------
/// Resolve a string-id value to the original string using the actor's
/// bytecode module constant pool.
fn resolve_string_constant(rt: &Runtime, actor_id: u64, value: &Value) -> Option<String> {
let string_id = value.as_string_id()?;
let actor = rt.actors.get(&actor_id)?;
let module = actor.bytecode_module.as_ref()?;
module
.constants
.get(string_id as usize)
.and_then(|c| match c {
Constant::String(s) => Some(s.clone()),
_ => None,
})
}
/// Emit a durable event for a workflow or event-sourced actor. For workflow
/// actors this appends to the durable journal and forces a checkpoint. For
/// event-sourced (non-workflow) actors the event is persisted to the event
/// journal and a checkpoint is forced.
pub(crate) fn emit_event(rt: &mut Runtime, actor_id: u64, event: &str, args: &[Value]) {
let is_workflow = rt
.actors
.get(&actor_id)
.map(|a| a.is_workflow)
.unwrap_or(false);
let seq = next_sequence(rt, actor_id);
if let Some(actor) = rt.actors.get_mut(&actor_id) {
actor.event_log.push((event.to_string(), args.to_vec()));
let event_sourced_names: Vec<String> = actor
.state_models
.iter()
.filter(|(_, model)| **model == StateModel::EventSourced)
.map(|(name, _)| name.clone())
.collect();
for name in &event_sourced_names {
if let Some(n) = actor.get_state_field(name).and_then(|v| v.as_int()) {
actor.set_state_field(name, Value::int(n + 1));
}
}
// Persist events for EventSourced fields (non-workflow actors).
if !is_workflow && !event_sourced_names.is_empty() {
let module = actor.bytecode_module.as_ref();
let persisted_args: Vec<PersistedValue> = args
.iter()
.map(|v| PersistedValue::from_value_resolved(v, module))
.collect();
for name in &event_sourced_names {
// Capture the field's current value AFTER the apply
// handler has run and the +1 has been applied. This
// snapshot lets recovery reconstruct the exact post-
// apply value without re-executing bytecode.
let current_val = actor.get_state_field(name).unwrap_or(Value::nil());
let entry = EventEntry {
sequence: seq,
field_name: name.clone(),
event_name: event.to_string(),
args: persisted_args.clone(),
value: PersistedValue::from_value_resolved(¤t_val, module),
};
let _ = rt.persistence.append_event(actor_id, entry);
}
if let Some(actor) = rt.actors.get_mut(&actor_id) {
for name in &event_sourced_names {
actor.event_sourced_sequences.insert(name.clone(), seq);
}
actor.sequence = seq;
}
}
}
if is_workflow {
if event == "ParallelBranchCompleted" && args.len() == 2 {
let parallel_step_name =
resolve_string_constant(rt, actor_id, &args[0]).unwrap_or_default();
let branch_name = resolve_string_constant(rt, actor_id, &args[1]).unwrap_or_default();
let _ = rt.persistence.append_parallel_branch_completed(
actor_id,
seq,
parallel_step_name,
branch_name,
);
if let Some(actor) = rt.actors.get_mut(&actor_id) {
let current = actor
.get_state_field("parallel_progress")
.and_then(|v| v.as_int())
.unwrap_or(0);
actor.set_state_field("parallel_progress", Value::int(current + 1));
}
} else {
let module = rt
.actors
.get(&actor_id)
.and_then(|a| a.bytecode_module.as_ref());
let payload: Vec<PersistedValue> = args
.iter()
.map(|v| PersistedValue::from_value_resolved(v, module))
.collect();
let _ = rt.persistence.append_workflow_event(
actor_id,
WorkflowEvent::Custom {
sequence: seq,
name: event.to_string(),
args: payload,
},
);
}
checkpoint_actor(rt, actor_id);
}
}
// ---------------------------------------------------------------------------
// Append wrappers
// ---------------------------------------------------------------------------
pub(crate) fn append_timer_set(
rt: &mut Runtime,
actor_id: u64,
name: &str,
duration_ms: u64,
) -> std::io::Result<()> {
let seq = next_sequence(rt, actor_id);
rt.persistence
.append_timer_set(actor_id, seq, name.to_string(), duration_ms)?;
checkpoint_actor(rt, actor_id);
Ok(())
}
pub(crate) fn append_timer_fired(
rt: &mut Runtime,
actor_id: u64,
name: &str,
) -> std::io::Result<()> {
let seq = next_sequence(rt, actor_id);
rt.persistence
.append_timer_fired(actor_id, seq, name.to_string())?;
checkpoint_actor(rt, actor_id);
Ok(())
}
pub(crate) fn append_signal_received(
rt: &mut Runtime,
actor_id: u64,
name: &str,
payload: Option<String>,
) -> std::io::Result<()> {
let seq = next_sequence(rt, actor_id);
rt.persistence
.append_signal_received(actor_id, seq, name.to_string(), payload)?;
checkpoint_actor(rt, actor_id);
Ok(())
}
pub(crate) fn append_saga_compensated(
rt: &mut Runtime,
actor_id: u64,
step_name: &str,
) -> std::io::Result<()> {
let seq = next_sequence(rt, actor_id);
rt.persistence
.append_saga_compensated(actor_id, seq, step_name.to_string())?;
checkpoint_actor(rt, actor_id);
Ok(())
}
// ---------------------------------------------------------------------------
// Signal delivery
// ---------------------------------------------------------------------------
/// Deliver a signal to a workflow actor. If the actor is currently suspended
/// waiting for this signal, its execution is resumed.
pub(crate) fn signal_workflow(
rt: &mut Runtime,
actor_id: u64,
name: &str,
payload: Option<String>,
) {
let _ = append_signal_received(rt, actor_id, name, payload.clone());
let should_resume = {
if let Some(actor) = rt.actors.get_mut(&actor_id) {
actor.received_signals.push((name.to_string(), payload));
actor
.waiting_signal
.as_ref()
.map(|s| s == name)
.unwrap_or(false)
} else {
false
}
};
if should_resume {
rt.resume_suspended_workflow_step(actor_id);
}
}
/// Register a read-only query handler on a workflow actor.
pub(crate) fn register_workflow_query(rt: &mut Runtime, actor_id: u64, name: &str, handler: Value) {
if let Some(actor) = rt.actors.get_mut(&actor_id) {
if actor.is_workflow {
actor.query_handlers.insert(name.to_string(), handler);
}
}
}
/// Invoke a registered query handler on a workflow actor and return its result.
pub(crate) fn query_workflow(rt: &mut Runtime, actor_id: u64, name: &str) -> Option<Value> {
let (handler, module) = {
let actor = rt.actors.get(&actor_id)?;
if !actor.is_workflow {
return None;
}
let handler = *actor.query_handlers.get(name)?;
(handler, actor.bytecode_module.clone()?)
};
let self_ptr: *mut Runtime = rt;
let mut vm = VM::new();
vm.load_module(module);
let offset = vm.function_offset_for_value(0, handler).ok()?;
vm.set_actor_callbacks(Box::new(BytecodeRuntimeCallbacks::new(self_ptr, actor_id)));
vm.set_distributed_callbacks(Box::new(BytecodeDistributedCallbacks { runtime: self_ptr }));
let mut frame = Frame::new(None, 0);
frame.pc = offset;
vm.set_current_frame(frame);
vm.run_from(0, offset).ok()
}
// ---------------------------------------------------------------------------
// Timer scheduling
// ---------------------------------------------------------------------------
/// Schedule a durable timer for a workflow actor.
pub(crate) fn schedule_workflow_timer(
rt: &mut Runtime,
actor_id: u64,
name: &str,
duration_ms: u64,
) {
if actor_is_workflow(rt, actor_id) {
let _ = append_timer_set(rt, actor_id, name, duration_ms);
}
rt.rearm_timer(actor_id, name, duration_ms);
}
// ---------------------------------------------------------------------------
// Helpers (re-exported from mod.rs; kept here for cohesion)
// ---------------------------------------------------------------------------
/// Convert a VM value into a Rust string, reading pointer payloads as
/// null-terminated UTF-8 and string-id values via the actor's bytecode module.
pub(crate) fn vm_value_to_string_in_actor(value: &Value, actor: &Actor) -> Option<String> {
if let Some(id) = value.as_string_id() {
actor
.bytecode_module
.as_ref()
.and_then(|m| m.constants.get(id as usize))
.and_then(|c| match c {
Constant::String(s) => Some(s.clone()),
_ => None,
})
} else if let Some(ptr) = value.as_ptr() {
if ptr.is_null() {
Some(String::new())
} else {
Some(unsafe {
std::ffi::CStr::from_ptr(ptr as *const std::ffi::c_char)
.to_string_lossy()
.into_owned()
})
}
} else {
None
}
}