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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
//! A session which allows HTTP applications to associate data with visitors.
use std::{
    collections::HashMap,
    fmt::Display,
    hash::Hash,
    str::FromStr,
    sync::{
        atomic::{self, AtomicBool},
        Arc,
    },
};

use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::Value;
use time::Duration;
use tokio::sync::{Mutex, MutexGuard};
use tower_cookies::cookie::time::OffsetDateTime;
use uuid::Uuid;

use crate::{session_store, SessionStore};

const DEFAULT_DURATION: Duration = Duration::weeks(2);

type Result<T> = std::result::Result<T, Error>;

type Data = HashMap<String, Value>;

/// Session errors.
#[derive(thiserror::Error, Debug)]
pub enum Error {
    /// Maps `serde_json` errors.
    #[error(transparent)]
    SerdeJson(#[from] serde_json::Error),

    #[error(transparent)]
    Store(#[from] session_store::Error),

    /// Missing session ID.
    #[error("Missing session ID")]
    MissingId,

    /// Missing cookies.
    #[error("Missing cookies; is tower-cookies set up?")]
    MissingCookies,
}

/// A session which allows HTTP applications to associate key-value pairs with
/// visitors.
#[derive(Debug, Clone)]
pub struct Session {
    // This will be `None` when:
    //
    // 1. We have not been provided a session cookie or have failed to parse it,
    // 2. The store has not found the session.
    //
    // Sync lock, see: https://docs.rs/tokio/latest/tokio/sync/struct.Mutex.html#which-kind-of-mutex-should-you-use
    session_id: Arc<parking_lot::Mutex<Option<Id>>>,

    store: Arc<dyn SessionStore>,

    // A lazy representation of the session's value, hydrated on a just-in-time basis. A
    // `None` value indicates we have not tried to access it yet. After access, it will always
    // contain `Some(Record)`.
    record: Arc<Mutex<Option<Record>>>,

    // Sync lock, see: https://docs.rs/tokio/latest/tokio/sync/struct.Mutex.html#which-kind-of-mutex-should-you-use
    expiry: Arc<parking_lot::Mutex<Option<Expiry>>>,

    is_modified: Arc<AtomicBool>,
}

impl Session {
    /// Creates a new session with the session ID, store, and expiry.
    ///
    /// This method is lazy and does not invoke the overhead of talking to the
    /// backing store.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// Session::new(None, store, None);
    /// ```
    pub fn new(
        session_id: Option<Id>,
        store: Arc<impl SessionStore>,
        expiry: Option<Expiry>,
    ) -> Self {
        Self {
            session_id: Arc::new(parking_lot::Mutex::new(session_id)),
            store,
            record: Arc::new(Mutex::new(None)), // `None` indicates we have not loaded from store.
            expiry: Arc::new(parking_lot::Mutex::new(expiry)),
            is_modified: Arc::new(AtomicBool::new(false)),
        }
    }

    fn create_record(&self) -> Record {
        Record::new(self.expiry_date())
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_record(&self) -> Result<MutexGuard<Option<Record>>> {
        let mut record_guard = self.record.lock().await;
        let session_id = *self.session_id.lock();

        // Lazily load the record.
        if record_guard.is_none() {
            tracing::trace!("record not loaded from store; loading");

            *record_guard = if let Some(session_id) = session_id {
                match self.store.load(&session_id).await.map_err(Error::Store)? {
                    Some(mut loaded_record) => {
                        tracing::trace!("record found in store");
                        loaded_record.expiry_date = self.expiry_date();
                        Some(loaded_record)
                    }
                    None => {
                        tracing::trace!("record not found in store");
                        *self.session_id.lock() = None;
                        Some(self.create_record())
                    }
                }
            } else {
                tracing::trace!("session id not found");
                Some(self.create_record())
            }
        }

        Ok(record_guard)
    }

    /// Inserts a `impl Serialize` value into the session.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let session = Session::new(None, store, None);
    ///
    /// session.insert("foo", 42).await.unwrap();
    ///
    /// let value = session.get::<usize>("foo").await.unwrap();
    /// assert_eq!(value, Some(42));
    /// # });
    /// ```
    ///
    /// # Errors
    ///
    /// - This method can fail when [`serde_json::to_value`] fails.
    /// - If the session has not been hydrated and loading from the store fails,
    ///   we fail with [`Error::Store`].
    pub async fn insert(&self, key: &str, value: impl Serialize) -> Result<()> {
        self.insert_value(key, serde_json::to_value(&value)?)
            .await?;
        Ok(())
    }

    /// Inserts a `serde_json::Value` into the session.
    ///
    /// If the key was not present in the underlying map, `None` is returned and
    /// `modified` is set to `true`.
    ///
    /// If the underlying map did have the key and its value is the same as the
    /// provided value, `None` is returned and `modified` is not set.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let session = Session::new(None, store, None);
    ///
    /// let value = session
    ///     .insert_value("foo", serde_json::json!(42))
    ///     .await
    ///     .unwrap();
    /// assert!(value.is_none());
    ///
    /// let value = session
    ///     .insert_value("foo", serde_json::json!(42))
    ///     .await
    ///     .unwrap();
    /// assert!(value.is_none());
    ///
    /// let value = session
    ///     .insert_value("foo", serde_json::json!("bar"))
    ///     .await
    ///     .unwrap();
    /// assert_eq!(value, Some(serde_json::json!(42)));
    /// # });
    /// ```
    ///
    /// # Errors
    ///
    /// - If the session has not been hydrated and loading from the store fails,
    ///   we fail with [`Error::Store`].
    pub async fn insert_value(&self, key: &str, value: Value) -> Result<Option<Value>> {
        Ok(self.get_record().await?.as_mut().and_then(|record| {
            if record.data.get(key) != Some(&value) {
                self.is_modified.store(true, atomic::Ordering::Release);
                record.data.insert(key.to_string(), value)
            } else {
                None
            }
        }))
    }

    /// Gets a value from the store.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let session = Session::new(None, store, None);
    ///
    /// session.insert("foo", 42).await.unwrap();
    ///
    /// let value = session.get::<usize>("foo").await.unwrap();
    /// assert_eq!(value, Some(42));
    /// # });
    /// ```
    ///
    /// # Errors
    ///
    /// - This method can fail when [`serde_json::from_value`] fails.
    /// - If the session has not been hydrated and loading from the store fails,
    ///   we fail with [`Error::Store`].
    pub async fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
        Ok(self
            .get_value(key)
            .await?
            .map(serde_json::from_value)
            .transpose()?)
    }

    /// Gets a `serde_json::Value` from the store.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let session = Session::new(None, store, None);
    ///
    /// session.insert("foo", 42).await.unwrap();
    ///
    /// let value = session.get_value("foo").await.unwrap().unwrap();
    /// assert_eq!(value, serde_json::json!(42));
    /// # });
    /// ```
    ///
    /// # Errors
    ///
    /// - If the session has not been hydrated and loading from the store fails,
    ///   we fail with [`Error::Store`].
    pub async fn get_value(&self, key: &str) -> Result<Option<Value>> {
        Ok(self
            .get_record()
            .await?
            .as_ref()
            .and_then(|record| record.data.get(key).cloned()))
    }

    /// Removes a value from the store, retuning the value of the key if it was
    /// present in the underlying map.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let session = Session::new(None, store, None);
    ///
    /// session.insert("foo", 42).await.unwrap();
    ///
    /// let value: Option<usize> = session.remove("foo").await.unwrap();
    /// assert_eq!(value, Some(42));
    ///
    /// let value: Option<usize> = session.get("foo").await.unwrap();
    /// assert!(value.is_none());
    /// # });
    /// ```
    ///
    /// # Errors
    ///
    /// - This method can fail when [`serde_json::from_value`] fails.
    /// - If the session has not been hydrated and loading from the store fails,
    ///   we fail with [`Error::Store`].
    pub async fn remove<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
        Ok(self
            .remove_value(key)
            .await?
            .map(serde_json::from_value)
            .transpose()?)
    }

    /// Removes a `serde_json::Value` from the session.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let session = Session::new(None, store, None);
    ///
    /// session.insert("foo", 42).await.unwrap();
    /// let value = session.remove_value("foo").await.unwrap().unwrap();
    /// assert_eq!(value, serde_json::json!(42));
    ///
    /// let value: Option<usize> = session.get("foo").await.unwrap();
    /// assert!(value.is_none());
    /// # });
    /// ```
    ///
    /// # Errors
    ///
    /// - If the session has not been hydrated and loading from the store fails,
    ///   we fail with [`Error::Store`].
    pub async fn remove_value(&self, key: &str) -> Result<Option<Value>> {
        Ok(self.get_record().await?.as_mut().and_then(|record| {
            self.is_modified.store(true, atomic::Ordering::Release);
            record.data.remove(key)
        }))
    }

    /// Clears the session of all data but does not delete it from the store.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    ///
    /// let session = Session::new(None, store.clone(), None);
    /// session.insert("foo", 42).await.unwrap();
    /// assert!(!session.is_empty().await);
    ///
    /// session.save().await.unwrap();
    ///
    /// session.clear().await;
    ///
    /// // Not empty! (We have an ID still.)
    /// assert!(!session.is_empty().await);
    /// // Data is cleared...
    /// assert!(session.get::<usize>("foo").await.unwrap().is_none());
    ///
    /// let session = Session::new(session.id(), store, None);
    /// // ...but not deleted from the store.
    /// assert_eq!(session.get::<usize>("foo").await.unwrap(), Some(42));
    /// # });
    /// ```
    pub async fn clear(&self) {
        let mut record = self.record.lock().await;
        if let Some(record) = record.as_mut() {
            record.data.clear();
        }
        self.is_modified.store(true, atomic::Ordering::Release);
    }

    /// Returns `true` if there is no session ID and the session is empty.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{session::Id, MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    ///
    /// let session = Session::new(None, store.clone(), None);
    /// // Empty if we have no ID and record is not loaded.
    /// assert!(session.is_empty().await);
    ///
    /// let session = Session::new(Some(Id::default()), store.clone(), None);
    /// // Not empty if we have an ID but no record. (Record is not loaded here.)
    /// assert!(!session.is_empty().await);
    ///
    /// let session = Session::new(Some(Id::default()), store.clone(), None);
    /// session.insert("foo", 42).await.unwrap();
    /// // Not empty after inserting.
    /// assert!(!session.is_empty().await);
    /// session.save().await.unwrap();
    /// // Not empty after saving.
    /// assert!(!session.is_empty().await);
    ///
    /// let session = Session::new(session.id(), store.clone(), None);
    /// session.load().await.unwrap();
    /// // Not empty after loading from store...
    /// assert!(!session.is_empty().await);
    /// // ...and not empty after accessing the session.
    /// session.get::<usize>("foo").await.unwrap();
    /// assert!(!session.is_empty().await);
    ///
    /// let session = Session::new(session.id(), store.clone(), None);
    /// session.delete().await.unwrap();
    /// // Not empty after deleting from store...
    /// assert!(!session.is_empty().await);
    /// session.get::<usize>("foo").await.unwrap();
    /// // ...but empty after trying to access the deleted session.
    /// assert!(session.is_empty().await);
    ///
    /// let session = Session::new(None, store, None);
    /// session.insert("foo", 42).await.unwrap();
    /// session.flush().await.unwrap();
    /// // Empty after flushing.
    /// assert!(session.is_empty().await);
    /// # });
    /// ```
    pub async fn is_empty(&self) -> bool {
        let record_guard = self.record.lock().await;

        // N.B.: Session IDs are `None` if:
        //
        // 1. The cookie was not provided or otherwise could not be parsed,
        // 2. Or the session could not be loaded from the store.
        let session_id = self.session_id.lock();

        let Some(record) = record_guard.as_ref() else {
            return session_id.is_none();
        };

        session_id.is_none() && record.data.is_empty()
    }

    /// Get the session ID.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{session::Id, MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    ///
    /// let session = Session::new(None, store.clone(), None);
    /// assert!(session.id().is_none());
    ///
    /// let id = Some(Id::default());
    /// let session = Session::new(id, store, None);
    /// assert_eq!(id, session.id());
    /// ```
    pub fn id(&self) -> Option<Id> {
        *self.session_id.lock()
    }

    /// Get the session expiry.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{session::Expiry, MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let session = Session::new(None, store, None);
    ///
    /// assert_eq!(session.expiry(), None);
    /// ```
    pub fn expiry(&self) -> Option<Expiry> {
        *self.expiry.lock()
    }

    /// Set `expiry` give the given value.
    ///
    /// This may be used within applications directly to alter the session's
    /// time to live.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::sync::Arc;
    ///
    /// use time::OffsetDateTime;
    /// use tower_sessions::{session::Expiry, MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let session = Session::new(None, store, None);
    ///
    /// let expiry = Expiry::AtDateTime(OffsetDateTime::now_utc());
    /// session.set_expiry(Some(expiry));
    ///
    /// assert_eq!(session.expiry(), Some(expiry));
    /// ```
    pub fn set_expiry(&self, expiry: Option<Expiry>) {
        let mut current_expiry = self.expiry.lock();
        *current_expiry = expiry;
    }

    /// Get session expiry as `OffsetDateTime`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::sync::Arc;
    ///
    /// use time::{Duration, OffsetDateTime};
    /// use tower_sessions::{MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let session = Session::new(None, store, None);
    ///
    /// // Our default duration is two weeks.
    /// let expected_expiry = OffsetDateTime::now_utc().saturating_add(Duration::weeks(2));
    ///
    /// assert!(session.expiry_date() > expected_expiry.saturating_sub(Duration::seconds(1)));
    /// assert!(session.expiry_date() < expected_expiry.saturating_add(Duration::seconds(1)));
    /// ```
    pub fn expiry_date(&self) -> OffsetDateTime {
        let expiry = self.expiry.lock();
        match *expiry {
            Some(Expiry::OnInactivity(duration)) => {
                OffsetDateTime::now_utc().saturating_add(duration)
            }
            Some(Expiry::AtDateTime(datetime)) => datetime,
            Some(Expiry::OnSessionEnd) | None => {
                OffsetDateTime::now_utc().saturating_add(DEFAULT_DURATION) // TODO: The default should probably be configurable.
            }
        }
    }

    /// Get session expiry as `Duration`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::sync::Arc;
    ///
    /// use time::Duration;
    /// use tower_sessions::{MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let session = Session::new(None, store, None);
    ///
    /// let expected_duration = Duration::weeks(2);
    ///
    /// assert!(session.expiry_age() > expected_duration.saturating_sub(Duration::seconds(1)));
    /// assert!(session.expiry_age() < expected_duration.saturating_add(Duration::seconds(1)));
    /// ```
    pub fn expiry_age(&self) -> Duration {
        std::cmp::max(
            self.expiry_date() - OffsetDateTime::now_utc(),
            Duration::ZERO,
        )
    }

    /// Returns `true` if the session has been modified during the request.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let session = Session::new(None, store, None);
    ///
    /// // Not modified initially.
    /// assert!(!session.is_modified());
    ///
    /// // Getting doesn't count as a modification.
    /// session.get::<usize>("foo").await.unwrap();
    /// assert!(!session.is_modified());
    ///
    /// // Insertions and removals do though.
    /// session.insert("foo", 42).await.unwrap();
    /// assert!(session.is_modified());
    /// # });
    /// ```
    pub fn is_modified(&self) -> bool {
        self.is_modified.load(atomic::Ordering::Acquire)
    }

    /// Saves the session record to the store.
    ///
    /// Note that this method is generally not needed and is reserved for
    /// situations where the session store must be updated during the
    /// request.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let session = Session::new(None, store.clone(), None);
    ///
    /// session.insert("foo", 42).await.unwrap();
    /// session.save().await.unwrap();
    ///
    /// let session = Session::new(session.id(), store, None);
    /// assert_eq!(session.get::<usize>("foo").await.unwrap().unwrap(), 42);
    /// # });
    /// ```
    ///
    /// # Errors
    ///
    /// - If saving to the store fails, we fail with [`Error::Store`].
    #[tracing::instrument(skip(self), err)]
    pub async fn save(&self) -> Result<()> {
        // N.B.: `get_record` will create a new record if one isn't found in the store.
        if let Some(record) = self.get_record().await?.as_mut() {
            {
                let mut session_id_guard = self.session_id.lock();
                if session_id_guard.is_none() {
                    // Generate a new ID here since e.g. flush may have been called, which will
                    // not directly update the record ID.
                    let id = Id::default();
                    *session_id_guard = Some(id);
                    record.id = id;
                }
            }

            self.store.save(record).await.map_err(Error::Store)?;
        }

        Ok(())
    }

    /// Loads the session record from the store.
    ///
    /// Note that this method is generally not needed and is reserved for
    /// situations where the session must be updated during the request.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{session::Id, MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let id = Some(Id::default());
    /// let session = Session::new(id, store.clone(), None);
    ///
    /// session.insert("foo", 42).await.unwrap();
    /// session.save().await.unwrap();
    ///
    /// let session = Session::new(session.id(), store, None);
    /// session.load().await.unwrap();
    ///
    /// assert_eq!(session.get::<usize>("foo").await.unwrap().unwrap(), 42);
    /// # });
    /// ```
    ///
    /// # Errors
    ///
    /// - If loading from the store fails, we fail with [`Error::Store`].
    #[tracing::instrument(skip(self), err)]
    pub async fn load(&self) -> Result<()> {
        let session_id = *self.session_id.lock();
        let Some(ref id) = session_id else {
            tracing::warn!("called load with no session id");
            return Ok(());
        };
        let loaded_record = self.store.load(id).await.map_err(Error::Store)?;
        let mut record_guard = self.record.lock().await;
        *record_guard = loaded_record;
        Ok(())
    }

    /// Deletes the session from the store.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{session::Id, MemoryStore, Session, SessionStore};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let session = Session::new(Some(Id::default()), store.clone(), None);
    ///
    /// // Save before deleting.
    /// session.save().await.unwrap();
    ///
    /// // Delete from the store.
    /// session.delete().await.unwrap();
    ///
    /// assert!(store.load(&session.id().unwrap()).await.unwrap().is_none());
    /// # });
    /// ```
    ///
    /// # Errors
    ///
    /// - If deleting from the store fails, we fail with [`Error::Store`].
    #[tracing::instrument(skip(self), err)]
    pub async fn delete(&self) -> Result<()> {
        let session_id = *self.session_id.lock();
        let Some(ref session_id) = session_id else {
            tracing::warn!("called delete with no session id");
            return Ok(());
        };
        self.store.delete(session_id).await.map_err(Error::Store)?;
        Ok(())
    }

    /// Flushes the session by removing all data contained in the session and
    /// then deleting it from the store.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{MemoryStore, Session, SessionStore};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let session = Session::new(None, store.clone(), None);
    ///
    /// session.insert("foo", "bar").await.unwrap();
    /// session.save().await.unwrap();
    ///
    /// let id = session.id().unwrap();
    ///
    /// session.flush().await.unwrap();
    ///
    /// assert!(session.id().is_none());
    /// assert!(session.is_empty().await);
    /// assert!(store.load(&id).await.unwrap().is_none());
    /// # });
    /// ```
    ///
    /// # Errors
    ///
    /// - If deleting from the store fails, we fail with [`Error::Store`].
    pub async fn flush(&self) -> Result<()> {
        self.clear().await;
        self.delete().await?;
        *self.session_id.lock() = None;
        Ok(())
    }

    /// Cycles the session ID while retaining any data that was associated with
    /// it.
    ///
    /// Using this method helps prevent session fixation attacks by ensuring a
    /// new ID is assigned to the session.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// use std::sync::Arc;
    ///
    /// use tower_sessions::{session::Id, MemoryStore, Session};
    ///
    /// let store = Arc::new(MemoryStore::default());
    /// let session = Session::new(None, store.clone(), None);
    ///
    /// session.insert("foo", 42).await.unwrap();
    /// session.save().await.unwrap();
    /// let id = session.id();
    ///
    /// let session = Session::new(session.id(), store.clone(), None);
    /// session.cycle_id().await.unwrap();
    ///
    /// assert!(!session.is_empty().await);
    /// assert!(session.is_modified());
    ///
    /// session.save().await.unwrap();
    ///
    /// let session = Session::new(session.id(), store, None);
    ///
    /// assert_ne!(id, session.id());
    /// assert_eq!(session.get::<usize>("foo").await.unwrap().unwrap(), 42);
    /// # });
    /// ```
    ///
    /// # Errors
    ///
    /// - If deleting from the store fails or saving to the store fails, we fail
    ///   with [`Error::Store`].
    pub async fn cycle_id(&self) -> Result<()> {
        let mut record_guard = self.get_record().await?;
        let Some(record) = record_guard.as_mut() else {
            return Ok(());
        };

        let old_session_id = record.id;
        record.id = Id::default();
        *self.session_id.lock() = Some(record.id);

        self.store
            .delete(&old_session_id)
            .await
            .map_err(Error::Store)?;

        self.is_modified.store(true, atomic::Ordering::Release);

        Ok(())
    }
}

/// ID type for sessions.
///
/// Wraps a UUIDv4.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::session::Id;
///
/// Id::default();
/// ```
#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, Hash, PartialEq)]
pub struct Id(pub Uuid); // TODO: By this being public, it may be possible to override UUIDv4,
                         // which is undesirable.

impl Default for Id {
    fn default() -> Self {
        Self(Uuid::new_v4())
    }
}

impl Display for Id {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0.as_hyphenated().to_string())
    }
}

