1use std::any::Any;
16use std::sync::Arc;
17
18use common_error::ext::{ErrorExt, RetryHint, retry_hint_from_io_error};
19use common_error::status_code::StatusCode;
20use common_macro::stack_trace_debug;
21use common_runtime::error::Error as RuntimeError;
22use common_wal::kafka::rskafka_client_error_to_retry_hint;
23use object_store::error::retry_hint_from_opendal_error;
24use serde_json::error::Error as JsonError;
25use snafu::{Location, Snafu};
26use store_api::storage::RegionId;
27
28#[derive(Snafu)]
29#[snafu(visibility(pub))]
30#[stack_trace_debug]
31pub enum Error {
32 #[snafu(display("Failed to create TLS Config"))]
33 TlsConfig {
34 #[snafu(implicit)]
35 location: Location,
36 source: common_wal::error::Error,
37 },
38
39 #[snafu(display("Invalid provider type, expected: {}, actual: {}", expected, actual))]
40 InvalidProvider {
41 #[snafu(implicit)]
42 location: Location,
43 expected: String,
44 actual: String,
45 },
46
47 #[snafu(display("Failed to start log store task: {}", name))]
48 StartWalTask {
49 name: String,
50 #[snafu(implicit)]
51 location: Location,
52 source: RuntimeError,
53 },
54
55 #[snafu(display("Failed to stop log store task: {}", name))]
56 StopWalTask {
57 name: String,
58 #[snafu(implicit)]
59 location: Location,
60 source: RuntimeError,
61 },
62
63 #[snafu(display("Failed to add entry to LogBatch"))]
64 AddEntryLogBatch {
65 #[snafu(source)]
66 error: raft_engine::Error,
67 #[snafu(implicit)]
68 location: Location,
69 },
70
71 #[snafu(display("Failed to perform raft-engine operation"))]
72 RaftEngine {
73 #[snafu(source)]
74 error: raft_engine::Error,
75 #[snafu(implicit)]
76 location: Location,
77 },
78
79 #[snafu(display("Failed to perform IO on path: {}", path))]
80 Io {
81 path: String,
82 #[snafu(source)]
83 error: std::io::Error,
84 #[snafu(implicit)]
85 location: Location,
86 },
87
88 #[snafu(display("Failed to join a blocking task of the log store"))]
89 Join {
90 #[snafu(source)]
91 error: tokio::task::JoinError,
92 #[snafu(implicit)]
93 location: Location,
94 },
95
96 #[snafu(display("Object store WAL I/O permit is already installed"))]
97 WalIoPermitAlreadyInstalled {
98 #[snafu(implicit)]
99 location: Location,
100 },
101
102 #[snafu(display("Log store not started yet"))]
103 IllegalState {
104 #[snafu(implicit)]
105 location: Location,
106 },
107
108 #[snafu(display("Namespace is illegal: {}", ns))]
109 IllegalNamespace {
110 ns: u64,
111 #[snafu(implicit)]
112 location: Location,
113 },
114
115 #[snafu(display(
116 "Failed to fetch entries from namespace: {}, start: {}, end: {}, max size: {}",
117 ns,
118 start,
119 end,
120 max_size,
121 ))]
122 FetchEntry {
123 ns: u64,
124 start: u64,
125 end: u64,
126 max_size: usize,
127 #[snafu(source)]
128 error: raft_engine::Error,
129 #[snafu(implicit)]
130 location: Location,
131 },
132
133 #[snafu(display(
134 "Cannot override compacted entry, namespace: {}, first index: {}, attempt index: {}",
135 namespace,
136 first_index,
137 attempt_index
138 ))]
139 OverrideCompactedEntry {
140 namespace: u64,
141 first_index: u64,
142 attempt_index: u64,
143 #[snafu(implicit)]
144 location: Location,
145 },
146
147 #[snafu(display(
148 "Failed to build a Kafka client, broker endpoints: {:?}",
149 broker_endpoints
150 ))]
151 BuildClient {
152 broker_endpoints: Vec<String>,
153 #[snafu(implicit)]
154 location: Location,
155 #[snafu(source)]
156 error: rskafka::client::error::Error,
157 },
158
159 #[snafu(display(
160 "Failed to build a Kafka partition client, topic: {}, partition: {}",
161 topic,
162 partition
163 ))]
164 BuildPartitionClient {
165 topic: String,
166 partition: i32,
167 #[snafu(implicit)]
168 location: Location,
169 #[snafu(source)]
170 error: rskafka::client::error::Error,
171 },
172
173 #[snafu(display("Missing required key in a record"))]
174 MissingKey {
175 #[snafu(implicit)]
176 location: Location,
177 },
178
179 #[snafu(display("Missing required value in a record"))]
180 MissingValue {
181 #[snafu(implicit)]
182 location: Location,
183 },
184
185 #[snafu(display("Failed to produce records to Kafka, topic: {}, size: {}", topic, size))]
186 ProduceRecord {
187 topic: String,
188 size: usize,
189 #[snafu(implicit)]
190 location: Location,
191 #[snafu(source)]
192 error: rskafka::client::producer::Error,
193 },
194
195 #[snafu(display("Failed to produce batch records to Kafka"))]
196 BatchProduce {
197 #[snafu(implicit)]
198 location: Location,
199 #[snafu(source)]
200 error: rskafka::client::error::Error,
201 },
202
203 #[snafu(display("Failed to read a record from Kafka, topic: {}", topic))]
204 ConsumeRecord {
205 topic: String,
206 #[snafu(implicit)]
207 location: Location,
208 #[snafu(source)]
209 error: rskafka::client::error::Error,
210 },
211
212 #[snafu(display("Failed to get the latest offset, topic: {}", topic))]
213 GetOffset {
214 topic: String,
215 #[snafu(implicit)]
216 location: Location,
217 #[snafu(source)]
218 error: rskafka::client::error::Error,
219 },
220
221 #[snafu(display("Failed to do a cast"))]
222 Cast {
223 #[snafu(implicit)]
224 location: Location,
225 },
226
227 #[snafu(display("Failed to encode object into json"))]
228 EncodeJson {
229 #[snafu(implicit)]
230 location: Location,
231 #[snafu(source)]
232 error: JsonError,
233 },
234
235 #[snafu(display("Failed to decode object from json"))]
236 DecodeJson {
237 #[snafu(implicit)]
238 location: Location,
239 #[snafu(source)]
240 error: JsonError,
241 },
242
243 #[snafu(display("The record sequence is not legal, error: {}", error))]
244 IllegalSequence {
245 #[snafu(implicit)]
246 location: Location,
247 error: String,
248 },
249
250 #[snafu(display(
251 "Attempt to append discontinuous log entry, region: {}, last index: {}, attempt index: {}",
252 region_id,
253 last_index,
254 attempt_index
255 ))]
256 DiscontinuousLogIndex {
257 region_id: RegionId,
258 last_index: u64,
259 attempt_index: u64,
260 },
261
262 #[snafu(display("OrderedBatchProducer is stopped",))]
263 OrderedBatchProducerStopped {
264 #[snafu(implicit)]
265 location: Location,
266 },
267
268 #[snafu(display("Failed to wait for ProduceResultReceiver"))]
269 WaitProduceResultReceiver {
270 #[snafu(implicit)]
271 location: Location,
272 #[snafu(source)]
273 error: tokio::sync::oneshot::error::RecvError,
274 },
275
276 #[snafu(display(
277 "The length of meta if exceeded the limit: {}, actual: {}",
278 limit,
279 actual
280 ))]
281 MetaLengthExceededLimit {
282 #[snafu(implicit)]
283 location: Location,
284 limit: usize,
285 actual: usize,
286 },
287
288 #[snafu(display("No max value"))]
289 NoMaxValue {
290 #[snafu(implicit)]
291 location: Location,
292 },
293
294 #[snafu(display("Corrupted WAL object, {}", reason))]
295 CorruptedWalObject {
296 reason: String,
297 #[snafu(implicit)]
298 location: Location,
299 },
300
301 #[snafu(display("Invalid WAL object store, {}", reason))]
302 InvalidWalObjectStore {
303 reason: String,
304 #[snafu(implicit)]
305 location: Location,
306 },
307
308 #[snafu(display(
309 "Object store WAL region mismatch, supplied region: {}, {}",
310 region_id,
311 reason
312 ))]
313 MismatchedWalRegion {
314 region_id: RegionId,
315 reason: String,
316 #[snafu(implicit)]
317 location: Location,
318 },
319
320 #[snafu(display(
321 "Invalid WAL entry range, region: {}, start: {}, end: {}",
322 region_id,
323 start_entry_id,
324 end_entry_id
325 ))]
326 InvalidWalEntryRange {
327 region_id: RegionId,
328 start_entry_id: u64,
329 end_entry_id: u64,
330 #[snafu(implicit)]
331 location: Location,
332 },
333
334 #[snafu(display("Incomplete multipart WAL entry of region {}", region_id))]
335 IncompleteWalEntry {
336 region_id: RegionId,
337 #[snafu(implicit)]
338 location: Location,
339 },
340
341 #[snafu(display("WAL object sequence is exhausted, last sequence: {}", last_object_seq))]
342 WalObjectSequenceExhausted {
343 last_object_seq: u64,
344 #[snafu(implicit)]
345 location: Location,
346 },
347
348 #[snafu(display(
349 "WAL object sequence {} is not settled: the open batch has assigned entry ids under it",
350 object_seq
351 ))]
352 WalObjectSequenceUnsettled {
353 object_seq: u64,
354 #[snafu(implicit)]
355 location: Location,
356 },
357
358 #[snafu(display(
359 "WAL entry positions of region {} in one object are exhausted",
360 region_id
361 ))]
362 WalEntryPositionExhausted {
363 region_id: RegionId,
364 #[snafu(implicit)]
365 location: Location,
366 },
367
368 #[snafu(display("WAL object already exists with different content, path: {}", path))]
369 WalObjectConflict {
370 path: String,
371 #[snafu(implicit)]
372 location: Location,
373 },
374
375 #[snafu(display(
376 "WAL object {} was written by the earlier epoch {}, this store writes epoch {}",
377 path,
378 existing_epoch,
379 epoch
380 ))]
381 StaleWalObject {
382 path: String,
383 existing_epoch: u64,
384 epoch: u64,
385 #[snafu(implicit)]
386 location: Location,
387 },
388
389 #[snafu(display(
390 "WAL object {} that starts epoch {} was already present, so the open cannot tell whether it wrote it",
391 path,
392 epoch
393 ))]
394 UnconfirmedWalEpochStart {
395 path: String,
396 epoch: u64,
397 #[snafu(implicit)]
398 location: Location,
399 },
400
401 #[snafu(display("Failed to {} WAL object, path: {}", operation, path))]
402 WalObjectStore {
403 operation: &'static str,
404 path: String,
405 #[snafu(source)]
406 error: object_store::Error,
407 #[snafu(implicit)]
408 location: Location,
409 },
410
411 #[snafu(display("Failed to fetch a segment of WAL object, path: {}", path))]
412 WalSegmentFetch {
413 path: String,
414 #[snafu(source)]
415 error: tokio::task::JoinError,
416 #[snafu(implicit)]
417 location: Location,
418 },
419
420 #[snafu(display("Invalid WAL object, path: {}", path))]
421 InvalidWalObject {
422 path: String,
423 #[snafu(source(from(Error, Box::new)))]
424 source: Box<Error>,
425 #[snafu(implicit)]
426 location: Location,
427 },
428
429 #[snafu(display(
430 "Object store WAL prefix mismatch, expected: {}, actual: {}",
431 expected,
432 actual
433 ))]
434 MismatchedWalPrefix {
435 expected: String,
436 actual: String,
437 #[snafu(implicit)]
438 location: Location,
439 },
440
441 #[snafu(display(
442 "Object store WAL prefix {} on {} does not hold the history of region {}: {}. \
443 If the WAL was moved, stop the instance, copy every object under the prefix from the \
444 old location to this one and start again. If the old WAL is lost, start once with \
445 `[wal].accept_missing_history = true`, which opens the region without its writes that \
446 were not flushed, and turn the option off again once the instance has written to the WAL",
447 prefix,
448 storage,
449 region_id,
450 reason
451 ))]
452 MissingWalHistory {
453 region_id: RegionId,
454 prefix: String,
455 storage: String,
457 reason: String,
458 #[snafu(implicit)]
459 location: Location,
460 },
461
462 #[snafu(display(
463 "Source WAL prefix {prefix} on {storage} does not hold the history of region {region_id}: {reason}. \
464 Check the source node prefix and whether its WAL objects were reclaimed or moved"
465 ))]
466 MissingSourceWalHistory {
467 region_id: RegionId,
468 prefix: String,
469 storage: String,
470 reason: String,
471 #[snafu(implicit)]
472 location: Location,
473 },
474
475 #[snafu(display(
476 "Object store WAL gave up its start object {} after refusing a region without its history, and accepts nothing more until it opens again",
477 path
478 ))]
479 WalStartWithdrawn {
480 path: String,
481 #[snafu(implicit)]
482 location: Location,
483 },
484
485 #[snafu(display("Object store WAL log store is stopped"))]
486 ObjectStoreWalStopped {
487 #[snafu(implicit)]
488 location: Location,
489 },
490
491 #[snafu(display("Object store WAL node lease is unavailable or expired"))]
492 ObjectStoreWalLeaseExpired {
493 #[snafu(implicit)]
494 location: Location,
495 },
496
497 #[snafu(display("Object store WAL operation failed"))]
498 ObjectStoreWal {
499 source: Arc<Error>,
500 #[snafu(implicit)]
501 location: Location,
502 },
503
504 #[snafu(display(
505 "Object store WAL rejects appends until the object store accepts its acknowledged backlog"
506 ))]
507 ObjectStoreWalFailing {
508 source: Arc<Error>,
509 #[snafu(implicit)]
510 location: Location,
511 },
512}
513
514pub type Result<T> = std::result::Result<T, Error>;
515
516fn rskafka_client_error_to_status_code(error: &rskafka::client::error::Error) -> StatusCode {
517 match error {
518 rskafka::client::error::Error::Connection(_)
519 | rskafka::client::error::Error::Request(_)
520 | rskafka::client::error::Error::InvalidResponse(_)
521 | rskafka::client::error::Error::ServerError { .. }
522 | rskafka::client::error::Error::RetryFailed(_) => StatusCode::Internal,
523 rskafka::client::error::Error::Timeout => StatusCode::StorageUnavailable,
524 _ => StatusCode::Internal,
525 }
526}
527
528impl ErrorExt for Error {
529 fn as_any(&self) -> &dyn Any {
530 self
531 }
532
533 fn status_code(&self) -> StatusCode {
534 use Error::*;
535
536 match self {
537 TlsConfig { .. }
538 | InvalidProvider { .. }
539 | IllegalNamespace { .. }
540 | MissingKey { .. }
541 | MissingValue { .. }
542 | OverrideCompactedEntry { .. }
543 | InvalidWalObjectStore { .. }
544 | MismatchedWalPrefix { .. }
545 | MissingWalHistory { .. }
546 | MissingSourceWalHistory { .. }
547 | MismatchedWalRegion { .. }
548 | IncompleteWalEntry { .. }
549 | InvalidWalEntryRange { .. } => StatusCode::InvalidArguments,
550 StartWalTask { .. }
551 | StopWalTask { .. }
552 | Join { .. }
553 | IllegalState { .. }
554 | NoMaxValue { .. }
555 | Cast { .. }
556 | EncodeJson { .. }
557 | DecodeJson { .. }
558 | IllegalSequence { .. }
559 | DiscontinuousLogIndex { .. }
560 | OrderedBatchProducerStopped { .. }
561 | WaitProduceResultReceiver { .. }
562 | MetaLengthExceededLimit { .. }
563 | ObjectStoreWalStopped { .. }
564 | WalStartWithdrawn { .. }
565 | WalSegmentFetch { .. } => StatusCode::Internal,
566
567 CorruptedWalObject { .. }
568 | WalObjectConflict { .. }
569 | WalObjectSequenceExhausted { .. }
570 | WalEntryPositionExhausted { .. } => StatusCode::Unexpected,
571 WalObjectSequenceUnsettled { .. } | WalIoPermitAlreadyInstalled { .. } => {
572 StatusCode::IllegalState
573 }
574
575 InvalidWalObject { source, .. } => source.status_code(),
576 ObjectStoreWal { source, .. } => source.status_code(),
577 ObjectStoreWalFailing { .. } => StatusCode::StorageUnavailable,
578 ObjectStoreWalLeaseExpired { .. } => StatusCode::RegionNotReady,
579
580 WalObjectStore { .. }
582 | StaleWalObject { .. }
583 | UnconfirmedWalEpochStart { .. }
584 | Io { .. } => StatusCode::StorageUnavailable,
585 FetchEntry { .. } | RaftEngine { .. } | AddEntryLogBatch { .. } => {
587 StatusCode::StorageUnavailable
588 }
589 ProduceRecord { error, .. } => match error {
591 rskafka::client::producer::Error::Client(error) => {
592 rskafka_client_error_to_status_code(error)
593 }
594 rskafka::client::producer::Error::Aggregator(_)
595 | rskafka::client::producer::Error::FlushError(_)
596 | rskafka::client::producer::Error::TooLarge => StatusCode::Internal,
597 },
598 BuildClient { error, .. }
599 | BuildPartitionClient { error, .. }
600 | BatchProduce { error, .. }
601 | GetOffset { error, .. }
602 | ConsumeRecord { error, .. } => rskafka_client_error_to_status_code(error),
603 }
604 }
605
606 fn retry_hint(&self) -> RetryHint {
607 use Error::*;
608
609 match self {
610 WalObjectStore { error, .. } => retry_hint_from_opendal_error(error),
611 ObjectStoreWal { source, .. } => source.retry_hint(),
612 Io { error, .. } => retry_hint_from_io_error(error),
613 FetchEntry { .. }
614 | RaftEngine { .. }
615 | AddEntryLogBatch { .. }
616 | WalObjectSequenceUnsettled { .. }
617 | StaleWalObject { .. }
618 | UnconfirmedWalEpochStart { .. }
619 | ObjectStoreWalFailing { .. } => RetryHint::Retryable,
620 ObjectStoreWalLeaseExpired { .. } => RetryHint::RetryAfterRouteRefresh,
621 ProduceRecord { error, .. } => match error {
622 rskafka::client::producer::Error::Client(error) => {
623 rskafka_client_error_to_retry_hint(error)
624 }
625 rskafka::client::producer::Error::Aggregator(_)
626 | rskafka::client::producer::Error::FlushError(_)
627 | rskafka::client::producer::Error::TooLarge => RetryHint::NonRetryable,
628 },
629 BuildClient { error, .. }
630 | BuildPartitionClient { error, .. }
631 | BatchProduce { error, .. }
632 | GetOffset { error, .. }
633 | ConsumeRecord { error, .. } => rskafka_client_error_to_retry_hint(error),
634 _ => RetryHint::NonRetryable,
635 }
636 }
637}