use std::sync::Arc;
use std::time::SystemTime;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::value::RawValue;
use crate::error::Error;
use crate::field::Field;
use crate::time::parse_opt;
use crate::vocab::{
CompanyRole, EventDirection, EventType, Importance, SentimentLabel, SourceType, StreamEventName,
};
fn null_as_empty<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
Ok(Option::<Vec<T>>::deserialize(deserializer)?.unwrap_or_default())
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Article {
pub id: String,
pub link: String,
pub source: ArticleSource,
pub title: String,
#[serde(default)]
pub summary: Option<String>,
#[serde(default)]
pub language: Option<String>,
#[serde(default, deserialize_with = "null_as_empty")]
pub media: Vec<Media>,
#[serde(default)]
pub published_at: Option<String>,
#[serde(default)]
pub first_seen_at: Option<String>,
#[serde(default)]
pub revised_at: Option<String>,
#[serde(default)]
pub available_at: Option<String>,
#[serde(default, deserialize_with = "null_as_empty")]
pub countries: Vec<String>,
#[serde(default, deserialize_with = "null_as_empty")]
pub categories: Vec<String>,
#[serde(default, skip_serializing_if = "Field::is_absent")]
pub content: Field<String>,
#[serde(default, skip_serializing_if = "Field::is_absent")]
pub sentiment: Field<Sentiment>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub companies: Option<Vec<Company>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub events: Option<Vec<EventTag>>,
#[serde(skip)]
raw: Option<Arc<str>>,
}
impl Article {
pub fn content_present(&self) -> bool {
self.content.is_present()
}
pub fn sentiment_present(&self) -> bool {
self.sentiment.is_present()
}
pub fn companies_present(&self) -> bool {
self.companies.is_some()
}
pub fn events_present(&self) -> bool {
self.events.is_some()
}
pub fn published_at_time(&self) -> Option<SystemTime> {
parse_opt(self.published_at.as_deref())
}
pub fn first_seen_at_time(&self) -> Option<SystemTime> {
parse_opt(self.first_seen_at.as_deref())
}
pub fn revised_at_time(&self) -> Option<SystemTime> {
parse_opt(self.revised_at.as_deref())
}
pub fn available_at_time(&self) -> Option<SystemTime> {
parse_opt(self.available_at.as_deref())
}
pub fn raw_json(&self) -> Option<&str> {
self.raw.as_deref()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ArticleSource {
pub domain: String,
#[serde(default)]
pub r#type: Option<SourceType>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Media {
#[serde(default)]
pub url: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Sentiment {
#[serde(default)]
pub label: Option<SentimentLabel>,
#[serde(default)]
pub confidence: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Company {
pub company_id: i64,
pub name: String,
#[serde(default)]
pub isin: Option<String>,
#[serde(default)]
pub primary_listing: Option<Listing>,
#[serde(default)]
pub confidence: Option<f64>,
#[serde(default)]
pub role: Option<CompanyRole>,
#[serde(default)]
pub relevance: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Listing {
#[serde(default)]
pub ticker: Option<String>,
#[serde(default)]
pub mic: Option<String>,
#[serde(default)]
pub country: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub active: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct EventTag {
pub r#type: EventType,
#[serde(default)]
pub direction: Option<EventDirection>,
#[serde(default)]
pub importance: Option<Importance>,
#[serde(default)]
pub confidence: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub company_ids: Option<Vec<i64>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CompanyRecord {
pub company_id: i64,
pub name: String,
#[serde(default)]
pub country: Option<String>,
#[serde(default)]
pub sector: Option<String>,
#[serde(default)]
pub industry: Option<String>,
#[serde(default, deserialize_with = "null_as_empty")]
pub isins: Vec<String>,
#[serde(default)]
pub primary_listing: Option<Listing>,
#[serde(default, deserialize_with = "null_as_empty")]
pub listings: Vec<Listing>,
#[serde(default)]
pub updated_at: Option<String>,
#[serde(skip)]
raw: Option<Arc<str>>,
#[serde(skip)]
cache: Option<CacheInfo>,
}
impl CompanyRecord {
pub fn updated_at_time(&self) -> Option<SystemTime> {
parse_opt(self.updated_at.as_deref())
}
pub fn raw_json(&self) -> Option<&str> {
self.raw.as_deref()
}
pub fn cache_info(&self) -> Option<&CacheInfo> {
self.cache.as_ref()
}
pub(crate) fn set_cache_info(&mut self, info: CacheInfo) {
self.cache = Some(info);
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct CacheInfo {
pub etag: Option<String>,
pub cache_control: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Source {
pub domain: String,
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub r#type: Option<SourceType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub is_default: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub has_content: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub is_custom: Option<bool>,
#[serde(default)]
pub country: Option<String>,
#[serde(default, deserialize_with = "null_as_empty")]
pub languages: Vec<String>,
#[serde(skip)]
raw: Option<Arc<str>>,
}
impl Source {
pub fn raw_json(&self) -> Option<&str> {
self.raw.as_deref()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Pagination {
#[serde(default)]
pub limit: Option<u32>,
#[serde(default)]
pub returned: Option<u32>,
pub has_more: bool,
#[serde(default)]
pub next_cursor: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SkippedEntry {
pub index: usize,
pub raw: String,
pub reason: String,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ArticlePage {
pub articles: Vec<Article>,
pub pagination: Pagination,
pub skipped: Vec<SkippedEntry>,
}
macro_rules! item_list {
($(#[$meta:meta])* $name:ident, $item:ty) => {
$(#[$meta])*
#[derive(Debug, Clone, PartialEq)]
pub struct $name {
items: Vec<$item>,
skipped: Vec<SkippedEntry>,
}
impl $name {
pub(crate) fn new(items: Vec<$item>, skipped: Vec<SkippedEntry>) -> Self {
Self { items, skipped }
}
pub fn skipped(&self) -> &[SkippedEntry] {
&self.skipped
}
pub fn into_vec(self) -> Vec<$item> {
self.items
}
}
impl std::ops::Deref for $name {
type Target = [$item];
fn deref(&self) -> &[$item] {
&self.items
}
}
impl IntoIterator for $name {
type Item = $item;
type IntoIter = std::vec::IntoIter<$item>;
fn into_iter(self) -> Self::IntoIter {
self.items.into_iter()
}
}
impl<'a> IntoIterator for &'a $name {
type Item = &'a $item;
type IntoIter = std::slice::Iter<'a, $item>;
fn into_iter(self) -> Self::IntoIter {
self.items.iter()
}
}
};
}
item_list!(
CompanyList,
CompanyRecord
);
item_list!(
SourceList,
Source
);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StreamEventKind {
Created,
Updated,
Other,
}
impl StreamEventKind {
pub fn as_str(&self) -> &'static str {
match self {
StreamEventKind::Created => "created",
StreamEventKind::Updated => "updated",
StreamEventKind::Other => "other",
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct StreamEvent {
pub kind: StreamEventKind,
pub event: StreamEventName,
pub data: Option<Article>,
raw: Arc<str>,
}
impl StreamEvent {
pub(crate) fn new(
kind: StreamEventKind,
event: StreamEventName,
data: Option<Article>,
raw: Arc<str>,
) -> Self {
StreamEvent {
kind,
event,
data,
raw,
}
}
pub fn raw_json(&self) -> &str {
&self.raw
}
}
pub(crate) fn decode_value<T: DeserializeOwned>(json: &str, path: &str) -> Result<T, Error> {
let mut de = serde_json::Deserializer::from_str(json);
match serde_path_to_error::deserialize::<_, T>(&mut de) {
Ok(v) => Ok(v),
Err(e) => {
let inner = e.path().to_string();
let full = match (path.is_empty(), inner.as_str()) {
(true, _) => inner.clone(),
(false, ".") => path.to_owned(),
(false, _) => format!("{path}.{inner}"),
};
let message = format!(
"could not decode {}: {}",
if full.is_empty() {
"the response"
} else {
&full
},
e.inner()
);
Err(Error::decode(
message,
Some(full),
Some(json.to_owned()),
Some(Box::new(e.into_inner())),
))
}
}
}
pub(crate) fn decode_article(raw: &RawValue, path: &str) -> Result<Article, Error> {
let mut article: Article = decode_value(raw.get(), path)?;
article.raw = Some(Arc::from(raw.get()));
Ok(article)
}
pub(crate) fn decode_company(raw: &RawValue, path: &str) -> Result<CompanyRecord, Error> {
let mut record: CompanyRecord = decode_value(raw.get(), path)?;
record.raw = Some(Arc::from(raw.get()));
Ok(record)
}
pub(crate) fn decode_source(raw: &RawValue, path: &str) -> Result<Source, Error> {
let mut source: Source = decode_value(raw.get(), path)?;
source.raw = Some(Arc::from(raw.get()));
Ok(source)
}
pub(crate) fn decode_entries<T>(
entries: &[Box<RawValue>],
list: &str,
decode: impl Fn(&RawValue, &str) -> Result<T, Error>,
) -> (Vec<T>, Vec<SkippedEntry>) {
let mut items = Vec::with_capacity(entries.len());
let mut skipped = Vec::new();
for (index, raw) in entries.iter().enumerate() {
match decode(raw, &format!("{list}[{index}]")) {
Ok(item) => items.push(item),
Err(err) => {
tracing::warn!(target: "finlight", list, index, "skipped an entry that could not be decoded: {err}");
skipped.push(SkippedEntry {
index,
raw: raw.get().to_owned(),
reason: err.to_string(),
});
}
}
}
(items, skipped)
}
#[derive(Deserialize)]
struct SearchEnvelope {
articles: Vec<Box<RawValue>>,
pagination: Pagination,
}
#[derive(Deserialize)]
struct ArticleEnvelope {
article: Box<RawValue>,
}
#[derive(Deserialize)]
struct CompaniesEnvelope {
companies: Vec<Box<RawValue>>,
}
#[derive(Deserialize)]
struct CompanyEnvelope {
company: Box<RawValue>,
}
#[derive(Deserialize)]
struct SourcesEnvelope {
sources: Vec<Box<RawValue>>,
}
pub(crate) fn decode_search_page(body: &str) -> Result<ArticlePage, Error> {
let env: SearchEnvelope = decode_value(body, "")?;
let (articles, skipped) = decode_entries(&env.articles, "articles", decode_article);
Ok(ArticlePage {
articles,
pagination: env.pagination,
skipped,
})
}
pub(crate) fn decode_article_envelope(body: &str) -> Result<Article, Error> {
let env: ArticleEnvelope = decode_value(body, "")?;
decode_article(&env.article, "article")
}
pub(crate) fn decode_companies(body: &str) -> Result<CompanyList, Error> {
let env: CompaniesEnvelope = decode_value(body, "")?;
let (items, skipped) = decode_entries(&env.companies, "companies", decode_company);
Ok(CompanyList::new(items, skipped))
}
pub(crate) fn decode_company_envelope(body: &str) -> Result<CompanyRecord, Error> {
let env: CompanyEnvelope = decode_value(body, "")?;
decode_company(&env.company, "company")
}
pub(crate) fn decode_sources(body: &str) -> Result<SourceList, Error> {
let env: SourcesEnvelope = decode_value(body, "")?;
let (items, skipped) = decode_entries(&env.sources, "sources", decode_source);
Ok(SourceList::new(items, skipped))
}