pitchfork-cli 2.9.0

Daemons with DX
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
use axum::{
    extract::Path,
    response::{
        Html,
        sse::{Event, KeepAlive, Sse},
    },
};
use std::convert::Infallible;

use crate::daemon::daemon_log_path;
use crate::daemon::is_valid_daemon_id;
use crate::daemon_id::DaemonId;
use crate::env;
use crate::pitchfork_toml::PitchforkToml;
use crate::settings::settings;
use crate::state_file::StateFile;
use crate::web::bp;
use crate::web::helpers::{html_escape, url_encode};
use console;
use std::io::{Read, Seek, SeekFrom};

fn base_html(title: &str, content: &str) -> String {
    let bp = bp();
    format!(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{title} - pitchfork</title>
    <link rel="icon" type="image/x-icon" href="{bp}/static/favicon.ico">
    <script src="https://unpkg.com/htmx.org@2.0.4"></script>
    <script src="https://unpkg.com/htmx-ext-sse@2.2.2/sse.js"></script>
    <script src="https://unpkg.com/lucide@0.474.0"></script>
    <link rel="stylesheet" href="{bp}/static/style.css">
</head>
<body>
    <nav>
        <a href="{bp}/" class="nav-brand"><img src="{bp}/static/logo.png" alt="pitchfork" class="logo-icon"> pitchfork</a>
        <div class="nav-links">
            <a href="{bp}/">Dashboard</a>
            <a href="{bp}/logs" class="active">Logs</a>
            <a href="{bp}/config">Config</a>
        </div>
    </nav>
    <main>
        {content}
    </main>
    <script>
        // Initialize Lucide icons on page load
        lucide.createIcons();

        // Re-initialize Lucide icons after HTMX swaps content
        document.body.addEventListener('htmx:afterSwap', function(evt) {{
            lucide.createIcons();
        }});
    </script>
</body>
</html>"#
    )
}

