Mountain/Air/AirServiceProvider.rs
1//! # AirServiceProvider
2//!
3//! High-level API surface for Air service methods.
4//!
5//! ## RESPONSIBILITIES
6//!
7//! - **Service Facade**: Provide convenient, high-level interface to Air daemon
8//! - **Authentication**: Manage user authentication and credentials
9//! - **Updates**: Check for and download application updates
10//! - **File Indexing**: Query Air's file search and indexing capabilities
11//! - **System Monitoring**: Retrieve system metrics and health data
12//! - **Graceful Degradation**: Handle Air unavailability with fallbacks
13//!
14//! ## ARCHITECTURAL ROLE
15//!
16//! AirServiceProvider acts as a facade over the raw `AirClient`, providing:
17//! - Simplified API for common operations
18//! - Automatic error handling and translation
19//! - Request ID generation for tracing
20//! - Connection state management
21//!
22//! ```text
23//! Application ──► AirServiceProvider ──► AirClient ──► gRPC ──► Air Daemon
24//! ```
25//!
26//! ### Dependencies
27//! - `AirClient`: Low-level gRPC client
28//! - `uuid`: For generating request identifiers
29//! - `CommonLibrary::Error::CommonError`: Error types
30//!
31//! ### Dependents
32//! - `Binary::Service::VineStart`: Initializes Air service
33//! - `MountainEnvironment`: Can delegate to Air when available
34//!
35//! ## IMPLEMENTATION
36//!
37//! This implementation provides a fully functional provider that wraps the
38//! AirClient type with automatic request ID generation and error handling.
39//!
40//! ## ERROR HANDLING
41//!
42//! All operations return `Result<T, CommonError>` with:
43//! - Translated gRPC errors to appropriate CommonError types
44//! - Request IDs included in logs for tracing
45//! - Graceful fallback to local operations when Air is unavailable
46//!
47//! ## PERFORMANCE
48//!
49//! - Request ID generation uses UUID v4 (cryptographically random)
50//! - Thread-safe operations via `Arc<AirClient>`
51//! - Non-blocking async operations via tokio
52//!
53//! ## VSCODE REFERENCE
54//!
55//! Patterns borrowed from VS Code:
56//! - `vs/platform/update/common/updateService.ts` - Update management
57//! - `vs/platform/authentication/common/authenticationService.ts` - Auth
58//! handling
59//! - `vs/platform/filesystem/common/filesystem.ts` - File indexing
60//!
61//! ## MODULE CONTENTS
62//!
63//! - [`AirServiceProvider`]: Main provider struct
64//! - [`generate_request_id`]: Helper function for UUID generation
65
66use std::{collections::HashMap, sync::Arc};
67
68use CommonLibrary::Error::CommonError::CommonError;
69
70#[allow(unused_imports)]
71use super::{
72 AirClient::DEFAULT_AIR_SERVER_ADDRESS,
73 AirClient::{
74 AirClient,
75 AirMetrics,
76 AirStatus,
77 DownloadStream,
78 DownloadStreamChunk,
79 ExtendedFileInfo,
80 FileInfo,
81 FileResult,
82 IndexInfo,
83 ResourceUsage,
84 UpdateInfo,
85 },
86};
87use crate::{Air::AirServiceProvider::GenerateRequestID::Fn as generate_request_id, dev_log};
88
89pub mod GenerateRequestID;
90
91// ============================================================================
92// AirServiceProvider - High-level API Implementation
93// ============================================================================
94
95/// AirServiceProvider provides a high-level, convenient interface to the Air
96/// daemon service.
97///
98/// This provider wraps the AirClient and provides simplified methods with
99/// automatic request ID generation and error handling. It acts as a facade
100/// pattern, hiding the complexity of gRPC communication from the rest of the
101/// Mountain application.
102///
103/// # Example
104///
105/// ```text
106/// use Mountain::Air::AirServiceProvider::{AirServiceProvider, DEFAULT_AIR_SERVER_ADDRESS};
107/// use CommonLibrary::Error::CommonError::CommonError;
108///
109/// # #[tokio::main]
110/// # async fn main() -> Result<(), CommonError> {
111/// let provider = AirServiceProvider::new(DEFAULT_AIR_SERVER_ADDRESS.to_string()).await?;
112///
113/// // Check for health
114/// let is_healthy = provider.health_check().await?;
115/// println!("Air service healthy: {}", is_healthy);
116///
117/// // Check for updates
118/// if let Some(update) =
119/// provider.check_for_updates("1.0.0".to_string(), "stable".to_string()).await?
120/// {
121/// println!("Update available: {}", update.version);
122/// }
123///
124/// # Ok(())
125/// # }
126/// ```
127#[derive(Debug, Clone)]
128pub struct AirServiceProvider {
129 /// The underlying Air client wrapped in Arc for thread safety
130 client:Arc<AirClient>,
131}
132
133impl AirServiceProvider {
134 /// Creates a new AirServiceProvider and connects to the Air daemon.
135 ///
136 /// # Arguments
137 /// * `address` - The gRPC server address (defaults to `[::1]:50053`)
138 ///
139 /// # Returns
140 /// * `Ok(Self)` - Successfully created provider
141 /// * `Err(CommonError)` - Connection failure
142 ///
143 /// # Example
144 ///
145 /// ```text
146 /// use Mountain::Air::AirServiceProvider::AirServiceProvider;
147 /// use CommonLibrary::Error::CommonError::CommonError;
148 ///
149 /// # #[tokio::main]
150 /// # async fn main() -> Result<(), CommonError> {
151 /// let provider = AirServiceProvider::new("http://[::1]:50053".to_string()).await?;
152 /// # Ok(())
153 /// # }
154 /// ```
155 pub async fn new(address:String) -> Result<Self, CommonError> {
156 dev_log!("grpc", "[AirServiceProvider] Creating AirServiceProvider at: {}", address);
157
158 let client = AirClient::new(&address).await?;
159
160 dev_log!("grpc", "[AirServiceProvider] AirServiceProvider created successfully");
161
162 Ok(Self { client:Arc::new(client) })
163 }
164
165 /// Creates a new AirServiceProvider with the default address.
166 ///
167 /// This is a convenience method that uses [`DEFAULT_AIR_SERVER_ADDRESS`].
168 ///
169 /// # Returns
170 /// * `Ok(Self)` - Successfully created provider
171 /// * `Err(CommonError)` - Connection failure
172 ///
173 /// # Example
174 ///
175 /// ```text
176 /// use Mountain::Air::AirServiceProvider::AirServiceProvider;
177 /// use CommonLibrary::Error::CommonError::CommonError;
178 ///
179 /// # #[tokio::main]
180 /// # async fn main() -> Result<(), CommonError> {
181 /// let provider = AirServiceProvider::new_default().await?;
182 /// # Ok(())
183 /// # }
184 /// ```
185 pub async fn new_default() -> Result<Self, CommonError> { Self::new(DEFAULT_AIR_SERVER_ADDRESS.to_string()).await }
186
187 /// Creates a new AirServiceProvider from an existing AirClient.
188 ///
189 /// This is useful when you need to share a client or have special
190 /// connection requirements.
191 ///
192 /// # Arguments
193 /// * `client` - The AirClient to wrap
194 ///
195 /// # Returns
196 /// * `Self` - The new provider
197 pub fn from_client(client:Arc<AirClient>) -> Self {
198 dev_log!("grpc", "[AirServiceProvider] Creating AirServiceProvider from existing client");
199 Self { client }
200 }
201
202 /// Gets a reference to the underlying AirClient.
203 ///
204 /// This provides access to the low-level client when needed.
205 ///
206 /// # Returns
207 /// Reference to the AirClient
208 pub fn client(&self) -> &Arc<AirClient> { &self.client }
209
210 /// Checks if the provider is connected to Air.
211 ///
212 /// # Returns
213 /// * `true` - Connected
214 /// * `false` - Not connected
215 pub fn is_connected(&self) -> bool { self.client.is_connected() }
216
217 /// Gets the address of the Air daemon.
218 ///
219 /// # Returns
220 /// The address string
221 pub fn address(&self) -> &str { self.client.address() }
222
223 // =========================================================================
224 // Authentication Operations
225 // =========================================================================
226
227 /// Authenticates a user with the Air daemon.
228 ///
229 /// This method handles request ID generation and provides a simplified
230 /// interface for authentication.
231 ///
232 /// # Arguments
233 /// * `username` - User's username
234 /// * `password` - User's password
235 /// * `provider` - Authentication provider (e.g., "github", "gitlab",
236 /// "microsoft")
237 ///
238 /// # Returns
239 /// * `Ok(token)` - Authentication token if successful
240 /// * `Err(CommonError)` - Authentication error
241 ///
242 /// # Example
243 ///
244 /// ```text
245 /// # use Mountain::Air::AirServiceProvider::AirServiceProvider;
246 /// # use CommonLibrary::Error::CommonError::CommonError;
247 /// # #[tokio::main]
248 /// # async fn main() -> Result<(), CommonError> {
249 /// # let provider = AirServiceProvider::new_default().await?;
250 /// let token = provider
251 /// .authenticate("user@example.com".to_string(), "password".to_string(), "github".to_string())
252 /// .await?;
253 /// println!("Auth token: {}", token);
254 /// # Ok(())
255 /// # }
256 /// ```
257 pub async fn authenticate(&self, username:String, password:String, provider:String) -> Result<String, CommonError> {
258 let request_id = generate_request_id();
259 dev_log!("grpc", "[AirServiceProvider] authenticate (request_id: {})", request_id);
260
261 self.client.authenticate(request_id, username, password, provider).await
262 }
263
264 // =========================================================================
265 // Update Operations
266 // =========================================================================
267
268 /// Checks for available updates.
269 ///
270 /// Returns None if no update is available, Some with update info otherwise.
271 ///
272 /// # Arguments
273 /// * `current_version` - Current application version
274 /// * `channel` - Update channel (e.g., "stable", "beta", "nightly")
275 ///
276 /// # Returns
277 /// * `Ok(Some(update))` - Update available with information
278 /// * `Ok(None)` - No update available
279 /// * `Err(CommonError)` - Check error
280 ///
281 /// # Example
282 ///
283 /// ```text
284 /// # use Mountain::Air::AirServiceProvider::AirServiceProvider;
285 /// # use CommonLibrary::Error::CommonError::CommonError;
286 /// # #[tokio::main]
287 /// # async fn main() -> Result<(), CommonError> {
288 /// # let provider = AirServiceProvider::new_default().await?;
289 /// if let Some(update) =
290 /// provider.check_for_updates("1.0.0".to_string(), "stable".to_string()).await?
291 /// {
292 /// println!("Update available: version {}", update.version);
293 /// }
294 /// # Ok(())
295 /// # }
296 /// ```
297 pub async fn check_for_updates(
298 &self,
299 current_version:String,
300 channel:String,
301 ) -> Result<Option<UpdateInfo::Struct>, CommonError> {
302 let request_id = generate_request_id();
303 dev_log!("grpc", "[AirServiceProvider] check_for_updates (request_id: {})", request_id);
304
305 let info = self.client.check_for_updates(request_id, current_version, channel).await?;
306
307 if info.update_available { Ok(Some(info)) } else { Ok(None) }
308 }
309
310 /// Downloads an update package.
311 ///
312 /// # Arguments
313 /// * `url` - URL of the update package
314 /// * `destination_path` - Local path to save the downloaded file
315 /// * `checksum` - Optional SHA256 checksum for verification
316 ///
317 /// # Returns
318 /// * `Ok(file_info)` - Downloaded file information
319 /// * `Err(CommonError)` - Download error
320 pub async fn download_update(
321 &self,
322 url:String,
323 destination_path:String,
324 checksum:String,
325 ) -> Result<FileInfo::Struct, CommonError> {
326 let request_id = generate_request_id();
327 dev_log!("grpc", "[AirServiceProvider] download_update (request_id: {})", request_id);
328
329 self.client
330 .download_update(request_id, url, destination_path, checksum, HashMap::new())
331 .await
332 }
333
334 /// Applies an update package.
335 ///
336 /// # Arguments
337 /// * `version` - Version of the update
338 /// * `update_path` - Path to the update package
339 ///
340 /// # Returns
341 /// * `Ok(())` - Update applied successfully
342 /// * `Err(CommonError)` - Application error
343 pub async fn apply_update(&self, version:String, update_path:String) -> Result<(), CommonError> {
344 let request_id = generate_request_id();
345 dev_log!("grpc", "[AirServiceProvider] apply_update (request_id: {})", request_id);
346
347 self.client.apply_update(request_id, version, update_path).await
348 }
349
350 // =========================================================================
351 // Download Operations
352 // =========================================================================
353
354 /// Downloads a file.
355 ///
356 /// # Arguments
357 /// * `url` - URL of the file to download
358 /// * `destination_path` - Local path to save the downloaded file
359 /// * `checksum` - Optional SHA256 checksum for verification
360 ///
361 /// # Returns
362 /// * `Ok(file_info)` - Downloaded file information
363 /// * `Err(CommonError)` - Download error
364 pub async fn download_file(
365 &self,
366 url:String,
367 destination_path:String,
368 checksum:String,
369 ) -> Result<FileInfo::Struct, CommonError> {
370 let request_id = generate_request_id();
371 dev_log!("grpc", "[AirServiceProvider] download_file (request_id: {})", request_id);
372
373 self.client
374 .download_file(request_id, url, destination_path, checksum, HashMap::new())
375 .await
376 }
377
378 /// Downloads a file as a stream.
379 ///
380 /// This method initiates a streaming download from the given URL, returning
381 /// a stream of chunks that can be processed incrementally without loading
382 /// the entire file into memory.
383 ///
384 /// # Arguments
385 /// * `url` - URL of the file to download
386 /// * `headers` - Optional HTTP headers
387 ///
388 /// # Returns
389 /// * `Ok(stream)` - Stream that yields download chunks
390 /// * `Err(CommonError)` - Download error
391 ///
392 /// # Example
393 ///
394 /// ```text
395 /// # use Mountain::Air::AirServiceProvider::AirServiceProvider;
396 /// # use CommonLibrary::Error::CommonError::CommonError;
397 /// # #[tokio::main]
398 /// # async fn main() -> Result<(), CommonError> {
399 /// # let provider = AirServiceProvider::new_default().await?;
400 /// let mut stream = provider
401 /// .download_stream(
402 /// "https://example.com/large-file.zip".to_string(),
403 /// std::collections::HashMap::new(),
404 /// )
405 /// .await?;
406 ///
407 /// let mut buffer = Vec::new();
408 /// while let Some(chunk) = stream.next().await {
409 /// let chunk = chunk?;
410 /// buffer.extend_from_slice(&chunk.data);
411 /// println!("Downloaded: {} / {} bytes", chunk.downloaded, chunk.total_size);
412 /// if chunk.completed {
413 /// break;
414 /// }
415 /// }
416 /// # Ok(())
417 /// # }
418 /// ```
419 pub async fn download_stream(
420 &self,
421 url:String,
422 headers:HashMap<String, String>,
423 ) -> Result<DownloadStream::Struct, CommonError> {
424 let request_id = generate_request_id();
425 dev_log!(
426 "grpc",
427 "[AirServiceProvider] download_stream (request_id: {}, url: {})",
428 request_id,
429 url
430 );
431
432 self.client.download_stream(request_id, url, headers).await
433 }
434
435 // =========================================================================
436 // File Indexing Operations
437 // =========================================================================
438
439 /// Indexes files in a directory.
440 ///
441 /// # Arguments
442 /// * `path` - Path to the directory to index
443 /// * `patterns` - File patterns to include (e.g., ["*.rs", "*.ts"])
444 /// * `exclude_patterns` - File patterns to exclude (e.g.,
445 /// ["node_modules/*"])
446 /// * `max_depth` - Maximum depth for recursion (0 for unlimited)
447 ///
448 /// # Returns
449 /// * `Ok(index_info)` - Index information with file count and total size
450 /// * `Err(CommonError)` - Indexing error
451 ///
452 /// # Example
453 ///
454 /// ```text
455 /// # use Mountain::Air::AirServiceProvider::AirServiceProvider;
456 /// # use CommonLibrary::Error::CommonError::CommonError;
457 /// # #[tokio::main]
458 /// # async fn main() -> Result<(), CommonError> {
459 /// # let provider = AirServiceProvider::new_default().await?;
460 /// let info = provider
461 /// .index_files(
462 /// "/path/to/project".to_string(),
463 /// vec!["*.rs".to_string(), "*.ts".to_string()],
464 /// vec!["node_modules/*".to_string()],
465 /// 10,
466 /// )
467 /// .await?;
468 /// println!("Indexed {} files ({} bytes)", info.files_indexed, info.total_size);
469 /// # Ok(())
470 /// # }
471 /// ```
472 pub async fn index_files(
473 &self,
474 path:String,
475 patterns:Vec<String>,
476 exclude_patterns:Vec<String>,
477 max_depth:u32,
478 ) -> Result<IndexInfo::Struct, CommonError> {
479 let request_id = generate_request_id();
480 dev_log!(
481 "grpc",
482 "[AirServiceProvider] index_files (request_id: {}, path: {})",
483 request_id,
484 path
485 );
486
487 self.client
488 .index_files(request_id, path, patterns, exclude_patterns, max_depth)
489 .await
490 }
491
492 /// Searches for files matching a query.
493 ///
494 /// # Arguments
495 /// * `query` - Search query string
496 /// * `path` - Path to search in (empty for entire workspace)
497 /// * `max_results` - Maximum number of results to return (0 for unlimited)
498 ///
499 /// # Returns
500 /// * `Ok(results)` - Vector of file search results
501 /// * `Err(CommonError)` - Search error
502 ///
503 /// # Example
504 ///
505 /// ```text
506 /// # use Mountain::Air::AirServiceProvider::AirServiceProvider;
507 /// # use CommonLibrary::Error::CommonError::CommonError;
508 /// # #[tokio::main]
509 /// # async fn main() -> Result<(), CommonError> {
510 /// # let provider = AirServiceProvider::new_default().await?;
511 /// let results = provider
512 /// .search_files("fn main".to_string(), "/path/to/project".to_string(), 50)
513 /// .await?;
514 /// for result in results {
515 /// println!("Found: {} at line {}", result.path, result.line_number);
516 /// }
517 /// # Ok(())
518 /// # }
519 /// ```
520 pub async fn search_files(
521 &self,
522 query:String,
523 path:String,
524 max_results:u32,
525 ) -> Result<Vec<FileResult::Struct>, CommonError> {
526 let request_id = generate_request_id();
527 dev_log!(
528 "grpc",
529 "[AirServiceProvider] search_files (request_id: {}, query: {})",
530 request_id,
531 query
532 );
533
534 self.client.search_files(request_id, query, path, max_results).await
535 }
536
537 /// Gets file information.
538 ///
539 /// # Arguments
540 /// * `path` - Path to the file
541 ///
542 /// # Returns
543 /// * `Ok(file_info)` - Extended file information
544 /// * `Err(CommonError)` - Request error
545 pub async fn get_file_info(&self, path:String) -> Result<ExtendedFileInfo::Struct, CommonError> {
546 let request_id = generate_request_id();
547 dev_log!(
548 "grpc",
549 "[AirServiceProvider] get_file_info (request_id: {}, path: {})",
550 request_id,
551 path
552 );
553
554 self.client.get_file_info(request_id, path).await
555 }
556
557 // =========================================================================
558 // Status and Monitoring Operations
559 // =========================================================================
560
561 /// Gets the status of the Air daemon.
562 ///
563 /// # Returns
564 /// * `Ok(status)` - Air daemon status information
565 /// * `Err(CommonError)` - Request error
566 pub async fn get_status(&self) -> Result<AirStatus::Struct, CommonError> {
567 let request_id = generate_request_id();
568 dev_log!("grpc", "[AirServiceProvider] get_status (request_id: {})", request_id);
569
570 self.client.get_status(request_id).await
571 }
572
573 /// Performs a health check on the Air daemon.
574 ///
575 /// # Returns
576 /// * `Ok(healthy)` - Health status (true if healthy)
577 /// * `Err(CommonError)` - Check error
578 ///
579 /// # Example
580 ///
581 /// ```text
582 /// # use Mountain::Air::AirServiceProvider::AirServiceProvider;
583 /// # use CommonLibrary::Error::CommonError::CommonError;
584 /// # #[tokio::main]
585 /// # async fn main() -> Result<(), CommonError> {
586 /// # let provider = AirServiceProvider::new_default().await?;
587 /// if provider.health_check().await? {
588 /// println!("Air service is healthy");
589 /// }
590 /// # Ok(())
591 /// # }
592 /// ```
593 pub async fn health_check(&self) -> Result<bool, CommonError> {
594 dev_log!("grpc", "[AirServiceProvider] health_check");
595 self.client.health_check().await
596 }
597
598 /// Gets metrics from the Air daemon.
599 ///
600 /// # Arguments
601 /// * `metric_type` - Optional type of metrics (e.g., "performance",
602 /// "resources")
603 ///
604 /// # Returns
605 /// * `Ok(metrics)` - Metrics data
606 /// * `Err(CommonError)` - Request error
607 pub async fn get_metrics(&self, metric_type:Option<String>) -> Result<AirMetrics::Struct, CommonError> {
608 let request_id = generate_request_id();
609 dev_log!("grpc", "[AirServiceProvider] get_metrics (request_id: {})", request_id);
610
611 self.client.get_metrics(request_id, metric_type).await
612 }
613
614 // =========================================================================
615 // Resource Management Operations
616 // =========================================================================
617
618 /// Gets resource usage information.
619 ///
620 /// # Returns
621 /// * `Ok(usage)` - Resource usage data
622 /// * `Err(CommonError)` - Request error
623 pub async fn get_resource_usage(&self) -> Result<ResourceUsage::Struct, CommonError> {
624 let request_id = generate_request_id();
625 dev_log!("grpc", "[AirServiceProvider] get_resource_usage (request_id: {})", request_id);
626
627 self.client.get_resource_usage(request_id).await
628 }
629
630 /// Sets resource limits.
631 ///
632 /// # Arguments
633 /// * `memory_limit_mb` - Memory limit in MB
634 /// * `cpu_limit_percent` - CPU limit as percentage (0-100)
635 /// * `disk_limit_mb` - Disk limit in MB
636 ///
637 /// # Returns
638 /// * `Ok(())` - Limits set successfully
639 /// * `Err(CommonError)` - Set error
640 pub async fn set_resource_limits(
641 &self,
642 memory_limit_mb:u32,
643 cpu_limit_percent:u32,
644 disk_limit_mb:u32,
645 ) -> Result<(), CommonError> {
646 let request_id = generate_request_id();
647 dev_log!("grpc", "[AirServiceProvider] set_resource_limits (request_id: {})", request_id);
648
649 self.client
650 .set_resource_limits(request_id, memory_limit_mb, cpu_limit_percent, disk_limit_mb)
651 .await
652 }
653
654 // =========================================================================
655 // Configuration Management Operations
656 // =========================================================================
657
658 /// Gets configuration.
659 ///
660 /// # Arguments
661 /// * `section` - Configuration section (e.g., "grpc", "authentication",
662 /// "updates")
663 ///
664 /// # Returns
665 /// * `Ok(config)` - Configuration data as key-value pairs
666 /// * `Err(CommonError)` - Request error
667 ///
668 /// # Example
669 ///
670 /// ```text
671 /// # use Mountain::Air::AirServiceProvider::AirServiceProvider;
672 /// # use CommonLibrary::Error::CommonError::CommonError;
673 /// # #[tokio::main]
674 /// # async fn main() -> Result<(), CommonError> {
675 /// # let provider = AirServiceProvider::new_default().await?;
676 /// let config = provider.get_configuration("grpc".to_string()).await?;
677 /// for (key, value) in config {
678 /// println!("{} = {}", key, value);
679 /// }
680 /// # Ok(())
681 /// # }
682 /// ```
683 pub async fn get_configuration(&self, section:String) -> Result<HashMap<String, String>, CommonError> {
684 let request_id = generate_request_id();
685 dev_log!(
686 "grpc",
687 "[AirServiceProvider] get_configuration (request_id: {}, section: {})",
688 request_id,
689 section
690 );
691
692 self.client.get_configuration(request_id, section).await
693 }
694
695 /// Updates configuration.
696 ///
697 /// # Arguments
698 /// * `section` - Configuration section
699 /// * `updates` - Configuration updates as key-value pairs
700 ///
701 /// # Returns
702 /// * `Ok(())` - Configuration updated successfully
703 /// * `Err(CommonError)` - Update error
704 pub async fn update_configuration(
705 &self,
706 section:String,
707 updates:HashMap<String, String>,
708 ) -> Result<(), CommonError> {
709 let request_id = generate_request_id();
710 dev_log!(
711 "grpc",
712 "[AirServiceProvider] update_configuration (request_id: {}, section: {})",
713 request_id,
714 section
715 );
716
717 self.client.update_configuration(request_id, section, updates).await
718 }
719}
720
721// Request-id helper moved to `GenerateRequestID::Fn` in the sibling file
722// declared at the top of this module. Internal callers reach it via the
723// `use self::GenerateRequestID::Fn as generate_request_id;` shorthand.
724
725// ============================================================================
726// Tests
727// ============================================================================
728
729#[cfg(test)]
730mod tests {
731 use super::*;
732
733 #[test]
734 fn test_generate_request_id() {
735 let id1 = generate_request_id();
736 let id2 = generate_request_id();
737
738 // IDs should be unique
739 assert_ne!(id1, id2);
740
741 // IDs should be valid UUIDs (simple format = 32 chars)
742 assert_eq!(id1.len(), 32);
743 assert_eq!(id2.len(), 32);
744
745 // IDs should be hex characters
746 assert!(id1.chars().all(|c| c.is_ascii_hexdigit()));
747 assert!(id2.chars().all(|c| c.is_ascii_hexdigit()));
748 }
749
750 #[test]
751 fn test_default_address() {
752 assert_eq!(DEFAULT_AIR_SERVER_ADDRESS, "[::1]:50053");
753 }
754}