libveezi 0.4.1

A Rust client for the Veezi API
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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
//! The [`Client`] for interfacing with the Veezi API

use std::{fmt::Debug, time::Duration};

use chrono::{NaiveDate, NaiveDateTime};
use log::debug;
use moka::future::{Cache, CacheBuilder};
use reqwest::Url;
use serde::de::DeserializeOwned;

use crate::{
    attr::{Attribute, AttributeId},
    error::ApiResult,
    film::{Film, FilmId},
    package::{FilmPackage, FilmPackageId},
    screen::{Screen, ScreenId},
    session::{Session, SessionId, SessionList},
    site::Site,
};

/// A structure for building a libveezi [`Client`] with various options
pub struct ClientBuilder {
    /// The underlying HTTP client
    http: reqwest::Client,
    /// The base URL for the Veezi API
    base_url: String,
    /// The access token for authenticating with the Veezi API
    token: String,
    /// Enable caching for [`Session`]s with the given TTL and max capacity
    pub session_cache: Option<(Duration, u64)>,
    /// Enable caching for [`Film`]s with the given TTL and max capacity
    pub film_cache: Option<(Duration, u64)>,
    /// Enable caching for [`FilmPackage`]s with the given TTL and max capacity
    pub film_package_cache: Option<(Duration, u64)>,
    /// Enable caching for [`Screen`]s with the given TTL and max capacity
    pub screen_cache: Option<(Duration, u64)>,
    /// Enable caching for [`Attribute`]s with the given TTL and max capacity
    pub attribute_cache: Option<(Duration, u64)>,
    /// Enable caching for the current [`Site`] with the given TTL
    pub site_cache: Option<Duration>,
}
impl ClientBuilder {
    /// Create a new [`ClientBuilder`] with the given base URL, access token,
    /// and underlying HTTP client
    #[must_use]
    pub fn new_with_http(base_url: &str, token: String, http_client: reqwest::Client) -> Self {
        Self {
            http: http_client,
            base_url: base_url.to_string(),
            token,
            session_cache: None,
            film_cache: None,
            film_package_cache: None,
            screen_cache: None,
            attribute_cache: None,
            site_cache: None,
        }
    }

    /// Create a new [`ClientBuilder`] with the given base URL and access token
    #[must_use]
    pub fn new(base_url: &str, token: String) -> Self {
        Self::new_with_http(base_url, token, reqwest::Client::new())
    }

    /// Build the [`Client`] from this builder
    ///
    /// # Errors
    ///
    /// This function will return an error if the URL provided is invalid.
    pub fn build(self) -> Result<Client, url::ParseError> {
        Client::from_builder(self)
    }

    /// Enable caching for [`Session`]s with the given TTL and max capacity
    #[must_use]
    pub const fn with_session_cache(mut self, ttl: Duration, max: u64) -> Self {
        self.session_cache = Some((ttl, max));
        self
    }

    /// Enable caching for [`Film`]s with the given TTL and max capacity
    #[must_use]
    pub const fn with_film_cache(mut self, ttl: Duration, max: u64) -> Self {
        self.film_cache = Some((ttl, max));
        self
    }

    /// Enable caching for [`FilmPackage`]s with the given TTL and max capacity
    #[must_use]
    pub const fn with_film_package_cache(mut self, ttl: Duration, max: u64) -> Self {
        self.film_package_cache = Some((ttl, max));
        self
    }

    /// Enable caching for [`Screen`]s with the given TTL and max capacity
    #[must_use]
    pub const fn with_screen_cache(mut self, ttl: Duration, max: u64) -> Self {
        self.screen_cache = Some((ttl, max));
        self
    }

    /// Enable caching for [`Attribute`]s with the given TTL and max capacity
    #[must_use]
    pub const fn with_attribute_cache(mut self, ttl: Duration, max: u64) -> Self {
        self.attribute_cache = Some((ttl, max));
        self
    }

    /// Enable caching for the current [`Site`] with the given TTL
    #[must_use]
    pub const fn with_site_cache(mut self, ttl: Duration) -> Self {
        self.site_cache = Some(ttl);
        self
    }

