Skip to content

Commit

Permalink
Use predefined constructors over Filder::builder
Browse files Browse the repository at this point in the history
  • Loading branch information
rustworthy committed Feb 28, 2025
1 parent ab6e2a9 commit 29f0259
Show file tree
Hide file tree
Showing 6 changed files with 76 additions and 117 deletions.
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ pub use crate::proto::{

/// Constructs used to mutate queues on the Faktory server.
pub mod mutate {
pub use crate::proto::{Filter, FilterBuilder, JobSet};
pub use crate::proto::{Filter, JobSet};
}

pub use crate::worker::{JobRunner, StopDetails, StopReason, Worker, WorkerBuilder};
Expand Down
16 changes: 6 additions & 10 deletions src/proto/client/mutation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl Client {
/// let job_id1 = JobId::new("3sgE_qwtqw1501");
/// let job_id2 = JobId::new("3sgE_qwtqw1502");
/// let scheduled = [&job_id1, &job_id2];
/// let filter = Filter::builder().jids(scheduled.as_slice()).build();
/// let filter = Filter::from_ids(scheduled.as_slice());
/// client.requeue(JobSet::Scheduled, &filter).await.unwrap();
/// # });
/// ```
Expand Down Expand Up @@ -65,7 +65,7 @@ impl Client {
candidate_job_set: JobSet,
jids: &'_ [&'_ JobId],
) -> Result<(), Error> {
let filter = Filter::builder().jids(jids).build();
let filter = Filter::from_ids(jids);
self.mutate(MutationType::Requeue, candidate_job_set, Some(&filter))
.await
}

Check warning on line 71 in src/proto/client/mutation.rs

View check run for this annotation

Codecov / codecov/patch

src/proto/client/mutation.rs#L63-L71

Added lines #L63 - L71 were not covered by tests
Expand All @@ -85,9 +85,7 @@ impl Client {
/// # use faktory::Client;
/// # use faktory::mutate::{JobSet, Filter};
/// # let mut client = Client::connect().await.unwrap();
/// let filter = Filter::builder()
/// .pattern(r#"*\"args\":\[\"fizz\"\]*"#)
/// .build();
/// let filter = Filter::from_pattern(r#"*\"args\":\[\"fizz\"\]*"#);
/// client.discard(JobSet::Scheduled, &filter).await.unwrap();
/// # });
/// ```
Expand Down Expand Up @@ -119,7 +117,7 @@ impl Client {
candidate_job_set: JobSet,
jids: &'_ [&'_ JobId],
) -> Result<(), Error> {
let filter = Filter::builder().jids(jids).build();
let filter = Filter::from_ids(jids);
self.mutate(MutationType::Discard, candidate_job_set, Some(&filter))
.await
}

Check warning on line 123 in src/proto/client/mutation.rs

View check run for this annotation

Codecov / codecov/patch

src/proto/client/mutation.rs#L115-L123

Added lines #L115 - L123 were not covered by tests
Expand All @@ -140,9 +138,7 @@ impl Client {
/// # use faktory::Client;
/// # use faktory::mutate::{JobSet, Filter};
/// # let mut client = Client::connect().await.unwrap();
/// let filter = Filter::builder()
/// .pattern(r#"*\"args\":\[\"bill\"\]*"#)
/// .build();
/// let filter = Filter::from_pattern(r#"*\"args\":\[\"bill\"\]*"#);
/// client.kill(JobSet::Scheduled, &filter).await.unwrap();
/// # });
/// ```
Expand All @@ -166,7 +162,7 @@ impl Client {
candidate_job_set: JobSet,
jids: &'_ [&'_ JobId],
) -> Result<(), Error> {
let filter = Filter::builder().jids(jids).build();
let filter = Filter::from_ids(jids);
self.mutate(MutationType::Kill, candidate_job_set, Some(&filter))
.await
}

Check warning on line 168 in src/proto/client/mutation.rs

View check run for this annotation

Codecov / codecov/patch

src/proto/client/mutation.rs#L160-L168

Added lines #L160 - L168 were not covered by tests
Expand Down
2 changes: 1 addition & 1 deletion src/proto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub use single::{
DataSnapshot, Failure, FaktoryState, Job, JobBuilder, JobId, ServerSnapshot, WorkerId,
};

pub use single::mutation::{Filter, FilterBuilder, JobSet};
pub use single::mutation::{Filter, JobSet};

pub(crate) use single::{Ack, Fail, Info, Push, PushBulk, QueueAction, QueueControl};

Expand Down
4 changes: 2 additions & 2 deletions src/proto/single/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ mod test {
assert_eq!(ser, r#"{"cmd":"requeue","target":"scheduled"}"#);

// filter is some but empty
let empty_filter = Filter::builder().build();
let empty_filter = Filter::empty();
let action = MutationAction {
cmd: MutationType::Requeue,
target: JobSet::Scheduled,
Expand All @@ -368,7 +368,7 @@ mod test {
assert_eq!(ser, r#"{"cmd":"requeue","target":"scheduled"}"#);

// filter with jobtype
let jobtype_filter = Filter::builder().kind("any").build();
let jobtype_filter = Filter::from_kind("any");
let action = MutationAction {
cmd: MutationType::Requeue,
target: JobSet::Scheduled,
Expand Down
86 changes: 43 additions & 43 deletions src/proto/single/mutation.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::JobId;
use derive_builder::Builder;

#[cfg(doc)]
use crate::{Client, Job};
Expand Down Expand Up @@ -29,39 +28,27 @@ pub enum JobSet {
//
/// A filter to help narrow down the mutation target.
///
/// As of Faktory version 1.9.2, if [`Filter::pattern`] and/or [`Filter::kind`]
/// is specified, the values in [`Filter::jids`] will not be taken into account by the
/// server. If you want to filter by `jids`, make sure to leave other fields of the filter empty
/// or use dedicated methods like [`Client::requeue_by_ids`].
///
/// Example usage:
/// ```no_run
/// # tokio_test::block_on(async {
/// # use faktory::Client;
/// # use faktory::mutate::{JobSet, Filter};
/// # let mut client = Client::connect().await.unwrap();
/// let filter = Filter::builder()
/// .kind("jobtype_here")
/// .pattern(r#"*\"args\":\[\"fizz\"\]*"#)
/// .build();
/// let filter = Filter::from_kind_and_pattern("jobtype_here", r#"*\"args\":\[\"fizz\"\]*"#);
/// client.requeue(JobSet::Retries, &filter).await.unwrap();
/// # })
/// ```
#[derive(Builder, Clone, Debug, PartialEq, Eq, Serialize)]
#[builder(setter(into), build_fn(name = "try_build", private), pattern = "owned")]
#[derive(Clone, Default, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct Filter<'a> {
/// A job's [`kind`](crate::Job::kind).
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "jobtype")]
#[builder(default)]
pub kind: Option<&'a str>,
pub(crate) kind: Option<&'a str>,

/// [`JobId`]s to target.
#[serde(skip_serializing_if = "Empty::is_empty")]
#[builder(setter(custom))]
#[builder(default)]
pub jids: Option<&'a [&'a JobId]>,
pub(crate) jids: Option<&'a [&'a JobId]>,

/// Match pattern to use for filtering.
///
Expand All @@ -70,8 +57,7 @@ pub struct Filter<'a> {
/// for further details.
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "regexp")]
#[builder(default)]
pub pattern: Option<&'a str>,
pub(crate) pattern: Option<&'a str>,
}

impl Empty for &Filter<'_> {
Expand All @@ -80,37 +66,51 @@ impl Empty for &Filter<'_> {
}
}

