monocle 1.2.0

A commandline application to search, parse, and process BGP information in public sources.
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
//! WebSocket server module for Monocle
//!
//! This module provides a WebSocket API server for Monocle, enabling real-time
//! communication with clients for BGP data operations.
//!
//! # Architecture
//!
//! The server is organized into several submodules:
//!
//! - `protocol` - Protocol types (request/response envelopes, error codes)
//! - `query` - Non-core protocol helper types (pagination/filters) used by query/streaming methods
//! - `handler` - Handler trait and context for method implementations
//! - `sink` - WebSocket sink abstraction for typed envelope writing (transport-level)
//! - `op_sink` - Operation-scoped sink enforcing streaming terminal semantics (protocol-level)
//! - `router` - Registry-based method routing
//! - `operations` - Operation registry for streaming operations and cancellation
//! - `handlers` - Individual method handler implementations
//!
//! # Connection lifecycle
//!
//! The WebSocket connection loop enforces:
//! - max message size (`ServerConfig.max_message_size`)
//! - periodic ping keepalive (`ServerConfig.ping_interval_secs`)
//! - idle timeout (`ServerConfig.connection_timeout_secs`)
//!
//! # Usage
//!
//! ```rust,ignore
//! use monocle::server::{create_router, WsContext, ServerConfig};
//! use monocle::config::MonocleConfig;
//!
//! // Create the router with all handlers registered
//! let router = create_router();
//!
//! // Create context from config
//! let config = MonocleConfig::new(&None)?;
//! let context = WsContext::from_config(config);
//!
//! // Start the server
//! let server_config = ServerConfig::default();
//! start_server(router, context, server_config).await?;
//! ```

pub mod handler;
pub mod handlers;
pub mod op_sink;
pub mod operations;
pub mod protocol;
pub mod query;
pub mod router;
pub mod sink;

// Re-export commonly used types
pub use handler::{WsContext, WsError, WsMethod, WsRequest, WsResult};
pub use op_sink::{WsOpSink, WsOpSinkError};
pub use operations::{OperationRegistry, OperationStatus};
pub use protocol::{
    ErrorCode, ErrorData, ProgressStage, RequestEnvelope, ResponseEnvelope, ResponseType,
    SystemInfo,
};
pub use router::{Dispatcher, Router};
pub use sink::{WsSink, WsSinkError};

use axum::{
    extract::{
        ws::{Message, WebSocket, WebSocketUpgrade},
        State,
    },
    response::Response,
    routing::get,
    Router as AxumRouter,
};
use futures::StreamExt;
use std::sync::Arc;
use tokio::time::{Duration, Instant};
use tower_http::cors::{Any, CorsLayer};

// =============================================================================
// Server Configuration
// =============================================================================

/// Server configuration
#[derive(Debug, Clone)]
pub struct ServerConfig {
    /// Address to bind to
    pub address: String,

    /// Port to listen on
    pub port: u16,

    /// Maximum concurrent operations per connection
    pub max_concurrent_ops: usize,

    /// Maximum message size in bytes
    pub max_message_size: usize,

    /// Connection timeout in seconds
    pub connection_timeout_secs: u64,

    /// Ping interval in seconds
    pub ping_interval_secs: u64,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            address: "127.0.0.1".to_string(),
            port: 8080,
            max_concurrent_ops: 10,
            max_message_size: 1024 * 1024, // 1MB
            connection_timeout_secs: 300,  // 5 minutes
            ping_interval_secs: 30,
        }
    }
}

impl ServerConfig {
    /// Create a new server configuration
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the address
    pub fn with_address(mut self, address: impl Into<String>) -> Self {
        self.address = address.into();
        self
    }

    /// Set the port
    pub fn with_port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }

    /// Get the full bind address
    pub fn bind_address(&self) -> String {
        format!("{}:{}", self.address, self.port)
    }
}

// =============================================================================
// Router Creation
// =============================================================================