    /// Enable caching for all supported types with default settings
    #[must_use]
    pub const fn with_default_caching(self) -> Self {
        self.with_session_cache(Duration::from_secs(30), 1000)
            .with_film_cache(Duration::from_mins(5), 500)
            .with_film_package_cache(Duration::from_mins(5), 500)
            .with_screen_cache(Duration::from_hours(1), 100)
            .with_attribute_cache(Duration::from_mins(5), 500)
            .with_site_cache(Duration::from_mins(5))
    }
}

#[allow(clippy::doc_markdown)]
/// The main client for interacting with the Veezi API
pub struct Client {
    /// The underlying HTTP client
    http: reqwest::Client,
    /// The base URL for the Veezi API
    base: Url,
    /// The access token for authenticating with the Veezi API
    token: String,

    // Some of these caches use `()` as the key type to cache the full list responses
    // We cannot just list all items from the individual item caches because they may expire
    /// The MiniLFU cache for [`Session`]s
    session_cache: Option<Cache<SessionId, Session>>,
    /// The MiniLFU cache for the full [`SessionList`]
    session_list_cache: Option<Cache<(), SessionList>>,
    /// The MiniLFU cache for the full web [`SessionList`]
    web_session_list_cache: Option<Cache<(), SessionList>>,
    /// The MiniLFU cache for [`Film`]s
    film_cache: Option<Cache<FilmId, Film>>,
    /// The MiniLFU cache for the full list of [`Film`]s
    film_list_cache: Option<Cache<(), Vec<Film>>>,
    /// The MiniLFU cache for [`FilmPackage`]s
    film_package_cache: Option<Cache<FilmPackageId, FilmPackage>>,
    /// The MiniLFU cache for the full list of [`FilmPackage`]s
    film_package_list_cache: Option<Cache<(), Vec<FilmPackage>>>,
    /// The MiniLFU cache for [`Screen`]s
    screen_cache: Option<Cache<ScreenId, Screen>>,
    /// The MiniLFU cache for the full list of [`Screen`]s
    screen_list_cache: Option<Cache<(), Vec<Screen>>>,
    /// The MiniLFU cache for [`Attribute`]s
    attribute_cache: Option<Cache<AttributeId, Attribute>>,
    /// The MiniLFU cache for the full list of [`Attribute`]s
    attribute_list_cache: Option<Cache<(), Vec<Attribute>>>,
    /// The MiniLFU cache for the current [`Site`]
    site_cache: Option<Cache<(), Site>>,
}
impl Client {
    /// Create a new Veezi API client from a given base URL, access token, and
    /// [`reqwest::Client`]
    ///
    /// # Errors
    ///
    /// This function will return an error if the URL provided is invalid.
    pub fn from_builder(builder: ClientBuilder) -> Result<Self, url::ParseError> {
        let ClientBuilder {
            http: http_client,
            base_url,
            token,
            session_cache,
            film_cache,
            film_package_cache,
            screen_cache,
            attribute_cache,
            site_cache,
        } = builder;

        debug!("Spawning new libveezi Client for API base: {base_url}");
        let base = Url::parse(&base_url)?;
        Ok(Self {
            http: http_client,
            base,
            token,

            session_cache: session_cache
                .map(|(ttl, max)| CacheBuilder::new(max).time_to_live(ttl).build()),
            session_list_cache: session_cache
                .map(|(ttl, _)| CacheBuilder::new(1).time_to_live(ttl).build()),
            web_session_list_cache: session_cache
                .map(|(ttl, _)| CacheBuilder::new(1).time_to_live(ttl).build()),
            film_cache: film_cache
                .map(|(ttl, max)| CacheBuilder::new(max).time_to_live(ttl).build()),
            film_list_cache: film_cache
                .map(|(ttl, _)| CacheBuilder::new(1).time_to_live(ttl).build()),
            film_package_cache: film_package_cache
                .map(|(ttl, max)| CacheBuilder::new(max).time_to_live(ttl).build()),
            film_package_list_cache: film_package_cache
                .map(|(ttl, _)| CacheBuilder::new(1).time_to_live(ttl).build()),
            screen_cache: screen_cache
                .map(|(ttl, max)| CacheBuilder::new(max).time_to_live(ttl).build()),
            screen_list_cache: screen_cache
                .map(|(ttl, _)| CacheBuilder::new(1).time_to_live(ttl).build()),
            attribute_cache: attribute_cache
                .map(|(ttl, max)| CacheBuilder::new(max).time_to_live(ttl).build()),
            attribute_list_cache: attribute_cache
                .map(|(ttl, _)| CacheBuilder::new(1).time_to_live(ttl).build()),
            site_cache: site_cache.map(|ttl| CacheBuilder::new(1).time_to_live(ttl).build()),
        })
    }

