onwardz 0.1.0

Server-side SDK for managing Onwardz rooms (create rooms, issue join tokens, manage settings).
Documentation
//! The [`OnwardzClient`] and its builder.

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::{json, Value};

use crate::error::{OnwardzError, Result};
use crate::models::{
    ConfigureRoomOptions, CreateRoomOptions, CreateRoomResponse, IssueTokenResponse,
    ListRoomsResponse, Room,
};

/// The default Onwardz API endpoint.
pub const DEFAULT_SERVER_URL: &str = "https://api.onwardz.com/rpc";

/// Default token lifetime (seconds) when none is given to
/// [`OnwardzClient::issue_token`].
const DEFAULT_TOKEN_TTL: u64 = 3600;

/// Authenticated client for the Onwardz server API.
///
/// Use this in your backend to create rooms, issue join tokens, and manage room
/// settings. It requires your API key — **never use it in client-side code.**
///
/// Cloning is cheap (the underlying HTTP client and state are shared).
///
/// ```no_run
/// use onwardz::{OnwardzClient, CreateRoomOptions};
///
/// # async fn run() -> Result<(), onwardz::OnwardzError> {
/// let onwardz = OnwardzClient::new(std::env::var("ONWARDZ_API_KEY").unwrap());
///
/// let room = onwardz.create_room(CreateRoomOptions::default()).await?;
/// let token = onwardz.issue_token(&room.room_id, None).await?;
/// // Hand room.room_id + token.token to the browser (@onwardz/js).
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct OnwardzClient {
    inner: Arc<Inner>,
}

struct Inner {
    http: reqwest::Client,
    server_url: String,
    api_key: String,
    next_id: AtomicU64,
}

impl OnwardzClient {
    /// Create a client against the default endpoint ([`DEFAULT_SERVER_URL`]).
    pub fn new(api_key: impl Into<String>) -> Self {
        Self::builder(api_key).build()
    }

    /// Start building a client, e.g. to point at a self-hosted deployment.
    pub fn builder(api_key: impl Into<String>) -> OnwardzClientBuilder {
        OnwardzClientBuilder {
            api_key: api_key.into(),
            server_url: DEFAULT_SERVER_URL.to_string(),
            http: None,
        }
    }

    /// Create a new room.
    pub async fn create_room(&self, opts: CreateRoomOptions) -> Result<CreateRoomResponse> {
        self.call("rooms.create", opts).await
    }

    /// List all active rooms owned by this account.
    pub async fn list_rooms(&self) -> Result<Vec<Room>> {
        let resp: ListRoomsResponse = self.call("rooms.list", json!({})).await?;
        Ok(resp.rooms)
    }

    /// Soft-delete a room. Active participants are not forcibly disconnected,
    /// but no new peers can join.
    pub async fn delete_room(&self, room_id: &str) -> Result<()> {
        let _: Value = self
            .call("rooms.delete", json!({ "room_id": room_id }))
            .await?;
        Ok(())
    }

    /// Update a room's settings. Only the fields you set on
    /// [`ConfigureRoomOptions`] are changed.
    pub async fn configure_room(&self, room_id: &str, opts: ConfigureRoomOptions) -> Result<()> {
        // Merge the room_id into the options object.
        let mut params =
            serde_json::to_value(&opts).map_err(|e| OnwardzError::Decode(e.to_string()))?;
        if let Value::Object(map) = &mut params {
            map.insert("room_id".to_string(), Value::String(room_id.to_string()));
        }
        let _: Value = self.call("rooms.configure", params).await?;
        Ok(())
    }

    /// Issue a signed JWT that lets a browser client join `room_id` without the
    /// API key. `ttl_seconds` defaults to 3600 (1 hour) when `None`.
    pub async fn issue_token(
        &self,
        room_id: &str,
        ttl_seconds: Option<u64>,
    ) -> Result<IssueTokenResponse> {
        let ttl = ttl_seconds.unwrap_or(DEFAULT_TOKEN_TTL);
        self.call(
            "rooms.issue_token",
            json!({ "room_id": room_id, "ttl_seconds": ttl }),
        )
        .await
    }

    /// Send one authenticated JSON-RPC request and deserialize its `result`.
    async fn call<P, T>(&self, method: &str, params: P) -> Result<T>
    where
        P: Serialize,
        T: DeserializeOwned,
    {
        let id = self.inner.next_id.fetch_add(1, Ordering::Relaxed);
        let body = json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
            "params": params,
        });

        let response = self
            .inner
            .http
            .post(&self.inner.server_url)
            .bearer_auth(&self.inner.api_key)
            .json(&body)
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(OnwardzError::Http(response.status()));
        }

        let envelope: RpcResponse<T> = response
            .json()
            .await
            .map_err(|e| OnwardzError::Decode(e.to_string()))?;

        if let Some(err) = envelope.error {
            return Err(OnwardzError::Rpc {
                code: err.code,
                message: err.message,
            });
        }

        envelope
            .result
            .ok_or_else(|| OnwardzError::Decode("response had neither result nor error".into()))
    }
}

/// Builder for [`OnwardzClient`].
pub struct OnwardzClientBuilder {
    api_key: String,
    server_url: String,
    http: Option<reqwest::Client>,
}

impl OnwardzClientBuilder {
    /// Override the API endpoint (for self-hosted deployments). Should point at
    /// the full `/rpc` URL.
    pub fn server_url(mut self, url: impl Into<String>) -> Self {
        self.server_url = url.into();
        self
    }

    /// Provide a preconfigured [`reqwest::Client`] (timeouts, proxy, etc.).
    pub fn http_client(mut self, client: reqwest::Client) -> Self {
        self.http = Some(client);
        self
    }

    /// Build the client.
    pub fn build(self) -> OnwardzClient {
        OnwardzClient {
            inner: Arc::new(Inner {
                http: self.http.unwrap_or_default(),
                server_url: self.server_url,
                api_key: self.api_key,
                next_id: AtomicU64::new(1),
            }),
        }
    }
}

/// The JSON-RPC 2.0 response envelope.
#[derive(serde::Deserialize)]
struct RpcResponse<T> {
    result: Option<T>,
    error: Option<RpcError>,
}

#[derive(serde::Deserialize)]
struct RpcError {
    code: i64,
    message: String,
}