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
//! Represents a session extractor.

use std::{
    convert::Infallible,
    fmt,
    sync::{
        atomic::{AtomicU8, Ordering},
        Arc, RwLock,
    },
};

use serde::{de::DeserializeOwned, Serialize};
use serde_json::{from_value, to_value, Value};

use sessions_core::{Data, State, CHANGED, PURGED, RENEWED, UNCHANGED};

use crate::{Error, FromRequest, IntoResponse, Request, RequestExt, StatusCode};

/// A session for the current request.
#[derive(Clone)]
pub struct Session {
    state: Arc<State>,
}

impl Session {
    /// Creates new `Session` with `Data`
    #[must_use]
    pub fn new(data: Data) -> Self {
        Self {
            state: Arc::new(State {
                status: AtomicU8::new(UNCHANGED),
                data: RwLock::new(data),
            }),
        }
    }

    /// Gets status of the session
    #[must_use]
    pub fn status(&self) -> &AtomicU8 {
        &self.state.status
    }

    /// Gets lock data of the session
    #[must_use]
    pub fn lock_data(&self) -> &RwLock<Data> {
        &self.state.data
    }

    /// Gets a value by the key
    ///
    /// # Errors
    /// TODO
    pub fn get<T>(&self, key: &str) -> Result<Option<T>, Error>
    where
        T: DeserializeOwned,
    {
        let read = self
            .lock_data()
            .read()
            .map_err(|e| responder_error((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())))?;

        let val = read.get(key).cloned();

        match val {
            Some(t) => from_value(t).map(Some).map_err(report_error),
            None => Ok(None),
        }
    }

    /// Sets a value by the key
    ///
    /// # Errors
    /// TODO
    pub fn set<T>(&self, key: &str, val: T) -> Result<(), Error>
    where
        T: Serialize,
    {
        let status = self.status().load(Ordering::Acquire);
        // not allowed `PURGED`
        if status != PURGED {
            if let Ok(mut d) = self.lock_data().write() {
                // not allowed `RENEWED & CHANGED`
                if status == UNCHANGED {
                    self.status().store(CHANGED, Ordering::SeqCst);
                }
                d.insert(key.into(), to_value(val).map_err(report_error)?);
            }
        }
        Ok(())
    }

    /// Removes a key from the session, returning the value at the key if the key was previously in
    /// the session.
    #[allow(clippy::must_use_candidate)]
    pub fn remove(&self, key: &str) -> Option<Value> {
        let status = self.status().load(Ordering::Acquire);
        // not allowed `PURGED`
        if status != PURGED {
            if let Ok(mut d) = self.lock_data().write() {
                // not allowed `RENEWED & CHANGED`
                if status == UNCHANGED {
                    self.status().store(CHANGED, Ordering::SeqCst);
                }
                return d.remove(key);
            }
        }
        None
    }

    /// Removes a value and deserialize
    #[allow(clippy::must_use_candidate)]
    pub fn remove_as<T>(&self, key: &str) -> Option<T>
    where
        T: DeserializeOwned,
    {
        self.remove(key).and_then(|t| from_value(t).ok())
    }

    /// Clears the state
    pub fn clear(&self) {
        let status = self.status().load(Ordering::Acquire);
        // not allowed `PURGED`
        if status != PURGED {
            if let Ok(mut d) = self.lock_data().write() {
                // not allowed `RENEWED & CHANGED`
                if status == UNCHANGED {
                    self.status().store(CHANGED, Ordering::SeqCst);
                }
                d.clear();
            }
        }
    }

    /// Renews the new state
    pub fn renew(&self) {
        let status = self.status().load(Ordering::Acquire);
        // not allowed `PURGED & RENEWED`
        if status != PURGED && status != RENEWED {
            self.status().store(RENEWED, Ordering::SeqCst);
        }
    }

    /// Destroys the current state from store
    pub fn purge(&self) {
        let status = self.status().load(Ordering::Acquire);
        // not allowed `PURGED`
        if status != PURGED {
            self.status().store(PURGED, Ordering::SeqCst);
            if let Ok(mut d) = self.lock_data().write() {
                d.clear();
            }
        }
    }

    /// Gets all raw key-value data from the session
    ///
    /// # Errors
    #[allow(clippy::must_use_candidate)]
    pub fn data(&self) -> Result<Data, Error> {
        self.lock_data()
            .read()
            .map_err(|e| responder_error((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())))
            .map(|d| d.clone())
    }
}

impl fmt::Debug for Session {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.state.fmt(f)
    }
}

impl FromRequest for Session {
    type Error = Infallible;

    async fn extract(req: &mut Request) -> Result<Self, Self::Error> {
        Ok(req.session().clone())
    }
}

fn responder_error(e: (StatusCode, String)) -> Error {
    Error::Responder(e.into_response())
}

fn report_error<E: std::error::Error + Send + Sync + 'static>(e: E) -> Error {
    Error::Report(
        Box::new(e),
        StatusCode::INTERNAL_SERVER_ERROR.into_response(),
    )
}