Skip to content

Commit 4dcb5bc

Browse files
committed
style: use rustfmt
1 parent 58d9476 commit 4dcb5bc

File tree

10 files changed

+194
-87
lines changed

10 files changed

+194
-87
lines changed

.rustfmt.toml

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
comment_width = 100
2+
max_width = 120
3+
edition = "2021"
4+
format_code_in_doc_comments = true
5+
format_strings = true
6+
group_imports = "StdExternalCrate"
7+
imports_granularity = "Crate"
8+
normalize_comments = true
9+
normalize_doc_attributes = true
10+
wrap_comments = true
11+
trailing_comma = "Vertical"
12+
fn_params_layout = "Vertical"
13+
blank_lines_upper_bound = 2
14+
blank_lines_lower_bound = 0

Cargo.toml

+1-2
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,11 @@ thiserror = "2.0"
4848
hashring = "0.3.6"
4949
job_scheduler = "1.2.1"
5050
log = "0.4"
51-
md5 = "0.7.0"
5251
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "sync"] }
5352
uuid = { version = "1", features = ["v4"] }
5453

5554
etcd-client = { version = "0.14", optional = true }
56-
redis = { version = "0.27.5", optional = true, features = ["tokio-comp"] }
55+
redis = { version = "0.27.6", optional = true, features = ["tokio-comp"] }
5756

5857
[dev-dependencies]
5958
pretty_env_logger = "0.5"

examples/etcd.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ async fn main() -> Result<(), Box<dyn Error>> {
1515
log::info!("Adding job");
1616
cron.add_job("test", "* * * * * *".parse().unwrap(), || {
1717
log::info!("Running job: {}", chrono::Utc::now());
18-
}).await?;
18+
})
19+
.await?;
1920

2021
log::info!("Starting cron");
2122
cron.start().await;

examples/redis.rs

+9-2
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,21 @@ async fn main() -> Result<(), Box<dyn Error>> {
88

99
let rdb = redis::Client::open("redis://localhost:6379").unwrap();
1010

11-
let driver = driver::redis::RedisDriver::new(rdb.get_multiplexed_tokio_connection().await?, "example-service", &uuid::Uuid::new_v4().to_string()).await?.with_timeout(3);
11+
let driver = driver::redis::RedisDriver::new(
12+
rdb.get_multiplexed_tokio_connection().await?,
13+
"example-service",
14+
&uuid::Uuid::new_v4().to_string(),
15+
)
16+
.await?
17+
.with_timeout(3);
1218
let np = node_pool::NodePool::new(driver).await?;
1319
let cron = cron::Cron::new(np).await;
1420

1521
log::info!("Adding job");
1622
cron.add_job("test", "* * * * * *".parse().unwrap(), || {
1723
log::info!("Running job: {}", chrono::Utc::now());
18-
}).await?;
24+
})
25+
.await?;
1926

2027
log::info!("Starting cron");
2128
cron.start().await;

src/cron.rs

+19-11
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
1-
use std::collections::HashMap;
2-
use std::future::Future;
3-
use std::sync::Arc;
1+
use std::{collections::HashMap, future::Future, sync::Arc};
42

53
use job_scheduler::{Schedule, Uuid};
64
use tokio::sync::Mutex;
75

8-
use crate::driver::Driver;
9-
use crate::node_pool;
6+
use crate::{driver::Driver, node_pool};
107

11-
/// The `Cron` struct is the main entry point for the library, providing the ability to add and remove jobs.
8+
/// The `Cron` struct is the main entry point for the library, providing the ability to add and
9+
/// remove jobs.
1210
pub struct Cron<'a, D>
1311
where
1412
D: Driver + Send + Sync,
@@ -60,7 +58,11 @@ where
6058
}
6159

