d-engine-core 0.2.3

Pure Raft consensus algorithm - for building custom Raft-based systems
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
use std::error::Error;

use d_engine_proto::error::ErrorCode;
use serde::Deserialize;
use serde::Serialize;
use tokio::task::JoinError;
use tonic::Code;
use tonic::Status;

/// Result type for KV operations
pub type ClientApiResult<T> = std::result::Result<T, ClientApiError>;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ClientApiError {
    /// Network layer error (retryable)
    #[serde(rename = "network")]
    Network {
        code: ErrorCode,
        message: String,
        retry_after_ms: Option<u64>,
        #[serde(skip_serializing_if = "Option::is_none")]
        leader_hint: Option<LeaderHint>,
    },

    /// Protocol layer error (client needs to check protocol compatibility)
    #[serde(rename = "protocol")]
    Protocol {
        code: ErrorCode,
        message: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        supported_versions: Option<Vec<String>>,
    },

    /// Storage layer error (internal problem on the server)
    #[serde(rename = "storage")]
    Storage { code: ErrorCode, message: String },

    /// Business logic error (client needs to adjust behavior)
    #[serde(rename = "business")]
    Business {
        code: ErrorCode,
        message: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        required_action: Option<String>,
    },

    /// General Client API error
    #[serde(rename = "general")]
    General {
        code: ErrorCode,
        message: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        required_action: Option<String>,
    },
}

// #[derive(Debug, Clone, Serialize, Deserialize)]
// pub enum NetworkErrorType {
//     Timeout,
//     ConnectionLost,
//     InvalidAddress,
//     TlsFailure,
//     ProtocolViolation,
//     JoinError,
// }

// #[derive(Debug, Clone, Serialize, Deserialize)]
// pub enum ProtocolErrorType {
//     InvalidResponseFormat,
//     VersionMismatch,
//     ChecksumFailure,
//     SerializationError,
// }

// #[derive(Debug, Clone, Serialize, Deserialize)]
// pub enum StorageErrorType {
//     DiskFull,
//     CorruptionDetected,
//     IoFailure,
//     PermissionDenied,
//     KeyNotExist,
// }

// #[derive(Debug, Clone, Serialize, Deserialize)]
// pub enum BusinessErrorType {
//     NotLeader,
//     StaleRead,
//     InvalidRequest,
//     RateLimited,
//     ClusterUnavailable,
//     ProposeFailed,
//     RetryRequired,
//     StaleTerm,
// }

// #[derive(Debug, Clone, Serialize, Deserialize)]
// pub enum GeneralErrorType {
//     General,
// }
// Re-export LeaderHint from proto (network layer use)
pub use d_engine_proto::common::LeaderHint;
impl From<tonic::transport::Error> for ClientApiError {
    /// Converts a tonic transport error into a ClientApiError
    ///
    /// This implementation handles different transport error scenarios:
    /// - Connection timeouts
    /// - Invalid URI/address formats
    /// - Unexpected connection loss
    ///
    /// # Parameters
    /// - `err`: The tonic transport error to convert
    ///
    /// # Returns
    /// A ClientApiError with appropriate error code and retry information
    fn from(err: tonic::transport::Error) -> Self {
        // Determine the error details based on the underlying error
        if let Some(io_err) = err.source().and_then(|e| e.downcast_ref::<std::io::Error>()) {
            if io_err.kind() == std::io::ErrorKind::TimedOut {
                return Self::Network {
                    code: ErrorCode::ConnectionTimeout,
                    message: format!("Connection timeout: {err}"),
                    retry_after_ms: Some(3000), // Retry after 3 seconds
                    leader_hint: None,
                };
            }
        }

        // Check for invalid address errors
        if err.to_string().contains("invalid uri") {
            return Self::Network {
                code: ErrorCode::InvalidAddress,
                message: format!("Invalid address: {err}"),
                retry_after_ms: None, // Not retryable - needs address correction
                leader_hint: None,
            };
        }

        // Default case: unexpected transport failure
        Self::Network {
            code: ErrorCode::Uncategorized,
            message: format!("Transport error: {err}"),
            retry_after_ms: Some(5000),
            leader_hint: None,
        }
    }
}

