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
// RequestContext Module
//
// INTENTION:
// This module provides the implementation of RequestContext, which encapsulates
// all contextual information needed to process service requests, including
// network identity, service path, and metadata.
//
// ARCHITECTURAL PRINCIPLE:
// Each request should have its own isolated context that moves with the
// request through the entire processing pipeline, ensuring proper tracing
// and consistent handling. The context avoids data duplication by
// deriving values from the TopicPath when needed.

use crate::node::Node; // Added for concrete type
use crate::routing::TopicPath;
use crate::services::service_registry::EventHandler;
use crate::services::NodeDelegate;
use crate::services::{EventRegistrationOptions, PublishOptions};
use anyhow::Result;
use runar_common::logging::{Component, Logger, LoggingContext};
use runar_macros_common::{log_debug, log_error, log_info, log_warn};
use runar_serializer::arc_value::AsArcValue;
use runar_serializer::ArcValue;

// AsArcValue trait and implementations moved to runar_common::types
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------

use std::{collections::HashMap, fmt, sync::Arc};

/// Context for handling service requests
///
/// INTENTION: Encapsulate all contextual information needed to process
/// a service request, including network identity, service path, and metadata.
/// This ensures consistent request processing and proper logging.
///
/// The RequestContext is immutable and is passed with each request to provide:
/// - Network isolation (via network_id derived from topic_path)
/// - Service targeting (via service_path derived from topic_path)
/// - Request metadata and contextual information
/// - Logging capabilities with consistent context
///
/// ARCHITECTURAL PRINCIPLE:
/// Each request should have its own isolated context that moves with the
/// request through the entire processing pipeline, ensuring proper tracing
/// and consistent handling.
pub struct RequestContext {
    /// Complete topic path for this request (optional) - includes service path and action
    pub topic_path: TopicPath,
    /// Metadata for this request - additional contextual information
    pub metadata: Option<ArcValue>,
    /// Logger for this context - pre-configured with the appropriate component and path
    pub logger: Arc<Logger>,
    /// Path parameters extracted from template matching
    pub path_params: HashMap<String, String>,

    pub user_profile_public_key: Vec<u8>,

    /// Node delegate for making requests or publishing events
    pub(crate) node_delegate: Arc<Node>,
}

// Manual implementation of Debug for RequestContext
impl fmt::Debug for RequestContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RequestContext")
            .field("network_id", &self.network_id())
            .field("service_path", &self.service_path())
            .field("topic_path", &self.topic_path)
            .field("metadata", &self.metadata)
            .field("logger", &"<Logger>") // Avoid trying to Debug the Logger
            .field("path_params", &self.path_params)
            .finish()
    }
}

// Manual implementation of Clone for RequestContext
impl Clone for RequestContext {
    fn clone(&self) -> Self {
        Self {
            topic_path: self.topic_path.clone(),
            metadata: self.metadata.clone(),
            logger: self.logger.clone(),
            path_params: self.path_params.clone(),
            node_delegate: self.node_delegate.clone(),
            user_profile_public_key: self.user_profile_public_key.clone(),
        }
    }
}

// Manual implementation of Default for RequestContext
impl Default for RequestContext {
    fn default() -> Self {
        panic!("RequestContext should not be created with default. Use new instead");
    }
}

/// Constructors follow the builder pattern principle:
/// - Prefer a single primary constructor with required parameters
/// - Use builder methods for optional parameters
/// - Avoid creating specialized constructors for every parameter combination
impl RequestContext {
    /// Create a new RequestContext with a TopicPath 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 {
        // Add action path to logger if available from topic_path
        let action_path = topic_path.action_path();
        let action_logger = if !action_path.is_empty() {
            // If there's an action path, add it to the logger
            Arc::new(logger.with_action_path(action_path))
        } else {
            logger
        };

