zinit 0.3.9

Process supervisor with dependency management
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! Blocking handle for Rhai to communicate with RPC client
//!
//! This handle provides simple blocking methods that Rhai functions can call.
//! Each method sends a command to an async thread and blocks waiting for the response.

use super::client::{
    AddServiceResult, ChildrenResponse, LogLevel, LogLine, PingResponse, PrepareRestartResult,
    ServiceConfig, ServiceInfo, ServiceStats, ServiceStatus, ServiceStatusFull, WhyBlocked,
    XinetConfig, XinetStatus, XinetStatusFull, ZinitClient,
};
use anyhow::{Result, anyhow};
use serde_json::Value;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

/// Command enum for RPC operations
enum RpcCmd {
    // RPC commands
    Discover {
        reply: mpsc::Sender<Result<Value>>,
    },

    // System commands
    Ping {
        reply: mpsc::Sender<Result<PingResponse>>,
    },
    Shutdown {
        reply: mpsc::Sender<Result<()>>,
    },
    Reboot {
        reply: mpsc::Sender<Result<()>>,
    },
    PrepareRestart {
        reply: mpsc::Sender<Result<PrepareRestartResult>>,
    },

    // Service commands
    ServiceSet {
        config: Box<ServiceConfig>,
        reply: mpsc::Sender<Result<AddServiceResult>>,
    },
    ServiceGet {
        name: String,
        reply: mpsc::Sender<Result<ServiceConfig>>,
    },
    ServiceDelete {
        name: String,
        reply: mpsc::Sender<Result<()>>,
    },
    List {
        reply: mpsc::Sender<Result<Vec<String>>>,
    },
    ListFull {
        reply: mpsc::Sender<Result<Vec<ServiceInfo>>>,
    },
    Start {
        name: String,
        reply: mpsc::Sender<Result<()>>,
    },
    Stop {
        name: String,
        reply: mpsc::Sender<Result<()>>,
    },
    Restart {
        name: String,
        reply: mpsc::Sender<Result<()>>,
    },
    Kill {
        name: String,
        signal: Option<String>,
        reply: mpsc::Sender<Result<()>>,
    },
    Status {
        name: String,
        reply: mpsc::Sender<Result<ServiceStatus>>,
    },
    StatusFull {
        name: String,
        reply: mpsc::Sender<Result<ServiceStatusFull>>,
    },
    Stats {
        name: String,
        reply: mpsc::Sender<Result<ServiceStats>>,
    },
    Children {
        name: String,
        reply: mpsc::Sender<Result<ChildrenResponse>>,
    },
    IsRunning {
        name: String,
        reply: mpsc::Sender<Result<bool>>,
    },
    Why {
        name: String,
        reply: mpsc::Sender<Result<WhyBlocked>>,
    },
    Tree {
        reply: mpsc::Sender<Result<String>>,
    },

    // Log commands
    Logs {
        name: Option<String>,
        lines: Option<usize>,
        reply: mpsc::Sender<Result<Vec<String>>>,
    },
    LogsTail {
        name: Option<String>,
        lines: Option<usize>,
        reply: mpsc::Sender<Result<Vec<LogLine>>>,
    },
    LogsFilter {
        name: Option<String>,
        stream: Option<String>,
        since: Option<u64>,
        lines: Option<usize>,
        reply: mpsc::Sender<Result<Vec<LogLine>>>,
    },

    // Debug commands
    DebugState {
        reply: mpsc::Sender<Result<String>>,
    },
    DebugProcessTree {
        name: String,
        reply: mpsc::Sender<Result<String>>,
    },

    // Xinet commands
    XinetSet {
        config: Box<XinetConfig>,
        reply: mpsc::Sender<Result<()>>,
    },
    XinetDelete {
        name: String,
        reply: mpsc::Sender<Result<()>>,
    },
    XinetList {
        reply: mpsc::Sender<Result<Vec<String>>>,
    },
    XinetStatus {
        name: String,
        reply: mpsc::Sender<Result<XinetStatus>>,
    },
    XinetStatusAll {
        reply: mpsc::Sender<Result<Vec<XinetStatusFull>>>,
    },
}

