runar_node 0.1.0

Runar Node implementation
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
// Services Module
//
// INTENTION:
// This module defines the core service architecture components, interfaces, and types
// that form the foundation of the service-oriented architecture. It establishes
// the contracts between services, the node, and clients that use them.
//
// ARCHITECTURAL PRINCIPLES:
// 1. Service Isolation - Services are self-contained with clear boundaries
// 2. Request-Response Pattern - All service interactions follow a consistent
//    request-response pattern for predictability and simplicity
// 3. Contextual Logging - All operations include context for proper tracing
// 4. Network Isolation - Services operate within specific network boundaries
// 5. Event-Driven Communication - Services can publish and subscribe to events
//
// This module is the cornerstone of the system's service architecture, defining
// how services are structured, discovered, and interacted with.

// Module declarations
pub mod abstract_service;
pub mod event_context;
pub mod keys_service;
pub mod load_balancing;
pub mod registry_service;
pub mod remote_service;
pub mod request_context;
pub mod service_registry;

// Import necessary components
use crate::node::Node; // Added for concrete type Node
use crate::routing::TopicPath;
use crate::services::service_registry::{EventHandler, RemoteEventHandler};
use anyhow::{anyhow, Result};
use runar_common::logging::{Component, Logger, LoggingContext};
use runar_macros_common::{log_debug, log_error, log_info, log_warn};
use runar_schemas::{ActionMetadata, FieldSchema};
use runar_serializer::arc_value::AsArcValue;
use runar_serializer::ArcValue;
use std::collections::HashMap;
use std::fmt::Debug;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

// Import types from submodules
use crate::services::abstract_service::ServiceState;
use crate::services::remote_service::RemoteService;
use runar_schemas::ServiceMetadata;

// Re-export the context types from their dedicated modules
pub use crate::services::event_context::EventContext;
pub use crate::services::request_context::RequestContext;

/// Handler for a service action
///
/// INTENTION: Define the signature for a function that handles a service action.
/// This provides a consistent interface for all action handlers and enables
/// them to be stored, passed around, and invoked uniformly.
pub type ActionHandler =
    Arc<dyn Fn(Option<ArcValue>, RequestContext) -> ServiceFuture + Send + Sync>;

