devrig 0.30.1

Local development orchestrator
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
use anyhow::{Context, Result};
use notify_debouncer_mini::notify::RecursiveMode;
use notify_debouncer_mini::{new_debouncer, DebouncedEventKind};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use tracing::{debug, error, warn};

use crate::cluster::deploy;
use crate::config::model::{ClusterDeployConfig, ClusterImageConfig};
use crate::orchestrator::state::ClusterDeployState;

const IGNORED_DIRS: &[&str] = &[
    ".git",
    "target",
    "node_modules",
    ".devrig",
    ".claude",
    "__pycache__",
];

const IGNORED_EXTENSIONS: &[&str] = &["swp", "swo", "tmp", "pyc", "pyo"];

/// Start file watchers for all cluster deploys that have `watch = true`.
///
/// Each watcher monitors the deploy's context directory for file changes,
/// debounces rapid edits, and triggers a rebuild+redeploy cycle.
pub async fn start_watchers(
    deploys: &BTreeMap<String, ClusterDeployConfig>,
    registry_port: Option<u16>,
    kubeconfig_path: PathBuf,
    config_dir: PathBuf,
    cancel: CancellationToken,
    tracker: &TaskTracker,
) -> Result<()> {
    for (name, deploy_config) in deploys {
        if !deploy_config.watch {
            continue;
        }

        let name = name.clone();
        let deploy_config = deploy_config.clone();
        let kubeconfig_path = kubeconfig_path.clone();
        let config_dir = config_dir.clone();
        let cancel = cancel.clone();

        tracker.spawn(async move {
            if let Err(e) = watch_and_rebuild(
                name.clone(),
                deploy_config,
                registry_port,
                kubeconfig_path,
                config_dir,
                cancel,
            )
            .await
            {
                error!(deploy = %name, error = %e, "watcher failed");
            }
        });
    }

    Ok(())
}

/// Start file watchers for all cluster images that have `watch = true`.
///
/// Each watcher monitors the image's context directory for file changes,
/// debounces rapid edits, and triggers a rebuild+push cycle (no manifests).
pub async fn start_image_watchers(
    images: &BTreeMap<String, ClusterImageConfig>,
    registry_port: Option<u16>,
    config_dir: PathBuf,
    deployed: BTreeMap<String, ClusterDeployState>,
    cancel: CancellationToken,
    tracker: &TaskTracker,
) -> Result<()> {
    for (name, image_config) in images {
        if !image_config.watch {
            continue;
        }

        let name = name.clone();
        let image_config = image_config.clone();
        let config_dir = config_dir.clone();
        let deployed = deployed.clone();
        let cancel = cancel.clone();

        tracker.spawn(async move {
            if let Err(e) = watch_and_rebuild_image(
                name.clone(),
                image_config,
                registry_port,
                config_dir,
                deployed,
                cancel,
            )
            .await
            {
                error!(image = %name, error = %e, "image watcher failed");
            }
        });
    }

    Ok(())
}

