use crate::event::TrackRequest;
use crate::{ApiError, BatchResponse, Context, Error, Result, Track, TrackKind, TrackResponse};
use reqwest::header::{HeaderValue, USER_AGENT};
use reqwest::{Response, Url};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::fmt;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use uuid::Uuid;
pub const CLOUD_ENDPOINT: &str = "https://gateway.umami.is/api/send";
const DEFAULT_USER_AGENT: &str = concat!("rust-umami/", env!("CARGO_PKG_VERSION"));
const MAX_BATCH_SIZE: usize = 500;
struct Inner {
http: reqwest::Client,
send_url: Url,
batch_url: Url,
website_id: Uuid,
context: Context,
user_agent: HeaderValue,
timeout: Option<Duration>,
}
#[derive(Clone)]
pub struct Client {
inner: Arc<Inner>,
}
impl fmt::Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Client")
.field("send_url", &self.inner.send_url)
.field("batch_url", &self.inner.batch_url)
.field("website_id", &self.inner.website_id)
.field("context", &self.inner.context)
.field("timeout", &self.inner.timeout)
.finish_non_exhaustive()
}
}
impl Client {
pub fn new(instance_url: impl Into<String>, website_id: impl ToString) -> Result<Self> {
Self::builder(instance_url, website_id).build()
}
pub fn cloud(website_id: impl ToString) -> Result<Self> {
Self::new(CLOUD_ENDPOINT, website_id)
}
#[must_use]
pub fn builder(instance_url: impl Into<String>, website_id: impl ToString) -> ClientBuilder {
ClientBuilder {
instance_url: instance_url.into(),
website_id: website_id.to_string(),
send_url: None,
batch_url: None,
context: Context::default(),
user_agent: DEFAULT_USER_AGENT.to_owned(),
http: None,
timeout: None,
}
}
#[must_use]
pub fn website_id(&self) -> Uuid {
self.inner.website_id
}
#[must_use]
pub fn endpoint(&self) -> &Url {
&self.inner.send_url
}
#[must_use]
pub fn batch_endpoint(&self) -> &Url {
&self.inner.batch_url
}
#[must_use]
pub fn default_context(&self) -> &Context {
&self.inner.context
}
#[must_use]
pub fn pageview(&self, url: impl Into<String>) -> Track {
Track::pageview(
Sender::stateless(self.clone()),
self.inner.context.clone(),
url.into(),
)
}
#[must_use]
pub fn event(&self, name: impl Into<String>) -> Track {
Track::event(
Sender::stateless(self.clone()),
self.inner.context.clone(),
name.into(),
)
}
#[must_use]
pub fn identify(&self, distinct_id: impl Into<String>) -> Track {
Track::identify(
Sender::stateless(self.clone()),
self.inner.context.clone(),
Some(distinct_id.into()),
)
}
#[must_use]
pub fn identify_anonymous(&self) -> Track {
Track::identify(
Sender::stateless(self.clone()),
self.inner.context.clone(),
None,
)
}
#[must_use]
pub fn performance(&self, url: impl Into<String>) -> Track {
Track::performance(
Sender::stateless(self.clone()),
self.inner.context.clone(),
url.into(),
)
}
#[must_use]
pub fn batch(&self) -> Batch {
Batch::new(Sender::stateless(self.clone()))
}
#[must_use]
pub fn session(&self) -> Session {
let context = self.inner.context.clone();
let sender = Sender::session(self.clone());
sender.set_identity(context.distinct_id.clone());
Session { sender, context }
}
async fn send_track(
&self,
request: TrackRequest,
cache: Option<String>,
) -> Result<TrackResponse> {
let hostname = request.hostname().map(ToOwned::to_owned);
self.post(
&self.inner.send_url,
&request,
cache.as_deref(),
hostname.as_deref(),
)
.await
}
async fn send_batch(
&self,
requests: Vec<TrackRequest>,
cache: Option<String>,
) -> Result<BatchResponse> {
let hostname = requests
.first()
.and_then(TrackRequest::hostname)
.map(ToOwned::to_owned);
self.post(
&self.inner.batch_url,
&requests,
cache.as_deref(),
hostname.as_deref(),
)
.await
}
async fn post<T: DeserializeOwned, B: Serialize + ?Sized>(
&self,
url: &Url,
body: &B,
cache: Option<&str>,
hostname: Option<&str>,
) -> Result<T> {
let mut request = self
.inner
.http
.post(url.clone())
.header(USER_AGENT, self.inner.user_agent.clone())
.header("x-umami-website-id", self.inner.website_id.to_string())
.json(body);
if let Some(timeout) = self.inner.timeout {
request = request.timeout(timeout);
}
if let Some(hostname) = hostname {
request = request.header("x-umami-hostname", hostname);
}
if let Some(cache) = cache {
let mut value = HeaderValue::from_str(cache).map_err(Error::InvalidCacheHeader)?;
value.set_sensitive(true);
request = request.header("x-umami-cache", value);
}
decode(request.send().await?).await
}
}
#[derive(Debug)]
pub struct ClientBuilder {
instance_url: String,
website_id: String,
send_url: Option<String>,
batch_url: Option<String>,
context: Context,
user_agent: String,
http: Option<reqwest::Client>,
timeout: Option<Duration>,
}
impl ClientBuilder {
#[must_use]
pub fn send_endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.send_url = Some(endpoint.into());
self
}
#[must_use]
pub fn batch_endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.batch_url = Some(endpoint.into());
self
}
#[must_use]
pub fn default_context(mut self, context: Context) -> Self {
self.context = context;
self
}
#[must_use]
pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
self.user_agent = user_agent.into();
self
}
#[must_use]
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
#[must_use]
pub fn http_client(mut self, client: reqwest::Client) -> Self {
self.http = Some(client);
self
}
pub fn build(self) -> Result<Client> {
let website_id = self.website_id.trim().to_owned();
let website_id =
Uuid::parse_str(&website_id).map_err(|source| Error::InvalidWebsiteId {
value: website_id,
source,
})?;
if self.user_agent.trim().is_empty() {
return Err(Error::EmptyUserAgent);
}
let user_agent = HeaderValue::from_str(&self.user_agent)?;
let (derived_send, derived_batch) = derive_endpoints(&self.instance_url)?;
let has_send_override = self.send_url.is_some();
let send_url = match self.send_url {
Some(url) => parse_endpoint(&url)?,
None => derived_send,
};
let batch_url = match self.batch_url {
Some(url) => parse_endpoint(&url)?,
None if has_send_override => sibling_endpoint(&send_url, "batch")?,
None => derived_batch,
};
let http = match self.http {
Some(http) => http,
None => reqwest::Client::builder().build()?,
};
Ok(Client {
inner: Arc::new(Inner {
http,
send_url,
batch_url,
website_id,
context: self.context,
user_agent,
timeout: self.timeout,
}),
})
}
}
#[derive(Clone)]
pub struct Session {
sender: Sender,
context: Context,
}
impl fmt::Debug for Session {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Session")
.field("client", &self.sender.client)
.field("context", &self.context)
.finish_non_exhaustive()
}
}
impl Session {
#[must_use]
pub fn context(mut self, context: Context) -> Self {
self.sender.set_identity(context.distinct_id.clone());
self.context = context;
self.sender.clear_cache();
self
}
#[must_use]
pub fn distinct_id(mut self, distinct_id: impl Into<String>) -> Self {
let distinct_id = distinct_id.into();
self.context.distinct_id = Some(distinct_id.clone());
self.sender.set_identity(Some(distinct_id));
self.sender.clear_cache();
self
}
#[must_use]
pub fn ip(mut self, ip: std::net::IpAddr) -> Self {
self.context.ip = Some(ip);
self
}
#[must_use]
pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
self.context.user_agent = Some(user_agent.into());
self
}
#[must_use]
pub fn hostname(mut self, hostname: impl Into<String>) -> Self {
self.context.hostname = Some(hostname.into());
self
}
#[must_use]
pub fn language(mut self, language: impl Into<String>) -> Self {
self.context.language = Some(language.into());
self
}
pub fn reset(&self) {
self.sender.clear_cache();
}
#[must_use]
pub fn pageview(&self, url: impl Into<String>) -> Track {
Track::pageview(self.sender.clone(), self.track_context(), url.into())
}
#[must_use]
pub fn event(&self, name: impl Into<String>) -> Track {
Track::event(self.sender.clone(), self.track_context(), name.into())
}
#[must_use]
pub fn identify(&self, distinct_id: impl Into<String>) -> Track {
let distinct_id = distinct_id.into();
self.sender.set_identity(Some(distinct_id.clone()));
Track::identify(self.sender.clone(), self.track_context(), Some(distinct_id))
}
#[must_use]
pub fn identify_anonymous(&self) -> Track {
Track::identify(self.sender.clone(), self.track_context(), None)
}
#[must_use]
pub fn performance(&self, url: impl Into<String>) -> Track {
Track::performance(self.sender.clone(), self.track_context(), url.into())
}
#[must_use]
pub fn batch(&self) -> Batch {
Batch::new(self.sender.clone())
}
fn track_context(&self) -> Context {
let mut context = self.context.clone();
if self.sender.identity.is_some() {
context.distinct_id = self.sender.current_identity();
}
context
}
}
pub struct Batch {
sender: Sender,
requests: Vec<TrackRequest>,
cache: Option<String>,
error: Option<Error>,
}
impl fmt::Debug for Batch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Batch")
.field("len", &self.requests.len())
.field("has_cache", &self.cache.is_some())
.field("error", &self.error)
.finish_non_exhaustive()
}
}
impl Batch {
fn new(sender: Sender) -> Self {
Self {
sender,
requests: Vec::new(),
cache: None,
error: None,
}
}
#[must_use]
pub fn push(mut self, track: Track) -> Self {
if self.error.is_some() {
return self;
}
match track.into_parts() {
Ok((sender, request, cache)) => {
if !self.sender.same_origin(&sender) {
self.error = Some(Error::MismatchedBatch);
return self;
}
if let Some(cache) = cache {
match &self.cache {
Some(current) if current != &cache => {
self.error = Some(Error::InvalidTrack(
"all tracks in a batch must use the same cache value".into(),
));
return self;
}
None => self.cache = Some(cache),
_ => {}
}
}
self.requests.push(request);
}
Err(error) => self.error = Some(error),
}
self
}
#[must_use]
pub fn extend(mut self, tracks: impl IntoIterator<Item = Track>) -> Self {
for track in tracks {
self = self.push(track);
}
self
}
#[must_use]
pub fn continue_from(mut self, response: &TrackResponse) -> Self {
self.cache.clone_from(&response.cache);
self
}
#[must_use]
pub fn len(&self) -> usize {
self.requests.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.requests.is_empty()
}
pub async fn send(self) -> Result<BatchResponse> {
if let Some(error) = self.error {
return Err(error);
}
if self.requests.len() > MAX_BATCH_SIZE {
return Err(Error::BatchTooLarge {
len: self.requests.len(),
max: MAX_BATCH_SIZE,
});
}
self.sender.send_batch(self.requests, self.cache).await
}
}
#[derive(Clone)]
pub(crate) struct Sender {
client: Client,
cache: Option<Arc<Mutex<Option<String>>>>,
identity: Option<Arc<Mutex<Option<String>>>>,
}
impl fmt::Debug for Sender {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Sender")
.field("client", &self.client)
.field("session_cache", &self.cache.is_some())
.finish()
}
}
impl Sender {
fn stateless(client: Client) -> Self {
Self {
client,
cache: None,
identity: None,
}
}
fn session(client: Client) -> Self {
Self {
client,
cache: Some(Arc::new(Mutex::new(None))),
identity: Some(Arc::new(Mutex::new(None))),
}
}
pub(crate) fn website_id(&self) -> Uuid {
self.client.inner.website_id
}
fn same_origin(&self, other: &Self) -> bool {
if !Arc::ptr_eq(&self.client.inner, &other.client.inner) {
return false;
}
match (&self.cache, &other.cache) {
(None, None) => true,
(Some(left), Some(right)) => Arc::ptr_eq(left, right),
_ => false,
}
}
fn current_cache(&self) -> Option<String> {
self.cache.as_ref().and_then(|cache| {
cache
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
})
}
fn set_cache(&self, value: Option<String>) {
if let Some(cache) = &self.cache {
*cache
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = value;
}
}
fn clear_cache(&self) {
self.set_cache(None);
}
fn current_identity(&self) -> Option<String> {
self.identity.as_ref().and_then(|identity| {
identity
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
})
}
fn set_identity(&self, value: Option<String>) {
if let Some(identity) = &self.identity {
*identity
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = value;
}
}
pub(crate) async fn send(
&self,
request: TrackRequest,
explicit_cache: Option<String>,
) -> Result<TrackResponse> {
if request.kind() == TrackKind::Identify {
self.clear_cache();
}
let cache = explicit_cache.or_else(|| self.current_cache());
let response = self.client.send_track(request, cache).await?;
self.set_cache(response.cache.clone());
Ok(response)
}
async fn send_batch(
&self,
requests: Vec<TrackRequest>,
explicit_cache: Option<String>,
) -> Result<BatchResponse> {
let contains_identify = requests
.iter()
.any(|request| request.kind() == TrackKind::Identify);
if contains_identify {
self.clear_cache();
}
let cache = explicit_cache.or_else(|| self.current_cache());
let response = self.client.send_batch(requests, cache).await?;
self.set_cache(if contains_identify {
None
} else {
response.cache.clone()
});
Ok(response)
}
}
async fn decode<T: DeserializeOwned>(response: Response) -> Result<T> {
let status = response.status();
let bytes = response.bytes().await?;
if !status.is_success() {
let body = serde_json::from_slice::<Value>(&bytes)
.unwrap_or_else(|_| Value::String(body_excerpt(&bytes)));
let details = body.get("error").unwrap_or(&body);
let message = details
.get("message")
.and_then(Value::as_str)
.map(ToOwned::to_owned)
.unwrap_or_else(|| {
status
.canonical_reason()
.unwrap_or("request failed")
.to_owned()
});
let code = details
.get("code")
.and_then(Value::as_str)
.map(ToOwned::to_owned);
return Err(ApiError {
status,
code,
message,
body,
}
.into());
}
serde_json::from_slice(&bytes).map_err(|source| Error::Decode {
status,
source,
body: body_excerpt(&bytes),
})
}
fn body_excerpt(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).chars().take(2_048).collect()
}
fn derive_endpoints(instance_url: &str) -> Result<(Url, Url)> {
let base = parse_endpoint(instance_url)?;
let segments: Vec<_> = base
.path_segments()
.ok_or_else(|| Error::InvalidEndpoint("URL cannot be used as a base".into()))?
.filter(|segment| !segment.is_empty())
.collect();
if segments.last() == Some(&"send") {
let batch = sibling_endpoint(&base, "batch")?;
return Ok((base, batch));
}
if segments.last() == Some(&"api") {
let send = append_segments(&base, &["send"])?;
let batch = append_segments(&base, &["batch"])?;
return Ok((send, batch));
}
let api = append_segments(&base, &["api"])?;
let send = append_segments(&api, &["send"])?;
let batch = append_segments(&api, &["batch"])?;
Ok((send, batch))
}
fn parse_endpoint(value: &str) -> Result<Url> {
let url = Url::parse(value)?;
if !matches!(url.scheme(), "http" | "https") {
return Err(Error::InvalidEndpoint(
"URL scheme must be http or https".into(),
));
}
if url.query().is_some() || url.fragment().is_some() {
return Err(Error::InvalidEndpoint(
"endpoint URLs cannot contain a query string or fragment".into(),
));
}
if url.cannot_be_a_base() {
return Err(Error::InvalidEndpoint(
"URL cannot be used as a base".into(),
));
}
Ok(url)
}
fn append_segments(url: &Url, segments: &[&str]) -> Result<Url> {
let mut url = url.clone();
url.path_segments_mut()
.map_err(|()| Error::InvalidEndpoint("URL cannot contain path segments".into()))?
.pop_if_empty()
.extend(segments);
Ok(url)
}
fn sibling_endpoint(url: &Url, name: &str) -> Result<Url> {
let mut url = url.clone();
url.path_segments_mut()
.map_err(|()| Error::InvalidEndpoint("URL cannot contain path segments".into()))?
.pop_if_empty()
.pop()
.push(name);
Ok(url)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn derives_endpoints_from_supported_inputs() {
for (input, send, batch) in [
(
"https://example.com",
"https://example.com/api/send",
"https://example.com/api/batch",
),
(
"https://example.com/umami/",
"https://example.com/umami/api/send",
"https://example.com/umami/api/batch",
),
(
"https://example.com/api",
"https://example.com/api/send",
"https://example.com/api/batch",
),
(
"https://example.com/api/send",
"https://example.com/api/send",
"https://example.com/api/batch",
),
] {
let (actual_send, actual_batch) = derive_endpoints(input).unwrap();
assert_eq!(actual_send.as_str(), send);
assert_eq!(actual_batch.as_str(), batch);
}
}
#[test]
fn rejects_non_http_endpoints() {
assert!(derive_endpoints("file:///tmp/umami").is_err());
}
}