/// Type for action registration function
pub type ActionRegistrar = Arc<
    dyn Fn(
            &TopicPath,
            ActionHandler,
            Option<ActionMetadata>,
        ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>
        + Send
        + Sync,
>;

/// Context for service lifecycle management
///
/// INTENTION: Provide services with the context needed for lifecycle operations
/// such as initialization and shutdown. Includes access to the node for
/// registering action handlers, subscribing to events, and other operations.
#[derive(Clone)]
pub struct LifecycleContext {
    /// Network ID for the context
    pub network_id: String,
    /// Service path - identifies the service within the network
    pub service_path: String,
    /// Optional configuration data
    pub config: Option<ArcValue>,
    /// Logger instance with service context
    pub logger: Arc<Logger>,
    /// Node delegate for node operations
    node_delegate: Arc<Node>,
    // Removed serializer registry (no longer needed with redesigned serializer)
}

impl LifecycleContext {
    /// Create a new LifecycleContext with a topic path and logger
    ///
    /// This is the primary constructor that takes the minimum required parameters.
    pub fn new(topic_path: &TopicPath, node_delegate: Arc<Node>, logger: Arc<Logger>) -> Self {
        Self {
            network_id: topic_path.network_id(),
            service_path: topic_path.service_path(),
            config: None,
            logger,
            node_delegate,
            // Removed serializer registry (no longer needed with redesigned serializer)
        }
    }

    /// Add configuration to a LifecycleContext
    ///
    /// Use builder-style methods instead of specialized constructors.
    pub fn with_config(mut self, config: ArcValue) -> Self {
        self.config = Some(config);
        self
    }

    /// Helper method to log debug level message
    pub fn debug(&self, message: impl Into<String>) {
        log_debug!(self.logger, "{}", message.into());
    }

    /// Helper method to log info level message
    pub fn info(&self, message: impl Into<String>) {
        log_info!(self.logger, "{}", message.into());
    }

    /// Helper method to log warning level message
    pub fn warn(&self, message: impl Into<String>) {
        log_warn!(self.logger, "{}", message.into());
    }

    /// Helper method to log error level message
    pub fn error(&self, message: impl Into<String>) {
        log_error!(self.logger, "{}", message.into());
    }

    pub async fn remote_request<P>(
        &self,
        topic: impl AsRef<str>,
        payload: Option<P>,
    ) -> Result<ArcValue>
    where
        P: AsArcValue + Send + Sync,
    {
        let topic_string = topic.as_ref();
        let full_topic = if topic_string.contains(':') {
            topic_string.to_string()
        } else if topic_string.contains('/') {
            // Treat as service/action path
            format!("{0}:{1}", self.network_id, topic_string)
        } else {
            // Treat as action under current service
            format!(
                "{0}:{1}/{2}",
                self.network_id, self.service_path, topic_string
            )
        };

        self.logger
            .debug(format!("Making request to processed path: {full_topic}"));

        self.node_delegate
            .remote_request::<P>(&full_topic, payload)
            .await
    }

    /// Make a service request from the lifecycle context.
    ///
    /// INTENTION: Allow services during their lifecycle (e.g., init, shutdown)
    /// to make requests to other services or their own actions.
    ///
    /// Handles different path formats:
    /// - Full path with network ID: "network:service/action" (used as is)
    /// - Path with service: "service/action" (current network ID added)
    /// - Simple action: "action" (current network ID and service path added - calls own service)
    pub async fn request<P>(&self, topic: impl AsRef<str>, payload: Option<P>) -> Result<ArcValue>
    where
        P: AsArcValue + Send + Sync,
    {
        let topic_string = topic.as_ref();
        let full_topic = if topic_string.contains(':') {
            topic_string.to_string()
        } else if topic_string.contains('/') {
            format!("{0}:{1}", self.network_id, topic_string)
        } else {
            format!(
                "{0}:{1}/{2}",
                self.network_id, self.service_path, topic_string
            )
        };

        self.logger.debug(format!(
            "LifecycleContext making request to processed path: {full_topic}"
        ));
        self.node_delegate.request::<P>(&full_topic, payload).await
    }

    /// Publish an event from the lifecycle context.
    ///
    /// INTENTION: Allow services during their lifecycle to publish events.
    ///
    /// Handles different topic formats:
    /// - Full topic with network ID: "network:service/topic" (used as is)
    /// - Topic with service: "service/topic" (current network ID added)
    /// - Simple topic: "topic" (current network ID and service path added)
    pub async fn publish(&self, topic: &str, data: Option<ArcValue>) -> Result<()> {
        let full_topic = if topic.contains(':') {
            topic.to_string()
        } else if topic.contains('/') {
            format!("{0}:{1}", self.network_id, topic)
        } else {
            format!("{0}:{1}/{2}", self.network_id, self.service_path, topic)
        };

        self.logger.debug(format!(
            "LifecycleContext publishing to processed topic: {full_topic}"
        ));
        self.node_delegate.publish(&full_topic, data).await
    }

    /// Publish an event with options (e.g., retain_for for include_past support)
    pub async fn publish_with_options(
        &self,
        topic: impl AsRef<str>,
        data: Option<ArcValue>,
        options: PublishOptions,
    ) -> Result<()> {
        let topic_string = topic.as_ref();
        let full_topic = if topic_string.contains(':') {
            topic_string.to_string()
        } else if topic_string.contains('/') {
            format!("{0}:{1}", self.network_id, topic_string)
        } else {
            format!(
                "{0}:{1}/{2}",
                self.network_id, self.service_path, topic_string
            )
        };

        self.logger.debug(format!(
            "LifecycleContext publishing (with options) to processed topic: {full_topic}"
        ));
        self.node_delegate
            .publish_with_options(&full_topic, data, options)
            .await
    }

    /// Wait for an event to occur with a timeout
    ///
    /// INTENTION: Allow services during their lifecycle to wait for specific events
    /// to occur before proceeding with their logic.
    ///
    /// Returns Ok(Option<ArcValue>) with the event payload if event occurs within timeout,
    /// or Err with timeout message if no event occurs.
    pub async fn on(
        &self,
        topic: impl AsRef<str>,
        options: Option<OnOptions>,
    ) -> Result<Option<ArcValue>> {
        let topic_string = topic.as_ref();
        let full_topic = if topic_string.contains(':') {
            topic_string.to_string()
        } else if topic_string.contains('/') {
            format!("{0}:{1}", self.network_id, topic_string)
        } else {
            format!(
                "{0}:{1}/{2}",
                self.network_id, self.service_path, topic_string
            )
        };
        let handle = self.node_delegate.on(&full_topic, options);
        let inner = handle.await.map_err(|e| anyhow::anyhow!(e))?;
        inner
    }

    // on_with_options removed; use on(topic, timeout, include_past) unified API instead

    /// Register an action handler
    ///
    /// INTENTION: Allow a service to register a handler function for a specific action.
    /// This is the main way for services to expose functionality to the Node.
    pub async fn register_action(
        &self,
        action_name: impl Into<String>,
        handler: ActionHandler,
    ) -> Result<()> {
        let delegate = &self.node_delegate;
        let action_name_string = action_name.into();

        // Create a topic path for this action
        let action_path = format!(
            "{service_path}/{action_name}",
            service_path = self.service_path,
            action_name = action_name_string
        );

        // Debug logs for action registration
        self.logger.debug(format!(
            "register_action name={}, service_path={}, action_path={}",
            action_name_string, self.service_path, action_path
        ));

        let topic_path: TopicPath = TopicPath::new(&action_path, &self.network_id)
            .map_err(|e| anyhow!("Invalid action path: {e}"))?;

        // More detailed debug after TopicPath creation
        self.logger
            .debug(format!("register_action: created TopicPath {topic_path}"));

        let metadata = ActionMetadata {
            name: action_name_string.clone(),
            description: format!(
                "Action {} for service {}",
                action_name_string, self.service_path
            ),
            input_schema: None,
            output_schema: None,
        };

        // Call the delegate to register the action handler
        delegate
            .register_action_handler(topic_path, handler, Some(metadata))
            .await
    }

    /// Register an action handler with metadata
    ///
    /// INTENTION: Allow a service to register a handler function for an action,
    /// along with descriptive metadata. This enables documentation and discovery
    /// of the action's purpose and parameters.
    pub async fn register_action_with_options(
        &self,
        action_name: impl Into<String>,
        handler: ActionHandler,
        options: ActionRegistrationOptions,
    ) -> Result<()> {
        let action_name_string = action_name.into();

        // Create action metadata from the options
        let metadata = ActionMetadata {
            name: action_name_string.clone(),
            description: options.description.unwrap_or_default(),
            input_schema: options.input_schema,
            output_schema: options.output_schema,
        };

        // Get the node delegate
        let delegate = &self.node_delegate;

        // Create a topic path for this action
        let action_path = format!(
            "{service_path}/{action_name}",
            service_path = self.service_path,
            action_name = action_name_string
        );
        let topic_path = TopicPath::new(&action_path, &self.network_id)
            .map_err(|e| anyhow!("Invalid action path: {e}"))?;

        // Register the action with the provided options
        delegate
            .register_action_handler(topic_path, handler, Some(metadata))
            .await
    }

    /// Subscribe to an event with specific registration options.
    ///
    /// INTENTION: Allow a service to subscribe to an event topic and provide
    /// detailed metadata about the event for discovery and documentation purposes.
    pub async fn subscribe(
        &self,
        topic: &str,
        callback: EventHandler,
        options: Option<EventRegistrationOptions>,
    ) -> Result<String> {
        let topic_string = topic.to_string();
        let full_topic = if topic_string.contains(':') {
            topic_string
        } else if topic_string.contains('/') {
            format!("{0}:{1}", self.network_id, topic_string)
        } else {
            format!(
                "{0}:{1}/{2}",
                self.network_id, self.service_path, topic_string
            )
        };

        let delegate = &self.node_delegate;
        delegate.subscribe(&full_topic, callback, options).await
    }

    // subscribe without options removed to unify API

    /// Unsubscribe from a subscription by ID
    pub async fn unsubscribe(&self, subscription_id: &str) -> Result<()> {
        self.node_delegate.unsubscribe(subscription_id).await
    }
}

impl LoggingContext for LifecycleContext {
    fn component(&self) -> Component {
        Component::Service
    }

    fn service_path(&self) -> Option<&str> {
        Some(&self.service_path)
    }

    fn logger(&self) -> &Logger {
        &self.logger
    }
}

/// Service request for an action on a specific service
///
/// INTENTION: Represent a request to perform an action on a service.
/// Includes the destination, requested action, and input data.
///
/// ARCHITECTURAL PRINCIPLE:
/// The ServiceRequest should be self-contained with all routing and
/// context information needed to process a request from start to finish.
pub struct ServiceRequest {
    /// Topic path for the service and action
    pub topic_path: TopicPath,
    /// Data for the request
    pub data: ArcValue,
    /// Request context
    pub context: Arc<RequestContext>,
}

impl ServiceRequest {
    /// Create a new service request
    ///
    /// INTENTION: Create a service request using the service path and action name.
    /// This method will construct the appropriate TopicPath and initialize the request.
    pub fn new(
        service_path: impl AsRef<str>,
        action_or_event: impl AsRef<str>,
        data: ArcValue,
        context: Arc<RequestContext>,
    ) -> Self {
        // Create a path string combining service path and action
        let service_path_string = service_path.as_ref();
        let action_or_event_string = action_or_event.as_ref();
        let path_string = format!("{service_path_string}/{action_or_event_string}");

        // Parse the path using the context's network_id method
        let topic_path =
            TopicPath::new(&path_string, &context.network_id()).expect("Invalid path format");

        Self {
            topic_path,
            data,
            context,
        }
    }

    /// Create a new service request with a TopicPath
    ///
    /// INTENTION: Create a service request using an existing TopicPath object.
    /// This is useful when the TopicPath has already been constructed and validated.
    pub fn new_with_topic_path(
        topic_path: TopicPath,
        data: ArcValue,
        context: Arc<RequestContext>,
    ) -> Self {
        Self {
            topic_path,
            data,
            context,
        }
    }

    /// Create a new service request with optional data
    ///
    /// INTENTION: Create a service request where the data parameter is optional.
    /// If no data is provided, ValueType::Null will be used.
    pub fn new_with_optional(
        service_path: impl AsRef<str>,
        action_or_event: impl AsRef<str>,
        data: Option<ArcValue>,
        context: Arc<RequestContext>,
    ) -> Self {
        // Create a TopicPath from the service path and action
        let service_path_string = service_path.as_ref();
        let action_or_event_string = action_or_event.as_ref();
        let path_string = format!("{service_path_string}/{action_or_event_string}");

        // Parse the path using the context's network_id method
        let topic_path =
            TopicPath::new(&path_string, &context.network_id()).expect("Invalid path format");

        Self {
            topic_path,
            data: data.unwrap_or_else(ArcValue::null),
            context,
        }
    }

    /// Get the service path from the topic path
    ///
    /// INTENTION: Extract the service path component from the topic path.
    /// This is useful for service identification and routing.
    pub fn path(&self) -> String {
        self.topic_path.service_path()
    }

    /// Get the action or event name from the topic path
    ///
    /// INTENTION: Extract the action or event name from the topic path.
    /// This identifies what operation is being requested.
    pub fn action_or_event(&self) -> String {
        // Get the action path and extract the last part which is the action name
        let action_path = self.topic_path.action_path();

        // If action_path contains a slash, take the part after the last slash
        if let Some(idx) = action_path.rfind('/') {
            action_path[idx + 1..].to_string()
        } else {
            // If there's no slash, it's just the action name itself
            action_path
        }
    }
}

// /// Response from a service handler
// #[derive(Debug, Clone)]
// pub struct ServiceResponse {
//     /// HTTP-like status code
//     pub status: u32,
//     /// Response data if any (immutable)
//     pub data: Option<ArcValue>,
//     /// Error message if any (immutable)
//     pub error: Option<String>,
// }

// impl ServiceResponse {
//     /// Create a new successful response with the given data
//     pub fn ok(data: ArcValue) -> Self {
//         Self {
//             status: 200,
//             data: Some(data),
//             error: None,
//         }
//     }

//     /// Create a new successful response without data
//     pub fn ok_empty() -> Self {
//         Self {
//             status: 200,
//             data: None,
//             error: None,
//         }
//     }

//     /// Create a new error response with the given message
//     pub fn error(status: i32, message: impl Into<String>) -> Self {
//         Self {
//             status: status as u32,
//             data: None,
//             error: Some(message.into()),
//         }
//     }

//     /// Create a standard bad request error response
//     pub fn bad_request(message: impl Into<String>) -> Self {
//         Self::error(400, message)
//     }

//     /// Create a standard not found error response
//     pub fn not_found(message: impl Into<String>) -> Self {
//         Self::error(404, message)
//     }

//     /// Create a standard internal server error response
//     pub fn internal_error(message: impl Into<String>) -> Self {
//         Self::error(500, message)
//     }

//     /// Create a standard method not allowed error response
//     pub fn method_not_allowed(message: impl Into<String>) -> Self {
//         Self::error(405, message)
//     }

//     /// Check if the response is successful
//     pub fn is_success(&self) -> bool {
//         self.status >= 200 && self.status < 300
//     }

//     /// Check if the response is an error
//     pub fn is_error(&self) -> bool {
//         !self.is_success()
//     }
// }

// Removed SubscriptionOptions in favor of EventRegistrationOptions to avoid redundancy

/// Options for publishing an event
///
/// INTENTION: Provide configuration options for event publishing,
/// allowing control over delivery scope, guarantees, and retention.
#[derive(Debug, Clone, Default)]
pub struct PublishOptions {
    /// Whether this event should be broadcast to all nodes in the network
    pub broadcast: bool,

    /// Whether delivery should be guaranteed (at-least-once semantics)
    pub guaranteed_delivery: bool,

    /// How long the event should be retained locally for late subscribers.
    /// None means no retention.
    pub retain_for: Option<std::time::Duration>,

    /// Target a specific node or service instead of all subscribers
    pub target: Option<String>,
}

impl PublishOptions {
    pub fn local_only() -> Self {
        Self {
            broadcast: false,
            guaranteed_delivery: false,
            retain_for: None,
            target: None,
        }
    }

    pub fn with_retain_for(mut self, duration: std::time::Duration) -> Self {
        self.retain_for = Some(duration);
        self
    }
}

/// Options for registering an action handler
///
/// INTENTION: Provide a way to specify metadata about an action when registering it,
/// reducing the need for services to define complete metadata upfront.
// #[derive(Debug, Clone, Default)] // This line was redundant and removed
/// Options for registering an event subscription with metadata.
#[derive(Clone, Debug, Default)]
pub struct EventRegistrationOptions {
    /// If set, deliver the newest retained event that occurred within this lookback window
    /// immediately upon subscription (in addition to future events). Local-only.
    pub include_past: Option<std::time::Duration>,
}

/// Options for one-shot event waits (on)
#[derive(Clone, Debug)]
pub struct OnOptions {
    pub timeout: std::time::Duration,
    pub include_past: Option<std::time::Duration>,
}

pub struct ActionRegistrationOptions {
    /// Description of what the action does
    pub description: Option<String>,
    /// Parameter schema for validation and documentation
    pub input_schema: Option<FieldSchema>,
    /// Return value schema for documentation
    pub output_schema: Option<FieldSchema>,
}

/// Interface for handling service requests
///
/// INTENTION: Define a consistent interface for handling node requests. This trait
/// is implemented by components that need to handle service requests, specifically
/// the Node component itself which should be responsible for routing requests to
/// appropriate services.
///
/// ARCHITECTURAL PRINCIPLE:
/// Request handling should be centralized in the Node component, with a clear
/// interface that allows for proper routing, logging, and error handling. This
/// separates the responsibility of request handling from service management.
#[async_trait::async_trait]
pub trait NodeRequestHandler: Send + Sync {
    /// Process a service request
    async fn request(&self, path: String, params: Option<ArcValue>) -> Result<ArcValue>;

    /// Publish an event to a topic
    async fn publish(&self, topic: String, data: Option<ArcValue>) -> Result<()>;

    /// Subscribe to a topic
    ///
    /// INTENTION: Register a callback that will be invoked when events are published
    /// to the specified topic. The callback receives both an EventContext and the event data.
    async fn subscribe(
        &self,
        topic: String,
        callback: Box<
            dyn Fn(Arc<EventContext>, ArcValue) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>
                + Send
                + Sync,
        >,
        options: Option<EventRegistrationOptions>,
    ) -> Result<String>;

    /// Unsubscribe from a topic
    async fn unsubscribe(&self, topic: String, subscription_id: Option<&str>) -> Result<()>;
}

/// Helper trait to enable easy logging from an Arc<RequestContext>
pub trait ArcContextLogging {
    /// Log a debug level message
    fn debug(&self, message: impl Into<String>);

    /// Log an info level message
    fn info(&self, message: impl Into<String>);

    /// Log a warning level message
    fn warn(&self, message: impl Into<String>);

    /// Log an error level message
    fn error(&self, message: impl Into<String>);
}

/// Implement logging methods for Arc<RequestContext>
impl ArcContextLogging for Arc<RequestContext> {
    fn debug(&self, message: impl Into<String>) {
        self.logger.debug(message);
    }

    fn info(&self, message: impl Into<String>) {
        self.logger.info(message);
    }

    fn warn(&self, message: impl Into<String>) {
        self.logger.warn(message);
    }

    fn error(&self, message: impl Into<String>) {
        self.logger.error(message);
    }
}

/// Type alias for a boxed future returning a Result with ServiceResponse
///
/// INTENTION: Provide a consistent return type for asynchronous service methods,
/// simplifying method signatures and ensuring uniformity across the codebase.
pub type ServiceFuture = Pin<Box<dyn Future<Output = Result<ArcValue>> + Send>>;

/// Event Dispatcher trait
///
/// INTENTION: Define a consistent interface for publishing events from services.
/// This trait is implemented by components that need to dispatch events,
/// specifically the Node component which should be responsible for publishing
/// events to subscribers.
///
/// ARCHITECTURAL PRINCIPLE:
/// Event publishing should be centralized in the Node component, with a clear
/// interface that allows for proper topic-based routing and delivery to subscribers.
/// This separates the responsibility of event publishing from service management.
#[async_trait::async_trait]
pub trait EventDispatcher: Send + Sync {
    /// Publish an event to subscribers
    ///
    /// INTENTION: Distribute an event to all subscribers of the specified topic.
    /// Implementations should handle subscriber lookups and asynchronous delivery.
    // (Removed leftover code block and delimiters due to doctest failure. Intention and architectural documentation preserved.)
    async fn publish(
        &self,
        topic: &str,
        event: &str,
        data: Option<ArcValue>,
        network_id: &str,
    ) -> Result<()>;
}

/// Unified Node Delegate trait
///
/// INTENTION: Provide a single interface for all Node operations that services
/// need to interact with, combining both request handling and event dispatching.
///
/// ARCHITECTURAL PRINCIPLE:
/// A single unified interface simplifies service interactions with the Node,
/// reducing code duplication and complexity while maintaining clear architectural
/// boundaries. This follows the Interface Segregation Principle by providing
/// a focused, cohesive interface for services.
#[async_trait::async_trait]
pub trait NodeDelegate: Send + Sync {
    /// Process a service request
    async fn request<P>(&self, path: &str, payload: Option<P>) -> Result<ArcValue>
    where
        P: AsArcValue + Send + Sync;

    /// Simplified publish for common cases
    async fn publish(&self, topic: &str, data: Option<ArcValue>) -> Result<()>;

    /// Subscribe to a topic
    async fn subscribe(
        &self,
        topic: &str,
        callback: EventHandler,
        options: Option<EventRegistrationOptions>, // None means default behavior
    ) -> Result<String>;

    /// Unsubscribe from a topic
    async fn unsubscribe(&self, subscription_id: &str) -> Result<()>;

    /// Register an action handler for a specific path
    ///
    /// INTENTION: Allow services to register handlers for actions through the NodeDelegate.
    async fn register_action_handler(
        &self,
        topic_path: TopicPath,
        handler: ActionHandler,
        metadata: Option<ActionMetadata>,
    ) -> Result<()>;

    /// Wait for an event to occur with a timeout
    ///
    /// INTENTION: Allow services to wait for specific events to occur
    /// before proceeding with their logic.
    ///
    /// Returns Ok(ArcValue) with the event payload if event occurs within timeout,
    /// or Err with timeout message if no event occurs.
    async fn on(&self, topic: &str, options: Option<OnOptions>) -> Result<Option<ArcValue>>;
}

/// Registry Delegate trait for keys service operations
///
/// INTENTION: Provide a dedicated interface for the Keys Service
/// to interact with the core keys management without creating circular references.
/// This follows the same pattern as NodeDelegate but provides only
/// the functionality needed by keys operations.
#[async_trait::async_trait]
pub trait KeysDelegate: Send + Sync {
    async fn ensure_symmetric_key(&self, key_name: &str) -> Result<ArcValue>;
}

/// Registry Delegate trait for registry service operations
///
/// INTENTION: Provide a dedicated interface for the Registry Service
/// to interact with the Node without creating circular references.
/// This follows the same pattern as NodeDelegate but provides only
/// the functionality needed by registry operations.
#[async_trait::async_trait]
pub trait RegistryDelegate: Send + Sync {
    async fn get_local_service_state(&self, service_path: &TopicPath) -> Option<ServiceState>;

    async fn get_remote_service_state(&self, service_path: &TopicPath) -> Option<ServiceState>;

    /// Get metadata for a specific service
    async fn get_service_metadata(&self, service_path: &TopicPath) -> Option<ServiceMetadata>;

    /// Get metadata for all registered services with an option to filter internal services
    ///
    /// INTENTION: Retrieve metadata for all registered services with the option
    /// to exclude internal services (those with paths starting with $)
    async fn get_all_service_metadata(
        &self,
        include_internal_services: bool,
    ) -> Result<HashMap<String, ServiceMetadata>>;

    /// Get metadata for all actions under a specific service path
    ///
    /// INTENTION: Retrieve metadata for all actions registered under a service path.
    /// This is useful for service discovery and introspection.
    async fn get_actions_metadata(&self, service_topic_path: &TopicPath) -> Vec<ActionMetadata>;

    /// Register a remote action handler
    ///
    /// INTENTION: Allow RemoteLifecycleContext to register remote action handlers
    /// through this delegate to avoid circular references.
    async fn register_remote_action_handler(
        &self,
        topic_path: &TopicPath,
        handler: ActionHandler,
    ) -> Result<()>;

    async fn remove_remote_action_handler(&self, topic_path: &TopicPath) -> Result<()>;

    async fn register_remote_event_handler(
        &self,
        topic_path: &TopicPath,
        handler: RemoteEventHandler,
    ) -> Result<String>;

    async fn remove_remote_event_handler(&self, topic_path: &TopicPath) -> Result<()>;

    /// Update service state only if the transition is valid
    ///
    /// INTENTION: Validate state transitions before updating service state.
    /// This ensures that services can only transition to valid states.
    async fn update_local_service_state_if_valid(
        &self,
        service_path: &TopicPath,
        new_state: ServiceState,
        current_state: ServiceState,
    ) -> Result<()>;

    // async fn update_remote_service_state(
    //     &self,
    //     service_path: &TopicPath,
    //     new_state: ServiceState,
    // ) -> Result<()>;

    /// Validate that a service can be paused
    ///
    /// INTENTION: Check if the service is in a state that allows pausing.
    /// Only services in Running state can be paused.
    async fn validate_pause_transition(&self, service_path: &TopicPath) -> Result<()>;

    /// Validate that a service can be resumed
    ///
    /// INTENTION: Check if the service is in a state that allows resuming.
    /// Only services in Paused state can be resumed.
    async fn validate_resume_transition(&self, service_path: &TopicPath) -> Result<()>;
}

/// Remote service lifecycle context
///
/// INTENTION: Provide remote services with the context needed for lifecycle operations
/// such as initialization, action registration, and shutdown. Similar to LifecycleContext
/// but with remote-specific methods.
pub struct RemoteLifecycleContext {
    /// Network ID for the context
    pub network_id: String,
    /// Service path - identifies the service within the network
    pub service_path: String,
    /// Optional configuration data
    pub config: Option<ArcValue>,
    /// Logger instance with service context
    pub logger: Arc<Logger>,
    /// Registry delegate for registry operations
    registry_delegate: Option<Arc<dyn RegistryDelegate + Send + Sync>>,
}

impl RemoteLifecycleContext {
    /// Create a new RemoteLifecycleContext with the given topic path and logger
    ///
    /// This is the primary constructor that takes the minimum required parameters.
    pub fn new(topic_path: &TopicPath, logger: Arc<Logger>) -> Self {
        Self {
            network_id: topic_path.network_id().to_string(),
            service_path: topic_path.service_path(),
            config: None,
            logger,
            registry_delegate: None,
        }
    }

    /// Add configuration to a RemoteLifecycleContext
    ///
    /// Use builder-style methods instead of specialized constructors.
    pub fn with_config(mut self, config: ArcValue) -> Self {
        self.config = Some(config);
        self
    }

    /// Add a RegistryDelegate to a RemoteLifecycleContext
    ///
    /// INTENTION: Provide access to registry operations during service lifecycle events,
    /// including action registration.
    pub fn with_registry_delegate(
        mut self,
        delegate: Arc<dyn RegistryDelegate + Send + Sync>,
    ) -> Self {
        self.registry_delegate = Some(delegate);
        self
    }

    /// Helper method to log debug level message
    pub fn debug(&self, message: impl Into<String>) {
        self.logger.debug(message);
    }

    /// Helper method to log info level message
    pub fn info(&self, message: impl Into<String>) {
        self.logger.info(message);
    }

    /// Helper method to log warning level message
    pub fn warn(&self, message: impl Into<String>) {
        self.logger.warn(message);
    }

    /// Helper method to log error level message
    pub fn error(&self, message: impl Into<String>) {
        self.logger.error(message);
    }

    pub async fn remove_remote_action_handler(&self, topic_path: &TopicPath) -> Result<()> {
        // Get the registry delegate
        let delegate = match &self.registry_delegate {
            Some(d) => d,
            None => return Err(anyhow!("No registry delegate available")),
        };

        // Call the delegate to remove the remote action handler
        delegate.remove_remote_action_handler(topic_path).await
    }

    /// Register a remote action handler
    ///
    /// INTENTION: Allow a remote service to register a handler function for a specific action.
    pub async fn register_remote_action_handler(
        &self,
        topic_path: &TopicPath,
        handler: ActionHandler,
    ) -> Result<()> {
        // Get the registry delegate
        let delegate = match &self.registry_delegate {
            Some(d) => d,
            None => return Err(anyhow!("No registry delegate available")),
        };

        // Call the delegate to register the remote action handler
        delegate
            .register_remote_action_handler(topic_path, handler)
            .await
    }
}

/// Service handler function type
/// Handler receives optional payload and context, returns a response
pub type ServiceHandler = Box<
    dyn Fn(
            Option<ArcValue>,
            Arc<RequestContext>,
        ) -> Pin<Box<dyn Future<Output = Option<ArcValue>> + Send>>
        + Send
        + Sync,
>;