portail 2.1.0

Unified proxy/gateway: AI Gateway + MCP Gateway + CDN cache
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
/*
 * Network Discovery — Self-Service Discovery
 *
 * Architecture:
 *
 *   ┌─────────────────────────────────────────────────────────────┐
 *   │                Network Discovery Flow                       │
 *   ├─────────────────────────────────────────────────────────────┤
 *   │                                                             │
 *   │   Agent Joins Network                                       │
 *   │        │                                                    │
 *   │        ▼                                                    │
 *   │   ┌────────────┐     ┌────────────┐     ┌────────────┐     │
 *   │   │  Register  │────▶│  Announce  │────▶│  Store     │     │
 *   │   │  (POST)    │     │  (mDNS)    │     │  (memory)  │     │
 *   │   └────────────┘     └────────────┘     └────────────┘     │
 *   │        │                                                    │
 *   │        ▼                                                    │
 *   │   ┌────────────┐     ┌────────────┐     ┌────────────┐     │
 *   │   │  Heartbeat │────▶│  Update    │────▶│  Expire    │     │
 *   │   │  (periodic)│     │  timestamp │     │  old nodes │     │
 *   │   └────────────┘     └────────────┘     └────────────┘     │
 *   │                                                             │
 *   │   Discovery Methods:                                        │
 *   │   1. HTTP API (POST /discovery/register)                    │
 *   │   2. mDNS/Bonjour (multicast)                              │
 *   │   3. DNS-SD (service discovery)                             │
 *   │   4. Static configuration                                   │
 *   │                                                             │
 *   │   Node Types:                                               │
 *   │   - agent     (AI agent)                                    │
 *   │   - service   (backend service)                             │
 *   │   - gateway   (portail instance)                            │
 *   │   - database  (data store)                                  │
 *   │   - cache     (redis/memcached)                             │
 *   │                                                             │
 *   └─────────────────────────────────────────────────────────────┘
 */

use crate::types::BoundedMeta;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

// ── Types ────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NetworkNode {
    pub id: String,
    pub name: String,
    pub node_type: NodeType,
    pub address: String,
    pub port: u16,
    pub protocol: Protocol,
    pub metadata: BoundedMeta,
    pub registered_at: u64,
    pub last_heartbeat: u64,
    pub status: NodeStatus,
    pub tags: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum NodeType {
    Agent,
    Service,
    Gateway,
    Database,
    Cache,
    Monitor,
    Custom(String),
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum Protocol {
    Http,
    Https,
    Tcp,
    Udp,
    Unix,
    Grpc,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum NodeStatus {
    Online,
    Degraded,
    Offline,
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DiscoveryConfig {
    pub enabled: bool,
    pub heartbeat_interval_secs: u64,
    pub node_expiry_secs: u64,
    pub mdns_enabled: bool,
    pub mdns_domain: String,
    pub dns_sd_enabled: bool,
}

impl Default for DiscoveryConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            heartbeat_interval_secs: 30,
            node_expiry_secs: 300, // 5 minutes
            mdns_enabled: true,
            mdns_domain: "_portail._tcp.local".into(),
            dns_sd_enabled: true,
        }
    }
}

// ── Discovery Store ──────────────────────────────────────────────

pub struct DiscoveryStore {
    nodes: std::sync::RwLock<FxHashMap<String, NetworkNode>>,
    config: DiscoveryConfig,
}

impl DiscoveryStore {
    pub fn new(config: DiscoveryConfig) -> Self {
        Self {
            nodes: std::sync::RwLock::new(FxHashMap::default()),
            config,
        }
    }

    pub fn register(&self, node: NetworkNode) -> NetworkNode {
        let mut nodes = self.nodes.write().unwrap();
        let mut node = node;
        node.registered_at = now_millis();
        node.last_heartbeat = now_millis();
        node.status = NodeStatus::Online;
        nodes.insert(node.id.clone(), node.clone());
        node
    }

    pub fn heartbeat(&self, id: &str) -> Option<NetworkNode> {
        let mut nodes = self.nodes.write().unwrap();
        if let Some(node) = nodes.get_mut(id) {
            node.last_heartbeat = now_millis();
            node.status = NodeStatus::Online;
            Some(node.clone())
        } else {
            None
        }
    }

