providers-kit 0.0.2

Portable enum-dispatch Kit over multiple model provider APIs.
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
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
use std::num::NonZeroUsize;

use futures_util::StreamExt;
use reqwest::{RequestBuilder, Response};
use serde::de::DeserializeOwned;

use crate::KitError;
use crate::error::{
    ClassificationBasis, ErrorKind, ErrorPhase, NativeErrorDetails, Operation, RemoteFailure,
    ResponseDetails, ResponseViolation,
};

use super::execution::RequestExecution;

const CONTROL_BODY_LIMIT: NonZeroUsize = NonZeroUsize::new(32 * 1024 * 1024).unwrap();
const ERROR_BODY_LIMIT: usize = 64 * 1024;
const TRUNCATION_MARKER: &str = "\n[response body truncated]";

pub(crate) struct HttpResponse<T> {
    value: T,
    metadata: NativeErrorDetails,
}

impl<T> HttpResponse<T> {
    pub(crate) fn value(&self) -> &T {
        &self.value
    }

    pub(crate) fn into_value(self) -> T {
        self.value
    }

    pub(crate) fn attach_error(&self, error: KitError) -> KitError {
        CheckedRequestSpec::attach_metadata(error, &self.metadata)
    }

    pub(crate) fn try_map<U>(
        self,
        normalize: impl FnOnce(T) -> Result<U, KitError>,
    ) -> Result<HttpResponse<U>, KitError> {
        let value = normalize(self.value)
            .map_err(|error| CheckedRequestSpec::attach_metadata(error, &self.metadata))?;
        Ok(HttpResponse {
            value,
            metadata: self.metadata,
        })
    }

    pub(crate) fn normalize<U>(
        self,
        normalize: impl FnOnce(T) -> Result<U, KitError>,
    ) -> Result<U, KitError> {
        self.try_map(normalize).map(HttpResponse::into_value)
    }
}

impl HttpResponse<Response> {
    pub(crate) fn from_response(response: Response) -> Self {
        Self {
            metadata: CheckedRequestSpec::response_metadata(&response),
            value: response,
        }
    }
}

struct DiagnosticBody {
    body: String,
    truncated: bool,
    failure: Option<KitError>,
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct CheckedRequestSpec {
    parse_error: fn(&str) -> Result<Option<RemoteFailure>, KitError>,
}

impl CheckedRequestSpec {
    pub(crate) const fn new(
        parse_error: fn(&str) -> Result<Option<RemoteFailure>, KitError>,
    ) -> Self {
        Self { parse_error }
    }

    /// Precise HTTP rejection remains authoritative; documented machine categories
    /// may refine only broad invalid-request, throttling, or unknown statuses.
    pub(crate) fn classify_http_failure(
        failure: RemoteFailure,
        status: u16,
    ) -> Result<RemoteFailure, KitError> {
        // Accepted work can fail inside a successful row envelope. The reported
        // success status remains metadata and cannot classify that failure.
        if (200..300).contains(&status) {
            return Ok(failure);
        }
        let kind = failure.kind();
        let http_kind = ErrorKind::from_http_status(status);
        let refined = match status {
            // FAILED_PRECONDITION has a documented HTTP 400 mapping.
            400 if kind == ErrorKind::FailedPrecondition
                && failure.classification_basis() == ClassificationBasis::CanonicalStatus =>
            {
                true
            }
            400 | 422 => {
                matches!(
                    failure.classification_basis(),
                    ClassificationBasis::NativeCode | ClassificationBasis::NativeReason
                ) && matches!(
                    kind,
                    ErrorKind::Authentication
                        | ErrorKind::PermissionDenied
                        | ErrorKind::NotFound
                        | ErrorKind::Billing
                        | ErrorKind::QuotaExceeded
                        | ErrorKind::FailedPrecondition
                        | ErrorKind::Unsupported
                        | ErrorKind::RequestTooLarge
                        | ErrorKind::ResourceExhausted
                )
            }
            429 => matches!(
                kind,
                ErrorKind::QuotaExceeded
                    | ErrorKind::Billing
                    | ErrorKind::ResourceExhausted
                    | ErrorKind::RateLimited
            ),
            _ => http_kind == ErrorKind::ProviderRejected && kind != ErrorKind::ProviderRejected,
        };
        if refined || (kind == http_kind && kind != ErrorKind::ProviderRejected) {
            return Ok(failure);
        }
        RemoteFailure::from_native(
            http_kind,
            ClassificationBasis::HttpStatus { status },
            failure.native_details().clone(),
        )
    }

