Skip to content

Commit

Permalink
wrap FilterConfig enum in a struct
Browse files Browse the repository at this point in the history
  • Loading branch information
shouya committed Sep 23, 2024
1 parent 34c7176 commit 3d26773
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 14 deletions.
54 changes: 45 additions & 9 deletions src/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub(crate) mod select;
pub(crate) mod simplify_html;

use std::collections::{HashMap, HashSet};
use std::ops::Deref;
use std::sync::Arc;

use schemars::JsonSchema;
Expand Down Expand Up @@ -153,12 +154,44 @@ impl BoxedFilter {
}
}

type Span = std::ops::Range<usize>;

#[derive(
JsonSchema, Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash,
)]
pub struct FilterConfig {
pub value: FilterConfigEnum,
pub span: Option<Span>,
}

impl Deref for FilterConfig {
type Target = FilterConfigEnum;

fn deref(&self) -> &Self::Target {
&self.value
}
}

impl FilterConfig {
pub async fn build(self) -> Result<BoxedFilter, ConfigError> {
self.value.build().await
}

pub fn parse_yaml_value(
key: &str,
value: serde_yaml::Value,
) -> Result<Self, ConfigError> {
let value = FilterConfigEnum::parse_yaml_value(key, value)?;
Ok(Self { value, span: None })
}
}

macro_rules! define_filters {
($($variant:ident => $config:ty, $desc:literal);* ;) => {
paste::paste! {
#[derive(JsonSchema, Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum FilterConfig {
pub enum FilterConfigEnum {
$(
#[doc = "# " $variant:snake "\n\n" $desc "\n"]
$variant($config),
Expand All @@ -167,13 +200,13 @@ macro_rules! define_filters {
}


impl FilterConfig {
impl FilterConfigEnum {
// currently only used in tests
#[cfg(test)]
pub fn parse_yaml_variant(input: &str) -> Result<Box<dyn std::any::Any>> {
let config: FilterConfig = Self::parse_yaml(input)?;
let config: FilterConfigEnum = Self::parse_yaml(input)?;
match config {
$(FilterConfig::$variant(config) => {
$(FilterConfigEnum::$variant(config) => {
Ok(Box::new(config))
})*
}
Expand All @@ -184,18 +217,21 @@ macro_rules! define_filters {
#[derive(Deserialize)]
struct Dummy {
#[serde(flatten)]
config: FilterConfig
config: FilterConfigEnum
}

let dummy: Dummy = serde_yaml::from_str(input).map_err(ConfigError::from)?;
Ok(dummy.config)
}

pub fn parse_yaml_value(key: &str, value: serde_yaml::Value) -> Result<Self, ConfigError> {
pub fn parse_yaml_value(
key: &str,
value: serde_yaml::Value
) -> Result<Self, ConfigError> {
#[derive(Deserialize)]
struct Dummy {
#[serde(flatten)]
config: FilterConfig
config: FilterConfigEnum
}

use serde_yaml::{Value, Mapping, value::{Tag, TaggedValue}};
Expand All @@ -214,7 +250,7 @@ macro_rules! define_filters {

pub async fn build(self) -> Result<BoxedFilter, ConfigError> {
match self {
$(FilterConfig::$variant(config) => {
$(FilterConfigEnum::$variant(config) => {
let filter = config.build().await?;
Ok(BoxedFilter::from(filter))
})*
Expand All @@ -227,7 +263,7 @@ macro_rules! define_filters {

pub fn name(&self) -> &'static str {
match self {
$(FilterConfig::$variant(_) => paste::paste! {stringify!([<$variant:snake>])},)*
$(FilterConfigEnum::$variant(_) => paste::paste! {stringify!([<$variant:snake>])},)*
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/otf_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use tracing::warn;

use crate::{
feed::Feed,
filter::{FilterConfig, FilterContext},
filter::{FilterConfig, FilterConfigEnum, FilterContext},
filter_pipeline::{FilterPipeline, FilterPipelineConfig},
util::{ConfigError, Error},
};
Expand All @@ -25,7 +25,7 @@ impl OnTheFlyFilterQuery {
filter_name = param;
}

if FilterConfig::is_valid_key(filter_name) {
if FilterConfigEnum::is_valid_key(filter_name) {
query.push(param.to_string());
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/server/inspector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use http::{StatusCode, Uri};
use schemars::schema::RootSchema;
use serde_json::json;

use crate::filter::FilterConfig;
use crate::filter::FilterConfigEnum;
use crate::util::Error;

use super::auth::{handle_login, handle_logout, Auth};
Expand Down Expand Up @@ -99,12 +99,12 @@ async fn filter_schema_handler(
_auth: Auth,
) -> Result<Json<HashMap<String, RootSchema>>, BadRequest<String>> {
if params.filters == "all" {
return Ok(Json(FilterConfig::schema_for_all()));
return Ok(Json(FilterConfigEnum::schema_for_all()));
}

let mut schemas = HashMap::new();
for filter in params.filters.split(',') {
let Some(schema) = FilterConfig::schema_for(filter) else {
let Some(schema) = FilterConfigEnum::schema_for(filter) else {
return Err(BadRequest(format!("unknown filter: {}", filter)));
};
schemas.insert(filter.to_string(), schema);
Expand Down

0 comments on commit 3d26773

Please sign in to comment.