impl FromStr for Id {
    type Err = uuid::Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Ok(Self(s.parse::<uuid::Uuid>()?))
    }
}

/// Record type that's appropriate for encoding and decoding sessions to and
/// from session stores.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Record {
    pub id: Id,
    pub data: Data,
    pub expiry_date: OffsetDateTime,
}

impl Record {
    fn new(expiry_date: OffsetDateTime) -> Self {
        Self {
            id: Id::default(),
            data: Data::default(),
            expiry_date,
        }
    }
}

/// Session expiry configuration.
///
/// # Examples
///
/// ```rust
/// use time::{Duration, OffsetDateTime};
/// use tower_sessions::Expiry;
///
/// // Will be expired on "session end".
/// let expiry = Expiry::OnSessionEnd;
///
/// // Will be expired in five minutes from last acitve.
/// let expiry = Expiry::OnInactivity(Duration::minutes(5));
///
/// // Will be expired at the given timestamp.
/// let expired_at = OffsetDateTime::now_utc().saturating_add(Duration::weeks(2));
/// let expiry = Expiry::AtDateTime(expired_at);
/// ```
#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum Expiry {
    /// Expire on [current session end][current-session-end], as defined by the
    /// browser.
    ///
    /// [current-session-end]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#define_the_lifetime_of_a_cookie
    OnSessionEnd,

    /// Expire on inactivity.
    ///
    /// Reading a session is not considered activity for expiration purposes.
    /// [`Session`] expiration is computed from the last time the session was
    /// _modified_.
    OnInactivity(Duration),

    /// Expire at a specific date and time.
    ///
    /// This value may be extended manually with
    /// [`set_expiry`](Session::set_expiry).
    AtDateTime(OffsetDateTime),
}