rust-umami 0.1.1

An ergonomic Rust client for Umami Analytics event ingestion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
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;

/// Current Umami Cloud collection endpoint.
///
/// This is the unauthenticated analytics gateway, not the authenticated
/// reporting API at `api.umami.is`.
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>,
}

/// Async client for Umami's unauthenticated analytics ingestion API.
///
/// The client is cheap to clone and is stateless, making it safe to share
/// across visitors. Use [`Client::session`] when sending a sequence of tracks
/// for one visitor and you want automatic cache reuse.
#[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 {
    /// Creates a client for a self-hosted Umami instance.
    ///
    /// `instance_url` may be the instance root (`https://analytics.example.com`),
    /// its API root (`https://analytics.example.com/api`), or the exact send
    /// endpoint (`https://analytics.example.com/api/send`).
    pub fn new(instance_url: impl Into<String>, website_id: impl ToString) -> Result<Self> {
        Self::builder(instance_url, website_id).build()
    }

    /// Creates a client for Umami Cloud's public collection gateway.
    pub fn cloud(website_id: impl ToString) -> Result<Self> {
        Self::new(CLOUD_ENDPOINT, website_id)
    }

    /// Starts a configurable client builder.
    #[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,
        }
    }

    /// Returns the configured website ID.
    #[must_use]
    pub fn website_id(&self) -> Uuid {
        self.inner.website_id
    }

    /// Returns the single-track collection endpoint.
    #[must_use]
    pub fn endpoint(&self) -> &Url {
        &self.inner.send_url
    }

    /// Returns the batch collection endpoint.
    #[must_use]
    pub fn batch_endpoint(&self) -> &Url {
        &self.inner.batch_url
    }

    /// Returns the default context inherited by new tracks.
    #[must_use]
    pub fn default_context(&self) -> &Context {
        &self.inner.context
    }

    /// Creates a pageview track.
    #[must_use]
    pub fn pageview(&self, url: impl Into<String>) -> Track {
        Track::pageview(
            Sender::stateless(self.clone()),
            self.inner.context.clone(),
            url.into(),
        )
    }

    /// Creates a named custom-event track.
    #[must_use]
    pub fn event(&self, name: impl Into<String>) -> Track {
        Track::event(
            Sender::stateless(self.clone()),
            self.inner.context.clone(),
            name.into(),
        )
    }

    /// Creates an identify track for a stable distinct ID.
    #[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()),
        )
    }

    /// Creates an identify track that associates properties without assigning
    /// a distinct ID.
    #[must_use]
    pub fn identify_anonymous(&self) -> Track {
        Track::identify(
            Sender::stateless(self.clone()),
            self.inner.context.clone(),
            None,
        )
    }

    /// Creates a Core Web Vitals performance track.
    #[must_use]
    pub fn performance(&self, url: impl Into<String>) -> Track {
        Track::performance(
            Sender::stateless(self.clone()),
            self.inner.context.clone(),
            url.into(),
        )
    }

    /// Starts an empty analytics batch.
    #[must_use]
    pub fn batch(&self) -> Batch {
        Batch::new(Sender::stateless(self.clone()))
    }

    /// Creates isolated state for a sequence of tracks from one visitor.
    ///
    /// Clones of the returned session share its cache, while other sessions and
    /// the client itself remain independent.
    #[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
    }
}

/// Builder for [`Client`].
#[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 {
    /// Overrides the exact `/send` endpoint.
    ///
    /// If no batch endpoint is supplied, a sibling path ending in `/batch` is
    /// derived from this URL.
    #[must_use]
    pub fn send_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.send_url = Some(endpoint.into());
        self
    }

    /// Overrides the exact `/batch` endpoint.
    #[must_use]
    pub fn batch_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.batch_url = Some(endpoint.into());
        self
    }

    /// Sets context inherited by every new track and session.
    #[must_use]
    pub fn default_context(mut self, context: Context) -> Self {
        self.context = context;
        self
    }

    /// Sets the HTTP user-agent header.
    ///
    /// Umami rejects ingestion requests without a proper user-agent. The
    /// default is `rust-umami/<crate-version>`.
    #[must_use]
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = user_agent.into();
        self
    }

    /// Sets a timeout applied to each ingestion request.
    #[must_use]
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Uses a caller-configured Reqwest client.
    ///
    /// This is useful for custom proxies, TLS settings, connection pools, or
    /// middleware. The Umami-specific user-agent is still applied per request.
    #[must_use]
    pub fn http_client(mut self, client: reqwest::Client) -> Self {
        self.http = Some(client);
        self
    }

    /// Validates the configuration and builds the client.
    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,
            }),
        })
    }
}

