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
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
//! PlainMessage sender implementations for TAP Node.
//!
//! This module provides functionality for sending TAP messages to recipients
//! using various transport mechanisms.
//!
//! # Overview
//!
//! The message sender system in TAP Node implements different strategies for
//! delivering DIDComm messages to their recipients. The primary implementations are:
//!
//! - `NodePlainMessageSender`: A flexible sender that uses a callback function for delivery
//! - `HttpPlainMessageSender`: Sends messages over HTTP with robust error handling and retries
//!
//! # Cross-platform Support
//!
//! The `HttpPlainMessageSender` implementation supports multiple platforms:
//!
//! - Native environments (using reqwest)
//! - WASM environments (using web-sys)
//! - Fallback implementations for environments without these libraries
//!
//! # Usage with TapNode
//!
//! ```no_run
//! # use std::sync::Arc;
//! # use tap_node::{NodeConfig, TapNode, HttpPlainMessageSender, PlainMessageSender};
//! # use tap_msg::didcomm::PlainMessage;
//! # use serde_json::json;
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create a TapNode
//! let node = TapNode::new(NodeConfig::default());
//!
//! // Create a sample message
//! let message = PlainMessage {
//!     id: "test-123".to_string(),
//!     typ: "https://tap.rsvp/schema/1.0#transfer".to_string(),
//!     type_: "https://tap.rsvp/schema/1.0#transfer".to_string(),
//!     body: json!({"amount": "100.00"}),
//!     from: "did:example:sender".to_string(),
//!     to: vec!["did:example:recipient".to_string()],
//!     created_time: Some(chrono::Utc::now().timestamp() as u64),
//!     expires_time: None,
//!     thid: None,
//!     pthid: None,
//!     attachments: None,
//!     from_prior: None,
//!     extra_headers: Default::default(),
//! };
//!
//! // Pack a message using the node's send_message method
//! let packed_message = node.send_message(
//!     "did:example:sender".to_string(),
//!     message
//! ).await?;
//!
//! // Create an HTTP sender for external dispatch
//! let sender = HttpPlainMessageSender::new("https://recipient-endpoint.example.com".to_string());
//!
//! // Send the packed message to the recipient node
//! sender.send(
//!     packed_message,
//!     vec!["did:example:recipient".to_string()]
//! ).await?;
//! # Ok(())
//! # }
//! ```

use async_trait::async_trait;
#[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
use std::collections::HashMap;
use std::fmt::{self, Debug};
use std::sync::Arc;

use crate::error::{Error, Result};
use crate::storage::{
    models::{DeliveryStatus, DeliveryType},
    Storage,
};

/// PlainMessage sender trait for sending packed messages to recipients
#[async_trait]
pub trait PlainMessageSender: Send + Sync + Debug {
    /// Send a packed message to one or more recipients
    async fn send(&self, packed_message: String, recipient_dids: Vec<String>) -> Result<()>;
}

/// Node message sender implementation
pub struct NodePlainMessageSender {
    /// Callback function for sending messages
    send_callback: Arc<dyn Fn(String, Vec<String>) -> Result<()> + Send + Sync>,
}

impl Debug for NodePlainMessageSender {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NodePlainMessageSender")
            .field("send_callback", &"<function>")
            .finish()
    }
}

impl NodePlainMessageSender {
    /// Create a new NodePlainMessageSender with the given callback
    pub fn new<F>(callback: F) -> Self
    where
        F: Fn(String, Vec<String>) -> Result<()> + Send + Sync + 'static,
    {
        Self {
            send_callback: Arc::new(callback),
        }
    }
}

#[async_trait]
impl PlainMessageSender for NodePlainMessageSender {
    async fn send(&self, packed_message: String, recipient_dids: Vec<String>) -> Result<()> {
        // Call the callback function with the packed message and recipient DIDs
        (self.send_callback)(packed_message, recipient_dids)
            .map_err(|e| Error::Dispatch(format!("Failed to send message: {}", e)))
    }
}

