xbbg-async 1.6.0

Async worker-pool engine over xbbg_core for Bloomberg API requests and subscriptions
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
//! Shared error classification and messages for native host adapters.
//!
//! Adapters choose their exception class or status code and attach host-specific
//! attributes. Existing message differences are limited to [`ErrorStyle`].

use std::fmt::{self, Display, Write};

use xbbg_core::BlpError;

use crate::BlpAsyncError;

/// Borrow a core error's host-facing message without allocating a buffer.
///
/// Request failures retain their full service, request, and source context.
/// Other variants preserve the core error's existing [`Display`] behavior.
/// Formatting stops immediately when the destination rejects further output.
pub fn blp_error_display(error: &BlpError) -> impl Display + '_ {
    BlpErrorDisplay(error)
}

struct BlpErrorDisplay<'a>(&'a BlpError);

impl Display for BlpErrorDisplay<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let BlpError::RequestFailure {
            service,
            operation,
            cid,
            label,
            request_id,
            source,
        } = self.0
        else {
            return Display::fmt(self.0, formatter);
        };

        write!(formatter, "Request failed on {service}")?;
        if let Some(operation) = operation {
            write!(formatter, "::{operation}")?;
        }
        if let Some(cid) = cid {
            write!(formatter, " (cid={cid})")?;
        }
        if let Some(request_id) = request_id {
            write!(formatter, " [request_id={request_id}]")?;
        }
        if let Some(label) = label {
            write!(formatter, " - {label}")?;
        }
        if let Some(source) = source {
            write!(formatter, ": {source}")?;
        }
        Ok(())
    }
}

/// Host-independent exception families emitted by the engine.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ErrorKind {
    Session,
    Request,
    Limit,
    DataLoss,
    Validation,
    Timeout,
    Internal,
}

/// Preserve established host wording without duplicating domain classification.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ErrorStyle {
    Python,
    JavaScript,
}

/// Structured subscription context retained for host exception attributes.
#[derive(Debug)]
pub struct SubscriptionDataLossContext {
    pub topic: String,
    pub detail: String,
}

/// A classified error ready for a host adapter to turn into an exception.
#[derive(Debug)]
pub struct ErrorPresentation {
    pub kind: ErrorKind,
    pub message: String,
    pub data_loss: Option<SubscriptionDataLossContext>,
}

impl ErrorPresentation {
    /// Consume a core error, retaining its domain context in the message.
    pub fn from_blp(error: BlpError, style: ErrorStyle) -> Self {
        let (kind, message) = match error {
            BlpError::SessionStart { source, label } => (
                ErrorKind::Session,
                format_error_msg("Session start failed", label.as_deref(), source.as_deref()),
            ),
            BlpError::OpenService {
                service,
                source,
                label,
            } => {
                let mut message = format!("Failed to open service '{service}': ");
                append_error_msg(&mut message, "", label.as_deref(), source.as_deref());
                (ErrorKind::Session, message)
            }
            BlpError::RequestFailure { ref label, .. } => {
                let kind = if request_failure_is_limit(label.as_deref()) {
                    ErrorKind::Limit
                } else {
                    ErrorKind::Request
                };
                (kind, blp_error_display(&error).to_string())
            }
            BlpError::InvalidArgument { detail } => {
                (ErrorKind::Validation, format!("Invalid argument: {detail}"))
            }
            BlpError::Timeout => (ErrorKind::Timeout, "Request timed out".into()),
            BlpError::TemplateTerminated { cid } => {
                let mut message = "Request template terminated".to_string();
                if let Some(cid) = cid {
                    write!(message, " (cid={cid})").expect("writing to a String");
                }
                (ErrorKind::Request, message)
            }
            BlpError::SubscriptionFailure { cid, label } => {
                let mut message = "Subscription failed".to_string();
                if let Some(cid) = cid {
                    write!(message, " (cid={cid})").expect("writing to a String");
                }
                if let Some(label) = label {
                    write!(message, ": {label}").expect("writing to a String");
                }
                (ErrorKind::Request, message)
            }
            BlpError::SubscriptionDataLoss { topic, detail } => {
                let message = match style {
                    ErrorStyle::Python => {
                        format!("Subscription data loss for '{topic}': {detail}")
                    }
                    ErrorStyle::JavaScript => {
                        format!("Subscription data loss [topic={topic}]: {detail}")
                    }
                };
                return Self {
                    kind: ErrorKind::DataLoss,
                    message,
                    data_loss: Some(SubscriptionDataLossContext { topic, detail }),
                };
            }
            BlpError::Internal { detail } => {
                (ErrorKind::Internal, format!("Internal error: {detail}"))
            }
            BlpError::SchemaOperationNotFound { service, operation } => (
                ErrorKind::Validation,
                format!("Operation not found: {service}::{operation}"),
            ),
            BlpError::SchemaElementNotFound { parent, name } => (
                ErrorKind::Validation,
                format!("Schema element not found: {parent}.{name}"),
            ),
            BlpError::SchemaTypeMismatch {
                element,
                expected,
                found,
            } => (
                ErrorKind::Validation,
                match style {
                    ErrorStyle::Python => format!(
                        "Schema type mismatch at {element}: expected {expected:?}, found {found:?}"
                    ),
                    ErrorStyle::JavaScript => format!(
                        "Schema type mismatch at {element}: expected {expected}, found {found}"
                    ),
                },
            ),
            BlpError::SchemaUnsupported { element, detail } => (
                ErrorKind::Validation,
                format!("Unsupported schema construct at {element}: {detail}"),
            ),
            BlpError::Validation {
                mut message,
                errors,
            } => {
                for (index, error) in errors.into_iter().enumerate() {
                    message.push_str(if index == 0 { ": " } else { "; " });
                    write!(message, "{error}").expect("writing to a String");
                    if let Some(suggestion) = error.suggestion {
                        write!(message, " (did you mean '{suggestion}'?)")
                            .expect("writing to a String");
                    }
                }
                (ErrorKind::Validation, message)
            }
        };
        Self {
            kind,
            message,
            data_loss: None,
        }
    }

