Skip to main content

finlight/
models.rs

1//! Wire models. Field names follow the wire keys in `snake_case`; serde writes the wire keys back.
2//!
3//! Readers are tolerant: unknown keys are ignored at every level, missing optional keys read as
4//! `None` (lists as empty), and only the required keys (`id`, `link`, `title`, `source.domain`;
5//! `companyId` and `name`; `domain`; event `type`) fail an entry. Timestamps keep the exact
6//! string the server sent; the `*_time()` accessors parse it strictly (RFC 3339) into a
7//! `SystemTime` and give `None` when it is not readable.
8
9use 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/// A news article (REST, streams and webhooks share this shape).
32#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
33#[serde(rename_all = "camelCase")]
34#[non_exhaustive]
35pub struct Article {
36    /// Stable id (22 characters, base64url).
37    pub id: String,
38    /// Article URL.
39    pub link: String,
40    /// Where the article comes from.
41    pub source: ArticleSource,
42    /// Title in the original language.
43    pub title: String,
44    /// Summary; `None` when there is none (never an empty string from the server).
45    #[serde(default)]
46    pub summary: Option<String>,
47    /// ISO 639-1 language.
48    #[serde(default)]
49    pub language: Option<String>,
50    /// Images, at most 3.
51    #[serde(default, deserialize_with = "null_as_empty")]
52    pub media: Vec<Media>,
53    /// Publication time claimed by the source, as sent (legacy data can carry 1970-01-01).
54    #[serde(default)]
55    pub published_at: Option<String>,
56    /// Ingest time, as sent.
57    #[serde(default)]
58    pub first_seen_at: Option<String>,
59    /// The source's revision time, as sent.
60    #[serde(default)]
61    pub revised_at: Option<String>,
62    /// When the enriched article first became available, as sent (always `None` on raw).
63    #[serde(default)]
64    pub available_at: Option<String>,
65    /// Geographic focus of the story (ISO alpha-2).
66    #[serde(default, deserialize_with = "null_as_empty")]
67    pub countries: Vec<String>,
68    /// Categories (open vocabulary).
69    #[serde(default, deserialize_with = "null_as_empty")]
70    pub categories: Vec<String>,
71    /// Full text: absent unless requested with `include` and entitled; `null` when there is none.
72    #[serde(default, skip_serializing_if = "Field::is_absent")]
73    pub content: Field<String>,
74    /// Sentiment: absent unless entitled; `null` when not computed.
75    #[serde(default, skip_serializing_if = "Field::is_absent")]
76    pub sentiment: Field<Sentiment>,
77    /// Tagged companies: `None` when absent (not requested or not entitled); `Some([])` means
78    /// tagged, no company.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub companies: Option<Vec<Company>>,
81    /// Tagged events: `None` when absent; `Some([])` means classified, no event.
82    #[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    /// `true` when the `content` key was in the JSON (`null` included).
90    pub fn content_present(&self) -> bool {
91        self.content.is_present()
92    }
93
94    /// `true` when the `sentiment` key was in the JSON (`null` included).
95    pub fn sentiment_present(&self) -> bool {
96        self.sentiment.is_present()
97    }
98
99    /// `true` when the `companies` key was in the JSON.
100    pub fn companies_present(&self) -> bool {
101        self.companies.is_some()
102    }
103
104    /// `true` when the `events` key was in the JSON.
105    pub fn events_present(&self) -> bool {
106        self.events.is_some()
107    }
108
109    /// `published_at` parsed strictly; `None` when absent or not RFC 3339.
110    pub fn published_at_time(&self) -> Option<SystemTime> {
111        parse_opt(self.published_at.as_deref())
112    }
113
114    /// `first_seen_at` parsed strictly.
115    pub fn first_seen_at_time(&self) -> Option<SystemTime> {
116        parse_opt(self.first_seen_at.as_deref())
117    }
118
119    /// `revised_at` parsed strictly.
120    pub fn revised_at_time(&self) -> Option<SystemTime> {
121        parse_opt(self.revised_at.as_deref())
122    }
123
124    /// `available_at` parsed strictly.
125    pub fn available_at_time(&self) -> Option<SystemTime> {
126        parse_opt(self.available_at.as_deref())
127    }
128
129    /// The article JSON exactly as received, unknown keys included.
130    pub fn raw_json(&self) -> Option<&str> {
131        self.raw.as_deref()
132    }
133}
134
135/// Source of an article.
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "camelCase")]
138#[non_exhaustive]
139pub struct ArticleSource {
140    /// Domain, e.g. `www.reuters.com`; the join key to `sources().list()`.
141    pub domain: String,
142    /// Source type when the article was indexed (open). `None` when the source is not
143    /// classified or the article is older than source types. Can lag `Source::type` after a
144    /// reclassification.
145    #[serde(default)]
146    pub r#type: Option<SourceType>,
147}
148
149/// An image of an article.
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
151#[serde(rename_all = "camelCase")]
152#[non_exhaustive]
153pub struct Media {
154    /// Image URL.
155    #[serde(default)]
156    pub url: Option<String>,
157}
158
159/// Sentiment of an article.
160#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
161#[serde(rename_all = "camelCase")]
162#[non_exhaustive]
163pub struct Sentiment {
164    /// Label (open), `None` when not set.
165    #[serde(default)]
166    pub label: Option<SentimentLabel>,
167    /// Confidence, full precision.
168    #[serde(default)]
169    pub confidence: Option<f64>,
170}
171
172/// A company tagged in an article.
173#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
174#[serde(rename_all = "camelCase")]
175#[non_exhaustive]
176pub struct Company {
177    /// Company id; join key to `companies().get()` and `EventTag::company_ids`.
178    pub company_id: i64,
179    /// Name.
180    pub name: String,
181    /// ISIN.
182    #[serde(default)]
183    pub isin: Option<String>,
184    /// Primary listing; `None` for private companies.
185    #[serde(default)]
186    pub primary_listing: Option<Listing>,
187    /// Tagging confidence.
188    #[serde(default)]
189    pub confidence: Option<f64>,
190    /// Position in the story (open); `None` for articles tagged without roles.
191    #[serde(default)]
192    pub role: Option<CompanyRole>,
193    /// Aboutness, 0 to 1; `None` for articles tagged without roles.
194    #[serde(default)]
195    pub relevance: Option<f64>,
196}
197
198/// A listing of a company.
199#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
200#[serde(rename_all = "camelCase")]
201#[non_exhaustive]
202pub struct Listing {
203    /// Ticker symbol.
204    #[serde(default)]
205    pub ticker: Option<String>,
206    /// Exchange (MIC).
207    #[serde(default)]
208    pub mic: Option<String>,
209    /// Exchange country.
210    #[serde(default)]
211    pub country: Option<String>,
212    /// Whether the listing is active; only set in `CompanyRecord::listings`.
213    #[serde(default, skip_serializing_if = "Option::is_none")]
214    pub active: Option<bool>,
215}
216
217/// An event tagged in an article.
218#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
219#[serde(rename_all = "camelCase")]
220#[non_exhaustive]
221pub struct EventTag {
222    /// Event type (open).
223    pub r#type: EventType,
224    /// Direction (open).
225    #[serde(default)]
226    pub direction: Option<EventDirection>,
227    /// Importance (open, ordered).
228    #[serde(default)]
229    pub importance: Option<Importance>,
230    /// Confidence.
231    #[serde(default)]
232    pub confidence: Option<f64>,
233    /// Ids of the companies the event is about. `None` when absent: it is only sent when the
234    /// `companies` block is in the same payload.
235    #[serde(default, skip_serializing_if = "Option::is_none")]
236    pub company_ids: Option<Vec<i64>>,
237}
238
239/// Company master data from `companies()`.
240#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
241#[serde(rename_all = "camelCase")]
242#[non_exhaustive]
243pub struct CompanyRecord {
244    /// Company id.
245    pub company_id: i64,
246    /// Name.
247    pub name: String,
248    /// Country of domicile.
249    #[serde(default)]
250    pub country: Option<String>,
251    /// Sector.
252    #[serde(default)]
253    pub sector: Option<String>,
254    /// Industry.
255    #[serde(default)]
256    pub industry: Option<String>,
257    /// ISINs.
258    #[serde(default, deserialize_with = "null_as_empty")]
259    pub isins: Vec<String>,
260    /// Primary listing; `None` for private companies.
261    #[serde(default)]
262    pub primary_listing: Option<Listing>,
263    /// One listing per exchange, the primary first.
264    #[serde(default, deserialize_with = "null_as_empty")]
265    pub listings: Vec<Listing>,
266    /// Last update, as sent.
267    #[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    /// `updated_at` parsed strictly.
277    pub fn updated_at_time(&self) -> Option<SystemTime> {
278        parse_opt(self.updated_at.as_deref())
279    }
280
281    /// The JSON exactly as received.
282    pub fn raw_json(&self) -> Option<&str> {
283        self.raw.as_deref()
284    }
285
286    /// ETag data of a record from `companies().get()` or `get_if_none_match()`; `None` for
287    /// other records.
288    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/// ETag data of a record from `companies().get()` or `get_if_none_match()`, for callers who
298/// keep records themselves. The SDK keeps no cache of company records.
299#[derive(Debug, Clone, PartialEq, Eq, Default)]
300#[non_exhaustive]
301pub struct CacheInfo {
302    /// `ETag` header; pass it to `companies().get_if_none_match()` later.
303    pub etag: Option<String>,
304    /// `Cache-Control` header (`max-age` says how long your own copy stays fresh).
305    pub cache_control: Option<String>,
306}
307
308/// A source from `sources().list()`.
309#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
310#[serde(rename_all = "camelCase")]
311#[non_exhaustive]
312pub struct Source {
313    /// Domain.
314    pub domain: String,
315    /// Display name; `None` when the source has none.
316    #[serde(default)]
317    pub name: Option<String>,
318    /// Source type (open); `None` when the source is not classified.
319    #[serde(default)]
320    pub r#type: Option<SourceType>,
321    /// Part of the default pool.
322    #[serde(default, skip_serializing_if = "Option::is_none")]
323    pub is_default: Option<bool>,
324    /// Whether the source has scraped content. `None` means unknown (your plan has no
325    /// `fullArticleAccess`), never "no content".
326    #[serde(default, skip_serializing_if = "Option::is_none")]
327    pub has_content: Option<bool>,
328    /// A custom source granted to your subscription.
329    #[serde(default, skip_serializing_if = "Option::is_none")]
330    pub is_custom: Option<bool>,
331    /// Country.
332    #[serde(default)]
333    pub country: Option<String>,
334    /// Languages, most common first.
335    #[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    /// The JSON exactly as received.
343    pub fn raw_json(&self) -> Option<&str> {
344        self.raw.as_deref()
345    }
346}
347
348/// Pagination of a search page.
349#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
350#[serde(rename_all = "camelCase")]
351#[non_exhaustive]
352pub struct Pagination {
353    /// Page size used.
354    #[serde(default)]
355    pub limit: Option<u32>,
356    /// Articles on this page.
357    #[serde(default)]
358    pub returned: Option<u32>,
359    /// More pages follow.
360    pub has_more: bool,
361    /// Cursor for the next page; `None` at the end.
362    #[serde(default)]
363    pub next_cursor: Option<String>,
364}
365
366/// An entry of a list that could not be decoded. It is left out of the list, logged as a
367/// warning and kept here.
368#[derive(Debug, Clone, PartialEq, Eq)]
369#[non_exhaustive]
370pub struct SkippedEntry {
371    /// Position in the list as received.
372    pub index: usize,
373    /// The entry's JSON as received.
374    pub raw: String,
375    /// Why it was skipped.
376    pub reason: String,
377}
378
379/// One page of `articles().search()`.
380#[derive(Debug, Clone, PartialEq)]
381#[non_exhaustive]
382pub struct ArticlePage {
383    /// Articles of this page.
384    pub articles: Vec<Article>,
385    /// Pagination.
386    pub pagination: Pagination,
387    /// Entries that could not be decoded.
388    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            /// Entries that could not be decoded.
406            pub fn skipped(&self) -> &[SkippedEntry] {
407                &self.skipped
408            }
409
410            /// The entries as a `Vec`.
411            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    /// Result of `companies().search()` and `companies().get_many()`: the records plus `skipped()`.
443    CompanyList,
444    CompanyRecord
445);
446item_list!(
447    /// Result of `sources().list()`: the sources plus `skipped()`.
448    SourceList,
449    Source
450);
451
452/// Kind of a stream element.
453#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
454#[non_exhaustive]
455pub enum StreamEventKind {
456    /// `article.created`.
457    Created,
458    /// `article.updated`.
459    Updated,
460    /// Any other event; `data` is `None` and the frame is reachable through `raw_json()`.
461    Other,
462}
463
464impl StreamEventKind {
465    /// `created`, `updated` or `other`.
466    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/// One element of a stream.
476#[derive(Debug, Clone, PartialEq)]
477#[non_exhaustive]
478pub struct StreamEvent {
479    /// `Created`, `Updated` or `Other`.
480    pub kind: StreamEventKind,
481    /// The wire event name (open).
482    pub event: StreamEventName,
483    /// The article; `None` for `Other`.
484    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    /// The whole frame exactly as received.
504    pub fn raw_json(&self) -> &str {
505        &self.raw
506    }
507}
508
509// ---- decoding -------------------------------------------------------------------------
510
511/// Decodes one JSON value with a path for errors.
512pub(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
560/// Decodes every entry of a list; broken entries are skipped, logged and returned apart.
561pub(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}