/// Watch a single image's context directory for file changes and trigger
/// rebuild+push cycles when relevant files are modified.
async fn watch_and_rebuild_image(
    name: String,
    image_config: ClusterImageConfig,
    registry_port: Option<u16>,
    config_dir: PathBuf,
    deployed: BTreeMap<String, ClusterDeployState>,
    cancel: CancellationToken,
) -> Result<()> {
    let watch_path = config_dir.join(&image_config.context);

    if !watch_path.exists() {
        warn!(
            image = %name,
            path = %watch_path.display(),
            "watch directory does not exist, skipping watcher"
        );
        return Ok(());
    }

    let (tx, mut rx) = mpsc::channel(100);

    let mut debouncer = new_debouncer(Duration::from_millis(500), move |result| {
        match result {
            Ok(events) => {
                if let Err(e) = tx.try_send(events) {
                    let _ = e;
                }
            }
            Err(e) => {
                eprintln!("file watcher error: {}", e);
            }
        }
    })
    .context("creating file watcher debouncer")?;

    debouncer
        .watcher()
        .watch(&watch_path, RecursiveMode::Recursive)
        .with_context(|| format!("watching directory {}", watch_path.display()))?;

    debug!(
        image = %name,
        path = %watch_path.display(),
        "image file watcher started"
    );

    let mut rebuild_cancel: Option<CancellationToken> = None;

    loop {
        tokio::select! {
            _ = cancel.cancelled() => {
                debug!(image = %name, "image watcher shutting down");
                if let Some(token) = rebuild_cancel.take() {
                    token.cancel();
                }
                break;
            }
            events = rx.recv() => {
                let events = match events {
                    Some(events) => events,
                    None => {
                        warn!(image = %name, "image watcher channel closed unexpectedly");
                        break;
                    }
                };

                let relevant: Vec<_> = events
                    .iter()
                    .filter(|ev| ev.kind == DebouncedEventKind::Any)
                    .filter(|ev| !should_ignore(&ev.path))
                    .collect();

                if relevant.is_empty() {
                    continue;
                }

                debug!(
                    image = %name,
                    "file change detected, rebuilding image..."
                );

                if let Some(token) = rebuild_cancel.take() {
                    token.cancel();
                }

                let child_cancel = cancel.child_token();
                rebuild_cancel = Some(child_cancel.clone());

                let rebuild_name = name.clone();
                let rebuild_config = image_config.clone();
                let rebuild_config_dir = config_dir.clone();

                let rebuild_deployed = deployed.clone();
                tokio::spawn(async move {
                    match deploy::rebuild_image(
                        &rebuild_name,
                        &rebuild_config,
                        registry_port,
                        &rebuild_config_dir,
                        &rebuild_deployed,
                        &child_cancel,
                    )
                    .await
                    {
                        Ok(()) => {
                            debug!(image = %rebuild_name, "image rebuild completed successfully");
                        }
                        Err(e) => {
                            if child_cancel.is_cancelled() {
                                debug!(
                                    image = %rebuild_name,
                                    "image rebuild cancelled (newer change detected)"
                                );
                            } else {
                                error!(
                                    image = %rebuild_name,
                                    error = %e,
                                    "image rebuild failed"
                                );
                            }
                        }
                    }
                });
            }
        }
    }

    drop(debouncer);

    Ok(())
}

/// Watch a single deploy's context directory for file changes and trigger
/// rebuilds when relevant files are modified.
async fn watch_and_rebuild(
    name: String,
    deploy_config: ClusterDeployConfig,
    registry_port: Option<u16>,
    kubeconfig_path: PathBuf,
    config_dir: PathBuf,
    cancel: CancellationToken,
) -> Result<()> {
    let watch_path = config_dir.join(&deploy_config.context);

    if !watch_path.exists() {
        warn!(
            deploy = %name,
            path = %watch_path.display(),
            "watch directory does not exist, skipping watcher"
        );
        return Ok(());
    }

    let (tx, mut rx) = mpsc::channel(100);

    let mut debouncer = new_debouncer(Duration::from_millis(500), move |result| {
        match result {
            Ok(events) => {
                if let Err(e) = tx.try_send(events) {
                    // If the channel is full or closed, log will happen on the receiver side
                    let _ = e;
                }
            }
            Err(e) => {
                eprintln!("file watcher error: {}", e);
            }
        }
    })
    .context("creating file watcher debouncer")?;

    debouncer
        .watcher()
        .watch(&watch_path, RecursiveMode::Recursive)
        .with_context(|| format!("watching directory {}", watch_path.display()))?;

    debug!(
        deploy = %name,
        path = %watch_path.display(),
        "file watcher started"
    );

    // Track any in-progress rebuild so we can cancel it on new changes.
    let mut rebuild_cancel: Option<CancellationToken> = None;

    loop {
        tokio::select! {
            _ = cancel.cancelled() => {
                debug!(deploy = %name, "watcher shutting down");
                // Cancel any in-progress rebuild.
                if let Some(token) = rebuild_cancel.take() {
                    token.cancel();
                }
                // Drop the debouncer by breaking out of the loop; the local
                // variable is dropped when the function returns.
                break;
            }
            events = rx.recv() => {
                let events = match events {
                    Some(events) => events,
                    None => {
                        // Channel closed -- debouncer was dropped unexpectedly.
                        warn!(deploy = %name, "watcher channel closed unexpectedly");
                        break;
                    }
                };

                // Filter to only relevant events (non-ignored paths with
                // an actual data-change kind).
                let relevant: Vec<_> = events
                    .iter()
                    .filter(|ev| ev.kind == DebouncedEventKind::Any)
                    .filter(|ev| !should_ignore(&ev.path))
                    .collect();

                if relevant.is_empty() {
                    continue;
                }

                debug!(
                    deploy = %name,
                    "file change detected, rebuilding..."
                );

                // Cancel any previous in-progress rebuild.
                if let Some(token) = rebuild_cancel.take() {
                    token.cancel();
                }

                // Create a child cancellation token for this rebuild so it
                // can be cancelled independently when the next change arrives.
                let child_cancel = cancel.child_token();
                rebuild_cancel = Some(child_cancel.clone());

                let rebuild_name = name.clone();
                let rebuild_config = deploy_config.clone();
                let rebuild_kubeconfig = kubeconfig_path.clone();
                let rebuild_config_dir = config_dir.clone();

                tokio::spawn(async move {
                    match deploy::run_rebuild(
                        &rebuild_name,
                        &rebuild_config,
                        registry_port,
                        &rebuild_kubeconfig,
                        &rebuild_config_dir,
                        &child_cancel,
                    )
                    .await
                    {
                        Ok(()) => {
                            debug!(deploy = %rebuild_name, "rebuild completed successfully");
                        }
                        Err(e) => {
                            if child_cancel.is_cancelled() {
                                debug!(
                                    deploy = %rebuild_name,
                                    "rebuild cancelled (newer change detected)"
                                );
                            } else {
                                error!(
                                    deploy = %rebuild_name,
                                    error = %e,
                                    "rebuild failed"
                                );
                            }
                        }
                    }
                });
            }
        }
    }

    // Explicitly drop to silence unused-variable warnings and make intent clear.
    drop(debouncer);

    Ok(())
}

