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
#![doc = include_str!("../README.md")]
use std::ops::Deref;

use async_trait::async_trait;
use libsql::params;
use time::OffsetDateTime;
use tower_sessions_core::{
    session::{Id, Record},
    session_store::{self, ExpiredDeletion},
    SessionStore,
};

/// An error type for libSQL stores.
#[derive(thiserror::Error, Debug)]
pub enum LibsqlStoreError {
    /// A variant to map `libsql` errors.
    #[error(transparent)]
    Libsql(#[from] libsql::Error),

    /// A variant to map `rmp_serde` encode errors.
    #[error(transparent)]
    Encode(#[from] rmp_serde::encode::Error),

    /// A variant to map `rmp_serde` decode errors.
    #[error(transparent)]
    Decode(#[from] rmp_serde::decode::Error),
}

impl From<LibsqlStoreError> for session_store::Error {
    fn from(err: LibsqlStoreError) -> Self {
        match err {
            LibsqlStoreError::Libsql(inner) => session_store::Error::Backend(inner.to_string()),
            LibsqlStoreError::Decode(inner) => session_store::Error::Decode(inner.to_string()),
            LibsqlStoreError::Encode(inner) => session_store::Error::Encode(inner.to_string()),
        }
    }
}

/// A libSQL session store.
#[derive(Clone)]
pub struct LibsqlStore {
    connection: libsql::Connection,
    table_name: String,
}

// Need this since connection does not implement Debug
impl std::fmt::Debug for LibsqlStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LibsqlStore")
            // Probably want to handle this differently
            .field("connection", &std::any::type_name::<libsql::Connection>())
            .field("table_name", &self.table_name)
            .finish()
    }
}

impl LibsqlStore {
    /// Create a new libSQL store with the provided connection pool.
    pub fn new(client: libsql::Connection) -> Self {
        Self {
            connection: client,
            table_name: "tower_sessions".into(),
        }
    }

    /// Set the session table name with the provided name.
    pub fn with_table_name(mut self, table_name: impl AsRef<str>) -> Result<Self, String> {
        let table_name = table_name.as_ref();
        if !is_valid_table_name(table_name) {
            return Err(format!(
                "Invalid table name '{}'. Table names must be alphanumeric and may contain \
                 hyphens or underscores.",
                table_name
            ));
        }

        table_name.clone_into(&mut self.table_name);
        Ok(self)
    }

    /// Migrate the session schema.
    pub async fn migrate(&self) -> libsql::Result<()> {
        let query = format!(
            r#"
            create table if not exists {}
            (
                id text primary key not null,
                data blob not null,
                expiry_date integer not null
            )
            "#,
            self.table_name
        );
        self.connection.execute(&query, ()).await?;

        Ok(())
    }

    async fn id_exists(&self, conn: &libsql::Connection, id: &Id) -> session_store::Result<bool> {
        let query = format!(
            r#"
            select exists(select 1 from {table_name} where id = ?)
            "#,
            table_name = self.table_name
        );

        let res = conn
            .query(&query, params![id.to_string()])
            .await
            .map_err(LibsqlStoreError::Libsql)
            .unwrap()
            .next()
            .await
            .unwrap()
            .unwrap()
            .get_value(0)
            .unwrap();

        Ok(res == libsql::Value::Integer(1))
    }

    async fn save_with_conn(
        &self,
        conn: &libsql::Connection,
        record: &Record,
    ) -> session_store::Result<()> {
        let query = format!(
            r#"
            insert into {}
              (id, data, expiry_date) values (?, ?, ?)
            on conflict(id) do update set
              data = excluded.data,
              expiry_date = excluded.expiry_date
            "#,
            self.table_name
        );
        conn.execute(
            &query,
            params![
                record.id.to_string(),
                rmp_serde::to_vec(record).map_err(LibsqlStoreError::Encode)?,
                record.expiry_date.unix_timestamp()
            ],
        )
        .await
        .map_err(LibsqlStoreError::Libsql)?;

        Ok(())
    }
}

#[async_trait]
impl ExpiredDeletion for LibsqlStore {
    async fn delete_expired(&self) -> session_store::Result<()> {
        let query = format!(
            r#"
            delete from {table_name}
            where expiry_date < unixepoch('now')
            "#,
            table_name = self.table_name
        );
        self.connection
            .execute(&query, ())
            .await
            .map_err(LibsqlStoreError::Libsql)?;
        Ok(())
    }
}

#[async_trait]
impl SessionStore for LibsqlStore {
    async fn create(&self, record: &mut Record) -> session_store::Result<()> {
        let tx = self.connection.transaction().await.unwrap();

        while self.id_exists(tx.deref(), &record.id).await? {
            record.id = Id::default() // Generate a new id
        }

        self.save_with_conn(tx.deref(), record).await?;

        tx.commit().await.map_err(LibsqlStoreError::Libsql)?;

        Ok(())
    }

    async fn save(&self, record: &Record) -> session_store::Result<()> {
        let conn = self.connection.clone();
        self.save_with_conn(&conn, record).await
    }