    pub(crate) fn refine_http_error(self, error: KitError) -> KitError {
        let Some(status) = error.http_status() else {
            return error;
        };
        let error = if error.remote_failure().is_none() {
            match RemoteFailure::from_native(
                ErrorKind::from_http_status(status),
                ClassificationBasis::HttpStatus { status },
                error.native_details().clone(),
            ) {
                Ok(failure) => error.with_remote_failure(failure),
                Err(failure) => return error.with_supplementary(failure),
            }
        } else {
            error
        };
        let Some(body) = error.native_details().body.as_deref() else {
            return error;
        };
        let parsed = match (self.parse_error)(body) {
            Ok(Some(failure)) => failure,
            Ok(None) => {
                return error.with_supplementary(
                    KitError::invalid_response(ResponseViolation::ProtocolViolation {
                        rule: "unrecognized provider error envelope",
                    })
                    .at_phase(ErrorPhase::Decode),
                );
            }
            Err(failure) => return error.with_supplementary(failure),
        };
        let original = error.native_details();
        let mut details = parsed.native_details().clone();
        details.body = original.body.clone();
        details.request_id = details.request_id.or_else(|| original.request_id.clone());
        details.retry_after = details.retry_after.or_else(|| original.retry_after.clone());
        details.url = details.url.or_else(|| original.url.clone());
        details.truncated |= original.truncated;
        let classified =
            RemoteFailure::from_native(parsed.kind(), parsed.classification_basis(), details)
                .and_then(|failure| Self::classify_http_failure(failure, status));
        match classified {
            Ok(failure) => error.with_remote_failure(failure),
            Err(failure) => error.with_supplementary(failure),
        }
    }

    pub(crate) async fn json<T>(
        self,
        path: &str,
        request: RequestBuilder,
        mut execution: RequestExecution,
    ) -> Result<HttpResponse<T>, KitError>
    where
        T: DeserializeOwned,
    {
        let path = Self::diagnostic_path(path);
        let response = self.checked(path, request, &mut execution).await?;
        let mut metadata = Self::response_metadata(&response);
        let bytes = self
            .read_bounded_body(path, response, &mut execution, CONTROL_BODY_LIMIT.get())
            .await
            .map_err(|error| Self::attach_metadata(error, &metadata))?;
        let diagnostic = Self::diagnostic_body(&bytes);
        metadata.body = diagnostic.body;
        metadata.truncated = diagnostic.truncated;
        let value = serde_json::from_slice(&bytes).map_err(|err| {
            let violation = ResponseViolation::from_json_error(&err, "response");
            let error = KitError::invalid_response(violation)
                .with_response_details(ResponseDetails::json(&err))
                .at_phase(ErrorPhase::Decode)
                .with_message(format!("failed to decode response from {path}: {err}"))
                .with_diagnostic(Some(Self::diagnostic_body(&bytes)));
            Self::attach_metadata(error, &metadata)
        })?;
        Ok(HttpResponse { value, metadata })
    }

    pub(crate) async fn bytes(
        self,
        path: &str,
        request: RequestBuilder,
        execution: RequestExecution,
    ) -> Result<HttpResponse<Vec<u8>>, KitError> {
        self.bytes_with_limit(path, request, execution, CONTROL_BODY_LIMIT.get())
            .await
    }