pub async fn index() -> Html<String> {
    let bp = bp();
    let state = match StateFile::read(&*env::PITCHFORK_STATE_FILE) {
        Ok(state) => state,
        Err(e) => {
            let content = format!(
                r#"<h1>Error</h1><p class="error">Failed to read state file: {}</p><a href="{bp}/" class="btn">Back</a>"#,
                html_escape(&e.to_string())
            );
            return Html(base_html("Error", &content));
        }
    };
    let pt = match PitchforkToml::all_merged() {
        Ok(pt) => pt,
        Err(e) => {
            let content = format!(
                r#"<h1>Error</h1><p class="error">Failed to load configuration: {}</p><a href="{bp}/" class="btn">Back</a>"#,
                html_escape(&e.to_string())
            );
            return Html(base_html("Error", &content));
        }
    };

    // Collect all daemon IDs
    let pitchfork_id = DaemonId::pitchfork();
    let mut ids: Vec<String> = state
        .daemons
        .keys()
        .filter(|id| **id != pitchfork_id)
        .map(|id| id.to_string())
        .collect();

    for id in pt.daemons.keys() {
        let id_str = id.to_string();
        if !ids.contains(&id_str) {
            ids.push(id_str);
        }
    }

    ids.sort();

    let content = if ids.is_empty() {
        r#"
        <h1>Logs</h1>
        <div class="empty-state">
            <h2>No daemons available</h2>
            <p>Configure daemons in your pitchfork.toml to view their logs.</p>
        </div>
        "#
        .to_string()
    } else {
        let mut tabs = String::new();
        let mut tab_contents = String::new();

        for (idx, id) in ids.iter().enumerate() {
            let safe_id = html_escape(id);
            let js_id = js_escape(id);
            let url_id = url_encode(id);
            let is_first = idx == 0;
            let active_class = if is_first { " active" } else { "" };

            // Tab button - use js_id for onclick to prevent JS injection
            tabs.push_str(&format!(
                r#"<button class="tab{active_class}" onclick="switchTab('{js_id}', event)">{safe_id}</button>"#
            ));

            // Tab content
            let log_path = daemon_log_path(id);

            let initial_logs = if log_path.exists() {
                match std::fs::read(&log_path) {
                    Ok(bytes) => {
                        let content = String::from_utf8_lossy(&bytes);
                        let lines: Vec<&str> = content.lines().collect();
                        let log_lines = settings().web.log_lines.max(0) as usize;
                        let start = if log_lines > 0 && lines.len() > log_lines {
                            lines.len() - log_lines
                        } else {
                            0
                        };
                        let stripped = lines[start..].join("\n");
                        html_escape(&console::strip_ansi_codes(&stripped))
                    }
                    Err(_) => String::new(),
                }
            } else {
                "No logs available yet.".to_string()
            };

            tab_contents.push_str(&format!(
                r#"
                <div id="tab-{safe_id}" class="tab-content{active_class}">
                    <div class="page-header">
                        <h2>DAEMON: {safe_id}</h2>
                        <div class="header-actions">
                            <button hx-post="{bp}/logs/{url_id}/clear" hx-swap="none" class="btn btn-sm"
                                hx-confirm="Are you sure you want to clear the logs for {safe_id}?"
                                onclick="clearTabLogs('{js_id}')"><i data-lucide="trash-2" class="icon"></i> Clear Logs</button>
                        </div>
                    </div>
                    <div class="log-viewer">
                        <pre id="log-output-{safe_id}" hx-ext="sse" sse-connect="{bp}/logs/{url_id}/stream" sse-swap="message" hx-swap="beforeend scroll:bottom">{initial_logs}</pre>
                    </div>
                </div>
                "#
            ));
        }

        format!(
            r#"
            <div class="page-header logs-header">
                <h1><i data-lucide="file-text" class="icon" style="width: 28px; height: 28px; vertical-align: middle;"></i> Logs</h1>
            </div>
            <div class="tabs">
                {}
            </div>
            {}
            <script>
                function switchTab(tabId, evt) {{
                    // Hide all tabs
                    document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
                    document.querySelectorAll('.tab').forEach(el => el.classList.remove('active'));

                    // Show selected tab
                    document.getElementById('tab-' + tabId).classList.add('active');
                    evt.currentTarget.classList.add('active');

                    // Scroll to bottom
                    const logOutput = document.getElementById('log-output-' + tabId);
                    if (logOutput) {{
                        logOutput.scrollTop = logOutput.scrollHeight;
                    }}
                }}

                function clearTabLogs(tabId) {{
                    const logOutput = document.getElementById('log-output-' + tabId);
                    if (logOutput) {{
                        setTimeout(() => {{
                            logOutput.textContent = '';
                        }}, 100);
                    }}
                }}

                // Auto-scroll first tab on load
                window.addEventListener('load', function() {{
                    const firstLog = document.querySelector('.tab-content.active pre');
                    if (firstLog) {{
                        firstLog.scrollTop = firstLog.scrollHeight;
                    }}
                }});

                // Setup clear event listeners for all tabs
                {}
            </script>
            "#,
            tabs,
            tab_contents,
            ids.iter()
                .enumerate()
                .map(|(idx, id)| {
                    let js_id = js_escape(id);
                    let url_id = url_encode(id);
                    format!(
                        r#"
                var clearSource_{idx} = new EventSource('{bp}/logs/{url_id}/stream');
                clearSource_{idx}.addEventListener('clear', function(e) {{
                    document.getElementById('log-output-' + '{js_id}').textContent = '';
                }});
                "#
                    )
                })
                .collect::<Vec<_>>()
                .join("\n")
        )
    };

    Html(base_html("Logs", &content))
}

