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,
};
pub const DEFAULT_SERVER_URL: &str = "https://api.onwardz.com/rpc";
const DEFAULT_TOKEN_TTL: u64 = 3600;
#[derive(Clone)]
pub struct OnwardzClient {
inner: Arc<Inner>,
}
struct Inner {
http: reqwest::Client,
server_url: String,
api_key: String,
next_id: AtomicU64,
}
impl OnwardzClient {
pub fn new(api_key: impl Into<String>) -> Self {
Self::builder(api_key).build()
}
pub fn builder(api_key: impl Into<String>) -> OnwardzClientBuilder {
OnwardzClientBuilder {
api_key: api_key.into(),
server_url: DEFAULT_SERVER_URL.to_string(),
http: None,
}
}
pub async fn create_room(&self, opts: CreateRoomOptions) -> Result<CreateRoomResponse> {
self.call("rooms.create", opts).await
}
pub async fn list_rooms(&self) -> Result<Vec<Room>> {
let resp: ListRoomsResponse = self.call("rooms.list", json!({})).await?;
Ok(resp.rooms)
}
pub async fn delete_room(&self, room_id: &str) -> Result<()> {
let _: Value = self
.call("rooms.delete", json!({ "room_id": room_id }))
.await?;
Ok(())
}
pub async fn configure_room(&self, room_id: &str, opts: ConfigureRoomOptions) -> Result<()> {
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(())
}
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
}
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()))
}
}
pub struct OnwardzClientBuilder {
api_key: String,
server_url: String,
http: Option<reqwest::Client>,
}
impl OnwardzClientBuilder {
pub fn server_url(mut self, url: impl Into<String>) -> Self {
self.server_url = url.into();
self
}
pub fn http_client(mut self, client: reqwest::Client) -> Self {
self.http = Some(client);
self
}
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),
}),
}
}
}
#[derive(serde::Deserialize)]
struct RpcResponse<T> {
result: Option<T>,
error: Option<RpcError>,
}
#[derive(serde::Deserialize)]
struct RpcError {
code: i64,
message: String,
}