Skip to main content

HttpRequest

Struct HttpRequest 

Source
#[non_exhaustive]
pub struct HttpRequest { pub method: Method, pub url: String, pub headers: Headers, pub body: Option<Bytes>, pub timeout: Option<Duration>, }
Expand description

An HTTP request built by a provider.

Debug output redacts credential headers (see Headers).

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§method: Method

Method.

§url: String

Absolute URL.

§headers: Headers

Headers, in order.

§body: Option<Bytes>

Body, if any.

§timeout: Option<Duration>

Bound on the whole exchange, when the provider sets one. Streaming requests usually leave it unset.

Implementations§

Source§

impl HttpRequest

Source

pub fn get(url: impl Into<String>) -> Self

A GET request.

Source

pub fn post(url: impl Into<String>, body: impl Into<Bytes>) -> Self

A POST request with body.

Source

pub fn header(self, name: impl Into<String>, value: impl Into<String>) -> Self

Add a header.

Source

pub fn timeout(self, timeout: Option<Duration>) -> Self

Set (or clear) the timeout.

Source

pub fn body_text(&self) -> Option<&str>

The body as UTF-8 text, if it is valid UTF-8.

Source

pub fn sensitive_header( self, name: impl Into<String>, value: impl Into<String>, ) -> Self

Add a header whose value is a secret: Debug output redacts it whatever its name. For an adapter that places a credential itself (CredentialPlacement::Custom).

Source

pub fn with_headers(self, headers: &Headers) -> Self

Set each of headers, replacing the request’s headers of the same name (ignoring case) and adding the others, in order. For the headers a provider sends with every request: the bundled providers set their DEFAULT_USER_AGENT and the builder’s own headers (header(name, value), validated by config::static_headers) with it, after their protocol headers and before apply_options, so a request’s own headers still win.

use allama_http::{Headers, HttpRequest};

let defaults: Headers = [("user-agent", "my-app/1.0"), ("x-route", "eu")].into_iter().collect();
let request = HttpRequest::post("https://api.example.com/v1/chat", "{}")
    .header("User-Agent", "allama/0.1.0")
    .with_headers(&defaults);
assert_eq!(request.headers.get("user-agent"), Some("my-app/1.0"));
assert_eq!(request.headers.iter().count(), 2);
Source

pub fn apply_options( self, options: &RequestOptions, slot: &CredentialSlot, ) -> Result<Self>

Apply the caller’s transport options for this request: the HttpRequestOptions in options, typed or in their JSON form, with the credentials addressed to slot’s scope.

Call it once the request carries every header the adapter sets, including its configured credential, and before sending it. Every bundled HTTP adapter calls it with the options of the request it serves and its own CredentialSlot, so callers get the same behaviour from first- and third-party adapters. In order, it:

  1. refuses, before anything is sent, a plain header that would carry a credential (see Errors);
  2. replaces the request’s headers with the plain headers of the same name, and adds the others;
  3. places the Credential::api_key addressed to the slot’s scope as the slot’s placement says, removing the configured credential and every header the slot replaces. A Custom slot is left alone: the adapter signs or places its credential after this call;
  4. adds the Credential::header values addressed to the scope, each replacing the headers of the same name.

Credentials addressed to other scopes are never sent. Placed credentials are redacted from Debug whatever the header name.

use allama::ChatRequest;
use allama_http::{Credential, CredentialPlacement, CredentialSlot, HttpRequest, HttpRequestOptions};

let slot = CredentialSlot::new("anthropic", CredentialPlacement::Header("x-api-key".into()));
let request = ChatRequest::new("m").user("Hi").with_option(
    HttpRequestOptions::new()
        .credential("anthropic", Credential::api_key("tenant-key"))
        .credential("openai", Credential::api_key("other-account"))
        .header("x-tenant-id", "acme"),
);
let http = HttpRequest::post("https://api.example.com/v1/messages", "{}")
    .header("x-api-key", "provider-key")
    .apply_options(&request.options, &slot)?;
assert_eq!(http.headers.get("x-api-key"), Some("tenant-key"));
assert_eq!(http.headers.get("x-tenant-id"), Some("acme"));
assert!(!format!("{http:?}").contains("other-account"));
§Errors
  • allama::Error::InvalidRequest when the JSON form of the options is malformed, names a header on the exact credential list (is_credential_header), or sets credentials.
  • An authored allama::Error::Configuration, before anything is sent, when a plain header is named on the exact credential list (is_credential_header) or is one the slot writes or replaces, or when the slot is required and no credential is addressed to its scope. These are the application’s bugs, not the end user’s, so they are not retried, never fall over to another provider, and map to a server error. Error text names headers and scopes, never secrets.

Trait Implementations§

Source§

impl Clone for HttpRequest

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for HttpRequest

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for HttpRequest

Source§

impl PartialEq for HttpRequest

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for HttpRequest

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more