hackshell 0.7.1

Lightweight, customizable shell framework
Documentation
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::thread;
use std::time::Duration;

use hackshell::taskpool::{TaskOptions, TaskPool};

#[test]
fn test_spawn_and_execute_task() {
    let pool = TaskPool::default();
    let executed = Arc::new(AtomicBool::new(false));
    let executed_clone = executed.clone();

    pool.spawn("test_task", TaskOptions::default(), move |run| {
        while run.load(Ordering::Relaxed) {
            executed_clone.store(true, Ordering::Relaxed);
            break;
        }
        None
    });

    thread::sleep(Duration::from_millis(50));
    assert!(executed.load(Ordering::Relaxed));
}

#[test]
fn test_task_metadata() {
    let pool = TaskPool::default();
    let task_name = "metadata_test";

    pool.spawn(task_name, TaskOptions::default(), |run| {
        while run.load(Ordering::Relaxed) {
            thread::sleep(Duration::from_millis(10));
        }
        None
    });

    let tasks = pool.get_all();
    assert_eq!(tasks.len(), 1);

    let task = &tasks[0];
    assert_eq!(task.name, task_name);
    assert!(task.started <= chrono::Utc::now());

    pool.remove(task_name).unwrap();
}

#[test]
fn test_remove_task() {
    let pool = TaskPool::default();
    let still_running = Arc::new(AtomicBool::new(true));
    let still_running_clone = still_running.clone();

    pool.spawn("removable_task", TaskOptions::default(), move |run| {
        while run.load(Ordering::Relaxed) {
            thread::sleep(Duration::from_millis(10));
        }
        still_running_clone.store(false, Ordering::Relaxed);
        None
    });

    thread::sleep(Duration::from_millis(50));
    assert!(still_running.load(Ordering::Relaxed));

    // Remove the task
    assert!(pool.remove("removable_task").is_ok());

    // Give time for the task to stop
    thread::sleep(Duration::from_millis(100));
    assert!(!still_running.load(Ordering::Relaxed));

    // Task should no longer be in the pool
    let tasks = pool.get_all();
    assert_eq!(tasks.len(), 0);
}

#[test]
fn test_remove_nonexistent_task() {
    let pool = TaskPool::default();
    assert!(pool.remove("nonexistent").is_err());
}

#[test]
fn test_join_for_task() {
    let pool = TaskPool::default();
    let completed = Arc::new(AtomicBool::new(false));
    let completed_clone = completed.clone();

    pool.spawn("join_task", TaskOptions::default(), move |_run| {
        thread::sleep(Duration::from_millis(100));
        completed_clone.store(true, Ordering::Relaxed);
        None
    });

    // Wait should block until task completes
    assert!(pool.join("join_task").is_ok());
    assert!(completed.load(Ordering::Relaxed));

    // Task should be automatically removed after completion
    let tasks = pool.get_all();
    assert_eq!(tasks.len(), 0);
}

#[test]
fn test_join_for_nonexistent_task() {
    let pool = TaskPool::default();
    // Waiting for a nonexistent task should return Ok (no-op)
    assert!(pool.join("nonexistent").is_ok());
}

#[test]
fn test_spawn_with_same_name_kills_previous() {
    let pool = TaskPool::default();
    let first_task_running = Arc::new(AtomicBool::new(true));
    let first_task_running_clone = first_task_running.clone();
    let second_task_started = Arc::new(AtomicBool::new(false));
    let second_task_started_clone = second_task_started.clone();

    // Spawn first task
    pool.spawn("duplicate_name", TaskOptions::default(), move |run| {
        while run.load(Ordering::Relaxed) {
            thread::sleep(Duration::from_millis(10));
        }
        first_task_running_clone.store(false, Ordering::Relaxed);
        None
    });

    thread::sleep(Duration::from_millis(50));
    assert!(first_task_running.load(Ordering::Relaxed));

    // Spawn second task with same name
    pool.spawn("duplicate_name", TaskOptions::default(), move |_run| {
        second_task_started_clone.store(true, Ordering::Relaxed);
        thread::sleep(Duration::from_millis(50));
        None
    });

    thread::sleep(Duration::from_millis(100));

    // First task should be killed
    assert!(!first_task_running.load(Ordering::Relaxed));
    // Second task should have started
    assert!(second_task_started.load(Ordering::Relaxed));
}

