torc 0.20.7

Workflow management system
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
//! Service management for torc-server
//!
//! This module provides cross-platform service installation and management
//! using systemd (Linux), launchd (macOS), or Windows Service.

use anyhow::{Context, Result};
use service_manager::*;
use std::env;
use std::ffi::OsString;
use std::path::PathBuf;

const SERVICE_NAME: &str = "torc-server";

/// Service management commands
#[derive(Debug, Clone)]
pub enum ServiceCommand {
    Install,
    Uninstall,
    Start,
    Stop,
    Status,
}

/// Configuration for service installation
#[derive(Debug, Clone)]
pub struct ServiceConfig {
    pub log_dir: Option<PathBuf>,
    pub database: Option<String>,
    pub host: String,
    pub port: u16,
    pub threads: u32,
    pub auth_file: Option<String>,
    pub require_auth: bool,
    pub credential_cache_ttl_secs: u64,
    pub enforce_access_control: bool,
    pub log_level: String,
    pub json_logs: bool,
    pub https: bool,
    pub tls_cert: Option<String>,
    pub tls_key: Option<String>,
    pub admin_users: Vec<String>,
    pub completion_check_interval_secs: Option<f64>,
}

impl ServiceConfig {
    /// Default completion check interval for services (5 seconds)
    pub const DEFAULT_SERVICE_INTERVAL_SECS: f64 = 5.0;

    /// Default credential cache TTL in seconds (must match clap default in ServerConfig)
    pub const DEFAULT_CREDENTIAL_CACHE_TTL_SECS: u64 = 60;

    /// Create default configuration for system-level service
    /// Uses a shorter completion check interval (5s) since local services
    /// typically run jobs on the same machine and benefit from faster feedback.
    fn default_system() -> Self {
        Self {
            log_dir: Some(PathBuf::from("/var/log/torc")),
            database: Some("/var/lib/torc/torc.db".to_string()),
            host: "0.0.0.0".to_string(),
            port: 8080,
            threads: 4,
            auth_file: None,
            require_auth: false,
            credential_cache_ttl_secs: Self::DEFAULT_CREDENTIAL_CACHE_TTL_SECS,
            enforce_access_control: false,
            log_level: "info".to_string(),
            json_logs: false,
            https: false,
            tls_cert: None,
            tls_key: None,
            admin_users: Vec::new(),
            completion_check_interval_secs: None, // Will use DEFAULT_SERVICE_INTERVAL_SECS
        }
    }

    /// Create default configuration for user-level service
    /// Uses a shorter completion check interval (5s) since local services
    /// typically run jobs on the same machine and benefit from faster feedback.
    fn default_user() -> Self {
        // Get user's home directory
        let home = env::var("HOME").unwrap_or_else(|_| ".".to_string());

        Self {
            log_dir: Some(PathBuf::from(format!("{}/.torc/logs", home))),
            database: Some(format!("{}/.torc/torc.db", home)),
            host: "0.0.0.0".to_string(),
            port: 8080,
            threads: 4,
            auth_file: None,
            require_auth: false,
            credential_cache_ttl_secs: Self::DEFAULT_CREDENTIAL_CACHE_TTL_SECS,
            enforce_access_control: false,
            log_level: "info".to_string(),
            json_logs: false,
            https: false,
            tls_cert: None,
            tls_key: None,
            admin_users: Vec::new(),
            completion_check_interval_secs: None, // Will use DEFAULT_SERVICE_INTERVAL_SECS
        }
    }

    /// Merge user-provided configuration with defaults
    /// User-provided values take precedence, but we fill in sensible defaults.
    /// Non-Option fields are compared against known clap defaults to determine
    /// if the user explicitly provided a value or if the clap default should be
    /// replaced with the service-appropriate default.
    fn merge_with_defaults(user_config: &ServiceConfig, user_level: bool) -> Self {
        let defaults = if user_level {
            Self::default_user()
        } else {
            Self::default_system()
        };

        Self {
            // Option fields: use user config if provided, otherwise use service default
            log_dir: user_config.log_dir.clone().or(defaults.log_dir),
            database: user_config.database.clone().or(defaults.database),
            auth_file: user_config.auth_file.clone().or(defaults.auth_file),
            tls_cert: user_config.tls_cert.clone().or(defaults.tls_cert),
            tls_key: user_config.tls_key.clone().or(defaults.tls_key),
            completion_check_interval_secs: user_config.completion_check_interval_secs,
            // Non-Option fields: fall back to service defaults when clap defaults are detected
            host: if user_config.host != "0.0.0.0" {
                user_config.host.clone()
            } else {
                defaults.host
            },
            port: if user_config.port != 8080 {
                user_config.port
            } else {
                defaults.port
            },
            threads: if user_config.threads != 1 {
                user_config.threads
            } else {
                defaults.threads
            },
            log_level: if user_config.log_level != "info" {
                user_config.log_level.clone()
            } else {
                defaults.log_level
            },
            credential_cache_ttl_secs: if user_config.credential_cache_ttl_secs
                != ServiceConfig::DEFAULT_CREDENTIAL_CACHE_TTL_SECS
            {
                user_config.credential_cache_ttl_secs
            } else {
                defaults.credential_cache_ttl_secs
            },
            // Boolean fields: true if either user or defaults enable it
            require_auth: user_config.require_auth || defaults.require_auth,
            enforce_access_control: user_config.enforce_access_control
                || defaults.enforce_access_control,
            json_logs: user_config.json_logs || defaults.json_logs,
            https: user_config.https || defaults.https,
            // Vec fields: use user config if non-empty
            admin_users: if user_config.admin_users.is_empty() {
                defaults.admin_users
            } else {
                user_config.admin_users.clone()
            },
        }
    }
}