/// HTTP message sender implementation for sending messages over HTTP
///
/// This sender allows TAP nodes to send messages to other TAP nodes over HTTP,
/// handling the necessary encoding, content types, and error handling.
///
/// # HTTP Endpoint Structure
///
/// PlainMessages are sent to endpoints derived from the recipient's DID, using a
/// configurable base URL.
///
/// # Error Handling
///
/// The sender includes built-in error handling for common HTTP issues:
/// - Connection timeouts
/// - Request failures
/// - Invalid responses
/// - Rate limiting
///
/// # Configuration
///
/// The sender can be configured with:
/// - Base URL for the HTTP endpoint
/// - Timeout settings
/// - Retry policies
#[derive(Debug)]
pub struct HttpPlainMessageSender {
    /// Base URL for the HTTP endpoint
    base_url: String,
    /// HTTP client (only in native environments)
    #[cfg(feature = "reqwest")]
    client: reqwest::Client,
    /// Timeout for HTTP requests in milliseconds
    #[allow(dead_code)] // Used for future timeout configuration
    timeout_ms: u64,
    /// Maximum number of retries
    max_retries: u32,
}

impl HttpPlainMessageSender {
    /// Create a new HttpPlainMessageSender with the given base URL
    pub fn new(base_url: String) -> Self {
        Self::with_options(base_url, 30000, 3) // Default 30 second timeout, 3 retries
    }

    /// Create a new HttpPlainMessageSender with custom options
    pub fn with_options(base_url: String, timeout_ms: u64, max_retries: u32) -> Self {
        #[cfg(feature = "reqwest")]
        {
            // Create a reqwest client with appropriate settings
            let client = reqwest::Client::builder()
                .timeout(std::time::Duration::from_millis(timeout_ms))
                .user_agent("TAP-Node/0.1")
                .build()
                .unwrap_or_default();

            Self {
                base_url,
                client,
                timeout_ms,
                max_retries,
            }
        }

        #[cfg(not(feature = "reqwest"))]
        {
            Self {
                base_url,
                timeout_ms,
                max_retries,
            }
        }
    }

    /// Helper to construct the endpoint URL for a recipient
    pub fn get_endpoint_url(&self, recipient_did: &str) -> String {
        // In a production implementation, this would map DID to HTTP endpoint
        // This could involve DID resolution or a lookup table

        // For now, we'll use a simple convention:
        // Append the DID to the base URL, with proper URL encoding
        let encoded_did = self.url_encode(recipient_did);
        format!(
            "{}/api/messages/{}",
            self.base_url.trim_end_matches('/'),
            encoded_did
        )
    }

    /// URL-encode a string for safe use in URLs
    fn url_encode(&self, text: &str) -> String {
        use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
        utf8_percent_encode(text, NON_ALPHANUMERIC).to_string()
    }
}

/// WebSocket message sender implementation for sending messages over WebSockets
///
/// This sender enables real-time bidirectional communication between TAP nodes,
/// providing a persistent connection that can be used for both sending and receiving
/// messages. WebSockets are particularly useful for scenarios requiring:
///
/// - Low-latency message delivery
/// - Bidirectional communication
/// - Connection state awareness
/// - Reduced overhead compared to repeated HTTP requests
///
/// # Connection Management
///
/// The WebSocket sender manages a pool of connections to recipient endpoints,
/// keeping them alive and reconnecting as needed. This makes it suitable for
/// high-frequency message exchanges between known parties.
///
/// # Error Handling
///
/// The sender handles various WebSocket-specific error conditions:
/// - Connection failures
/// - PlainMessage delivery failures
/// - Connection drops and reconnection
/// - Protocol errors
///
/// # Cross-platform Support
///
/// Like the HTTP sender, the WebSocket sender supports:
/// - Native environments (using tokio_tungstenite)
/// - WASM environments (using web-sys WebSocket API)
/// - Fallback implementations for environments without these libraries
#[derive(Debug)]
pub struct WebSocketPlainMessageSender {
    /// Base URL for WebSocket endpoints (ws:// or wss://)
    base_url: String,
    /// Active connections (only in native environments)
    #[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
    connections: std::sync::Mutex<HashMap<String, tokio::sync::mpsc::Sender<String>>>,
    /// WebSocket task handles (only in native environments)
    #[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
    task_handles: std::sync::Mutex<HashMap<String, tokio::task::JoinHandle<()>>>,
}

impl WebSocketPlainMessageSender {
    /// Create a new WebSocketPlainMessageSender with the given base URL
    pub fn new(base_url: String) -> Self {
        Self::with_options(base_url)
    }

    /// Create a new WebSocketPlainMessageSender with custom options
    pub fn with_options(base_url: String) -> Self {
        #[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
        {
            Self {
                base_url,
                connections: std::sync::Mutex::new(HashMap::new()),
                task_handles: std::sync::Mutex::new(HashMap::new()),
            }
        }

        #[cfg(not(all(not(target_arch = "wasm32"), feature = "websocket")))]
        {
            Self { base_url }
        }
    }

