Skip to main content

finlight/
client.rs

1use std::fmt;
2use std::sync::Arc;
3
4use crate::articles::Articles;
5use crate::companies::Companies;
6use crate::config::Config;
7use crate::error::Result;
8use crate::http::Transport;
9use crate::params::{RawStreamParams, StreamParams};
10use crate::sources::Sources;
11use crate::stream::{FinlightStream, StreamOptions, start};
12
13pub(crate) struct Inner {
14    pub transport: Transport,
15    pub config: Arc<Config>,
16}
17
18/// Client of the finlight API v3. Cheap to clone; clones share the HTTP client.
19/// Safe to use from many tasks, with many streams at the same time.
20#[derive(Clone)]
21pub struct Client {
22    inner: Arc<Inner>,
23}
24
25impl Client {
26    /// Builds a client. Fails with `Error::Validation` for an empty API key or a bad URL.
27    pub fn new(config: Config) -> Result<Self> {
28        config.validate()?;
29        let config = Arc::new(config);
30        Ok(Client {
31            inner: Arc::new(Inner {
32                transport: Transport::new(config.clone())?,
33                config,
34            }),
35        })
36    }
37
38    /// Article search and lookups.
39    pub fn articles(&self) -> Articles<'_> {
40        Articles { inner: &self.inner }
41    }
42
43    /// Company master data.
44    pub fn companies(&self) -> Companies<'_> {
45        Companies { inner: &self.inner }
46    }
47
48    /// Source catalog.
49    pub fn sources(&self) -> Sources<'_> {
50        Sources { inner: &self.inner }
51    }
52
53    /// Opens the enriched stream. The parameters are checked here; the connection opens in the
54    /// background, and every outcome arrives through the returned stream. Needs a tokio runtime.
55    pub async fn stream(
56        &self,
57        params: StreamParams,
58        options: StreamOptions,
59    ) -> Result<FinlightStream> {
60        let frame = params.to_frame()?;
61        Ok(start(self.inner.config.clone(), false, frame, options))
62    }
63
64    /// Opens the raw stream (article skeletons only, before enrichment).
65    pub async fn raw_stream(
66        &self,
67        params: RawStreamParams,
68        options: StreamOptions,
69    ) -> Result<FinlightStream> {
70        Ok(start(
71            self.inner.config.clone(),
72            true,
73            params.to_frame(),
74            options,
75        ))
76    }
77}
78
79impl fmt::Debug for Client {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        f.debug_struct("Client")
82            .field("config", &self.inner.config)
83            .finish()
84    }
85}
86
87impl fmt::Debug for Inner {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        f.debug_struct("Inner")
90            .field("config", &self.config)
91            .finish()
92    }
93}