    /// Internal helper to make a GET request to the Veezi API and parse the
    /// JSON response.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    async fn get_json<T>(&self, endpoint: &str) -> ApiResult<T>
    where
        T: DeserializeOwned + Debug,
    {
        let url = self.base.join(endpoint)?;

        debug!(target: "libveezi-http", "GET {url}");

        let resp = self
            .http
            .get(url)
            .header("VeeziAccessToken", &self.token)
            .send()
            .await?
            .error_for_status()?
            .json::<T>()
            .await?;

        debug!(target: "libveezi-http", "OK: {resp:?}");

        Ok(resp)
    }

    /// Invalidate all cached data
    pub fn invalidate_all_caches(&self) {
        self.invalidate_all_cached_sessions();
        self.invalidate_all_cached_web_sessions();
        self.invalidate_all_cached_films();
        self.invalidate_all_cached_film_packages();
        self.invalidate_all_cached_screens();
        self.invalidate_all_cached_attributes();
        self.invalidate_cached_site();
    }

    /// Get a list of all future [Session]s.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn list_sessions(&self) -> ApiResult<SessionList> {
        let fetch_raw = async {
            Ok(SessionList::from(
                self.get_json::<Vec<Session>>("v1/session").await?,
            ))
        };

        // Fetch from API if no cache is configured
        let Some(cache) = &self.session_list_cache else {
            return fetch_raw.await;
        };

        // Try to get from cache
        if let Some(cached) = cache.get(&()).await {
            debug!("SessionList cache hit");
            return Ok(cached);
        }

