1use anyhow::Result;
2use clap::{Parser, ValueEnum};
3use std::io::Write;
4use std::sync::Arc;
5use tokio::sync::mpsc;
6use tracing::{debug, error};
7
8use crate::{error::CliError, CommandContext};
9use theater::chain::ChainEvent;
10use theater::config::actor_manifest::{
11 RuntimeHostConfig, StoreHandlerConfig, SupervisorHostConfig, TcpHandlerConfig,
12 TerminalHandlerConfig, TimerHandlerConfig,
13};
14use theater::handler::HandlerRegistry;
15use theater::messages::{default_init_state, TheaterCommand};
16use theater::pack_bridge::Value;
17use theater::theater_runtime::TheaterRuntime;
18use theater::utils::{resolve_reference, ResourceCache};
19use theater::ManifestConfig;
20use theater::TheaterId;
21use theater_handler_loop::LoopHandler;
22use theater_handler_message_server::{MessageRouter, MessageServerHandler};
23use theater_handler_podman::PodmanHandler;
24use theater_handler_rpc::RpcHandler;
25use theater_handler_runtime::RuntimeHandler;
26use theater_handler_store::StoreHandler;
27use theater_handler_supervisor::SupervisorHandler;
28use theater_handler_tcp::TcpHandler;
29use theater_handler_terminal::TerminalHandler;
30use theater_handler_timer::TimerHandler;
31
32#[derive(Debug, Clone, Copy, ValueEnum, Default)]
34pub enum EventFormat {
35 Json,
37 #[default]
39 Short,
40 Full,
42}
43
44#[derive(Debug, Parser)]
46pub struct SpawnArgs {
47 #[arg(default_value = "manifest.toml")]
49 pub manifest: String,
50
51 #[arg(long)]
53 pub events: bool,
54
55 #[arg(long, value_enum, default_value = "short")]
57 pub events_format: EventFormat,
58
59 #[arg(long)]
61 pub no_actor_logs: bool,
62}
63
64pub type SetupArgs = SpawnArgs;
66
67fn format_event_short(event: &ChainEvent, actor_id: &TheaterId) -> String {
69 let id_str = actor_id.to_string();
70 let short_id = &id_str[..8.min(id_str.len())];
71 format!("[{}] {}\n", short_id, event)
72}
73
74fn format_event_full(event: &ChainEvent, actor_id: &TheaterId) -> String {
76 let id_str = actor_id.to_string();
77 let short_id = &id_str[..8.min(id_str.len())];
78 let hash_hex = hex::encode(&event.hash);
79 let parent_hex = event
80 .parent_hash
81 .as_ref()
82 .map(hex::encode)
83 .unwrap_or_else(|| "none".to_string());
84 let data_str = String::from_utf8_lossy(&event.data);
85
86 format!(
87 "EVENT [{}] {}\nparent: {}\ntype: {}\nsize: {}\n{}\n\n",
88 short_id,
89 hash_hex,
90 parent_hex,
91 event.event_type,
92 event.data.len(),
93 data_str
94 )
95}
96
97fn format_event_json(event: &ChainEvent, actor_id: &TheaterId) -> String {
99 let json = serde_json::json!({
100 "actor_id": actor_id.to_string(),
101 "hash": hex::encode(&event.hash),
102 "parent_hash": event.parent_hash.as_ref().map(hex::encode),
103 "event_type": event.event_type,
104 "data": format!("{} bytes (pack-encoded)", event.data.len())
105 });
106 serde_json::to_string(&json).unwrap_or_else(|_| "{}".to_string())
107}
108
109fn create_handler_registry(
111 theater_tx: mpsc::Sender<TheaterCommand>,
112 show_actor_logs: bool,
113 resource_cache: Arc<ResourceCache>,
114) -> Result<HandlerRegistry, CliError> {
115 let mut registry = HandlerRegistry::new();
116
117 let runtime_config = RuntimeHostConfig {};
119 registry.register(
120 RuntimeHandler::new(runtime_config, theater_tx.clone(), None)
121 .with_show_logs(show_actor_logs),
122 );
123
124 let store_config = StoreHandlerConfig::default();
126 registry.register(StoreHandler::new(store_config, None));
127
128 let supervisor_config = SupervisorHostConfig {};
133 registry.register(
134 SupervisorHandler::new(supervisor_config, None).with_resource_cache(resource_cache),
135 );
136
137 let message_router = MessageRouter::new();
139 registry.register(MessageServerHandler::new(None, message_router.clone()));
140
141 registry.register(RpcHandler::new(theater_tx.clone()));
143
144 let tcp_config = TcpHandlerConfig {
146 listen: None,
147 max_connections: None,
148 ..Default::default()
149 };
150 registry.register(TcpHandler::new(tcp_config));
151
152 let terminal_config = TerminalHandlerConfig::default();
154 registry.register(TerminalHandler::new(terminal_config));
155
156 let timer_config = TimerHandlerConfig::default();
158 registry.register(TimerHandler::new(timer_config));
159
160 registry.register(LoopHandler::new());
162
163 let podman_config = theater::config::actor_manifest::PodmanHandlerConfig::default();
165 registry.register(PodmanHandler::new(podman_config));
166
167 Ok(registry)
168}
169
170pub async fn execute_spawn(args: &SpawnArgs, ctx: &CommandContext) -> Result<(), CliError> {
175 run(args, ctx, true).await
176}
177
178pub async fn execute_setup(args: &SetupArgs, ctx: &CommandContext) -> Result<(), CliError> {
183 run(args, ctx, false).await
184}
185
186async fn run(args: &SpawnArgs, ctx: &CommandContext, call_init: bool) -> Result<(), CliError> {
189 debug!("Starting actor from manifest: {}", args.manifest);
190
191 let manifest_bytes = resolve_reference(&args.manifest).await.map_err(|e| {
193 CliError::invalid_manifest(format!(
194 "Failed to resolve manifest reference '{}': {}",
195 args.manifest, e
196 ))
197 })?;
198
199 let manifest_content = String::from_utf8(manifest_bytes).map_err(|e| {
200 CliError::invalid_manifest(format!("Manifest content is not valid UTF-8: {}", e))
201 })?;
202
203 let manifest = ManifestConfig::from_toml_str(&manifest_content)
205 .map_err(|e| CliError::invalid_manifest(format!("Failed to parse manifest: {}", e)))?;
206
207 let (theater_tx, theater_rx) = mpsc::channel::<TheaterCommand>(32);
209 let resource_cache = Arc::new(ResourceCache::new());
212 let handler_registry =
213 create_handler_registry(theater_tx.clone(), !args.no_actor_logs, resource_cache)?;
214
215 let mut runtime = TheaterRuntime::new(
216 theater_tx.clone(),
217 theater_rx,
218 None, handler_registry,
220 )
221 .await
222 .map_err(|e| CliError::server_error(format!("Failed to create runtime: {}", e)))?;
223
224 let (global_events_tx, mut global_events_rx) = mpsc::channel(256);
226 runtime.add_global_subscription(global_events_tx);
227
228 let runtime_handle = tokio::spawn(async move {
230 if let Err(e) = runtime.run().await {
231 error!("Theater runtime error: {}", e);
232 }
233 });
234
235 let wasm_path = if manifest.package.starts_with('/') || manifest.package.contains("://") {
237 manifest.package.clone()
239 } else {
240 let manifest_path = std::path::Path::new(&args.manifest);
242 if let Some(manifest_dir) = manifest_path.parent() {
243 manifest_dir
244 .join(&manifest.package)
245 .to_string_lossy()
246 .to_string()
247 } else {
248 manifest.package.clone()
249 }
250 };
251
252 let wasm_bytes = resolve_reference(&wasm_path).await.map_err(|e| {
254 CliError::server_error(format!("Failed to load WASM from '{}': {}", wasm_path, e))
255 })?;
256
257 let (response_tx, response_rx) = tokio::sync::oneshot::channel();
259
260 let (supervisor_tx, mut supervisor_rx) = mpsc::channel(32);
262
263 let init_state = match manifest.initial_state.as_ref() {
272 Some(s) => Value::String(s.clone()),
273 None => default_init_state(),
274 };
275
276 let cmd = if call_init {
280 TheaterCommand::SpawnActor {
281 wasm_bytes,
282 name: Some(manifest.name.clone()),
283 manifest: Some(manifest),
284 init_state,
285 response_tx,
286 supervisor_tx: Some(supervisor_tx),
287 subscription_tx: None, }
289 } else {
290 TheaterCommand::SetupActor {
291 wasm_bytes,
292 name: Some(manifest.name.clone()),
293 manifest: Some(manifest),
294 init_state,
295 response_tx,
296 supervisor_tx: Some(supervisor_tx),
297 subscription_tx: None, }
299 };
300
301 theater_tx
302 .send(cmd)
303 .await
304 .map_err(|e| CliError::server_error(format!("Failed to send spawn command: {}", e)))?;
305
306 let actor_id = match response_rx.await {
308 Ok(Ok(id)) => {
309 debug!("Actor started: {}", id);
310 id
311 }
312 Ok(Err(e)) => {
313 return Err(CliError::server_error(format!(
314 "Failed to start actor: {}",
315 e
316 )));
317 }
318 Err(e) => {
319 return Err(CliError::server_error(format!(
320 "Failed to receive spawn response: {}",
321 e
322 )));
323 }
324 };
325
326 loop {
336 tokio::select! {
337 result = supervisor_rx.recv() => {
339 match result {
340 Some(actor_result) => {
341 debug!("Actor exited: {:?}", actor_result);
342 match actor_result {
343 theater::messages::ActorResult::Success(success) => {
344 if let Some(output) = success.result {
345 let _ = std::io::stdout().write_all(&output);
347 let _ = std::io::stdout().flush();
348 }
349 }
350 theater::messages::ActorResult::Error(err) => {
351 eprintln!("Actor error: {}", err.error);
352 std::process::exit(1);
353 }
354 theater::messages::ActorResult::ExternalStop(_) => {
355 debug!("Actor stopped externally");
356 }
357 }
358 break;
359 }
360 None => {
361 debug!("Supervisor channel closed");
363 break;
364 }
365 }
366 }
367
368 event = global_events_rx.recv() => {
370 if let Some((event_actor_id, chain_event)) = event {
371 if args.events {
374 match args.events_format {
375 EventFormat::Json => {
376 println!("{}", format_event_json(&chain_event, &event_actor_id));
377 }
378 EventFormat::Short => {
379 print!("{}", format_event_short(&chain_event, &event_actor_id));
380 }
381 EventFormat::Full => {
382 print!("{}", format_event_full(&chain_event, &event_actor_id));
383 }
384 }
385 }
386
387 if event_actor_id == actor_id && chain_event.event_type == "shutdown" {
389 break;
390 }
391 }
392 }
393
394 _ = tokio::signal::ctrl_c() => {
396 debug!("Received Ctrl+C, stopping actor {}", actor_id);
397 eprintln!("\nStopping actor...");
398
399 let (stop_tx, stop_rx) = tokio::sync::oneshot::channel();
400 let _ = theater_tx.send(TheaterCommand::StopActor {
401 actor_id,
402 response_tx: stop_tx,
403 }).await;
404
405 match tokio::time::timeout(
407 tokio::time::Duration::from_secs(5),
408 stop_rx,
409 ).await {
410 Ok(Ok(Ok(()))) => debug!("Actor stopped gracefully"),
411 _ => debug!("Actor stop timed out or failed"),
412 }
413 break;
414 }
415
416 _ = ctx.shutdown_token.cancelled() => {
418 debug!("Shutdown token cancelled");
419 break;
420 }
421 }
422 }
423
424 drop(theater_tx);
426
427 let _ = tokio::time::timeout(tokio::time::Duration::from_secs(5), runtime_handle).await;
429
430 Ok(())
431}