    /// Helper to construct the WebSocket endpoint URL for a recipient
    fn get_endpoint_url(&self, recipient_did: &str) -> String {
        // In a production implementation, this would map DID to WebSocket endpoint
        // This could involve DID resolution or a lookup table

        // Convert http(s):// to ws(s)://
        let ws_base_url = if self.base_url.starts_with("https://") {
            self.base_url.replace("https://", "wss://")
        } else if self.base_url.starts_with("http://") {
            self.base_url.replace("http://", "ws://")
        } else {
            self.base_url.clone()
        };

        // Append the DID to the base URL, with proper URL encoding
        let encoded_did = self.url_encode(recipient_did);
        format!(
            "{}/ws/messages/{}",
            ws_base_url.trim_end_matches('/'),
            encoded_did
        )
    }

    /// URL-encode a string for safe use in URLs
    fn url_encode(&self, text: &str) -> String {
        use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
        utf8_percent_encode(text, NON_ALPHANUMERIC).to_string()
    }

    /// Ensures a connection exists for the given recipient
    #[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
    async fn ensure_connection(
        &self,
        recipient: &str,
    ) -> Result<tokio::sync::mpsc::Sender<String>> {
        use futures::sink::SinkExt;
        use futures::stream::StreamExt;
        use tokio_tungstenite::connect_async;
        use tokio_tungstenite::tungstenite::protocol::Message;

        // Check if we already have an active connection and return it if we do
        {
            // Scope the lock to ensure it's released before any await points
            let connections = self.connections.lock().unwrap();
            if let Some(connection) = connections.get(recipient) {
                return Ok(connection.clone());
            }
        }

        // Otherwise, create a new connection
        let endpoint = self.get_endpoint_url(recipient);
        log::info!(
            "Creating new WebSocket connection to {} at {}",
            recipient,
            endpoint
        );

        // Create a channel for sending messages to the WebSocket task
        let (tx, mut rx) = tokio::sync::mpsc::channel::<String>(100);

        // Connect to the WebSocket with default timeout (30 seconds)
        let (ws_stream, _) = match tokio::time::timeout(
            std::time::Duration::from_millis(30000),
            connect_async(&endpoint),
        )
        .await
        {
            Ok(Ok(stream)) => stream,
            Ok(Err(e)) => {
                return Err(Error::Dispatch(format!(
                    "Failed to connect to WebSocket endpoint {}: {}",
                    endpoint, e
                )));
            }
            Err(_) => {
                return Err(Error::Dispatch(format!(
                    "Connection to WebSocket endpoint {} timed out",
                    endpoint
                )));
            }
        };

        log::debug!("WebSocket connection established to {}", recipient);

        // Split the WebSocket stream
        let (mut write, mut read) = ws_stream.split();

        // Create a task that will:
        // 1. Listen for messages from the channel and send them to the WebSocket
        // 2. Listen for messages from the WebSocket and handle them
        let recipient_clone = recipient.to_string();
        let handle = tokio::spawn(async move {
            // Process messages from the channel to send over WebSocket
            loop {
                tokio::select! {
                    // Handle outgoing messages
                    Some(message) = rx.recv() => {
                        log::debug!("Sending message to {} via WebSocket", recipient_clone);
                        if let Err(e) = write.send(Message::Text(message)).await {
                            log::error!("Failed to send WebSocket message to {}: {}", recipient_clone, e);
                            // Try to reconnect? For now we'll just log the error
                        }
                    }

                    // Handle incoming messages
                    result = read.next() => {
                        match result {
                            Some(Ok(message)) => {
                                // Process incoming message - for now just log it
                                if let Message::Text(text) = message {
                                    log::debug!("Received WebSocket message from {}: {}", recipient_clone, text);
                                }
                            }
                            Some(Err(e)) => {
                                log::error!("WebSocket error from {}: {}", recipient_clone, e);
                                // Connection likely dropped, exit the loop
                                break;
                            }
                            None => {
                                // WebSocket closed
                                log::info!("WebSocket connection to {} closed", recipient_clone);
                                break;
                            }
                        }
                    }
                }
            }

            // WebSocket loop ended - clean up and possibly reconnect
            log::info!("WebSocket connection to {} terminated", recipient_clone);
        });

        // Store the sender and task handle (using separate scopes to avoid holding multiple locks)
        {
            // Get mutable access to the connections map
            let mut connections = self.connections.lock().unwrap();
            connections.insert(recipient.to_string(), tx.clone());
        }

        {
            // Get mutable access to the task handles map
            let mut task_handles = self.task_handles.lock().unwrap();
            task_handles.insert(recipient.to_string(), handle);
        }

        Ok(tx)
    }
}

