koi-net 0.3.0

Local network toolkit: service discovery, DNS, health monitoring, TLS proxy, and certificate mesh
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
//! Dashboard wiring — connects domain cores to the shared dashboard
//! infrastructure in `koi_common::dashboard`.
//!
//! This module provides:
//! - A snapshot closure that queries all domain cores
//! - An event forwarding loop that maps domain events → `DashboardSseEvent`
//! - A builder that produces the `DashboardState` consumed by koi-common

use std::sync::Arc;
use std::time::Instant;

use tokio::sync::broadcast;
use tokio_util::sync::CancellationToken;

use koi_common::capability::Capability;
use koi_common::dashboard::{DashboardIdentity, DashboardSseEvent, DashboardState};

// ── Snapshot detail types (private — serialized into opaque JSON) ────

use serde::Serialize;

#[derive(Debug, Serialize)]
struct CapabilityCard {
    name: String,
    enabled: bool,
    healthy: bool,
    summary: String,
}

#[derive(Debug, Serialize)]
struct HealthDetail {
    machines: Vec<koi_health::MachineHealth>,
    services: Vec<koi_health::ServiceHealth>,
}

#[derive(Debug, Serialize)]
struct DnsDetail {
    running: bool,
    zone: String,
    port: u16,
    static_count: usize,
    certmesh_count: usize,
    mdns_count: usize,
}

#[derive(Debug, Serialize)]
struct CertmeshDetail {
    ca_initialized: bool,
    ca_locked: bool,
    auth_method: Option<String>,
    profile: String,
    member_count: usize,
    enrollment_state: String,
}

#[derive(Debug, Serialize)]
struct ProxyDetail {
    entries: Vec<ProxyEntryDetail>,
    listeners: Vec<ProxyListenerDetail>,
}

#[derive(Debug, Serialize)]
struct ProxyEntryDetail {
    name: String,
    listen_port: u16,
    backend: String,
}

#[derive(Debug, Serialize)]
struct ProxyListenerDetail {
    name: String,
    listen_port: u16,
    state: String,
    cert_source: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<String>,
}

#[derive(Debug, Serialize)]
struct UdpDetail {
    bindings: Vec<UdpBindingDetail>,
}

#[derive(Debug, Serialize)]
struct UdpBindingDetail {
    id: String,
    local_addr: String,
}

// ── Domain core references (cloned into the snapshot closure) ────────

#[derive(Clone)]
struct DomainCores {
    mdns: Option<Arc<koi_mdns::MdnsCore>>,
    certmesh: Option<Arc<koi_certmesh::CertmeshCore>>,
    dns: Option<Arc<koi_dns::DnsRuntime>>,
    health: Option<Arc<koi_health::HealthRuntime>>,
    proxy: Option<Arc<koi_proxy::ProxyRuntime>>,
    udp: Option<Arc<koi_udp::UdpRuntime>>,
    runtime: Option<Arc<koi_runtime::RuntimeCore>>,
}

// ── Build snapshot (domain-specific) ────────────────────────────────

