playwright_rs/protocol/request.rs
1// Request protocol object
2//
3// Represents an HTTP request. Created during navigation operations.
4// In Playwright's architecture, navigation creates a Request which receives a Response.
5
6use crate::error::Result;
7use crate::protocol::response::HeaderEntry;
8use crate::server::channel_owner::{ChannelOwner, ChannelOwnerImpl, ParentOrConnection};
9use crate::server::connection::ConnectionExt;
10use serde::de::DeserializeOwned;
11use serde_json::Value;
12use std::any::Any;
13use std::collections::HashMap;
14use std::sync::{Arc, Mutex};
15
16/// Request represents an HTTP request during navigation.
17///
18/// Request objects are created by the server during navigation operations.
19/// They are parents to Response objects.
20///
21/// See: <https://playwright.dev/docs/api/class-request>
22#[derive(Clone)]
23pub struct Request {
24 base: ChannelOwnerImpl,
25 /// Failure text set when a `requestFailed` event is received for this request.
26 failure_text: Arc<Mutex<Option<String>>>,
27 /// Timing data set when the associated `requestFinished` event fires.
28 /// The value is the raw JSON timing object from the Response initializer.
29 timing: Arc<Mutex<Option<Value>>>,
30 /// Eagerly resolved Frame back-reference from the initializer's `frame.guid`.
31 frame: Arc<Mutex<Option<crate::protocol::Frame>>>,
32 /// The request that redirected to this one (from initializer `redirectedFrom`).
33 redirected_from: Arc<Mutex<Option<Request>>>,
34 /// The request that this one redirected to (set by the later request's construction).
35 redirected_to: Arc<Mutex<Option<Request>>>,
36 /// The Response that has been received for this request, if any.
37 /// Set when the `ResponseObject` for this request is constructed.
38 response: Arc<Mutex<Option<crate::protocol::page::Response>>>,
39}
40
41impl Request {
42 /// Creates a new Request from protocol initialization
43 ///
44 /// This is called by the object factory when the server sends a `__create__` message
45 /// for a Request object.
46 pub fn new(
47 parent: Arc<dyn ChannelOwner>,
48 type_name: String,
49 guid: Arc<str>,
50 initializer: Value,
51 ) -> Result<Self> {
52 let base = ChannelOwnerImpl::new(
53 ParentOrConnection::Parent(parent),
54 type_name,
55 guid,
56 initializer,
57 );
58
59 Ok(Self {
60 base,
61 failure_text: Arc::new(Mutex::new(None)),
62 timing: Arc::new(Mutex::new(None)),
63 frame: Arc::new(Mutex::new(None)),
64 redirected_from: Arc::new(Mutex::new(None)),
65 redirected_to: Arc::new(Mutex::new(None)),
66 response: Arc::new(Mutex::new(None)),
67 })
68 }
69
70 /// Returns the [`Frame`](crate::protocol::Frame) that initiated this request.
71 ///
72 /// The frame is resolved from the `frame` GUID in the protocol initializer data.
73 ///
74 /// See: <https://playwright.dev/docs/api/class-request#request-frame>
75 pub fn frame(&self) -> Option<crate::protocol::Frame> {
76 self.frame.lock().unwrap().clone()
77 }
78
79 /// Returns the request that redirected to this one, or `None`.
80 ///
81 /// When the server responds with a redirect, Playwright creates a new Request
82 /// for the redirect target. The new request's `redirected_from` points back to
83 /// the original request.
84 ///
85 /// See: <https://playwright.dev/docs/api/class-request#request-redirected-from>
86 pub fn redirected_from(&self) -> Option<Request> {
87 self.redirected_from.lock().unwrap().clone()
88 }
89
90 /// Returns the request that this one redirected to, or `None`.
91 ///
92 /// This is the inverse of `redirected_from()`: if request A redirected to
93 /// request B, then `A.redirected_to()` returns B.
94 ///
95 /// See: <https://playwright.dev/docs/api/class-request#request-redirected-to>
96 pub fn redirected_to(&self) -> Option<Request> {
97 self.redirected_to.lock().unwrap().clone()
98 }
99
100 /// Sets the redirect-from back-pointer. Called by the object factory
101 /// when a new Request has `redirectedFrom` in its initializer.
102 pub(crate) fn set_redirected_from(&self, from: Request) {
103 *self.redirected_from.lock().unwrap() = Some(from);
104 }
105
106 /// Sets the redirect-to forward pointer. Called as a side-effect when
107 /// the redirect target request is constructed.
108 pub(crate) fn set_redirected_to(&self, to: Request) {
109 *self.redirected_to.lock().unwrap() = Some(to);
110 }
111
112 /// Returns the [`Response`](crate::protocol::page::Response) if it has already been received,
113 /// or `None` if the response has not yet arrived.
114 ///
115 /// This method returns immediately without waiting. Use [`response()`](Self::response) if you
116 /// need to wait for the response to arrive.
117 ///
118 /// See: <https://playwright.dev/docs/api/class-request#request-existing-response>
119 pub fn existing_response(&self) -> Option<crate::protocol::page::Response> {
120 self.response.lock().unwrap().clone()
121 }
122
123 /// Sets the cached response. Called by the object factory when the `ResponseObject`
124 /// for this request is constructed.
125 pub(crate) fn set_response(&self, response: crate::protocol::page::Response) {
126 *self.response.lock().unwrap() = Some(response);
127 }
128
129 /// Returns the [`Response`](crate::protocol::response::ResponseObject) for this request.
130 ///
131 /// Sends a `"response"` RPC call to the Playwright server.
132 /// Returns `None` if the request has not received a response (e.g., it failed).
133 ///
134 /// See: <https://playwright.dev/docs/api/class-request#request-response>
135 pub async fn response(&self) -> Result<Option<crate::protocol::page::Response>> {
136 use serde::Deserialize;
137
138 #[derive(Deserialize)]
139 struct GuidRef {
140 guid: String,
141 }
142
143 #[derive(Deserialize)]
144 struct ResponseResult {
145 response: Option<GuidRef>,
146 }
147
148 let result: ResponseResult = self
149 .channel()
150 .send("response", serde_json::json!({}))
151 .await?;
152
153 let guid = match result.response {
154 Some(r) => r.guid,
155 None => return Ok(None),
156 };
157
158 let connection = self.connection();
159 // get_typed validates the type; get_object provides the Arc<dyn ChannelOwner>
160 // needed by Response::new for back-reference support
161 let response_obj: crate::protocol::ResponseObject = connection
162 .get_typed::<crate::protocol::ResponseObject>(&guid)
163 .await
164 .map_err(|e| {
165 crate::error::Error::ProtocolError(format!(
166 "Failed to get Response object {}: {}",
167 guid, e
168 ))
169 })?;
170 let response_arc = connection.get_object(&guid).await.map_err(|e| {
171 crate::error::Error::ProtocolError(format!(
172 "Failed to get Response object {}: {}",
173 guid, e
174 ))
175 })?;
176
177 let initializer = response_obj.initializer();
178 let status = initializer
179 .get("status")
180 .and_then(|v| v.as_u64())
181 .unwrap_or(0) as u16;
182 let headers: std::collections::HashMap<String, String> = initializer
183 .get("headers")
184 .and_then(|v| v.as_array())
185 .map(|arr| {
186 arr.iter()
187 .filter_map(|h| {
188 let name = h.get("name")?.as_str()?;
189 let value = h.get("value")?.as_str()?;
190 Some((name.to_string(), value.to_string()))
191 })
192 .collect()
193 })
194 .unwrap_or_default();
195
196 Ok(Some(crate::protocol::page::Response::new(
197 initializer
198 .get("url")
199 .and_then(|v| v.as_str())
200 .unwrap_or("")
201 .to_string(),
202 status,
203 initializer
204 .get("statusText")
205 .and_then(|v| v.as_str())
206 .unwrap_or("")
207 .to_string(),
208 headers,
209 Some(response_arc),
210 )))
211 }
212
213 /// Returns resource size information for this request.
214 ///
215 /// Internally fetches the associated Response (via RPC) and calls `sizes()`
216 /// on the response's channel.
217 ///
218 /// See: <https://playwright.dev/docs/api/class-request#request-sizes>
219 pub async fn sizes(&self) -> Result<crate::protocol::response::RequestSizes> {
220 let response = self.response().await?;
221 let response = response.ok_or_else(|| {
222 crate::error::Error::ProtocolError(
223 "Unable to fetch sizes for failed request".to_string(),
224 )
225 })?;
226
227 let response_obj = response.response_object().map_err(|_| {
228 crate::error::Error::ProtocolError(
229 "Response has no backing protocol object for sizes()".to_string(),
230 )
231 })?;
232
233 response_obj.sizes().await
234 }
235
236 /// Sets the eagerly-resolved Frame back-reference.
237 ///
238 /// Called by the object factory after the Request is created and the Frame
239 /// has been looked up from the connection registry.
240 pub(crate) fn set_frame(&self, frame: crate::protocol::Frame) {
241 *self.frame.lock().unwrap() = Some(frame);
242 }
243
244 /// Returns the URL of the request.
245 ///
246 /// See: <https://playwright.dev/docs/api/class-request#request-url>
247 pub fn url(&self) -> &str {
248 self.initializer()
249 .get("url")
250 .and_then(|v| v.as_str())
251 .unwrap_or("")
252 }
253
254 /// Returns the HTTP method of the request (GET, POST, etc.).
255 ///
256 /// See: <https://playwright.dev/docs/api/class-request#request-method>
257 pub fn method(&self) -> &str {
258 self.initializer()
259 .get("method")
260 .and_then(|v| v.as_str())
261 .unwrap_or("GET")
262 }
263
264 /// Returns the resource type of the request (e.g., "document", "stylesheet", "image", "fetch", etc.).
265 ///
266 /// See: <https://playwright.dev/docs/api/class-request#request-resource-type>
267 pub fn resource_type(&self) -> &str {
268 self.initializer()
269 .get("resourceType")
270 .and_then(|v| v.as_str())
271 .unwrap_or("other")
272 }
273
274 /// Check if this request is for a navigation (main document).
275 ///
276 /// A navigation request is when the request is for the main frame's document.
277 /// This is used to distinguish between main document loads and subresource loads.
278 ///
279 /// See: <https://playwright.dev/docs/api/class-request#request-is-navigation-request>
280 pub fn is_navigation_request(&self) -> bool {
281 self.resource_type() == "document"
282 }
283
284 /// Returns the request headers as a HashMap.
285 ///
286 /// The headers are read from the protocol initializer data. The format in the
287 /// protocol is a list of `{name, value}` objects which are merged into a
288 /// `HashMap<String, String>`. If duplicate header names exist, the last
289 /// value wins.
290 ///
291 /// For the full set of raw headers (including duplicates), use
292 /// [`headers_array()`](Self::headers_array) or [`all_headers()`](Self::all_headers).
293 ///
294 /// See: <https://playwright.dev/docs/api/class-request#request-headers>
295 pub fn headers(&self) -> HashMap<String, String> {
296 let mut map = HashMap::new();
297 if let Some(headers) = self.initializer().get("headers").and_then(|v| v.as_array()) {
298 for entry in headers {
299 if let (Some(name), Some(value)) = (
300 entry.get("name").and_then(|v| v.as_str()),
301 entry.get("value").and_then(|v| v.as_str()),
302 ) {
303 map.insert(name.to_lowercase(), value.to_string());
304 }
305 }
306 }
307 map
308 }
309
310 /// Returns the raw base64-encoded post data from the initializer, or `None`.
311 fn post_data_b64(&self) -> Option<&str> {
312 self.initializer().get("postData").and_then(|v| v.as_str())
313 }
314
315 /// Returns the request body (POST data) as bytes, or `None` if there is no body.
316 ///
317 /// The Playwright protocol sends `postData` as a base64-encoded string.
318 /// This method decodes it to raw bytes.
319 ///
320 /// This is a local read and does not require an RPC call.
321 ///
322 /// See: <https://playwright.dev/docs/api/class-request#request-post-data-buffer>
323 pub fn post_data_buffer(&self) -> Option<Vec<u8>> {
324 let b64 = self.post_data_b64()?;
325 use base64::Engine;
326 base64::engine::general_purpose::STANDARD.decode(b64).ok()
327 }
328
329 /// Returns the request body (POST data) as a UTF-8 string, or `None` if there is no body.
330 ///
331 /// The Playwright protocol sends `postData` as a base64-encoded string.
332 /// This method decodes the base64 and then converts the bytes to a UTF-8 string.
333 ///
334 /// This is a local read and does not require an RPC call.
335 ///
336 /// See: <https://playwright.dev/docs/api/class-request#request-post-data>
337 pub fn post_data(&self) -> Option<String> {
338 let bytes = self.post_data_buffer()?;
339 String::from_utf8(bytes).ok()
340 }
341
342 /// Parses the POST data as JSON and deserializes into the target type `T`.
343 ///
344 /// Returns `None` if the request has no POST data, or `Some(Err(...))` if the
345 /// JSON parsing fails.
346 ///
347 /// See: <https://playwright.dev/docs/api/class-request#request-post-data-json>
348 pub fn post_data_json<T: DeserializeOwned>(&self) -> Option<Result<T>> {
349 let data = self.post_data()?;
350 Some(serde_json::from_str(&data).map_err(|e| {
351 crate::error::Error::ProtocolError(format!(
352 "Failed to parse request post data as JSON: {}",
353 e
354 ))
355 }))
356 }
357
358 /// Returns the error text if the request failed, or `None` for successful requests.
359 ///
360 /// The failure text is set when the `requestFailed` browser event fires for this
361 /// request. Use `page.on_request_failed()` to capture failed requests and then
362 /// call this method to get the error reason.
363 ///
364 /// See: <https://playwright.dev/docs/api/class-request#request-failure>
365 pub fn failure(&self) -> Option<String> {
366 self.failure_text.lock().unwrap().clone()
367 }
368
369 /// Sets the failure text. Called by the dispatcher when a `requestFailed` event
370 /// arrives for this request.
371 pub(crate) fn set_failure_text(&self, text: String) {
372 *self.failure_text.lock().unwrap() = Some(text);
373 }
374
375 /// Sets the timing data. Called by the dispatcher when a `requestFinished` event
376 /// arrives and timing data is extracted from the associated Response's initializer.
377 pub(crate) fn set_timing(&self, timing_val: Value) {
378 *self.timing.lock().unwrap() = Some(timing_val);
379 }
380
381 /// Returns all request headers as name-value pairs, preserving duplicates.
382 ///
383 /// Sends a `"rawRequestHeaders"` RPC call to the Playwright server which returns
384 /// the complete list of headers as sent over the wire, including headers added by
385 /// the browser (e.g., `accept-encoding`, `accept-language`).
386 ///
387 /// # Errors
388 ///
389 /// Returns an error if the RPC call to the server fails.
390 ///
391 /// See: <https://playwright.dev/docs/api/class-request#request-headers-array>
392 pub async fn headers_array(&self) -> Result<Vec<HeaderEntry>> {
393 use serde::Deserialize;
394
395 #[derive(Deserialize)]
396 struct RawHeadersResponse {
397 headers: Vec<HeaderEntryRaw>,
398 }
399
400 #[derive(Deserialize)]
401 struct HeaderEntryRaw {
402 name: String,
403 value: String,
404 }
405
406 let result: RawHeadersResponse = self
407 .channel()
408 .send("rawRequestHeaders", serde_json::json!({}))
409 .await?;
410
411 Ok(result
412 .headers
413 .into_iter()
414 .map(|h| HeaderEntry {
415 name: h.name,
416 value: h.value,
417 })
418 .collect())
419 }
420
421 /// Returns all request headers as a `HashMap<String, String>` with lowercased keys.
422 ///
423 /// When multiple headers have the same name, their values are joined with `\n`
424 /// (matching Playwright's behavior).
425 ///
426 /// Sends a `"rawRequestHeaders"` RPC call to the Playwright server.
427 ///
428 /// # Errors
429 ///
430 /// Returns an error if the RPC call to the server fails.
431 ///
432 /// See: <https://playwright.dev/docs/api/class-request#request-all-headers>
433 pub async fn all_headers(&self) -> Result<HashMap<String, String>> {
434 let entries = self.headers_array().await?;
435 let mut map: HashMap<String, String> = HashMap::new();
436 for entry in entries {
437 let key = entry.name.to_lowercase();
438 map.entry(key)
439 .and_modify(|existing| {
440 existing.push('\n');
441 existing.push_str(&entry.value);
442 })
443 .or_insert(entry.value);
444 }
445 Ok(map)
446 }
447
448 /// Returns the value of the specified header (case-insensitive), or `None` if not found.
449 ///
450 /// Uses [`all_headers()`](Self::all_headers) internally, so it sends a
451 /// `"rawRequestHeaders"` RPC call to the Playwright server.
452 ///
453 /// # Errors
454 ///
455 /// Returns an error if the RPC call to the server fails.
456 ///
457 /// See: <https://playwright.dev/docs/api/class-request#request-header-value>
458 pub async fn header_value(&self, name: &str) -> Result<Option<String>> {
459 let all = self.all_headers().await?;
460 Ok(all.get(&name.to_lowercase()).cloned())
461 }
462
463 /// Returns timing information for the request.
464 ///
465 /// The timing data is sourced from the associated Response's initializer when the
466 /// `requestFinished` event fires. This method should be called from within a
467 /// `page.on_request_finished()` handler or after it has fired.
468 ///
469 /// Fields use `-1` to indicate that a timing phase was not reached or is
470 /// unavailable for a given request.
471 ///
472 /// # Errors
473 ///
474 /// Returns an error if timing data is not yet available (e.g., called before
475 /// `requestFinished` fires, or for a request that has not completed successfully).
476 ///
477 /// See: <https://playwright.dev/docs/api/class-request#request-timing>
478 pub async fn timing(&self) -> Result<ResourceTiming> {
479 use serde::Deserialize;
480
481 #[derive(Deserialize)]
482 #[serde(rename_all = "camelCase")]
483 struct RawTiming {
484 start_time: Option<f64>,
485 domain_lookup_start: Option<f64>,
486 domain_lookup_end: Option<f64>,
487 connect_start: Option<f64>,
488 connect_end: Option<f64>,
489 secure_connection_start: Option<f64>,
490 request_start: Option<f64>,
491 response_start: Option<f64>,
492 response_end: Option<f64>,
493 }
494
495 let timing_val = self.timing.lock().unwrap().clone().ok_or_else(|| {
496 crate::error::Error::ProtocolError(
497 "Request timing is not yet available. Call timing() from \
498 on_request_finished() or after it has fired."
499 .to_string(),
500 )
501 })?;
502
503 let raw: RawTiming = serde_json::from_value(timing_val).map_err(|e| {
504 crate::error::Error::ProtocolError(format!("Failed to parse timing data: {}", e))
505 })?;
506
507 Ok(ResourceTiming {
508 start_time: raw.start_time.unwrap_or(-1.0),
509 domain_lookup_start: raw.domain_lookup_start.unwrap_or(-1.0),
510 domain_lookup_end: raw.domain_lookup_end.unwrap_or(-1.0),
511 connect_start: raw.connect_start.unwrap_or(-1.0),
512 connect_end: raw.connect_end.unwrap_or(-1.0),
513 secure_connection_start: raw.secure_connection_start.unwrap_or(-1.0),
514 request_start: raw.request_start.unwrap_or(-1.0),
515 response_start: raw.response_start.unwrap_or(-1.0),
516 response_end: raw.response_end.unwrap_or(-1.0),
517 })
518 }
519}
520
521/// Resource timing information for an HTTP request.
522///
523/// All time values are in milliseconds relative to the navigation start.
524/// A value of `-1` indicates the timing phase was not reached.
525///
526/// See: <https://playwright.dev/docs/api/class-request#request-timing>
527#[derive(Debug, Clone)]
528pub struct ResourceTiming {
529 /// Request start time in milliseconds since epoch.
530 pub start_time: f64,
531 /// Time immediately before the browser starts the domain name lookup
532 /// for the resource. The value is given in milliseconds relative to
533 /// `startTime`, -1 if not available.
534 pub domain_lookup_start: f64,
535 /// Time immediately after the browser starts the domain name lookup
536 /// for the resource. The value is given in milliseconds relative to
537 /// `startTime`, -1 if not available.
538 pub domain_lookup_end: f64,
539 /// Time immediately before the user agent starts establishing the
540 /// connection to the server to retrieve the resource.
541 pub connect_start: f64,
542 /// Time immediately after the browser starts the handshake process
543 /// to secure the current connection.
544 pub secure_connection_start: f64,
545 /// Time immediately after the browser finishes establishing the connection
546 /// to the server to retrieve the resource.
547 pub connect_end: f64,
548 /// Time immediately before the browser starts requesting the resource from
549 /// the server, cache, or local resource.
550 pub request_start: f64,
551 /// Time immediately after the browser starts requesting the resource from
552 /// the server, cache, or local resource.
553 pub response_start: f64,
554 /// Time immediately after the browser receives the last byte of the resource
555 /// or immediately before the transport connection is closed, whichever comes first.
556 pub response_end: f64,
557}
558
559impl ChannelOwner for Request {
560 fn guid(&self) -> &str {
561 self.base.guid()
562 }
563
564 fn type_name(&self) -> &str {
565 self.base.type_name()
566 }
567
568 fn parent(&self) -> Option<Arc<dyn ChannelOwner>> {
569 self.base.parent()
570 }
571
572 fn connection(&self) -> Arc<dyn crate::server::connection::ConnectionLike> {
573 self.base.connection()
574 }
575
576 fn initializer(&self) -> &Value {
577 self.base.initializer()
578 }
579
580 fn channel(&self) -> &crate::server::channel::Channel {
581 self.base.channel()
582 }
583
584 fn dispose(&self, reason: crate::server::channel_owner::DisposeReason) {
585 self.base.dispose(reason)
586 }
587
588 fn adopt(&self, child: Arc<dyn ChannelOwner>) {
589 self.base.adopt(child)
590 }
591
592 fn add_child(&self, guid: Arc<str>, child: Arc<dyn ChannelOwner>) {
593 self.base.add_child(guid, child)
594 }
595
596 fn remove_child(&self, guid: &str) {
597 self.base.remove_child(guid)
598 }
599
600 fn on_event(&self, _method: &str, _params: Value) {
601 // Request events will be handled in future phases
602 }
603
604 fn was_collected(&self) -> bool {
605 self.base.was_collected()
606 }
607
608 fn as_any(&self) -> &dyn Any {
609 self
610 }
611}
612
613impl std::fmt::Debug for Request {
614 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
615 f.debug_struct("Request")
616 .field("guid", &self.guid())
617 .finish()
618 }
619}