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 "start": self.config.start,
326 }))
327 .build(),
328 );
329
330 Ok(())
331 }
332
333 pub async fn from_frame(frame: &Frame, store: &Store) -> Result<Self, Error> {
334 let topic = frame
335 .topic
336 .strip_suffix(".register")
337 .ok_or("Frame topic must end with .register")?;
338
339 let hash = frame.hash.as_ref().ok_or("Missing hash field")?;
341 let mut reader = store
342 .cas_reader(hash.clone())
343 .await
344 .map_err(|e| format!("Failed to get cas reader: {e}"))?;
345
346 let mut expression = String::new();
347 reader
348 .read_to_string(&mut expression)
349 .await
350 .map_err(|e| format!("Failed to read expression: {e}"))?;
351
352 let engine = crate::processor::build_engine(store, &frame.id)?;
354
355 let actor = Actor::new(
356 frame.id,
357 topic.to_string(),
358 engine,
359 expression,
360 store.clone(),
361 )
362 .await?;
363
364 Ok(actor)
365 }
366
367 async fn configure_read_options(&self) -> ReadOptions {
368 let (after, is_new) = match &self.config.start {
370 Start::First => (None, false),
371 Start::New => (None, true),
372 Start::After(id) => (Some(*id), false),
373 };
374
375 let follow_option = self
377 .config
378 .pulse
379 .map(|pulse| FollowOption::WithHeartbeat(Duration::from_millis(pulse)))
380 .unwrap_or(FollowOption::On);
381
382 ReadOptions::builder()
383 .follow(follow_option)
384 .new(is_new)
385 .maybe_after(after)
386 .build()
387 }
388}
389
390use tokio::sync::{mpsc, oneshot};
391
392pub struct EngineWorker {
393 work_tx: mpsc::Sender<WorkItem>,
394}
395
396struct WorkItem {
397 frame: Frame,
398 resp_tx: oneshot::Sender<Result<ClosureResult, Error>>,
399}
400
401impl EngineWorker {
402 pub fn new(
403 engine: nu::Engine,
404 closure: nu_protocol::engine::Closure,
405 initial_state: Value,
406 ) -> Self {
407 let (work_tx, mut work_rx) = mpsc::channel(32);
408
409 std::thread::spawn(move || {
410 let mut engine = engine;
411 let mut state = initial_state;
412
413 while let Some(WorkItem { frame, resp_tx }) = work_rx.blocking_recv() {
414 let frame_val =
415 crate::nu::frame_to_value(&frame, nu_protocol::Span::unknown(), false);
416
417 let pipeline = engine.run_closure_in_job(
418 &closure,
419 vec![frame_val, state.clone()],
420 None,
421 format!("actor {topic}", topic = frame.topic),
422 );
423
424 let result = pipeline
425 .map_err(|e| {
426 let working_set = nu_protocol::engine::StateWorkingSet::new(&engine.state);
427 Error::from(nu_protocol::format_cli_error(None, &working_set, &*e, None))
428 })
429 .and_then(|pd| {
430 pd.into_value(nu_protocol::Span::unknown())
431 .map_err(Error::from)
432 })
433 .and_then(interpret_closure_result);
434
435 if let Ok(ClosureResult::Continue { ref next_state, .. }) = result {
436 state = next_state.clone();
437 }
438
439 let _ = resp_tx.send(result);
440 }
441 });
442
443 Self { work_tx }
444 }
445
446 pub async fn eval(&self, frame: Frame) -> Result<ClosureResult, Error> {
447 let (resp_tx, resp_rx) = oneshot::channel();
448 let work_item = WorkItem { frame, resp_tx };
449
450 self.work_tx
451 .send(work_item)
452 .await
453 .map_err(|_| Error::from("Engine worker thread has terminated"))?;
454
455 resp_rx
456 .await
457 .map_err(|_| Error::from("Engine worker thread has terminated"))?
458 }
459}
460
461fn interpret_closure_result(value: Value) -> Result<ClosureResult, Error> {
462 match value {
463 Value::Nothing { .. } => Ok(ClosureResult::Stop { output: None }),
464 Value::Record { ref val, .. } => {
465 for key in val.columns() {
466 if key != "out" && key != "next" {
467 return Err(format!(
468 "Unexpected key '{key}' in closure return record; only 'out' and 'next' are allowed"
469 )
470 .into());
471 }
472 }
473 let output = val.get("out").cloned();
474 match val.get("next").cloned() {
475 Some(next_state) => Ok(ClosureResult::Continue { output, next_state }),
476 None => Ok(ClosureResult::Stop { output }),
477 }
478 }
479 _ => Err(format!(
480 "Closure must return a record with 'out' and/or 'next' keys, or nothing; got {}",
481 value.get_type()
482 )
483 .into()),
484 }
485}
486
487fn is_value_an_append_frame_from_actor(value: &Value, actor_id: &Scru128Id) -> bool {
488 value
489 .as_record()
490 .ok()
491 .filter(|record| record.get("id").is_some() && record.get("topic").is_some())
492 .and_then(|record| record.get("meta"))
493 .and_then(|meta| meta.as_record().ok())
494 .and_then(|meta_record| meta_record.get("actor_id"))
495 .and_then(|id| id.as_str().ok())
496 .filter(|id| *id == actor_id.to_string())
497 .is_some()
498}
499
500fn extract_actor_config(
502 script_config: &NuScriptConfig,
503) -> Result<(ActorConfig, Option<serde_json::Value>), Error> {
504 let script_options: ActorScriptOptions = script_config.deserialize_options()?;
506
507 let start =
509 match script_options.start.as_deref() {
510 Some("first") => Start::First,
511 Some("new") => Start::New,
512 Some(id_str) => Start::After(Scru128Id::from_str(id_str).map_err(|_| -> Error {
513 format!("Invalid scru128 ID for start: {id_str}").into()
514 })?),
515 None => Start::default(), };
517
518 Ok((
520 ActorConfig {
521 start,
522 pulse: script_options.pulse,
523 return_options: script_options.return_options,
524 },
525 script_options.initial,
526 ))
527}