impl From<Status> for ClientApiError {
    fn from(status: Status) -> Self {
        let code = status.code();
        let message = status.message().to_string();

        match code {
            Code::Unavailable => Self::Business {
                code: ErrorCode::ClusterUnavailable,
                message,
                required_action: Some("Retry after cluster recovery".into()),
            },

            Code::Cancelled => Self::Network {
                code: ErrorCode::ConnectionTimeout,
                message,
                leader_hint: None,
                retry_after_ms: Some(1000),
            },

            Code::FailedPrecondition => {
                if let Some(leader) = parse_leader_from_metadata(&status) {
                    Self::Network {
                        code: ErrorCode::LeaderChanged,
                        message: "Leadership changed".into(),
                        retry_after_ms: Some(1000),
                        leader_hint: Some(leader),
                    }
                } else {
                    Self::Business {
                        code: ErrorCode::StaleOperation,
                        message,
                        required_action: Some("Refresh cluster state".into()),
                    }
                }
            }

            Code::InvalidArgument => Self::Business {
                code: ErrorCode::InvalidRequest,
                message,
                required_action: None,
            },

            Code::PermissionDenied => Self::Business {
                code: ErrorCode::NotLeader,
                message,
                required_action: Some("Refresh cluster state".into()),
            },

            _ => Self::Business {
                code: ErrorCode::Uncategorized,
                message: format!("Unhandled status code: {code:?}"),
                required_action: None,
            },
        }
    }
}

fn parse_leader_from_metadata(status: &Status) -> Option<LeaderHint> {
    status
        .metadata()
        .get("x-raft-leader")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| {
            // Manually parse JSON-like string
            let mut leader_id = None;
            let mut address = None;

            // Remove whitespace and outer braces
            let s = s.trim().trim_start_matches('{').trim_end_matches('}');

            // Split into key-value pairs
            for pair in s.split(',') {
                let pair = pair.trim();
                if let Some((key, value)) = pair.split_once(':') {
                    let key = key.trim().trim_matches('"');
                    let value = value.trim().trim_matches('"');

                    match key {
                        "leader_id" => leader_id = value.parse().ok(),
                        "address" => address = Some(value.to_string()),
                        _ => continue,
                    }
                }
            }

            Some(LeaderHint {
                leader_id: leader_id?,
                address: address?,
            })
        })
}

