wuapi 0.14.0

Rust SDK for wuapi, a WhatsApp API for developers. Link numbers by QR or pairing code, send and receive messages, manage chats, contacts, groups and channels, split them into projects and verify webhooks.
Documentation
// Generated by wuapi-codegen from the OpenAPI spec. Do not edit: run `bun run codegen`.

use std::time::Duration;

use crate::error::Error;
use crate::http::HttpClient;
use crate::stream::{
    EventStream, HttpStreamTransport, StreamBudget, StreamErrorKind, StreamLimits, StreamOptions,
    StreamRefusal, StreamSpec, StreamTiming,
};
use crate::types;

/// The stream, as the generator's config describes it: what the runtime
/// works from.
#[must_use]
pub fn stream_spec() -> StreamSpec {
    StreamSpec {
        base_url: "https://stream.wuapi.dev".to_owned(),
        path: "/v1/events/stream".to_owned(),
        resume_header: "Last-Event-ID".to_owned(),
        reset_event: "reset".to_owned(),
        timing: StreamTiming {
            retry: Duration::from_millis(3000),
            heartbeat: Duration::from_millis(15000),
            idle_timeout: Duration::from_millis(45000),
            open_timeout: Duration::from_millis(12000),
            backoff_base: Duration::from_millis(1000),
            backoff_cap: Duration::from_millis(30000),
            min_gap: Duration::from_millis(1000),
            stable_after: Duration::from_millis(30000),
            retry_max: Duration::from_millis(60000),
            retry_after_max: Duration::from_millis(300000),
            replay_window: Duration::from_millis(1800000),
        },
        limits: StreamLimits {
            connect_budget: 6,
            connect_budget_window: Duration::from_millis(60000),
            max_frame_bytes: 1048576,
            dedupe_window: 2048,
        },
        refusals: vec![
            StreamRefusal { status: 400, code: None, error: Some(StreamErrorKind::InvalidRequest), api_only: false, wait: None },
            StreamRefusal { status: 401, code: None, error: Some(StreamErrorKind::Unauthorized), api_only: true, wait: None },
            StreamRefusal { status: 403, code: None, error: Some(StreamErrorKind::Forbidden), api_only: false, wait: None },
            StreamRefusal { status: 404, code: None, error: Some(StreamErrorKind::NotFound), api_only: false, wait: None },
            StreamRefusal { status: 429, code: Some("stream_connection_limit".to_owned()), error: None, api_only: false, wait: Some(Duration::from_millis(30000)) },
            StreamRefusal { status: 429, code: None, error: None, api_only: false, wait: Some(Duration::from_millis(60000)) },
        ],
    }
}

/// What `events.stream` takes. Every field is optional: without any, the stream carries every event, from now.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct EventsStreamParams {
    /// Only these event types. Presence events and `webhook.test` are not on Streams. At most 50.
    pub types: Vec<types::WebhookEventType>,
    /// Only these accounts, by id. At most 50.
    pub accounts: Vec<String>,
    /// Resume after this cursor: the `cursor` of the last event you handled, or a stream's `last_event_id()`. Sent as `Last-Event-ID`.
    pub last_event_id: Option<String>,
}

impl EventsStreamParams {
    /// No filter and no cursor.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Only these event types. Presence events and `webhook.test` are not on Streams. At most 50.
    #[must_use]
    pub fn types(mut self, types: impl IntoIterator<Item = types::WebhookEventType>) -> Self {
        self.types = types.into_iter().collect();
        self
    }

    /// Only these accounts, by id. At most 50.
    #[must_use]
    pub fn accounts(mut self, accounts: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.accounts = accounts.into_iter().map(Into::into).collect();
        self
    }

    /// Resume after this cursor.
    #[must_use]
    pub fn last_event_id(mut self, last_event_id: impl Into<String>) -> Self {
        self.last_event_id = Some(last_event_id.into());
        self
    }
}

/// Streams: your events over one connection your code opens, the same envelope a webhook carries. No public endpoint needed.
#[derive(Clone, Debug)]
pub struct EventsResource {
    http: HttpClient,
}

impl EventsResource {
    pub(crate) fn new(http: HttpClient) -> Self {
        Self { http }
    }

    /// Streams: your events over one connection your code opens, the same envelope a webhook carries. No public endpoint needed.
    ///
    /// Opens the stream. Ask it for `next_event()`; it reconnects and resumes by itself, and stops only when it is closed or on a terminal `StreamError`. Nothing is sent until the stream is polled.
    ///
    /// `GET https://stream.wuapi.dev/v1/events/stream`
    ///
    /// # Errors
    ///
    /// [`Error::Config`] when the stream URL is not one the API key may travel to.
    pub fn stream(&self, params: EventsStreamParams) -> Result<EventStream, Error> {
        self.stream_with(params, StreamOptions::new())
    }

    /// The same, with options: a give-up time, the dedupe window, a status
    /// callback.
    ///
    /// # Errors
    ///
    /// [`Error::Config`] when the stream URL is not one the API key may travel to.
    pub fn stream_with(
        &self,
        params: EventsStreamParams,
        options: StreamOptions,
    ) -> Result<EventStream, Error> {
        let transport = self.transport(&params)?;
        Ok(EventStream::with_transport(
            std::sync::Arc::new(transport),
            stream_spec(),
            params.last_event_id,
            options.or_budget(self.budget()),
        ))
    }

    /// The transport a stream with these params connects through, to make
    /// one connect yourself (a diagnosis) or to run a stream with a
    /// description of your own (`EventStream::with_transport`).
    ///
    /// # Errors
    ///
    /// [`Error::Config`] when the stream URL is not one the API key may travel to.
    pub fn transport(&self, params: &EventsStreamParams) -> Result<HttpStreamTransport, Error> {
        let filters = [
            ("types", params.types.iter().map(|v| v.as_str().to_owned()).collect()),
            ("accounts", params.accounts.clone()),
        ];
        HttpStreamTransport::new(&self.http, &stream_spec(), &filters)
    }

    /// The connect budget every stream of this client draws on.
    #[must_use]
    pub fn budget(&self) -> StreamBudget {
        StreamBudget::of(&self.http, &stream_spec().limits)
    }
}