-
Notifications
You must be signed in to change notification settings - Fork 350
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
doc mapper: convert number handling to deserialization #5527
Open
PSeitz
wants to merge
1
commit into
main
Choose a base branch
from
refactor_mapping
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+252
−123
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
226 changes: 226 additions & 0 deletions
226
quickwit/quickwit-doc-mapper/src/doc_mapper/deser_num.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,226 @@ | ||
// Copyright (C) 2024 Quickwit, Inc. | ||
// | ||
// Quickwit is offered under the AGPL v3.0 and as commercial software. | ||
// For commercial licensing, contact us at [email protected]. | ||
// | ||
// AGPL: | ||
// This program is free software: you can redistribute it and/or modify | ||
// it under the terms of the GNU Affero General Public License as | ||
// published by the Free Software Foundation, either version 3 of the | ||
// License, or (at your option) any later version. | ||
// | ||
// This program is distributed in the hope that it will be useful, | ||
// but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
// GNU Affero General Public License for more details. | ||
// | ||
// You should have received a copy of the GNU Affero General Public License | ||
// along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
|
||
use std::fmt::{self, Display}; | ||
|
||
use serde::de::{self, Deserializer, IntoDeserializer, Visitor}; | ||
use serde::Deserialize; | ||
use serde_json::Value; | ||
|
||
/// Deserialize a number. | ||
/// | ||
/// If the value is a string, it can be optionally coerced to a number. | ||
fn deserialize_num_with_coerce<'de, T, D>(deserializer: D, coerce: bool) -> Result<T, String> | ||
where | ||
T: std::str::FromStr + Deserialize<'de>, | ||
T::Err: fmt::Display, | ||
D: Deserializer<'de>, | ||
{ | ||
struct CoerceVisitor<T> { | ||
coerce: bool, | ||
marker: std::marker::PhantomData<T>, | ||
} | ||
|
||
impl<'de, T> Visitor<'de> for CoerceVisitor<T> | ||
where | ||
T: std::str::FromStr + Deserialize<'de>, | ||
T::Err: fmt::Display, | ||
{ | ||
type Value = T; | ||
|
||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { | ||
if self.coerce { | ||
formatter | ||
.write_str("any number of i64, u64, or f64 or a string that can be coerced") | ||
} else { | ||
formatter.write_str("any number of i64, u64, or f64") | ||
} | ||
} | ||
|
||
fn visit_str<E>(self, v: &str) -> Result<T, E> | ||
where E: de::Error { | ||
if self.coerce { | ||
v.parse::<T>().map_err(|_e| { | ||
de::Error::custom(format!( | ||
"failed to coerce JSON string `\"{}\"` to {}", | ||
v, | ||
std::any::type_name::<T>(), | ||
)) | ||
}) | ||
} else { | ||
Err(de::Error::custom(format!( | ||
"expected JSON number, got string `\"{}\"`. enable coercion to {} with the \ | ||
`coerce` parameter in the field mapping", | ||
v, | ||
std::any::type_name::<T>() | ||
))) | ||
} | ||
} | ||
|
||
fn visit_i64<E>(self, v: i64) -> Result<T, E> | ||
where E: de::Error { | ||
T::deserialize(v.into_deserializer()).map_err(|_: E| { | ||
de::Error::custom(format!( | ||
"expected {}, got inconvertible JSON number `{}`", | ||
std::any::type_name::<T>(), | ||
v | ||
)) | ||
}) | ||
} | ||
|
||
fn visit_u64<E>(self, v: u64) -> Result<T, E> | ||
where E: de::Error { | ||
T::deserialize(v.into_deserializer()).map_err(|_: E| { | ||
de::Error::custom(format!( | ||
"expected {}, got inconvertible JSON number `{}`", | ||
std::any::type_name::<T>(), | ||
v | ||
)) | ||
}) | ||
} | ||
|
||
fn visit_f64<E>(self, v: f64) -> Result<T, E> | ||
where E: de::Error { | ||
T::deserialize(v.into_deserializer()).map_err(|_: E| { | ||
de::Error::custom(format!( | ||
"expected {}, got inconvertible JSON number `{}`", | ||
std::any::type_name::<T>(), | ||
v | ||
)) | ||
}) | ||
} | ||
|
||
fn visit_map<M>(self, mut map: M) -> Result<T, M::Error> | ||
where M: de::MapAccess<'de> { | ||
let json_value: Value = | ||
Deserialize::deserialize(de::value::MapAccessDeserializer::new(&mut map))?; | ||
Err(de::Error::custom(error_message(json_value, self.coerce))) | ||
} | ||
|
||
fn visit_seq<S>(self, mut seq: S) -> Result<T, S::Error> | ||
where S: de::SeqAccess<'de> { | ||
let json_value: Value = | ||
Deserialize::deserialize(de::value::SeqAccessDeserializer::new(&mut seq))?; | ||
Err(de::Error::custom(error_message(json_value, self.coerce))) | ||
} | ||
|
||
fn visit_none<E>(self) -> Result<Self::Value, E> | ||
where E: de::Error { | ||
Err(de::Error::custom(error_message("null", self.coerce))) | ||
} | ||
|
||
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> | ||
where E: de::Error { | ||
Err(de::Error::custom(error_message(v, self.coerce))) | ||
} | ||
} | ||
|
||
deserializer | ||
.deserialize_any(CoerceVisitor { | ||
coerce, | ||
marker: std::marker::PhantomData, | ||
}) | ||
.map_err(|err| err.to_string()) | ||
} | ||
|
||
fn error_message<T: Display>(got: T, coerce: bool) -> String { | ||
if coerce { | ||
format!("expected JSON number or string, got `{}`", got) | ||
} else { | ||
format!("expected JSON, got `{}`", got) | ||
} | ||
} | ||
|
||
pub fn deserialize_i64<'de, D>(deserializer: D, coerce: bool) -> Result<i64, String> | ||
where D: Deserializer<'de> { | ||
deserialize_num_with_coerce(deserializer, coerce) | ||
} | ||
|
||
pub fn deserialize_u64<'de, D>(deserializer: D, coerce: bool) -> Result<u64, String> | ||
where D: Deserializer<'de> { | ||
deserialize_num_with_coerce(deserializer, coerce) | ||
} | ||
|
||
pub fn deserialize_f64<'de, D>(deserializer: D, coerce: bool) -> Result<f64, String> | ||
where D: Deserializer<'de> { | ||
deserialize_num_with_coerce(deserializer, coerce) | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use serde_json::json; | ||
|
||
use super::*; | ||
|
||
#[test] | ||
fn test_deserialize_i64_with_coercion() { | ||
let json_data = json!("-123"); | ||
let result: i64 = deserialize_i64(json_data.into_deserializer(), true).unwrap(); | ||
assert_eq!(result, -123); | ||
|
||
let json_data = json!("456"); | ||
let result: i64 = deserialize_i64(json_data.into_deserializer(), true).unwrap(); | ||
assert_eq!(result, 456); | ||
} | ||
|
||
#[test] | ||
fn test_deserialize_u64_with_coercion() { | ||
let json_data = json!("789"); | ||
let result: u64 = deserialize_u64(json_data.into_deserializer(), true).unwrap(); | ||
assert_eq!(result, 789); | ||
|
||
let json_data = json!(123); | ||
let result: u64 = deserialize_u64(json_data.into_deserializer(), false).unwrap(); | ||
assert_eq!(result, 123); | ||
} | ||
|
||
#[test] | ||
fn test_deserialize_f64_with_coercion() { | ||
let json_data = json!("78.9"); | ||
let result: f64 = deserialize_f64(json_data.into_deserializer(), true).unwrap(); | ||
assert_eq!(result, 78.9); | ||
|
||
let json_data = json!(45.6); | ||
let result: f64 = deserialize_f64(json_data.into_deserializer(), false).unwrap(); | ||
assert_eq!(result, 45.6); | ||
} | ||
|
||
#[test] | ||
fn test_deserialize_invalid_string_coercion() { | ||
let json_data = json!("abc"); | ||
let result: Result<i64, _> = deserialize_i64(json_data.into_deserializer(), true); | ||
assert!(result.is_err()); | ||
|
||
let err_msg = result.unwrap_err().to_string(); | ||
assert_eq!(err_msg, "failed to coerce JSON string `\"abc\"` to i64"); | ||
} | ||
|
||
#[test] | ||
fn test_deserialize_json_object() { | ||
let json_data = json!({ "key": "value" }); | ||
let result: Result<i64, _> = deserialize_i64(json_data.into_deserializer(), true); | ||
assert!(result.is_err()); | ||
|
||
let err_msg = result.unwrap_err().to_string(); | ||
assert_eq!( | ||
err_msg, | ||
"expected JSON number or string, got `{\"key\":\"value\"}`" | ||
); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we need to test what happens for stuff that is out of bound.