#[test]
fn test_multiple_tasks() {
    let pool = TaskPool::default();
    let counter = Arc::new(AtomicUsize::new(0));

    for i in 0..5 {
        let counter_clone = counter.clone();
        pool.spawn(
            &format!("task_{}", i),
            TaskOptions::default(),
            move |_run| {
                counter_clone.fetch_add(1, Ordering::Relaxed);
                thread::sleep(Duration::from_millis(50));
                None
            },
        );
    }

    thread::sleep(Duration::from_millis(100));

    // All tasks should have incremented the counter
    assert_eq!(counter.load(Ordering::Relaxed), 5);

    // All tasks should've ended
    let tasks = pool.get_all();
    assert_eq!(tasks.len(), 0);
}

#[test]
fn test_auto_removal_on_completion() {
    let pool = TaskPool::default();

    pool.spawn("auto_remove", TaskOptions::default(), |_run| {
        // Task completes immediately
        None
    });

    thread::sleep(Duration::from_millis(100));

    // Task should be automatically removed after completion
    let tasks = pool.get_all();
    assert_eq!(tasks.len(), 0);
}

#[test]
fn test_clone_pool() {
    let pool1 = TaskPool::default();
    let pool2 = pool1.clone();

    pool1.spawn("task_from_pool1", TaskOptions::default(), |_run| {
        thread::sleep(Duration::from_millis(100));
        None
    });

    // Should be able to see the task from cloned pool
    let tasks = pool2.get_all();
    assert_eq!(tasks.len(), 1);
    assert_eq!(tasks[0].name, "task_from_pool1");

    // Should be able to remove from cloned pool
    assert!(pool2.remove("task_from_pool1").is_ok());

    // Should be gone from both pools
    assert_eq!(pool1.get_all().len(), 0);
    assert_eq!(pool2.get_all().len(), 0);
}

#[cfg(feature = "async")]
mod async_tests {
    use super::*;
    use tokio;

    #[tokio::test]
    async fn test_spawn_async_task() {
        let pool = TaskPool::default();
        let executed = Arc::new(AtomicBool::new(false));
        let executed_clone = executed.clone();

        pool.spawn_async("async_task", TaskOptions::default(), async move {
            tokio::time::sleep(Duration::from_millis(50)).await;
            executed_clone.store(true, Ordering::Relaxed);
            None
        });

        tokio::time::sleep(Duration::from_millis(100)).await;
        assert!(executed.load(Ordering::Relaxed));
    }

