nika 0.20.0

Semantic YAML workflow engine for AI tasks - DAG execution, MCP integration, multi-provider LLM support
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
//! Jobs Daemon configuration types.
//!
//! This module defines the canonical types for job configuration.
//! All other modules MUST align with these types.

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::time::Duration;

use super::error::JobsError;

/// Root configuration for the Jobs Daemon.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JobsConfig {
    /// Whether the daemon is enabled.
    #[serde(default = "default_enabled")]
    pub enabled: bool,

    /// Path to the PID file for daemon lifecycle.
    #[serde(default = "default_pid_file")]
    pub pid_file: PathBuf,

    /// Path to the SQLite state database.
    #[serde(default = "default_state_db")]
    pub state_db: PathBuf,

    /// Directory for job execution logs.
    #[serde(default = "default_log_dir")]
    pub log_dir: PathBuf,

    /// Port for metrics/health endpoint.
    #[serde(default = "default_metrics_port")]
    pub metrics_port: u16,

    /// Maximum concurrent job executions.
    #[serde(default = "default_max_concurrent")]
    pub max_concurrent_jobs: usize,

    /// Default timeout for job executions (seconds).
    #[serde(default = "default_timeout_secs")]
    pub default_timeout_secs: u64,

    /// Webhook server configuration.
    #[serde(default)]
    pub webhook: WebhookConfig,

    /// Notification channel configuration.
    #[serde(default)]
    pub notify: NotifyConfig,

    /// Job definitions.
    #[serde(default)]
    pub definitions: Vec<JobDefinition>,
}

impl Default for JobsConfig {
    fn default() -> Self {
        Self {
            enabled: default_enabled(),
            pid_file: default_pid_file(),
            state_db: default_state_db(),
            log_dir: default_log_dir(),
            metrics_port: default_metrics_port(),
            max_concurrent_jobs: default_max_concurrent(),
            default_timeout_secs: default_timeout_secs(),
            webhook: WebhookConfig::default(),
            notify: NotifyConfig::default(),
            definitions: Vec::new(),
        }
    }
}

impl JobsConfig {
    /// Load configuration from a TOML file.
    ///
    /// # Arguments
    /// * `path` - Path to the TOML configuration file
    ///
    /// # Returns
    /// * `Ok(JobsConfig)` - Parsed configuration
    /// * `Err(JobsError)` - If file not found or parse error
    pub fn from_file(path: &Path) -> Result<Self, JobsError> {
        if !path.exists() {
            return Err(JobsError::ConfigNotFound {
                path: path.to_path_buf(),
            });
        }

        let content = std::fs::read_to_string(path).map_err(|e| JobsError::IoError {
            reason: format!("Failed to read config file: {}", e),
        })?;

        toml::from_str(&content).map_err(|e| JobsError::ConfigParseError {
            reason: format!("Failed to parse TOML: {}", e),
        })
    }
}

fn default_enabled() -> bool {
    true
}

fn default_pid_file() -> PathBuf {
    PathBuf::from(".nika/jobs/daemon.pid")
}

fn default_state_db() -> PathBuf {
    PathBuf::from(".nika/jobs/state.db")
}

fn default_log_dir() -> PathBuf {
    PathBuf::from(".nika/jobs/logs")
}

fn default_metrics_port() -> u16 {
    9090
}

fn default_max_concurrent() -> usize {
    10
}

fn default_timeout_secs() -> u64 {
    300 // 5 minutes
}

/// Webhook server configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct WebhookConfig {
    /// Enable webhook server.
    #[serde(default)]
    pub enabled: bool,

    /// Port for webhook server.
    #[serde(default = "default_webhook_port")]
    pub port: u16,

    /// Bind address.
    #[serde(default = "default_webhook_host")]
    pub host: String,

    /// Authentication token (optional).
    pub auth_token: Option<String>,
}

fn default_webhook_port() -> u16 {
    8080
}

fn default_webhook_host() -> String {
    "127.0.0.1".to_string()
}

/// Notification configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct NotifyConfig {
    /// Slack webhook URL.
    pub slack_webhook: Option<String>,

    /// Email configuration.
    pub email: Option<EmailConfig>,

    /// Notify on job failure.
    #[serde(default = "default_true")]
    pub on_failure: bool,

    /// Notify on job success.
    #[serde(default)]
    pub on_success: bool,
}

fn default_true() -> bool {
    true
}

/// Email notification configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmailConfig {
    /// SMTP server host.
    pub smtp_host: String,

    /// SMTP server port.
    #[serde(default = "default_smtp_port")]
    pub smtp_port: u16,

    /// SMTP username.
    pub username: Option<String>,

    /// SMTP password.
    pub password: Option<String>,

    /// From address.
    pub from: String,

    /// To addresses.
    pub to: Vec<String>,
}

fn default_smtp_port() -> u16 {
    587
}

/// A job definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JobDefinition {
    /// Unique job name.
    pub name: String,

    /// Path to the workflow file.
    pub workflow: PathBuf,

    /// Whether the job is enabled.
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Trigger configuration (determines when job runs).
    pub trigger: JobTrigger,

    /// Retry configuration.
    #[serde(default)]
    pub retry: RetryConfig,

    /// Timeout for this job (overrides default).
    #[serde(with = "humantime_serde", default = "default_job_timeout")]
    pub timeout: Duration,

    /// Environment variables for job execution.
    #[serde(default)]
    pub env: std::collections::HashMap<String, String>,

    /// Tags for filtering/grouping.
    #[serde(default)]
    pub tags: Vec<String>,
}