#[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
#[async_trait]
impl PlainMessageSender for WebSocketPlainMessageSender {
    async fn send(&self, packed_message: String, recipient_dids: Vec<String>) -> Result<()> {
        if recipient_dids.is_empty() {
            return Err(Error::Dispatch("No recipients specified".to_string()));
        }

        // Track failures to report them at the end
        let mut failures = Vec::new();

        // Send the message to each recipient
        for recipient in &recipient_dids {
            log::info!("Sending message to {} via WebSocket", recipient);

            // Ensure we have a connection
            match self.ensure_connection(recipient).await {
                Ok(sender) => {
                    // Send the message through the channel to the WebSocket task
                    if let Err(e) = sender.send(packed_message.clone()).await {
                        let err_msg = format!("Failed to send message to WebSocket task: {}", e);
                        log::error!("{}", err_msg);
                        failures.push((recipient.clone(), err_msg));
                    }
                }
                Err(e) => {
                    let err_msg = format!("Failed to establish WebSocket connection: {}", e);
                    log::error!("{}", err_msg);
                    failures.push((recipient.clone(), err_msg));
                }
            }
        }

        // Report failures if any
        if !failures.is_empty() {
            let failure_messages = failures
                .iter()
                .map(|(did, err)| format!("{}: {}", did, err))
                .collect::<Vec<_>>()
                .join("; ");

            return Err(Error::Dispatch(format!(
                "Failed to send message to some recipients via WebSocket: {}",
                failure_messages
            )));
        }

        Ok(())
    }
}

// Specific implementation for WASM environments with web-sys feature
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
#[async_trait(?Send)]
impl PlainMessageSender for WebSocketPlainMessageSender {
    async fn send(&self, packed_message: String, recipient_dids: Vec<String>) -> Result<()> {
        use wasm_bindgen::prelude::*;
        use wasm_bindgen_futures::JsFuture;
        use web_sys::{MessageEvent, WebSocket};

        if recipient_dids.is_empty() {
            return Err(Error::Dispatch("No recipients specified".to_string()));
        }

        // Track failures to report them at the end
        let mut failures = Vec::new();

        // Get the window object
        let window = web_sys::window().ok_or_else(|| {
            Error::Dispatch("Could not get window object in WASM environment".to_string())
        })?;

        // Send the message to each recipient
        for recipient in &recipient_dids {
            let endpoint = self.get_endpoint_url(recipient);
            log::info!(
                "Sending message to {} via WebSocket at {} (WASM)",
                recipient,
                endpoint
            );

            // Create a promise to set up a WebSocket connection and send the message
            let (resolve, reject) = js_sys::Promise::new_resolver();
            let promise_resolver = resolve.clone();
            let promise_rejecter = reject.clone();

            // Create a new WebSocket
            let ws = match WebSocket::new(&endpoint) {
                Ok(ws) => ws,
                Err(err) => {
                    let err_msg = format!("Failed to create WebSocket: {:?}", err);
                    log::error!("{}", err_msg);
                    failures.push((recipient.clone(), err_msg));
                    continue;
                }
            };

            // Set up event handlers
            let onopen_callback = Closure::once(Box::new(move |_: web_sys::Event| {
                promise_resolver.resolve(&JsValue::from(true));
            }) as Box<dyn FnOnce(web_sys::Event)>);

            let onerror_callback = Closure::once(Box::new(move |e: web_sys::Event| {
                let err_msg = format!("WebSocket error: {:?}", e);
                promise_rejecter.reject(&JsValue::from_str(&err_msg));
            }) as Box<dyn FnOnce(web_sys::Event)>);

            let message_clone = packed_message.clone();
            let onmessage_callback = Closure::wrap(Box::new(move |e: MessageEvent| {
                if let Ok(txt) = e.data().dyn_into::<js_sys::JsString>() {
                    log::debug!("Received message: {}", String::from(txt));
                }
            }) as Box<dyn FnMut(MessageEvent)>);

            // Register event handlers
            ws.set_onopen(Some(onopen_callback.as_ref().unchecked_ref()));
            ws.set_onerror(Some(onerror_callback.as_ref().unchecked_ref()));
            ws.set_onmessage(Some(onmessage_callback.as_ref().unchecked_ref()));

            // Wait for the connection to be established
            match JsFuture::from(js_sys::Promise::race(&js_sys::Array::of2(
                &js_sys::Promise::resolve(&promise_resolver),
                &js_sys::Promise::new(&mut |resolve, _| {
                    let timeout_closure = Closure::once_into_js(move || {
                        resolve.call0(&JsValue::NULL).unwrap();
                    });
                    window
                        .set_timeout_with_callback_and_timeout_and_arguments_0(
                            timeout_closure.as_ref().unchecked_ref(),
                            30000, // Default 30 second timeout
                        )
                        .unwrap();
                }),
            )))
            .await
            {
                Ok(_) => {
                    // Connection established, send the message
                    if let Err(err) = ws.send_with_str(&message_clone) {
                        let err_msg = format!("Failed to send WebSocket message: {:?}", err);
                        log::error!("{}", err_msg);
                        failures.push((recipient.clone(), err_msg));
                    }
                }
                Err(err) => {
                    let err_msg = format!("WebSocket connection failed: {:?}", err);
                    log::error!("{}", err_msg);
                    failures.push((recipient.clone(), err_msg));
                }
            }

            // Keep the callbacks alive
            onopen_callback.forget();
            onerror_callback.forget();
            onmessage_callback.forget();
        }

        // Report failures if any
        if !failures.is_empty() {
            let failure_messages = failures
                .iter()
                .map(|(did, err)| format!("{}: {}", did, err))
                .collect::<Vec<_>>()
                .join("; ");

            return Err(Error::Dispatch(format!(
                "Failed to send message to some recipients via WebSocket: {}",
                failure_messages
            )));
        }

        Ok(())
    }
}