    pub(crate) async fn bytes_with_limit(
        self,
        path: &str,
        request: RequestBuilder,
        mut execution: RequestExecution,
        max_bytes: usize,
    ) -> Result<HttpResponse<Vec<u8>>, KitError> {
        let path = Self::diagnostic_path(path);
        let response = self.checked(path, request, &mut execution).await?;
        let mut metadata = Self::response_metadata(&response);
        let value = self
            .read_bounded_body(path, response, &mut execution, max_bytes)
            .await
            .map_err(|error| Self::attach_metadata(error, &metadata))?;
        let diagnostic = Self::diagnostic_body(&value);
        metadata.body = diagnostic.body;
        metadata.truncated = diagnostic.truncated;
        Ok(HttpResponse { value, metadata })
    }

    pub(crate) async fn text(
        self,
        path: &str,
        request: RequestBuilder,
        mut execution: RequestExecution,
    ) -> Result<HttpResponse<String>, KitError> {
        let path = Self::diagnostic_path(path);
        let response = self.checked(path, request, &mut execution).await?;
        let mut metadata = Self::response_metadata(&response);
        let bytes = self
            .read_bounded_body(path, response, &mut execution, CONTROL_BODY_LIMIT.get())
            .await
            .map_err(|error| Self::attach_metadata(error, &metadata))?;
        let diagnostic = Self::diagnostic_body(&bytes);
        metadata.body = diagnostic.body;
        metadata.truncated = diagnostic.truncated;
        let value = String::from_utf8(bytes).map_err(|err| {
            let error = KitError::invalid_response(ResponseViolation::InvalidUtf8)
                .at_phase(ErrorPhase::Decode)
                .with_message(format!("response from {path} was not valid UTF-8: {err}"))
                .with_diagnostic(Some(Self::diagnostic_body(err.as_bytes())));
            Self::attach_metadata(error, &metadata)
        })?;
        Ok(HttpResponse { value, metadata })
    }

    pub(crate) async fn response(
        self,
        path: &str,
        request: RequestBuilder,
        mut execution: RequestExecution,
    ) -> Result<Response, KitError> {
        let path = Self::diagnostic_path(path);
        self.checked(path, request, &mut execution).await
    }

    async fn checked(
        self,
        path: &str,
        request: RequestBuilder,
        execution: &mut RequestExecution,
    ) -> Result<Response, KitError> {
        let timeout = execution.timeout();
        let deadline = execution.deadline()?;
        let mut attempts = 0;
        let mut request = request;
        loop {
            let remaining = execution
                .remaining_timeout(deadline)
                .map_err(|error| execution.attach_rejection(error))?;
            let retry_request = request.try_clone();
            let (current, delay, rejected) = match request.timeout(remaining).send().await {
                Ok(response) => {
                    if response.status().is_success() {
                        return Ok(response);
                    }
                    let delay = execution.retry_delay_for_response(attempts, &response);
                    let error = match self.ensure_response_success(path, response, timeout).await {
                        Ok(response) => return Ok(response),
                        Err(error) => error,
                    };
                    // Headers already established a rejection. A failed diagnostic read
                    // cannot replace it with a synthesized retry/deadline failure.
                    if error.supplementary().iter().any(|failure| {
                        failure.kind() == ErrorKind::Timeout
                            && failure.context().phase == ErrorPhase::ReadBody
                    }) {
                        return Err(error);
                    }
                    (error, delay, true)
                }
                Err(error) => {
                    let delay = if error.is_timeout() && !error.is_connect() {
                        None
                    } else {
                        execution.retry_delay_for_error(attempts, &error)
                    };
                    let error = RequestExecution::transport_error(path, timeout, error);
                    (error, delay, false)
                }
            };
            let (Some(delay), Some(next_request)) = (delay, retry_request) else {
                return Err(execution.attach_rejection(current));
            };
            let remaining = match execution.remaining_timeout(deadline) {
                Ok(remaining) => remaining,
                Err(error) => {
                    return Err(if rejected {
                        error.with_supplementary(current)
                    } else {
                        let error = error.with_cause(current);
                        execution.attach_rejection(error)
                    });
                }
            };
            // Merely declining another attempt is not an elapsed deadline.
            if delay >= remaining {
                return Err(execution.attach_rejection(current));
            }
            tokio::time::sleep(delay).await;
            if rejected {
                execution.record_rejection(current);
                execution
                    .remaining_timeout(deadline)
                    .map_err(|error| execution.attach_rejection(error))?;
            } else if let Err(error) = execution.remaining_timeout(deadline) {
                let error = error.with_cause(current);
                return Err(execution.attach_rejection(error));
            }
            attempts += 1;
            request = next_request;
        }
    }

