re_redap_client 0.36.1

Official gRPC client for the Rerun Data Protocol
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
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
use std::sync::Arc;

use crate::connection_registry::ClientCredentialsError;
use crate::extract_trace_id;

#[derive(Clone, Debug)]
pub struct ApiError {
    /// A message that does NOT include the contents of [`Self::source`].
    pub message: String,

    pub kind: ApiErrorKind,

    pub source: Option<Arc<dyn std::error::Error + Send + Sync + 'static>>,

    /// When the error comes from the server returning a trace id, we include it in the client
    /// error for easier reporting.
    trace_id: Option<opentelemetry::TraceId>,
}

/// Convenience for `Result<T, ApiError>`
pub type ApiResult<T = ()> = Result<T, ApiError>;

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ApiErrorKind {
    NotFound,
    AlreadyExists,
    PermissionDenied,
    Unauthenticated,

    /// The gRPC endpoint has not been implemented.
    Unimplemented,
    Connection,
    Timeout,
    Internal,
    InvalidArguments,
    FailedPrecondition,
    ResourcesExhausted,

    /// Failed to decode data received from the server (e.g. protobuf → Arrow conversion).
    Deserialization,

    /// Failed to encode data for sending to the server.
    Serialization,

    InvalidServer,
}

impl From<tonic::Code> for ApiErrorKind {
    fn from(code: tonic::Code) -> Self {
        match code {
            tonic::Code::NotFound => Self::NotFound,
            tonic::Code::AlreadyExists => Self::AlreadyExists,
            tonic::Code::PermissionDenied => Self::PermissionDenied,
            tonic::Code::ResourceExhausted => Self::ResourcesExhausted,
            tonic::Code::Unauthenticated => Self::Unauthenticated,
            tonic::Code::Unimplemented => Self::Unimplemented,
            tonic::Code::Unavailable => Self::Connection,
            tonic::Code::InvalidArgument => Self::InvalidArguments,
            tonic::Code::FailedPrecondition => Self::FailedPrecondition,
            tonic::Code::DeadlineExceeded => Self::Timeout,
            _ => Self::Internal,
        }
    }
}

impl ApiErrorKind {
    /// Transient errors that may succeed on retry (with backoff).
    pub fn is_retryable(self) -> bool {
        match self {
            Self::Connection | Self::Timeout | Self::Internal | Self::ResourcesExhausted => true,

            Self::NotFound
            | Self::AlreadyExists
            | Self::PermissionDenied
            | Self::Unauthenticated
            | Self::Unimplemented
            | Self::InvalidArguments
            | Self::FailedPrecondition
            | Self::Deserialization
            | Self::Serialization
            | Self::InvalidServer => false,
        }
    }
}

impl std::fmt::Display for ApiErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotFound => write!(f, "NotFound"),
            Self::AlreadyExists => write!(f, "AlreadyExists"),
            Self::PermissionDenied => write!(f, "PermissionDenied"),
            Self::Unauthenticated => write!(f, "Unauthenticated"),
            Self::Unimplemented => write!(f, "Unimplemented"),
            Self::Connection => write!(f, "Connection"),
            Self::Internal => write!(f, "Internal"),
            Self::InvalidArguments => write!(f, "InvalidArguments"),
            Self::FailedPrecondition => write!(f, "FailedPrecondition"),
            Self::ResourcesExhausted => write!(f, "ResourcesExhausted"),
            Self::Deserialization => write!(f, "Deserialization"),
            Self::Serialization => write!(f, "Serialization"),
            Self::Timeout => write!(f, "Timeout"),
            Self::InvalidServer => write!(f, "InvalidServer"),
        }
    }
}