impl From<ErrorCode> for ClientApiError {
    fn from(code: ErrorCode) -> Self {
        match code {
            // Network layer errors
            ErrorCode::ConnectionTimeout => ClientApiError::Network {
                code,
                message: "Connection timeout".to_string(),
                retry_after_ms: None,
                leader_hint: None,
            },
            ErrorCode::InvalidAddress => ClientApiError::Network {
                code,
                message: "Invalid address".to_string(),
                retry_after_ms: None,
                leader_hint: None,
            },
            ErrorCode::LeaderChanged => ClientApiError::Network {
                code,
                message: "Leader changed".to_string(),
                retry_after_ms: Some(100), // suggest immediate retry
                leader_hint: None,         // Note: This would ideally be populated from context
            },
            ErrorCode::JoinError => ClientApiError::Network {
                code,
                message: "Task Join Error".to_string(),
                retry_after_ms: Some(100), // suggest immediate retry
                leader_hint: None,         // Note: This would ideally be populated from context
            },

            // Protocol layer errors
            ErrorCode::InvalidResponse => ClientApiError::Protocol {
                code,
                message: "Invalid response format".to_string(),
                supported_versions: None,
            },
            ErrorCode::VersionMismatch => ClientApiError::Protocol {
                code,
                message: "Version mismatch".to_string(),
                supported_versions: None, // Note: This would ideally be populated from context
            },

            // Storage layer errors
            ErrorCode::DiskFull => ClientApiError::Storage {
                code,
                message: "Disk full".to_string(),
            },
            ErrorCode::DataCorruption => ClientApiError::Storage {
                code,
                message: "Data corruption detected".to_string(),
            },
            ErrorCode::StorageIoError => ClientApiError::Storage {
                code,
                message: "Storage I/O error".to_string(),
            },
            ErrorCode::StoragePermissionDenied => ClientApiError::Storage {
                code,
                message: "Storage permission denied".to_string(),
            },
            ErrorCode::KeyNotExist => ClientApiError::Storage {
                code,
                message: "Key not exist in storage".to_string(),
            },

            // Business logic errors
            ErrorCode::NotLeader => ClientApiError::Business {
                code,
                message: "Not leader".to_string(),
                required_action: Some("redirect to leader".to_string()),
            },
            ErrorCode::StaleOperation => ClientApiError::Business {
                code,
                message: "Stale operation".to_string(),
                required_action: Some("refresh state and retry".to_string()),
            },
            ErrorCode::InvalidRequest => ClientApiError::Business {
                code,
                message: "Invalid request".to_string(),
                required_action: Some("check request parameters".to_string()),
            },
            ErrorCode::RateLimited => ClientApiError::Business {
                code,
                message: "Rate limited".to_string(),
                required_action: Some("wait and retry".to_string()),
            },
            ErrorCode::ClusterUnavailable => ClientApiError::Business {
                code,
                message: "Cluster unavailable".to_string(),
                required_action: Some("try again later".to_string()),
            },
            ErrorCode::ProposeFailed => ClientApiError::Business {
                code,
                message: "Propose failed".to_string(),
                required_action: Some("try again later".to_string()),
            },
            ErrorCode::Uncategorized => ClientApiError::Business {
                code,
                message: "Uncategorized error".to_string(),
                required_action: None,
            },
            ErrorCode::TermOutdated => ClientApiError::Business {
                code,
                message: "Stale term error".to_string(),
                required_action: None,
            },
            ErrorCode::RetryRequired => ClientApiError::Business {
                code,
                message: "Retry required. Please try again.".to_string(),
                required_action: None,
            },

            // Unclassified error
            ErrorCode::General => ClientApiError::General {
                code,
                message: "General Client Api error".to_string(),
                required_action: None,
            },
            // Success case - should normally not be converted to error
            ErrorCode::Success => unreachable!(),
        }
    }
}

impl ClientApiError {
    /// Returns the error code associated with this error
    pub fn code(&self) -> ErrorCode {
        match self {
            ClientApiError::Network { code, .. } => *code,
            ClientApiError::Protocol { code, .. } => *code,
            ClientApiError::Storage { code, .. } => *code,
            ClientApiError::Business { code, .. } => *code,
            ClientApiError::General { code, .. } => *code,
        }
    }

    /// Returns the error message
    pub fn message(&self) -> &str {
        match self {
            ClientApiError::Network { message, .. } => message,
            ClientApiError::Protocol { message, .. } => message,
            ClientApiError::Storage { message, .. } => message,
            ClientApiError::Business { message, .. } => message,
            ClientApiError::General { message, .. } => message,
        }
    }
}

impl From<JoinError> for ClientApiError {
    fn from(_err: JoinError) -> Self {
        ErrorCode::JoinError.into()
    }
}
impl From<std::io::Error> for ClientApiError {
    fn from(_err: std::io::Error) -> Self {
        ErrorCode::StorageIoError.into()
    }
}

impl ClientApiError {
    pub fn general_client_error(message: String) -> Self {
        ClientApiError::General {
            code: ErrorCode::General,
            message,
            required_action: None,
        }
    }
}

impl std::fmt::Display for ClientApiError {
    fn fmt(
        &self,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        write!(f, "{:?}: {}", self.code(), self.message())
    }
}

impl std::error::Error for ClientApiError {}