    async fn ensure_response_success(
        self,
        path: &str,
        response: Response,
        timeout: std::time::Duration,
    ) -> Result<Response, KitError> {
        let status = response.status();
        if status.is_success() {
            return Ok(response);
        }

        let metadata = Self::response_metadata(&response);
        // Construct the authoritative rejection before awaiting diagnostic I/O.
        let failure = RemoteFailure::from_native(
            ErrorKind::from_http_status(status.as_u16()),
            ClassificationBasis::HttpStatus {
                status: status.as_u16(),
            },
            metadata,
        )?;
        let mut error =
            KitError::from_remote(failure, Operation::Unspecified, ErrorPhase::ResponseHeaders)
                .with_http_status(status.as_u16());
        let diagnostic = self.read_diagnostic_body(path, response, timeout).await;
        error = error.with_diagnostic(Some(NativeErrorDetails {
            body: Some(if diagnostic.truncated {
                format!("{}{TRUNCATION_MARKER}", diagnostic.body)
            } else {
                diagnostic.body
            }),
            truncated: diagnostic.truncated,
            ..Default::default()
        }));
        if let Some(failure) = diagnostic.failure {
            error = error.with_supplementary(failure);
        }
        error = self.refine_http_error(error);
        Err(error)
    }

    async fn read_bounded_body(
        self,
        path: &str,
        response: Response,
        execution: &mut RequestExecution,
        max_bytes: usize,
    ) -> Result<Vec<u8>, KitError> {
        let limit = u64::try_from(max_bytes).unwrap_or(u64::MAX);
        if let Some(length) = response.content_length().filter(|length| *length > limit) {
            return Err(
                KitError::invalid_response(ResponseViolation::LimitExceeded { limit: max_bytes })
                    .with_response_details(ResponseDetails::Size {
                        observed: usize::try_from(length).unwrap_or(usize::MAX),
                    })
                    .at_phase(ErrorPhase::ReadBody)
                    .with_message(format!(
                        "response from {path} exceeded the {max_bytes}-byte limit"
                    )),
            );
        }

        let mut body = Vec::new();
        let mut stream = response.bytes_stream();
        while let Some(chunk) = stream.next().await {
            let chunk = chunk.map_err(|err| {
                let error = RequestExecution::transport_error(path, execution.timeout(), err)
                    .at_phase(ErrorPhase::ReadBody);
                execution.attach_rejection(error)
            })?;
            let next_len = body.len().checked_add(chunk.len()).ok_or_else(|| {
                KitError::invalid_response(ResponseViolation::LimitExceeded { limit: max_bytes })
                    .with_response_details(ResponseDetails::Size {
                        observed: usize::MAX,
                    })
                    .at_phase(ErrorPhase::ReadBody)
                    .with_message(format!(
                        "response from {path} exceeded the {max_bytes}-byte limit"
                    ))
            })?;
            if next_len > max_bytes {
                return Err(
                    KitError::invalid_response(ResponseViolation::LimitExceeded {
                        limit: max_bytes,
                    })
                    .with_response_details(ResponseDetails::Size { observed: next_len })
                    .at_phase(ErrorPhase::ReadBody)
                    .with_message(format!(
                        "response from {path} exceeded the {max_bytes}-byte limit"
                    )),
                );
            }
            body.extend_from_slice(&chunk);
        }
        Ok(body)
    }