6260
/// Register a job in the scheduler
63-
async fn register_job(&self, job_name: &str, job: job_scheduler::Job<'a>) {
61+
async fn register_job(
62+
&self,
63+
job_name: &str,
64+
job: job_scheduler::Job<'a>,
65+
) {
6466
let mut cron = self.scheduler.lock().await;
6567
let id = cron.add(job);
6668
self.jobs.lock().await.insert(job_name.to_string(), id);
@@ -73,8 +75,12 @@ where
7375
/// * `job_name` - The unique name of the job
7476
/// * `schedule` - The schedule of the job
7577
/// * `run` - The function to run
76-
///
77-
pub async fn add_job<F>(&self, job_name: &str, schedule: Schedule, run: F) -> Result<(), Error>
78+
pub async fn add_job<F>(
79+
&self,
80+
job_name: &str,
81+
schedule: Schedule,
82+
run: F,
83+
) -> Result<(), Error>
7884
where
7985
F: 'static + Sync + Send + Fn(),
8086
{
@@ -159,8 +165,10 @@ where
159165
/// # Arguments
160166
///
161167
/// * `job_name` - The unique name of the job
162-
///
163-
pub async fn remove_job(&self, job_name: &str) -> Result<(), Error> {
168+
pub async fn remove_job(
169+
&self,
170+
job_name: &str,
171+
) -> Result<(), Error> {
164172
if let Some(id) = self.jobs.lock().await.remove(job_name) {
165173
self.scheduler.lock().await.remove(id);
166174
}

src/driver/etcd.rs

+45-14
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
/// Etcd driver implementation.
2-
32
use std::collections::HashSet;
4-
use std::sync::Arc;
5-
use std::sync::atomic::AtomicBool;
3+
use std::sync::{atomic::AtomicBool, Arc};
64

75
use etcd_client::*;
86
use tokio::sync::{Mutex, RwLock};
97

10-
use super::{Driver, utils};
8+
use super::{utils, Driver};
119

1210
const DEFAULT_LEASE_TTL: i64 = 3;
1311

@@ -26,9 +24,11 @@ pub struct EtcdDriver {
2624
}
2725

2826
impl std::fmt::Debug for EtcdDriver {
29-
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
30-
f
31-
.debug_struct("EtcdDriver")
27+
fn fmt(
28+
&self,
29+
f: &mut std::fmt::Formatter,
30+
) -> std::fmt::Result {
31+
f.debug_struct("EtcdDriver")
3232
.field("service_name", &self.service_name)
3333
.field("node_id", &self.node_id)
3434
.field("stop", &self.stop)
@@ -51,7 +51,11 @@ pub enum Error {
5151

5252
impl EtcdDriver {
5353
/// Create a new etcd driver with the given client, service name, and node id.
54-
pub async fn new(client: Client, service_name: &str, node_id: &str) -> Result<Self, Error> {
54+
pub async fn new(
55+
client: Client,
56+
service_name: &str,
57+
node_id: &str,
58+
) -> Result<Self, Error> {
5559
if service_name.is_empty() {
5660
return Err(Error::EmptyServiceName);
5761
}
@@ -71,7 +75,10 @@ impl EtcdDriver {
7175
}
7276

7377
/// Set the timeout for the driver.
74-
pub fn with_timeout(mut self, timeout: i64) -> Self {
78+
pub fn with_timeout(
79+
mut self,
80+
timeout: i64,
81+
) -> Self {
7582
self.lease_ttl = timeout;
7683
self
7784
}
@@ -92,20 +99,33 @@ impl Driver for EtcdDriver {
9299
Ok(self.node_list.read().await.iter().cloned().collect())
93100
}
94101

95-
/// Start a routine to watch for node changes and register the current node. Use lease to keep the node key alive.
102+
/// Start a routine to watch for node changes and register the current node. Use lease to keep
103+
/// the node key alive.
96104
async fn start(&mut self) -> Result<(), Box<dyn std::error::Error>> {
97105
let mut client = self.client.lock().await;
98106
self.stop.store(false, std::sync::atomic::Ordering::SeqCst);
99107

100108
// init node list
101109
let mut node_list = self.node_list.write().await;
102-
for kv in client.get(utils::get_key_prefix(&self.service_name), Some(GetOptions::new().with_prefix())).await?.kvs() {
110+
for kv in client
111+
.get(
112+
utils::get_key_prefix(&self.service_name),
113+
Some(GetOptions::new().with_prefix()),
114+
)
115+
.await?
116+
.kvs()
117+
{
103118
node_list.insert(kv.key_str()?.into());
104119
}
105120

106121
// watch for node changes
107122
{
108-
let (mut watcher, mut watch_stream) = client.watch(utils::get_key_prefix(&self.service_name), Some(WatchOptions::new().with_prefix())).await?;
123+
let (mut watcher, mut watch_stream) = client
124+
.watch(
125+
utils::get_key_prefix(&self.service_name),
126+
Some(WatchOptions::new().with_prefix()),
127+
)
128+
.await?;
109129
let node_list = self.node_list.clone();
110130
let stop = self.stop.clone();
111131
tokio::spawn(async move {
@@ -160,7 +180,12 @@ impl Driver for EtcdDriver {
160180

161181
loop {
162182
if stop.load(std::sync::atomic::Ordering::SeqCst) {
163-
inner_client.lock().await.lease_revoke(lease_id).await.expect("Failed to revoke lease");
183+
inner_client
184+
.lock()
185+
.await
186+
.lease_revoke(lease_id)
187+
.await
188+
.expect("Failed to revoke lease");
164189
break;
165190
}
166191

@@ -173,7 +198,13 @@ impl Driver for EtcdDriver {
173198
});
174199

175200
// put the node key
176-
client.put(self.node_id.as_str(), self.node_id.as_str(), Some(PutOptions::new().with_lease(lease_id))).await?;
201+
client
202+
.put(
203+
self.node_id.as_str(),
204+
self.node_id.as_str(),
205+
Some(PutOptions::new().with_lease(lease_id)),
206+
)
207+
.await?;
177208
}
178209

179210
Ok(())

src/driver/redis.rs

+40-27
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
use std::fmt::Debug;
2-
use std::sync::atomic::AtomicBool;
3-
use std::sync::Arc;
1+
use std::{
2+
fmt::Debug,
3+
sync::{atomic::AtomicBool, Arc},
4+
};
45

5-
use redis::aio::ConnectionLike;
6-
use redis::AsyncCommands;
6+
use redis::{aio::ConnectionLike, AsyncCommands};
77

88
use super::{utils, Driver};
99

@@ -36,7 +36,11 @@ impl<C> RedisDriver<C>
3636
where
3737
C: ConnectionLike,
3838
{
39-
pub async fn new(con: C, service_name: &str, node_id: &str) -> Result<Self, Error> {
39+
pub async fn new(
40+
con: C,
41+
service_name: &str,
42+
node_id: &str,
43+
) -> Result<Self, Error> {
4044
if service_name.is_empty() {
4145
return Err(Error::EmptyServiceName);
4246
}
@@ -54,7 +58,10 @@ where
5458
})
5559
}
5660

57-
pub fn with_timeout(mut self, timeout: u64) -> Self {
61+
pub fn with_timeout(
62+
mut self,
63+
timeout: u64,
64+
) -> Self {
5865
self.timeout = timeout;
5966
self
6067
}
@@ -64,7 +71,6 @@ where
6471
}
6572
}
6673

67-
6874
#[async_trait::async_trait]
6975
impl<C> Driver for RedisDriver<C>
7076
where
@@ -133,8 +139,11 @@ where
133139
/// * `node_id` - The id of the node
134140
/// * `timeout` - The timeout of the node
135141
/// * `con` - The redis connection
136-
///
137-
async fn register_node<C: ConnectionLike + Send>(node_id: &str, timeout: u64, con: &mut C) -> Result<(), Box<dyn std::error::Error>> {
142+
async fn register_node<C: ConnectionLike + Send>(
143+
node_id: &str,
144+
timeout: u64,
145+
con: &mut C,
146+
) -> Result<(), Box<dyn std::error::Error>> {
138147
con.set_ex(node_id, node_id, timeout).await?;
139148
Ok(())
140149
}
@@ -152,8 +161,12 @@ async fn register_node<C: ConnectionLike + Send>(node_id: &str, timeout: u64, co
152161
/// # Returns
153162
///
154163
/// * `Result<(), Box<dyn std::error::Error>` - The result of the function
155-
///
156-
async fn heartbeat<C: ConnectionLike + Send>(node_id: &str, timeout: u64, con: C, started: Arc<AtomicBool>) -> Result<(), Box<dyn std::error::Error>> {
164+
async fn heartbeat<C: ConnectionLike + Send>(
165+
node_id: &str,
166+
timeout: u64,
167+
con: C,
168+
started: Arc<AtomicBool>,
169+
) -> Result<(), Box<dyn std::error::Error>> {
157170
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(1));
158171
let mut con = con;
159172
let mut error_time = 0;
@@ -170,7 +183,8 @@ async fn heartbeat<C: ConnectionLike + Send>(node_id: &str, timeout: u64, con: C
170183
interval.tick().await;
171184

172185
// register the node
173-
register_node(node_id, timeout, &mut con).await
186+
register_node(node_id, timeout, &mut con)
187+
.await
174188
.map_err(|e| {
175189
error_time += 1;
176190
log::error!("Failed to register node: {:?}", e);
@@ -198,12 +212,10 @@ mod tests {
198212
let node_id = "test-node";
199213
let timeout = 10_u64;
200214

201-
let mut mock_con = MockRedisConnection::new(vec![
202-
MockCmd::new(
203-
redis::cmd("SETEX").arg(node_id).arg(timeout as usize).arg(node_id),
204-
Ok(redis::Value::Okay),
205-
),
206-
]);
215+
let mut mock_con = MockRedisConnection::new(vec![MockCmd::new(
216+
redis::cmd("SETEX").arg(node_id).arg(timeout as usize).arg(node_id),
217+
Ok(redis::Value::Okay),
218+
)]);
207219

208220
// Perform the node registration
209221
let result = register_node(node_id, timeout, &mut mock_con).await;
@@ -218,14 +230,15 @@ mod tests {
218230
let pattern = utils::get_key_prefix(service_name) + "*";
219231

220232
let keys = ["test-service-node1", "test-service-node2", "test-service-node3"];
221-
let keys_as_redis_values = keys.iter().map(|k| redis::Value::BulkString(k.to_string().into_bytes())).collect::<Vec<_>>();
222-
223-
let mock_con = MockRedisConnection::new(vec![
224-
MockCmd::new(
225-
redis::cmd("SCAN").arg("0").arg("MATCH").arg(&pattern),
226-
Ok(redis::Value::Array(keys_as_redis_values)),
227-
)
228-
]);
233+
let keys_as_redis_values = keys
234+
.iter()
235+
.map(|k| redis::Value::BulkString(k.to_string().into_bytes()))
236+
.collect::<Vec<_>>();
237+
238+
let mock_con = MockRedisConnection::new(vec![MockCmd::new(
239+
redis::cmd("SCAN").arg("0").arg("MATCH").arg(&pattern),
240+
Ok(redis::Value::Array(keys_as_redis_values)),
241+
)]);
229242

230243
// Perform the node registration
231244
let driver = RedisDriver::new(mock_con, service_name, node_id).await.unwrap();

0 commit comments

Comments
 (0)