pub async fn show(Path(id): Path<String>) -> Html<String> {
    let bp = bp();
    // Require a fully-qualified daemon ID ("namespace/name") so the log path
    // can be resolved correctly via DaemonId::log_path().
    let daemon_id = match DaemonId::parse(&id) {
        Ok(d) => d,
        Err(_) => {
            let content = format!(
                r#"<h1>Error</h1><p class="error">Invalid or unqualified daemon ID. Use the qualified form <code>namespace/name</code>.</p><a href="{bp}/logs" class="btn"><i data-lucide="arrow-left" class="icon"></i> Back</a>"#
            );
            return Html(base_html("Error", &content));
        }
    };

    let safe_id = html_escape(&daemon_id.to_string());
    let url_id = url_encode(&daemon_id.to_string());
    let log_path = daemon_id.log_path();

    let initial_logs = if log_path.exists() {
        match std::fs::read(&log_path) {
            Ok(bytes) => {
                // Use lossy conversion to handle invalid UTF-8
                let content = String::from_utf8_lossy(&bytes);
                // Get last N lines (configurable via web.log_lines setting)
                let lines: Vec<&str> = content.lines().collect();
                let log_lines = settings().web.log_lines.max(0) as usize;
                let start = if log_lines > 0 && lines.len() > log_lines {
                    lines.len() - log_lines
                } else {
                    0
                };
                html_escape(&lines[start..].join("\n"))
            }
            Err(_) => String::new(),
        }
    } else {
        "No logs available yet.".to_string()
    };

    let content = format!(
        r#"
        <div class="page-header">
            <h1>Logs: {safe_id}</h1>
            <div class="header-actions">
            <button hx-post="{bp}/logs/{url_id}/clear" hx-swap="none" class="btn btn-sm"
                hx-confirm="Are you sure you want to clear the logs for {safe_id}?"><i data-lucide="trash-2" class="icon"></i> Clear Logs</button>
            <a href="{bp}/logs" class="btn btn-sm"><i data-lucide="arrow-left" class="icon"></i> Back</a>            </div>
        </div>
        <div class="log-viewer">
            <pre id="log-output" hx-ext="sse" sse-connect="{bp}/logs/{url_id}/stream" sse-swap="message" hx-swap="beforeend scroll:bottom">{initial_logs}</pre>
        </div>
        <script>
            // Auto-scroll to bottom on load
            document.getElementById('log-output').scrollTop = document.getElementById('log-output').scrollHeight;
            // Listen for clear event using native EventSource (htmx-ext-sse only handles 'message' events)
            var clearSource = new EventSource('{bp}/logs/{url_id}/stream');
            clearSource.addEventListener('clear', function(e) {{
                document.getElementById('log-output').textContent = '';
            }});
        </script>
    "#
    );

    Html(base_html(&format!("Logs: {safe_id}"), &content))
}

pub async fn lines_partial(Path(id): Path<String>) -> Html<String> {
    let daemon_id = match DaemonId::parse(&id) {
        Ok(d) => d,
        Err(_) => return Html(String::new()),
    };

    let log_path = daemon_id.log_path();

    let logs = if log_path.exists() {
        match std::fs::read(&log_path) {
            Ok(bytes) => {
                // Use lossy conversion to handle invalid UTF-8
                let content = String::from_utf8_lossy(&bytes);
                let lines: Vec<&str> = content.lines().collect();
                let log_lines = settings().web.log_lines.max(0) as usize;
                let start = if log_lines > 0 && lines.len() > log_lines {
                    lines.len() - log_lines
                } else {
                    0
                };
                html_escape(&lines[start..].join("\n"))
            }
            Err(_) => String::new(),
        }
    } else {
        String::new()
    };

    Html(logs)
}

