torc 0.23.0

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
//! Configuration loader with layered configuration support
//!
//! Loads configuration from multiple sources with the following priority:
//! 1. Built-in defaults (lowest)
//! 2. System config (`/etc/torc/config.toml`)
//! 3. User config (`~/.config/torc/config.toml`)
//! 4. Project-local config (`./torc.toml`)
//! 5. Environment variables (`TORC_*`)
//! 6. CLI arguments (highest, handled externally)

use config::{Config, ConfigError, Environment, File, FileFormat};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

use super::{ClientConfig, DashConfig, ServerConfig};

/// Complete Torc configuration containing all component settings
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct TorcConfig {
    /// Client (CLI) configuration
    pub client: ClientConfig,

    /// Server configuration
    pub server: ServerConfig,

    /// Dashboard configuration
    pub dash: DashConfig,
}

/// Configuration file paths and their sources
#[derive(Debug, Clone)]
pub struct ConfigPaths {
    /// System-wide config path
    pub system: PathBuf,

    /// User config path
    pub user: Option<PathBuf>,

    /// Project-local config path
    pub local: PathBuf,
}

impl Default for ConfigPaths {
    fn default() -> Self {
        Self::new()
    }
}

impl ConfigPaths {
    /// Create new config paths with platform-appropriate defaults
    pub fn new() -> Self {
        let user = dirs::config_dir().map(|p| p.join("torc").join("config.toml"));

        Self {
            system: PathBuf::from("/etc/torc/config.toml"),
            user,
            local: PathBuf::from("torc.toml"),
        }
    }

    /// Get all paths that exist
    pub fn existing_paths(&self) -> Vec<&PathBuf> {
        let mut paths = Vec::new();
        if self.system.exists() {
            paths.push(&self.system);
        }
        if let Some(user) = &self.user
            && user.exists()
        {
            paths.push(user);
        }
        if self.local.exists() {
            paths.push(&self.local);
        }
        paths
    }

    /// Get the user config directory (creates parent dirs if needed)
    pub fn user_config_dir(&self) -> Option<PathBuf> {
        self.user
            .as_ref()
            .and_then(|p| p.parent().map(|p| p.to_path_buf()))
    }
}

impl TorcConfig {
    /// Load configuration from all sources
    ///
    /// Sources are loaded in this order (later sources override earlier):
    /// 1. Built-in defaults
    /// 2. System config (`/etc/torc/config.toml`)
    /// 3. User config (`~/.config/torc/config.toml`)
    /// 4. Project-local config (`./torc.toml`)
    /// 5. Environment variables (`TORC_*`)
    pub fn load() -> Result<Self, ConfigError> {
        let paths = ConfigPaths::new();
        Self::load_with_paths(&paths)
    }

    /// Load configuration with custom paths
    pub fn load_with_paths(paths: &ConfigPaths) -> Result<Self, ConfigError> {
        let mut builder = Config::builder();

        // 1. System config (optional)
        if paths.system.exists() {
            builder = builder.add_source(
                File::from(paths.system.clone())
                    .format(FileFormat::Toml)
                    .required(false),
            );
        }

        // 2. User config (optional)
        if let Some(user_path) = &paths.user
            && user_path.exists()
        {
            builder = builder.add_source(
                File::from(user_path.clone())
                    .format(FileFormat::Toml)
                    .required(false),
            );
        }

        // 3. Project-local config (optional)
        if paths.local.exists() {
            builder = builder.add_source(
                File::from(paths.local.clone())
                    .format(FileFormat::Toml)
                    .required(false),
            );
        }

        // 4. Environment variables
        // Use double underscore for nesting to avoid conflicts with field names:
        //   TORC_CLIENT__API_URL -> client.api_url
        //   TORC_SERVER__PORT -> server.port
        //   TORC_DASH__HOST -> dash.host
        // Single underscore is preserved in field names.
        builder = builder.add_source(
            Environment::with_prefix("TORC")
                .prefix_separator("_")
                .separator("__") // Double underscore for nesting
                .try_parsing(true)
                .keep_prefix(false),
        );

        // Build and deserialize with defaults for missing fields
        let config = builder.build()?;
        config.try_deserialize().or_else(|_| Ok(Self::default()))
    }

    /// Load configuration from specific file paths
    pub fn load_from_files(paths: &[PathBuf]) -> Result<Self, ConfigError> {
        let mut builder = Config::builder();

        for path in paths {
            if path.exists() {
                builder = builder.add_source(
                    File::from(path.clone())
                        .format(FileFormat::Toml)
                        .required(false),
                );
            }
        }

        // Add environment variables
        builder = builder.add_source(
            Environment::with_prefix("TORC")
                .separator("_")
                .try_parsing(true),
        );

        let config = builder.build()?;
        config.try_deserialize().or_else(|_| Ok(Self::default()))
    }

