1use std::sync::Arc;
10use std::time::SystemTime;
11
12use serde::de::DeserializeOwned;
13use serde::{Deserialize, Deserializer, Serialize};
14use serde_json::value::RawValue;
15
16use crate::error::Error;
17use crate::field::Field;
18use crate::time::parse_opt;
19use crate::vocab::{
20 CompanyRole, EventDirection, EventType, Importance, SentimentLabel, SourceType, StreamEventName,
21};
22
23fn null_as_empty<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
24where
25 D: Deserializer<'de>,
26 T: Deserialize<'de>,
27{
28 Ok(Option::<Vec<T>>::deserialize(deserializer)?.unwrap_or_default())
29}
30
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
33#[serde(rename_all = "camelCase")]
34#[non_exhaustive]
35pub struct Article {
36 pub id: String,
38 pub link: String,
40 pub source: ArticleSource,
42 pub title: String,
44 #[serde(default)]
46 pub summary: Option<String>,
47 #[serde(default)]
49 pub language: Option<String>,
50 #[serde(default, deserialize_with = "null_as_empty")]
52 pub media: Vec<Media>,
53 #[serde(default)]
55 pub published_at: Option<String>,
56 #[serde(default)]
58 pub first_seen_at: Option<String>,
59 #[serde(default)]
61 pub revised_at: Option<String>,
62 #[serde(default)]
64 pub available_at: Option<String>,
65 #[serde(default, deserialize_with = "null_as_empty")]
67 pub countries: Vec<String>,
68 #[serde(default, deserialize_with = "null_as_empty")]
70 pub categories: Vec<String>,
71 #[serde(default, skip_serializing_if = "Field::is_absent")]
73 pub content: Field<String>,
74 #[serde(default, skip_serializing_if = "Field::is_absent")]
76 pub sentiment: Field<Sentiment>,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub companies: Option<Vec<Company>>,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub events: Option<Vec<EventTag>>,
84 #[serde(skip)]
85 raw: Option<Arc<str>>,
86}
87
88impl Article {
89 pub fn content_present(&self) -> bool {
91 self.content.is_present()
92 }
93
94 pub fn sentiment_present(&self) -> bool {
96 self.sentiment.is_present()
97 }
98
99 pub fn companies_present(&self) -> bool {
101 self.companies.is_some()
102 }
103
104 pub fn events_present(&self) -> bool {
106 self.events.is_some()
107 }
108
109 pub fn published_at_time(&self) -> Option<SystemTime> {
111 parse_opt(self.published_at.as_deref())
112 }
113
114 pub fn first_seen_at_time(&self) -> Option<SystemTime> {
116 parse_opt(self.first_seen_at.as_deref())
117 }
118
119 pub fn revised_at_time(&self) -> Option<SystemTime> {
121 parse_opt(self.revised_at.as_deref())
122 }
123
124 pub fn available_at_time(&self) -> Option<SystemTime> {
126 parse_opt(self.available_at.as_deref())
127 }
128
129 pub fn raw_json(&self) -> Option<&str> {
131 self.raw.as_deref()
132 }
133}
134
135#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "camelCase")]
138#[non_exhaustive]
139pub struct ArticleSource {
140 pub domain: String,
142 #[serde(default)]
146 pub r#type: Option<SourceType>,
147}
148
149#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
151#[serde(rename_all = "camelCase")]
152#[non_exhaustive]
153pub struct Media {
154 #[serde(default)]
156 pub url: Option<String>,
157}
158
159#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
161#[serde(rename_all = "camelCase")]
162#[non_exhaustive]
163pub struct Sentiment {
164 #[serde(default)]
166 pub label: Option<SentimentLabel>,
167 #[serde(default)]
169 pub confidence: Option<f64>,
170}
171
172#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
174#[serde(rename_all = "camelCase")]
175#[non_exhaustive]
176pub struct Company {
177 pub company_id: i64,
179 pub name: String,
181 #[serde(default)]
183 pub isin: Option<String>,
184 #[serde(default)]
186 pub primary_listing: Option<Listing>,
187 #[serde(default)]
189 pub confidence: Option<f64>,
190 #[serde(default)]
192 pub role: Option<CompanyRole>,
193 #[serde(default)]
195 pub relevance: Option<f64>,
196}
197
198#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
200#[serde(rename_all = "camelCase")]
201#[non_exhaustive]
202pub struct Listing {
203 #[serde(default)]
205 pub ticker: Option<String>,
206 #[serde(default)]
208 pub mic: Option<String>,
209 #[serde(default)]
211 pub country: Option<String>,
212 #[serde(default, skip_serializing_if = "Option::is_none")]
214 pub active: Option<bool>,
215}
216
217#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
219#[serde(rename_all = "camelCase")]
220#[non_exhaustive]
221pub struct EventTag {
222 pub r#type: EventType,
224 #[serde(default)]
226 pub direction: Option<EventDirection>,
227 #[serde(default)]
229 pub importance: Option<Importance>,
230 #[serde(default)]
232 pub confidence: Option<f64>,
233 #[serde(default, skip_serializing_if = "Option::is_none")]
236 pub company_ids: Option<Vec<i64>>,
237}
238
239#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
241#[serde(rename_all = "camelCase")]
242#[non_exhaustive]
243pub struct CompanyRecord {
244 pub company_id: i64,
246 pub name: String,
248 #[serde(default)]
250 pub country: Option<String>,
251 #[serde(default)]
253 pub sector: Option<String>,
254 #[serde(default)]
256 pub industry: Option<String>,
257 #[serde(default, deserialize_with = "null_as_empty")]
259 pub isins: Vec<String>,
260 #[serde(default)]
262 pub primary_listing: Option<Listing>,
263 #[serde(default, deserialize_with = "null_as_empty")]
265 pub listings: Vec<Listing>,
266 #[serde(default)]
268 pub updated_at: Option<String>,
269 #[serde(skip)]
270 raw: Option<Arc<str>>,
271 #[serde(skip)]
272 cache: Option<CacheInfo>,
273}
274
275impl CompanyRecord {
276 pub fn updated_at_time(&self) -> Option<SystemTime> {
278 parse_opt(self.updated_at.as_deref())
279 }
280
281 pub fn raw_json(&self) -> Option<&str> {
283 self.raw.as_deref()
284 }
285
286 pub fn cache_info(&self) -> Option<&CacheInfo> {
289 self.cache.as_ref()
290 }
291
292 pub(crate) fn set_cache_info(&mut self, info: CacheInfo) {
293 self.cache = Some(info);
294 }
295}
296
297#[derive(Debug, Clone, PartialEq, Eq, Default)]
300#[non_exhaustive]
301pub struct CacheInfo {
302 pub etag: Option<String>,
304 pub cache_control: Option<String>,
306}
307
308#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
310#[serde(rename_all = "camelCase")]
311#[non_exhaustive]
312pub struct Source {
313 pub domain: String,
315 #[serde(default)]
317 pub name: Option<String>,
318 #[serde(default)]
320 pub r#type: Option<SourceType>,
321 #[serde(default, skip_serializing_if = "Option::is_none")]
323 pub is_default: Option<bool>,
324 #[serde(default, skip_serializing_if = "Option::is_none")]
327 pub has_content: Option<bool>,
328 #[serde(default, skip_serializing_if = "Option::is_none")]
330 pub is_custom: Option<bool>,
331 #[serde(default)]
333 pub country: Option<String>,
334 #[serde(default, deserialize_with = "null_as_empty")]
336 pub languages: Vec<String>,
337 #[serde(skip)]
338 raw: Option<Arc<str>>,
339}
340
341impl Source {
342 pub fn raw_json(&self) -> Option<&str> {
344 self.raw.as_deref()
345 }
346}
347
348#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
350#[serde(rename_all = "camelCase")]
351#[non_exhaustive]
352pub struct Pagination {
353 #[serde(default)]
355 pub limit: Option<u32>,
356 #[serde(default)]
358 pub returned: Option<u32>,
359 pub has_more: bool,
361 #[serde(default)]
363 pub next_cursor: Option<String>,
364}
365
366#[derive(Debug, Clone, PartialEq, Eq)]
369#[non_exhaustive]
370pub struct SkippedEntry {
371 pub index: usize,
373 pub raw: String,
375 pub reason: String,
377}
378
379#[derive(Debug, Clone, PartialEq)]
381#[non_exhaustive]
382pub struct ArticlePage {
383 pub articles: Vec<Article>,
385 pub pagination: Pagination,
387 pub skipped: Vec<SkippedEntry>,
389}
390
391macro_rules! item_list {
392 ($(#[$meta:meta])* $name:ident, $item:ty) => {
393 $(#[$meta])*
394 #[derive(Debug, Clone, PartialEq)]
395 pub struct $name {
396 items: Vec<$item>,
397 skipped: Vec<SkippedEntry>,
398 }
399
400 impl $name {
401 pub(crate) fn new(items: Vec<$item>, skipped: Vec<SkippedEntry>) -> Self {
402 Self { items, skipped }
403 }
404
405 pub fn skipped(&self) -> &[SkippedEntry] {
407 &self.skipped
408 }
409
410 pub fn into_vec(self) -> Vec<$item> {
412 self.items
413 }
414 }
415
416 impl std::ops::Deref for $name {
417 type Target = [$item];
418 fn deref(&self) -> &[$item] {
419 &self.items
420 }
421 }
422
423 impl IntoIterator for $name {
424 type Item = $item;
425 type IntoIter = std::vec::IntoIter<$item>;
426 fn into_iter(self) -> Self::IntoIter {
427 self.items.into_iter()
428 }
429 }
430
431 impl<'a> IntoIterator for &'a $name {
432 type Item = &'a $item;
433 type IntoIter = std::slice::Iter<'a, $item>;
434 fn into_iter(self) -> Self::IntoIter {
435 self.items.iter()
436 }
437 }
438 };
439}
440
441item_list!(
442 CompanyList,
444 CompanyRecord
445);
446item_list!(
447 SourceList,
449 Source
450);
451
452#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
454#[non_exhaustive]
455pub enum StreamEventKind {
456 Created,
458 Updated,
460 Other,
462}
463
464impl StreamEventKind {
465 pub fn as_str(&self) -> &'static str {
467 match self {
468 StreamEventKind::Created => "created",
469 StreamEventKind::Updated => "updated",
470 StreamEventKind::Other => "other",
471 }
472 }
473}
474
475#[derive(Debug, Clone, PartialEq)]
477#[non_exhaustive]
478pub struct StreamEvent {
479 pub kind: StreamEventKind,
481 pub event: StreamEventName,
483 pub data: Option<Article>,
485 raw: Arc<str>,
486}
487
488impl StreamEvent {
489 pub(crate) fn new(
490 kind: StreamEventKind,
491 event: StreamEventName,
492 data: Option<Article>,
493 raw: Arc<str>,
494 ) -> Self {
495 StreamEvent {
496 kind,
497 event,
498 data,
499 raw,
500 }
501 }
502
503 pub fn raw_json(&self) -> &str {
505 &self.raw
506 }
507}
508
509pub(crate) fn decode_value<T: DeserializeOwned>(json: &str, path: &str) -> Result<T, Error> {
513 let mut de = serde_json::Deserializer::from_str(json);
514 match serde_path_to_error::deserialize::<_, T>(&mut de) {
515 Ok(v) => Ok(v),
516 Err(e) => {
517 let inner = e.path().to_string();
518 let full = match (path.is_empty(), inner.as_str()) {
519 (true, _) => inner.clone(),
520 (false, ".") => path.to_owned(),
521 (false, _) => format!("{path}.{inner}"),
522 };
523 let message = format!(
524 "could not decode {}: {}",
525 if full.is_empty() {
526 "the response"
527 } else {
528 &full
529 },
530 e.inner()
531 );
532 Err(Error::decode(
533 message,
534 Some(full),
535 Some(json.to_owned()),
536 Some(Box::new(e.into_inner())),
537 ))
538 }
539 }
540}
541
542pub(crate) fn decode_article(raw: &RawValue, path: &str) -> Result<Article, Error> {
543 let mut article: Article = decode_value(raw.get(), path)?;
544 article.raw = Some(Arc::from(raw.get()));
545 Ok(article)
546}
547
548pub(crate) fn decode_company(raw: &RawValue, path: &str) -> Result<CompanyRecord, Error> {
549 let mut record: CompanyRecord = decode_value(raw.get(), path)?;
550 record.raw = Some(Arc::from(raw.get()));
551 Ok(record)
552}
553
554pub(crate) fn decode_source(raw: &RawValue, path: &str) -> Result<Source, Error> {
555 let mut source: Source = decode_value(raw.get(), path)?;
556 source.raw = Some(Arc::from(raw.get()));
557 Ok(source)
558}
559
560pub(crate) fn decode_entries<T>(
562 entries: &[Box<RawValue>],
563 list: &str,
564 decode: impl Fn(&RawValue, &str) -> Result<T, Error>,
565) -> (Vec<T>, Vec<SkippedEntry>) {
566 let mut items = Vec::with_capacity(entries.len());
567 let mut skipped = Vec::new();
568 for (index, raw) in entries.iter().enumerate() {
569 match decode(raw, &format!("{list}[{index}]")) {
570 Ok(item) => items.push(item),
571 Err(err) => {
572 tracing::warn!(target: "finlight", list, index, "skipped an entry that could not be decoded: {err}");
573 skipped.push(SkippedEntry {
574 index,
575 raw: raw.get().to_owned(),
576 reason: err.to_string(),
577 });
578 }
579 }
580 }
581 (items, skipped)
582}
583
584#[derive(Deserialize)]
585struct SearchEnvelope {
586 articles: Vec<Box<RawValue>>,
587 pagination: Pagination,
588}
589
590#[derive(Deserialize)]
591struct ArticleEnvelope {
592 article: Box<RawValue>,
593}
594
595#[derive(Deserialize)]
596struct CompaniesEnvelope {
597 companies: Vec<Box<RawValue>>,
598}
599
600#[derive(Deserialize)]
601struct CompanyEnvelope {
602 company: Box<RawValue>,
603}
604
605#[derive(Deserialize)]
606struct SourcesEnvelope {
607 sources: Vec<Box<RawValue>>,
608}
609
610pub(crate) fn decode_search_page(body: &str) -> Result<ArticlePage, Error> {
611 let env: SearchEnvelope = decode_value(body, "")?;
612 let (articles, skipped) = decode_entries(&env.articles, "articles", decode_article);
613 Ok(ArticlePage {
614 articles,
615 pagination: env.pagination,
616 skipped,
617 })
618}
619
620pub(crate) fn decode_article_envelope(body: &str) -> Result<Article, Error> {
621 let env: ArticleEnvelope = decode_value(body, "")?;
622 decode_article(&env.article, "article")
623}
624
625pub(crate) fn decode_companies(body: &str) -> Result<CompanyList, Error> {
626 let env: CompaniesEnvelope = decode_value(body, "")?;
627 let (items, skipped) = decode_entries(&env.companies, "companies", decode_company);
628 Ok(CompanyList::new(items, skipped))
629}
630
631pub(crate) fn decode_company_envelope(body: &str) -> Result<CompanyRecord, Error> {
632 let env: CompanyEnvelope = decode_value(body, "")?;
633 decode_company(&env.company, "company")
634}
635
636pub(crate) fn decode_sources(body: &str) -> Result<SourceList, Error> {
637 let env: SourcesEnvelope = decode_value(body, "")?;
638 let (items, skipped) = decode_entries(&env.sources, "sources", decode_source);
639 Ok(SourceList::new(items, skipped))
640}