// Fallback implementation for environments without WebSocket support
#[cfg(not(any(
    all(not(target_arch = "wasm32"), feature = "websocket"),
    all(target_arch = "wasm32", feature = "wasm")
)))]
#[async_trait]
impl PlainMessageSender for WebSocketPlainMessageSender {
    async fn send(&self, packed_message: String, recipient_dids: Vec<String>) -> Result<()> {
        // This is a fallback implementation when neither tokio_tungstenite nor web-sys is available
        for recipient in &recipient_dids {
            let endpoint = self.get_endpoint_url(recipient);
            log::info!(
                "Would send message to {} via WebSocket at {} (WebSocket not available)",
                recipient,
                endpoint
            );
            log::debug!("PlainMessage content: {}", packed_message);
        }

        log::warn!("WebSocket sender is running without WebSocket features enabled. No actual WebSocket connections will be made.");
        Ok(())
    }
}

#[cfg(all(not(target_arch = "wasm32"), feature = "reqwest"))]
#[async_trait]
impl PlainMessageSender for HttpPlainMessageSender {
    async fn send(&self, packed_message: String, recipient_dids: Vec<String>) -> Result<()> {
        if recipient_dids.is_empty() {
            return Err(Error::Dispatch("No recipients specified".to_string()));
        }

        // Track failures to report them at the end
        let mut failures = Vec::new();

        // Send the message to each recipient
        for recipient in &recipient_dids {
            let endpoint = self.get_endpoint_url(recipient);
            log::info!("Sending message to {} via HTTP at {}", recipient, endpoint);

            // Retry logic
            let mut attempt = 0;
            let mut success = false;
            let mut last_error = None;

            while attempt < self.max_retries && !success {
                attempt += 1;

                // Exponential backoff for retries
                if attempt > 1 {
                    let backoff_ms = 100 * (2_u64.pow(attempt - 1));
                    tokio::time::sleep(std::time::Duration::from_millis(backoff_ms)).await;
                }

                // Make the HTTP request
                match self
                    .client
                    .post(&endpoint)
                    .header("Content-Type", "application/didcomm-message+json")
                    .body(packed_message.clone())
                    .send()
                    .await
                {
                    Ok(response) => {
                        // Check if the response was successful (2xx status code)
                        if response.status().is_success() {
                            log::debug!("Successfully sent message to {}", recipient);
                            success = true;
                        } else {
                            let status = response.status();
                            let body = response.text().await.unwrap_or_default();
                            log::warn!(
                                "Failed to send message to {} (attempt {}/{}): HTTP {} - {}",
                                recipient,
                                attempt,
                                self.max_retries,
                                status,
                                body
                            );
                            last_error = Some(format!("HTTP error: {} - {}", status, body));

                            // Don't retry certain status codes
                            if status.as_u16() == 404 || status.as_u16() == 400 {
                                break; // Don't retry not found or bad request
                            }
                        }
                    }
                    Err(err) => {
                        log::warn!(
                            "Failed to send message to {} (attempt {}/{}): {}",
                            recipient,
                            attempt,
                            self.max_retries,
                            err
                        );
                        last_error = Some(format!("Request error: {}", err));
                    }
                }
            }

            if !success {
                // Record the failure
                failures.push((
                    recipient.clone(),
                    last_error.unwrap_or_else(|| "Unknown error".to_string()),
                ));
            }
        }

        // Report failures if any
        if !failures.is_empty() {
            let failure_messages = failures
                .iter()
                .map(|(did, err)| format!("{}: {}", did, err))
                .collect::<Vec<_>>()
                .join("; ");

            return Err(Error::Dispatch(format!(
                "Failed to send message to some recipients: {}",
                failure_messages
            )));
        }

        Ok(())
    }
}