        debug!("SessionList cache miss, fetching from API");
        let sessions = fetch_raw.await?;
        cache.insert((), sessions.clone()).await;
        if let Some(session_cache) = &self.session_cache {
            for session in sessions.iter() {
                session_cache.insert(session.id, session.clone()).await;
            }
        }
        Ok(sessions)
    }
    /// Invalidate a cached [`Session`] by its ID
    ///
    /// As a side effect, this also invalidates the full session list cache
    pub async fn invalidate_cached_session(&self, id: SessionId) {
        if let Some(cache) = &self.session_cache {
            cache.invalidate(&id).await;
        }
        if let Some(cache) = &self.session_list_cache {
            cache.invalidate_all();
        }
    }
    /// Invalidate all cached [`Session`]s
    pub fn invalidate_all_cached_sessions(&self) {
        if let Some(cache) = &self.session_cache {
            cache.invalidate_all();
        }
        if let Some(cache) = &self.session_list_cache {
            cache.invalidate_all();
        }
    }

    /// Get a list of all future [`Session`]s that should be available for
    /// online sales.
    ///
    /// This asserts the following for each [`Session`]:
    /// - [`Session::sales_cut_off_time`] is in the future
    /// - [`Session::status`] is [`crate::session::SessionStatus::Open`]
    /// - [`Session::show_type`] is [`crate::session::ShowType::Public`]
    /// - [`Session::sales_via`] allows [`crate::session::SalesVia::www`] sales
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn list_web_sessions(&self) -> ApiResult<SessionList> {
        let fetch_raw = async {
            Ok(SessionList::from(
                self.get_json::<Vec<Session>>("v1/websession").await?,
            ))
        };

        // Fetch from API if no cache is configured
        let Some(cache) = &self.web_session_list_cache else {
            return fetch_raw.await;
        };

        // Try to get from cache
        if let Some(cached) = cache.get(&()).await {
            debug!("Web SessionList cache hit");
            return Ok(cached);
        }

        debug!("Web SessionList cache miss, fetching from API");
        let sessions = fetch_raw.await?;
        cache.insert((), sessions.clone()).await;
        if let Some(session_cache) = &self.session_cache {
            for session in sessions.iter() {
                // Although we are operating on only a subset of sessions, cache what we have
                session_cache.insert(session.id, session.clone()).await;
            }
        }

        Ok(sessions)
    }
    /// Invalidate all cached web [`Session`]s
    pub fn invalidate_all_cached_web_sessions(&self) {
        if let Some(cache) = &self.web_session_list_cache {
            cache.invalidate_all();
        }
    }

    /// Get a specific [Session] by its ID.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn get_session(&self, id: SessionId) -> ApiResult<Session> {
        let fetch_raw = async { self.get_json::<Session>(&format!("v1/session/{id}")).await };

        // Fetch from API if no cache is configured
        let Some(cache) = &self.session_cache else {
            return fetch_raw.await;
        };

        // Try to get from cache
        if let Some(cached) = cache.get(&id).await {
            debug!("Session cache hit for ID {id}");
            return Ok(cached);
        }

        debug!("Session cache miss for ID {id}, fetching from API");
        let session = fetch_raw.await?;
        cache.insert(id, session.clone()).await;
        Ok(session)
    }

    /// Get a list of all [Film]s in the Veezi system.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn list_films(&self) -> ApiResult<Vec<Film>> {
        // v4/film

        let fetch_raw = async { self.get_json::<Vec<Film>>("v4/film").await };

        // Fetch from API if no cache is configured
        let Some(cache) = &self.film_list_cache else {
            return fetch_raw.await;
        };

        // Try to get from cache
        if let Some(cached) = cache.get(&()).await {
            debug!("Film list cache hit");
            return Ok(cached);
        }

        debug!("Film list cache miss, fetching from API");
        let films = fetch_raw.await?;
        cache.insert((), films.clone()).await;
        if let Some(film_cache) = &self.film_cache {
            for film in &films {
                film_cache.insert(film.id.clone(), film.clone()).await;
            }
        }
        Ok(films)
    }
    /// Invalidate all cached [`Film`]s
    pub fn invalidate_all_cached_films(&self) {
        if let Some(cache) = &self.film_cache {
            cache.invalidate_all();
        }
        if let Some(cache) = &self.film_list_cache {
            cache.invalidate_all();
        }
    }
    /// Invalidate a cached [`Film`] by its ID
    ///
    /// As a side effect, this also invalidates the full film list cache
    pub async fn invalidate_cached_film(&self, id: &FilmId) {
        if let Some(cache) = &self.film_cache {
            cache.invalidate(id).await;
        }
        if let Some(cache) = &self.film_list_cache {
            cache.invalidate_all();
        }
    }

    /// Get a specific [`Film`] by its ID.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn get_film(&self, id: &FilmId) -> ApiResult<Film> {
        let fetch_raw = async {
            self.get_json::<Film>(&format!("v4/film/{}", id.as_str()))
                .await
        };

        // Fetch from API if no cache is configured
        let Some(cache) = &self.film_cache else {
            return fetch_raw.await;
        };

        // Try to get from cache
        if let Some(cached) = cache.get(id).await {
            debug!("Film cache hit for ID {id}");
            return Ok(cached);
        }

        debug!("Film cache miss for ID {id}, fetching from API");
        let film = fetch_raw.await?;
        cache.insert(id.clone(), film.clone()).await;
        Ok(film)
    }

    /// Get a specific [`Film`] by its exact [`Film::title`]. If multiple films
    /// have the same title, the first one found will be returned.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails, or None if
    /// no film with the given title is found.
    pub async fn get_film_by_title(&self, title: &str) -> ApiResult<Option<Film>> {
        let films = self.list_films().await?;
        Ok(films.into_iter().find(|film| film.title == title))
    }

    /// Get a specific [`Film`] by its exact [`Film::short_name`]. If multiple
    /// films have the same short name, the first one found will be
    /// returned.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails, or None if
    /// no film with the given short name is found.
    pub async fn get_film_by_short_name(&self, short_name: &str) -> ApiResult<Option<Film>> {
        let films = self.list_films().await?;
        Ok(films.into_iter().find(|film| film.short_name == short_name))
    }

    /// Get a specific [`Film`] by its exact [`Film::signage_text`]. If multiple
    /// films have the same signage text, the first one found will be
    /// returned.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails, or None if
    /// no film with the given signage text is found.
    pub async fn get_film_by_signage_text(&self, signage_text: &str) -> ApiResult<Option<Film>> {
        let films = self.list_films().await?;
        Ok(films
            .into_iter()
            .find(|film| film.signage_text == signage_text))
    }

    /// Get a list of all [`Film`]s with a specific [`Film::genre`] string.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn list_films_by_genre(&self, genre: &str) -> ApiResult<Vec<Film>> {
        let films = self.list_films().await?;
        Ok(films
            .into_iter()
            .filter(|film| film.genre == genre)
            .collect())
    }

    /// Get a list of all [`Film`]s by a specific [`Film::distributor`].
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn list_films_by_distributor(&self, distributor: &str) -> ApiResult<Vec<Film>> {
        let films = self.list_films().await?;
        Ok(films
            .into_iter()
            .filter(|film| film.distributor == distributor)
            .collect())
    }

    /// Get only the films that have sessions scheduled in the included time
    /// range.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn list_films_with_sessions_in_time_range(
        &self,
        start: NaiveDateTime,
        end: NaiveDateTime,
    ) -> ApiResult<Vec<Film>> {
        // using our existing methods, no http
        self.list_sessions()
            .await?
            .filter_by_time_range(start, end)
            .films(self)
            .await
    }

    /// Get only the films that have sessions scheduled in the included date
    /// range.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn list_films_with_sessions_in_date_range(
        &self,
        start: NaiveDate,
        end: NaiveDate,
    ) -> ApiResult<Vec<Film>> {
        // using our existing methods, no http
        self.list_sessions()
            .await?
            .filter_by_date_range(start, end)
            .films(self)
            .await
    }

    /// Get a list of all [`FilmPackage`]s in the Veezi system.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn list_film_packages(&self) -> ApiResult<Vec<FilmPackage>> {
        let fetch_raw = async { self.get_json::<Vec<FilmPackage>>("v1/filmpackage").await };

        // Fetch from API if no cache is configured
        let Some(cache) = &self.film_package_list_cache else {
            return fetch_raw.await;
        };

        // Try to get from cache
        if let Some(cached) = cache.get(&()).await {
            debug!("FilmPackage list cache hit");
            return Ok(cached);
        }

        debug!("FilmPackage list cache miss, fetching from API");
        let packages = fetch_raw.await?;
        cache.insert((), packages.clone()).await;
        if let Some(package_cache) = &self.film_package_cache {
            for package in &packages {
                package_cache.insert(package.id, package.clone()).await;
            }
        }
        Ok(packages)
    }
    /// Invalidate all cached [`FilmPackage`]s
    pub fn invalidate_all_cached_film_packages(&self) {
        if let Some(cache) = &self.film_package_cache {
            cache.invalidate_all();
        }
        if let Some(cache) = &self.film_package_list_cache {
            cache.invalidate_all();
        }
    }
    /// Invalidate a cached [`FilmPackage`] by its ID
    ///
    /// As a side effect, this also invalidates the full film package list cache
    pub async fn invalidate_cached_film_package(&self, id: FilmPackageId) {
        if let Some(cache) = &self.film_package_cache {
            cache.invalidate(&id).await;
        }
        if let Some(cache) = &self.film_package_list_cache {
            cache.invalidate_all();
        }
    }

    /// Get a specific [`FilmPackage`] by its exact [`FilmPackage::title`]. If
    /// multiple packages have the same title, the first one found will be
    /// returned.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails, or None if
    /// no package with the given title is found.
    pub async fn get_film_package_by_title(&self, title: &str) -> ApiResult<Option<FilmPackage>> {
        let packages = self.list_film_packages().await?;
        Ok(packages.into_iter().find(|package| package.title == title))
    }

    /// Get a list of all [`FilmPackage`]s containing a specific [`FilmId`].
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn list_film_packages_by_film_id(
        &self,
        film_id: &FilmId,
    ) -> ApiResult<Vec<FilmPackage>> {
        let packages = self.list_film_packages().await?;
        Ok(packages
            .into_iter()
            .filter(|package| package.films.iter().any(|pf| pf.film_id == *film_id))
            .collect())
    }

    /// Get a specific [`FilmPackage`] by its ID.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn get_film_package(&self, id: FilmPackageId) -> ApiResult<FilmPackage> {
        let fetch_raw = async {
            self.get_json::<FilmPackage>(&format!("v1/filmpackage/{id}"))
                .await
        };

        // Fetch from API if no cache is configured
        let Some(cache) = &self.film_package_cache else {
            return fetch_raw.await;
        };

        // Try to get from cache
        if let Some(cached) = cache.get(&id).await {
            debug!("FilmPackage cache hit for ID {id}");
            return Ok(cached);
        }

        debug!("FilmPackage cache miss for ID {id}, fetching from API");
        let package = fetch_raw.await?;
        cache.insert(id, package.clone()).await;
        Ok(package)
    }

    /// Get a list of all [`Screen`]s in the current site.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn list_screens(&self) -> ApiResult<Vec<Screen>> {
        let fetch_raw = async { self.get_json::<Vec<Screen>>("v1/screen").await };

        // Fetch from API if no cache is configured
        let Some(cache) = &self.screen_list_cache else {
            return fetch_raw.await;
        };

        // Try to get from cache
        if let Some(cached) = cache.get(&()).await {
            debug!("Screen list cache hit");
            return Ok(cached);
        }

        debug!("Screen list cache miss, fetching from API");
        let screens = fetch_raw.await?;
        cache.insert((), screens.clone()).await;
        if let Some(screen_cache) = &self.screen_cache {
            for screen in &screens {
                screen_cache.insert(screen.id, screen.clone()).await;
            }
        }
        Ok(screens)
    }
    /// Invalidate all cached [`Screen`]s
    pub fn invalidate_all_cached_screens(&self) {
        if let Some(cache) = &self.screen_cache {
            cache.invalidate_all();
        }
        if let Some(cache) = &self.screen_list_cache {
            cache.invalidate_all();
        }
    }
    /// Invalidate a cached [`Screen`] by its ID
    ///
    /// As a side effect, this also invalidates the full screen list cache
    pub async fn invalidate_cached_screen(&self, id: ScreenId) {
        if let Some(cache) = &self.screen_cache {
            cache.invalidate(&id).await;
        }
        if let Some(cache) = &self.screen_list_cache {
            cache.invalidate_all();
        }
    }

    /// Get a specific [`Screen`] by its ID.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn get_screen(&self, id: ScreenId) -> ApiResult<Screen> {
        let fetch_raw = async { self.get_json::<Screen>(&format!("v1/screen/{id}")).await };

        // Fetch from API if no cache is configured
        let Some(cache) = &self.screen_cache else {
            return fetch_raw.await;
        };

        // Try to get from cache
        if let Some(cached) = cache.get(&id).await {
            debug!("Screen cache hit for ID {id}");
            return Ok(cached);
        }

        debug!("Screen cache miss for ID {id}, fetching from API");
        let screen = fetch_raw.await?;
        cache.insert(id, screen.clone()).await;
        Ok(screen)
    }

    /// Get a specific [`Screen`] by its exact [`Screen::screen_number`]. If
    /// multiple screens have the same screen number, the first one found will
    /// be returned.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails, or None if
    /// no screen with the given screen number is found.
    pub async fn get_screen_by_number(&self, screen_number: String) -> ApiResult<Option<Screen>> {
        let screens = self.list_screens().await?;
        Ok(screens
            .into_iter()
            .find(|screen| screen.screen_number == screen_number))
    }

    /// Get the [`Site`] information for the current Veezi site.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn get_site(&self) -> ApiResult<Site> {
        let fetch_raw = async { self.get_json::<Site>("v1/site").await };

        // Fetch from API if no cache is configured
        let Some(cache) = &self.site_cache else {
            return fetch_raw.await;
        };

        // Try to get from cache
        if let Some(cached) = cache.get(&()).await {
            debug!("Site cache hit");
            return Ok(cached);
        }

        debug!("Site cache miss, fetching from API");
        let site = fetch_raw.await?;
        cache.insert((), site.clone()).await;
        Ok(site)
    }
    /// Invalidate the cached [`Site`]
    pub fn invalidate_cached_site(&self) {
        if let Some(cache) = &self.site_cache {
            cache.invalidate_all();
        }
    }

    /// Get a list of all [`Attribute`]s set in the site.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn list_attributes(&self) -> ApiResult<Vec<Attribute>> {
        let fetch_raw = async { self.get_json::<Vec<Attribute>>("v1/attribute").await };

        // Fetch from API if no cache is configured
        let Some(cache) = &self.attribute_list_cache else {
            return fetch_raw.await;
        };

        // Try to get from cache
        if let Some(cached) = cache.get(&()).await {
            debug!("Attribute list cache hit");
            return Ok(cached);
        }

        debug!("Attribute list cache miss, fetching from API");
        let attributes = fetch_raw.await?;
        cache.insert((), attributes.clone()).await;
        if let Some(attribute_cache) = &self.attribute_cache {
            for attribute in &attributes {
                attribute_cache
                    .insert(attribute.id.clone(), attribute.clone())
                    .await;
            }
        }
        Ok(attributes)
    }
    /// Invalidate all cached [`Attribute`]s
    pub fn invalidate_all_cached_attributes(&self) {
        if let Some(cache) = &self.attribute_cache {
            cache.invalidate_all();
        }
        if let Some(cache) = &self.attribute_list_cache {
            cache.invalidate_all();
        }
    }
    /// Invalidate a cached [`Attribute`] by its ID
    ///
    /// As a side effect, this also invalidates the full attribute list cache
    pub async fn invalidate_cached_attribute(&self, id: &AttributeId) {
        if let Some(cache) = &self.attribute_cache {
            cache.invalidate(id).await;
        }
        if let Some(cache) = &self.attribute_list_cache {
            cache.invalidate_all();
        }
    }

    /// Get a specific [`Attribute`] by its ID.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails.
    pub async fn get_attribute(&self, id: &AttributeId) -> ApiResult<Attribute> {
        let fetch_raw = async {
            self.get_json::<Attribute>(&format!("v1/attribute/{}", id.as_str()))
                .await
        };

        // Fetch from API if no cache is configured
        let Some(cache) = &self.attribute_cache else {
            return fetch_raw.await;
        };

        // Try to get from cache
        if let Some(cached) = cache.get(id).await {
            debug!("Attribute cache hit for ID {id}");
            return Ok(cached);
        }

        debug!("Attribute cache miss for ID {id}, fetching from API");
        let attribute = fetch_raw.await?;
        cache.insert(id.clone(), attribute.clone()).await;
        Ok(attribute)
    }

    /// Get a specific [`Attribute`] by its exact [`Attribute::short_name`]. If
    /// multiple attributes have the same short name, the first one found
    /// will be returned.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails, or None if
    /// no attribute with the given short name is found.
    pub async fn get_attribute_by_short_name(
        &self,
        short_name: &str,
    ) -> ApiResult<Option<Attribute>> {
        let attributes = self.list_attributes().await?;
        Ok(attributes
            .into_iter()
            .find(|attr| attr.short_name == short_name))
    }

    /// Get a specific [`Attribute`] by its exact [`Attribute::description`]. If
    /// multiple attributes have the same description, the first one found
    /// will be returned.
    ///
    /// # Errors
    ///
    /// This function will return an error if the API request fails, or None if
    /// no attribute with the given description is found.
    pub async fn get_attribute_by_description(
        &self,
        description: &str,
    ) -> ApiResult<Option<Attribute>> {
        let attributes = self.list_attributes().await?;
        Ok(attributes
            .into_iter()
            .find(|attr| attr.description == description))
    }
}