1use std::collections::VecDeque;
2use std::future::Future;
3use std::pin::Pin;
4use std::sync::Arc;
5use std::task::{Context, Poll};
6
7use futures_core::Stream;
8use serde_json::{Map, Value};
9
10use crate::client::Inner;
11use crate::error::{Error, Result};
12use crate::http::Request;
13use crate::models::{Article, ArticlePage, decode_article_envelope, decode_search_page};
14use crate::params::{GetArticleOptions, SearchAllOptions, SearchParams, encode_component};
15
16#[derive(Debug, Clone, Copy)]
18pub struct Articles<'a> {
19 pub(crate) inner: &'a Arc<Inner>,
20}
21
22impl Articles<'_> {
23 pub async fn search(&self, params: &SearchParams) -> Result<ArticlePage> {
25 let body = Value::Object(params.to_body()?).to_string();
26 fetch_page(self.inner.clone(), body).await
27 }
28
29 pub fn search_all(
35 &self,
36 params: SearchParams,
37 options: SearchAllOptions,
38 ) -> Result<SearchAllResult> {
39 let mut body = params.to_body()?;
40 let cursor = match body.remove("cursor") {
41 Some(Value::String(c)) => Some(c),
42 _ => None,
43 };
44 let max_pages = options
45 .max_pages
46 .unwrap_or(self.inner.transport.config().max_pages);
47 if max_pages == 0 {
48 return Err(Error::validation(
49 "max_pages must be at least 1",
50 Some("max_pages"),
51 ));
52 }
53 Ok(SearchAllResult {
54 inner: self.inner.clone(),
55 frozen: body,
56 cursor,
57 max_pages,
58 pages_fetched: 0,
59 truncated: false,
60 done: false,
61 buffer: VecDeque::new(),
62 mode: None,
63 pending: None,
64 })
65 }
66
67 pub async fn get(&self, id: &str, options: &GetArticleOptions) -> Result<Article> {
70 if id.is_empty() {
71 return Err(Error::validation("id must not be empty", Some("id")));
72 }
73 let mut req = Request::get(format!("/v3/articles/{}", encode_component(id)));
74 if let Some(include) = options.include_query()? {
75 req.query.push(("include", include));
76 }
77 let resp = self.inner.transport.call(&req).await?;
78 decode_article_envelope(&resp.body)
79 }
80
81 pub async fn get_by_link(&self, link: &str, options: &GetArticleOptions) -> Result<Article> {
83 if link.is_empty() {
84 return Err(Error::validation("link must not be empty", Some("link")));
85 }
86 let mut req = Request::get("/v3/articles/by-link");
87 req.query.push(("link", link.to_owned()));
88 if let Some(include) = options.include_query()? {
89 req.query.push(("include", include));
90 }
91 let resp = self.inner.transport.call(&req).await?;
92 decode_article_envelope(&resp.body)
93 }
94}
95
96async fn fetch_page(inner: Arc<Inner>, body: String) -> Result<ArticlePage> {
97 let resp = inner
98 .transport
99 .call(&Request::post("/v3/articles/search", body))
100 .await?;
101 decode_search_page(&resp.body)
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105enum Mode {
106 Articles,
107 Pages,
108}
109
110type PageFuture = Pin<Box<dyn Future<Output = Result<ArticlePage>> + Send>>;
111
112pub struct SearchAllResult {
116 inner: Arc<Inner>,
117 frozen: Map<String, Value>,
118 cursor: Option<String>,
119 max_pages: u32,
120 pages_fetched: u32,
121 truncated: bool,
122 done: bool,
123 buffer: VecDeque<Article>,
124 mode: Option<Mode>,
125 pending: Option<PageFuture>,
126}
127
128impl SearchAllResult {
129 pub async fn next(&mut self) -> Option<Result<Article>> {
131 std::future::poll_fn(|cx| self.poll_article(cx)).await
132 }
133
134 pub async fn next_page(&mut self) -> Option<Result<ArticlePage>> {
136 if let Some(err) = self.lock(Mode::Pages) {
137 return Some(Err(err));
138 }
139 std::future::poll_fn(|cx| self.poll_page(cx)).await
140 }
141
142 pub fn next_cursor(&self) -> Option<&str> {
144 self.cursor.as_deref()
145 }
146
147 pub fn truncated(&self) -> bool {
149 self.truncated
150 }
151
152 pub fn pages_fetched(&self) -> u32 {
154 self.pages_fetched
155 }
156
157 fn lock(&mut self, mode: Mode) -> Option<Error> {
158 match self.mode {
159 None => {
160 self.mode = Some(mode);
161 None
162 }
163 Some(m) if m == mode => None,
164 Some(_) => Some(Error::validation(
165 "a search_all result is iterated once, either by article or by page; call search_all again",
166 None,
167 )),
168 }
169 }
170
171 fn poll_page(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<ArticlePage>>> {
172 if self.done {
173 return Poll::Ready(None);
174 }
175 if self.pending.is_none() {
176 let mut body = self.frozen.clone();
177 if let Some(cursor) = &self.cursor {
178 body.insert("cursor".into(), Value::String(cursor.clone()));
179 }
180 let body = Value::Object(body).to_string();
181 self.pending = Some(Box::pin(fetch_page(self.inner.clone(), body)));
182 }
183 let Some(fut) = self.pending.as_mut() else {
184 return Poll::Ready(None);
185 };
186 let result = match fut.as_mut().poll(cx) {
187 Poll::Pending => return Poll::Pending,
188 Poll::Ready(r) => r,
189 };
190 self.pending = None;
191 match result {
192 Ok(page) => {
193 self.pages_fetched += 1;
194 let next = page.pagination.next_cursor.clone();
195 if !page.pagination.has_more || next.is_none() {
196 self.done = true;
197 self.cursor = None;
198 } else {
199 self.cursor = next;
200 if self.pages_fetched >= self.max_pages {
201 self.done = true;
202 self.truncated = true;
203 tracing::warn!(
204 target: "finlight",
205 max_pages = self.max_pages,
206 "search_all stopped at max_pages; next_cursor() continues the search"
207 );
208 }
209 }
210 Poll::Ready(Some(Ok(page)))
211 }
212 Err(err) => {
213 self.done = true;
214 Poll::Ready(Some(Err(err)))
215 }
216 }
217 }
218
219 fn poll_article(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Article>>> {
220 if let Some(err) = self.lock(Mode::Articles) {
221 return Poll::Ready(Some(Err(err)));
222 }
223 loop {
224 if let Some(article) = self.buffer.pop_front() {
225 return Poll::Ready(Some(Ok(article)));
226 }
227 match self.poll_page(cx) {
228 Poll::Ready(Some(Ok(page))) => self.buffer.extend(page.articles),
229 Poll::Ready(Some(Err(err))) => return Poll::Ready(Some(Err(err))),
230 Poll::Ready(None) => return Poll::Ready(None),
231 Poll::Pending => return Poll::Pending,
232 }
233 }
234 }
235}
236
237impl Stream for SearchAllResult {
238 type Item = Result<Article>;
239
240 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
241 self.get_mut().poll_article(cx)
242 }
243}
244
245impl std::fmt::Debug for SearchAllResult {
246 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
247 f.debug_struct("SearchAllResult")
248 .field("pages_fetched", &self.pages_fetched)
249 .field("max_pages", &self.max_pages)
250 .field("truncated", &self.truncated)
251 .field("done", &self.done)
252 .finish()
253 }
254}