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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Command execution logic extracted from Program for testability
use super::error_handler::{DefaultErrorHandler, ErrorHandler};
use crate::panic_utils;
use crate::resource_limits::{ResourceLimits, ResourceMonitor};
use crate::shared_runtime::shared_runtime;
use hojicha_core::core::Cmd;
use hojicha_core::event::Event;
use log::error;
use std::panic::{self, AssertUnwindSafe};
use std::sync::atomic::AtomicUsize;
use std::sync::{mpsc, Arc};
use tokio::runtime::Runtime;
/// Executes commands and sends resulting messages
#[derive(Clone)]
pub struct CommandExecutor<M = ()> {
runtime: Arc<Runtime>,
error_handler: Arc<dyn ErrorHandler<M> + Send + Sync>,
resource_monitor: Arc<ResourceMonitor>,
_recursion_depth: Arc<AtomicUsize>,
}
impl<M> CommandExecutor<M>
where
M: Clone + Send + 'static,
{
/// Create a new command executor with default error handler
pub fn new() -> std::io::Result<Self> {
Ok(Self {
runtime: shared_runtime(),
error_handler: Arc::new(DefaultErrorHandler),
resource_monitor: Arc::new(ResourceMonitor::new()),
_recursion_depth: Arc::new(AtomicUsize::new(0)),
})
}
/// Create a new command executor with custom error handler
pub fn with_error_handler<H>(error_handler: H) -> std::io::Result<Self>
where
H: ErrorHandler<M> + Send + Sync + 'static,
{
Ok(Self {
runtime: shared_runtime(),
error_handler: Arc::new(error_handler),
resource_monitor: Arc::new(ResourceMonitor::new()),
_recursion_depth: Arc::new(AtomicUsize::new(0)),
})
}
/// Create a new command executor with custom resource limits
pub fn with_resource_limits(limits: ResourceLimits) -> std::io::Result<Self> {
Ok(Self {
runtime: shared_runtime(),
error_handler: Arc::new(DefaultErrorHandler),
resource_monitor: Arc::new(ResourceMonitor::with_limits(limits)),
_recursion_depth: Arc::new(AtomicUsize::new(0)),
})
}
/// Get current resource statistics
pub fn resource_stats(&self) -> crate::resource_limits::ResourceStats {
self.resource_monitor.stats()
}
/// Spawn a task with resource limit checking
fn spawn_with_limits<F>(&self, f: F)
where
F: std::future::Future<Output = ()> + Send + 'static,
{
let monitor = self.resource_monitor.clone();
let runtime = self.runtime.clone();
// Try to spawn with resource checking
runtime.spawn(async move {
match monitor.try_acquire_task_permit().await {
Ok(_permit) => {
// Permit will be dropped when task completes
f.await;
}
Err(e) => {
error!("Failed to spawn task: {}", e);
}
}
});
}
/// Execute a command and send the result through the channel
pub fn execute(&self, cmd: Cmd<M>, tx: &mpsc::SyncSender<Event<M>>) {
if cmd.is_noop() {
// NoOp command - do nothing
} else if cmd.is_quit() {
// Handle quit command by sending a special quit event
let _ = tx.send(Event::Quit);
} else if cmd.is_exec_process() {
// Handle exec process commands specially
if let Some((_program, _args, _callback)) = cmd.take_exec_process() {
// For testing, we just send an ExecProcess event
// The actual process execution would be handled by the Program
let _ = tx.send(Event::ExecProcess);
}
} else if cmd.is_batch() {
// Handle batch commands by executing them concurrently
if let Some(cmds) = cmd.take_batch() {
self.execute_batch(cmds, tx);
}
} else if cmd.is_sequence() {
// Handle sequence commands by executing them in order
if let Some(cmds) = cmd.take_sequence() {
self.execute_sequence(cmds, tx);
}
} else if cmd.is_tick() {
// Handle tick command with async delay
if let Some((duration, callback)) = cmd.take_tick() {
let tx_clone = tx.clone();
self.spawn_with_limits(async move {
tokio::time::sleep(duration).await;
// Wrap callback execution in panic recovery
let result = panic::catch_unwind(AssertUnwindSafe(callback));
match result {
Ok(msg) => {
let _ = tx_clone.send(Event::User(msg));
}
Err(panic) => {
let panic_msg =
panic_utils::format_panic_message(panic, "Tick callback panicked");
eprintln!("{}", panic_msg);
// Continue running - don't crash the application
}
}
});
}
} else if cmd.is_every() {
// Handle every command with recurring async timer
if let Some((duration, callback)) = cmd.take_every() {
let tx_clone = tx.clone();
self.spawn_with_limits(async move {
// Since callback is FnOnce, we can only call it once
// For now, just execute once after delay
tokio::time::sleep(duration).await;
// Wrap callback execution in panic recovery
let result = panic::catch_unwind(AssertUnwindSafe(|| {
callback(std::time::Instant::now())
}));
match result {
Ok(msg) => {
let _ = tx_clone.send(Event::User(msg));
}
Err(panic) => {
let panic_msg =
panic_utils::format_panic_message(panic, "Every callback panicked");
eprintln!("{}", panic_msg);
// Continue running - don't crash the application
}
}
});
}
} else if cmd.is_async() {
// Handle async command using shared runtime
if let Some(future) = cmd.take_async() {
let tx_clone = tx.clone();
self.spawn_with_limits(async move {
// SAFETY: The future is already boxed and will not be moved.
// This is safe because we immediately await it without moving.
// TODO: Use Pin::from(Box::pin(future)) for safer alternative
use std::pin::Pin;
let mut future = future;
let future = unsafe { Pin::new_unchecked(&mut *future) };
// Actually await the future
if let Some(msg) = future.await {
let _ = tx_clone.send(Event::User(msg));
}
});
}
} else {
// Spawn async task for regular command execution (like Bubbletea's goroutines)
let tx_clone = tx.clone();
let error_handler = self.error_handler.clone();
self.spawn_with_limits(async move {
// Wrap command execution in panic recovery
let result = panic::catch_unwind(AssertUnwindSafe(|| cmd.execute()));
match result {
Ok(Ok(Some(msg))) => {
let _ = tx_clone.send(Event::User(msg));
}
Ok(Ok(None)) => {
// Command executed successfully but produced no message
}
Ok(Err(error)) => {
// Use the configured error handler
error_handler.handle_error(error, &tx_clone);
}
Err(panic) => {
// Command panicked - log and recover
let panic_msg =
panic_utils::format_panic_message(panic, "Command execution panicked");
eprintln!("{}", panic_msg);
// Continue running - don't crash the application
}
}
});
}
}
/// Execute a batch of commands concurrently
pub fn execute_batch(&self, commands: Vec<Cmd<M>>, tx: &mpsc::SyncSender<Event<M>>) {
// Spawn all commands concurrently (like Bubbletea's batch)
for cmd in commands {
// Each command runs in its own async task
self.execute(cmd, tx);
}
}
/// Execute a sequence of commands (one after another)
pub fn execute_sequence(&self, commands: Vec<Cmd<M>>, tx: &mpsc::SyncSender<Event<M>>) {
// Spawn async task to execute commands in sequence
let tx_clone = tx.clone();
let error_handler = self.error_handler.clone();
self.spawn_with_limits(async move {
for cmd in commands {
let tx_inner = tx_clone.clone();
// Execute the command through the regular execution path
if cmd.is_tick() {
if let Some((duration, callback)) = cmd.take_tick() {
tokio::time::sleep(duration).await;
// Wrap callback execution in panic recovery
let result = panic::catch_unwind(AssertUnwindSafe(callback));
match result {
Ok(msg) => {
let _ = tx_inner.send(Event::User(msg));
}
Err(panic) => {
let panic_msg = if let Some(s) = panic.downcast_ref::<String>() {
s.clone()
} else if let Some(s) = panic.downcast_ref::<&str>() {
s.to_string()
} else {
"Unknown panic in tick callback".to_string()
};
eprintln!("Tick callback panicked: {}", panic_msg);
// Continue running - don't crash the application
}
}
}
} else if cmd.is_every() {
if let Some((duration, callback)) = cmd.take_every() {
tokio::time::sleep(duration).await;
// Wrap callback execution in panic recovery
let result = panic::catch_unwind(AssertUnwindSafe(|| {
callback(std::time::Instant::now())
}));
match result {
Ok(msg) => {
let _ = tx_inner.send(Event::User(msg));
}
Err(panic) => {
let panic_msg = if let Some(s) = panic.downcast_ref::<String>() {
s.clone()
} else if let Some(s) = panic.downcast_ref::<&str>() {
s.to_string()
} else {
"Unknown panic in every callback".to_string()
};
eprintln!("Every callback panicked: {}", panic_msg);
// Continue running - don't crash the application
}
}
}
} else {
// Regular command execution with panic recovery
let result = panic::catch_unwind(AssertUnwindSafe(|| cmd.execute()));
match result {
Ok(Ok(Some(msg))) => {
let _ = tx_inner.send(Event::User(msg));
}
Ok(Ok(None)) => {}
Ok(Err(error)) => {
// Use the configured error handler
error_handler.handle_error(error, &tx_inner);
}
Err(panic) => {
let panic_msg = panic_utils::format_panic_message(
panic,
"Sequence command panicked",
);
eprintln!("{}", panic_msg);
// Continue running - don't crash the application
}
}
}
}
});
}
/// Spawn a future on the runtime with resource limit checking
pub fn spawn<F>(&self, future: F) -> tokio::task::JoinHandle<F::Output>
where
F: std::future::Future + Send + 'static,
F::Output: Send + 'static,
{
let monitor = self.resource_monitor.clone();
let runtime = self.runtime.clone();
// Spawn wrapper task that acquires permit first
runtime.spawn(async move {
match monitor.try_acquire_task_permit().await {
Ok(_permit) => {
// Permit will be dropped when task completes
future.await
}
Err(e) => {
error!("Failed to spawn task due to resource limits: {}", e);
// Since we can't change the API to return Result, we have to
// handle this gracefully. For futures that return Option or Result,
// we'd ideally return None or an error. For now, we'll use a
// workaround by creating a future that immediately completes with
// a default value.
// This is a known limitation - in production code, consider using
// spawn_with_result that returns Result<JoinHandle, Error>
std::future::pending().await
}
}
})
}
/// Block on the runtime to ensure all tasks complete (for testing)
pub fn block_on<F: std::future::Future>(&self, future: F) -> F::Output {
self.runtime.block_on(future)
}
}
impl<M> Default for CommandExecutor<M>
where
M: Clone + Send + 'static,
{
fn default() -> Self {
Self::new().expect("Failed to create runtime")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::AsyncTestHarness;
use hojicha_core::commands;
use std::time::Duration;
#[derive(Debug, Clone, PartialEq)]
enum TestMsg {
Inc,
Dec,
Text(String),
}
#[test]
fn test_execute_custom_command() {
// Using AsyncTestHarness for cleaner testing
let harness = AsyncTestHarness::new();
let cmd = commands::custom(|| Some(TestMsg::Inc));
let messages = harness.execute_command(cmd);
assert_eq!(messages, vec![TestMsg::Inc]);
}
#[test]
fn test_execute_custom_command_raw() {
// Keep raw test to verify CommandExecutor directly
let executor = CommandExecutor::<TestMsg>::new().unwrap();
let (tx, rx) = mpsc::sync_channel(10);
let cmd = commands::custom(|| Some(TestMsg::Inc));
executor.execute(cmd, &tx);
// Give async task time to execute
std::thread::sleep(Duration::from_millis(10));
let event = rx.try_recv().unwrap();
assert_eq!(event, Event::User(TestMsg::Inc));
}
#[test]
fn test_execute_quit_command() {
let executor = CommandExecutor::<TestMsg>::new().unwrap();
let (tx, rx) = mpsc::sync_channel(10);
let cmd: Cmd<TestMsg> = commands::quit();
executor.execute(cmd, &tx);
let event = rx.recv_timeout(Duration::from_millis(100)).unwrap();
assert_eq!(event, Event::Quit);
}
#[test]
fn test_execute_batch_commands() {
// Using AsyncTestHarness for cleaner testing
let harness = AsyncTestHarness::new();
let batch = commands::batch(vec![
commands::custom(|| Some(TestMsg::Inc)),
commands::custom(|| Some(TestMsg::Dec)),
commands::custom(|| Some(TestMsg::Text("test".to_string()))),
]);
let messages = harness.execute_command(batch);
assert_eq!(messages.len(), 3);
assert!(messages.contains(&TestMsg::Inc));
assert!(messages.contains(&TestMsg::Dec));
assert!(messages.contains(&TestMsg::Text("test".to_string())));
}
#[test]
fn test_execute_none_command() {
let executor = CommandExecutor::<TestMsg>::new().unwrap();
let (tx, rx) = mpsc::sync_channel(10);
// Cmd::noop() returns Option<Cmd>, which is None
// So we test with a cmd that does nothing
let cmd: Cmd<TestMsg> = commands::custom(|| None);
executor.execute(cmd, &tx);
// Give async task time to execute
std::thread::sleep(Duration::from_millis(10));
// Should not receive any event
assert!(rx.try_recv().is_err());
}
#[test]
fn test_execute_tick_command() {
// Using AsyncTestHarness for cleaner testing
let harness = AsyncTestHarness::new();
let cmd = commands::tick(Duration::from_millis(10), || TestMsg::Inc);
let messages = harness.execute_command(cmd);
assert_eq!(messages, vec![TestMsg::Inc]);
}
#[test]
fn test_execute_tick_command_raw() {
// Keep raw test to verify CommandExecutor directly
let executor = CommandExecutor::<TestMsg>::new().unwrap();
let (tx, rx) = mpsc::sync_channel(10);
let cmd = commands::tick(Duration::from_millis(10), || TestMsg::Inc);
executor.execute(cmd, &tx);
// Wait for tick
let event = rx.recv_timeout(Duration::from_millis(50)).unwrap();
if let Event::User(msg) = event {
assert_eq!(msg, TestMsg::Inc);
} else {
panic!("Expected User event");
}
}
#[test]
fn test_execute_sequence() {
// Using AsyncTestHarness for cleaner testing
let harness = AsyncTestHarness::new();
let seq = commands::sequence(vec![
commands::custom(|| Some(TestMsg::Inc)),
commands::custom(|| Some(TestMsg::Dec)),
]);
let messages = harness.execute_and_wait(seq, Duration::from_millis(50));
// Sequence should maintain order
assert_eq!(messages.len(), 2);
assert_eq!(messages[0], TestMsg::Inc);
assert_eq!(messages[1], TestMsg::Dec);
}
#[test]
fn test_multiple_executors() {
let executor1 = CommandExecutor::<TestMsg>::new().unwrap();
let executor2 = CommandExecutor::<TestMsg>::new().unwrap();
let (tx, rx) = mpsc::sync_channel(10);
executor1.execute(commands::custom(|| Some(TestMsg::Inc)), &tx);
executor2.execute(commands::custom(|| Some(TestMsg::Dec)), &tx);
// Give async tasks time to execute
std::thread::sleep(Duration::from_millis(50));
let mut events = Vec::new();
while let Ok(Event::User(msg)) = rx.try_recv() {
events.push(msg);
}
assert_eq!(events.len(), 2);
assert!(events.contains(&TestMsg::Inc));
assert!(events.contains(&TestMsg::Dec));
}
}