#[cfg(all(not(target_arch = "wasm32"), not(feature = "reqwest")))]
#[async_trait]
impl PlainMessageSender for HttpPlainMessageSender {
    async fn send(&self, packed_message: String, recipient_dids: Vec<String>) -> Result<()> {
        // This is a fallback implementation when reqwest is not available
        // In a production environment, reqwest should always be available in the native configuration

        for recipient in &recipient_dids {
            let endpoint = self.get_endpoint_url(recipient);
            log::info!(
                "Would send message to {} via HTTP at {} (reqwest not available)",
                recipient,
                endpoint
            );
            log::debug!("PlainMessage content: {}", packed_message);
        }

        log::warn!("HTTP sender is running without reqwest feature enabled. No actual HTTP requests will be made.");
        Ok(())
    }
}

// Specific implementation for WASM environments with web-sys feature
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
#[async_trait(?Send)]
impl PlainMessageSender for HttpPlainMessageSender {
    async fn send(&self, packed_message: String, recipient_dids: Vec<String>) -> Result<()> {
        use wasm_bindgen::prelude::*;
        use wasm_bindgen_futures::JsFuture;
        use web_sys::{Request, RequestInit, RequestMode, Response};

        if recipient_dids.is_empty() {
            return Err(Error::Dispatch("No recipients specified".to_string()));
        }

        // Track failures to report them at the end
        let mut failures = Vec::new();

        // Get the window object
        let window = web_sys::window().ok_or_else(|| {
            Error::Dispatch("Could not get window object in WASM environment".to_string())
        })?;

        // Send the message to each recipient
        for recipient in &recipient_dids {
            let endpoint = self.get_endpoint_url(recipient);
            log::info!(
                "Sending message to {} via HTTP at {} (WASM)",
                recipient,
                endpoint
            );

            // Retry logic
            let mut attempt = 0;
            let mut success = false;
            let mut last_error = None;

            while attempt < self.max_retries && !success {
                attempt += 1;

                // Exponential backoff for retries
                if attempt > 1 {
                    let backoff_ms = 100 * (2_u64.pow(attempt - 1));
                    // In WASM, we need to use a Promise-based sleep
                    let promise = js_sys::Promise::new(&mut |resolve, _| {
                        let closure = Closure::once_into_js(move || {
                            resolve.call0(&JsValue::NULL).unwrap();
                        });
                        window
                            .set_timeout_with_callback_and_timeout_and_arguments_0(
                                closure.as_ref().unchecked_ref(),
                                backoff_ms as i32,
                            )
                            .unwrap();
                    });

                    let _ = JsFuture::from(promise).await;
                }

                // Initialize a new Request
                let mut opts = RequestInit::new();
                opts.method("POST");
                opts.mode(RequestMode::Cors);
                opts.body(Some(&JsValue::from_str(&packed_message)));

                let request = match Request::new_with_str_and_init(&endpoint, &opts) {
                    Ok(req) => req,
                    Err(err) => {
                        let err_msg = format!("Failed to create request: {:?}", err);
                        log::warn!("{}", err_msg);
                        last_error = Some(err_msg);
                        continue;
                    }
                };

                // Set headers
                if let Err(err) = request
                    .headers()
                    .set("Content-Type", "application/didcomm-message+json")
                {
                    let err_msg = format!("Failed to set headers: {:?}", err);
                    log::warn!("{}", err_msg);
                    last_error = Some(err_msg);
                    continue;
                }

                // Perform the fetch
                let resp_promise = window.fetch_with_request(&request);
                let resp_jsvalue = match JsFuture::from(resp_promise).await {
                    Ok(val) => val,
                    Err(err) => {
                        let err_msg = format!("Fetch error: {:?}", err);
                        log::warn!(
                            "Failed to send message to {} (attempt {}/{}): {}",
                            recipient,
                            attempt,
                            self.max_retries,
                            err_msg
                        );
                        last_error = Some(err_msg);
                        continue;
                    }
                };

                // Convert the response to a Response object
                let response: Response = match resp_jsvalue.dyn_into() {
                    Ok(resp) => resp,
                    Err(err) => {
                        let err_msg = format!("Failed to convert response: {:?}", err);
                        log::warn!("{}", err_msg);
                        last_error = Some(err_msg);
                        continue;
                    }
                };

                // Check the status
                if response.ok() {
                    log::debug!("Successfully sent message to {}", recipient);
                    success = true;
                } else {
                    let status = response.status();

                    // Try to get the response body as text
                    let body_promise = response.text();
                    let body = match JsFuture::from(body_promise).await {
                        Ok(text_jsval) => text_jsval.as_string().unwrap_or_default(),
                        Err(_) => String::from("[Could not read response body]"),
                    };

                    let err_msg = format!("HTTP error: {} - {}", status, body);
                    log::warn!(
                        "Failed to send message to {} (attempt {}/{}): {}",
                        recipient,
                        attempt,
                        self.max_retries,
                        err_msg
                    );
                    last_error = Some(err_msg);

                    // Don't retry certain status codes
                    if status == 404 || status == 400 {
                        break; // Don't retry not found or bad request
                    }
                }
            }

            if !success {
                failures.push((
                    recipient.clone(),
                    last_error.unwrap_or_else(|| "Unknown error".to_string()),
                ));
            }
        }

        // Report failures if any
        if !failures.is_empty() {
            let failure_messages = failures
                .iter()
                .map(|(did, err)| format!("{}: {}", did, err))
                .collect::<Vec<_>>()
                .join("; ");

            return Err(Error::Dispatch(format!(
                "Failed to send message to some recipients: {}",
                failure_messages
            )));
        }

        Ok(())
    }
}