/// Returns `true` if the given path should be ignored by the file watcher.
///
/// A path is ignored if any of its directory components match an entry in
/// `IGNORED_DIRS`, or if its file extension matches an entry in
/// `IGNORED_EXTENSIONS`.
fn should_ignore(path: &Path) -> bool {
    for component in path.components() {
        if let std::path::Component::Normal(segment) = component {
            if let Some(s) = segment.to_str() {
                if IGNORED_DIRS.contains(&s) {
                    return true;
                }
            }
        }
    }

    if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
        if IGNORED_EXTENSIONS.contains(&ext) {
            return true;
        }
    }

    false
}

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

    #[test]
    fn test_should_ignore_git_dir() {
        assert!(should_ignore(Path::new("src/.git/config")));
        assert!(should_ignore(Path::new(".git/HEAD")));
    }

    #[test]
    fn test_should_ignore_target_dir() {
        assert!(should_ignore(Path::new("target/debug/build")));
    }

    #[test]
    fn test_should_ignore_node_modules() {
        assert!(should_ignore(Path::new(
            "frontend/node_modules/react/index.js"
        )));
    }

    #[test]
    fn test_should_ignore_pycache() {
        assert!(should_ignore(Path::new(
            "app/__pycache__/module.cpython-310.pyc"
        )));
    }

    #[test]
    fn test_should_ignore_devrig_dir() {
        assert!(should_ignore(Path::new(".devrig/state.json")));
    }

    #[test]
    fn test_should_ignore_claude_dir() {
        assert!(should_ignore(Path::new(".claude/settings.json")));
    }

    #[test]
    fn test_should_ignore_swap_files() {
        assert!(should_ignore(Path::new("src/main.rs.swp")));
        assert!(should_ignore(Path::new("src/main.rs.swo")));
    }

    #[test]
    fn test_should_ignore_tmp_files() {
        assert!(should_ignore(Path::new("data/output.tmp")));
    }

    #[test]
    fn test_should_ignore_pyc_files() {
        assert!(should_ignore(Path::new("app/module.pyc")));
        assert!(should_ignore(Path::new("app/module.pyo")));
    }

    #[test]
    fn test_should_not_ignore_normal_files() {
        assert!(!should_ignore(Path::new("src/main.rs")));
        assert!(!should_ignore(Path::new("Cargo.toml")));
        assert!(!should_ignore(Path::new("frontend/src/App.tsx")));
        assert!(!should_ignore(Path::new("Dockerfile")));
    }
}