1use std::str::FromStr;
2use std::sync::{Arc, Mutex};
3use std::time::Duration;
4
5use tracing::instrument;
6
7use serde::{Deserialize, Serialize};
8
9use tokio::io::AsyncReadExt;
10
11use nu_protocol::Value;
12
13use scru128::Scru128Id;
14
15use crate::error::Error;
16use crate::nu;
17use crate::nu::commands;
18use crate::nu::value_to_json;
19use crate::nu::{NuScriptConfig, ReturnOptions};
20use crate::store::{FollowOption, Frame, ReadOptions, Store};
21
22#[derive(Clone)]
23pub struct Actor {
24 pub id: Scru128Id,
25 pub topic: String,
26 config: ActorConfig,
27 engine_worker: Arc<EngineWorker>,
28 output: Arc<Mutex<Vec<Frame>>>,
29}
30
31#[derive(Clone, Debug)]
32struct ActorConfig {
33 start: Start,
34 pulse: Option<u64>,
35 return_options: Option<ReturnOptions>,
36}
37
38#[derive(Clone, Debug, Default, Serialize, Deserialize)]
39#[serde(rename_all = "snake_case")]
40enum Start {
41 First,
42 #[default]
43 New,
44 After(Scru128Id),
45}
46
47#[derive(Deserialize, Debug, Default)]
49#[serde(default)] struct ActorScriptOptions {
51 start: Option<String>,
53 pulse: Option<u64>,
55 return_options: Option<ReturnOptions>,
57 initial: Option<serde_json::Value>,
59}
60
61pub(super) enum ClosureResult {
62 Continue {
63 output: Option<Value>,
64 next_state: Value,
65 },
66 Stop {
67 output: Option<Value>,
68 },
69}
70
71impl Actor {
72 pub async fn new(
73 id: Scru128Id,
74 topic: String,
75 mut engine: nu::Engine,
76 expression: String,
77 store: Store,
78 ) -> Result<Self, Error> {
79 let output = Arc::new(Mutex::new(Vec::new()));
80 engine.add_commands(vec![
81 Box::new(commands::cat_command::CatCommand::new(store.clone())),
82 Box::new(commands::last_command::LastCommand::new(store.clone())),
83 Box::new(commands::append_command_buffered::AppendCommand::new(
84 store.clone(),
85 output.clone(),
86 )),
87 ])?;
88
89 let nu_script_config = nu::parse_config(&mut engine, &expression)?;
91
92 let (actor_config, initial_json) = extract_actor_config(&nu_script_config)?;
94
95 let block = engine
97 .state
98 .get_block(nu_script_config.run_closure.block_id);
99 let num_required = block.signature.required_positional.len();
100 let num_optional = block.signature.optional_positional.len();
101
102 let total_positional = num_required + num_optional;
103 if total_positional != 2 {
104 return Err(format!(
105 "Closure must accept exactly 2 params (frame, state) -- got {total_positional}"
106 )
107 .into());
108 }
109
110 let span = nu_protocol::Span::unknown();
112 let initial_state = if let Some(json) = initial_json {
113 crate::nu::util::json_to_value(&json, span)
114 } else if num_optional > 0 {
115 let state_param = &block.signature.optional_positional[0];
116 state_param
117 .default_value
118 .clone()
119 .unwrap_or_else(|| Value::nothing(span))
120 } else {
121 Value::nothing(span)
122 };
123
124 let engine_worker = Arc::new(EngineWorker::new(
125 engine,
126 nu_script_config.run_closure,
127 initial_state,
128 ));
129
130 Ok(Self {
131 id,
132 topic,
133 config: actor_config,
134 engine_worker,
135 output,
136 })
137 }
138
139 async fn eval_in_thread(&self, frame: &Frame) -> Result<ClosureResult, Error> {
140 self.engine_worker.eval(frame.clone()).await
141 }
142
143 #[instrument(
144 level = "info",
145 skip(self, frame, store),
146 fields(
147 message = %format!(
148 "actor={actor_id}:{topic} frame={frame_id}:{frame_topic}",
149 actor_id = self.id, topic = self.topic, frame_id = frame.id, frame_topic = frame.topic)
150 )
151 )]
152 async fn process_frame(&mut self, frame: &Frame, store: &Store) -> Result<bool, Error> {
153 let result = self.eval_in_thread(frame).await?;
154
155 let (output, should_continue) = match result {
156 ClosureResult::Continue { output, .. } => (output, true),
157 ClosureResult::Stop { output } => (output, false),
158 };
159
160 let additional_frame = match output {
162 Some(ref value)
163 if !is_value_an_append_frame_from_actor(value, &self.id)
164 && !matches!(value, Value::Nothing { .. }) =>
165 {
166 let return_options = self.config.return_options.as_ref();
167 let suffix = return_options
168 .and_then(|ro| ro.suffix.as_deref())
169 .unwrap_or(".out");
170 let use_cas = return_options
171 .and_then(|ro| ro.target.as_deref())
172 .is_some_and(|t| t == "cas");
173
174 let topic = format!("{topic}{suffix}", topic = self.topic, suffix = suffix);
175 let ttl = return_options.and_then(|ro| ro.ttl.clone());
176
177 if use_cas {
178 let hash = match value {
179 Value::Binary { val, .. } => store.cas_insert(val).await?,
180 _ => store.cas_insert(&value_to_json(value).to_string()).await?,
181 };
182 Some(
183 Frame::builder(topic)
184 .maybe_ttl(ttl)
185 .maybe_hash(Some(hash))
186 .build(),
187 )
188 } else {
189 match value {
191 Value::Record { .. } => {
192 let json = value_to_json(value);
193 Some(Frame::builder(topic).maybe_ttl(ttl).meta(json).build())
194 }
195 _ => {
196 return Err(format!(
197 "Actor output must be a record when target is not \"cas\"; got {}. \
198 Set return_options.target to \"cas\" for non-record output.",
199 value.get_type()
200 )
201 .into());
202 }
203 }
204 }
205 }
206 _ => None,
207 };
208
209 let output_to_process: Vec<_> = {
211 let mut output = self.output.lock().unwrap();
212 output
213 .drain(..)
214 .chain(additional_frame.into_iter())
215 .collect()
216 };
217
218 for mut output_frame in output_to_process {
219 let meta_obj = output_frame
220 .meta
221 .get_or_insert_with(|| serde_json::Value::Object(Default::default()))
222 .as_object_mut()
223 .expect("meta should be an object");
224
225 meta_obj.insert(
226 "actor_id".to_string(),
227 serde_json::Value::String(self.id.to_string()),
228 );
229 meta_obj.insert(
230 "frame_id".to_string(),
231 serde_json::Value::String(frame.id.to_string()),
232 );
233
234 let _ = store.append(output_frame);
235 }
236
237 Ok(should_continue)
238 }
239
240 async fn serve(&mut self, store: &Store, options: ReadOptions) {
241 let mut recver = store.read(options).await;
242
243 while let Some(frame) = recver.recv().await {
244 if (frame.topic == format!("{topic}.register", topic = self.topic)
246 || frame.topic == format!("{topic}.unregister", topic = self.topic))
247 && frame.id <= self.id
248 {
249 continue;
250 }
251
252 if frame.topic == format!("{topic}.register", topic = &self.topic)
253 || frame.topic == format!("{topic}.unregister", topic = &self.topic)
254 {
255 let _ = store.append(
256 Frame::builder(format!("{topic}.unregistered", topic = &self.topic))
257 .meta(serde_json::json!({
258 "actor_id": self.id.to_string(),
259 "frame_id": frame.id.to_string(),
260 }))
261 .build(),
262 );
263 break;
264 }
265
266 if frame
268 .meta
269 .as_ref()
270 .and_then(|meta| meta.get("actor_id"))
271 .and_then(|actor_id| actor_id.as_str())
272 .filter(|actor_id| *actor_id == self.id.to_string())
273 .is_some()
274 {
275 continue;
276 }
277
278 match self.process_frame(&frame, store).await {
279 Ok(true) => {}
280 Ok(false) => {
281 let _ = store.append(
283 Frame::builder(format!("{topic}.unregistered", topic = self.topic))
284 .meta(serde_json::json!({
285 "actor_id": self.id.to_string(),
286 "frame_id": frame.id.to_string(),
287 }))
288 .build(),
289 );
290 break;
291 }
292 Err(err) => {
293 let _ = store.append(
294 Frame::builder(format!("{topic}.unregistered", topic = self.topic))
295 .meta(serde_json::json!({
296 "actor_id": self.id.to_string(),
297 "frame_id": frame.id.to_string(),
298 "error": err.to_string(),
299 }))
300 .build(),
301 );
302 break;
303 }
304 }
305 }
306 }
307
308 pub async fn spawn(&self, store: Store) -> Result<(), Error> {
309 let options = self.configure_read_options().await;
310
311 {
312 let store = store.clone();
313 let options = options.clone();
314 let mut actor = self.clone();
315
316 tokio::spawn(async move {
317 actor.serve(&store, options).await;
318 });
319 }
320
321 let _ = store.append(
322 Frame::builder(format!("{topic}.active", topic = &self.topic))
323 .meta(serde_json::json!({
324 "actor_id": self.id.to_string(),
325 "new": options.new,
326 "after": options.after.map(|id| id.to_string()),
327 }))
328 .build(),
329 );
330
331 Ok(())
332 }
333
334 pub async fn from_frame(frame: &Frame, store: &Store) -> Result<Self, Error> {
335 let topic = frame
336 .topic
337 .strip_suffix(".register")
338 .ok_or("Frame topic must end with .register")?;
339
340 let hash = frame.hash.as_ref().ok_or("Missing hash field")?;
342 let mut reader = store
343 .cas_reader(hash.clone())
344 .await
345 .map_err(|e| format!("Failed to get cas reader: {e}"))?;
346
347 let mut expression = String::new();
348 reader
349 .read_to_string(&mut expression)
350 .await
351 .map_err(|e| format!("Failed to read expression: {e}"))?;
352
353 let engine = crate::processor::build_engine(store, &frame.id)?;
355
356 let actor = Actor::new(
357 frame.id,
358 topic.to_string(),
359 engine,
360 expression,
361 store.clone(),
362 )
363 .await?;
364
365 Ok(actor)
366 }
367
368 async fn configure_read_options(&self) -> ReadOptions {
369 let (after, is_new) = match &self.config.start {
371 Start::First => (None, false),
372 Start::New => (None, true),
373 Start::After(id) => (Some(*id), false),
374 };
375
376 let follow_option = self
378 .config
379 .pulse
380 .map(|pulse| FollowOption::WithHeartbeat(Duration::from_millis(pulse)))
381 .unwrap_or(FollowOption::On);
382
383 ReadOptions::builder()
384 .follow(follow_option)
385 .new(is_new)
386 .maybe_after(after)
387 .build()
388 }
389}
390
391use tokio::sync::{mpsc, oneshot};
392
393pub struct EngineWorker {
394 work_tx: mpsc::Sender<WorkItem>,
395}
396
397struct WorkItem {
398 frame: Frame,
399 resp_tx: oneshot::Sender<Result<ClosureResult, Error>>,
400}
401
402impl EngineWorker {
403 pub fn new(
404 engine: nu::Engine,
405 closure: nu_protocol::engine::Closure,
406 initial_state: Value,
407 ) -> Self {
408 let (work_tx, mut work_rx) = mpsc::channel(32);
409
410 std::thread::spawn(move || {
411 let mut engine = engine;
412 let mut state = initial_state;
413
414 while let Some(WorkItem { frame, resp_tx }) = work_rx.blocking_recv() {
415 let frame_val =
416 crate::nu::frame_to_value(&frame, nu_protocol::Span::unknown(), false);
417
418 let pipeline = engine.run_closure_in_job(
419 &closure,
420 vec![frame_val, state.clone()],
421 None,
422 format!("actor {topic}", topic = frame.topic),
423 );
424
425 let result = pipeline
426 .map_err(|e| {
427 let working_set = nu_protocol::engine::StateWorkingSet::new(&engine.state);
428 Error::from(nu_protocol::format_cli_error(None, &working_set, &*e, None))
429 })
430 .and_then(|pd| {
431 pd.into_value(nu_protocol::Span::unknown())
432 .map_err(Error::from)
433 })
434 .and_then(interpret_closure_result);
435
436 if let Ok(ClosureResult::Continue { ref next_state, .. }) = result {
437 state = next_state.clone();
438 }
439
440 let _ = resp_tx.send(result);
441 }
442 });
443
444 Self { work_tx }
445 }
446
447 pub async fn eval(&self, frame: Frame) -> Result<ClosureResult, Error> {
448 let (resp_tx, resp_rx) = oneshot::channel();
449 let work_item = WorkItem { frame, resp_tx };
450
451 self.work_tx
452 .send(work_item)
453 .await
454 .map_err(|_| Error::from("Engine worker thread has terminated"))?;
455
456 resp_rx
457 .await
458 .map_err(|_| Error::from("Engine worker thread has terminated"))?
459 }
460}
461
462fn interpret_closure_result(value: Value) -> Result<ClosureResult, Error> {
463 match value {
464 Value::Nothing { .. } => Ok(ClosureResult::Stop { output: None }),
465 Value::Record { ref val, .. } => {
466 for key in val.columns() {
467 if key != "out" && key != "next" {
468 return Err(format!(
469 "Unexpected key '{key}' in closure return record; only 'out' and 'next' are allowed"
470 )
471 .into());
472 }
473 }
474 let output = val.get("out").cloned();
475 match val.get("next").cloned() {
476 Some(next_state) => Ok(ClosureResult::Continue { output, next_state }),
477 None => Ok(ClosureResult::Stop { output }),
478 }
479 }
480 _ => Err(format!(
481 "Closure must return a record with 'out' and/or 'next' keys, or nothing; got {}",
482 value.get_type()
483 )
484 .into()),
485 }
486}
487
488fn is_value_an_append_frame_from_actor(value: &Value, actor_id: &Scru128Id) -> bool {
489 value
490 .as_record()
491 .ok()
492 .filter(|record| record.get("id").is_some() && record.get("topic").is_some())
493 .and_then(|record| record.get("meta"))
494 .and_then(|meta| meta.as_record().ok())
495 .and_then(|meta_record| meta_record.get("actor_id"))
496 .and_then(|id| id.as_str().ok())
497 .filter(|id| *id == actor_id.to_string())
498 .is_some()
499}
500
501fn extract_actor_config(
503 script_config: &NuScriptConfig,
504) -> Result<(ActorConfig, Option<serde_json::Value>), Error> {
505 let script_options: ActorScriptOptions = script_config.deserialize_options()?;
507
508 let start =
510 match script_options.start.as_deref() {
511 Some("first") => Start::First,
512 Some("new") => Start::New,
513 Some(id_str) => Start::After(Scru128Id::from_str(id_str).map_err(|_| -> Error {
514 format!("Invalid scru128 ID for start: {id_str}").into()
515 })?),
516 None => Start::default(), };
518
519 Ok((
521 ActorConfig {
522 start,
523 pulse: script_options.pulse,
524 return_options: script_options.return_options,
525 },
526 script_options.initial,
527 ))
528}