impl Default for ServiceConfig {
    fn default() -> Self {
        Self::default_system()
    }
}

/// Get the service manager for the current platform
fn get_service_manager(user_level: bool) -> Result<Box<dyn ServiceManager>> {
    let level = if user_level {
        ServiceLevel::User
    } else {
        ServiceLevel::System
    };

    let mut manager = <dyn ServiceManager>::native()
        .context("Failed to detect native service manager for this platform")?;

    manager
        .set_level(level)
        .context("Failed to set service level")?;

    Ok(manager)
}

/// Build service label
fn service_label() -> ServiceLabel {
    ServiceLabel {
        qualifier: Some("com.github".to_string()),
        organization: Some("torc".to_string()),
        application: SERVICE_NAME.to_string(),
    }
}

/// Install the service with the given configuration
pub fn install_service(config: &ServiceConfig, user_level: bool) -> Result<()> {
    // Validate HTTPS configuration upfront to avoid installing a service that fails to start
    if config.https {
        if config.tls_cert.is_none() {
            anyhow::bail!("--https requires --tls-cert to be specified");
        }
        if config.tls_key.is_none() {
            anyhow::bail!("--https requires --tls-key to be specified");
        }
    }

    let manager = get_service_manager(user_level)?;

    // Get the path to the current executable
    let exe_path = env::current_exe().context("Failed to get current executable path")?;

    // Build command-line arguments for the service
    // Start with "run" subcommand since config options are now scoped to it
    let mut args: Vec<OsString> = vec!["run".into()];

    if let Some(ref log_dir) = config.log_dir {
        args.push("--log-dir".into());
        args.push(log_dir.as_os_str().to_owned());
    }

    if let Some(ref database) = config.database {
        args.push("--database".into());
        args.push(database.into());
    }

    args.push("--host".into());
    args.push(config.host.clone().into());

    args.push("--port".into());
    args.push(config.port.to_string().into());

    args.push("--threads".into());
    args.push(config.threads.to_string().into());

    args.push("--log-level".into());
    args.push(config.log_level.clone().into());

    if config.json_logs {
        args.push("--json-logs".into());
    }

    if let Some(ref auth_file) = config.auth_file {
        args.push("--auth-file".into());
        args.push(auth_file.into());
    }

    if config.require_auth {
        args.push("--require-auth".into());
    }

    if config.credential_cache_ttl_secs != ServiceConfig::DEFAULT_CREDENTIAL_CACHE_TTL_SECS {
        args.push("--credential-cache-ttl-secs".into());
        args.push(config.credential_cache_ttl_secs.to_string().into());
    }

    if config.enforce_access_control {
        args.push("--enforce-access-control".into());
    }

    if config.https {
        args.push("--https".into());
    }

    if let Some(ref tls_cert) = config.tls_cert {
        args.push("--tls-cert".into());
        args.push(tls_cert.into());
    }

    if let Some(ref tls_key) = config.tls_key {
        args.push("--tls-key".into());
        args.push(tls_key.into());
    }

    for admin_user in &config.admin_users {
        args.push("--admin-user".into());
        args.push(admin_user.into());
    }

    let interval = config
        .completion_check_interval_secs
        .unwrap_or(ServiceConfig::DEFAULT_SERVICE_INTERVAL_SECS);
    args.push("--completion-check-interval-secs".into());
    args.push(interval.to_string().into());

    // Create service install context
    let install_ctx = ServiceInstallCtx {
        label: service_label(),
        program: exe_path,
        args,
        contents: None, // Optional for systemd unit file overrides
        username: None, // Run as current user by default
        working_directory: None,
        environment: None,
        autostart: true, // Start automatically on boot
    };

    // Install the service
    manager
        .install(install_ctx)
        .context("Failed to install service")?;

    let service_type = if user_level { "user" } else { "system" };
    println!(
        "✓ Service '{}' installed successfully as {} service",
        SERVICE_NAME, service_type
    );
    println!();
    println!("Configuration:");
    if let Some(ref log_dir) = config.log_dir {
        println!("  Log directory: {}", log_dir.display());
    }
    if let Some(ref database) = config.database {
        println!("  Database: {}", database);
    }
    println!("  Listen address: {}:{}", config.host, config.port);
    println!("  HTTPS: {}", config.https);
    println!("  Worker threads: {}", config.threads);
    println!("  Log level: {}", config.log_level);
    println!("  Require auth: {}", config.require_auth);
    println!(
        "  Enforce access control: {}",
        config.enforce_access_control
    );
    if !config.admin_users.is_empty() {
        println!("  Admin users: {}", config.admin_users.join(", "));
    }
    println!();
    println!("To start the service, run:");
    if user_level {
        println!("  torc-server service start --user");
    } else {
        println!("  sudo torc-server service start");
    }

    Ok(())
}