fn default_job_timeout() -> Duration {
    Duration::from_secs(300)
}

/// Job trigger types.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum JobTrigger {
    /// Cron-based scheduling.
    Cron(CronTriggerConfig),

    /// Webhook-triggered execution.
    Webhook(WebhookTriggerConfig),

    /// File system watch trigger.
    Watch(WatchTriggerConfig),

    /// Fixed interval trigger.
    Interval(IntervalTriggerConfig),
}

/// Cron trigger configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CronTriggerConfig {
    /// Cron expression (e.g., "0 0 * * *" for daily at midnight).
    pub expression: String,

    /// Timezone for cron evaluation (default: UTC).
    #[serde(default = "default_timezone")]
    pub timezone: String,
}

fn default_timezone() -> String {
    "UTC".to_string()
}

/// Webhook trigger configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookTriggerConfig {
    /// Endpoint path (e.g., "/jobs/my-job/trigger").
    pub path: String,

    /// HTTP method (default: POST).
    #[serde(default = "default_http_method")]
    pub method: String,

    /// Required secret in Authorization header.
    pub secret: Option<String>,
}

fn default_http_method() -> String {
    "POST".to_string()
}

/// File watch trigger configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WatchTriggerConfig {
    /// Paths to watch (supports globs).
    pub paths: Vec<String>,

    /// Debounce duration to prevent rapid re-triggers.
    #[serde(with = "humantime_serde", default = "default_debounce")]
    pub debounce: Duration,

    /// Watch for specific events.
    #[serde(default = "default_watch_events")]
    pub events: Vec<WatchEvent>,
}

fn default_debounce() -> Duration {
    Duration::from_secs(5)
}

fn default_watch_events() -> Vec<WatchEvent> {
    vec![WatchEvent::Create, WatchEvent::Modify]
}

/// File watch events.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WatchEvent {
    Create,
    Modify,
    Delete,
    Rename,
}

/// Interval trigger configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IntervalTriggerConfig {
    /// Interval duration between executions.
    #[serde(with = "humantime_serde")]
    pub every: Duration,

    /// Delay before first execution.
    #[serde(with = "humantime_serde", default)]
    pub initial_delay: Duration,
}

/// Retry configuration for failed jobs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetryConfig {
    /// Maximum retry attempts.
    #[serde(default = "default_max_attempts")]
    pub max_attempts: u32,

    /// Backoff strategy.
    #[serde(default)]
    pub backoff: BackoffStrategy,

    /// Initial delay before first retry.
    #[serde(with = "humantime_serde", default = "default_initial_delay")]
    pub initial_delay: Duration,

    /// Maximum delay between retries.
    #[serde(with = "humantime_serde", default = "default_max_delay")]
    pub max_delay: Duration,

    /// Add jitter to retry delays.
    #[serde(default = "default_true")]
    pub jitter: bool,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_attempts: default_max_attempts(),
            backoff: BackoffStrategy::default(),
            initial_delay: default_initial_delay(),
            max_delay: default_max_delay(),
            jitter: true,
        }
    }
}

fn default_max_attempts() -> u32 {
    3
}

fn default_initial_delay() -> Duration {
    Duration::from_secs(1)
}

fn default_max_delay() -> Duration {
    Duration::from_secs(60)
}

/// Backoff strategy for retries.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BackoffStrategy {
    /// Constant delay between retries.
    Constant,

    /// Linear increase (delay * attempt).
    Linear,

    /// Exponential increase (delay * 2^attempt).
    #[default]
    Exponential,
}

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

    #[test]
    fn test_default_config() {
        let config = JobsConfig::default();
        assert!(config.enabled);
        assert_eq!(config.max_concurrent_jobs, 10);
        assert_eq!(config.metrics_port, 9090);
    }

    #[test]
    fn test_cron_trigger_serde() {
        let trigger = JobTrigger::Cron(CronTriggerConfig {
            expression: "0 0 * * *".to_string(),
            timezone: "UTC".to_string(),
        });

        let json = serde_json::to_string(&trigger).unwrap();
        assert!(json.contains("cron"));
        assert!(json.contains("0 0 * * *"));
    }

    #[test]
    fn test_interval_trigger_serde() {
        let trigger = JobTrigger::Interval(IntervalTriggerConfig {
            every: Duration::from_secs(3600),
            initial_delay: Duration::from_secs(0),
        });

        let json = serde_json::to_string(&trigger).unwrap();
        assert!(json.contains("interval"));
    }

    #[test]
    fn test_retry_config_default() {
        let retry = RetryConfig::default();
        assert_eq!(retry.max_attempts, 3);
        assert_eq!(retry.backoff, BackoffStrategy::Exponential);
        assert!(retry.jitter);
    }

    #[test]
    fn test_job_definition() {
        let job = JobDefinition {
            name: "test-job".to_string(),
            workflow: PathBuf::from("workflow.nika.yaml"),
            enabled: true,
            trigger: JobTrigger::Interval(IntervalTriggerConfig {
                every: Duration::from_secs(60),
                initial_delay: Duration::from_secs(0),
            }),
            retry: RetryConfig::default(),
            timeout: Duration::from_secs(120),
            env: std::collections::HashMap::new(),
            tags: vec!["test".to_string()],
        };

        assert_eq!(job.name, "test-job");
        assert!(job.enabled);
    }
}