    /// Consume an async error using the same core classification as stream errors.
    pub fn from_async(error: BlpAsyncError, style: ErrorStyle) -> Self {
        let (kind, message) = match error {
            BlpAsyncError::Blp(error) => return Self::from_blp(error, style),
            BlpAsyncError::Internal(message) => (ErrorKind::Internal, message),
            BlpAsyncError::ConfigError { detail } => (
                ErrorKind::Validation,
                format!("Configuration error: {detail}"),
            ),
            BlpAsyncError::ChannelClosed => {
                (ErrorKind::Internal, "Channel closed unexpectedly".into())
            }
            BlpAsyncError::AllWorkersDown { pool_size } => (
                ErrorKind::Session,
                match style {
                    ErrorStyle::Python => format!(
                        "all {pool_size} request workers are dead — no healthy worker available"
                    ),
                    ErrorStyle::JavaScript => {
                        format!("All {pool_size} request workers are down")
                    }
                },
            ),
        };
        Self {
            kind,
            message,
            data_loss: None,
        }
    }
}

fn request_failure_is_limit(label: Option<&str>) -> bool {
    label.is_some_and(|label| {
        label.contains("category=LIMIT") || label.contains("DAILY_CAPACITY_REACHED")
    })
}

fn format_error_msg(
    base: &str,
    label: Option<&str>,
    source: Option<&(dyn std::error::Error + Send + Sync)>,
) -> String {
    let mut message = String::new();
    append_error_msg(&mut message, base, label, source);
    message
}