    pub fn deregister(&self, id: &str) -> bool {
        let mut nodes = self.nodes.write().unwrap();
        nodes.remove(id).is_some()
    }

    pub fn get(&self, id: &str) -> Option<NetworkNode> {
        let nodes = self.nodes.read().unwrap();
        nodes.get(id).cloned()
    }

    pub fn list(&self, node_type: Option<NodeType>) -> Vec<NetworkNode> {
        let nodes = self.nodes.read().unwrap();
        match node_type {
            Some(t) => nodes
                .values()
                .filter(|n| n.node_type == t)
                .cloned()
                .collect(),
            None => nodes.values().cloned().collect(),
        }
    }

    pub fn expire_old(&self) -> usize {
        let mut nodes = self.nodes.write().unwrap();
        let now = now_millis();
        let expiry_ms = self.config.node_expiry_secs * 1000;
        let before = nodes.len();
        nodes.retain(|_, n| now - n.last_heartbeat < expiry_ms);
        before - nodes.len()
    }

    pub fn stats(&self) -> DiscoveryStats {
        let nodes = self.nodes.read().unwrap();
        let now = now_millis();
        let online = nodes
            .values()
            .filter(|n| now - n.last_heartbeat < self.config.node_expiry_secs * 1000)
            .count();

        DiscoveryStats {
            total_nodes: nodes.len(),
            online_nodes: online,
            offline_nodes: nodes.len() - online,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DiscoveryStats {
    pub total_nodes: usize,
    pub online_nodes: usize,
    pub offline_nodes: usize,
}

// ── mDNS/SD Helpers ──────────────────────────────────────────────

pub fn mdns_service_name(_config: &DiscoveryConfig) -> String {
    "_portail._tcp.local.".to_string()
}

pub fn mdns_txt_record(node: &NetworkNode) -> Vec<(String, String)> {
    vec![
        ("id".into(), node.id.clone()),
        ("name".into(), node.name.clone()),
        ("type".into(), format!("{:?}", node.node_type)),
        ("protocol".into(), format!("{:?}", node.protocol)),
        ("port".into(), node.port.to_string()),
    ]
}

// ── Background Discovery Loop ────────────────────────────────────

pub async fn run_discovery(
    config: DiscoveryConfig,
    store: Arc<DiscoveryStore>,
    event_log: Arc<crate::events::EventLog>,
) {
    let interval = std::time::Duration::from_secs(config.heartbeat_interval_secs);

    tracing::info!("Network discovery service started");

    event_log.publish(crate::events::AgentEvent {
        agent_id: "discovery".into(),
        event_type: "started".into(),
        severity: "info".into(),
        timestamp: 0,
        metadata: BoundedMeta::from_iter([
            ("mdns_enabled".into(), config.mdns_enabled.to_string()),
            ("dns_sd_enabled".into(), config.dns_sd_enabled.to_string()),
        ]),
    });

    loop {
        tokio::time::sleep(interval).await;

        // Expire old nodes
        let expired = store.expire_old();
        if expired > 0 {
            event_log.publish(crate::events::AgentEvent {
                agent_id: "discovery".into(),
                event_type: "nodes_expired".into(),
                severity: "info".into(),
                timestamp: 0,
                metadata: BoundedMeta::from_iter([("expired".into(), expired.to_string())]),
            });
        }

        // Publish stats
        let stats = store.stats();
        event_log.publish(crate::events::AgentEvent {
            agent_id: "discovery".into(),
            event_type: "heartbeat".into(),
            severity: "info".into(),
            timestamp: 0,
            metadata: BoundedMeta::from_iter([
                ("total_nodes".into(), stats.total_nodes.to_string()),
                ("online_nodes".into(), stats.online_nodes.to_string()),
                ("offline_nodes".into(), stats.offline_nodes.to_string()),
            ]),
        });
    }
}

// ── HTTP Handlers ────────────────────────────────────────────────

pub async fn handle_register(
    axum::extract::State(state): axum::extract::State<Arc<crate::AppState>>,
    axum::Json(node): axum::Json<NetworkNode>,
) -> impl axum::response::IntoResponse {
    let registered = state.discovery.register(node);
    (axum::http::StatusCode::CREATED, axum::Json(registered))
}

pub async fn handle_heartbeat(
    axum::extract::State(state): axum::extract::State<Arc<crate::AppState>>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> impl axum::response::IntoResponse {
    match state.discovery.heartbeat(&id) {
        Some(node) => (
            axum::http::StatusCode::OK,
            axum::Json(serde_json::to_value(node).unwrap()),
        ),
        None => (
            axum::http::StatusCode::NOT_FOUND,
            axum::Json(serde_json::json!({"error": "not found"})),
        ),
    }
}

pub async fn handle_deregister(
    axum::extract::State(state): axum::extract::State<Arc<crate::AppState>>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> impl axum::response::IntoResponse {
    if state.discovery.deregister(&id) {
        (axum::http::StatusCode::OK, "deregistered")
    } else {
        (axum::http::StatusCode::NOT_FOUND, "not found")
    }
}

pub async fn handle_list(
    axum::extract::State(state): axum::extract::State<Arc<crate::AppState>>,
    axum::extract::Query(params): axum::extract::Query<FxHashMap<String, String>>,
) -> axum::Json<Vec<NetworkNode>> {
    let node_type = params.get("type").and_then(|t| match t.as_str() {
        "agent" => Some(NodeType::Agent),
        "service" => Some(NodeType::Service),
        "gateway" => Some(NodeType::Gateway),
        "database" => Some(NodeType::Database),
        "cache" => Some(NodeType::Cache),
        "monitor" => Some(NodeType::Monitor),
        _ => None,
    });
    axum::Json(state.discovery.list(node_type))
}

pub async fn handle_stats(
    axum::extract::State(state): axum::extract::State<Arc<crate::AppState>>,
) -> axum::Json<DiscoveryStats> {
    axum::Json(state.discovery.stats())
}

// ── Module Router ────────────────────────────────────────────────

pub fn router() -> axum::Router<Arc<crate::AppState>> {
    axum::Router::new()
        .route("/discovery/register", axum::routing::post(handle_register))
        .route(
            "/discovery/heartbeat/{id}",
            axum::routing::post(handle_heartbeat),
        )
        .route(
            "/discovery/deregister/{id}",
            axum::routing::post(handle_deregister),
        )
        .route("/discovery/nodes", axum::routing::get(handle_list))
        .route("/discovery/stats", axum::routing::get(handle_stats))
}

// ── Helpers ──────────────────────────────────────────────────────

fn now_millis() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

// ── Tests ────────────────────────────────────────────────────────

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

    fn test_node(id: &str) -> NetworkNode {
        NetworkNode {
            id: id.into(),
            name: format!("test-{}", id),
            node_type: NodeType::Agent,
            address: "127.0.0.1".into(),
            port: 8787,
            protocol: Protocol::Http,
            metadata: BoundedMeta::default(),
            registered_at: 0,
            last_heartbeat: 0,
            status: NodeStatus::Unknown,
            tags: vec![],
        }
    }

    #[test]
    fn register_and_list() {
        let store = DiscoveryStore::new(DiscoveryConfig::default());
        store.register(test_node("node-1"));
        store.register(test_node("node-2"));

        let nodes = store.list(None);
        assert_eq!(nodes.len(), 2);
    }

    #[test]
    fn heartbeat_updates() {
        let store = DiscoveryStore::new(DiscoveryConfig::default());
        store.register(test_node("node-1"));

        let node = store.heartbeat("node-1").unwrap();
        assert!(matches!(node.status, NodeStatus::Online));
    }

    #[test]
    fn deregister() {
        let store = DiscoveryStore::new(DiscoveryConfig::default());
        store.register(test_node("node-1"));

        assert!(store.deregister("node-1"));
        assert!(store.get("node-1").is_none());
    }

    #[test]
    fn stats() {
        let store = DiscoveryStore::new(DiscoveryConfig::default());
        store.register(test_node("node-1"));
        store.register(test_node("node-2"));

        let stats = store.stats();
        assert_eq!(stats.total_nodes, 2);
        assert_eq!(stats.online_nodes, 2);
    }
}