/// Synchronous handle for Rhai functions to use
#[derive(Clone)]
pub struct ZinitHandle {
    cmd_tx: mpsc::Sender<RpcCmd>,
    log_level: LogLevel,
}

impl ZinitHandle {
    /// Create a new handle that connects to the default server.
    /// Performs a health check (ping) to verify the connection is working.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The default socket path cannot be determined
    /// - The zinit server is not running or not reachable
    /// - The ping request fails
    pub fn new() -> Result<Self> {
        let client = ZinitClient::try_default()?;
        let handle = Self::with_client(client)?;

        // Verify connection with a ping (health check)
        handle.test_connection()?;

        Ok(handle)
    }

    /// Create a new handle without health check (for advanced use cases).
    ///
    /// Use this when you want to defer the connection test or handle it manually.
    /// Call `test_connection()` afterwards to verify the connection.
    pub fn new_unchecked() -> Result<Self> {
        let client = ZinitClient::try_default()?;
        Self::with_client(client)
    }

    /// Create a new handle connecting to a specific socket path.
    /// Performs a health check (ping) to verify the connection is working.
    ///
    /// # Arguments
    ///
    /// * `socket_path` - Path to the Unix socket file
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The zinit server is not running or not reachable at the specified path
    /// - The ping request fails
    pub fn with_socket<P: AsRef<std::path::Path>>(socket_path: P) -> Result<Self> {
        let client = ZinitClient::unix(socket_path);
        let handle = Self::with_client(client)?;

        // Verify connection with a ping (health check)
        handle.test_connection()?;

        Ok(handle)
    }

    /// Create a new handle connecting to a specific socket path without health check.
    ///
    /// Use this when you want to defer the connection test or handle it manually.
    /// Call `test_connection()` afterwards to verify the connection.
    pub fn with_socket_unchecked<P: AsRef<std::path::Path>>(socket_path: P) -> Result<Self> {
        let client = ZinitClient::unix(socket_path);
        Self::with_client(client)
    }

