zinit 0.3.7

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
//! Response data structures for zinit RPC methods.

use serde::{Deserialize, Serialize};

use super::state::ServiceState;

/// Simple state enum for API responses.
/// Serializes as lowercase string matching the state name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum State {
    Inactive,
    Blocked,
    Starting,
    Running,
    Stopping,
    Exited,
    Failed,
}

impl State {
    /// Check if this state represents a running process
    pub fn is_running(&self) -> bool {
        matches!(self, State::Running)
    }

    /// Check if this state has an active process
    pub fn is_active(&self) -> bool {
        matches!(self, State::Starting | State::Running | State::Stopping)
    }
}

impl std::fmt::Display for State {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            State::Inactive => write!(f, "inactive"),
            State::Blocked => write!(f, "blocked"),
            State::Starting => write!(f, "starting"),
            State::Running => write!(f, "running"),
            State::Stopping => write!(f, "stopping"),
            State::Exited => write!(f, "exited"),
            State::Failed => write!(f, "failed"),
        }
    }
}

impl From<&ServiceState> for State {
    fn from(state: &ServiceState) -> Self {
        match state {
            ServiceState::Inactive => State::Inactive,
            ServiceState::Blocked { .. } => State::Blocked,
            ServiceState::Starting { .. } => State::Starting,
            ServiceState::Running { .. } => State::Running,
            ServiceState::Stopping { .. } => State::Stopping,
            ServiceState::Exited { .. } => State::Exited,
            ServiceState::Failed { .. } => State::Failed,
        }
    }
}

/// Service status returned by service.status.
/// Simplified to match OpenRPC spec.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServiceStatus {
    pub name: String,
    /// State as enum (serializes as lowercase string)
    pub state: State,
    /// Process ID (0 if not running)
    #[serde(default)]
    pub pid: u32,
    /// Last exit code (if exited or failed)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,
    /// Error message (if failed)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

impl ServiceStatus {
    /// Create from ServiceState
    pub fn from_state(name: String, state: &ServiceState) -> Self {
        let (state_enum, pid, exit_code, error) = match state {
            ServiceState::Inactive => (State::Inactive, 0, None, None),
            ServiceState::Blocked { waiting_on } => {
                let err = if waiting_on.is_empty() {
                    None
                } else {
                    Some(format!("waiting on: {}", waiting_on.join(", ")))
                };
                (State::Blocked, 0, None, err)
            }
            ServiceState::Starting { pid } => (State::Starting, *pid, None, None),
            ServiceState::Running { pid } => (State::Running, *pid, None, None),
            ServiceState::Stopping { pid } => (State::Stopping, *pid, None, None),
            ServiceState::Exited { exit_code: code } => (State::Exited, 0, *code, None),
            ServiceState::Failed { reason } => {
                let (code, err) = match reason {
                    super::state::FailureReason::ExitCode { code } => (Some(*code), None),
                    super::state::FailureReason::Signal { signal } => {
                        (None, Some(format!("killed by signal {}", signal)))
                    }
                    super::state::FailureReason::StartTimeout => {
                        (None, Some("start timeout".to_string()))
                    }
                    super::state::FailureReason::StopTimeout => {
                        (None, Some("stop timeout".to_string()))
                    }
                    super::state::FailureReason::HealthCheckFailed { attempts } => (
                        None,
                        Some(format!("health check failed after {} attempts", attempts)),
                    ),
                    super::state::FailureReason::DependencyFailed { service } => {
                        (None, Some(format!("dependency '{}' failed", service)))
                    }
                    super::state::FailureReason::SpawnError { message } => {
                        (None, Some(format!("spawn error: {}", message)))
                    }
                    super::state::FailureReason::MissingDependency { dependency } => {
                        (None, Some(format!("missing dependency '{}'", dependency)))
                    }
                };
                (State::Failed, 0, code, err)
            }
        };
        Self {
            name,
            state: state_enum,
            pid,
            exit_code,
            error,
        }
    }
}

/// Service resource usage statistics.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServiceStats {
    pub pid: u32,
    pub memory_bytes: u64,
    pub cpu_percent: f32,
}

/// Xinet proxy status.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct XinetStatus {
    pub name: String,
    pub running: bool,
    pub connections: u32,
}

/// Response for system ping.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PingResponse {
    pub version: String,
}

/// Simple success response.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OkResponse {
    pub ok: bool,
}

impl Default for OkResponse {
    fn default() -> Self {
        Self { ok: true }
    }
}

/// Result of service.create operation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CreateResult {
    pub name: String,
}

// ============================================================================
// Legacy types kept for backward compatibility during transition
// These will be removed in a future version
// ============================================================================

/// Basic service information returned by list (legacy).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServiceInfo {
    pub name: String,
    pub state: ServiceState,
    pub is_target: bool,
}

/// Information about a single dependency (legacy).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DependencyInfo {
    pub name: String,
    pub dep_type: DepType,
    pub state: ServiceState,
    pub satisfied: bool,
}

/// Detailed service status with dependencies (legacy).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LegacyServiceStatus {
    pub name: String,
    pub state: ServiceState,
    pub is_target: bool,
    pub dependencies: Vec<DependencyInfo>,
    pub uptime_secs: Option<u64>,
}

