Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement create method for mongdb-store #16

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions mongodb-store/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Unreleased

# 0.12.0

- Update `tower-sessions` to `0.12.0` and implement `SessionStore::create`.

# 0.11.0

- Update `tower-sessions` to `0.11.0`
Expand Down
2 changes: 1 addition & 1 deletion mongodb-store/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "tower-sessions-mongodb-store"
description = "MongoDB session store for `tower-sessions`."
version = "0.11.0"
version = "0.12.0"
edition = "2021"
authors = ["Max Countryman <[email protected]>"]
license = "MIT"
Expand Down
98 changes: 83 additions & 15 deletions mongodb-store/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use async_trait::async_trait;
use bson::{doc, to_document};
pub use mongodb;
use mongodb::{options::UpdateOptions, Client, Collection};
use mongodb::{options::UpdateOptions, Client, ClientSession, Collection};
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use tower_sessions_core::{
Expand Down Expand Up @@ -53,6 +53,7 @@ struct MongoDBSessionRecord {
/// A MongoDB session store.
#[derive(Clone, Debug)]
pub struct MongoDBStore {
client: Client,
collection: Collection<MongoDBSessionRecord>,
}

Expand All @@ -73,8 +74,49 @@ impl MongoDBStore {
pub fn new(client: Client, database: String) -> Self {
Self {
collection: client.database(&database).collection("sessions"),
client,
}
}

async fn id_exists(
&self,
session: &mut ClientSession,
record: &Record,
) -> session_store::Result<bool> {
Ok(self
.collection
.find_one_with_session(doc! { "_id": record.id.to_string() }, None, session)
.await
.map_err(MongoDBStoreError::MongoDB)?
.is_some())
}

async fn save_with_session(
&self,
session: &mut ClientSession,
record: &Record,
) -> session_store::Result<()> {
let doc = to_document(&MongoDBSessionRecord {
data: bson::Binary {
subtype: bson::spec::BinarySubtype::Generic,
bytes: rmp_serde::to_vec(record).map_err(MongoDBStoreError::Encode)?,
},
expiry_date: bson::DateTime::from(record.expiry_date),
})
.map_err(MongoDBStoreError::BsonSerialize)?;

self.collection
.update_one_with_session(
doc! { "_id": record.id.to_string() },
doc! { "$set": doc },
UpdateOptions::builder().upsert(true).build(),
session,
)
.await
.map_err(MongoDBStoreError::MongoDB)?;

Ok(())
}
}

#[async_trait]
Expand All @@ -94,22 +136,48 @@ impl ExpiredDeletion for MongoDBStore {

#[async_trait]
impl SessionStore for MongoDBStore {
async fn create(&self, record: &mut Record) -> session_store::Result<()> {
let mut session = self
.client
.start_session(None)
.await
.map_err(MongoDBStoreError::MongoDB)?;

session
.start_transaction(None)
.await
.map_err(MongoDBStoreError::MongoDB)?;

while self.id_exists(&mut session, record).await? {
record.id = Id::default();
}

self.save_with_session(&mut session, record).await?;

session
.commit_transaction()
.await
.map_err(MongoDBStoreError::MongoDB)?;

Ok(())
}

async fn save(&self, record: &Record) -> session_store::Result<()> {
let doc = to_document(&MongoDBSessionRecord {
data: bson::Binary {
subtype: bson::spec::BinarySubtype::Generic,
bytes: rmp_serde::to_vec(record).map_err(MongoDBStoreError::Encode)?,
},
expiry_date: bson::DateTime::from(record.expiry_date),
})
.map_err(MongoDBStoreError::BsonSerialize)?;
let mut session = self
.client
.start_session(None)
.await
.map_err(MongoDBStoreError::MongoDB)?;

self.collection
.update_one(
doc! { "_id": record.id.to_string() },
doc! { "$set": doc },
UpdateOptions::builder().upsert(true).build(),
)
session
.start_transaction(None)
.await
.map_err(MongoDBStoreError::MongoDB)?;

self.save_with_session(&mut session, record).await?;

session
.commit_transaction()
.await
.map_err(MongoDBStoreError::MongoDB)?;

Expand Down
Loading