    /// Create a new handle with a specific client
    pub fn with_client(client: ZinitClient) -> Result<Self> {
        let (cmd_tx, cmd_rx) = mpsc::channel::<RpcCmd>();
        let client_clone = client.clone();

        // Spawn the async worker thread
        thread::spawn(move || {
            let client = client_clone;
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .expect("Failed to create tokio runtime");

            rt.block_on(async {
                while let Ok(cmd) = cmd_rx.recv() {
                    match cmd {
                        // RPC commands
                        RpcCmd::Discover { reply } => {
                            let _ = reply.send(client.discover().await);
                        }

                        // System commands
                        RpcCmd::Ping { reply } => {
                            let _ = reply.send(client.ping().await);
                        }
                        RpcCmd::Shutdown { reply } => {
                            let _ = reply.send(client.shutdown().await);
                        }
                        RpcCmd::Reboot { reply } => {
                            let _ = reply.send(client.reboot().await);
                        }
                        RpcCmd::PrepareRestart { reply } => {
                            let _ = reply.send(client.prepare_restart().await);
                        }

                        // Service commands
                        RpcCmd::ServiceSet { config, reply } => {
                            let _ = reply.send(client.service_set(&config).await);
                        }
                        RpcCmd::ServiceGet { name, reply } => {
                            let _ = reply.send(client.service_get(&name).await);
                        }
                        RpcCmd::ServiceDelete { name, reply } => {
                            let _ = reply.send(client.service_delete(&name).await);
                        }
                        RpcCmd::List { reply } => {
                            let _ = reply.send(client.list().await);
                        }
                        RpcCmd::ListFull { reply } => {
                            let _ = reply.send(client.list_full().await);
                        }
                        RpcCmd::Start { name, reply } => {
                            let _ = reply.send(client.start(&name).await);
                        }
                        RpcCmd::Stop { name, reply } => {
                            let _ = reply.send(client.stop(&name).await);
                        }
                        RpcCmd::Restart { name, reply } => {
                            let _ = reply.send(client.restart(&name).await);
                        }
                        RpcCmd::Kill {
                            name,
                            signal,
                            reply,
                        } => {
                            let _ = reply.send(client.kill(&name, signal.as_deref()).await);
                        }
                        RpcCmd::Status { name, reply } => {
                            let _ = reply.send(client.status(&name).await);
                        }
                        RpcCmd::StatusFull { name, reply } => {
                            let _ = reply.send(client.status_full(&name).await);
                        }
                        RpcCmd::Stats { name, reply } => {
                            let _ = reply.send(client.stats(&name).await);
                        }
                        RpcCmd::Children { name, reply } => {
                            let _ = reply.send(client.children(&name).await);
                        }
                        RpcCmd::IsRunning { name, reply } => {
                            let _ = reply.send(client.is_running(&name).await);
                        }
                        RpcCmd::Why { name, reply } => {
                            let _ = reply.send(client.why(&name).await);
                        }
                        RpcCmd::Tree { reply } => {
                            let _ = reply.send(client.tree().await);
                        }

                        // Log commands
                        RpcCmd::Logs { name, lines, reply } => {
                            let _ = reply.send(client.logs(name.as_deref(), lines).await);
                        }
                        RpcCmd::LogsTail { name, lines, reply } => {
                            let _ = reply.send(client.logs_tail(name.as_deref(), lines).await);
                        }
                        RpcCmd::LogsFilter {
                            name,
                            stream,
                            since,
                            lines,
                            reply,
                        } => {
                            let _ = reply.send(
                                client
                                    .logs_filter(name.as_deref(), stream.as_deref(), since, lines)
                                    .await,
                            );
                        }

                        // Debug commands
                        RpcCmd::DebugState { reply } => {
                            let _ = reply.send(client.debug_state().await);
                        }
                        RpcCmd::DebugProcessTree { name, reply } => {
                            let _ = reply.send(client.debug_process_tree(&name).await);
                        }

                        // Xinet commands
                        RpcCmd::XinetSet { config, reply } => {
                            let _ = reply.send(client.xinet_set(&config).await);
                        }
                        RpcCmd::XinetDelete { name, reply } => {
                            let _ = reply.send(client.xinet_delete(&name).await);
                        }
                        RpcCmd::XinetList { reply } => {
                            let _ = reply.send(client.xinet_list().await);
                        }
                        RpcCmd::XinetStatus { name, reply } => {
                            let _ = reply.send(client.xinet_status(&name).await);
                        }
                        RpcCmd::XinetStatusAll { reply } => {
                            let _ = reply.send(client.xinet_status_all().await);
                        }
                    }
                }
            });
        });

        let log_level = client.log_level();
        Ok(Self { cmd_tx, log_level })
    }

    /// Set the log level for this handle
    pub fn with_log_level(mut self, level: LogLevel) -> Self {
        self.log_level = level;
        self
    }

    /// Log a message if the current level allows it
    fn log(&self, min_level: LogLevel, message: &str) {
        self.log_level.log(min_level, message);
    }

    /// Helper to send command and wait for response
    fn send_recv<T>(&self, cmd_fn: impl FnOnce(mpsc::Sender<Result<T>>) -> RpcCmd) -> Result<T> {
        let (reply_tx, reply_rx) = mpsc::channel();
        let cmd = cmd_fn(reply_tx);
        self.cmd_tx
            .send(cmd)
            .map_err(|_| anyhow!("RPC thread not available"))?;
        reply_rx
            .recv_timeout(Duration::from_secs(5))
            .map_err(|_| anyhow!("Failed to connect to zinit server: connection timed out (server not running?)"))?
    }

    // ============ RPC ============

    /// Returns the OpenRPC specification
    pub fn discover(&self) -> Result<Value> {
        self.send_recv(|reply| RpcCmd::Discover { reply })
    }

    // ============ System ============

    /// Ping the server and get version info
    pub fn ping(&self) -> Result<PingResponse> {
        self.send_recv(|reply| RpcCmd::Ping { reply })
    }