/// Uninstall the service
pub fn uninstall_service(user_level: bool) -> Result<()> {
    let manager = get_service_manager(user_level)?;

    manager
        .uninstall(ServiceUninstallCtx {
            label: service_label(),
        })
        .context("Failed to uninstall service")?;

    let service_type = if user_level { "user" } else { "system" };
    println!(
        "✓ Service '{}' uninstalled successfully ({} service)",
        SERVICE_NAME, service_type
    );
    Ok(())
}

/// Start the service
pub fn start_service(user_level: bool) -> Result<()> {
    let manager = get_service_manager(user_level)?;
    let label = service_label();

    manager
        .start(ServiceStartCtx { label })
        .context("Failed to start service")?;

    let service_type = if user_level { "user" } else { "system" };
    println!(
        "✓ Service '{}' started successfully ({} service)",
        SERVICE_NAME, service_type
    );
    Ok(())
}

/// Stop the service
pub fn stop_service(user_level: bool) -> Result<()> {
    let manager = get_service_manager(user_level)?;
    let label = service_label();

    manager
        .stop(ServiceStopCtx { label })
        .context("Failed to stop service")?;

    let service_type = if user_level { "user" } else { "system" };
    println!(
        "✓ Service '{}' stopped successfully ({} service)",
        SERVICE_NAME, service_type
    );
    Ok(())
}

/// Check service status
pub fn service_status(user_level: bool) -> Result<()> {
    let service_type = if user_level { "user" } else { "system" };
    println!(
        "Service status check varies by platform ({} service):",
        service_type
    );
    println!();

    #[cfg(target_os = "linux")]
    {
        println!("On Linux (systemd):");
        if user_level {
            println!("  systemctl --user status com.github.torc.torc-server");
            println!();
            println!("Or check service logs:");
            println!("  journalctl --user -u com.github.torc.torc-server -f");
        } else {
            println!("  sudo systemctl status com.github.torc.torc-server");
            println!();
            println!("Or check service logs:");
            println!("  journalctl -u com.github.torc.torc-server -f");
        }
    }

    #[cfg(target_os = "macos")]
    {
        println!("On macOS (launchd):");
        if user_level {
            println!("  launchctl list | grep torc-server");
            println!();
            println!("Or check service logs:");
            println!("  tail -f ~/Library/Logs/torc-server.log");
        } else {
            println!("  sudo launchctl list | grep torc-server");
            println!();
            println!("Or check service logs:");
            println!("  tail -f /var/log/torc/torc-server.log");
        }
    }

    #[cfg(target_os = "windows")]
    {
        println!("On Windows:");
        println!("  sc query torc-server");
        println!();
        println!("Or use Services management console (services.msc)");
    }

    Ok(())
}

/// Execute a service command
pub fn execute_service_command(
    command: ServiceCommand,
    config: Option<&ServiceConfig>,
    user_level: bool,
) -> Result<()> {
    match command {
        ServiceCommand::Install => {
            // Merge user-provided config with appropriate defaults
            let merged_config = if let Some(user_config) = config {
                ServiceConfig::merge_with_defaults(user_config, user_level)
            } else if user_level {
                ServiceConfig::default_user()
            } else {
                ServiceConfig::default_system()
            };
            install_service(&merged_config, user_level)
        }
        ServiceCommand::Uninstall => uninstall_service(user_level),
        ServiceCommand::Start => start_service(user_level),
        ServiceCommand::Stop => stop_service(user_level),
        ServiceCommand::Status => service_status(user_level),
    }
}