    #[tokio::test]
    async fn test_async_task_metadata() {
        let pool = TaskPool::default();

        pool.spawn_async("async_metadata_test", TaskOptions::default(), async {
            tokio::time::sleep(Duration::from_millis(100)).await;
            None
        });

        let tasks = pool.get_all();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].name, "async_metadata_test");

        pool.remove("async_metadata_test").unwrap();
    }

    #[tokio::test]
    async fn test_kill_async_task() {
        let pool = TaskPool::default();
        let still_running = Arc::new(AtomicBool::new(true));
        let still_running_clone = still_running.clone();

        pool.spawn_async("killable_async", TaskOptions::default(), async move {
            tokio::time::sleep(Duration::from_secs(10)).await;
            still_running_clone.store(false, Ordering::Relaxed);
            None
        });

        tokio::time::sleep(Duration::from_millis(50)).await;
        assert!(still_running.load(Ordering::Relaxed));

        // Kill the task
        assert!(pool.remove("killable_async").is_ok());

        tokio::time::sleep(Duration::from_millis(100)).await;
        // Variable should still be "running" (true) because task was aborted, not completed
        assert!(still_running.load(Ordering::Relaxed));
    }

    #[tokio::test]
    async fn test_join_async_task() {
        let pool = TaskPool::default();
        let completed = Arc::new(AtomicBool::new(false));
        let completed_clone = completed.clone();

        pool.spawn_async("join_async", TaskOptions::default(), async move {
            tokio::time::sleep(Duration::from_millis(100)).await;
            completed_clone.store(true, Ordering::Relaxed);
            None
        });

        // Wait for the async task from sync context
        assert!(pool.join_async("join_async").await.is_ok());
        assert!(completed.load(Ordering::Relaxed));
    }

    #[tokio::test]
    async fn test_async_auto_removal() {
        let pool = TaskPool::default();

        pool.spawn_async("async_auto_remove", TaskOptions::default(), async {
            tokio::time::sleep(Duration::from_millis(50)).await;
            None
        });

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Task should be automatically removed after completion
        let tasks = pool.get_all();
        assert_eq!(tasks.len(), 0);
    }

    #[tokio::test]
    async fn test_mixed_sync_and_async_tasks() {
        let pool = TaskPool::default();
        let sync_counter = Arc::new(AtomicUsize::new(0));
        let async_counter = Arc::new(AtomicUsize::new(0));

        let sync_counter_clone = sync_counter.clone();
        pool.spawn("sync_task", TaskOptions::default(), move |_run| {
            sync_counter_clone.fetch_add(1, Ordering::Relaxed);
            None
        });

        let async_counter_clone = async_counter.clone();
        pool.spawn_async("async_task", TaskOptions::default(), async move {
            async_counter_clone.fetch_add(1, Ordering::Relaxed);
            None
        });

        assert!(pool.join("sync_task").is_ok());
        assert!(pool.join_async("async_task").await.is_ok());

        assert_eq!(sync_counter.load(Ordering::Relaxed), 1);
        assert_eq!(async_counter.load(Ordering::Relaxed), 1);

        // Both tasks should have auto-removed
        assert_eq!(pool.get_all().len(), 0);
    }

    #[tokio::test]
    async fn test_drop_kills_async_tasks() {
        let task_aborted = Arc::new(AtomicBool::new(false));
        let task_aborted_clone = task_aborted.clone();

        {
            let pool = TaskPool::default();

            pool.spawn_async("long_async", TaskOptions::default(), async move {
                tokio::time::sleep(Duration::from_secs(10)).await;
                // This should not execute if task is aborted
                task_aborted_clone.store(true, Ordering::Relaxed);
                None
            });

            // Ensure task is running
            tokio::time::sleep(Duration::from_millis(50)).await;

            // Pool is dropped here
        }

        // Give time for abort to propagate
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Task should have been aborted, not completed
        assert!(!task_aborted.load(Ordering::Relaxed));
    }

    #[tokio::test]
    async fn test_drop_kills_mixed_tasks() {
        let sync_stopped = Arc::new(AtomicBool::new(false));
        let sync_stopped_clone = sync_stopped.clone();
        let async_completed = Arc::new(AtomicBool::new(false));
        let async_completed_clone = async_completed.clone();

        {
            let pool = TaskPool::default();

            pool.spawn("sync_task", TaskOptions::default(), move |run| {
                while run.load(Ordering::Relaxed) {
                    thread::sleep(Duration::from_millis(10));
                }
                sync_stopped_clone.store(true, Ordering::Relaxed);
                None
            });

            pool.spawn_async("async_task", TaskOptions::default(), async move {
                tokio::time::sleep(Duration::from_secs(10)).await;
                async_completed_clone.store(true, Ordering::Relaxed);
                None
            });

            tokio::time::sleep(Duration::from_millis(50)).await;

            // Pool is dropped here
        }

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Sync task should have stopped gracefully
        assert!(sync_stopped.load(Ordering::Relaxed));
        // Async task should have been aborted
        assert!(!async_completed.load(Ordering::Relaxed));
    }
}

#[test]
fn test_concurrent_access() {
    let pool = TaskPool::default();
    let barrier = Arc::new(std::sync::Barrier::new(3));

    let pool1 = pool.clone();
    let barrier1 = barrier.clone();
    let handle1 = thread::spawn(move || {
        barrier1.wait();
        for i in 0..10 {
            pool1.spawn(
                &format!("thread1_task_{}", i),
                TaskOptions::default(),
                |_run| {
                    thread::sleep(Duration::from_millis(10));
                    None
                },
            );
        }
    });

    let pool2 = pool.clone();
    let barrier2 = barrier.clone();
    let handle2 = thread::spawn(move || {
        barrier2.wait();
        for i in 0..10 {
            pool2.spawn(
                &format!("thread2_task_{}", i),
                TaskOptions::default(),
                |_run| {
                    thread::sleep(Duration::from_millis(10));
                    None
                },
            );
        }
    });

    barrier.wait();

    handle1.join().unwrap();
    handle2.join().unwrap();

    thread::sleep(Duration::from_millis(100));

    // Should have no tasks
    let tasks = pool.get_all();
    assert!(tasks.len() == 0);
}

#[test]
fn test_drop_kills_running_tasks() {
    let task_stopped = Arc::new(AtomicBool::new(false));
    let task_stopped_clone = task_stopped.clone();

    {
        let pool = TaskPool::default();

        pool.spawn("long_running", TaskOptions::default(), move |run| {
            while run.load(Ordering::Relaxed) {
                thread::sleep(Duration::from_millis(10));
            }
            task_stopped_clone.store(true, Ordering::Relaxed);
            None
        });

        // Ensure task is running
        thread::sleep(Duration::from_millis(50));
        assert!(!task_stopped.load(Ordering::Relaxed));

        // Pool is dropped here
    }

    // Give time for task to receive stop signal and exit
    thread::sleep(Duration::from_millis(100));
    assert!(task_stopped.load(Ordering::Relaxed));
}