async fn build_snapshot_value(cores: &DomainCores) -> serde_json::Value {
    let mut capabilities = Vec::with_capacity(7);

    // mDNS
    if let Some(ref core) = cores.mdns {
        let s = core.status();
        capabilities.push(CapabilityCard {
            name: s.name,
            enabled: true,
            healthy: s.healthy,
            summary: s.summary,
        });
    } else {
        capabilities.push(CapabilityCard {
            name: "mdns".to_string(),
            enabled: false,
            healthy: false,
            summary: "disabled".to_string(),
        });
    }

    // Certmesh
    if let Some(ref core) = cores.certmesh {
        let s = core.status();
        capabilities.push(CapabilityCard {
            name: s.name,
            enabled: true,
            healthy: s.healthy,
            summary: s.summary,
        });
    } else {
        capabilities.push(CapabilityCard {
            name: "certmesh".to_string(),
            enabled: false,
            healthy: false,
            summary: "disabled".to_string(),
        });
    }

    // DNS
    if let Some(ref runtime) = cores.dns {
        let running = runtime.status().await.running;
        if running {
            let s = runtime.core().status();
            capabilities.push(CapabilityCard {
                name: s.name,
                enabled: true,
                healthy: s.healthy,
                summary: s.summary,
            });
        } else {
            capabilities.push(CapabilityCard {
                name: "dns".to_string(),
                enabled: true,
                healthy: false,
                summary: "stopped".to_string(),
            });
        }
    } else {
        capabilities.push(CapabilityCard {
            name: "dns".to_string(),
            enabled: false,
            healthy: false,
            summary: "disabled".to_string(),
        });
    }

    // Health
    if let Some(ref runtime) = cores.health {
        let running = runtime.status().await.running;
        if running {
            let s = runtime.core().status();
            capabilities.push(CapabilityCard {
                name: s.name,
                enabled: true,
                healthy: s.healthy,
                summary: s.summary,
            });
        } else {
            capabilities.push(CapabilityCard {
                name: "health".to_string(),
                enabled: true,
                healthy: false,
                summary: "stopped".to_string(),
            });
        }
    } else {
        capabilities.push(CapabilityCard {
            name: "health".to_string(),
            enabled: false,
            healthy: false,
            summary: "disabled".to_string(),
        });
    }

    // Proxy
    if let Some(ref runtime) = cores.proxy {
        let status = runtime.status().await;
        capabilities.push(CapabilityCard {
            name: "proxy".to_string(),
            enabled: true,
            healthy: true,
            summary: if status.is_empty() {
                "no listeners".to_string()
            } else {
                format!("{} listeners", status.len())
            },
        });
    } else {
        capabilities.push(CapabilityCard {
            name: "proxy".to_string(),
            enabled: false,
            healthy: false,
            summary: "disabled".to_string(),
        });
    }

    // UDP
    if let Some(ref runtime) = cores.udp {
        let s = Capability::status(runtime.as_ref());
        capabilities.push(CapabilityCard {
            name: s.name,
            enabled: true,
            healthy: s.healthy,
            summary: s.summary,
        });
    } else {
        capabilities.push(CapabilityCard {
            name: "udp".to_string(),
            enabled: false,
            healthy: false,
            summary: "disabled".to_string(),
        });
    }

    // Runtime
    if let Some(ref runtime_core) = cores.runtime {
        let s = runtime_core.capability_status().await;
        capabilities.push(CapabilityCard {
            name: s.name,
            enabled: true,
            healthy: s.healthy,
            summary: s.summary,
        });
    } else {
        capabilities.push(CapabilityCard {
            name: "runtime".to_string(),
            enabled: false,
            healthy: false,
            summary: "disabled".to_string(),
        });
    }

    // Domain details
    let health = if let Some(ref runtime) = cores.health {
        let snap = runtime.core().snapshot().await;
        Some(HealthDetail {
            machines: snap.machines,
            services: snap.services,
        })
    } else {
        None
    };

    let dns = if let Some(ref runtime) = cores.dns {
        let core = runtime.core();
        let snap = core.snapshot();
        let cfg = core.config();
        Some(DnsDetail {
            running: runtime.status().await.running,
            zone: cfg.zone.clone(),
            port: cfg.port,
            static_count: snap.static_entries.len(),
            certmesh_count: snap.certmesh_entries.len(),
            mdns_count: snap.mdns_entries.len(),
        })
    } else {
        None
    };

    let certmesh = if let Some(ref core) = cores.certmesh {
        let status = core.certmesh_status().await;
        Some(CertmeshDetail {
            ca_initialized: status.ca_initialized,
            ca_locked: status.ca_locked,
            auth_method: status.auth_method,
            profile: format!("{:?}", status.profile),
            member_count: status.member_count,
            enrollment_state: format!("{:?}", status.enrollment_state),
        })
    } else {
        None
    };

    let proxy = if let Some(ref runtime) = cores.proxy {
        let entries = runtime.core().entries().await;
        let status = runtime.status().await;
        Some(ProxyDetail {
            entries: entries
                .into_iter()
                .map(|e| ProxyEntryDetail {
                    name: e.name,
                    listen_port: e.listen_port,
                    backend: e.backend,
                })
                .collect(),
            listeners: status
                .into_iter()
                .map(|s| ProxyListenerDetail {
                    name: s.name,
                    listen_port: s.listen_port,
                    state: s.state,
                    cert_source: s.cert_source,
                    error: s.error,
                })
                .collect(),
        })
    } else {
        None
    };

    let udp = if let Some(ref runtime) = cores.udp {
        let bindings = runtime.status().await;
        Some(UdpDetail {
            bindings: bindings
                .into_iter()
                .map(|b| UdpBindingDetail {
                    id: b.id,
                    local_addr: b.local_addr,
                })
                .collect(),
        })
    } else {
        None
    };

    serde_json::json!({
        "capabilities": capabilities,
        "health": health,
        "dns": dns,
        "certmesh": certmesh,
        "proxy": proxy,
        "udp": udp,
    })
}

// ── Event forwarding ────────────────────────────────────────────────

