tap-node 0.6.0

Transaction Authorization Protocol (TAP) node implementation for routing and processing messages
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
//! # Event Logger for TAP Node
//!
//! This module provides an event logging system that captures all node events
//! and logs them to a configurable location. It implements the `EventSubscriber`
//! trait to receive events via callbacks from the event bus.
//!
//! The event logger supports different output formats and destinations, including:
//! - Console logging via the standard logging framework
//! - File-based logging with rotation support
//! - Structured JSON logging for machine readability
//!
//! ## Usage
//!
//! ```no_run
//! use std::sync::Arc;
//! use tap_node::{NodeConfig, TapNode};
//! use tap_node::event::logger::{EventLogger, EventLoggerConfig, LogDestination};
//!
//! async fn example() {
//!     // Create a new TAP node
//!     let node = TapNode::new(NodeConfig::default());
//!
//!     // Configure the event logger
//!     let logger_config = EventLoggerConfig {
//!         destination: LogDestination::File {
//!             path: "/var/log/tap-node/events.log".to_string(),
//!             max_size: Some(10 * 1024 * 1024), // 10 MB
//!             rotate: true,
//!         },
//!         structured: true, // Use JSON format
//!         log_level: log::Level::Info,
//!     };
//!
//!     // Create and subscribe the event logger
//!     let event_logger = Arc::new(EventLogger::new(logger_config));
//!     node.event_bus().subscribe(event_logger).await;
//!
//!     // The event logger will now receive and log all events
//! }
//! ```

use std::fmt;
use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::SystemTime;

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde_json::json;
use tracing::{debug, error, info, trace, warn};

use crate::error::{Error, Result};
use crate::event::{EventSubscriber, NodeEvent};

/// Configuration for where event logs should be sent
#[derive(Clone)]
pub enum LogDestination {
    /// Log to the console via the standard logging framework
    Console,

    /// Log to a file with optional rotation
    File {
        /// Path to the log file
        path: String,

        /// Maximum file size before rotation (in bytes)
        max_size: Option<usize>,

        /// Whether to rotate log files when they reach max_size
        rotate: bool,
    },

    /// Custom logging function
    Custom(Arc<dyn Fn(&str) + Send + Sync>),
}

// Custom Debug implementation that doesn't try to print the function pointer
impl fmt::Debug for LogDestination {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LogDestination::Console => write!(f, "LogDestination::Console"),
            LogDestination::File {
                path,
                max_size,
                rotate,
            } => f
                .debug_struct("LogDestination::File")
                .field("path", path)
                .field("max_size", max_size)
                .field("rotate", rotate)
                .finish(),
            LogDestination::Custom(_) => write!(f, "LogDestination::Custom(<function>)"),
        }
    }
}

/// Configuration for the event logger
#[derive(Debug, Clone)]
pub struct EventLoggerConfig {
    /// Where to send the log output
    pub destination: LogDestination,

    /// Whether to use structured (JSON) logging
    pub structured: bool,

    /// The log level to use
    pub log_level: log::Level,
}

impl Default for EventLoggerConfig {
    fn default() -> Self {
        Self {
            destination: LogDestination::Console,
            structured: false,
            log_level: log::Level::Info,
        }
    }
}

/// Event logger for TAP Node
///
/// This component subscribes to the node's event bus and logs all events
/// to the configured destination. It supports both plain text and structured
/// (JSON) logging, and can output to the console or files.
pub struct EventLogger {
    /// Configuration for the logger
    config: EventLoggerConfig,

    /// File handle if using file destination
    file: Option<Arc<Mutex<File>>>,
}

impl EventLogger {
    /// Create a new event logger with the given configuration
    pub fn new(config: EventLoggerConfig) -> Self {
        let file = match &config.destination {
            LogDestination::File { path, .. } => match Self::open_log_file(path) {
                Ok(file) => Some(Arc::new(Mutex::new(file))),
                Err(err) => {
                    error!("Failed to open log file {}: {}", path, err);
                    None
                }
            },
            _ => None,
        };

        Self { config, file }
    }

    /// Open or create a log file
    fn open_log_file(path: &str) -> io::Result<File> {
        // Ensure directory exists
        if let Some(parent) = Path::new(path).parent() {
            std::fs::create_dir_all(parent)?;
        }

        // Open or create the file
        OpenOptions::new().create(true).append(true).open(path)
    }