pub async fn stream_sse(
    Path(id): Path<String>,
) -> Sse<impl tokio_stream::Stream<Item = Result<Event, Infallible>>> {
    let sse_poll_interval = settings().web_sse_poll_interval();

    let stream = async_stream::stream! {
        // Validate daemon ID to prevent path traversal before touching the filesystem
        if !is_valid_daemon_id(&id) {
            yield Ok(Event::default().event("error").data("invalid daemon id"));
            return;
        }

        let daemon_id = match DaemonId::parse(&id) {
            Ok(d) => d,
            Err(_) => {
                yield Ok(Event::default().event("error").data("invalid daemon id"));
                return;
            }
        };
        let log_path = daemon_id.log_path();
        let (mut last_size, mut last_path_ino) = match tokio::task::spawn_blocking({
            let path = log_path.clone();
            move || {
                match std::fs::metadata(&path) {
                    Ok(metadata) => {
                        #[cfg(unix)]
                        {
                            use std::os::unix::fs::MetadataExt;
                            (metadata.len(), Some(metadata.ino()))
                        }
                        #[cfg(not(unix))]
                        {
                            (metadata.len(), None)
                        }
                    }
                    Err(_) => (0, None),
                }
            }
        })
        .await
        {
            Ok(state) => state,
            Err(err) => {
                warn!(
                    "SSE log stream: failed to read initial metadata for '{}': {err:?}",
                    log_path.display()
                );
                (0, None)
            }
        };
        let mut file_handle: Option<std::fs::File> = None;

        // Internal result type for file operations within spawn_blocking
        enum FileOpResult {
            Data(Vec<u8>),
            Truncated,
            FileRotated,
            SeekFailed,
            ReadFailed,
            Eof,
        }

        struct FileOpOutput {
            file: Option<std::fs::File>,
            size: u64,
            result: Option<FileOpResult>,
            inode: Option<u64>,
        }

        let mut poll_count = 0u64;

        loop {
            tokio::time::sleep(sse_poll_interval).await;
            poll_count = poll_count.wrapping_add(1);

            // Use spawn_blocking for all blocking file operations
            let file_op_result = {
                let path = log_path.clone();
                let fh = file_handle.take();
                let mut ls = last_size;
                let prev_ino = last_path_ino;
                let poll_count = poll_count;
                tokio::task::spawn_blocking(move || {
                    let opened_fresh = fh.is_none();
                    let mut file = match fh {
                        Some(f) => f,
                        None => match std::fs::File::open(&path) {
                            Ok(f) => f,
                            Err(_) => {
                                return FileOpOutput {
                                    file: None,
                                    size: ls,
                                    result: None,
                                    inode: prev_ino,
                                };
                            }
                        },
                    };

                    // Check if file was rotated while we had no handle (fresh open case)
                    // and cache metadata to avoid redundant fstat calls
                    #[cfg(unix)]
                    let (fresh_open_rotated, cached_metadata, fresh_ino) = if opened_fresh {
                        use std::os::unix::fs::MetadataExt;
                        if let Ok(meta) = file.metadata() {
                            let ino = meta.ino();
                            if let Some(prev_ino_val) = prev_ino {
                                if ino != prev_ino_val {
                                    // File was rotated since we last had a handle
                                    (true, Some(meta), Some(ino))
                                } else {
                                    (false, Some(meta), Some(ino))
                                }
                            } else {
                                // No previous inode, capture current one for future checks
                                (false, Some(meta), Some(ino))
                            }
                        } else {
                            (false, None, None)
                        }
                    } else {
                        (false, None, None)
                    };
                    #[cfg(unix)]
                    if fresh_open_rotated {
                        return FileOpOutput {
                            file: None,
                            size: 0,
                            result: Some(FileOpResult::FileRotated),
                            inode: fresh_ino,
                        };
                    }

                    // Fallback for non-unix platforms
                    #[cfg(not(unix))]
                    let (cached_metadata, fresh_ino): (Option<std::fs::Metadata>, Option<u64>) = (None, None);

                    let metadata = match cached_metadata {
                        Some(m) => m,
                        None => match file.metadata() {
                            Ok(m) => m,
                            Err(_) => {
                                return FileOpOutput {
                                    file: None,
                                    size: ls,
                                    result: None,
                                    inode: fresh_ino,
                                };
                            }
                        },
                    };
                    let current_size = metadata.len();

                    // Check if file was recreated (inode changed) on Unix systems
                    #[cfg(unix)]
                    if current_size != ls || poll_count.is_multiple_of(10) {
                        use std::os::unix::fs::MetadataExt;
                        let path_ino = std::fs::metadata(&path).map(|m| m.ino()).ok();
                        let file_ino = metadata.ino();
                        if let Some(path_ino) = path_ino && path_ino != file_ino {
                            // File was recreated; drop handle and reset
                            return FileOpOutput {
                                file: None,
                                size: 0,
                                result: Some(FileOpResult::FileRotated),
                                inode: Some(path_ino),
                            };
                        }
                    }

                    // Use the current file's inode for future rotation checks
                    // metadata is already available from above, no need for extra fstat
                    #[cfg(unix)]
                    let current_ino = fresh_ino.or_else(|| {
                        use std::os::unix::fs::MetadataExt;
                        Some(metadata.ino())
                    });
                    #[cfg(not(unix))]
                    let current_ino: Option<u64> = None;

                    if current_size > ls {
                        // Read new content as bytes to handle invalid UTF-8
                        if file.seek(SeekFrom::Start(ls)).is_err() {
                            return FileOpOutput {
                                file: None,
                                size: ls,
                                result: Some(FileOpResult::SeekFailed),
                                inode: current_ino,
                            };
                        }

                        const MAX_READ_SIZE: u64 = 1024 * 1024;
                        let bytes_to_read = (current_size - ls).min(MAX_READ_SIZE) as usize;
                        let mut buffer = Vec::with_capacity(bytes_to_read);
                        match (&mut file).take(bytes_to_read as u64).read_to_end(&mut buffer) {
                            Ok(0) => {
                                return FileOpOutput {
                                    file: Some(file),
                                    size: ls,
                                    result: Some(FileOpResult::Eof),
                                    inode: current_ino,
                                };
                            }
                            Ok(n) => {
                                ls += n as u64;
                                return FileOpOutput {
                                    file: Some(file),
                                    size: ls,
                                    result: Some(FileOpResult::Data(buffer)),
                                    inode: current_ino,
                                };
                            }
                            Err(_) => {
                                return FileOpOutput {
                                    file: None,
                                    size: ls,
                                    result: Some(FileOpResult::ReadFailed),
                                    inode: current_ino,
                                };
                            }
                        }
                    } else if current_size < ls {
                        // File was truncated (cleared)
                        return FileOpOutput {
                            file: Some(file),
                            size: 0,
                            result: Some(FileOpResult::Truncated),
                            inode: current_ino,
                        };
                    }

                    FileOpOutput {
                        file: Some(file),
                        size: ls,
                        result: None,
                        inode: current_ino,
                    }
                }).await
            };

            match file_op_result {
                Ok(output) => {
                    file_handle = output.file;
                    last_size = output.size;
                    last_path_ino = output.inode;

                    match output.result {
                        Some(FileOpResult::Data(buffer)) => {
                            let new_content = String::from_utf8_lossy(&buffer);
                            let stripped = console::strip_ansi_codes(&new_content);
                            let escaped = html_escape(&stripped);
                            yield Ok(Event::default().event("message").data(escaped));
                        }
                        Some(FileOpResult::Truncated) => {
                            yield Ok(Event::default().event("clear").data(""));
                        }
                        Some(FileOpResult::FileRotated) => {
                            // Signal the client to clear stale content from the previous file
                            yield Ok(Event::default().event("clear").data(""));
                        }
                        Some(FileOpResult::SeekFailed) => {
                            debug!("SSE log stream: seek failed on '{}', will reopen", log_path.display());
                        }
                        Some(FileOpResult::ReadFailed) => {
                            debug!("SSE log stream: read failed on '{}', will reopen", log_path.display());
                        }
                        Some(FileOpResult::Eof) => {
                            debug!(
                                "SSE log stream: read 0 bytes from '{}' after size check; retrying",
                                log_path.display()
                            );
                        }
                        _ => {}
                    }
                }
                Err(err) => {
                    // file_handle is already None after take() above;
                    // last_size remains valid from before this iteration.
                    warn!(
                        "SSE log stream: spawn_blocking panicked for '{}': {err:?}",
                        log_path.display()
                    );
                }
            }
        }
    };

    Sse::new(stream).keep_alive(KeepAlive::default())
}

pub async fn clear(Path(id): Path<String>) -> Html<String> {
    let daemon_id = match DaemonId::parse(&id) {
        Ok(d) => d,
        Err(_) => return Html("".to_string()),
    };

    let log_path = daemon_id.log_path();

    if log_path.exists() {
        let _ = std::fs::write(&log_path, "");
    }

    Html("".to_string())
}

/// Escape a string for use inside JavaScript single-quoted string literals.
/// This prevents breaking out of the string when the value contains quotes.
fn js_escape(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('\'', "\\'")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
}