/// Spawn a task that subscribes to all domain broadcast channels and
/// forwards events into the unified `DashboardSseEvent` channel.
pub(crate) fn spawn_event_forwarder(
    mdns: Option<Arc<koi_mdns::MdnsCore>>,
    certmesh: Option<Arc<koi_certmesh::CertmeshCore>>,
    dns: Option<Arc<koi_dns::DnsRuntime>>,
    health: Option<Arc<koi_health::HealthRuntime>>,
    proxy: Option<Arc<koi_proxy::ProxyRuntime>>,
    event_tx: broadcast::Sender<DashboardSseEvent>,
    cancel: CancellationToken,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        let mut mdns_rx = mdns.as_ref().map(|c| c.subscribe());
        let mut health_rx = health.as_ref().map(|r| r.core().subscribe());
        let mut dns_rx = dns.as_ref().map(|r| r.core().subscribe());
        let mut certmesh_rx = certmesh.as_ref().map(|c| c.subscribe());
        let mut proxy_rx = proxy.as_ref().map(|r| r.core().subscribe());

        loop {
            let sse_event: Option<DashboardSseEvent> = tokio::select! {
                _ = cancel.cancelled() => break,

                Some(Ok(ev)) = async { match mdns_rx.as_mut() { Some(rx) => Some(rx.recv().await), None => None } } => {
                    let id = uuid::Uuid::now_v7().to_string();
                    match ev {
                        koi_mdns::MdnsEvent::Found(record) => Some(DashboardSseEvent {
                            event_type: "mdns.found".to_string(), id,
                            data: serde_json::to_value(record).unwrap_or_default(),
                        }),
                        koi_mdns::MdnsEvent::Resolved(record) => Some(DashboardSseEvent {
                            event_type: "mdns.resolved".to_string(), id,
                            data: serde_json::to_value(record).unwrap_or_default(),
                        }),
                        koi_mdns::MdnsEvent::Removed { name, service_type } => Some(DashboardSseEvent {
                            event_type: "mdns.removed".to_string(), id,
                            data: serde_json::json!({ "name": name, "service_type": service_type }),
                        }),
                    }
                },

                Some(Ok(ev)) = async { match health_rx.as_mut() { Some(rx) => Some(rx.recv().await), None => None } } => {
                    let id = uuid::Uuid::now_v7().to_string();
                    match ev {
                        koi_health::HealthEvent::StatusChanged { name, status } => Some(DashboardSseEvent {
                            event_type: "health.changed".to_string(), id,
                            data: serde_json::json!({ "name": name, "status": status }),
                        }),
                    }
                },

                Some(Ok(ev)) = async { match dns_rx.as_mut() { Some(rx) => Some(rx.recv().await), None => None } } => {
                    let id = uuid::Uuid::now_v7().to_string();
                    match ev {
                        koi_dns::DnsEvent::EntryUpdated { name, ip } => Some(DashboardSseEvent {
                            event_type: "dns.updated".to_string(), id,
                            data: serde_json::json!({ "name": name, "ip": ip }),
                        }),
                        koi_dns::DnsEvent::EntryRemoved { name } => Some(DashboardSseEvent {
                            event_type: "dns.removed".to_string(), id,
                            data: serde_json::json!({ "name": name }),
                        }),
                    }
                },

                Some(Ok(ev)) = async { match certmesh_rx.as_mut() { Some(rx) => Some(rx.recv().await), None => None } } => {
                    let id = uuid::Uuid::now_v7().to_string();
                    match ev {
                        koi_certmesh::CertmeshEvent::MemberJoined { hostname, fingerprint } => Some(DashboardSseEvent {
                            event_type: "certmesh.joined".to_string(), id,
                            data: serde_json::json!({ "hostname": hostname, "fingerprint": fingerprint }),
                        }),
                        koi_certmesh::CertmeshEvent::MemberRevoked { hostname } => Some(DashboardSseEvent {
                            event_type: "certmesh.revoked".to_string(), id,
                            data: serde_json::json!({ "hostname": hostname }),
                        }),
                        koi_certmesh::CertmeshEvent::Destroyed => Some(DashboardSseEvent {
                            event_type: "certmesh.destroyed".to_string(), id,
                            data: serde_json::json!({}),
                        }),
                    }
                },

                Some(Ok(ev)) = async { match proxy_rx.as_mut() { Some(rx) => Some(rx.recv().await), None => None } } => {
                    let id = uuid::Uuid::now_v7().to_string();
                    match ev {
                        koi_proxy::ProxyEvent::EntryUpdated { entry } => Some(DashboardSseEvent {
                            event_type: "proxy.updated".to_string(), id,
                            data: serde_json::to_value(entry).unwrap_or_default(),
                        }),
                        koi_proxy::ProxyEvent::EntryRemoved { name } => Some(DashboardSseEvent {
                            event_type: "proxy.removed".to_string(), id,
                            data: serde_json::json!({ "name": name }),
                        }),
                    }
                },
            };

            if let Some(ev) = sse_event {
                let _ = event_tx.send(ev);
            }
        }
    })
}

// ── Build dashboard state ───────────────────────────────────────────

/// Construct the `DashboardState` for the daemon.
pub(crate) fn build_dashboard_state(
    cores: &crate::DaemonCores,
    started_at: Instant,
    mode: &'static str,
) -> DashboardState {
    let domain = DomainCores {
        mdns: cores.mdns.clone(),
        certmesh: cores.certmesh.clone(),
        dns: cores.dns.clone(),
        health: cores.health.clone(),
        proxy: cores.proxy.clone(),
        udp: cores.udp.clone(),
        runtime: cores.runtime.clone(),
    };

    let snapshot_fn: koi_common::dashboard::SnapshotFn = Arc::new(move || {
        let d = domain.clone();
        Box::pin(async move { build_snapshot_value(&d).await })
    });

    let (event_tx, _) = broadcast::channel(256);

    DashboardState {
        identity: DashboardIdentity {
            version: env!("CARGO_PKG_VERSION").to_string(),
            platform: std::env::consts::OS.to_string(),
        },
        mode,
        snapshot_fn,
        event_tx,
        started_at,
    }
}