// Fallback implementation for WASM environments without web-sys feature
#[cfg(all(target_arch = "wasm32", not(feature = "wasm")))]
#[async_trait(?Send)]
impl PlainMessageSender for HttpPlainMessageSender {
    async fn send(&self, packed_message: String, recipient_dids: Vec<String>) -> Result<()> {
        // This is a fallback implementation when web-sys is not available in WASM
        for recipient in &recipient_dids {
            let endpoint = self.get_endpoint_url(recipient);
            log::info!(
                "Would send message to {} via HTTP at {} (WASM without web-sys)",
                recipient,
                endpoint
            );
            log::debug!("PlainMessage content: {}", packed_message);
        }

        log::warn!("HTTP sender is running in WASM without the web-sys feature enabled. No actual HTTP requests will be made.");
        Ok(())
    }
}

/// HTTP message sender with delivery tracking
///
/// This sender extends HttpPlainMessageSender with delivery tracking capabilities,
/// recording delivery attempts, success/failure status, HTTP status codes, and retry counts
/// in the database for monitoring and automatic retry processing.
///
/// # Features
/// - All capabilities of HttpPlainMessageSender
/// - Delivery record creation before sending
/// - Status updates after delivery attempts
/// - Retry count tracking
/// - HTTP status code recording
/// - Error message logging
///
/// # Usage
///
/// ```no_run
/// # use std::sync::Arc;
/// # use tap_node::{HttpPlainMessageSenderWithTracking, PlainMessageSender, Storage};
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// // Create storage instance
/// let storage = Arc::new(Storage::new(None).await?);
///
/// // Create sender with tracking
/// let sender = HttpPlainMessageSenderWithTracking::new(
///     "https://recipient.example.com".to_string(),
///     storage
/// );
///
/// // Send message - delivery will be tracked automatically
/// sender.send("packed_message".to_string(), vec!["did:example:recipient".to_string()]).await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct HttpPlainMessageSenderWithTracking {
    /// The underlying HTTP sender
    http_sender: HttpPlainMessageSender,
    /// Storage for tracking deliveries
    storage: Arc<Storage>,
}

