Skip to content

Commit

Permalink
save only when messages have been modified
Browse files Browse the repository at this point in the history
  • Loading branch information
maxcountryman committed Jan 18, 2024
1 parent 117a117 commit 9b7cd82
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 5 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Unreleased

# 0.2.1

- Save only when messages have been modified

# 0.2.0

**Breaking Changes**
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "axum-messages"
version = "0.2.0"
version = "0.2.1"
edition = "2021"
authors = ["Max Countryman <hello@maxcountryman.com>"]
categories = ["asynchronous", "network-programming", "web-programming"]
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ To use the crate in your project, add the following to your `Cargo.toml` file:

```toml
[dependencies]
axum-messages = "0.2.0"
axum-messages = "0.2.1"
```

## 🤸 Usage
Expand Down
24 changes: 21 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ use std::{
collections::VecDeque,
future::Future,
pin::Pin,
sync::Arc,
sync::{
atomic::{self, AtomicBool},
Arc,
},
task::{Context, Poll},
};

Expand Down Expand Up @@ -145,6 +148,7 @@ struct Data {
pub struct Messages {
session: Session,
data: Arc<Mutex<Data>>,
is_modified: Arc<AtomicBool>,
}

impl Messages {
Expand All @@ -154,6 +158,7 @@ impl Messages {
Self {
session,
data: Arc::new(Mutex::new(data)),
is_modified: Arc::new(AtomicBool::new(false)),
}
}

Expand Down Expand Up @@ -191,6 +196,11 @@ impl Messages {
level,
});
}

if !self.is_modified() {
self.is_modified.store(true, atomic::Ordering::Release);
}

self
}

Expand All @@ -209,14 +219,22 @@ impl Messages {
}
self
}

fn is_modified(&self) -> bool {
self.is_modified.load(atomic::Ordering::Acquire)
}
}

impl Iterator for Messages {
type Item = Message;

fn next(&mut self) -> Option<Self::Item> {
let mut data = self.data.lock();
data.messages.pop_front()
let message = data.messages.pop_front();
if message.is_some() && !self.is_modified() {
self.is_modified.store(true, atomic::Ordering::Release);
}
message
}
}

Expand Down Expand Up @@ -274,7 +292,7 @@ where

let res = inner.call(req).await;

if messages.save().await.is_err() {
if messages.is_modified() && messages.save().await.is_err() {
let mut res = Response::default();
*res.status_mut() = http::StatusCode::INTERNAL_SERVER_ERROR;
return Ok(res);
Expand Down

0 comments on commit 9b7cd82

Please sign in to comment.