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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// Copyright 2024-2025 Tree xie.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::{
Error, get_hash_key, get_int_conf, get_step_conf_in, get_str_conf,
get_str_slice_conf,
};
use async_trait::async_trait;
use http::StatusCode;
use humantime::parse_duration;
use pingap_config::{PluginCategory, PluginConf};
use pingap_core::{
Ctx, HttpResponse, Plugin, PluginStep, RequestPluginResult, convert_headers,
};
use pingora::proxy::Session;
use std::borrow::Cow;
use std::time::Duration;
use tokio::time::sleep;
use tracing::debug;
type Result<T, E = Error> = std::result::Result<T, E>;
/// MockResponse provides a configurable way to return mock HTTP responses for testing and development.
/// It can match specific paths and introduce artificial delays to simulate various scenarios.
pub struct MockResponse {
/// The URL path to match against incoming requests.
/// - If empty string: matches all paths
/// - If set: must exactly match the request path
/// Example: "/api/users" will only mock requests to that exact path
pub path: String,
/// Determines at which point in the request lifecycle this mock should execute.
/// Only supports two phases:
/// - Request: Early in the cycle, before any upstream processing
/// - ProxyUpstream: Just before the request would be sent to the upstream
/// server, so a cache hit is served normally and only origin-bound
/// requests get the mock
pub plugin_step: PluginStep,
/// The pre-configured HTTP response that will be returned when this mock is triggered.
/// Contains:
/// - status: HTTP status code (defaults to 200 OK)
/// - headers: Optional response headers
/// - body: Response body content
/// This response is constructed once during initialization for better performance
pub resp: HttpResponse,
/// Optional artificial delay before sending the mock response.
/// Useful for:
/// - Testing timeout handling
/// - Simulating slow network conditions
/// - Load testing with controlled response times
/// Format: Standard Duration (e.g., 500ms, 1s, 1m)
pub delay: Option<Duration>,
/// Unique identifier for this plugin instance.
/// - Generated from the plugin configuration
/// - Used internally for plugin management
/// - Not exposed publicly as it's an implementation detail
hash_value: String,
}
impl MockResponse {
/// Creates a new mock response handler from a plugin configuration.
///
/// # Parameters
/// - params: PluginConf containing the following optional fields:
/// - path: String - URL path to match
/// - status: int - HTTP status code (defaults to 200 OK if not specified)
/// - headers: []string - Response headers in "Key: Value" format
/// - data: string - Response body content
/// - delay: string - Human-readable duration (e.g., "500ms", "1s") to delay response
///
/// # Returns
/// Result<MockResponse> - Configured mock handler or error if configuration is invalid
pub fn new(params: &PluginConf) -> Result<Self> {
debug!(params = params.to_string(), "new mock plugin");
// Generate unique hash for this configuration
let hash_value = get_hash_key(params);
let invalid = |message: String| Error::Invalid {
category: PluginCategory::Mock.to_string(),
message,
};
// Extract all configuration parameters
let path = get_str_conf(params, "path"); // Path to match (empty = match all)
let status = get_int_conf(params, "status"); // HTTP status code
let headers = get_str_slice_conf(params, "headers"); // Response headers
let data = get_str_conf(params, "data"); // Response body
// Parse delay duration if specified
// Supports human-readable formats like "500ms", "1s", "1m"
let delay = get_str_conf(params, "delay");
let delay = if !delay.is_empty() {
let d =
parse_duration(&delay).map_err(|e| invalid(e.to_string()))?;
Some(d)
} else {
None
};
// A mock exists to produce exactly what was configured, so a status
// or header that cannot be is an error rather than a 200 without
// headers.
let status = if status == 0 {
StatusCode::OK
} else {
u16::try_from(status)
.ok()
.and_then(|status| StatusCode::from_u16(status).ok())
.ok_or_else(|| invalid(format!("Invalid status({status})")))?
};
let headers = if headers.is_empty() {
None
} else {
Some(
convert_headers(&headers)
.map_err(|e| invalid(format!("invalid headers: {e}")))?,
)
};
let resp = HttpResponse {
status,
headers,
body: data.into(),
..Default::default()
};
Ok(MockResponse {
hash_value,
resp,
plugin_step: get_step_conf_in(
params,
&PluginCategory::Mock.to_string(),
PluginStep::Request,
&[PluginStep::Request, PluginStep::ProxyUpstream],
)?,
path,
delay,
})
}
}
#[async_trait]
impl Plugin for MockResponse {
/// Returns the unique identifier for this plugin instance
#[inline]
fn config_key(&self) -> Cow<'_, str> {
Cow::Borrowed(&self.hash_value)
}
/// Handles incoming requests and returns mock responses when appropriate.
///
/// # Parameters
/// - step: Current execution phase
/// - session: Contains request details including URL path
/// - _ctx: Ctx context (unused in mock plugin)
///
/// # Returns
/// - Ok(None) if request should proceed normally
/// - Ok(Some(HttpResponse)) to return mock response
/// - Err(...) if processing fails
async fn handle_request(
&self,
step: PluginStep,
session: &mut Session,
_ctx: &mut Ctx,
) -> pingora::Result<RequestPluginResult> {
// Only process if we're in the correct execution phase
if step != self.plugin_step {
return Ok(RequestPluginResult::Skipped);
}
// Check if request path matches our configured path (if any)
if !self.path.is_empty() && session.req_header().uri.path() != self.path
{
return Ok(RequestPluginResult::Skipped);
}
// Implement artificial delay if configured
if let Some(d) = self.delay {
sleep(d).await;
}
// Return our pre-configured mock response
Ok(RequestPluginResult::Respond(self.resp.clone()))
}
}
register_plugin!("mock", MockResponse);
#[cfg(test)]
mod tests {
use super::*;
use bytes::Bytes;
use http::StatusCode;
use pingap_config::PluginConf;
use pingap_core::{Ctx, PluginStep};
use pingora::proxy::Session;
use pretty_assertions::assert_eq;
use tokio_test::io::Builder;
#[test]
fn test_mock_params() {
let params = MockResponse::new(
&toml::from_str::<PluginConf>(
r###"
path = "/"
status = 500
headers = [
"Content-Type: application/json"
]
data = "{\"message\":\"Mock Service Unavailable\"}"
"###,
)
.unwrap(),
)
.unwrap();
assert_eq!("/", params.path);
assert_eq!("request", params.plugin_step.to_string());
// `step` used to be parsed and then thrown away.
let params = MockResponse::new(
&toml::from_str::<PluginConf>(
r###"
path = "/"
step = "proxy_upstream"
"###,
)
.unwrap(),
)
.unwrap();
assert_eq!("proxy_upstream", params.plugin_step.to_string());
let result = MockResponse::new(
&toml::from_str::<PluginConf>(
r###"
path = "/"
step = "response"
"###,
)
.unwrap(),
);
assert_eq!(
"Plugin mock invalid, message: Invalid step(response), expect one of: request, proxy_upstream",
result.err().unwrap().to_string()
);
// What cannot be produced is refused, not silently replaced.
for (conf, expect) in [
("status = 99", "Invalid status(99)"),
("status = 1000", "Invalid status(1000)"),
("headers = [\"bad name: 1\"]", "invalid headers"),
] {
let err =
MockResponse::new(&toml::from_str::<PluginConf>(conf).unwrap())
.err()
.unwrap()
.to_string();
assert_eq!(true, err.contains(expect), "{conf}: {err}");
}
}
#[tokio::test]
async fn test_mock_response() {
let params = toml::from_str::<PluginConf>(
r###"
path = "/vicanso/pingap"
status = 500
headers = [
"Content-Type: application/json"
]
data = "{\"message\":\"Mock Service Unavailable\"}"
"###,
)
.unwrap();
let mock = MockResponse::new(¶ms).unwrap();
// match request path, get mock response
let headers = ["Accept-Encoding: gzip"].join("\r\n");
let input_header =
format!("GET /vicanso/pingap?size=1 HTTP/1.1\r\n{headers}\r\n\r\n");
let mock_io = Builder::new().read(input_header.as_bytes()).build();
let mut session = Session::new_h1(Box::new(mock_io));
session.read_request().await.unwrap();
let result = mock
.handle_request(
PluginStep::Request,
&mut session,
&mut Ctx::default(),
)
.await
.unwrap();
let RequestPluginResult::Respond(resp) = result else {
panic!("result is not Respond");
};
assert_eq!(StatusCode::INTERNAL_SERVER_ERROR, resp.status);
assert_eq!(
r###"Some([("content-type", "application/json")])"###,
format!("{:?}", resp.headers)
);
assert_eq!(
Bytes::from_static(b"{\"message\":\"Mock Service Unavailable\"}"),
resp.body
);
// not match request path
let headers = ["Accept-Encoding: gzip"].join("\r\n");
let input_header =
format!("GET /vicanso?size=1 HTTP/1.1\r\n{headers}\r\n\r\n");
let mock_io = Builder::new().read(input_header.as_bytes()).build();
let mut session = Session::new_h1(Box::new(mock_io));
session.read_request().await.unwrap();
let result = mock
.handle_request(
PluginStep::Request,
&mut session,
&mut Ctx::default(),
)
.await
.unwrap();
assert_eq!(true, result == RequestPluginResult::Skipped);
}
}