    async fn load(&self, session_id: &Id) -> session_store::Result<Option<Record>> {
        let query = format!(
            r#"
            select data from {}
            where id = ? and expiry_date > ?
            "#,
            self.table_name
        );

        let mut data = self
            .connection
            .query(
                &query,
                params![
                    session_id.to_string(),
                    OffsetDateTime::now_utc().unix_timestamp()
                ],
            )
            .await
            .map_err(LibsqlStoreError::Libsql)?;

        if let Ok(Some(data)) = data.next().await {
            Ok(Some(
                rmp_serde::from_slice(
                    data.get_value(0)
                        .map_err(LibsqlStoreError::Libsql)
                        .unwrap()
                        .as_blob()
                        .unwrap(),
                )
                .map_err(LibsqlStoreError::Decode)?,
            ))
        } else {
            Ok(None)
        }
    }

    async fn delete(&self, session_id: &Id) -> session_store::Result<()> {
        let query = format!(
            r#"
            delete from {} where id = ?
            "#,
            self.table_name
        );

        self.connection
            .execute(&query, params![session_id.to_string()])
            .await
            .map_err(LibsqlStoreError::Libsql)?;

        Ok(())
    }
}

fn is_valid_table_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}

#[cfg(test)]
mod libsql_store_tests {
    use std::collections::HashMap;

    use libsql::Builder;
    use serde_json::Value;
    use tower_sessions::cookie::time::{Duration, OffsetDateTime};

    use super::*;

    #[tokio::test]
    // Quick test to ensure that the db can be connected to, a migration can run,
    // and the table is queried, returning None.
    async fn basic_roundtrip() {
        let db = Builder::new_local(":memory:").build().await.unwrap();
        let conn = db.connect().unwrap();
        let store = LibsqlStore::new(conn.clone());
        store.migrate().await.unwrap();

        let query = r#"
            select * from tower_sessions limit 1
        "#;

        let row = conn.query(query, ()).await.unwrap().next().await.unwrap();

        assert!(row.is_none());
    }

    #[tokio::test]
    // Test a create with conflict
    async fn create_with_conflict() {
        let db = Builder::new_local(":memory:").build().await.unwrap();
        let conn = db.connect().unwrap();
        let store = LibsqlStore::new(conn.clone());
        store.migrate().await.unwrap();

        let data: HashMap<String, Value> =
            HashMap::from_iter([("key", "value")].to_vec().iter().map(|(k, v)| {
                (
                    k.to_string(),
                    serde_json::to_value(v).expect("Error encoding"),
                )
            }));

        let mut session_record1 = Record {
            id: Id::default(),
            data,
            expiry_date: OffsetDateTime::now_utc()
                .checked_add(Duration::days(1))
                .expect("Overflow making expiry"),
        };
        store
            .create(&mut session_record1)
            .await
            .expect("Error saving session");

        let mut session_record2 = session_record1.clone();
        store
            .create(&mut session_record2)
            .await
            .expect("Error saving session");

        let loaded1 = store
            .load(&session_record1.id)
            .await
            .expect("Error loading")
            .expect("Value missing");

        let loaded2 = store
            .load(&session_record2.id)
            .await
            .expect("Error loading")
            .expect("Value missing");

        assert_eq!(
            loaded1.data, loaded2.data,
            "Session created with dumplcate data"
        );
        assert_ne!(
            loaded1.id, loaded2.id,
            "Session conflict on id generates a new id"
        );
    }

    #[tokio::test]
    // Test a save and load
    async fn save_and_load() {
        let db = Builder::new_local(":memory:").build().await.unwrap();
        let conn = db.connect().unwrap();
        let store = LibsqlStore::new(conn.clone());
        store.migrate().await.unwrap();

        let data: HashMap<String, Value> =
            HashMap::from_iter([("key", "value")].to_vec().iter().map(|(k, v)| {
                (
                    k.to_string(),
                    serde_json::to_value(v).expect("Error encoding"),
                )
            }));

        let session_record = Record {
            id: Id::default(),
            data,
            expiry_date: OffsetDateTime::now_utc()
                .checked_add(Duration::days(1))
                .expect("Overflow making expiry"),
        };

        store
            .save(&session_record)
            .await
            .expect("Error saving session");

        let loaded = store
            .load(&session_record.id)
            .await
            .expect("Error loading")
            .expect("Value missing");

        assert_eq!(session_record, loaded, "Save and load match");
    }

    #[tokio::test]
    // Test a delete
    async fn save_and_delete() {
        let db = Builder::new_local(":memory:").build().await.unwrap();
        let conn = db.connect().unwrap();
        let store = LibsqlStore::new(conn.clone());
        store.migrate().await.unwrap();

        let data: HashMap<String, Value> =
            HashMap::from_iter([("key", "value")].to_vec().iter().map(|(k, v)| {
                (
                    k.to_string(),
                    serde_json::to_value(v).expect("Error encoding"),
                )
            }));

        let session_record = Record {
            id: Id::default(),
            data,
            expiry_date: OffsetDateTime::now_utc()
                .checked_add(Duration::days(1))
                .expect("Overflow making expiry"),
        };

        store
            .save(&session_record)
            .await
            .expect("Error saving session");

        let loaded = store
            .load(&session_record.id)
            .await
            .expect("Error loading")
            .expect("Value missing");

        assert_eq!(session_record, loaded, "Save and load match");

        store
            .delete(&session_record.id)
            .await
            .expect("Error deleting session record");

        let loaded = store.load(&session_record.id).await.expect("Error loading");

        assert!(loaded.is_none())
    }
}