    /// Test connection to the zinit server by performing a ping.
    ///
    /// Returns `Ok(version)` if the connection is successful, or an error
    /// with a descriptive message if the connection fails.
    ///
    /// This method is useful for explicitly verifying the connection
    /// after creating a handle with `new_unchecked()`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use zinit::ZinitHandle;
    ///
    /// let handle = ZinitHandle::new_unchecked()?;
    /// let version = handle.test_connection()?;
    /// println!("Connected to zinit server version: {}", version);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn test_connection(&self) -> Result<String> {
        self.ping()
            .map(|resp| resp.version)
            .map_err(|e| anyhow!("Failed to connect to zinit server: {}", e))
    }

    /// Request daemon shutdown
    pub fn shutdown(&self) -> Result<()> {
        self.send_recv(|reply| RpcCmd::Shutdown { reply })
    }

    /// Reboot the system (Linux only, requires PID 1)
    pub fn reboot(&self) -> Result<()> {
        self.send_recv(|reply| RpcCmd::Reboot { reply })
    }

    /// Prepare for hot restart by saving state to disk
    pub fn prepare_restart(&self) -> Result<PrepareRestartResult> {
        self.send_recv(|reply| RpcCmd::PrepareRestart { reply })
    }

    // ============ Service Management ============

    /// Create or update a service (always persisted)
    pub fn service_set(&self, config: ServiceConfig) -> Result<AddServiceResult> {
        let service_name = config.service.name.clone();
        let result = self.send_recv(|reply| RpcCmd::ServiceSet {
            config: Box::new(config),
            reply,
        });
        if result.is_ok() {
            self.log(LogLevel::Minimal, &format!("✓ Created: {}", service_name));
        }
        result
    }

    /// Get service configuration
    pub fn service_get(&self, name: &str) -> Result<ServiceConfig> {
        self.send_recv(|reply| RpcCmd::ServiceGet {
            name: name.to_string(),
            reply,
        })
    }

    /// Delete a service (stop and remove)
    pub fn service_delete(&self, name: &str) -> Result<()> {
        let result = self.send_recv(|reply| RpcCmd::ServiceDelete {
            name: name.to_string(),
            reply,
        });
        if result.is_ok() {
            self.log(LogLevel::Minimal, &format!("✓ Deleted: {}", name));
        }
        result
    }

    /// List all services
    pub fn list(&self) -> Result<Vec<String>> {
        self.send_recv(|reply| RpcCmd::List { reply })
    }

    /// List all services with state information
    pub fn list_full(&self) -> Result<Vec<ServiceInfo>> {
        self.send_recv(|reply| RpcCmd::ListFull { reply })
    }

    /// Start a service
    pub fn start(&self, name: &str) -> Result<()> {
        let result = self.send_recv(|reply| RpcCmd::Start {
            name: name.to_string(),
            reply,
        });
        if result.is_ok() {
            self.log(LogLevel::Minimal, &format!("✓ Started: {}", name));
        }
        result
    }

    /// Stop a service
    pub fn stop(&self, name: &str) -> Result<()> {
        let result = self.send_recv(|reply| RpcCmd::Stop {
            name: name.to_string(),
            reply,
        });
        if result.is_ok() {
            self.log(LogLevel::Minimal, &format!("✓ Stopped: {}", name));
        }
        result
    }

    /// Restart a service
    pub fn restart(&self, name: &str) -> Result<()> {
        let result = self.send_recv(|reply| RpcCmd::Restart {
            name: name.to_string(),
            reply,
        });
        if result.is_ok() {
            self.log(LogLevel::Minimal, &format!("✓ Restarted: {}", name));
        }
        result
    }

    /// Send a signal to a service
    pub fn kill(&self, name: &str, signal: Option<&str>) -> Result<()> {
        let result = self.send_recv(|reply| RpcCmd::Kill {
            name: name.to_string(),
            signal: signal.map(|s| s.to_string()),
            reply,
        });
        if result.is_ok() {
            let sig = signal.unwrap_or("TERM");
            self.log(LogLevel::Minimal, &format!("✓ Sent {} to: {}", sig, name));
        }
        result
    }

    /// Get service status (simplified)
    pub fn status(&self, name: &str) -> Result<ServiceStatus> {
        self.send_recv(|reply| RpcCmd::Status {
            name: name.to_string(),
            reply,
        })
    }

    /// Get detailed service status with dependencies and uptime
    pub fn status_full(&self, name: &str) -> Result<ServiceStatusFull> {
        self.send_recv(|reply| RpcCmd::StatusFull {
            name: name.to_string(),
            reply,
        })
    }

    /// Get CPU and memory statistics for a service
    pub fn stats(&self, name: &str) -> Result<ServiceStats> {
        self.send_recv(|reply| RpcCmd::Stats {
            name: name.to_string(),
            reply,
        })
    }

    /// Get child processes for a service
    pub fn children(&self, name: &str) -> Result<ChildrenResponse> {
        self.send_recv(|reply| RpcCmd::Children {
            name: name.to_string(),
            reply,
        })
    }

    /// Check if a service is currently running
    pub fn is_running(&self, name: &str) -> Result<bool> {
        self.send_recv(|reply| RpcCmd::IsRunning {
            name: name.to_string(),
            reply,
        })
    }

    /// Get information about why a service is blocked
    pub fn why(&self, name: &str) -> Result<WhyBlocked> {
        self.send_recv(|reply| RpcCmd::Why {
            name: name.to_string(),
            reply,
        })
    }

    /// Get the dependency tree as ASCII art
    pub fn tree(&self) -> Result<String> {
        self.send_recv(|reply| RpcCmd::Tree { reply })
    }

    // ============ Logs ============

    /// Get logs (simplified, returns strings)
    pub fn logs(&self, name: Option<&str>, lines: Option<usize>) -> Result<Vec<String>> {
        self.send_recv(|reply| RpcCmd::Logs {
            name: name.map(|s| s.to_string()),
            lines,
            reply,
        })
    }

    /// Get structured log entries
    pub fn logs_tail(&self, name: Option<&str>, lines: Option<usize>) -> Result<Vec<LogLine>> {
        self.send_recv(|reply| RpcCmd::LogsTail {
            name: name.map(|s| s.to_string()),
            lines,
            reply,
        })
    }

    /// Get filtered log entries
    pub fn logs_filter(
        &self,
        name: Option<&str>,
        stream: Option<&str>,
        since: Option<u64>,
        lines: Option<usize>,
    ) -> Result<Vec<LogLine>> {
        self.send_recv(|reply| RpcCmd::LogsFilter {
            name: name.map(|s| s.to_string()),
            stream: stream.map(|s| s.to_string()),
            since,
            lines,
            reply,
        })
    }

    // ============ Debug ============

    /// Get full supervisor state for debugging
    pub fn debug_state(&self) -> Result<String> {
        self.send_recv(|reply| RpcCmd::DebugState { reply })
    }

    /// Get process tree for a service
    pub fn debug_process_tree(&self, name: &str) -> Result<String> {
        self.send_recv(|reply| RpcCmd::DebugProcessTree {
            name: name.to_string(),
            reply,
        })
    }

    // ============ Xinet ============

    /// Create or update an xinet proxy
    pub fn xinet_set(&self, config: XinetConfig) -> Result<()> {
        self.send_recv(|reply| RpcCmd::XinetSet {
            config: Box::new(config),
            reply,
        })
    }

    /// Delete an xinet proxy
    pub fn xinet_delete(&self, name: &str) -> Result<()> {
        self.send_recv(|reply| RpcCmd::XinetDelete {
            name: name.to_string(),
            reply,
        })
    }

    /// List all xinet proxy names
    pub fn xinet_list(&self) -> Result<Vec<String>> {
        self.send_recv(|reply| RpcCmd::XinetList { reply })
    }

    /// Get xinet proxy status (simplified)
    pub fn xinet_status(&self, name: &str) -> Result<XinetStatus> {
        self.send_recv(|reply| RpcCmd::XinetStatus {
            name: name.to_string(),
            reply,
        })
    }

    /// Get status of all xinet proxies
    pub fn xinet_status_all(&self) -> Result<Vec<XinetStatusFull>> {
        self.send_recv(|reply| RpcCmd::XinetStatusAll { reply })
    }
}