Skip to main content

Mountain/Vine/Client/
Shared.rs

1#![allow(non_snake_case)]
2
3//! Module-private state for the Vine client: connection pool, per-
4//! connection metadata, the broadcast fan-out, the shutdown flag, plus
5//! the constants and message-size validator that every entry-point shares.
6
7use std::{
8	collections::HashMap,
9	sync::{
10		Arc,
11		atomic::{AtomicBool, Ordering},
12	},
13	time::Instant,
14};
15
16use lazy_static::lazy_static;
17use parking_lot::Mutex;
18
19use crate::Vine::{Client::NotificationFrame, Error::VineError, Generated::cocoon_service_client::CocoonServiceClient};
20
21/// Cocoon gRPC client over a tonic transport channel.
22pub type CocoonClient = CocoonServiceClient<tonic::transport::Channel>;
23
24/// Default timeout for RPC calls.
25pub const DEFAULT_TIMEOUT_MS:u64 = 5000;
26/// Maximum number of retry attempts for failed connections.
27pub const MAX_RETRY_ATTEMPTS:usize = 3;
28/// Base delay between retry attempts.
29pub const RETRY_BASE_DELAY_MS:u64 = 100;
30/// Maximum message size for validation (4 MB to match the tonic default).
31pub const MAX_MESSAGE_SIZE_BYTES:usize = 4 * 1024 * 1024;
32/// Health-check interval.
33pub const HEALTH_CHECK_INTERVAL_MS:u64 = 30000;
34/// Connection timeout (currently unused - kept for the streaming variant).
35#[allow(dead_code)]
36pub const CONNECTION_TIMEOUT_MS:u64 = 10000;
37
38/// Notification broadcast capacity (drop-oldest when full). 4096 covers
39/// the worst-case storms (sky://diagnostics/changed at 50-200/s during
40/// rust-analyzer cargo-check) with margin.
41pub const NOTIFICATION_BROADCAST_CAPACITY:usize = 4096;
42
43/// Connection metadata tracking health and last activity.
44pub struct ConnectionMetadata {
45	pub LastActivity:Instant,
46	pub FailureCount:usize,
47	pub IsHealthy:bool,
48}
49
50lazy_static! {
51	pub static ref SIDECAR_CLIENTS: Arc<Mutex<HashMap<String, CocoonClient>>> = Arc::new(Mutex::new(HashMap::new()));
52	pub static ref CONNECTION_METADATA: Arc<Mutex<HashMap<String, ConnectionMetadata>>> =
53		Arc::new(Mutex::new(HashMap::new()));
54	pub static ref NOTIFICATION_BROADCAST: tokio::sync::broadcast::Sender<NotificationFrame::Struct> = {
55		let (Sender, _) = tokio::sync::broadcast::channel(NOTIFICATION_BROADCAST_CAPACITY);
56		Sender
57	};
58}
59
60/// Process-wide shutdown flag. Set to `true` once Mountain has issued
61/// `$shutdown` (or SIGKILL'd) Cocoon. After that point all
62/// `SendNotification` / `SendRequest` calls short-circuit.
63pub static SHUTDOWN_FLAG:AtomicBool = AtomicBool::new(false);
64
65pub fn ShutdownFlagStore(Value:bool) { SHUTDOWN_FLAG.store(Value, Ordering::Relaxed); }
66pub fn ShutdownFlagLoad() -> bool { SHUTDOWN_FLAG.load(Ordering::Relaxed) }
67
68/// Increment the failure counter and mark the connection unhealthy.
69pub fn RecordSideCarFailure(SideCarIdentifier:&str) {
70	let mut Metadata = CONNECTION_METADATA.lock();
71	if let Some(Connection) = Metadata.get_mut(SideCarIdentifier) {
72		Connection.FailureCount += 1;
73		Connection.IsHealthy = false;
74	}
75}
76
77/// Refresh the last-activity timestamp and reset the failure counter.
78pub fn UpdateSideCarActivity(SideCarIdentifier:&str) {
79	let mut Metadata = CONNECTION_METADATA.lock();
80	if let Some(Connection) = Metadata.get_mut(SideCarIdentifier) {
81		Connection.LastActivity = Instant::now();
82		Connection.FailureCount = 0;
83		Connection.IsHealthy = true;
84	}
85}
86
87/// Reject messages above `MAX_MESSAGE_SIZE_BYTES` to bound the worst-case
88/// gRPC frame. Mirrors tonic's own check so we don't pay the codec round-
89/// trip for an oversize payload.
90pub fn ValidateMessageSize(Data:&[u8]) -> Result<(), VineError> {
91	if Data.len() > MAX_MESSAGE_SIZE_BYTES {
92		Err(VineError::MessageTooLarge { ActualSize:Data.len(), MaxSize:MAX_MESSAGE_SIZE_BYTES })
93	} else {
94		Ok(())
95	}
96}