-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathmessage.rs
More file actions
1749 lines (1558 loc) · 59.6 KB
/
Copy pathmessage.rs
File metadata and controls
1749 lines (1558 loc) · 59.6 KB
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
// Copyright (c) 2024-present, arana-db Community. All rights reserved.
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Message channel communication system for dual runtime architecture
//!
//! This module provides the data structures and communication mechanisms
//! for passing storage requests between the network and storage runtimes.
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::{Duration, Instant};
use serde::{Deserialize, Serialize};
use tokio::sync::{Mutex, mpsc, oneshot};
use uuid::Uuid;
use crate::error_logging::{CorrelationId, ErrorLogger, RuntimeContext};
use resp::RespData;
use storage::error::Error as StorageError;
/// Unique identifier for tracking storage requests across runtime boundaries
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RequestId(Uuid);
impl RequestId {
/// Create a new unique request ID
pub fn new() -> Self {
Self(Uuid::new_v4())
}
/// Get the inner UUID value
pub fn inner(&self) -> Uuid {
self.0
}
}
impl Default for RequestId {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Display for RequestId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
/// Storage commands that can be executed in the storage runtime
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum StorageCommand {
/// Execute a Redis command using the storage runtime command table
Execute {
cmd_name: Vec<u8>,
argv: Vec<Vec<u8>>,
},
/// Batch multiple commands together
Batch { commands: Vec<StorageCommand> },
}
/// Storage-layer instrumentation types.
///
/// These were originally defined here (see
/// <https://github.com/arana-db/kiwi/issues/312>) but now live in the `client`
/// crate so that `storage`, `runtime` and `cmd` can all depend on them without
/// creating a dependency cycle. Re-exported here for backward compatibility with
/// existing `runtime::message::*` importers.
pub use client::storage_stats::{
NoopStorageStatsCollector, RealStorageStatsCollector, STORAGE_STATS_COLLECTOR, StorageStats,
StorageStatsCollector, try_collector,
};
/// Request sent from network runtime to storage runtime
#[derive(Debug)]
pub struct StorageRequest {
/// Unique identifier for this request
#[cfg(not(feature = "runtime-baseline"))]
pub id: RequestId,
/// Unique identifier for this request, bound to the baseline attempt trace.
#[cfg(feature = "runtime-baseline")]
pub(crate) id: RequestId,
/// The storage command to execute
pub command: StorageCommand,
/// Channel to send the response back
pub response_channel: oneshot::Sender<StorageResponse>,
/// Request timeout duration
pub timeout: Duration,
/// Timestamp when the request was created
pub timestamp: Instant,
/// Priority level for request processing
pub priority: RequestPriority,
/// Baseline lifecycle token carried across the storage runtime boundary.
#[cfg(feature = "runtime-baseline")]
pub(crate) baseline_attempt: Option<crate::baseline::BaselineAttempt>,
}
impl StorageRequest {
/// Create a request without feature-specific instrumentation.
pub fn new(
id: RequestId,
command: StorageCommand,
response_channel: oneshot::Sender<StorageResponse>,
timeout: Duration,
priority: RequestPriority,
) -> Self {
Self {
id,
command,
response_channel,
timeout,
timestamp: Instant::now(),
priority,
#[cfg(feature = "runtime-baseline")]
baseline_attempt: None,
}
}
/// Return the immutable physical request identity.
pub fn id(&self) -> RequestId {
self.id
}
/// Create an instrumented request whose physical identity is derived from
/// its baseline attempt token.
///
/// Instrumented request identities cannot be overwritten by callers:
///
/// ```compile_fail
/// use runtime::{RequestId, StorageRequest};
///
/// fn overwrite_id(request: &mut StorageRequest) {
/// request.id = RequestId::new();
/// }
/// ```
///
/// Instrumented requests also cannot be reconstructed with a mismatched ID:
///
/// ```compile_fail
/// use runtime::{RequestId, StorageRequest};
///
/// fn forge_id(request: StorageRequest) -> StorageRequest {
/// StorageRequest {
/// id: RequestId::new(),
/// ..request
/// }
/// }
/// ```
#[cfg(feature = "runtime-baseline")]
pub fn new_with_baseline_attempt(
baseline_attempt: crate::baseline::BaselineAttempt,
command: StorageCommand,
response_channel: oneshot::Sender<StorageResponse>,
timeout: Duration,
priority: RequestPriority,
) -> Self {
Self {
id: baseline_attempt.trace().attempt_id,
command,
response_channel,
timeout,
timestamp: Instant::now(),
priority,
baseline_attempt: Some(baseline_attempt),
}
}
/// Return the baseline token without permitting callers to replace it with
/// an identity that diverges from [`StorageRequest::id()`].
#[cfg(feature = "runtime-baseline")]
pub fn baseline_attempt(&self) -> Option<&crate::baseline::BaselineAttempt> {
self.baseline_attempt.as_ref()
}
}
/// Priority levels for storage request processing
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]
pub enum RequestPriority {
/// Low priority requests (background operations)
Low = 0,
/// Normal priority requests (regular client operations)
#[default]
Normal = 1,
/// High priority requests (critical operations)
High = 2,
/// Critical priority requests (system operations)
Critical = 3,
}
/// Response sent from storage runtime back to network runtime
#[derive(Debug)]
pub struct StorageResponse {
/// Request ID this response corresponds to
pub id: RequestId,
/// Result of the storage operation
pub result: Result<RespData, StorageError>,
/// Time taken to execute the storage operation
pub execution_time: Duration,
/// Statistics about the storage operation
pub storage_stats: StorageStats,
}
/// Message channel for communication between network and storage runtimes
pub struct MessageChannel {
/// Sender for storage requests (used by network runtime)
request_sender: mpsc::Sender<StorageRequest>,
/// Receiver for storage requests (used by storage runtime)
request_receiver: Option<mpsc::Receiver<StorageRequest>>,
/// Buffer size for the request channel
buffer_size: usize,
/// Channel statistics for monitoring
stats: Arc<Mutex<ChannelStats>>,
/// Configuration for backpressure handling
backpressure_config: BackpressureConfig,
}
/// Configuration for backpressure handling
#[derive(Debug, Clone)]
pub struct BackpressureConfig {
/// Threshold percentage (0-100) at which backpressure kicks in
pub threshold_percent: u8,
/// Maximum time to wait when channel is full before giving up
pub max_wait_time: Duration,
/// Whether to drop oldest requests when channel is full
pub drop_oldest_on_full: bool,
}
impl Default for BackpressureConfig {
fn default() -> Self {
Self {
threshold_percent: 80,
max_wait_time: Duration::from_millis(100),
drop_oldest_on_full: false,
}
}
}
/// Configuration for retry logic
#[derive(Debug, Clone)]
pub struct RetryConfig {
/// Maximum number of retry attempts
pub max_retries: usize,
/// Base delay between retries
pub base_delay: Duration,
/// Maximum delay between retries
pub max_delay: Duration,
/// Multiplier for exponential backoff
pub backoff_multiplier: f64,
/// Whether to add jitter to retry delays
pub jitter: bool,
}
impl Default for RetryConfig {
fn default() -> Self {
Self {
max_retries: 3,
base_delay: Duration::from_millis(10),
max_delay: Duration::from_secs(1),
backoff_multiplier: 2.0,
jitter: true,
}
}
}
/// Detailed error information for failed requests
#[derive(Debug, Clone)]
pub struct RequestError {
/// The original request ID
pub request_id: RequestId,
/// The error that occurred
pub error: String,
/// Number of retry attempts made
pub retry_attempts: usize,
/// Total time spent on the request
pub total_time: Duration,
/// Timestamp when the error occurred
pub timestamp: Instant,
}
/// Circuit breaker for handling repeated failures
#[derive(Debug, Clone)]
pub struct CircuitBreaker {
/// Number of consecutive failures before opening
failure_threshold: usize,
/// Time to wait before attempting to close the circuit
recovery_timeout: Duration,
/// Current state of the circuit breaker
state: CircuitBreakerState,
/// Number of consecutive failures
failure_count: usize,
/// Timestamp when the circuit was opened
opened_at: Option<Instant>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum CircuitBreakerState {
Closed, // Normal operation
Open, // Failing fast
HalfOpen, // Testing if service has recovered
}
impl CircuitBreaker {
/// Create a new circuit breaker
pub fn new(failure_threshold: usize, recovery_timeout: Duration) -> Self {
Self {
failure_threshold,
recovery_timeout,
state: CircuitBreakerState::Closed,
failure_count: 0,
opened_at: None,
}
}
/// Check if a request should be allowed through
pub fn should_allow_request(&mut self) -> bool {
match self.state {
CircuitBreakerState::Closed => true,
CircuitBreakerState::Open => {
if let Some(opened_at) = self.opened_at {
if opened_at.elapsed() >= self.recovery_timeout {
self.state = CircuitBreakerState::HalfOpen;
true
} else {
false
}
} else {
false
}
}
CircuitBreakerState::HalfOpen => true,
}
}
/// Record a successful request
pub fn record_success(&mut self) {
self.failure_count = 0;
self.state = CircuitBreakerState::Closed;
self.opened_at = None;
}
/// Record a failed request
pub fn record_failure(&mut self) {
self.failure_count += 1;
if self.failure_count >= self.failure_threshold {
self.state = CircuitBreakerState::Open;
self.opened_at = Some(Instant::now());
}
}
/// Get the current state
pub fn state(&self) -> &CircuitBreakerState {
&self.state
}
}
/// Statistics for monitoring channel health and performance
#[derive(Debug, Clone, Default)]
pub struct ChannelStats {
/// Total number of requests sent
pub requests_sent: u64,
/// Total number of requests received
pub requests_received: u64,
/// Total number of responses sent
pub responses_sent: u64,
/// Total number of requests that timed out
pub requests_timeout: u64,
/// Total number of channel send failures
pub send_failures: u64,
/// Current number of pending requests
pub pending_requests: u64,
/// Maximum pending requests seen
pub max_pending_requests: u64,
/// Number of times backpressure was applied
pub backpressure_events: u64,
/// Average request processing time
pub avg_processing_time: Duration,
}
impl MessageChannel {
/// Create a new message channel with the specified buffer size
pub fn new(buffer_size: usize) -> Self {
Self::with_backpressure_config(buffer_size, BackpressureConfig::default())
}
/// Create a new message channel with custom backpressure configuration
pub fn with_backpressure_config(
buffer_size: usize,
backpressure_config: BackpressureConfig,
) -> Self {
let (request_sender, request_receiver) = mpsc::channel(buffer_size);
Self {
request_sender,
request_receiver: Some(request_receiver),
buffer_size,
stats: Arc::new(Mutex::new(ChannelStats::default())),
backpressure_config,
}
}
/// Get the request sender (for network runtime)
pub fn request_sender(&self) -> mpsc::Sender<StorageRequest> {
self.request_sender.clone()
}
/// Take the request receiver (for storage runtime)
/// This can only be called once as the receiver is moved
pub fn take_request_receiver(&mut self) -> Option<mpsc::Receiver<StorageRequest>> {
self.request_receiver.take()
}
/// Get the buffer size of the channel
pub fn buffer_size(&self) -> usize {
self.buffer_size
}
/// Get current channel statistics
pub async fn stats(&self) -> ChannelStats {
self.stats.lock().await.clone()
}
/// Check if the channel is healthy (not closed and within capacity)
pub fn is_healthy(&self) -> bool {
!self.request_sender.is_closed()
}
/// Get the current number of pending requests in the channel
pub fn pending_requests(&self) -> usize {
let capacity = self.request_sender.capacity();
let max_capacity = self.request_sender.max_capacity();
max_capacity.saturating_sub(capacity)
}
/// Check if the channel is experiencing backpressure
pub fn has_backpressure(&self) -> bool {
let threshold =
(self.buffer_size * self.backpressure_config.threshold_percent as usize) / 100;
self.pending_requests() >= threshold
}
/// Get the backpressure configuration
pub fn backpressure_config(&self) -> &BackpressureConfig {
&self.backpressure_config
}
/// Update statistics when a request is sent
pub async fn record_request_sent(&self) {
let mut stats = self.stats.lock().await;
stats.requests_sent += 1;
stats.pending_requests += 1;
stats.max_pending_requests = stats.max_pending_requests.max(stats.pending_requests);
if self.has_backpressure() {
stats.backpressure_events += 1;
}
}
/// Update statistics when a request is received
pub async fn record_request_received(&self) {
let mut stats = self.stats.lock().await;
stats.requests_received += 1;
}
/// Update statistics when a response is sent
pub async fn record_response_sent(&self, processing_time: Duration) {
let mut stats = self.stats.lock().await;
stats.responses_sent += 1;
stats.pending_requests = stats.pending_requests.saturating_sub(1);
// Update average processing time using exponential moving average
if stats.avg_processing_time.is_zero() {
stats.avg_processing_time = processing_time;
} else {
let alpha = 0.1; // Smoothing factor
let current_nanos = stats.avg_processing_time.as_nanos() as f64;
let new_nanos = processing_time.as_nanos() as f64;
let updated_nanos = (alpha * new_nanos + (1.0 - alpha) * current_nanos) as u64;
stats.avg_processing_time = Duration::from_nanos(updated_nanos);
}
}
/// Update statistics when a request times out
pub async fn record_timeout(&self) {
let mut stats = self.stats.lock().await;
stats.requests_timeout += 1;
stats.pending_requests = stats.pending_requests.saturating_sub(1);
}
/// Update statistics when a send operation fails
pub async fn record_send_failure(&self) {
let mut stats = self.stats.lock().await;
stats.send_failures += 1;
}
}
/// Request queue for managing requests during storage unavailability
#[derive(Debug)]
pub struct RequestQueue {
/// Queued requests waiting for storage to become available
queue: VecDeque<QueuedRequest>,
/// Maximum number of requests to queue
max_size: usize,
/// Total time requests can stay in queue
max_queue_time: Duration,
}
/// A request that has been queued due to storage unavailability
#[derive(Debug)]
pub struct QueuedRequest {
/// The storage request
pub request: StorageRequest,
/// When the request was queued
pub queued_at: Instant,
/// Number of retry attempts made
pub retry_attempts: usize,
}
/// Recovery manager for handling storage unavailability and degraded performance
#[derive(Debug)]
pub struct RecoveryManager {
/// Current recovery state
state: RecoveryState,
/// Last successful operation timestamp
last_success: Option<Instant>,
/// Number of consecutive failures
consecutive_failures: usize,
/// Recovery detection configuration
recovery_config: RecoveryConfig,
}
/// Recovery state of the storage system
#[derive(Debug, Clone, PartialEq)]
pub enum RecoveryState {
/// Normal operation
Healthy,
/// Degraded performance but still functional
Degraded,
/// Storage unavailable, using fallback mechanisms
Unavailable,
/// Attempting to recover from failure
Recovering,
}
/// Configuration for recovery detection and management
#[derive(Debug, Clone)]
pub struct RecoveryConfig {
/// Number of failures before considering storage unavailable
failure_threshold: usize,
/// Time to wait before attempting recovery
recovery_delay: Duration,
/// Number of successful operations needed to consider recovery complete
#[allow(dead_code)]
success_threshold: usize,
/// Maximum time to wait for recovery
#[allow(dead_code)]
max_recovery_time: Duration,
}
impl Default for RecoveryConfig {
fn default() -> Self {
Self {
failure_threshold: 5,
recovery_delay: Duration::from_secs(10),
success_threshold: 3,
max_recovery_time: Duration::from_secs(300), // 5 minutes
}
}
}
impl RequestQueue {
/// Create a new request queue
pub fn new(max_size: usize, max_queue_time: Duration) -> Self {
Self {
queue: VecDeque::new(),
max_size,
max_queue_time,
}
}
/// Add a request to the queue
pub fn enqueue(
&mut self,
request: StorageRequest,
retry_attempts: usize,
) -> Result<(), crate::error::DualRuntimeError> {
// Remove expired requests first
self.remove_expired();
if self.queue.len() >= self.max_size {
return Err(crate::error::DualRuntimeError::Channel(
"Request queue is full".to_string(),
));
}
let queued_request = QueuedRequest {
request,
queued_at: Instant::now(),
retry_attempts,
};
self.queue.push_back(queued_request);
Ok(())
}
/// Remove and return the next request from the queue
pub fn dequeue(&mut self) -> Option<QueuedRequest> {
self.remove_expired();
self.queue.pop_front()
}
/// Get the current queue size
pub fn len(&self) -> usize {
self.queue.len()
}
/// Check if the queue is empty
pub fn is_empty(&self) -> bool {
self.queue.is_empty()
}
/// Remove expired requests from the queue
fn remove_expired(&mut self) {
let now = Instant::now();
self.queue
.retain(|req| now.duration_since(req.queued_at) < self.max_queue_time);
}
/// Get statistics about the queue
pub fn stats(&self) -> QueueStats {
let now = Instant::now();
let mut oldest_age = Duration::ZERO;
let mut total_age = Duration::ZERO;
for req in &self.queue {
let age = now.duration_since(req.queued_at);
total_age += age;
if age > oldest_age {
oldest_age = age;
}
}
let avg_age = if self.queue.is_empty() {
Duration::ZERO
} else {
total_age / self.queue.len() as u32
};
QueueStats {
current_size: self.queue.len(),
max_size: self.max_size,
oldest_request_age: oldest_age,
average_request_age: avg_age,
}
}
}
/// Statistics about the request queue
#[derive(Debug, Clone)]
pub struct QueueStats {
pub current_size: usize,
pub max_size: usize,
pub oldest_request_age: Duration,
pub average_request_age: Duration,
}
impl RecoveryManager {
/// Create a new recovery manager
pub fn new(config: RecoveryConfig) -> Self {
Self {
state: RecoveryState::Healthy,
last_success: None,
consecutive_failures: 0,
recovery_config: config,
}
}
/// Record a successful operation
pub fn record_success(&mut self) {
self.last_success = Some(Instant::now());
match self.state {
RecoveryState::Recovering => {
// Check if we have enough successes to consider recovery complete
if self.consecutive_failures == 0 {
self.state = RecoveryState::Healthy;
}
}
RecoveryState::Degraded | RecoveryState::Unavailable => {
// Start recovery process
self.state = RecoveryState::Recovering;
self.consecutive_failures = 0;
}
_ => {
self.consecutive_failures = 0;
}
}
}
/// Record a failed operation
pub fn record_failure(&mut self) {
self.consecutive_failures += 1;
match self.state {
RecoveryState::Healthy
if self.consecutive_failures >= self.recovery_config.failure_threshold / 2 =>
{
self.state = RecoveryState::Degraded;
}
RecoveryState::Degraded
if self.consecutive_failures >= self.recovery_config.failure_threshold =>
{
self.state = RecoveryState::Unavailable;
}
RecoveryState::Recovering => {
// Recovery failed, go back to unavailable
self.state = RecoveryState::Unavailable;
}
_ => {}
}
}
/// Check if recovery should be attempted
pub fn should_attempt_recovery(&self) -> bool {
match self.state {
RecoveryState::Unavailable => {
if let Some(last_success) = self.last_success {
last_success.elapsed() >= self.recovery_config.recovery_delay
} else {
true // No previous success, try recovery immediately
}
}
_ => false,
}
}
/// Get the current recovery state
pub fn state(&self) -> &RecoveryState {
&self.state
}
/// Check if the system is in a degraded state
pub fn is_degraded(&self) -> bool {
matches!(
self.state,
RecoveryState::Degraded | RecoveryState::Unavailable
)
}
/// Check if storage is available for requests
pub fn is_available(&self) -> bool {
!matches!(self.state, RecoveryState::Unavailable)
}
/// Get recovery statistics
pub fn stats(&self) -> RecoveryStats {
RecoveryStats {
state: self.state.clone(),
consecutive_failures: self.consecutive_failures,
last_success: self.last_success,
time_since_last_success: self.last_success.map(|t| t.elapsed()),
}
}
}
/// Statistics about the recovery manager
#[derive(Debug, Clone)]
pub struct RecoveryStats {
pub state: RecoveryState,
pub consecutive_failures: usize,
pub last_success: Option<Instant>,
pub time_since_last_success: Option<Duration>,
}
/// Storage client for sending requests from network runtime to storage runtime
#[derive(Clone)]
pub struct StorageClient {
/// Channel for sending storage requests
message_channel: Arc<MessageChannel>,
/// Map of pending requests waiting for responses
pending_requests: Arc<Mutex<HashMap<RequestId, oneshot::Receiver<StorageResponse>>>>,
/// Aggregate logical storage I/O from all received responses
storage_io_stats: Arc<Mutex<StorageStats>>,
/// Default timeout for storage requests
default_timeout: Duration,
/// Retry configuration
retry_config: RetryConfig,
/// Circuit breaker for handling repeated failures
circuit_breaker: Arc<Mutex<CircuitBreaker>>,
/// Request queue for managing requests during storage unavailability
request_queue: Arc<Mutex<RequestQueue>>,
/// Recovery manager for handling storage failures
recovery_manager: Arc<Mutex<RecoveryManager>>,
/// Error logger for comprehensive error tracking
error_logger: Option<Arc<ErrorLogger>>,
}
impl StorageClient {
/// Create a new storage client with the given message channel
pub fn new(message_channel: Arc<MessageChannel>, default_timeout: Duration) -> Self {
Self::with_retry_config(message_channel, default_timeout, RetryConfig::default())
}
/// Create a new storage client with custom retry configuration
pub fn with_retry_config(
message_channel: Arc<MessageChannel>,
default_timeout: Duration,
retry_config: RetryConfig,
) -> Self {
Self {
message_channel,
pending_requests: Arc::new(Mutex::new(HashMap::new())),
storage_io_stats: Arc::new(Mutex::new(StorageStats::default())),
default_timeout,
retry_config,
circuit_breaker: Arc::new(Mutex::new(CircuitBreaker::new(5, Duration::from_secs(30)))),
request_queue: Arc::new(Mutex::new(RequestQueue::new(1000, Duration::from_secs(60)))),
recovery_manager: Arc::new(Mutex::new(RecoveryManager::new(RecoveryConfig::default()))),
error_logger: crate::error_logging::get_global_error_logger(),
}
}
/// Create a new storage client with full configuration
pub fn with_full_config(
message_channel: Arc<MessageChannel>,
default_timeout: Duration,
retry_config: RetryConfig,
recovery_config: RecoveryConfig,
queue_size: usize,
queue_timeout: Duration,
) -> Self {
Self {
message_channel,
pending_requests: Arc::new(Mutex::new(HashMap::new())),
storage_io_stats: Arc::new(Mutex::new(StorageStats::default())),
default_timeout,
retry_config,
circuit_breaker: Arc::new(Mutex::new(CircuitBreaker::new(5, Duration::from_secs(30)))),
request_queue: Arc::new(Mutex::new(RequestQueue::new(queue_size, queue_timeout))),
recovery_manager: Arc::new(Mutex::new(RecoveryManager::new(recovery_config))),
error_logger: crate::error_logging::get_global_error_logger(),
}
}
/// Create a new storage client with error logger
pub fn with_error_logger(
message_channel: Arc<MessageChannel>,
default_timeout: Duration,
error_logger: Arc<ErrorLogger>,
) -> Self {
Self {
message_channel,
pending_requests: Arc::new(Mutex::new(HashMap::new())),
storage_io_stats: Arc::new(Mutex::new(StorageStats::default())),
default_timeout,
retry_config: RetryConfig::default(),
circuit_breaker: Arc::new(Mutex::new(CircuitBreaker::new(5, Duration::from_secs(30)))),
request_queue: Arc::new(Mutex::new(RequestQueue::new(1000, Duration::from_secs(60)))),
recovery_manager: Arc::new(Mutex::new(RecoveryManager::new(RecoveryConfig::default()))),
error_logger: Some(error_logger),
}
}
/// Send a storage request and wait for the response
pub async fn send_request(
&self,
command: StorageCommand,
) -> Result<RespData, crate::error::DualRuntimeError> {
self.send_request_with_timeout(command, self.default_timeout)
.await
}
/// Return aggregate logical storage I/O from responses received by this client.
pub async fn storage_io_stats(&self) -> StorageStats {
self.storage_io_stats.lock().await.clone()
}
/// Send a storage request with a custom timeout
pub async fn send_request_with_timeout(
&self,
command: StorageCommand,
timeout: Duration,
) -> Result<RespData, crate::error::DualRuntimeError> {
self.send_request_with_priority(command, timeout, RequestPriority::Normal)
.await
}
/// Send a storage request with custom timeout and priority
pub async fn send_request_with_priority(
&self,
command: StorageCommand,
timeout: Duration,
priority: RequestPriority,
) -> Result<RespData, crate::error::DualRuntimeError> {
let start_time = Instant::now();
let mut last_error = None;
// Check recovery state and handle accordingly
let recovery_state = {
let recovery_manager = self.recovery_manager.lock().await;
recovery_manager.state().clone()
};
match recovery_state {
RecoveryState::Unavailable => {
// Storage is unavailable, try fallback mechanisms
return self
.handle_storage_unavailable(command, timeout, priority)
.await;
}
RecoveryState::Degraded => {
// Storage is degraded, use more conservative approach
return self
.handle_degraded_storage(command, timeout, priority)
.await;
}
_ => {
// Normal operation or recovering
}
}
// Check circuit breaker
{
let mut circuit_breaker = self.circuit_breaker.lock().await;
if !circuit_breaker.should_allow_request() {
// Circuit breaker is open, queue the request if possible
return self
.queue_request_for_later(command, timeout, priority)
.await;
}
}
for attempt in 0..=self.retry_config.max_retries {
// Check if we have enough time left for this attempt
let elapsed = start_time.elapsed();
if elapsed >= timeout {
break;
}
let remaining_timeout = timeout - elapsed;
let attempt_result = self
.try_send_request(command.clone(), remaining_timeout, priority)
.await;
match attempt_result {
Ok(data) => {
// Success - record in circuit breaker and recovery manager
{
let mut circuit_breaker = self.circuit_breaker.lock().await;
circuit_breaker.record_success();
}
{
let mut recovery_manager = self.recovery_manager.lock().await;
recovery_manager.record_success();
}
// Process any queued requests on success
tokio::spawn({
let client = self.clone();
async move {
client.process_queued_requests().await;
}
});
return Ok(data);
}
Err(err) => {
// Log the error with correlation
if let Some(ref logger) = self.error_logger {
let correlation_id = CorrelationId::new();
let mut context = HashMap::new();
context.insert("attempt".to_string(), attempt.to_string());
context.insert(
"remaining_timeout".to_string(),
remaining_timeout.as_millis().to_string(),
);
tokio::spawn({
let logger = Arc::clone(logger);
let error = err.clone();
async move {
logger
.log_error(
error,
RuntimeContext::Network,
Some(correlation_id),
None,
context,