// Service errors add a prefix before the same label/source suffix. Append into
// the final buffer rather than allocating a second formatted message.
fn append_error_msg(
    message: &mut String,
    base: &str,
    label: Option<&str>,
    source: Option<&(dyn std::error::Error + Send + Sync)>,
) {
    let start = message.len();
    message.push_str(base);
    if let Some(label) = label {
        if message.len() > start {
            message.push_str(": ");
        }
        message.push_str(label);
    }
    if let Some(source) = source {
        if message.len() > start {
            message.push_str(" - ");
        }
        write!(message, "{source}").expect("writing to a String");
    }
    if message.len() == start {
        message.push_str("Unknown error");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use xbbg_core::errors::{CorrelationContext, ValidationError};

    #[test]
    fn optional_label_and_source_keep_identical_separators_and_fallback() {
        let source = std::io::Error::other("synthetic cause");
        for (base, label, with_source, expected) in [
            ("", None, false, "Unknown error"),
            ("", Some(""), false, "Unknown error"),
            ("", Some("label"), false, "label"),
            ("", None, true, "synthetic cause"),
            ("", Some("label"), true, "label - synthetic cause"),
            ("base", None, false, "base"),
            ("base", Some(""), false, "base: "),
            ("base", Some("label"), false, "base: label"),
            ("base", None, true, "base - synthetic cause"),
            ("base", Some("label"), true, "base: label - synthetic cause"),
        ] {
            let cause = with_source.then_some(&source as &(dyn std::error::Error + Send + Sync));
            assert_eq!(format_error_msg(base, label, cause), expected);
        }
    }

    #[test]
    fn request_limits_share_classification_and_full_context() {
        for style in [ErrorStyle::Python, ErrorStyle::JavaScript] {
            for (label, kind) in [
                (None, ErrorKind::Request),
                (Some("category=BAD_ARGS"), ErrorKind::Request),
                (Some("category=LIMIT"), ErrorKind::Limit),
                (Some("DAILY_CAPACITY_REACHED"), ErrorKind::Limit),
                (Some("subcategory=DAILY_CAPACITY_REACHED"), ErrorKind::Limit),
            ] {
                let presentation = ErrorPresentation::from_blp(
                    BlpError::RequestFailure {
                        service: "//blp/refdata".into(),
                        operation: Some("ReferenceDataRequest".into()),
                        cid: Some(CorrelationContext::U64(42)),
                        label: label.map(str::to_owned),
                        request_id: Some("synthetic-request".into()),
                        source: Some(Box::new(std::io::Error::other("synthetic cause"))),
                    },
                    style,
                );
                let mut expected = "Request failed on //blp/refdata::ReferenceDataRequest (cid=42) [request_id=synthetic-request]".to_string();
                if let Some(label) = label {
                    write!(expected, " - {label}").unwrap();
                }
                expected.push_str(": synthetic cause");
                assert_eq!(presentation.kind, kind);
                assert_eq!(presentation.message, expected);
                assert!(presentation.data_loss.is_none());
            }
        }
    }

    #[test]
    fn core_errors_keep_their_domain_and_message() {
        for style in [ErrorStyle::Python, ErrorStyle::JavaScript] {
            let cases = [
                (
                    BlpError::SessionStart {
                        source: None,
                        label: Some("synthetic start failure".into()),
                    },
                    ErrorKind::Session,
                    "Session start failed: synthetic start failure",
                ),
                (
                    BlpError::OpenService {
                        service: "//blp/refdata".into(),
                        source: Some(Box::new(std::io::Error::other("synthetic cause"))),
                        label: Some("unavailable".into()),
                    },
                    ErrorKind::Session,
                    "Failed to open service '//blp/refdata': unavailable - synthetic cause",
                ),
                (
                    BlpError::OpenService {
                        service: "//blp/refdata".into(),
                        source: None,
                        label: None,
                    },
                    ErrorKind::Session,
                    "Failed to open service '//blp/refdata': Unknown error",
                ),
                (
                    BlpError::RequestFailure {
                        service: "//blp/refdata".into(),
                        operation: None,
                        cid: None,
                        label: None,
                        request_id: None,
                        source: None,
                    },
                    ErrorKind::Request,
                    "Request failed on //blp/refdata",
                ),
                (
                    BlpError::InvalidArgument {
                        detail: "fields required".into(),
                    },
                    ErrorKind::Validation,
                    "Invalid argument: fields required",
                ),
                (BlpError::Timeout, ErrorKind::Timeout, "Request timed out"),
                (
                    BlpError::TemplateTerminated {
                        cid: Some(CorrelationContext::Tag("synthetic".into())),
                    },
                    ErrorKind::Request,
                    "Request template terminated (cid=synthetic)",
                ),
                (
                    BlpError::TemplateTerminated { cid: None },
                    ErrorKind::Request,
                    "Request template terminated",
                ),
                (
                    BlpError::SubscriptionFailure {
                        cid: Some(CorrelationContext::U64(42)),
                        label: Some("synthetic subscription failure".into()),
                    },
                    ErrorKind::Request,
                    "Subscription failed (cid=42): synthetic subscription failure",
                ),
                (
                    BlpError::SubscriptionFailure {
                        cid: None,
                        label: None,
                    },
                    ErrorKind::Request,
                    "Subscription failed",
                ),
                (
                    BlpError::Internal {
                        detail: "session connection dropped (worker=2)".into(),
                    },
                    ErrorKind::Internal,
                    "Internal error: session connection dropped (worker=2)",
                ),
                (
                    BlpError::SchemaOperationNotFound {
                        service: "//blp/refdata".into(),
                        operation: "SyntheticRequest".into(),
                    },
                    ErrorKind::Validation,
                    "Operation not found: //blp/refdata::SyntheticRequest",
                ),
                (
                    BlpError::SchemaElementNotFound {
                        parent: "request".into(),
                        name: "synthetic".into(),
                    },
                    ErrorKind::Validation,
                    "Schema element not found: request.synthetic",
                ),
                (
                    BlpError::SchemaUnsupported {
                        element: "request.synthetic".into(),
                        detail: "choice".into(),
                    },
                    ErrorKind::Validation,
                    "Unsupported schema construct at request.synthetic: choice",
                ),
                (
                    BlpError::Validation {
                        message: "invalid request".into(),
                        errors: Vec::new(),
                    },
                    ErrorKind::Validation,
                    "invalid request",
                ),
                (
                    BlpError::Validation {
                        message: "invalid request".into(),
                        errors: vec![
                            ValidationError {
                                path: "fields[0]".into(),
                                message: "unknown field".into(),
                                suggestion: Some("PX_LAST".into()),
                            },
                            ValidationError {
                                path: "securities".into(),
                                message: "required".into(),
                                suggestion: None,
                            },
                        ],
                    },
                    ErrorKind::Validation,
                    "invalid request: fields[0]: unknown field (did you mean 'PX_LAST'?); securities: required",
                ),
            ];
            for (error, kind, message) in cases {
                let presentation = ErrorPresentation::from_blp(error, style);
                assert_eq!(presentation.kind, kind);
                assert_eq!(presentation.message, message);
                assert!(presentation.data_loss.is_none());
            }
        }
    }

    #[test]
    fn host_wording_does_not_change_domain_or_structured_context() {
        for (style, data_loss_message, schema_message, session_message) in [
            (
                ErrorStyle::Python,
                "Subscription data loss for 'SYNTHETIC Equity': synthetic overflow",
                "Schema type mismatch at fields: expected \"String\", found \"Int32\"",
                "all 2 request workers are dead — no healthy worker available",
            ),
            (
                ErrorStyle::JavaScript,
                "Subscription data loss [topic=SYNTHETIC Equity]: synthetic overflow",
                "Schema type mismatch at fields: expected String, found Int32",
                "All 2 request workers are down",
            ),
        ] {
            let presentation = ErrorPresentation::from_async(
                BlpError::SubscriptionDataLoss {
                    topic: "SYNTHETIC Equity".into(),
                    detail: "synthetic overflow".into(),
                }
                .into(),
                style,
            );
            assert_eq!(presentation.kind, ErrorKind::DataLoss);
            assert_eq!(presentation.message, data_loss_message);
            let context = presentation.data_loss.unwrap();
            assert_eq!(context.topic, "SYNTHETIC Equity");
            assert_eq!(context.detail, "synthetic overflow");

            let presentation = ErrorPresentation::from_blp(
                BlpError::SchemaTypeMismatch {
                    element: "fields".into(),
                    expected: "String".into(),
                    found: "Int32".into(),
                },
                style,
            );
            assert_eq!(presentation.kind, ErrorKind::Validation);
            assert_eq!(presentation.message, schema_message);

            let presentation = ErrorPresentation::from_async(
                BlpAsyncError::AllWorkersDown { pool_size: 2 },
                style,
            );
            assert_eq!(presentation.kind, ErrorKind::Session);
            assert_eq!(presentation.message, session_message);
        }
    }

    #[test]
    fn async_errors_keep_their_domain_and_message() {
        for style in [ErrorStyle::Python, ErrorStyle::JavaScript] {
            for (error, kind, message) in [
                (
                    BlpError::Timeout.into(),
                    ErrorKind::Timeout,
                    "Request timed out",
                ),
                (
                    BlpAsyncError::Internal("synthetic failure".into()),
                    ErrorKind::Internal,
                    "synthetic failure",
                ),
                (
                    BlpAsyncError::ConfigError {
                        detail: "synthetic config failure".into(),
                    },
                    ErrorKind::Validation,
                    "Configuration error: synthetic config failure",
                ),
                (
                    BlpAsyncError::ChannelClosed,
                    ErrorKind::Internal,
                    "Channel closed unexpectedly",
                ),
            ] {
                let presentation = ErrorPresentation::from_async(error, style);
                assert_eq!(presentation.kind, kind);
                assert_eq!(presentation.message, message);
                assert!(presentation.data_loss.is_none());
            }
        }
    }
}