impl HttpPlainMessageSenderWithTracking {
    /// Create a new HttpPlainMessageSenderWithTracking
    pub fn new(base_url: String, storage: Arc<Storage>) -> Self {
        Self {
            http_sender: HttpPlainMessageSender::new(base_url),
            storage,
        }
    }

    /// Create a new HttpPlainMessageSenderWithTracking with custom options
    pub fn with_options(
        base_url: String,
        timeout_ms: u64,
        max_retries: u32,
        storage: Arc<Storage>,
    ) -> Self {
        Self {
            http_sender: HttpPlainMessageSender::with_options(base_url, timeout_ms, max_retries),
            storage,
        }
    }
}

#[async_trait]
impl PlainMessageSender for HttpPlainMessageSenderWithTracking {
    async fn send(&self, packed_message: String, recipient_dids: Vec<String>) -> Result<()> {
        if recipient_dids.is_empty() {
            return Err(Error::Dispatch("No recipients specified".to_string()));
        }

        // Extract message ID from packed message for tracking
        // This is a simplified approach - in production you might want a more robust way to get the message ID
        let message_id = format!("msg_{}", uuid::Uuid::new_v4());

        // Create delivery records for each recipient before attempting delivery
        let mut delivery_ids = Vec::new();
        for recipient in &recipient_dids {
            let delivery_url = Some(self.http_sender.get_endpoint_url(recipient));
            match self
                .storage
                .create_delivery(
                    &message_id,
                    &packed_message,
                    recipient,
                    delivery_url.as_deref(),
                    DeliveryType::Https,
                )
                .await
            {
                Ok(delivery_id) => {
                    delivery_ids.push((recipient.clone(), delivery_id));
                    log::debug!(
                        "Created delivery record {} for message {} to {}",
                        delivery_id,
                        message_id,
                        recipient
                    );
                }
                Err(e) => {
                    log::error!("Failed to create delivery record for {}: {}", recipient, e);
                    // Continue with delivery attempt even if we can't track it
                    delivery_ids.push((recipient.clone(), -1)); // Use -1 to indicate no tracking
                }
            }
        }

        // Now attempt delivery using the underlying HTTP sender
        let delivery_result = self
            .http_sender
            .send(packed_message, recipient_dids.clone())
            .await;

        // Update delivery records based on the result
        for (_recipient, delivery_id) in delivery_ids {
            if delivery_id == -1 {
                continue; // Skip if we couldn't create the delivery record
            }

            match &delivery_result {
                Ok(_) => {
                    // Delivery successful
                    if let Err(e) = self
                        .storage
                        .update_delivery_status(
                            delivery_id,
                            DeliveryStatus::Success,
                            Some(200), // Assume 200 for successful delivery
                            None,
                        )
                        .await
                    {
                        log::error!(
                            "Failed to update delivery record {} to success: {}",
                            delivery_id,
                            e
                        );
                    } else {
                        log::debug!("Updated delivery record {} to success", delivery_id);
                    }
                }
                Err(e) => {
                    // Delivery failed - extract HTTP status code if possible
                    let error_msg = e.to_string();
                    let http_status_code = if error_msg.contains("HTTP error: ") {
                        // Try to extract status code from error message
                        error_msg
                            .split("HTTP error: ")
                            .nth(1)
                            .and_then(|s| s.split(' ').next())
                            .and_then(|s| s.parse::<i32>().ok())
                    } else {
                        None
                    };

                    if let Err(e) = self
                        .storage
                        .update_delivery_status(
                            delivery_id,
                            DeliveryStatus::Failed,
                            http_status_code,
                            Some(&error_msg),
                        )
                        .await
                    {
                        log::error!(
                            "Failed to update delivery record {} to failed: {}",
                            delivery_id,
                            e
                        );
                    } else {
                        log::debug!(
                            "Updated delivery record {} to failed with error: {}",
                            delivery_id,
                            error_msg
                        );
                    }

                    // Increment retry count for future retry processing
                    if let Err(e) = self
                        .storage
                        .increment_delivery_retry_count(delivery_id)
                        .await
                    {
                        log::error!(
                            "Failed to increment retry count for delivery record {}: {}",
                            delivery_id,
                            e
                        );
                    }
                }
            }
        }

        delivery_result
    }
}