/// Type of dependency relationship.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DepType {
    After,
    Requires,
    Wants,
    Conflicts,
}

impl std::fmt::Display for DepType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DepType::After => write!(f, "after"),
            DepType::Requires => write!(f, "requires"),
            DepType::Wants => write!(f, "wants"),
            DepType::Conflicts => write!(f, "conflicts"),
        }
    }
}

/// A single log line from a service (legacy - now returns strings).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LogLine {
    pub timestamp_ms: u64,
    pub service: String,
    pub stream: LogStream,
    pub content: String,
}

impl LogLine {
    /// Format as simple string for new API
    pub fn to_string_format(&self) -> String {
        format!("{} [{}] {}", self.timestamp_ms, self.stream, self.content)
    }
}

/// Log stream type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LogStream {
    Stdout,
    Stderr,
    Syslog,
}

impl std::fmt::Display for LogStream {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LogStream::Stdout => write!(f, "stdout"),
            LogStream::Stderr => write!(f, "stderr"),
            LogStream::Syslog => write!(f, "syslog"),
        }
    }
}

/// Response explaining why a service is blocked (legacy).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WhyBlocked {
    pub name: String,
    pub blocked: bool,
    pub waiting_on: Vec<String>,
    pub conflicts_with: Vec<String>,
    pub ascii: String,
}

/// Response for dependency tree (legacy).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TreeResponse {
    pub ascii: String,
}

/// Response for reload operation (legacy).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ReloadResult {
    pub added: Vec<String>,
    pub removed: Vec<String>,
    pub changed: Vec<String>,
    #[serde(default)]
    pub config_errors: Vec<(String, String)>,
}

impl ReloadResult {
    pub fn has_changes(&self) -> bool {
        !self.added.is_empty() || !self.removed.is_empty() || !self.changed.is_empty()
    }

    pub fn total_changes(&self) -> usize {
        self.added.len() + self.removed.len() + self.changed.len()
    }

    pub fn has_config_errors(&self) -> bool {
        !self.config_errors.is_empty()
    }
}

/// Response for bulk operations (legacy).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BulkStartResult {
    pub started: Vec<String>,
    pub count: usize,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BulkStopResult {
    pub stopped: Vec<String>,
    pub count: usize,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BulkDeleteResult {
    pub deleted: Vec<String>,
    pub count: usize,
}

/// Response for add-service operation (legacy).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AddServiceResult {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(default)]
    pub warnings: Vec<String>,
}

/// Parameters for add-service RPC call (legacy).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddServiceParams {
    pub config: super::config::ServiceConfig,
    #[serde(default)]
    pub persist: bool,
}

/// Response for system.prepare_restart operation (legacy).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrepareRestartResult {
    pub state_path: String,
    pub ready: bool,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sdk::state::FailureReason;

    #[test]
    fn test_service_status_from_state() {
        // Running state
        let status =
            ServiceStatus::from_state("test".to_string(), &ServiceState::Running { pid: 123 });
        assert_eq!(status.state, State::Running);
        assert_eq!(status.pid, 123);
        assert!(status.exit_code.is_none());
        assert!(status.error.is_none());

        // Failed state
        let status = ServiceStatus::from_state(
            "test".to_string(),
            &ServiceState::Failed {
                reason: FailureReason::ExitCode { code: 1 },
            },
        );
        assert_eq!(status.state, State::Failed);
        assert_eq!(status.exit_code, Some(1));

        // Blocked state
        let status = ServiceStatus::from_state(
            "test".to_string(),
            &ServiceState::Blocked {
                waiting_on: vec!["dep1".to_string(), "dep2".to_string()],
            },
        );
        assert_eq!(status.state, State::Blocked);
        assert!(status.error.as_ref().unwrap().contains("dep1"));
    }

    #[test]
    fn test_ok_response() {
        let resp = OkResponse::default();
        assert!(resp.ok);
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains("\"ok\":true"));
    }

    #[test]
    fn test_service_stats() {
        let stats = ServiceStats {
            pid: 123,
            memory_bytes: 1024 * 1024,
            cpu_percent: 5.5,
        };
        let json = serde_json::to_string(&stats).unwrap();
        assert!(json.contains("\"pid\":123"));
        assert!(json.contains("\"memory_bytes\":1048576"));
    }

    #[test]
    fn test_xinet_status() {
        let status = XinetStatus {
            name: "proxy1".to_string(),
            running: true,
            connections: 5,
        };
        let json = serde_json::to_string(&status).unwrap();
        assert!(json.contains("\"running\":true"));
        assert!(json.contains("\"connections\":5"));
    }

    #[test]
    fn test_log_line_to_string() {
        let line = LogLine {
            timestamp_ms: 1234567890,
            service: "test".to_string(),
            stream: LogStream::Stdout,
            content: "Hello".to_string(),
        };
        let s = line.to_string_format();
        assert!(s.contains("1234567890"));
        assert!(s.contains("stdout"));
        assert!(s.contains("Hello"));
    }
}