impl ApiError {
    #[inline]
    fn new(kind: ApiErrorKind, message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            kind,
            source: None,
            trace_id: None,
        }
    }

    /// Do NOT include `err` in the `message` - it will be added for you.
    #[inline]
    fn new_with_source(
        err: impl std::error::Error + Send + Sync + 'static,
        kind: ApiErrorKind,
        message: impl Into<String>,
    ) -> Self {
        Self {
            message: message.into(),
            kind,
            source: Some(Arc::new(err)),
            trace_id: None,
        }
    }

    /// Do NOT include `err` in the `message` - it will be added for you.
    #[inline]
    fn new_with_source_and_trace_id(
        err: impl std::error::Error + Send + Sync + 'static,
        kind: ApiErrorKind,
        message: impl Into<String>,
        trace_id: opentelemetry::TraceId,
    ) -> Self {
        Self {
            message: message.into(),
            kind,
            source: Some(Arc::new(err)),
            trace_id: Some(trace_id),
        }
    }

    /// Construct an [`ApiError`] with an explicit `kind` and an optional `trace_id`.
    ///
    /// Do NOT include `err` in the `message` - it will be added for you.
    pub fn with_kind_and_source(
        kind: ApiErrorKind,
        trace_id: Option<opentelemetry::TraceId>,
        err: impl std::error::Error + Send + Sync + 'static,
        message: impl Into<String>,
    ) -> Self {
        Self {
            message: message.into(),
            kind,
            source: Some(Arc::new(err)),
            trace_id,
        }
    }

    /// Convert an unsuccessful HTTP status into an [`ApiError`].
    ///
    /// Authentication, authorization, missing-resource, precondition, and throttling responses map
    /// to their corresponding API error kinds.
    /// Server errors are treated as connection failures so callers may retry them.
    /// Other statuses indicate that the server did not honor the expected HTTP protocol.
    pub fn http_status(
        trace_id: Option<opentelemetry::TraceId>,
        status: u16,
        message: impl Into<String>,
    ) -> Self {
        Self::http_status_with_source(
            trace_id,
            status,
            std::io::Error::other(format!("HTTP {status}")),
            message,
        )
    }

    /// Convert an unsuccessful HTTP status into an [`ApiError`] with a specific source error.
    ///
    /// Do NOT include `err` in the `message` - it will be added for you.
    pub fn http_status_with_source(
        trace_id: Option<opentelemetry::TraceId>,
        status: u16,
        err: impl std::error::Error + Send + Sync + 'static,
        message: impl Into<String>,
    ) -> Self {
        let kind = match status {
            401 => ApiErrorKind::Unauthenticated,
            403 => ApiErrorKind::PermissionDenied,
            404 => ApiErrorKind::NotFound,
            412 => ApiErrorKind::FailedPrecondition,
            429 => ApiErrorKind::ResourcesExhausted,
            500..=599 => ApiErrorKind::Connection,
            _ => ApiErrorKind::InvalidServer,
        };
        Self::with_kind_and_source(kind, trace_id, err, message)
    }

    /// Do NOT include `err` in the `message` - it will be added for you.
    pub fn tonic(err: tonic::Status, message: impl Into<String>) -> Self {
        let message = message.into();
        let kind = ApiErrorKind::from(err.code());

        // On the web, the browser blocks failed `fetch` calls (CORS, mixed content, server
        // unreachable, DNS, …) and — for security reasons — hides the actual cause from
        // JavaScript, surfacing only an opaque message (e.g. `TypeError: Failed to fetch` in
        // Chrome, `NetworkError when attempting to fetch resource` in Firefox, `Load failed` in
        // Safari). `tonic-web-wasm-client` wraps all of these as `Error::JsError`, which tonic
        // turns into a `Code::Unknown` status whose message is prefixed `js api error:`.
        //
        // Note: other `Code::Unknown` variants (malformed response, missing content-type, …)
        // mean the server *did* respond but with non-gRPC data (wrong port, a proxy serving
        // HTML, …) — those are not network failures, so we deliberately don't add the hint there.
        //
        // Point the user at the developer console, where the browser *does* print the real
        // reason (e.g. the missing CORS header).
        #[cfg(target_arch = "wasm32")]
        let (kind, message) = if err.code() == tonic::Code::Unknown
            && err.message().to_ascii_lowercase().contains("js api error")
        {
            (
                ApiErrorKind::Connection,
                format!(
                    "{message}: failed to reach the server. \
                     This is often a CORS issue, but can also mean the server is unreachable. \
                     Open your browser's developer console for the underlying error."
                ),
            )
        } else {
            (kind, message)
        };

        let trace_id = extract_trace_id(err.metadata());
        let err = crate::TonicStatusError::from(err); // Wrap in TonicStatusError so we get our nice Display formatting
        if let Some(trace_id) = trace_id {
            Self::new_with_source_and_trace_id(err, kind, message, trace_id)
        } else {
            Self::new_with_source(err, kind, message)
        }
    }

    /// Sets the trace-id if not already set.
    #[must_use]
    pub fn with_trace_id(mut self, trace_id: Option<opentelemetry::TraceId>) -> Self {
        if self.trace_id.is_none() {
            self.trace_id = trace_id;
        }
        self
    }

    /// Failed to decode data received from the server.
    pub fn deserialization(
        trace_id: Option<opentelemetry::TraceId>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            message: message.into(),
            kind: ApiErrorKind::Deserialization,
            source: None,
            trace_id,
        }
    }

    /// Failed to decode data received from the server.
    ///
    /// Do NOT include `err` in the `message` - it will be added for you.
    pub fn deserialization_with_source(
        trace_id: Option<opentelemetry::TraceId>,
        err: impl std::error::Error + Send + Sync + 'static,
        message: impl Into<String>,
    ) -> Self {
        Self {
            message: message.into(),
            kind: ApiErrorKind::Deserialization,
            source: Some(Arc::new(err)),
            trace_id,
        }
    }

    /// Failed to decode a quiver record batch received from the server.
    ///
    /// Decoding server data is a [`ApiErrorKind::Deserialization`]; the quiver error names the
    /// offending column and the exact mismatch, so no extra message is needed.
    pub fn deserialization_quiver(
        trace_id: Option<opentelemetry::TraceId>,
        err: quiver::Error,
    ) -> Self {
        Self {
            message: "failed to decode record batch".to_owned(),
            kind: ApiErrorKind::Deserialization,
            source: Some(Arc::new(err)),
            trace_id,
        }
    }

    /// Like [`Self::deserialization_quiver`], but names where the batch came from (the endpoint or
    /// response stream); the quiver error itself only describes the schema mismatch.
    pub fn deserialization_quiver_from(
        trace_id: Option<opentelemetry::TraceId>,
        err: quiver::Error,
        context: impl std::fmt::Display,
    ) -> Self {
        Self {
            message: format!("failed to decode record batch from {context}"),
            kind: ApiErrorKind::Deserialization,
            source: Some(Arc::new(err)),
            trace_id,
        }
    }

    /// Failed to encode data for sending to the server.
    pub fn serialization(message: impl Into<String>) -> Self {
        Self::new(ApiErrorKind::Serialization, message)
    }

    /// Failed to encode a quiver record batch for sending to the server.
    pub fn serialization_quiver(err: quiver::Error) -> Self {
        Self::new_with_source(
            err,
            ApiErrorKind::Serialization,
            "failed to encode record batch",
        )
    }

    /// Failed to encode data for sending to the server.
    ///
    /// Do NOT include `err` in the `message` - it will be added for you.
    pub fn serialization_with_source(
        err: impl std::error::Error + Send + Sync + 'static,
        message: impl Into<String>,
    ) -> Self {
        Self::new_with_source(err, ApiErrorKind::Serialization, message)
    }

    /// Do NOT include `err` in the `message` - it will be added for you.
    pub fn invalid_arguments_with_source(
        trace_id: Option<opentelemetry::TraceId>,
        err: impl std::error::Error + Send + Sync + 'static,
        message: impl Into<String>,
    ) -> Self {
        Self {
            message: message.into(),
            kind: ApiErrorKind::InvalidArguments,
            source: Some(Arc::new(err)),
            trace_id,
        }
    }

    pub fn invalid_arguments(message: impl Into<String>) -> Self {
        Self::new(ApiErrorKind::InvalidArguments, message)
    }

    pub fn internal(message: impl Into<String>) -> Self {
        Self::new(ApiErrorKind::Internal, message)
    }

    /// Failed to decode a quiver record batch. The quiver error names the offending column and the
    /// record-batch schema, so no extra message is needed.
    pub fn internal_quiver(err: quiver::Error) -> Self {
        Self::new_with_source(err, ApiErrorKind::Internal, "failed to decode record batch")
    }

    /// Do NOT include `err` in the `message` - it will be added for you.
    pub fn internal_with_source(
        trace_id: Option<opentelemetry::TraceId>,
        err: impl std::error::Error + Send + Sync + 'static,
        message: impl Into<String>,
    ) -> Self {
        Self {
            message: message.into(),
            kind: ApiErrorKind::Internal,
            source: Some(Arc::new(err)),
            trace_id,
        }
    }

    /// Do NOT include `err` in the `message` - it will be added for you.
    pub fn connection_with_source(
        trace_id: Option<opentelemetry::TraceId>,
        err: impl std::error::Error + Send + Sync + 'static,
        message: impl Into<String>,
    ) -> Self {
        Self {
            message: message.into(),
            kind: ApiErrorKind::Connection,
            source: Some(Arc::new(err)),
            trace_id,
        }
    }

    pub fn connection(message: impl Into<String>) -> Self {
        Self::new(ApiErrorKind::Connection, message)
    }

    pub fn permission_denied(
        trace_id: Option<opentelemetry::TraceId>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            message: message.into(),
            kind: ApiErrorKind::PermissionDenied,
            source: None,
            trace_id,
        }
    }

    /// Do NOT include `err` in the `message` - it will be added for you.
    pub fn credentials_with_source(
        trace_id: Option<opentelemetry::TraceId>,
        err: ClientCredentialsError,
        message: impl Into<String>,
    ) -> Self {
        Self {
            message: message.into(),
            kind: ApiErrorKind::Unauthenticated,
            source: Some(Arc::new(err)),
            trace_id,
        }
    }

    /// Raised when `GET /version` against the requested origin returns a non-2xx response.
    ///
    /// The included status line and body snippet usually tell the user whether the path is
    /// wrong (404 from a non-Rerun HTTP server), the server is down (5xx), or they hit a
    /// reverse proxy that redirected somewhere unexpected. Connection-refused (wrong port
    /// or server not running) hits a different error path above.
    #[expect(clippy::needless_pass_by_value)]
    pub fn invalid_server_with_response(
        origin: re_uri::Origin,
        status: u16,
        status_text: &str,
        body_snippet: Option<&str>,
        hint: Option<&str>,
    ) -> Self {
        let mut msg = format!(
            "{origin} is not a valid Rerun server (GET /version returned HTTP {status} {status_text})"
        );
        if let Some(body) = body_snippet.filter(|s| !s.is_empty()) {
            msg.push_str(": ");
            msg.push_str(body);
        }
        if let Some(hint) = hint {
            msg.push_str(". ");
            msg.push_str(hint);
        }
        Self::new(ApiErrorKind::InvalidServer, msg)
    }

    /// Helper method to downcast the source error to a `ClientCredentialsError` if possible.
    #[inline]
    pub fn as_client_credentials_error(&self) -> Option<&ClientCredentialsError> {
        self.source
            .as_ref()?
            .downcast_ref::<ClientCredentialsError>()
    }

    #[inline]
    pub fn is_client_credentials_error(&self) -> bool {
        self.kind == ApiErrorKind::Unauthenticated
            && matches!(self.source.as_ref(), Some(e) if e.is::<ClientCredentialsError>())
    }
}

impl std::fmt::Display for ApiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let Self {
            message,
            kind,
            source,
            trace_id,
        } = self;

        write!(f, "{message} ({kind})")?;

        if let Some(trace_id) = trace_id {
            write!(f, " (trace-id: {trace_id})")?;
        }

        if let Some(err) = source {
            write!(f, ", {err}")?;
        }

        Ok(())
    }
}

impl std::error::Error for ApiError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source
            .as_ref()
            .map(|e| e.as_ref() as &(dyn std::error::Error + 'static))
    }
}