    /// Generate a default configuration file content
    pub fn generate_default_config() -> String {
        r#"# Torc Configuration File
# Place in ~/.config/torc/config.toml (user) or /etc/torc/config.toml (system)
# Or ./torc.toml for project-specific settings

[client]
# URL of the torc-server API
api_url = "http://localhost:8080/torc-service/v1"

# Output format: "table" or "json"
format = "table"

# Log level: error, warn, info, debug, trace
log_level = "info"

[client.run]
# Job completion poll interval in seconds
poll_interval = 5.0

# Output directory for job logs and artifacts
output_dir = "torc_output"

# Maximum number of parallel jobs (optional, uses resource-based if not set)
# max_parallel_jobs = 4

# Resource limits for local execution (optional)
# num_cpus = 8
# memory_gb = 32.0
# num_gpus = 1

[client.tls]
# Path to a PEM-encoded CA certificate to trust
# ca_cert = "/path/to/ca.pem"

# Skip certificate verification (for testing only)
insecure = false

[client.slurm]
# Poll interval in seconds for Slurm job runners
poll_interval = 30

# Keep submission scripts after job submission (useful for debugging)
keep_submission_scripts = false

[client.hpc]
# Default account to use for HPC jobs (applies to all profiles)
# default_account = "my_project"

# Override settings for built-in profiles
# [client.hpc.profile_overrides.kestrel]
# default_account = "my_kestrel_account"

# Define custom HPC profiles
# [[client.hpc.custom_profiles]]
# name = "my_cluster"
# display_name = "My Custom Cluster"
# description = "Our department's HPC cluster"
# detect_env_var = "MY_CLUSTER=prod"
# default_account = "dept_account"
# charge_factor_cpu = 1.0
# charge_factor_gpu = 10.0
#
# [[client.hpc.custom_profiles.my_cluster.partitions]]
# name = "compute"
# cpus_per_node = 64
# memory_mb = 256000
# max_walltime_secs = 172800  # 2 days

[server]
# Hostname/IP to bind to
url = "localhost"

# Port to listen on
port = 8080

# Number of worker threads
threads = 1

# Use HTTPS
https = false

# Path to SQLite database (optional, uses DATABASE_URL env var if not set)
# database = "/path/to/torc.db"

# Path to htpasswd file for authentication (optional)
# auth_file = "/path/to/htpasswd"

# Require authentication for all requests
require_auth = false

# Interval for background job completion processing (seconds)
completion_check_interval_secs = 30.0

# Log level: error, warn, info, debug, trace
log_level = "info"

[server.logging]
# Directory for log files (enables file logging)
# log_dir = "/var/log/torc"

# Use JSON format for logs
json_logs = false

# Admin users (can create and manage access groups)
# These users are automatically added to the system "admin" group on startup
# admin_users = ["alice", "bob"]

[dash]
# Host to bind to
host = "127.0.0.1"

# Port to listen on
port = 8090

# URL of the torc-server API
api_url = "http://localhost:8080/torc-service/v1"

# Path to torc CLI binary
torc_bin = "torc"

# Path to torc-server binary
torc_server_bin = "torc-server"

# Run in standalone mode (auto-start torc-server)
standalone = false

# Server port for standalone mode (0 = auto-detect)
server_port = 0

# Job completion check interval for standalone mode (seconds)
completion_check_interval_secs = 5
"#
        .to_string()
    }

    /// Validate the configuration
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        // Validate client config
        if !["table", "json"].contains(&self.client.format.as_str()) {
            errors.push(format!(
                "client.format must be 'table' or 'json', got '{}'",
                self.client.format
            ));
        }

        if self.client.run.poll_interval <= 0.0 {
            errors.push("client.run.poll_interval must be positive".to_string());
        }

        // Validate server config
        if self.server.port == 0 {
            errors.push("server.port cannot be 0".to_string());
        }

        if self.server.threads == 0 {
            errors.push("server.threads must be at least 1".to_string());
        }

        if self.server.completion_check_interval_secs <= 0.0 {
            errors.push("server.completion_check_interval_secs must be positive".to_string());
        }

        // Validate dash config
        if self.dash.port == 0 {
            errors.push("dash.port cannot be 0".to_string());
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Get the configuration paths
    pub fn paths() -> ConfigPaths {
        ConfigPaths::new()
    }

    /// Convert to TOML string
    pub fn to_toml(&self) -> Result<String, ::toml::ser::Error> {
        ::toml::to_string_pretty(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let config = TorcConfig::default();
        assert_eq!(
            config.client.api_url,
            "http://localhost:8080/torc-service/v1"
        );
        assert_eq!(config.server.port, 8080);
        assert_eq!(config.dash.port, 8090);
    }

    #[test]
    fn test_config_paths() {
        let paths = ConfigPaths::new();
        assert_eq!(paths.system, PathBuf::from("/etc/torc/config.toml"));
        assert!(paths.user.is_some());
        assert_eq!(paths.local, PathBuf::from("torc.toml"));
    }

    #[test]
    fn test_validate_valid_config() {
        let config = TorcConfig::default();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_validate_invalid_format() {
        let mut config = TorcConfig::default();
        config.client.format = "invalid".to_string();
        let result = config.validate();
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(errors.iter().any(|e| e.contains("format")));
    }

    #[test]
    fn test_generate_default_config() {
        let config = TorcConfig::generate_default_config();
        assert!(config.contains("[client]"));
        assert!(config.contains("[server]"));
        assert!(config.contains("[dash]"));
        assert!(config.contains("api_url"));
    }
}