/// Create a router with all handlers registered
pub fn create_router() -> Router {
    use handlers::*;

    let mut router = Router::new();

    // System handlers
    router.register::<SystemInfoHandler>();

    // Time handlers
    router.register::<TimeParseHandler>();

    // Country handlers
    router.register::<CountryLookupHandler>();

    // IP handlers
    router.register::<IpLookupHandler>();
    router.register::<IpPublicHandler>();

    // RPKI handlers
    router.register::<RpkiValidateHandler>();
    router.register::<RpkiRoasHandler>();
    router.register::<RpkiAspasHandler>();

    // AS2Rel handlers
    router.register::<As2relSearchHandler>();
    router.register::<As2relRelationshipHandler>();
    router.register::<As2relUpdateHandler>();

    // Pfx2as handlers
    router.register::<Pfx2asLookupHandler>();

    // Database handlers
    router.register::<DatabaseStatusHandler>();
    router.register::<DatabaseRefreshHandler>();

    // Inspect handlers
    router.register::<InspectQueryHandler>();
    router.register::<InspectRefreshHandler>();

    router
}

// =============================================================================
// Server State
// =============================================================================

/// Shared server state
#[derive(Clone)]
pub struct ServerState {
    /// Dispatcher for routing messages
    pub dispatcher: Arc<Dispatcher>,

    /// Server configuration
    pub config: Arc<ServerConfig>,
}

// =============================================================================
// Axum Router Creation
// =============================================================================

/// Create the Axum router for the WebSocket server
pub fn create_axum_router(state: ServerState) -> AxumRouter {
    // Configure CORS
    let cors = CorsLayer::new()
        .allow_origin(Any)
        .allow_methods(Any)
        .allow_headers(Any);

    AxumRouter::new()
        .route("/ws", get(ws_handler))
        .route("/health", get(health_handler))
        .layer(cors)
        .with_state(state)
}

/// Health check handler
async fn health_handler() -> &'static str {
    "OK"
}

/// WebSocket upgrade handler
async fn ws_handler(ws: WebSocketUpgrade, State(state): State<ServerState>) -> Response {
    ws.on_upgrade(move |socket| handle_socket(socket, state))
}

/// Handle a WebSocket connection
async fn handle_socket(socket: WebSocket, state: ServerState) {
    let (sender, mut receiver) = socket.split();
    let sink = WsSink::new(sender);

    tracing::info!("WebSocket connection established");

    let max_message_size = state.config.max_message_size;
    let ping_interval = Duration::from_secs(state.config.ping_interval_secs.max(1));
    let idle_timeout = Duration::from_secs(state.config.connection_timeout_secs.max(1));

    let mut last_activity = Instant::now();
    let mut next_ping = Instant::now() + ping_interval;

    // Connection loop: enforce max message size, periodic ping keepalive, and idle timeout.
    loop {
        tokio::select! {
            maybe_msg = receiver.next() => {
                let Some(msg) = maybe_msg else {
                    break;
                };

                match msg {
                    Ok(Message::Text(text)) => {
                        if text.len() > max_message_size {
                            tracing::warn!(
                                "Closing connection: text message too large ({} > {} bytes)",
                                text.len(),
                                max_message_size
                            );
                            let _ = sink.send_message_raw(Message::Close(None)).await;
                            break;
                        }
                        last_activity = Instant::now();
                        tracing::debug!("Received message: {}", text);
                        state.dispatcher.dispatch(&text, sink.clone()).await;
                    }
                    Ok(Message::Binary(data)) => {
                        if data.len() > max_message_size {
                            tracing::warn!(
                                "Closing connection: binary message too large ({} > {} bytes)",
                                data.len(),
                                max_message_size
                            );
                            let _ = sink.send_message_raw(Message::Close(None)).await;
                            break;
                        }
                        last_activity = Instant::now();

                        // Try to parse binary as UTF-8 text
                        match String::from_utf8(data) {
                            Ok(text) => {
                                tracing::debug!("Received binary message as text: {}", text);
                                state.dispatcher.dispatch(&text, sink.clone()).await;
                            }
                            Err(_) => {
                                tracing::warn!("Received non-UTF8 binary message, ignoring");
                            }
                        }
                    }
                    Ok(Message::Ping(data)) => {
                        last_activity = Instant::now();
                        // Respond with pong
                        if let Err(e) = sink.send_message_raw(Message::Pong(data)).await {
                            tracing::warn!("Failed to send pong: {}", e);
                            break;
                        }
                    }
                    Ok(Message::Pong(_)) => {
                        last_activity = Instant::now();
                        // Ignore pong responses
                    }
                    Ok(Message::Close(_)) => {
                        tracing::info!("WebSocket connection closed by client");
                        break;
                    }
                    Err(e) => {
                        tracing::error!("WebSocket error: {}", e);
                        break;
                    }
                }
            }

            _ = tokio::time::sleep_until(next_ping) => {
                // Idle timeout check
                if last_activity.elapsed() > idle_timeout {
                    tracing::info!(
                        "Closing connection due to idle timeout (>{}s)",
                        idle_timeout.as_secs()
                    );
                    let _ = sink.send_message_raw(Message::Close(None)).await;
                    break;
                }

                // Periodic ping keepalive
                if let Err(e) = sink.send_message_raw(Message::Ping(Vec::new())).await {
                    tracing::warn!("Failed to send ping: {}", e);
                    break;
                }

                next_ping = Instant::now() + ping_interval;
            }
        }
    }

    tracing::info!("WebSocket connection closed");
}