impl<'a> Filter<'_> {
impl<'a> Filter<'a> {
/// Creates an empty filter.
///
/// Sending a mutation command (e.g. [`Client::discard`]) with an empty
/// filter effectively means performing no filtering at all.
/// filter effectively means using a wildcard.
pub fn empty() -> Self {
Self::default()
}

/// Creates a filter from the provided [`JobId`]s.
pub fn from_ids(ids: &'a [&JobId]) -> Self {
Self {
kind: None,
jids: None,
pattern: None,
jids: Some(ids),
..Default::default()
}
}

/// Creates a new builder for a [`Filter`].
pub fn builder() -> FilterBuilder<'a> {
FilterBuilder::default()
/// Creates a filter with the provided job's [`kind`](crate::Job::kind).
pub fn from_kind(job_kind: &'a str) -> Self {
Self {
kind: Some(job_kind),
..Default::default()
}
}
}

impl<'a> FilterBuilder<'a> {
/// Ids of jobs to target.
pub fn jids(mut self, value: &'a [&JobId]) -> Self {
self.jids = Some(value).into();
self
/// Creates a filter with the provided search pattern.
///
/// Faktory will pass this directly to Redis's `SCAN` command,
/// so please see the [`SCAN` documentation](https://redis.io/docs/latest/commands/scan/)
/// for further details.// Creates a filter with provided job kind.
pub fn from_pattern(pattern: &'a str) -> Self {
Self {
pattern: Some(pattern),
..Default::default()
}
}
}

impl<'a> FilterBuilder<'a> {
/// Builds a new [`Filter`] from the parameters of this builder.
pub fn build(self) -> Filter<'a> {
self.try_build().expect("infallible")
/// Creates a filter with the provided job's [`kind`](crate::Job::kind) and search pattern.
///
/// This is essentially [`Filter::from_kind`] and [`Filter::from_pattern`] merged together.
pub fn from_kind_and_pattern(job_kind: &'a str, pattern: &'a str) -> Self {
Self {
kind: Some(job_kind),
pattern: Some(pattern),
jids: None,
}
}
}

Expand All @@ -121,13 +121,13 @@ mod test {
#[test]
fn filter_is_serialized_correctly() {
// every field None
let filter = Filter::builder().build();
let filter = Filter::empty();
let ser = serde_json::to_string(&filter).unwrap();
assert_eq!(ser, r#"{}"#);
assert_eq!(ser, "{}");

// some but empty jids
let filter = Filter::builder().jids(&[]).kind("welcome_email").build();
let filter = Filter::from_ids(&[]);
let ser = serde_json::to_string(&filter).unwrap();
assert_eq!(ser, r#"{"jobtype":"welcome_email"}"#)
assert_eq!(ser, "{}")
}
}
Loading

0 comments on commit 29f0259

Please sign in to comment.