1use crate::{path_segment, Client, HistoryEvent, RequestProtocol, Result, Value};
10use serde::{de::DeserializeOwned, Deserialize, Deserializer, Serialize};
11use std::collections::{BTreeMap, HashMap, VecDeque};
12
13#[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#[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 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#[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 pub fn wait_new_event(mut self, value: bool) -> Self {
92 self.wait_new_event = Some(value);
93 self
94 }
95}
96
97#[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
118fn 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#[derive(Clone, Debug, Deserialize, Serialize)]
133#[non_exhaustive]
134pub struct WorkflowListPage {
135 pub workflows: Vec<WorkflowSummary>,
136 pub workflow_count: Option<u64>,
138 pub next_page_token: Option<String>,
139 #[serde(flatten)]
140 pub raw: HashMap<String, Value>,
141}
142
143#[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 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 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 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 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
237fn 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
274pub struct WorkflowIterator {
276 client: Client,
277 options: WorkflowListOptions,
278 cursor: PageCursor<WorkflowSummary>,
279}
280
281impl WorkflowIterator {
282 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
311pub 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 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 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}