    /// Log an event to the configured destination
    fn log_event(&self, event: &NodeEvent) -> Result<()> {
        let log_message = if self.config.structured {
            self.format_structured_log(event)?
        } else {
            self.format_plain_log(event)
        };

        match &self.config.destination {
            LogDestination::Console => {
                // Use the standard logging framework
                match self.config.log_level {
                    log::Level::Error => error!("{}", log_message),
                    log::Level::Warn => warn!("{}", log_message),
                    log::Level::Info => info!("{}", log_message),
                    log::Level::Debug => debug!("{}", log_message),
                    log::Level::Trace => trace!("{}", log_message),
                }
                Ok(())
            }
            LogDestination::File { .. } => {
                if let Some(file) = &self.file {
                    let mut file_guard = file.lock().map_err(|_| {
                        Error::Configuration("Failed to acquire log file lock".to_string())
                    })?;

                    // Write to the file with newline
                    writeln!(file_guard, "{}", log_message).map_err(|err| {
                        Error::Configuration(format!("Failed to write to log file: {}", err))
                    })?;

                    // Ensure the log is flushed
                    file_guard.flush().map_err(|err| {
                        Error::Configuration(format!("Failed to flush log file: {}", err))
                    })?;

                    Ok(())
                } else {
                    // Fall back to console logging if file isn't available
                    error!("{}", log_message);
                    Ok(())
                }
            }
            LogDestination::Custom(func) => {
                // Call the custom logging function
                func(&log_message);
                Ok(())
            }
        }
    }

    /// Format an event as a plain text log message
    fn format_plain_log(&self, event: &NodeEvent) -> String {
        let timestamp = DateTime::<Utc>::from(SystemTime::now()).format("%Y-%m-%dT%H:%M:%S%.3fZ");

        match event {
            NodeEvent::PlainMessageReceived { message } => {
                format!("[{}] MESSAGE RECEIVED: {}", timestamp, message)
            }
            NodeEvent::PlainMessageSent { message, from, to } => {
                format!(
                    "[{}] MESSAGE SENT: from={}, to={}, message={}",
                    timestamp, from, to, message
                )
            }
            NodeEvent::AgentRegistered { did } => {
                format!("[{}] AGENT REGISTERED: {}", timestamp, did)
            }
            NodeEvent::AgentUnregistered { did } => {
                format!("[{}] AGENT UNREGISTERED: {}", timestamp, did)
            }
            NodeEvent::DidResolved { did, success } => {
                format!(
                    "[{}] DID RESOLVED: did={}, success={}",
                    timestamp, did, success
                )
            }
            NodeEvent::AgentPlainMessage { did, message } => {
                format!(
                    "[{}] AGENT MESSAGE: did={}, message_length={}",
                    timestamp,
                    did,
                    message.len()
                )
            }
            NodeEvent::MessageRejected {
                message_id,
                reason,
                from,
                to,
            } => {
                format!(
                    "[{}] MESSAGE REJECTED: id={}, from={}, to={}, reason={}",
                    timestamp, message_id, from, to, reason
                )
            }
            NodeEvent::MessageAccepted {
                message_id,
                message_type,
                from,
                to,
            } => {
                format!(
                    "[{}] MESSAGE ACCEPTED: id={}, type={}, from={}, to={}",
                    timestamp, message_id, message_type, from, to
                )
            }
            NodeEvent::ReplyReceived {
                original_message_id,
                ..
            } => {
                format!(
                    "[{}] REPLY RECEIVED: original_id={}",
                    timestamp, original_message_id
                )
            }
            NodeEvent::TransactionStateChanged {
                transaction_id,
                old_state,
                new_state,
                agent_did,
            } => match agent_did {
                Some(did) => format!(
                    "[{}] TRANSACTION STATE CHANGED: id={}, {} -> {} (by {})",
                    timestamp, transaction_id, old_state, new_state, did
                ),
                None => format!(
                    "[{}] TRANSACTION STATE CHANGED: id={}, {} -> {}",
                    timestamp, transaction_id, old_state, new_state
                ),
            },
            NodeEvent::MessageReceived { message, source } => {
                format!(
                    "[{}] MESSAGE RECEIVED: source={}, type={}, id={}",
                    timestamp, source, message.type_, message.id
                )
            }
            NodeEvent::MessageSent {
                message,
                destination,
            } => {
                format!(
                    "[{}] MESSAGE SENT: destination={}, type={}, id={}",
                    timestamp, destination, message.type_, message.id
                )
            }
            NodeEvent::TransactionCreated {
                transaction,
                agent_did,
            } => {
                format!(
                    "[{}] TRANSACTION CREATED: id={}, agent={}",
                    timestamp, transaction.id, agent_did
                )
            }
            NodeEvent::CustomerUpdated {
                customer_id,
                agent_did,
                update_type,
            } => {
                format!(
                    "[{}] CUSTOMER UPDATED: id={}, agent={}, type={}",
                    timestamp, customer_id, agent_did, update_type
                )
            }
            NodeEvent::DecisionRequired {
                transaction_id,
                transaction_state,
                pending_agents,
                ..
            } => {
                format!(
                    "[{}] DECISION REQUIRED: tx={}, state={}, pending_agents={}",
                    timestamp,
                    transaction_id,
                    transaction_state,
                    pending_agents.join(", ")
                )
            }
        }
    }