// =============================================================================
// Server Startup
// =============================================================================

/// Start the WebSocket server
pub async fn start_server(
    router: Router,
    context: WsContext,
    config: ServerConfig,
) -> anyhow::Result<()> {
    let operations = OperationRegistry::with_max_concurrent(config.max_concurrent_ops);
    let dispatcher = Dispatcher::new(router, context, operations);

    let state = ServerState {
        dispatcher: Arc::new(dispatcher),
        config: Arc::new(config.clone()),
    };

    let app = create_axum_router(state);

    let bind_address = config.bind_address();
    tracing::info!("Starting WebSocket server on {}", bind_address);

    let listener = tokio::net::TcpListener::bind(&bind_address).await?;
    axum::serve(listener, app).await?;

    Ok(())
}

// =============================================================================
// Tests
// =============================================================================

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

    #[test]
    fn test_server_config_default() {
        let config = ServerConfig::default();
        assert_eq!(config.address, "127.0.0.1");
        assert_eq!(config.port, 8080);
        assert_eq!(config.max_concurrent_ops, 10);
    }

    #[test]
    fn test_server_config_builder() {
        let config = ServerConfig::new().with_address("0.0.0.0").with_port(9000);

        assert_eq!(config.address, "0.0.0.0");
        assert_eq!(config.port, 9000);
        assert_eq!(config.bind_address(), "0.0.0.0:9000");
    }

    #[test]
    fn test_create_router() {
        let router = create_router();

        // Check that key methods are registered
        assert!(router.has_method("system.info"));
        assert!(router.has_method("time.parse"));
        assert!(router.has_method("country.lookup"));
        assert!(router.has_method("ip.lookup"));
        assert!(router.has_method("ip.public"));
        assert!(router.has_method("rpki.validate"));
        assert!(router.has_method("rpki.roas"));
        assert!(router.has_method("rpki.aspas"));
        assert!(router.has_method("as2rel.search"));
        assert!(router.has_method("as2rel.relationship"));
        assert!(router.has_method("as2rel.update"));
        assert!(router.has_method("pfx2as.lookup"));
        assert!(router.has_method("database.status"));
        assert!(router.has_method("database.refresh"));
        assert!(router.has_method("inspect.query"));
        assert!(router.has_method("inspect.refresh"));

        // Check that unknown methods return false
        assert!(!router.has_method("unknown.method"));
    }

    #[test]
    fn test_router_streaming_flags() {
        let router = create_router();

        // Non-streaming methods
        assert!(!router.is_streaming("system.info"));
        assert!(!router.is_streaming("time.parse"));
        assert!(!router.is_streaming("rpki.validate"));

        // Unknown methods should return false
        assert!(!router.is_streaming("unknown.method"));
    }
}