#[test]
fn test_drop_kills_multiple_tasks() {
    let stopped_count = Arc::new(AtomicUsize::new(0));

    {
        let pool = TaskPool::default();

        for i in 0..5 {
            let stopped_count_clone = stopped_count.clone();
            pool.spawn(&format!("task_{}", i), TaskOptions::default(), move |run| {
                while run.load(Ordering::Relaxed) {
                    thread::sleep(Duration::from_millis(10));
                }
                stopped_count_clone.fetch_add(1, Ordering::Relaxed);
                None
            });
        }

        // Ensure tasks are running
        thread::sleep(Duration::from_millis(50));
        assert_eq!(stopped_count.load(Ordering::Relaxed), 0);

        // Pool is dropped here
    }

    // Give time for tasks to stop
    thread::sleep(Duration::from_millis(100));
    assert_eq!(stopped_count.load(Ordering::Relaxed), 5);
}

#[test]
fn test_drop_only_when_last_clone_dropped() {
    let task_stopped = Arc::new(AtomicBool::new(false));
    let task_stopped_clone = task_stopped.clone();

    let pool1 = TaskPool::default();
    let pool2 = pool1.clone();

    pool1.spawn("shared_task", TaskOptions::default(), move |run| {
        while run.load(Ordering::Relaxed) {
            thread::sleep(Duration::from_millis(10));
        }
        task_stopped_clone.store(true, Ordering::Relaxed);
        None
    });

    thread::sleep(Duration::from_millis(50));

    // Drop first clone - task should still be running
    drop(pool1);
    thread::sleep(Duration::from_millis(50));
    assert!(!task_stopped.load(Ordering::Relaxed));

    // Drop second clone - task should now be killed
    drop(pool2);
    thread::sleep(Duration::from_millis(100));
    assert!(task_stopped.load(Ordering::Relaxed));
}

#[test]
fn test_hidden_task_not_in_default_listing() {
    let pool = TaskPool::default();

    pool.spawn("visible", TaskOptions::default(), |_run| {
        thread::sleep(Duration::from_millis(100));
        None
    });

    pool.spawn(
        "hidden",
        TaskOptions {
            hidden: true,
            ..Default::default()
        },
        |_run| {
            thread::sleep(Duration::from_millis(100));
            None
        },
    );

    // Default listing should only show visible task
    let tasks = pool.get_all();
    assert_eq!(tasks.len(), 1);
    assert_eq!(tasks[0].name, "visible");

    // Filtered listing should show both
    let all_tasks = pool.get_all_filtered(true);
    assert_eq!(all_tasks.len(), 2);

    pool.kill_all();
}

#[test]
fn test_hidden_task_metadata() {
    let pool = TaskPool::default();

    pool.spawn("visible", TaskOptions::default(), |_run| {
        thread::sleep(Duration::from_millis(100));
        None
    });

    pool.spawn(
        "hidden",
        TaskOptions {
            hidden: true,
            ..Default::default()
        },
        |_run| {
            thread::sleep(Duration::from_millis(100));
            None
        },
    );

    let all_tasks = pool.get_all_filtered(true);
    let visible = all_tasks.iter().find(|t| t.name == "visible").unwrap();
    let hidden = all_tasks.iter().find(|t| t.name == "hidden").unwrap();

    assert!(!visible.hidden);
    assert!(hidden.hidden);

    pool.kill_all();
}

#[test]
fn test_protected_task_cannot_be_terminated_via_command() {
    use hackshell::{Hackshell, error::HackshellError};

    let shell = Hackshell::new("> ").unwrap();

    // Spawn a protected task
    shell.spawn(
        "protected_task",
        TaskOptions {
            protected: true,
            ..Default::default()
        },
        |run| {
            while run.load(Ordering::Relaxed) {
                thread::sleep(Duration::from_millis(10));
            }
            None
        },
    );

    thread::sleep(Duration::from_millis(50));

    // Trying to terminate via the task command should fail
    let result = shell.feed_line("task --terminate protected_task");
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        HackshellError::TaskIsProtected
    ));

    // Task should still be running
    let tasks = shell.get_tasks();
    assert_eq!(tasks.len(), 1);
    assert_eq!(tasks[0].name, "protected_task");

    // Programmatic termination should work
    assert!(shell.terminate("protected_task").is_ok());

    thread::sleep(Duration::from_millis(50));

    // Task should be gone
    let tasks = shell.get_tasks();
    assert!(tasks.is_empty());
}