risingwave_error/tonic/extra.rs
1// Copyright 2025 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use serde::{Deserialize, Serialize};
16
17use crate::code::PostgresErrorCode;
18use crate::error_request_copy;
19
20/// The score of the error.
21///
22/// Currently, it's used to identify the root cause of streaming pipeline failures, i.e., which actor
23/// led to the failure.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
25pub struct Score(pub i32);
26
27/// A error with a score, used to find the root cause of multiple failures.
28#[derive(Debug, Clone)]
29pub struct ScoredError<E> {
30 pub error: E,
31 pub score: Score,
32}
33
34impl<E: std::fmt::Display> std::fmt::Display for ScoredError<E> {
35 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36 self.error.fmt(f)
37 }
38}
39
40impl<E: std::error::Error> std::error::Error for ScoredError<E> {
41 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
42 self.error.source()
43 }
44
45 fn provide<'a>(&'a self, request: &mut std::error::Request<'a>) {
46 self.error.provide(request);
47 // HIGHLIGHT: Provide the score to make it retrievable from meta service.
48 request.provide_value(self.score);
49 }
50}
51
52/// Extra fields in errors that can be passed through the gRPC boundary.
53///
54/// - Field being set to `None` means it is not available.
55/// - To add a new field, also update the `provide` method.
56#[derive(Debug, Default, Clone, Serialize, Deserialize)]
57pub(super) struct Extra {
58 score: Option<Score>,
59 code: Option<PostgresErrorCode>,
60}
61
62impl Extra {
63 /// Create a new [`Extra`] by [requesting](std::error::request_ref) each field from the given error.
64 pub fn new<T>(error: &T) -> Self
65 where
66 T: ?Sized + std::error::Error,
67 {
68 Self {
69 score: error_request_copy(error),
70 code: error_request_copy(error),
71 }
72 }
73
74 /// Provide each field to the given [request](std::error::Request).
75 pub fn provide<'a>(&'a self, request: &mut std::error::Request<'a>) {
76 if let Some(score) = self.score {
77 request.provide_value(score);
78 }
79 if let Some(code) = self.code {
80 request.provide_value(code);
81 }
82 }
83}