Skip to content
Durable Workflowrust

durable_workflow/
pagination.rs

1//! Namespace-scoped one-page reads and lazy, bounded-memory enumeration.
2//!
3//! Iterators fetch only when `next().await` needs another page. They retain one
4//! page, follow the Server's opaque token, and stop at a null/empty token. An
5//! error is returned to the caller and then the iterator ends. Listing follows
6//! the Server's ordering and consistency contract; it is not a snapshot across
7//! concurrent changes. No new Server query fields or filter grammar are added.
8
9use crate::{path_segment, Client, HistoryEvent, RequestProtocol, Result, Value};
10use serde::{de::DeserializeOwned, Deserialize, Deserializer, Serialize};
11use std::collections::{BTreeMap, HashMap, VecDeque};
12
13/// Invalid page metadata that would otherwise truncate or misdirect a read.
14#[derive(Clone, Debug, thiserror::Error)]
15#[error("pagination failed ({reason}): {message}")]
16#[non_exhaustive]
17pub struct PaginationError {
18    pub reason: String,
19    pub message: String,
20}
21
22fn invalid(reason: &str, message: &str) -> crate::Error {
23    PaginationError {
24        reason: reason.into(),
25        message: message.into(),
26    }
27    .into()
28}
29
30/// Filters accepted by the published `GET /workflows` API.
31#[derive(Clone, Debug, Default)]
32#[non_exhaustive]
33pub struct WorkflowListOptions {
34    pub workflow_type: Option<String>,
35    pub status: Option<String>,
36    pub query: Option<String>,
37    pub page_size: Option<u32>,
38    pub next_page_token: Option<String>,
39}
40
41impl WorkflowListOptions {
42    pub fn new() -> Self {
43        Self::default()
44    }
45    pub fn workflow_type(mut self, value: impl Into<String>) -> Self {
46        self.workflow_type = Some(value.into());
47        self
48    }
49    pub fn status(mut self, value: impl Into<String>) -> Self {
50        self.status = Some(value.into());
51        self
52    }
53    pub fn query(mut self, value: impl Into<String>) -> Self {
54        self.query = Some(value.into());
55        self
56    }
57    /// The Server validates its limit; values are never silently clamped.
58    pub fn page_size(mut self, value: u32) -> Self {
59        self.page_size = Some(value);
60        self
61    }
62    pub fn next_page_token(mut self, value: impl Into<String>) -> Self {
63        self.next_page_token = Some(value.into());
64        self
65    }
66}
67
68/// Options accepted by the published run-history API.
69#[derive(Clone, Debug, Default)]
70#[non_exhaustive]
71pub struct WorkflowHistoryOptions {
72    pub page_size: Option<u32>,
73    pub next_page_token: Option<String>,
74    pub wait_new_event: Option<bool>,
75}
76
77impl WorkflowHistoryOptions {
78    pub fn new() -> Self {
79        Self::default()
80    }
81    pub fn page_size(mut self, value: u32) -> Self {
82        self.page_size = Some(value);
83        self
84    }
85    pub fn next_page_token(mut self, value: impl Into<String>) -> Self {
86        self.next_page_token = Some(value.into());
87        self
88    }
89    /// Wait according to the Server's existing long-poll contract. Iteration
90    /// still terminates when the Server returns no continuation token.
91    pub fn wait_new_event(mut self, value: bool) -> Self {
92        self.wait_new_event = Some(value);
93        self
94    }
95}
96
97/// Typed metadata for one listed run. Unknown response fields remain in `raw`.
98#[derive(Clone, Debug, Deserialize, Serialize)]
99#[non_exhaustive]
100pub struct WorkflowSummary {
101    pub workflow_id: String,
102    pub run_id: String,
103    pub workflow_type: String,
104    pub status: String,
105    pub status_bucket: Option<String>,
106    pub business_key: Option<String>,
107    pub task_queue: Option<String>,
108    pub is_terminal: Option<bool>,
109    pub compatibility: Option<String>,
110    pub started_at: Option<String>,
111    pub closed_at: Option<String>,
112    #[serde(default, deserialize_with = "attribute_map")]
113    pub search_attributes: BTreeMap<String, Value>,
114    #[serde(flatten)]
115    pub raw: HashMap<String, Value>,
116}
117
118// PHP can encode an empty attribute map as []; treat only that empty array
119// (or a legacy null) as empty, retaining real values without type conversion.
120fn attribute_map<'de, D: Deserializer<'de>>(
121    deserializer: D,
122) -> std::result::Result<BTreeMap<String, Value>, D::Error> {
123    match Value::deserialize(deserializer)? {
124        Value::Object(map) => Ok(map.into_iter().collect()),
125        Value::Null => Ok(BTreeMap::new()),
126        Value::Array(values) if values.is_empty() => Ok(BTreeMap::new()),
127        _ => Err(serde::de::Error::custom("expected a search-attribute map")),
128    }
129}
130
131/// Exactly one list response. `next_page_token` indicates more results.
132#[derive(Clone, Debug, Deserialize, Serialize)]
133#[non_exhaustive]
134pub struct WorkflowListPage {
135    pub workflows: Vec<WorkflowSummary>,
136    /// Server-reported number of rows in this page.
137    pub workflow_count: Option<u64>,
138    pub next_page_token: Option<String>,
139    #[serde(flatten)]
140    pub raw: HashMap<String, Value>,
141}
142
143/// Exactly one run-history response, with the existing lossless event model.
144#[derive(Clone, Debug, Deserialize, Serialize)]
145#[non_exhaustive]
146pub struct WorkflowHistoryPage {
147    pub workflow_id: String,
148    pub run_id: String,
149    pub events: Vec<HistoryEvent>,
150    pub next_page_token: Option<String>,
151    #[serde(flatten)]
152    pub raw: HashMap<String, Value>,
153}
154
155impl Client {
156    /// Read one page, preserving the Server's filters, validation and ordering.
157    /// Published Server2.11 defaults to50 rows and accepts1..=200 per page.
158    pub async fn list_workflows(&self, options: WorkflowListOptions) -> Result<WorkflowListPage> {
159        let path = query_path(
160            "/workflows",
161            [
162                ("workflow_type", options.workflow_type),
163                ("status", options.status),
164                ("query", options.query),
165                ("page_size", options.page_size.map(|n| n.to_string())),
166                ("next_page_token", options.next_page_token),
167            ],
168        );
169        read_page(self, &path).await
170    }
171
172    /// Lazily enumerate list results, retaining the original namespace/filters.
173    pub fn iter_workflows(&self, options: WorkflowListOptions) -> WorkflowIterator {
174        let cursor = PageCursor::new(options.next_page_token.clone());
175        WorkflowIterator {
176            client: self.clone(),
177            options,
178            cursor,
179        }
180    }
181
182    /// Read one page of a selected run's history. This is not a complete export.
183    /// Published Server2.11 defaults to100 events and accepts1..=1000 per page.
184    /// Use `export_workflow_history` for the self-contained replay bundle.
185    pub async fn get_workflow_history(
186        &self,
187        workflow_id: &str,
188        run_id: &str,
189        options: WorkflowHistoryOptions,
190    ) -> Result<WorkflowHistoryPage> {
191        let path = query_path(
192            &format!(
193                "/workflows/{}/runs/{}/history",
194                path_segment("workflow_id", workflow_id)?,
195                path_segment("run_id", run_id)?
196            ),
197            [
198                ("page_size", options.page_size.map(|n| n.to_string())),
199                ("next_page_token", options.next_page_token),
200                (
201                    "wait_new_event",
202                    options
203                        .wait_new_event
204                        .map(|wait| if wait { "1".into() } else { "0".into() }),
205                ),
206            ],
207        );
208        let page: WorkflowHistoryPage = read_page(self, &path).await?;
209        if page.workflow_id != workflow_id || page.run_id != run_id {
210            return Err(invalid(
211                "response_identity_mismatch",
212                "history response does not match the requested workflow and run",
213            ));
214        }
215        Ok(page)
216    }
217
218    /// Lazily enumerate one selected run. It does not follow continue-as-new
219    /// into another run or subscribe indefinitely after history is exhausted.
220    pub fn iter_workflow_history(
221        &self,
222        workflow_id: impl Into<String>,
223        run_id: impl Into<String>,
224        options: WorkflowHistoryOptions,
225    ) -> WorkflowHistoryIterator {
226        let cursor = PageCursor::new(options.next_page_token.clone());
227        WorkflowHistoryIterator {
228            client: self.clone(),
229            workflow_id: workflow_id.into(),
230            run_id: run_id.into(),
231            options,
232            cursor,
233        }
234    }
235}
236
237// Only the query is serialized with this static URL; caller paths never pass
238// through a second path parser or get percent-encoded twice here.
239fn query_path<const N: usize>(path: &str, fields: [(&str, Option<String>); N]) -> String {
240    let mut url =
241        reqwest::Url::parse("http://sdk.invalid/").expect("static query serializer origin");
242    {
243        let mut pairs = url.query_pairs_mut();
244        for (key, value) in fields {
245            if let Some(value) = value {
246                pairs.append_pair(key, &value);
247            }
248        }
249    }
250    match url.query().filter(|query| !query.is_empty()) {
251        Some(query) => format!("{path}?{query}"),
252        None => path.into(),
253    }
254}
255
256async fn read_page<T: DeserializeOwned>(client: &Client, path: &str) -> Result<T> {
257    let response: Value = client
258        .request_json(
259            reqwest::Method::GET,
260            path,
261            RequestProtocol::ControlPlane,
262            Option::<&Value>::None,
263        )
264        .await?;
265    if response.get("next_page_token").is_none() {
266        return Err(invalid(
267            "missing_continuation",
268            "page response omitted next_page_token",
269        ));
270    }
271    Ok(serde_json::from_value(response)?)
272}
273
274/// Lazy workflow-list enumeration. An error is propagated once, then it ends.
275pub struct WorkflowIterator {
276    client: Client,
277    options: WorkflowListOptions,
278    cursor: PageCursor<WorkflowSummary>,
279}
280
281impl WorkflowIterator {
282    /// Adapt to the standard async Stream API without eager fetching.
283    pub fn into_stream(self) -> impl futures_util::Stream<Item = Result<WorkflowSummary>> + Send {
284        futures_util::stream::try_unfold(self, |mut iterator| async move {
285            Ok(iterator.next().await?.map(|item| (item, iterator)))
286        })
287    }
288
289    pub async fn next(&mut self) -> Result<Option<WorkflowSummary>> {
290        loop {
291            if let Some(item) = self.cursor.items.pop_front() {
292                return Ok(Some(item));
293            }
294            if self.cursor.done {
295                return Ok(None);
296            }
297            self.cursor.items = VecDeque::new();
298            let mut options = self.options.clone();
299            options.next_page_token = self.cursor.token.clone();
300            match self.client.list_workflows(options).await {
301                Ok(page) => self.cursor.accept(page.workflows, page.next_page_token)?,
302                Err(error) => {
303                    self.cursor.done = true;
304                    return Err(error);
305                }
306            }
307        }
308    }
309}
310
311/// Lazy run-history enumeration. An error is propagated once, then it ends.
312pub struct WorkflowHistoryIterator {
313    client: Client,
314    workflow_id: String,
315    run_id: String,
316    options: WorkflowHistoryOptions,
317    cursor: PageCursor<HistoryEvent>,
318}
319
320impl WorkflowHistoryIterator {
321    /// Adapt to the standard async Stream API without eager fetching.
322    pub fn into_stream(self) -> impl futures_util::Stream<Item = Result<HistoryEvent>> + Send {
323        futures_util::stream::try_unfold(self, |mut iterator| async move {
324            Ok(iterator.next().await?.map(|item| (item, iterator)))
325        })
326    }
327
328    pub async fn next(&mut self) -> Result<Option<HistoryEvent>> {
329        loop {
330            if let Some(item) = self.cursor.items.pop_front() {
331                return Ok(Some(item));
332            }
333            if self.cursor.done {
334                return Ok(None);
335            }
336            self.cursor.items = VecDeque::new();
337            let mut options = self.options.clone();
338            options.next_page_token = self.cursor.token.clone();
339            match self
340                .client
341                .get_workflow_history(&self.workflow_id, &self.run_id, options)
342                .await
343            {
344                Ok(page) => self.cursor.accept(page.events, page.next_page_token)?,
345                Err(error) => {
346                    self.cursor.done = true;
347                    return Err(error);
348                }
349            }
350        }
351    }
352}
353
354struct PageCursor<T> {
355    items: VecDeque<T>,
356    token: Option<String>,
357    done: bool,
358    checkpoint: Option<String>,
359    distance: u64,
360    power: u64,
361}
362
363impl<T> PageCursor<T> {
364    fn new(token: Option<String>) -> Self {
365        Self {
366            items: VecDeque::new(),
367            checkpoint: token.clone(),
368            token,
369            done: false,
370            distance: 0,
371            power: 1,
372        }
373    }
374
375    fn accept(&mut self, items: Vec<T>, next: Option<String>) -> Result<()> {
376        let next = next.filter(|value| !value.is_empty());
377        if let Some(token) = &next {
378            // Brent's cycle detection retains two tokens rather than an
379            // ever-growing set of every page in a long audit/export.
380            if Some(token) == self.token.as_ref() || Some(token) == self.checkpoint.as_ref() {
381                self.done = true;
382                return Err(invalid(
383                    "repeated_page_token",
384                    "Server repeated a continuation token or formed a token cycle",
385                ));
386            }
387            self.distance = self.distance.saturating_add(1);
388            if self.distance >= self.power {
389                self.checkpoint = Some(token.clone());
390                self.power = self.power.saturating_mul(2);
391                self.distance = 0;
392            }
393        }
394        self.done = next.is_none();
395        self.token = next;
396        self.items = items.into();
397        Ok(())
398    }
399}