    async fn read_diagnostic_body(
        self,
        path: &str,
        response: Response,
        timeout: std::time::Duration,
    ) -> DiagnosticBody {
        let mut body = Vec::new();
        let mut truncated = response
            .content_length()
            .is_some_and(|length| length > ERROR_BODY_LIMIT as u64);
        let mut stream = response.bytes_stream();
        let mut failure = None;
        while body.len() < ERROR_BODY_LIMIT {
            let Some(chunk) = stream.next().await else {
                break;
            };
            let chunk = match chunk {
                Ok(chunk) => chunk,
                Err(error) => {
                    failure = Some(
                        RequestExecution::transport_error(path, timeout, error)
                            .at_phase(ErrorPhase::ReadBody),
                    );
                    break;
                }
            };
            let remaining = ERROR_BODY_LIMIT - body.len();
            if chunk.len() > remaining {
                body.extend_from_slice(&chunk[..remaining]);
                truncated = true;
                break;
            }
            body.extend_from_slice(&chunk);
        }
        if body.len() == ERROR_BODY_LIMIT && !truncated && failure.is_none() {
            match stream.next().await {
                Some(Ok(_)) => truncated = true,
                Some(Err(error)) => {
                    failure = Some(
                        RequestExecution::transport_error(path, timeout, error)
                            .at_phase(ErrorPhase::ReadBody),
                    );
                }
                None => {}
            }
        }
        let (body, truncated) = Self::bounded_lossy_text(&body, truncated || failure.is_some());
        DiagnosticBody {
            body,
            truncated,
            failure,
        }
    }

    fn response_metadata(response: &Response) -> NativeErrorDetails {
        NativeErrorDetails {
            request_id: response
                .headers()
                .get("x-request-id")
                .or_else(|| response.headers().get("request-id"))
                .and_then(|value| value.to_str().ok())
                .map(str::to_owned),
            retry_after: response
                .headers()
                .get("retry-after")
                .and_then(|value| value.to_str().ok())
                .map(str::to_owned),
            url: Some(Self::diagnostic_path(response.url().as_str()).to_owned()),
            ..NativeErrorDetails::default()
        }
    }

    fn attach_metadata(error: KitError, metadata: &NativeErrorDetails) -> KitError {
        let mut details = error.native_details().clone();
        details.request_id = details.request_id.or_else(|| metadata.request_id.clone());
        details.retry_after = details.retry_after.or_else(|| metadata.retry_after.clone());
        details.url = details.url.or_else(|| metadata.url.clone());
        if details.body.is_none() {
            details.body = metadata.body.clone();
            details.truncated |= metadata.truncated;
        }
        error.with_native_capture(details)
    }

    fn diagnostic_path(path: &str) -> &str {
        let path = path.split_once('?').map_or(path, |(path, _)| path);
        let path = path.split_once('#').map_or(path, |(path, _)| path);
        path.split_once("://").map_or(path, |(_, authority)| {
            authority.find('/').map_or("/", |index| &authority[index..])
        })
    }

    pub(crate) fn diagnostic_body(bytes: &[u8]) -> NativeErrorDetails {
        let source_truncated = bytes.len() > ERROR_BODY_LIMIT;
        let prefix = &bytes[..bytes.len().min(ERROR_BODY_LIMIT)];
        let (body, truncated) = Self::bounded_lossy_text(prefix, source_truncated);
        let body = if truncated {
            format!("{body}{TRUNCATION_MARKER}")
        } else {
            body
        };
        NativeErrorDetails {
            body: Some(body),
            truncated,
            ..NativeErrorDetails::default()
        }
    }

    fn bounded_lossy_text(bytes: &[u8], source_truncated: bool) -> (String, bool) {
        let mut body = String::from_utf8_lossy(bytes).into_owned();
        let truncated = source_truncated || body.len() > ERROR_BODY_LIMIT;
        if truncated {
            let limit = ERROR_BODY_LIMIT.saturating_sub(TRUNCATION_MARKER.len());
            let mut end = body.len().min(limit);
            while !body.is_char_boundary(end) {
                end -= 1;
            }
            body.truncate(end);
        }
        (body, truncated)
    }

    pub(crate) fn diagnostic_json<T>(value: &T) -> Option<NativeErrorDetails>
    where
        T: serde::Serialize + ?Sized,
    {
        serde_json::to_vec(value)
            .ok()
            .map(|bytes| Self::diagnostic_body(&bytes))
    }
}