    /// Format an event as a structured (JSON) log message
    fn format_structured_log(&self, event: &NodeEvent) -> Result<String> {
        // Create common fields for all event types
        let timestamp = DateTime::<Utc>::from(SystemTime::now()).to_rfc3339();

        // Create event-specific fields
        let (event_type, event_data) = match event {
            NodeEvent::PlainMessageReceived { message } => (
                "message_received",
                json!({
                    "message": message,
                }),
            ),
            NodeEvent::PlainMessageSent { message, from, to } => (
                "message_sent",
                json!({
                    "from": from,
                    "to": to,
                    "message": message,
                }),
            ),
            NodeEvent::AgentRegistered { did } => (
                "agent_registered",
                json!({
                    "did": did,
                }),
            ),
            NodeEvent::AgentUnregistered { did } => (
                "agent_unregistered",
                json!({
                    "did": did,
                }),
            ),
            NodeEvent::DidResolved { did, success } => (
                "did_resolved",
                json!({
                    "did": did,
                    "success": success,
                }),
            ),
            NodeEvent::AgentPlainMessage { did, message } => (
                "agent_message",
                json!({
                    "did": did,
                    "message_length": message.len(),
                }),
            ),
            NodeEvent::MessageRejected {
                message_id,
                reason,
                from,
                to,
            } => (
                "message_rejected",
                json!({
                    "message_id": message_id,
                    "reason": reason,
                    "from": from,
                    "to": to,
                }),
            ),
            NodeEvent::MessageAccepted {
                message_id,
                message_type,
                from,
                to,
            } => (
                "message_accepted",
                json!({
                    "message_id": message_id,
                    "message_type": message_type,
                    "from": from,
                    "to": to,
                }),
            ),
            NodeEvent::ReplyReceived {
                original_message_id,
                reply_message,
                original_message,
            } => (
                "reply_received",
                json!({
                    "original_message_id": original_message_id,
                    "reply_message": serde_json::to_value(reply_message).unwrap_or(json!(null)),
                    "original_message": serde_json::to_value(original_message).unwrap_or(json!(null)),
                }),
            ),
            NodeEvent::TransactionStateChanged {
                transaction_id,
                old_state,
                new_state,
                agent_did,
            } => (
                "transaction_state_changed",
                json!({
                    "transaction_id": transaction_id,
                    "old_state": old_state,
                    "new_state": new_state,
                    "agent_did": agent_did,
                }),
            ),
            NodeEvent::MessageReceived { message, source } => (
                "message_received_new",
                json!({
                    "message": serde_json::to_value(message).unwrap_or(json!(null)),
                    "source": source,
                }),
            ),
            NodeEvent::MessageSent {
                message,
                destination,
            } => (
                "message_sent_new",
                json!({
                    "message": serde_json::to_value(message).unwrap_or(json!(null)),
                    "destination": destination,
                }),
            ),
            NodeEvent::TransactionCreated {
                transaction,
                agent_did,
            } => (
                "transaction_created",
                json!({
                    "transaction_id": transaction.id,
                    "agent_did": agent_did,
                }),
            ),
            NodeEvent::CustomerUpdated {
                customer_id,
                agent_did,
                update_type,
            } => (
                "customer_updated",
                json!({
                    "customer_id": customer_id,
                    "agent_did": agent_did,
                    "update_type": update_type,
                }),
            ),
            NodeEvent::DecisionRequired {
                transaction_id,
                transaction_state,
                decision,
                pending_agents,
            } => (
                "decision_required",
                json!({
                    "transaction_id": transaction_id,
                    "transaction_state": transaction_state,
                    "decision": decision,
                    "pending_agents": pending_agents,
                }),
            ),
        };

        // Combine into a single JSON object
        let log_entry = json!({
            "timestamp": timestamp,
            "event_type": event_type,
            "data": event_data,
        });

        // Serialize to a string
        serde_json::to_string(&log_entry).map_err(|e| Error::Serialization(e.to_string()))
    }
}

#[async_trait]
impl EventSubscriber for EventLogger {
    async fn handle_event(&self, event: NodeEvent) {
        if let Err(err) = self.log_event(&event) {
            error!("Failed to log event: {}", err);
        }
    }
}

impl fmt::Debug for EventLogger {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EventLogger")
            .field("config", &self.config)
            .field("file", &self.file.is_some())
            .finish()
    }
}