From 89981b27846f7d32457101d8ff78894f238babc9 Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Sun, 11 Oct 2020 15:14:34 -0300 Subject: [PATCH 01/19] wip: use expire from session with mongodb index --- src/lib.rs | 19 +++++++++++++++++-- tests/test.rs | 22 ++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 431dc4f..6e9877c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -20,7 +20,7 @@ use async_session::{Result, Session, SessionStore}; use async_trait::async_trait; use mongodb::bson; use mongodb::bson::doc; -use mongodb::options::ReplaceOptions; +use mongodb::options::{ReplaceOptions,SelectionCriteria}; use mongodb::Client; /// A MongoDB session store. @@ -43,6 +43,17 @@ impl MongodbSessionStore { /// ``` pub async fn connect(uri: &str, db: &str, coll_name: &str) -> mongodb::error::Result { let client = Client::with_uri_str(uri).await?; + let create_index = doc! { + "createIndexes": coll_name, + "indexes": [ + { + "key" : {"expireAt": 1 }, + "name": "session_expire_at_index", + "expireAfterSeconds": 0, + } + ] + }; + client.database(db).run_command(create_index, SelectionCriteria::ReadPreference( mongodb::options::ReadPreference::Primary)).await?; Ok(Self::from_client(client, db, coll_name)) } @@ -82,7 +93,11 @@ impl SessionStore for MongodbSessionStore { let value = bson::to_bson(&session)?; let id = session.id(); let query = doc! { "session_id": id }; - let replacement = doc! { "session_id": id, "session": value, "created": Utc::now() }; + let replacement = match session.expiry() { + None => { doc! { "session_id": id, "session": value,"created": Utc::now() } }, + Some( expire_at ) => { doc! { "session_id": id, "session": value, "expireAt": expire_at, "created": Utc::now() } } + }; + let opts = ReplaceOptions::builder().upsert(true).build(); coll.replace_one(query, replacement, Some(opts)).await?; diff --git a/tests/test.rs b/tests/test.rs index a390569..4b42407 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -63,4 +63,26 @@ mod tests { Ok(()) }) } + + #[test] + fn test_with_expire() -> async_session::Result { + async_std::task::block_on(async { + let store = + MongodbSessionStore::connect(&CONNECTION_STRING, "db_name", "collection").await?; + + let mut rng = rand::thread_rng(); + let n2: u16 = rng.gen(); + let key = format!("key-{}", n2); + let value = format!("value-{}", n2); + let mut session = Session::new(); + session.expire_in(std::time::Duration::from_secs(5)); + session.insert(&key, &value)?; + + let cookie_value = store.store_session(session).await?.unwrap(); + let session = store.load_session(cookie_value).await?.unwrap(); + assert_eq!(&session.get::(&key).unwrap(), &value); + + Ok(()) + }) + } } From db6a76f16cd19dcaf7223311fb41e411db4c95a5 Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Sun, 11 Oct 2020 20:25:45 -0300 Subject: [PATCH 02/19] add tests and modify readme --- Cargo.toml | 1 + README.md | 22 +++------------------- tests/test.rs | 29 +++++++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 19 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 13ef5a6..9e82817 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ authors = [ "Yoshua Wuyts ", "Irina Shestak ", "Anton Whalley ", + "Javier Viola " ] [features] diff --git a/README.md b/README.md index f121775..587937a 100644 --- a/README.md +++ b/README.md @@ -48,29 +48,13 @@ $ cargo add async-mongodb-session ## Configuration -This library utilises the document [expiry feature](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-after-a-specified-number-of-seconds) in mongodb to expire the session. +This library utilises the document [expiry feature](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time) in mongodb to expire the session at the expiry The management of the expiry feature fits into the 12 factor [admin process definintion](https://12factor.net/admin-processes) so it's recommended to use an process outside of your web application to manage the expiry parameters. -A `created` property is available on the root of the session document that so the [expiry feature](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-after-a-specified-number-of-seconds) can be used in the configuration. +A `expireAt` property is available on the root of the session document IFF the session expire is set. Note that [async-session doesn't set by default](https://github.com/http-rs/async-session/blob/main/src/session.rs#L98). -If your application code to create a session store is something like: -``` -let store = MongodbSessionStore::connect("mongodb://127.0.0.1:27017", "db_name", "coll_session").await?; -``` - -Then the script to create the expiry would be: -``` -use db_name; -db.coll_session.createIndex( { created": 1 } , { expireAfterSeconds: 300 } ) -``` - -If you wish to redefine the session duration then the index must be dropped first using: -``` -use db_name; -db.coll_session.dropIndex( { "created": 1 }) -db.coll_session.createIndex( { created": 1 } , { expireAfterSeconds: 300 } ) -``` +To enable this [expiry feature](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time) at `index` for `expireAt` is created when the client `connet`. Allowing then to use this property from the session to set the expiration of the document. ## Test diff --git a/tests/test.rs b/tests/test.rs index 4b42407..8816485 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -85,4 +85,33 @@ mod tests { Ok(()) }) } + + #[test] + fn test_check_expired() -> async_session::Result { + use std::time::Duration; + use async_std::task; + async_std::task::block_on(async { + let store = + MongodbSessionStore::connect(&CONNECTION_STRING, "db_name", "collection").await?; + + let mut rng = rand::thread_rng(); + let n2: u16 = rng.gen(); + let key = format!("key-{}", n2); + let value = format!("value-{}", n2); + let mut session = Session::new(); + session.expire_in(Duration::from_secs(1)); + session.insert(&key, &value)?; + + let cookie_value = store.store_session(session).await?.unwrap(); + + // mongodb runs the background task that removes expired documents runs every 60 seconds. + // https://docs.mongodb.com/manual/core/index-ttl/#timing-of-the-delete-operation + task::sleep(Duration::from_secs(60)).await; + let session_to_recover = store.load_session(cookie_value).await?; + + assert!(&session_to_recover.is_none()); + + Ok(()) + }) + } } From 374d7761546b4a8699999861eb164536c054106d Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Sun, 11 Oct 2020 20:37:28 -0300 Subject: [PATCH 03/19] typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 587937a..4e8a03b 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ $ cargo add async-mongodb-session ## Configuration -This library utilises the document [expiry feature](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time) in mongodb to expire the session at the expiry +This library utilises the document [expiry feature](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time) in mongodb to expire the session at the expiry. The management of the expiry feature fits into the 12 factor [admin process definintion](https://12factor.net/admin-processes) so it's recommended to use an process outside of your web application to manage the expiry parameters. From 9129246b39b8b7ad545f608f946d2b7eecedc56a Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Mon, 12 Oct 2020 06:17:03 -0300 Subject: [PATCH 04/19] fmt --- src/lib.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 6e9877c..5dd3eb8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -20,7 +20,7 @@ use async_session::{Result, Session, SessionStore}; use async_trait::async_trait; use mongodb::bson; use mongodb::bson::doc; -use mongodb::options::{ReplaceOptions,SelectionCriteria}; +use mongodb::options::{ReplaceOptions, SelectionCriteria}; use mongodb::Client; /// A MongoDB session store. @@ -53,7 +53,13 @@ impl MongodbSessionStore { } ] }; - client.database(db).run_command(create_index, SelectionCriteria::ReadPreference( mongodb::options::ReadPreference::Primary)).await?; + client + .database(db) + .run_command( + create_index, + SelectionCriteria::ReadPreference(mongodb::options::ReadPreference::Primary), + ) + .await?; Ok(Self::from_client(client, db, coll_name)) } @@ -94,8 +100,12 @@ impl SessionStore for MongodbSessionStore { let id = session.id(); let query = doc! { "session_id": id }; let replacement = match session.expiry() { - None => { doc! { "session_id": id, "session": value,"created": Utc::now() } }, - Some( expire_at ) => { doc! { "session_id": id, "session": value, "expireAt": expire_at, "created": Utc::now() } } + None => { + doc! { "session_id": id, "session": value,"created": Utc::now() } + } + Some(expire_at) => { + doc! { "session_id": id, "session": value, "expireAt": expire_at, "created": Utc::now() } + } }; let opts = ReplaceOptions::builder().upsert(true).build(); From a5b3fe2f798c17e396bb9afe5c590f54cfa0e9c8 Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Mon, 12 Oct 2020 06:24:02 -0300 Subject: [PATCH 05/19] fmt tests --- tests/test.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test.rs b/tests/test.rs index 8816485..9494262 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -88,8 +88,8 @@ mod tests { #[test] fn test_check_expired() -> async_session::Result { - use std::time::Duration; use async_std::task; + use std::time::Duration; async_std::task::block_on(async { let store = MongodbSessionStore::connect(&CONNECTION_STRING, "db_name", "collection").await?; From 50d5d1c0c5251ccce553a9de6e81578c21a1f0de Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Mon, 12 Oct 2020 08:27:33 -0300 Subject: [PATCH 06/19] feedback changes --- README.md | 31 +++++++++++++++--- src/lib.rs | 87 +++++++++++++++++++++++++++++++++++++++++---------- tests/test.rs | 4 +++ 3 files changed, 101 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 4e8a03b..5bcc046 100644 --- a/README.md +++ b/README.md @@ -48,13 +48,36 @@ $ cargo add async-mongodb-session ## Configuration -This library utilises the document [expiry feature](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time) in mongodb to expire the session at the expiry. +A `created` property is available on the root of the session document that so the [expiry feature](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-after-a-specified-number-of-seconds) can be used in the configuration. -The management of the expiry feature fits into the 12 factor [admin process definintion](https://12factor.net/admin-processes) so it's recommended to use an process outside of your web application to manage the expiry parameters. +If your application code to create a session store is something like: +``` +let store = MongodbSessionStore::connect("mongodb://127.0.0.1:27017", "db_name", "coll_session").await?; +``` + +Then the script to create the expiry would be: +``` +use db_name; +db.coll_session.createIndex( { "created": 1 } , { expireAfterSeconds: 300 } ); +``` + +If you wish to redefine the session duration then the index must be dropped first using: +``` +use db_name; +db.coll_session.dropIndex( { "created": 1 }) +db.coll_session.createIndex( { "created": 1 } , { expireAfterSeconds: 300 } ); +``` + +Other way to set create the index is using `create_created_index_for_global_expiry` passing the amount of seconds to expiry after the session. -A `expireAt` property is available on the root of the session document IFF the session expire is set. Note that [async-session doesn't set by default](https://github.com/http-rs/async-session/blob/main/src/session.rs#L98). +Also, an `expireAt` property is available on the root of the session document IFF the session expire is set. Note that [async-session doesn't set by default](https://github.com/http-rs/async-session/blob/main/src/session.rs#L98). -To enable this [expiry feature](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time) at `index` for `expireAt` is created when the client `connet`. Allowing then to use this property from the session to set the expiration of the document. +To enable this [expiry feature](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time) at `index` for `expireAt` should be created calling `create_expire_at_index` function or with this script ( following the above example ) + +``` +use db_name; +db.coll_session.createIndex( { "expireAt": 1 } , { expireAfterSeconds: 0 } ); +``` ## Test diff --git a/src/lib.rs b/src/lib.rs index 5dd3eb8..9a1d015 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -43,23 +43,6 @@ impl MongodbSessionStore { /// ``` pub async fn connect(uri: &str, db: &str, coll_name: &str) -> mongodb::error::Result { let client = Client::with_uri_str(uri).await?; - let create_index = doc! { - "createIndexes": coll_name, - "indexes": [ - { - "key" : {"expireAt": 1 }, - "name": "session_expire_at_index", - "expireAfterSeconds": 0, - } - ] - }; - client - .database(db) - .run_command( - create_index, - SelectionCriteria::ReadPreference(mongodb::options::ReadPreference::Primary), - ) - .await?; Ok(Self::from_client(client, db, coll_name)) } @@ -89,6 +72,76 @@ impl MongodbSessionStore { coll_name: coll_name.to_string(), } } + + /// Create a new index for the `created` property and set the expiry ttl (in secods). + /// The session will expire when the number of seconds in the expireAfterSeconds field has passed + /// since the time specified in its created field. + /// https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-after-a-specified-number-of-seconds + /// ```rust + /// # fn main() -> async_session::Result { async_std::task::block_on(async { + /// # use async_mongodb_session::MongodbSessionStore; + /// let store = + /// MongodbSessionStore::connect("mongodb://127.0.0.1:27017", "db_name", "collection") + /// .await?; + /// store.create_created_index_for_global_expiry(300).await?; + /// # Ok(()) }) } + /// ``` + pub async fn create_created_index_for_global_expiry( + &self, + expire_after_seconds: u32, + ) -> Result { + let create_index = doc! { + "createIndexes": &self.coll_name, + "indexes": [ + { + "key" : { "created": 1 }, + "name": "session_expire_after_created_index", + "expireAfterSeconds": expire_after_seconds, + } + ] + }; + self.client + .database(&self.db) + .run_command( + create_index, + SelectionCriteria::ReadPreference(mongodb::options::ReadPreference::Primary), + ) + .await?; + Ok(()) + } + + /// Create a new index for the `expireAt` property, allowing to expire sessions at a specific clock time. + /// If the `expireAt` date field contains a date in the past, mongodb considers the document expired and will be deleted. + /// https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time + /// ```rust + /// # fn main() -> async_session::Result { async_std::task::block_on(async { + /// # use async_mongodb_session::MongodbSessionStore; + /// let store = + /// MongodbSessionStore::connect("mongodb://127.0.0.1:27017", "db_name", "collection") + /// .await?; + /// store.create_expire_at_index().await?; + /// # Ok(()) }) } + /// ``` + pub async fn create_expire_at_index(&self) -> Result { + let create_index = doc! { + "createIndexes": &self.coll_name, + "indexes": [ + { + "key" : { "expireAt": 1 }, + "name": "session_expire_at_index", + "expireAfterSeconds": 0, + } + ] + }; + self.client + .database(&self.db) + .run_command( + create_index, + SelectionCriteria::ReadPreference(mongodb::options::ReadPreference::Primary), + ) + .await?; + Ok(()) + } } #[async_trait] diff --git a/tests/test.rs b/tests/test.rs index 9494262..f4904bf 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -70,6 +70,8 @@ mod tests { let store = MongodbSessionStore::connect(&CONNECTION_STRING, "db_name", "collection").await?; + store.create_expire_at_index().await?; + let mut rng = rand::thread_rng(); let n2: u16 = rng.gen(); let key = format!("key-{}", n2); @@ -94,6 +96,8 @@ mod tests { let store = MongodbSessionStore::connect(&CONNECTION_STRING, "db_name", "collection").await?; + store.create_expire_at_index().await?; + let mut rng = rand::thread_rng(); let n2: u16 = rng.gen(); let key = format!("key-{}", n2); From a94f090edaa9b75257d1909fa093262383ae12f5 Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Mon, 12 Oct 2020 10:26:25 -0300 Subject: [PATCH 07/19] add overvew and 12factor to readme --- README.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5bcc046..9f393d7 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,11 @@ $ cargo add async-mongodb-session ``` +## Overview +This library allow you to utilises the document expiration feature based on a [specified number of seconds](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-after-a-specified-number-of-seconds) or in a [specific clock time](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time) supported by mongodb to expire the session. + +The management of the expiry feature fits into the 12 factor [admin process definintion](https://12factor.net/admin-processes) so it's recommended to use an process outside of your web application to manage the expiry parameters. + ## Configuration A `created` property is available on the root of the session document that so the [expiry feature](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-after-a-specified-number-of-seconds) can be used in the configuration. @@ -68,11 +73,11 @@ db.coll_session.dropIndex( { "created": 1 }) db.coll_session.createIndex( { "created": 1 } , { expireAfterSeconds: 300 } ); ``` -Other way to set create the index is using `create_created_index_for_global_expiry` passing the amount of seconds to expiry after the session. +Other way to set create the index is using `index_on_created` passing the amount of seconds to expiry after the session. Also, an `expireAt` property is available on the root of the session document IFF the session expire is set. Note that [async-session doesn't set by default](https://github.com/http-rs/async-session/blob/main/src/session.rs#L98). -To enable this [expiry feature](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time) at `index` for `expireAt` should be created calling `create_expire_at_index` function or with this script ( following the above example ) +To enable this [expiry feature](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time) at `index` for `expireAt` should be created calling `index_on_expiry_at` function or with this script ( following the above example ) ``` use db_name; From 459341b325510ec883c497a565fb47d10afc2928 Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Mon, 12 Oct 2020 10:26:43 -0300 Subject: [PATCH 08/19] change naming from feedback --- src/lib.rs | 8 ++++---- tests/test.rs | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 9a1d015..998e96d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -83,10 +83,10 @@ impl MongodbSessionStore { /// let store = /// MongodbSessionStore::connect("mongodb://127.0.0.1:27017", "db_name", "collection") /// .await?; - /// store.create_created_index_for_global_expiry(300).await?; + /// store.index_on_created(300).await?; /// # Ok(()) }) } /// ``` - pub async fn create_created_index_for_global_expiry( + pub async fn index_on_created( &self, expire_after_seconds: u32, ) -> Result { @@ -119,10 +119,10 @@ impl MongodbSessionStore { /// let store = /// MongodbSessionStore::connect("mongodb://127.0.0.1:27017", "db_name", "collection") /// .await?; - /// store.create_expire_at_index().await?; + /// store.index_on_expiry_at().await?; /// # Ok(()) }) } /// ``` - pub async fn create_expire_at_index(&self) -> Result { + pub async fn index_on_expiry_at(&self) -> Result { let create_index = doc! { "createIndexes": &self.coll_name, "indexes": [ diff --git a/tests/test.rs b/tests/test.rs index f4904bf..faa988c 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -70,7 +70,7 @@ mod tests { let store = MongodbSessionStore::connect(&CONNECTION_STRING, "db_name", "collection").await?; - store.create_expire_at_index().await?; + store.index_on_expiry_at().await?; let mut rng = rand::thread_rng(); let n2: u16 = rng.gen(); @@ -96,7 +96,7 @@ mod tests { let store = MongodbSessionStore::connect(&CONNECTION_STRING, "db_name", "collection").await?; - store.create_expire_at_index().await?; + store.index_on_expiry_at().await?; let mut rng = rand::thread_rng(); let n2: u16 = rng.gen(); From 345f977a425397a54251a752a15d8c20016fb8f4 Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Mon, 12 Oct 2020 10:32:26 -0300 Subject: [PATCH 09/19] fmt --- src/lib.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 998e96d..e07af61 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -86,10 +86,7 @@ impl MongodbSessionStore { /// store.index_on_created(300).await?; /// # Ok(()) }) } /// ``` - pub async fn index_on_created( - &self, - expire_after_seconds: u32, - ) -> Result { + pub async fn index_on_created(&self, expire_after_seconds: u32) -> Result { let create_index = doc! { "createIndexes": &self.coll_name, "indexes": [ From 92ec601274744fcae5e874a0333119a80dc2543d Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Mon, 12 Oct 2020 20:30:27 -0300 Subject: [PATCH 10/19] add more context to readme --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 9f393d7..9836b33 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,10 @@ $ cargo add async-mongodb-session ## Overview This library allow you to utilises the document expiration feature based on a [specified number of seconds](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-after-a-specified-number-of-seconds) or in a [specific clock time](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time) supported by mongodb to expire the session. +The specified number of seconds approach is designed to enable the session time out to be managed at the mongodb layer. This approach provides a globally consistent session timeout across multiple processes but has the downside that all services using the same session collection must use the same timeout value. + +The specific clock time clock time approach is where you require more flexibility on your session timeouts such as a different session timeout per running service or you would prefer to manage the session time out at the process level. This is more flexible but might lead to some perceived inconsistency in session timeout depending on your upgrade/rollout strategy. + The management of the expiry feature fits into the 12 factor [admin process definintion](https://12factor.net/admin-processes) so it's recommended to use an process outside of your web application to manage the expiry parameters. ## Configuration From 0735bdaa258baf2acb2f8a359cdf48b5c4cdc19b Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Thu, 15 Oct 2020 23:24:14 -0300 Subject: [PATCH 11/19] wip - move to initialize version --- src/lib.rs | 81 +++++++++++++++++++++++++-------------------------- tests/test.rs | 4 +-- 2 files changed, 41 insertions(+), 44 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index e07af61..685278e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,7 +15,7 @@ #![deny(missing_debug_implementations, nonstandard_style)] #![warn(missing_docs, missing_doc_code_examples, unreachable_pub)] -use async_session::chrono::Utc; +use async_session::chrono::{Utc, Duration}; use async_session::{Result, Session, SessionStore}; use async_trait::async_trait; use mongodb::bson; @@ -73,26 +73,22 @@ impl MongodbSessionStore { } } - /// Create a new index for the `created` property and set the expiry ttl (in secods). - /// The session will expire when the number of seconds in the expireAfterSeconds field has passed - /// since the time specified in its created field. - /// https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-after-a-specified-number-of-seconds - /// ```rust - /// # fn main() -> async_session::Result { async_std::task::block_on(async { - /// # use async_mongodb_session::MongodbSessionStore; - /// let store = - /// MongodbSessionStore::connect("mongodb://127.0.0.1:27017", "db_name", "collection") - /// .await?; - /// store.index_on_created(300).await?; - /// # Ok(()) }) } - /// ``` - pub async fn index_on_created(&self, expire_after_seconds: u32) -> Result { + /// + /// + pub async fn initialize(&self) -> Result { + self.index_on_expiry_at().await?; + Ok(()) + } + + /// + /// + async fn create_expire_index(&self, field_name: &str, expire_after_seconds: u32) -> Result { let create_index = doc! { "createIndexes": &self.coll_name, "indexes": [ { - "key" : { "created": 1 }, - "name": "session_expire_after_created_index", + "key" : { field_name: 1 }, + "name": format!("session_expire_index_{}", field_name), "expireAfterSeconds": expire_after_seconds, } ] @@ -107,6 +103,24 @@ impl MongodbSessionStore { Ok(()) } + /// Create a new index for the `created` property and set the expiry ttl (in secods). + /// The session will expire when the number of seconds in the expireAfterSeconds field has passed + /// since the time specified in its created field. + /// https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-after-a-specified-number-of-seconds + /// ```rust + /// # fn main() -> async_session::Result { async_std::task::block_on(async { + /// # use async_mongodb_session::MongodbSessionStore; + /// let store = + /// MongodbSessionStore::connect("mongodb://127.0.0.1:27017", "db_name", "collection") + /// .await?; + /// store.index_on_created(300).await?; + /// # Ok(()) }) } + /// ``` + pub async fn index_on_created(&self, expire_after_seconds: u32) -> Result { + self.create_expire_index("created", expire_after_seconds).await?; + Ok(()) + } + /// Create a new index for the `expireAt` property, allowing to expire sessions at a specific clock time. /// If the `expireAt` date field contains a date in the past, mongodb considers the document expired and will be deleted. /// https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time @@ -120,23 +134,7 @@ impl MongodbSessionStore { /// # Ok(()) }) } /// ``` pub async fn index_on_expiry_at(&self) -> Result { - let create_index = doc! { - "createIndexes": &self.coll_name, - "indexes": [ - { - "key" : { "expireAt": 1 }, - "name": "session_expire_at_index", - "expireAfterSeconds": 0, - } - ] - }; - self.client - .database(&self.db) - .run_command( - create_index, - SelectionCriteria::ReadPreference(mongodb::options::ReadPreference::Primary), - ) - .await?; + self.create_expire_index("expireAt", 0).await?; Ok(()) } } @@ -149,14 +147,12 @@ impl SessionStore for MongodbSessionStore { let value = bson::to_bson(&session)?; let id = session.id(); let query = doc! { "session_id": id }; - let replacement = match session.expiry() { - None => { - doc! { "session_id": id, "session": value,"created": Utc::now() } - } - Some(expire_at) => { - doc! { "session_id": id, "session": value, "expireAt": expire_at, "created": Utc::now() } - } + let expire_at = match session.expiry() { + None => { Utc::now() + Duration::from_std(std::time::Duration::from_secs(1220)).unwrap() }, + + Some(expiry) => *{ expiry } }; + let replacement = doc! { "session_id": id, "session": value, "expireAt": expire_at, "created": Utc::now() }; let opts = ReplaceOptions::builder().upsert(true).build(); coll.replace_one(query, replacement, Some(opts)).await?; @@ -189,7 +185,8 @@ impl SessionStore for MongodbSessionStore { async fn clear_store(&self) -> Result { let coll = self.client.database(&self.db).collection(&self.coll_name); - coll.drop(None).await?; // does this need to be followed by a create? + coll.drop(None).await?; + self.initialize().await?; Ok(()) } } diff --git a/tests/test.rs b/tests/test.rs index faa988c..17ed9e5 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -70,7 +70,7 @@ mod tests { let store = MongodbSessionStore::connect(&CONNECTION_STRING, "db_name", "collection").await?; - store.index_on_expiry_at().await?; + store.initialize().await?; let mut rng = rand::thread_rng(); let n2: u16 = rng.gen(); @@ -96,7 +96,7 @@ mod tests { let store = MongodbSessionStore::connect(&CONNECTION_STRING, "db_name", "collection").await?; - store.index_on_expiry_at().await?; + store.initialize().await?; let mut rng = rand::thread_rng(); let n2: u16 = rng.gen(); From 281f6234c20dc35cf7395faea1a27727c87c2a11 Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Thu, 15 Oct 2020 23:27:58 -0300 Subject: [PATCH 12/19] fmt --- src/lib.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 685278e..4562a8e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,7 +15,7 @@ #![deny(missing_debug_implementations, nonstandard_style)] #![warn(missing_docs, missing_doc_code_examples, unreachable_pub)] -use async_session::chrono::{Utc, Duration}; +use async_session::chrono::{Duration, Utc}; use async_session::{Result, Session, SessionStore}; use async_trait::async_trait; use mongodb::bson; @@ -117,7 +117,8 @@ impl MongodbSessionStore { /// # Ok(()) }) } /// ``` pub async fn index_on_created(&self, expire_after_seconds: u32) -> Result { - self.create_expire_index("created", expire_after_seconds).await?; + self.create_expire_index("created", expire_after_seconds) + .await?; Ok(()) } @@ -148,9 +149,9 @@ impl SessionStore for MongodbSessionStore { let id = session.id(); let query = doc! { "session_id": id }; let expire_at = match session.expiry() { - None => { Utc::now() + Duration::from_std(std::time::Duration::from_secs(1220)).unwrap() }, + None => Utc::now() + Duration::from_std(std::time::Duration::from_secs(1200)).unwrap(), - Some(expiry) => *{ expiry } + Some(expiry) => *{ expiry }, }; let replacement = doc! { "session_id": id, "session": value, "expireAt": expire_at, "created": Utc::now() }; From a5bad730a9589f29c86f1ab4541976ee7d23c2e6 Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Sat, 17 Oct 2020 09:20:58 -0300 Subject: [PATCH 13/19] clean up readme and add examples --- README.md | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9836b33..30d6bcd 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,60 @@ $ cargo add async-mongodb-session ``` ## Overview -This library allow you to utilises the document expiration feature based on a [specified number of seconds](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-after-a-specified-number-of-seconds) or in a [specific clock time](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time) supported by mongodb to expire the session. +By default this library utilises the document expiration feature based on [specific clock time](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time) supported by mongodb to auto-expire the session. + +For other option to offloading the session expiration to the mongodb layer check the [Advance options](#advance-options). + +## Example with tide +Create an HTTP server that keep track of user visits in the session. + +```rust +#[async_std::main] +async fn main() -> Result<(), std::io::Error> { + tide::log::start(); + let mut app = tide::new(); + + let store = MongodbSessionStore::new("mongodb://127.0.0.1:27017", "db_name", "collection").await + .expect("Coldn't connect to the mongodb instance"); + store.initialize().await.expect("Couldn't initialize the session store"); + + app.with(tide::sessions::SessionMiddleware::new( + store, + std::env::var("TIDE_SECRET") + .expect( + "Please provide a TIDE_SECRET value of at \ + least 32 bytes in order to run this example", + ) + .as_bytes(), + )); + + app.with(tide::utils::Before( + |mut request: tide::Request<()>| async move { + let session = request.session_mut(); + let visits: usize = session.get("visits").unwrap_or_default(); + session.insert("visits", visits + 1).unwrap(); + request + }, + )); + + app.at("/").get(|req: tide::Request<()>| async move { + let visits: usize = req.session().get("visits").unwrap(); + Ok(format!("you have visited this website {} times", visits)) + }); + + app.at("/reset") + .get(|mut req: tide::Request<()>| async move { + req.session_mut().destroy(); + Ok(tide::Redirect::new("/")) + }); + + app.listen("127.0.0.1:8080").await?; + + Ok(()) +} +``` +## Advance options +a [specified number of seconds](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-after-a-specified-number-of-seconds) or in a The specified number of seconds approach is designed to enable the session time out to be managed at the mongodb layer. This approach provides a globally consistent session timeout across multiple processes but has the downside that all services using the same session collection must use the same timeout value. @@ -55,7 +108,7 @@ The specific clock time clock time approach is where you require more flexibilit The management of the expiry feature fits into the 12 factor [admin process definintion](https://12factor.net/admin-processes) so it's recommended to use an process outside of your web application to manage the expiry parameters. -## Configuration +## Manual configuration A `created` property is available on the root of the session document that so the [expiry feature](https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-after-a-specified-number-of-seconds) can be used in the configuration. From b49ea3de11ef8d71724997581202f85345457f5e Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Sat, 17 Oct 2020 09:21:31 -0300 Subject: [PATCH 14/19] changes to use initialize and the default expireAt mechanism --- Cargo.toml | 1 + src/lib.rs | 65 ++++++++++++++++++++++++++++++++++++++++++--------- tests/test.rs | 8 +++---- 3 files changed, 59 insertions(+), 15 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 9e82817..299a397 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,3 +28,4 @@ serde_json = "1.0.56" async-std = { version = "1.6.2", features = ["attributes"] } rand = {version = "0.7.3"} lazy_static = "1" +tide = "0.13" diff --git a/src/lib.rs b/src/lib.rs index 4562a8e..c4a43f5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,7 +7,7 @@ //! use async_session::{Session, SessionStore}; //! //! # fn main() -> async_session::Result { async_std::task::block_on(async { -//! let store = MongodbSessionStore::connect("mongodb://127.0.0.1:27017", "db_name", "collection"); +//! let store = MongodbSessionStore::new("mongodb://127.0.0.1:27017", "db_name", "collection"); //! # Ok(()) }) } //! ``` @@ -29,19 +29,20 @@ pub struct MongodbSessionStore { client: mongodb::Client, db: String, coll_name: String, + ttl: usize, } impl MongodbSessionStore { - /// Create a new instance of `MongodbSessionStore`. + /// Create a new instance of `MongodbSessionStore` after stablish the connection to monngodb. /// ```rust /// # fn main() -> async_session::Result { async_std::task::block_on(async { /// # use async_mongodb_session::MongodbSessionStore; /// let store = - /// MongodbSessionStore::connect("mongodb://127.0.0.1:27017", "db_name", "collection") + /// MongodbSessionStore::new("mongodb://127.0.0.1:27017", "db_name", "collection") /// .await?; /// # Ok(()) }) } /// ``` - pub async fn connect(uri: &str, db: &str, coll_name: &str) -> mongodb::error::Result { + pub async fn new(uri: &str, db: &str, coll_name: &str) -> mongodb::error::Result { let client = Client::with_uri_str(uri).await?; Ok(Self::from_client(client, db, coll_name)) } @@ -70,18 +71,60 @@ impl MongodbSessionStore { client, db: db.to_string(), coll_name: coll_name.to_string(), + ttl: 1200, // 20 mins by default. } } - /// - /// + /// Initialize the default expiration mechanism, based on the document expiration + /// that mongodb provides https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time. + /// The default ttl applyed to sessions without expiry is 20 minutes. + /// If the `expireAt` date field contains a date in the past, mongodb considers the document expired and will be deleted. + /// Note: mongodb runs the expiration logic every 60 seconds. + /// ```rust + /// # fn main() -> async_session::Result { async_std::task::block_on(async { + /// # use async_mongodb_session::MongodbSessionStore; + /// let store = + /// MongodbSessionStore::new("mongodb://127.0.0.1:27017", "db_name", "collection") + /// .await?; + /// store.initialize().await?; + /// # Ok(()) }) } + /// ``` pub async fn initialize(&self) -> Result { - self.index_on_expiry_at().await?; + &self.index_on_expiry_at().await?; Ok(()) } - /// - /// + /// Get the default ttl value in seconds. + /// ```rust + /// # fn main() -> async_session::Result { async_std::task::block_on(async { + /// # use async_mongodb_session::MongodbSessionStore; + /// let store = + /// MongodbSessionStore::new("mongodb://127.0.0.1:27017", "db_name", "collection") + /// .await?; + /// let ttl = store.ttl(); + /// # Ok(()) }) } + /// ``` + pub fn ttl(&self) -> usize { + self.ttl + } + + /// Set the default ttl value in seconds. + /// ```rust + /// # fn main() -> async_session::Result { async_std::task::block_on(async { + /// # use async_mongodb_session::MongodbSessionStore; + /// let mut store = + /// MongodbSessionStore::new("mongodb://127.0.0.1:27017", "db_name", "collection") + /// .await?; + /// store.set_ttl(300); + /// # Ok(()) }) } + /// ``` + pub fn set_ttl(&mut self, ttl: usize) { + self.ttl = ttl; + } + + /// private associated function + /// Create an `expire after seconds` index in the provided field. + /// Testing is covered by initialize test. async fn create_expire_index(&self, field_name: &str, expire_after_seconds: u32) -> Result { let create_index = doc! { "createIndexes": &self.coll_name, @@ -111,7 +154,7 @@ impl MongodbSessionStore { /// # fn main() -> async_session::Result { async_std::task::block_on(async { /// # use async_mongodb_session::MongodbSessionStore; /// let store = - /// MongodbSessionStore::connect("mongodb://127.0.0.1:27017", "db_name", "collection") + /// MongodbSessionStore::new("mongodb://127.0.0.1:27017", "db_name", "collection") /// .await?; /// store.index_on_created(300).await?; /// # Ok(()) }) } @@ -129,7 +172,7 @@ impl MongodbSessionStore { /// # fn main() -> async_session::Result { async_std::task::block_on(async { /// # use async_mongodb_session::MongodbSessionStore; /// let store = - /// MongodbSessionStore::connect("mongodb://127.0.0.1:27017", "db_name", "collection") + /// MongodbSessionStore::new("mongodb://127.0.0.1:27017", "db_name", "collection") /// .await?; /// store.index_on_expiry_at().await?; /// # Ok(()) }) } diff --git a/tests/test.rs b/tests/test.rs index 17ed9e5..f1a477f 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -44,10 +44,10 @@ mod tests { } #[test] - fn test_connect() -> async_session::Result { + fn test_new() -> async_session::Result { async_std::task::block_on(async { let store = - MongodbSessionStore::connect(&CONNECTION_STRING, "db_name", "collection").await?; + MongodbSessionStore::new(&CONNECTION_STRING, "db_name", "collection").await?; let mut rng = rand::thread_rng(); let n2: u16 = rng.gen(); @@ -68,7 +68,7 @@ mod tests { fn test_with_expire() -> async_session::Result { async_std::task::block_on(async { let store = - MongodbSessionStore::connect(&CONNECTION_STRING, "db_name", "collection").await?; + MongodbSessionStore::new(&CONNECTION_STRING, "db_name", "collection").await?; store.initialize().await?; @@ -94,7 +94,7 @@ mod tests { use std::time::Duration; async_std::task::block_on(async { let store = - MongodbSessionStore::connect(&CONNECTION_STRING, "db_name", "collection").await?; + MongodbSessionStore::new(&CONNECTION_STRING, "db_name", "collection").await?; store.initialize().await?; From 6dbf35b85aeaac5d6ccc282673619375e0712feb Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Sun, 20 Dec 2020 14:19:09 -0300 Subject: [PATCH 15/19] change example to work with --- examples/mongodb_session_store.rs | 47 +++++++++++++++++++++++++++++++ src/lib.rs | 6 ++-- 2 files changed, 50 insertions(+), 3 deletions(-) create mode 100644 examples/mongodb_session_store.rs diff --git a/examples/mongodb_session_store.rs b/examples/mongodb_session_store.rs new file mode 100644 index 0000000..8f886d3 --- /dev/null +++ b/examples/mongodb_session_store.rs @@ -0,0 +1,47 @@ +extern crate async_mongodb_session; +extern crate tide; + +use async_mongodb_session::MongodbSessionStore; + +#[async_std::main] +async fn main() -> tide::Result<()> { + tide::log::start(); + let mut app = tide::new(); + let store = + MongodbSessionStore::new("mongodb://127.0.0.1:27017", "db_name", "collection").await?; + store.initialize().await?; + + app.with(tide::sessions::SessionMiddleware::new( + store, + std::env::var("TIDE_SECRET") + .expect( + "Please provide a TIDE_SECRET value of at \ + least 32 bytes in order to run this example", + ) + .as_bytes(), + )); + + app.with(tide::utils::Before( + |mut request: tide::Request<()>| async move { + let session = request.session_mut(); + let visits: usize = session.get("visits").unwrap_or_default(); + session.insert("visits", visits + 1).unwrap(); + request + }, + )); + + app.at("/").get(|req: tide::Request<()>| async move { + let visits: usize = req.session().get("visits").unwrap(); + Ok(format!("you have visited this website {} times", visits)) + }); + + app.at("/reset") + .get(|mut req: tide::Request<()>| async move { + req.session_mut().destroy(); + Ok(tide::Redirect::new("/")) + }); + + app.listen("127.0.0.1:8080").await?; + + Ok(()) +} diff --git a/src/lib.rs b/src/lib.rs index c4a43f5..f548af1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -79,7 +79,7 @@ impl MongodbSessionStore { /// that mongodb provides https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time. /// The default ttl applyed to sessions without expiry is 20 minutes. /// If the `expireAt` date field contains a date in the past, mongodb considers the document expired and will be deleted. - /// Note: mongodb runs the expiration logic every 60 seconds. + /// Note: mongodb runs the expiration logic every 60 seconds. /// ```rust /// # fn main() -> async_session::Result { async_std::task::block_on(async { /// # use async_mongodb_session::MongodbSessionStore; @@ -103,7 +103,7 @@ impl MongodbSessionStore { /// .await?; /// let ttl = store.ttl(); /// # Ok(()) }) } - /// ``` + /// ``` pub fn ttl(&self) -> usize { self.ttl } @@ -117,7 +117,7 @@ impl MongodbSessionStore { /// .await?; /// store.set_ttl(300); /// # Ok(()) }) } - /// ``` + /// ``` pub fn set_ttl(&mut self, ttl: usize) { self.ttl = ttl; } From 56a644a26438403495bb18468d2ea86360708b91 Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Sun, 20 Dec 2020 14:33:35 -0300 Subject: [PATCH 16/19] update deps --- Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 299a397..48353ab 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,7 +25,7 @@ async-trait = "0.1.36" serde_json = "1.0.56" [dev-dependencies] -async-std = { version = "1.6.2", features = ["attributes"] } +async-std = { version = "1.8.0", features = ["attributes"] } rand = {version = "0.7.3"} lazy_static = "1" -tide = "0.13" +tide = "0.15" From bb65d43c3d96c5355768988f51ca31e6b05a266f Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Mon, 21 Dec 2020 07:41:53 -0300 Subject: [PATCH 17/19] improve ergonomics --- README.md | 8 ++------ examples/mongodb_session_store.rs | 5 +---- src/lib.rs | 8 +++++--- 3 files changed, 8 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 30d6bcd..ebc4214 100644 --- a/README.md +++ b/README.md @@ -56,16 +56,12 @@ Create an HTTP server that keep track of user visits in the session. ```rust #[async_std::main] -async fn main() -> Result<(), std::io::Error> { +async fn main() -> tide::Result<()> { tide::log::start(); let mut app = tide::new(); - let store = MongodbSessionStore::new("mongodb://127.0.0.1:27017", "db_name", "collection").await - .expect("Coldn't connect to the mongodb instance"); - store.initialize().await.expect("Couldn't initialize the session store"); - app.with(tide::sessions::SessionMiddleware::new( - store, + MongodbSessionStore::new("mongodb://127.0.0.1:27017", "db_name", "collection").await?, std::env::var("TIDE_SECRET") .expect( "Please provide a TIDE_SECRET value of at \ diff --git a/examples/mongodb_session_store.rs b/examples/mongodb_session_store.rs index 8f886d3..355040e 100644 --- a/examples/mongodb_session_store.rs +++ b/examples/mongodb_session_store.rs @@ -7,12 +7,9 @@ use async_mongodb_session::MongodbSessionStore; async fn main() -> tide::Result<()> { tide::log::start(); let mut app = tide::new(); - let store = - MongodbSessionStore::new("mongodb://127.0.0.1:27017", "db_name", "collection").await?; - store.initialize().await?; app.with(tide::sessions::SessionMiddleware::new( - store, + MongodbSessionStore::new("mongodb://127.0.0.1:27017", "db_name", "collection").await?, std::env::var("TIDE_SECRET") .expect( "Please provide a TIDE_SECRET value of at \ diff --git a/src/lib.rs b/src/lib.rs index f548af1..edb55f1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -42,9 +42,11 @@ impl MongodbSessionStore { /// .await?; /// # Ok(()) }) } /// ``` - pub async fn new(uri: &str, db: &str, coll_name: &str) -> mongodb::error::Result { - let client = Client::with_uri_str(uri).await?; - Ok(Self::from_client(client, db, coll_name)) + pub async fn new(uri: &str, db: &str, coll_name: &str) -> Result { //mongodb::error::Result { + let client = Client::with_uri_str(uri).await.map_err(|e | { std::io::Error::new( std::io::ErrorKind::Other, e.labels().join(" ") ) })?; + let middleware = Self::from_client(client, db, coll_name); + middleware.index_on_expiry_at().await?; + Ok(middleware) } /// Create a new instance of `MongodbSessionStore` from an open client. From af0f8465916a215638d356cddd85a846f94b2bed Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Mon, 21 Dec 2020 07:50:30 -0300 Subject: [PATCH 18/19] fmt --- src/lib.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index edb55f1..d36d338 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -42,8 +42,11 @@ impl MongodbSessionStore { /// .await?; /// # Ok(()) }) } /// ``` - pub async fn new(uri: &str, db: &str, coll_name: &str) -> Result { //mongodb::error::Result { - let client = Client::with_uri_str(uri).await.map_err(|e | { std::io::Error::new( std::io::ErrorKind::Other, e.labels().join(" ") ) })?; + pub async fn new(uri: &str, db: &str, coll_name: &str) -> Result { + //mongodb::error::Result { + let client = Client::with_uri_str(uri) + .await + .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.labels().join(" ")))?; let middleware = Self::from_client(client, db, coll_name); middleware.index_on_expiry_at().await?; Ok(middleware) From 636f3a72960c9296fedc9e457d83bd0cd8b5efe1 Mon Sep 17 00:00:00 2001 From: Pepo Viola Date: Mon, 21 Dec 2020 11:19:51 -0300 Subject: [PATCH 19/19] fmt --- src/lib.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index d36d338..ab639db 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -42,13 +42,10 @@ impl MongodbSessionStore { /// .await?; /// # Ok(()) }) } /// ``` - pub async fn new(uri: &str, db: &str, coll_name: &str) -> Result { - //mongodb::error::Result { - let client = Client::with_uri_str(uri) - .await - .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.labels().join(" ")))?; + pub async fn new(uri: &str, db: &str, coll_name: &str) -> mongodb::error::Result { + let client = Client::with_uri_str(uri).await?; let middleware = Self::from_client(client, db, coll_name); - middleware.index_on_expiry_at().await?; + middleware.create_expire_index("expireAt", 0).await?; Ok(middleware) } @@ -130,7 +127,11 @@ impl MongodbSessionStore { /// private associated function /// Create an `expire after seconds` index in the provided field. /// Testing is covered by initialize test. - async fn create_expire_index(&self, field_name: &str, expire_after_seconds: u32) -> Result { + async fn create_expire_index( + &self, + field_name: &str, + expire_after_seconds: u32, + ) -> mongodb::error::Result<()> { let create_index = doc! { "createIndexes": &self.coll_name, "indexes": [