1use crate::event::TrackRequest;
2use crate::{ApiError, BatchResponse, Context, Error, Result, Track, TrackKind, TrackResponse};
3use reqwest::header::{HeaderValue, USER_AGENT};
4use reqwest::{Response, Url};
5use serde::Serialize;
6use serde::de::DeserializeOwned;
7use serde_json::Value;
8use std::fmt;
9use std::sync::{Arc, Mutex};
10use std::time::Duration;
11use uuid::Uuid;
12
13pub const CLOUD_ENDPOINT: &str = "https://gateway.umami.is/api/send";
18
19const DEFAULT_USER_AGENT: &str = concat!("rust-umami/", env!("CARGO_PKG_VERSION"));
20const MAX_BATCH_SIZE: usize = 500;
21
22struct Inner {
23 http: reqwest::Client,
24 send_url: Url,
25 batch_url: Url,
26 website_id: Uuid,
27 context: Context,
28 user_agent: HeaderValue,
29 timeout: Option<Duration>,
30}
31
32#[derive(Clone)]
38pub struct Client {
39 inner: Arc<Inner>,
40}
41
42impl fmt::Debug for Client {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 f.debug_struct("Client")
45 .field("send_url", &self.inner.send_url)
46 .field("batch_url", &self.inner.batch_url)
47 .field("website_id", &self.inner.website_id)
48 .field("context", &self.inner.context)
49 .field("timeout", &self.inner.timeout)
50 .finish_non_exhaustive()
51 }
52}
53
54impl Client {
55 pub fn new(instance_url: impl Into<String>, website_id: impl ToString) -> Result<Self> {
61 Self::builder(instance_url, website_id).build()
62 }
63
64 pub fn cloud(website_id: impl ToString) -> Result<Self> {
66 Self::new(CLOUD_ENDPOINT, website_id)
67 }
68
69 #[must_use]
71 pub fn builder(instance_url: impl Into<String>, website_id: impl ToString) -> ClientBuilder {
72 ClientBuilder {
73 instance_url: instance_url.into(),
74 website_id: website_id.to_string(),
75 send_url: None,
76 batch_url: None,
77 context: Context::default(),
78 user_agent: DEFAULT_USER_AGENT.to_owned(),
79 http: None,
80 timeout: None,
81 }
82 }
83
84 #[must_use]
86 pub fn website_id(&self) -> Uuid {
87 self.inner.website_id
88 }
89
90 #[must_use]
92 pub fn endpoint(&self) -> &Url {
93 &self.inner.send_url
94 }
95
96 #[must_use]
98 pub fn batch_endpoint(&self) -> &Url {
99 &self.inner.batch_url
100 }
101
102 #[must_use]
104 pub fn default_context(&self) -> &Context {
105 &self.inner.context
106 }
107
108 #[must_use]
110 pub fn pageview(&self, url: impl Into<String>) -> Track {
111 Track::pageview(
112 Sender::stateless(self.clone()),
113 self.inner.context.clone(),
114 url.into(),
115 )
116 }
117
118 #[must_use]
120 pub fn event(&self, name: impl Into<String>) -> Track {
121 Track::event(
122 Sender::stateless(self.clone()),
123 self.inner.context.clone(),
124 name.into(),
125 )
126 }
127
128 #[must_use]
130 pub fn identify(&self, distinct_id: impl Into<String>) -> Track {
131 Track::identify(
132 Sender::stateless(self.clone()),
133 self.inner.context.clone(),
134 Some(distinct_id.into()),
135 )
136 }
137
138 #[must_use]
141 pub fn identify_anonymous(&self) -> Track {
142 Track::identify(
143 Sender::stateless(self.clone()),
144 self.inner.context.clone(),
145 None,
146 )
147 }
148
149 #[must_use]
151 pub fn performance(&self, url: impl Into<String>) -> Track {
152 Track::performance(
153 Sender::stateless(self.clone()),
154 self.inner.context.clone(),
155 url.into(),
156 )
157 }
158
159 #[must_use]
161 pub fn batch(&self) -> Batch {
162 Batch::new(Sender::stateless(self.clone()))
163 }
164
165 #[must_use]
170 pub fn session(&self) -> Session {
171 let context = self.inner.context.clone();
172 let sender = Sender::session(self.clone());
173 sender.set_identity(context.distinct_id.clone());
174 Session { sender, context }
175 }
176
177 async fn send_track(
178 &self,
179 request: TrackRequest,
180 cache: Option<String>,
181 ) -> Result<TrackResponse> {
182 let hostname = request.hostname().map(ToOwned::to_owned);
183 self.post(
184 &self.inner.send_url,
185 &request,
186 cache.as_deref(),
187 hostname.as_deref(),
188 )
189 .await
190 }
191
192 async fn send_batch(
193 &self,
194 requests: Vec<TrackRequest>,
195 cache: Option<String>,
196 ) -> Result<BatchResponse> {
197 let hostname = requests
198 .first()
199 .and_then(TrackRequest::hostname)
200 .map(ToOwned::to_owned);
201 self.post(
202 &self.inner.batch_url,
203 &requests,
204 cache.as_deref(),
205 hostname.as_deref(),
206 )
207 .await
208 }
209
210 async fn post<T: DeserializeOwned, B: Serialize + ?Sized>(
211 &self,
212 url: &Url,
213 body: &B,
214 cache: Option<&str>,
215 hostname: Option<&str>,
216 ) -> Result<T> {
217 let mut request = self
218 .inner
219 .http
220 .post(url.clone())
221 .header(USER_AGENT, self.inner.user_agent.clone())
222 .header("x-umami-website-id", self.inner.website_id.to_string())
223 .json(body);
224
225 if let Some(timeout) = self.inner.timeout {
226 request = request.timeout(timeout);
227 }
228 if let Some(hostname) = hostname {
229 request = request.header("x-umami-hostname", hostname);
230 }
231 if let Some(cache) = cache {
232 let mut value = HeaderValue::from_str(cache).map_err(Error::InvalidCacheHeader)?;
233 value.set_sensitive(true);
234 request = request.header("x-umami-cache", value);
235 }
236
237 decode(request.send().await?).await
238 }
239}
240
241#[derive(Debug)]
243pub struct ClientBuilder {
244 instance_url: String,
245 website_id: String,
246 send_url: Option<String>,
247 batch_url: Option<String>,
248 context: Context,
249 user_agent: String,
250 http: Option<reqwest::Client>,
251 timeout: Option<Duration>,
252}
253
254impl ClientBuilder {
255 #[must_use]
260 pub fn send_endpoint(mut self, endpoint: impl Into<String>) -> Self {
261 self.send_url = Some(endpoint.into());
262 self
263 }
264
265 #[must_use]
267 pub fn batch_endpoint(mut self, endpoint: impl Into<String>) -> Self {
268 self.batch_url = Some(endpoint.into());
269 self
270 }
271
272 #[must_use]
274 pub fn default_context(mut self, context: Context) -> Self {
275 self.context = context;
276 self
277 }
278
279 #[must_use]
284 pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
285 self.user_agent = user_agent.into();
286 self
287 }
288
289 #[must_use]
291 pub fn timeout(mut self, timeout: Duration) -> Self {
292 self.timeout = Some(timeout);
293 self
294 }
295
296 #[must_use]
301 pub fn http_client(mut self, client: reqwest::Client) -> Self {
302 self.http = Some(client);
303 self
304 }
305
306 pub fn build(self) -> Result<Client> {
308 let website_id = self.website_id.trim().to_owned();
309 let website_id =
310 Uuid::parse_str(&website_id).map_err(|source| Error::InvalidWebsiteId {
311 value: website_id,
312 source,
313 })?;
314
315 if self.user_agent.trim().is_empty() {
316 return Err(Error::EmptyUserAgent);
317 }
318 let user_agent = HeaderValue::from_str(&self.user_agent)?;
319
320 let (derived_send, derived_batch) = derive_endpoints(&self.instance_url)?;
321 let has_send_override = self.send_url.is_some();
322 let send_url = match self.send_url {
323 Some(url) => parse_endpoint(&url)?,
324 None => derived_send,
325 };
326 let batch_url = match self.batch_url {
327 Some(url) => parse_endpoint(&url)?,
328 None if has_send_override => sibling_endpoint(&send_url, "batch")?,
329 None => derived_batch,
330 };
331
332 let http = match self.http {
333 Some(http) => http,
334 None => reqwest::Client::builder().build()?,
335 };
336
337 Ok(Client {
338 inner: Arc::new(Inner {
339 http,
340 send_url,
341 batch_url,
342 website_id,
343 context: self.context,
344 user_agent,
345 timeout: self.timeout,
346 }),
347 })
348 }
349}
350
351#[derive(Clone)]
356pub struct Session {
357 sender: Sender,
358 context: Context,
359}
360
361impl fmt::Debug for Session {
362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363 f.debug_struct("Session")
364 .field("client", &self.sender.client)
365 .field("context", &self.context)
366 .finish_non_exhaustive()
367 }
368}
369
370impl Session {
371 #[must_use]
373 pub fn context(mut self, context: Context) -> Self {
374 self.sender.set_identity(context.distinct_id.clone());
375 self.context = context;
376 self.sender.clear_cache();
377 self
378 }
379
380 #[must_use]
383 pub fn distinct_id(mut self, distinct_id: impl Into<String>) -> Self {
384 let distinct_id = distinct_id.into();
385 self.context.distinct_id = Some(distinct_id.clone());
386 self.sender.set_identity(Some(distinct_id));
387 self.sender.clear_cache();
388 self
389 }
390
391 #[must_use]
393 pub fn ip(mut self, ip: std::net::IpAddr) -> Self {
394 self.context.ip = Some(ip);
395 self
396 }
397
398 #[must_use]
400 pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
401 self.context.user_agent = Some(user_agent.into());
402 self
403 }
404
405 #[must_use]
407 pub fn hostname(mut self, hostname: impl Into<String>) -> Self {
408 self.context.hostname = Some(hostname.into());
409 self
410 }
411
412 #[must_use]
414 pub fn language(mut self, language: impl Into<String>) -> Self {
415 self.context.language = Some(language.into());
416 self
417 }
418
419 pub fn reset(&self) {
421 self.sender.clear_cache();
422 }
423
424 #[must_use]
426 pub fn pageview(&self, url: impl Into<String>) -> Track {
427 Track::pageview(self.sender.clone(), self.track_context(), url.into())
428 }
429
430 #[must_use]
432 pub fn event(&self, name: impl Into<String>) -> Track {
433 Track::event(self.sender.clone(), self.track_context(), name.into())
434 }
435
436 #[must_use]
438 pub fn identify(&self, distinct_id: impl Into<String>) -> Track {
439 let distinct_id = distinct_id.into();
440 self.sender.set_identity(Some(distinct_id.clone()));
441 Track::identify(self.sender.clone(), self.track_context(), Some(distinct_id))
442 }
443
444 #[must_use]
446 pub fn identify_anonymous(&self) -> Track {
447 Track::identify(self.sender.clone(), self.track_context(), None)
448 }
449
450 #[must_use]
452 pub fn performance(&self, url: impl Into<String>) -> Track {
453 Track::performance(self.sender.clone(), self.track_context(), url.into())
454 }
455
456 #[must_use]
458 pub fn batch(&self) -> Batch {
459 Batch::new(self.sender.clone())
460 }
461
462 fn track_context(&self) -> Context {
463 let mut context = self.context.clone();
464 if self.sender.identity.is_some() {
465 context.distinct_id = self.sender.current_identity();
466 }
467 context
468 }
469}
470
471pub struct Batch {
473 sender: Sender,
474 requests: Vec<TrackRequest>,
475 cache: Option<String>,
476 error: Option<Error>,
477}
478
479impl fmt::Debug for Batch {
480 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
481 f.debug_struct("Batch")
482 .field("len", &self.requests.len())
483 .field("has_cache", &self.cache.is_some())
484 .field("error", &self.error)
485 .finish_non_exhaustive()
486 }
487}
488
489impl Batch {
490 fn new(sender: Sender) -> Self {
491 Self {
492 sender,
493 requests: Vec::new(),
494 cache: None,
495 error: None,
496 }
497 }
498
499 #[must_use]
503 pub fn push(mut self, track: Track) -> Self {
504 if self.error.is_some() {
505 return self;
506 }
507
508 match track.into_parts() {
509 Ok((sender, request, cache)) => {
510 if !self.sender.same_origin(&sender) {
511 self.error = Some(Error::MismatchedBatch);
512 return self;
513 }
514 if let Some(cache) = cache {
515 match &self.cache {
516 Some(current) if current != &cache => {
517 self.error = Some(Error::InvalidTrack(
518 "all tracks in a batch must use the same cache value".into(),
519 ));
520 return self;
521 }
522 None => self.cache = Some(cache),
523 _ => {}
524 }
525 }
526 self.requests.push(request);
527 }
528 Err(error) => self.error = Some(error),
529 }
530 self
531 }
532
533 #[must_use]
535 pub fn extend(mut self, tracks: impl IntoIterator<Item = Track>) -> Self {
536 for track in tracks {
537 self = self.push(track);
538 }
539 self
540 }
541
542 #[must_use]
544 pub fn continue_from(mut self, response: &TrackResponse) -> Self {
545 self.cache.clone_from(&response.cache);
546 self
547 }
548
549 #[must_use]
551 pub fn len(&self) -> usize {
552 self.requests.len()
553 }
554
555 #[must_use]
557 pub fn is_empty(&self) -> bool {
558 self.requests.is_empty()
559 }
560
561 pub async fn send(self) -> Result<BatchResponse> {
563 if let Some(error) = self.error {
564 return Err(error);
565 }
566 if self.requests.len() > MAX_BATCH_SIZE {
567 return Err(Error::BatchTooLarge {
568 len: self.requests.len(),
569 max: MAX_BATCH_SIZE,
570 });
571 }
572 self.sender.send_batch(self.requests, self.cache).await
573 }
574}
575
576#[derive(Clone)]
577pub(crate) struct Sender {
578 client: Client,
579 cache: Option<Arc<Mutex<Option<String>>>>,
580 identity: Option<Arc<Mutex<Option<String>>>>,
581}
582
583impl fmt::Debug for Sender {
584 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
585 f.debug_struct("Sender")
586 .field("client", &self.client)
587 .field("session_cache", &self.cache.is_some())
588 .finish()
589 }
590}
591
592impl Sender {
593 fn stateless(client: Client) -> Self {
594 Self {
595 client,
596 cache: None,
597 identity: None,
598 }
599 }
600
601 fn session(client: Client) -> Self {
602 Self {
603 client,
604 cache: Some(Arc::new(Mutex::new(None))),
605 identity: Some(Arc::new(Mutex::new(None))),
606 }
607 }
608
609 pub(crate) fn website_id(&self) -> Uuid {
610 self.client.inner.website_id
611 }
612
613 fn same_origin(&self, other: &Self) -> bool {
614 if !Arc::ptr_eq(&self.client.inner, &other.client.inner) {
615 return false;
616 }
617 match (&self.cache, &other.cache) {
618 (None, None) => true,
619 (Some(left), Some(right)) => Arc::ptr_eq(left, right),
620 _ => false,
621 }
622 }
623
624 fn current_cache(&self) -> Option<String> {
625 self.cache.as_ref().and_then(|cache| {
626 cache
627 .lock()
628 .unwrap_or_else(std::sync::PoisonError::into_inner)
629 .clone()
630 })
631 }
632
633 fn set_cache(&self, value: Option<String>) {
634 if let Some(cache) = &self.cache {
635 *cache
636 .lock()
637 .unwrap_or_else(std::sync::PoisonError::into_inner) = value;
638 }
639 }
640
641 fn clear_cache(&self) {
642 self.set_cache(None);
643 }
644
645 fn current_identity(&self) -> Option<String> {
646 self.identity.as_ref().and_then(|identity| {
647 identity
648 .lock()
649 .unwrap_or_else(std::sync::PoisonError::into_inner)
650 .clone()
651 })
652 }
653
654 fn set_identity(&self, value: Option<String>) {
655 if let Some(identity) = &self.identity {
656 *identity
657 .lock()
658 .unwrap_or_else(std::sync::PoisonError::into_inner) = value;
659 }
660 }
661
662 pub(crate) async fn send(
663 &self,
664 request: TrackRequest,
665 explicit_cache: Option<String>,
666 ) -> Result<TrackResponse> {
667 if request.kind() == TrackKind::Identify {
668 self.clear_cache();
669 }
670 let cache = explicit_cache.or_else(|| self.current_cache());
671 let response = self.client.send_track(request, cache).await?;
672 self.set_cache(response.cache.clone());
673 Ok(response)
674 }
675
676 async fn send_batch(
677 &self,
678 requests: Vec<TrackRequest>,
679 explicit_cache: Option<String>,
680 ) -> Result<BatchResponse> {
681 let contains_identify = requests
682 .iter()
683 .any(|request| request.kind() == TrackKind::Identify);
684 if contains_identify {
685 self.clear_cache();
686 }
687 let cache = explicit_cache.or_else(|| self.current_cache());
688 let response = self.client.send_batch(requests, cache).await?;
689 self.set_cache(if contains_identify {
693 None
694 } else {
695 response.cache.clone()
696 });
697 Ok(response)
698 }
699}
700
701async fn decode<T: DeserializeOwned>(response: Response) -> Result<T> {
702 let status = response.status();
703 let bytes = response.bytes().await?;
704
705 if !status.is_success() {
706 let body = serde_json::from_slice::<Value>(&bytes)
707 .unwrap_or_else(|_| Value::String(body_excerpt(&bytes)));
708 let details = body.get("error").unwrap_or(&body);
709 let message = details
710 .get("message")
711 .and_then(Value::as_str)
712 .map(ToOwned::to_owned)
713 .unwrap_or_else(|| {
714 status
715 .canonical_reason()
716 .unwrap_or("request failed")
717 .to_owned()
718 });
719 let code = details
720 .get("code")
721 .and_then(Value::as_str)
722 .map(ToOwned::to_owned);
723 return Err(ApiError {
724 status,
725 code,
726 message,
727 body,
728 }
729 .into());
730 }
731
732 serde_json::from_slice(&bytes).map_err(|source| Error::Decode {
733 status,
734 source,
735 body: body_excerpt(&bytes),
736 })
737}
738
739fn body_excerpt(bytes: &[u8]) -> String {
740 String::from_utf8_lossy(bytes).chars().take(2_048).collect()
741}
742
743fn derive_endpoints(instance_url: &str) -> Result<(Url, Url)> {
744 let base = parse_endpoint(instance_url)?;
745 let segments: Vec<_> = base
746 .path_segments()
747 .ok_or_else(|| Error::InvalidEndpoint("URL cannot be used as a base".into()))?
748 .filter(|segment| !segment.is_empty())
749 .collect();
750
751 if segments.last() == Some(&"send") {
752 let batch = sibling_endpoint(&base, "batch")?;
753 return Ok((base, batch));
754 }
755
756 if segments.last() == Some(&"api") {
757 let send = append_segments(&base, &["send"])?;
758 let batch = append_segments(&base, &["batch"])?;
759 return Ok((send, batch));
760 }
761
762 let api = append_segments(&base, &["api"])?;
763 let send = append_segments(&api, &["send"])?;
764 let batch = append_segments(&api, &["batch"])?;
765 Ok((send, batch))
766}
767
768fn parse_endpoint(value: &str) -> Result<Url> {
769 let url = Url::parse(value)?;
770 if !matches!(url.scheme(), "http" | "https") {
771 return Err(Error::InvalidEndpoint(
772 "URL scheme must be http or https".into(),
773 ));
774 }
775 if url.query().is_some() || url.fragment().is_some() {
776 return Err(Error::InvalidEndpoint(
777 "endpoint URLs cannot contain a query string or fragment".into(),
778 ));
779 }
780 if url.cannot_be_a_base() {
781 return Err(Error::InvalidEndpoint(
782 "URL cannot be used as a base".into(),
783 ));
784 }
785 Ok(url)
786}
787
788fn append_segments(url: &Url, segments: &[&str]) -> Result<Url> {
789 let mut url = url.clone();
790 url.path_segments_mut()
791 .map_err(|()| Error::InvalidEndpoint("URL cannot contain path segments".into()))?
792 .pop_if_empty()
793 .extend(segments);
794 Ok(url)
795}
796
797fn sibling_endpoint(url: &Url, name: &str) -> Result<Url> {
798 let mut url = url.clone();
799 url.path_segments_mut()
800 .map_err(|()| Error::InvalidEndpoint("URL cannot contain path segments".into()))?
801 .pop_if_empty()
802 .pop()
803 .push(name);
804 Ok(url)
805}
806
807#[cfg(test)]
808mod tests {
809 use super::*;
810
811 #[test]
812 fn derives_endpoints_from_supported_inputs() {
813 for (input, send, batch) in [
814 (
815 "https://example.com",
816 "https://example.com/api/send",
817 "https://example.com/api/batch",
818 ),
819 (
820 "https://example.com/umami/",
821 "https://example.com/umami/api/send",
822 "https://example.com/umami/api/batch",
823 ),
824 (
825 "https://example.com/api",
826 "https://example.com/api/send",
827 "https://example.com/api/batch",
828 ),
829 (
830 "https://example.com/api/send",
831 "https://example.com/api/send",
832 "https://example.com/api/batch",
833 ),
834 ] {
835 let (actual_send, actual_batch) = derive_endpoints(input).unwrap();
836 assert_eq!(actual_send.as_str(), send);
837 assert_eq!(actual_batch.as_str(), batch);
838 }
839 }
840
841 #[test]
842 fn rejects_non_http_endpoints() {
843 assert!(derive_endpoints("file:///tmp/umami").is_err());
844 }
845}