        Self {
            topic_path: topic_path.clone(),
            metadata: None,
            logger: action_logger,
            node_delegate,
            path_params: HashMap::new(),
            user_profile_public_key: vec![],
        }
    }

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

    pub fn with_user_profile_public_key(mut self, user_profile_public_key: Vec<u8>) -> Self {
        self.user_profile_public_key = user_profile_public_key;
        self
    }

    /// Get the network ID from the topic path
    pub fn network_id(&self) -> String {
        self.topic_path.network_id()
    }

    /// Get the service path from the topic path
    pub fn service_path(&self) -> String {
        self.topic_path.service_path()
    }

    /// Helper method to log debug level message
    ///
    /// INTENTION: Provide a convenient way to log debug messages with the
    /// context's logger, without having to access the logger directly.
    pub fn debug(&self, message: impl Into<String>) {
        log_debug!(self.logger, "{}", message.into());
    }

    /// Helper method to log info level message
    ///
    /// INTENTION: Provide a convenient way to log info messages with the
    /// context's logger, without having to access the logger directly.
    pub fn info(&self, message: impl Into<String>) {
        log_info!(self.logger, "{}", message.into());
    }

    /// Helper method to log warning level message
    ///
    /// INTENTION: Provide a convenient way to log warning messages with the
    /// context's logger, without having to access the logger directly.
    pub fn warn(&self, message: impl Into<String>) {
        log_warn!(self.logger, "{}", message.into());
    }

    /// Helper method to log error level message
    ///
    /// INTENTION: Provide a convenient way to log error messages with the
    /// context's logger, without having to access the logger directly.
    pub fn error(&self, message: impl Into<String>) {
        log_error!(self.logger, "{}", message.into());
    }

    /// Publish an event
    ///
    /// INTENTION: Allow event handlers to publish their own events.
    /// This method provides a convenient way to publish events from within
    /// an event handler.
    ///
    /// Handles different path formats:
    /// - Full path with network ID: "network:service/topic" (used as is)
    /// - Path with service: "service/topic" (network ID added)
    /// - Simple topic: "topic" (both service path and network ID added)
    pub async fn publish(&self, topic: &str, data: Option<ArcValue>) -> Result<()> {
        let topic_string = topic.to_string();

        // Process the topic based on its format
        let full_topic = if topic_string.contains(':') {
            // Already has network ID, use as is
            topic_string
        } else if topic_string.contains('/') {
            // Path contains a '/', could already include service path. Check first segment.
            let first_seg = topic_string.split('/').next().unwrap_or("");
            if first_seg == self.topic_path.service_path() {
                // Already has service path, just prefix network id
                format!(
                    "{network_id}:{topic}",
                    network_id = self.topic_path.network_id(),
                    topic = topic_string,
                )
            } else {
                // Treat as relative to this service – prepend service path and network
                format!(
                    "{network_id}:{service}/{topic}",
                    network_id = self.topic_path.network_id(),
                    service = self.topic_path.service_path(),
                    topic = topic_string,
                )
            }
        } else {
            // Simple topic name - add service path and network ID
            format!(
                "{}:{}/{}",
                self.topic_path.network_id(),
                self.topic_path.service_path(),
                topic_string
            )
        };

        log_debug!(self.logger, "Publishing to processed topic: {full_topic}");
        self.node_delegate.publish(&full_topic, data).await
    }

    /// Publish an event with options (e.g., retain_for)
    pub async fn publish_with_options(
        &self,
        topic: &str,
        data: Option<ArcValue>,
        options: PublishOptions,
    ) -> Result<()> {
        let topic_string = topic.to_string();
        let full_topic = if topic_string.contains(':') {
            topic_string
        } else if topic_string.contains('/') {
            let first_seg = topic_string.split('/').next().unwrap_or("");
            if first_seg == self.topic_path.service_path() {
                format!(
                    "{network_id}:{topic}",
                    network_id = self.topic_path.network_id(),
                    topic = topic_string,
                )
            } else {
                format!(
                    "{network_id}:{service}/{topic}",
                    network_id = self.topic_path.network_id(),
                    service = self.topic_path.service_path(),
                    topic = topic_string,
                )
            }
        } else {
            format!(
                "{}:{}/{}",
                self.topic_path.network_id(),
                self.topic_path.service_path(),
                topic_string
            )
        };

        log_debug!(self.logger, "Publishing (with options) to: {full_topic}");
        self.node_delegate
            .publish_with_options(&full_topic, data, options)
            .await
    }

    pub async fn remote_request<P>(
        &self,
        path: impl AsRef<str>,
        payload: Option<P>,
    ) -> Result<ArcValue>
    where
        P: AsArcValue + Send + Sync,
    {
        let path_string = path.as_ref();

        // Process the path based on its format
        let full_path = if path_string.contains(':') {
            // Already has network ID, use as is
            path_string.to_string()
        } else if path_string.contains('/') {
            // Has service/action but no network ID
            format!(
                "{network_id}:{path_string}",
                network_id = self.topic_path.network_id()
            )
        } else {
            // Simple action name - add both service path and network ID
            format!(
                "{}:{}/{}",
                self.topic_path.network_id(),
                self.topic_path.service_path(),
                path_string
            )
        };

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

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

    /// Make a service request
    ///
    /// INTENTION: Allow event handlers to make requests to other services.
    /// This method provides a convenient way to call service actions from
    /// within an event handler.
    ///
    /// Handles different path formats:
    /// - Full path with network ID: "network:service/action" (used as is)
    /// - Path with service: "service/action" (network ID added)
    /// - Simple action: "action" (both service path and network ID added - calls own service)
    pub async fn request<P>(&self, path: &str, payload: Option<P>) -> Result<ArcValue>
    where
        P: AsArcValue + Send + Sync,
    {
        let path_string = path;

        // Process the path based on its format
        let full_path = if path_string.contains(':') {
            // Already has network ID, use as is
            path_string.to_string()
        } else if path_string.contains('/') {
            // Has service/action but no network ID
            format!(
                "{network_id}:{path_string}",
                network_id = self.topic_path.network_id()
            )
        } else {
            // Simple action name - add both service path and network ID
            format!(
                "{}:{}/{}",
                self.topic_path.network_id(),
                self.topic_path.service_path(),
                path_string
            )
        };

        log_debug!(self.logger, "Making request to processed path: {full_path}");

        self.node_delegate.request::<P>(&full_path, payload).await
    }

    /// Wait for an event to occur with a timeout
    ///
    /// INTENTION: Allow event handlers 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 Into<String>,
        options: Option<crate::services::OnOptions>,
    ) -> Result<Option<ArcValue>> {
        // Node::on returns a JoinHandle; await the handle, then unwrap the inner Result
        let handle = self.node_delegate.on(topic, options);
        handle.await.map_err(|e| anyhow::anyhow!(e))?
    }

    /// Subscribe to an event with options from a request handler
    pub async fn subscribe(
        &self,
        topic: impl Into<String>,
        callback: EventHandler,
        options: Option<EventRegistrationOptions>,
    ) -> Result<String> {
        let topic_string = topic.into();
        let full_topic = if topic_string.contains(':') {
            topic_string
        } else if topic_string.contains('/') {
            format!(
                "{network_id}:{topic}",
                network_id = self.topic_path.network_id(),
                topic = topic_string
            )
        } else {
            format!(
                "{}:{}/{}",
                self.topic_path.network_id(),
                self.topic_path.service_path(),
                topic_string
            )
        };

        self.node_delegate
            .subscribe(&full_topic, callback, options)
            .await
    }

    // Convenience subscribe without options removed to unify API
    // subscribe without options removed to unify API
}

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

    fn service_path(&self) -> Option<&str> {
        let path = self.topic_path.service_path();
        Some(Box::leak(path.into_boxed_str()))
    }

    fn action_path(&self) -> Option<&str> {
        let path = self.topic_path.action_path();
        Some(Box::leak(path.into_boxed_str()))
    }

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