1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
//! Pagination strategies for REST APIs.
pub mod cursor;
pub mod link_header;
pub mod next_link_body;
pub mod offset;
pub mod page;
use faucet_core::FaucetError;
use reqwest::header::HeaderMap;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
/// Supported pagination strategies.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type")]
pub enum PaginationStyle {
None,
Cursor {
next_token_path: String,
param_name: String,
},
LinkHeader,
/// The full URL of the next page is embedded in the response body.
/// `next_link_path` is a JSONPath expression pointing to that URL field
/// (e.g. `"$.next_link"`). Pagination stops when the field is absent,
/// null, or an empty string.
NextLinkInBody {
next_link_path: String,
},
PageNumber {
param_name: String,
start_page: usize,
page_size: Option<usize>,
page_size_param: Option<String>,
},
Offset {
offset_param: String,
limit_param: String,
limit: usize,
total_path: Option<String>,
},
}
/// Internal state tracked across pages.
#[derive(Debug, Default)]
pub struct PaginationState {
pub page: usize,
pub next_token: Option<String>,
pub offset: usize,
pub next_link: Option<String>,
/// The previous page's token/link, used for loop detection.
/// If `advance()` produces the same value twice in a row, pagination
/// is stuck and we stop rather than looping forever.
#[doc(hidden)]
pub previous_token: Option<String>,
/// Fingerprint of the previous page's body, used by `PageNumber` loop
/// detection: APIs that clamp an out-of-range page to the last page and
/// re-return it (non-empty) would otherwise loop until `max_pages`.
#[doc(hidden)]
pub previous_page_fingerprint: Option<u64>,
}
/// Cheap, stable fingerprint of a response body for content-stagnation
/// loop detection.
fn body_fingerprint(body: &Value) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
body.to_string().hash(&mut h);
h.finish()
}
impl PaginationStyle {
pub fn apply_params(&self, params: &mut HashMap<String, String>, state: &PaginationState) {
match self {
PaginationStyle::None => {}
PaginationStyle::Cursor { param_name, .. } => {
cursor::apply_params(params, param_name, &state.next_token);
}
PaginationStyle::LinkHeader => {}
PaginationStyle::NextLinkInBody { .. } => {}
PaginationStyle::PageNumber {
param_name,
start_page,
page_size,
page_size_param,
} => {
page::apply_params(
params,
param_name,
*start_page,
state.page,
*page_size,
page_size_param.as_deref(),
);
}
PaginationStyle::Offset {
offset_param,
limit_param,
limit,
..
} => {
offset::apply_params(params, offset_param, limit_param, state.offset, *limit);
}
}
}
/// Advance pagination state based on the response body and headers.
/// Returns `true` if there is a next page to fetch.
///
/// Includes **loop detection**: if a cursor or next-link value is identical
/// to the previous page's value, pagination stops with a warning instead of
/// looping forever.
pub fn advance(
&self,
body: &Value,
headers: &HeaderMap,
state: &mut PaginationState,
record_count: usize,
) -> Result<bool, FaucetError> {
match self {
PaginationStyle::None => Ok(false),
PaginationStyle::Cursor {
next_token_path, ..
} => {
let has_next = cursor::advance(body, next_token_path, &mut state.next_token)?;
if has_next {
if state.next_token == state.previous_token {
tracing::warn!(
"pagination loop detected: cursor {:?} repeated — stopping",
state.next_token
);
return Ok(false);
}
state.previous_token = state.next_token.clone();
}
Ok(has_next)
}
PaginationStyle::LinkHeader => match link_header::extract_next_link(headers) {
Some(link) => {
if Some(&link) == state.previous_token.as_ref() {
tracing::warn!(
"pagination loop detected: link {link:?} repeated — stopping"
);
state.next_link = None;
return Ok(false);
}
state.previous_token = Some(link.clone());
state.next_link = Some(link);
Ok(true)
}
None => {
state.next_link = None;
Ok(false)
}
},
PaginationStyle::NextLinkInBody { next_link_path } => {
let has_next = next_link_body::advance(body, next_link_path, &mut state.next_link)?;
if has_next {
if state.next_link == state.previous_token {
tracing::warn!(
"pagination loop detected: next_link {:?} repeated — stopping",
state.next_link
);
return Ok(false);
}
state.previous_token = state.next_link.clone();
}
Ok(has_next)
}
PaginationStyle::PageNumber { .. } => {
state.page += 1;
if record_count == 0 {
return Ok(false);
}
// Content-stagnation guard: some APIs clamp an out-of-range
// page to the last page and return it again (non-empty), which
// would loop until `max_pages` and duplicate records. Stop if
// this page's body is identical to the previous one (#78/#15).
let fp = body_fingerprint(body);
if state.previous_page_fingerprint == Some(fp) {
tracing::warn!(
"pagination loop detected: PageNumber returned an identical page — stopping"
);
return Ok(false);
}
state.previous_page_fingerprint = Some(fp);
Ok(true)
}
PaginationStyle::Offset {
limit, total_path, ..
} => offset::advance(
body,
&mut state.offset,
record_count,
*limit,
total_path.as_deref(),
),
}
}
}