/// Per-visitor tracking state with automatic Umami cache reuse.
///
/// A session is cheap to clone; clones share cache state. Construct a separate
/// session for each visitor when using the crate in a multi-user server.
#[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 {
    /// Replaces the context inherited by new tracks in this 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
    }

    /// Sets a stable distinct ID and clears any cache derived for the previous
    /// identity.
    #[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
    }

    /// Sets the original visitor IP address.
    #[must_use]
    pub fn ip(mut self, ip: std::net::IpAddr) -> Self {
        self.context.ip = Some(ip);
        self
    }

    /// Sets the original visitor user agent.
    #[must_use]
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.context.user_agent = Some(user_agent.into());
        self
    }

    /// Sets the hostname inherited by new tracks.
    #[must_use]
    pub fn hostname(mut self, hostname: impl Into<String>) -> Self {
        self.context.hostname = Some(hostname.into());
        self
    }

    /// Sets the language inherited by new tracks.
    #[must_use]
    pub fn language(mut self, language: impl Into<String>) -> Self {
        self.context.language = Some(language.into());
        self
    }

    /// Clears Umami's cached session/visit metadata.
    pub fn reset(&self) {
        self.sender.clear_cache();
    }

    /// Creates a pageview track in this session.
    #[must_use]
    pub fn pageview(&self, url: impl Into<String>) -> Track {
        Track::pageview(self.sender.clone(), self.track_context(), url.into())
    }

    /// Creates a named custom-event track in this session.
    #[must_use]
    pub fn event(&self, name: impl Into<String>) -> Track {
        Track::event(self.sender.clone(), self.track_context(), name.into())
    }

    /// Creates an identify track and assigns a stable distinct ID.
    #[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))
    }

    /// Creates an identify track without assigning a distinct ID.
    #[must_use]
    pub fn identify_anonymous(&self) -> Track {
        Track::identify(self.sender.clone(), self.track_context(), None)
    }

    /// Creates a Core Web Vitals performance track in this session.
    #[must_use]
    pub fn performance(&self, url: impl Into<String>) -> Track {
        Track::performance(self.sender.clone(), self.track_context(), url.into())
    }

    /// Starts an empty batch bound to this session.
    #[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
    }
}

/// Builder for sending up to 500 tracks in a single HTTP request.
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,
        }
    }

    /// Adds a track to the batch.
    ///
    /// Validation is deferred until [`Batch::send`], preserving a fluent API.
    #[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
    }

    /// Adds multiple tracks to the batch.
    #[must_use]
    pub fn extend(mut self, tracks: impl IntoIterator<Item = Track>) -> Self {
        for track in tracks {
            self = self.push(track);
        }
        self
    }

    /// Reuses the cache value returned by a previous single-track response.
    #[must_use]
    pub fn continue_from(mut self, response: &TrackResponse) -> Self {
        self.cache.clone_from(&response.cache);
        self
    }

    /// Returns the number of tracks currently in the batch.
    #[must_use]
    pub fn len(&self) -> usize {
        self.requests.len()
    }

    /// Returns true when the batch contains no tracks.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.requests.is_empty()
    }

    /// Sends the batch to Umami.
    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?;
        // `/api/batch` returns the cache from the first successful item. That
        // cache may predate an identify item later in the same batch, so it is
        // unsafe to retain for an identity-changing batch.
        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());
    }
}