-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathresponse.rs
More file actions
604 lines (538 loc) · 20 KB
/
Copy pathresponse.rs
File metadata and controls
604 lines (538 loc) · 20 KB
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex as AsyncMutex;
use bytes::Bytes;
use encoding::label::encoding_from_whatwg_label;
use futures::{Stream, StreamExt};
use impit::{errors::ImpitError, utils::ContentType};
use pyo3::prelude::*;
use reqwest::{Response, StatusCode, Version};
use std::pin::Pin;
use crate::errors::ImpitPyError;
type SharedStream =
Arc<AsyncMutex<Option<Pin<Box<dyn Stream<Item = reqwest::Result<Bytes>> + Send + 'static>>>>>;
#[pyclass]
pub struct PyResponseBytesIterator {
ready_content: Option<Vec<u8>>,
stream: Option<Pin<Box<dyn Stream<Item = reqwest::Result<Bytes>> + Send + Sync>>>,
runtime: tokio::runtime::Handle,
content_returned: bool,
parent_response: Option<Py<ImpitPyResponse>>,
}
#[pymethods]
impl PyResponseBytesIterator {
fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
slf
}
fn __next__(mut slf: PyRefMut<'_, Self>) -> PyResult<Option<Vec<u8>>> {
if let Some(content) = slf.ready_content.take() {
slf.content_returned = true;
return Ok(Some(content));
}
if slf.content_returned {
return Ok(None);
}
if let Some(parent) = &slf.parent_response {
let py = slf.py();
let is_parent_closed = parent.borrow(py).is_closed;
if is_parent_closed && !slf.content_returned {
slf.content_returned = true;
return Ok(None);
}
}
let runtime = slf.runtime.clone();
let py = slf.py();
if let Some(stream) = &mut slf.stream {
let result = py.detach(|| runtime.block_on(stream.next()));
match result {
Some(Ok(chunk)) => Ok(Some(chunk.to_vec())),
Some(Err(e)) => {
slf.content_returned = true;
if let Some(parent) = &slf.parent_response {
if let Ok(mut parent_ref) = parent.try_borrow_mut(py) {
parent_ref.inner_state = InnerResponseState::StreamingClosed;
parent_ref.is_closed = true;
}
}
Err(pyo3::exceptions::PyStopIteration::new_err(format!(
"Stream error: {e}"
)))
}
None => {
slf.content_returned = true;
if let Some(parent) = &slf.parent_response {
if let Ok(mut parent_ref) = parent.try_borrow_mut(py) {
parent_ref.inner_state = InnerResponseState::StreamingClosed;
parent_ref.is_stream_consumed = true;
parent_ref.is_closed = true;
}
}
Ok(None)
}
}
} else {
slf.content_returned = true;
Ok(None)
}
}
}
#[pyclass]
pub struct PyResponseAsyncBytesIterator {
ready_content: Option<Vec<u8>>,
stream: Option<SharedStream>,
content_returned: bool,
parent_response: Option<Py<ImpitPyResponse>>,
}
#[pymethods]
impl PyResponseAsyncBytesIterator {
fn __aiter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
slf
}
fn __anext__<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
if let Some(content) = self.ready_content.take() {
self.content_returned = true;
let future =
pyo3_async_runtimes::tokio::future_into_py::<_, Vec<u8>>(py, async move {
Ok(content)
})?;
return Ok(future);
}
if self.content_returned {
return Err(pyo3::exceptions::PyStopAsyncIteration::new_err(""));
}
if let Some(parent) = &self.parent_response {
let is_closed = parent.borrow(py).is_closed;
if is_closed {
self.content_returned = true;
return Err(pyo3::exceptions::PyStopAsyncIteration::new_err(
"Response is closed",
));
}
}
let stream_arc = match &self.stream {
Some(arc) => arc.clone(),
None => {
self.content_returned = true;
return Err(pyo3::exceptions::PyStopAsyncIteration::new_err(
"No stream available",
));
}
};
let parent_response = self.parent_response.as_ref().map(|p| p.clone_ref(py));
let future = pyo3_async_runtimes::tokio::future_into_py::<_, Vec<u8>>(py, async move {
let chunk_result = {
let mut stream_guard = stream_arc.lock().await;
if let Some(stream) = stream_guard.as_mut() {
stream.next().await
} else {
None
}
};
match chunk_result {
Some(Ok(chunk)) => Ok(chunk.to_vec()),
Some(Err(e)) => {
if let Some(parent) = parent_response {
Python::attach(|py| {
if let Ok(mut parent_ref) = parent.try_borrow_mut(py) {
parent_ref.inner_state = InnerResponseState::StreamingClosed;
parent_ref.is_closed = true;
}
});
}
Err(pyo3::exceptions::PyStopAsyncIteration::new_err(format!(
"Stream error: {e}"
)))
}
None => {
if let Some(parent) = parent_response {
Python::attach(|py| {
if let Ok(mut parent_ref) = parent.try_borrow_mut(py) {
parent_ref.inner_state = InnerResponseState::StreamingClosed;
parent_ref.is_stream_consumed = true;
parent_ref.is_closed = true;
}
});
}
Err(pyo3::exceptions::PyStopAsyncIteration::new_err(""))
}
}
})?;
Ok(future)
}
}
#[derive(Debug, Clone, Copy)]
pub enum InnerResponseState {
Unread,
Read,
Streaming,
StreamingClosed,
}
#[pyclass(name = "Response", dict, weakref)]
#[derive(Debug)]
pub struct ImpitPyResponse {
#[pyo3(get)]
status_code: u16,
#[pyo3(get)]
reason_phrase: String,
#[pyo3(get)]
http_version: String,
#[pyo3(get)]
headers: HashMap<String, String>,
#[pyo3(get)]
encoding: String,
#[pyo3(get)]
is_redirect: bool,
#[pyo3(get)]
url: String,
#[pyo3(get)]
is_closed: bool,
#[pyo3(get)]
is_stream_consumed: bool,
// #[pyo3(get)]
// request: Request,
// #[pyo3(get)]
// next_request: Option<Request>,
// #[pyo3(get)]
// cookies: Cookies,
// #[pyo3(get)]
// history: Vec<Response>,
// #[pyo3(get)]
// elapsed: Duration,
text: Option<String>,
content: Option<Vec<u8>>,
inner: Option<Response>,
inner_state: InnerResponseState,
}
#[pymethods]
impl ImpitPyResponse {
#[new]
#[pyo3(signature = (status_code, content=None, headers=None, url=None, default_encoding="utf-8"))]
fn new(
status_code: u16,
content: Option<Vec<u8>>,
headers: Option<HashMap<String, String>>,
url: Option<String>,
default_encoding: Option<&str>,
) -> Self {
let headers = headers.unwrap_or_default();
let encoding = match headers
.iter()
.find(|(k, _)| k.to_lowercase() == "content-type")
{
Some((_, ct)) => ContentType::from(ct)
.ok()
.map(|ct| ct.charset)
.unwrap_or_else(|| default_encoding.unwrap_or("utf-8").to_string()),
None => default_encoding.unwrap_or("utf-8").to_string(),
};
let reason_phrase = StatusCode::from_u16(status_code)
.map(|s| s.canonical_reason().unwrap_or("Unknown").to_string())
.unwrap_or_else(|_| "Unknown".to_string());
Self {
status_code,
reason_phrase,
http_version: "HTTP/1.1".to_string(),
headers,
encoding,
is_redirect: false,
url: url.unwrap_or_default(),
is_closed: true,
is_stream_consumed: true,
text: None,
content: Some(content.unwrap_or_default()),
inner: None,
inner_state: InnerResponseState::Read,
}
}
fn __repr__(&self) -> String {
format!("<Response [{} {}]>", self.status_code, self.reason_phrase)
}
fn raise_for_status(&self) -> PyResult<()> {
if self.status_code >= 400 {
return Err(
ImpitPyError(impit::errors::ImpitError::HTTPStatusError(self.status_code)).into(),
);
}
Ok(())
}
fn aclose(slf: Py<Self>, py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
pyo3_async_runtimes::tokio::future_into_py(py, async move {
Self::close_async_impl(slf)?;
Ok(())
})
}
fn aiter_bytes(slf: Py<Self>, py: Python) -> PyResult<PyResponseAsyncBytesIterator> {
let mut slf_ref = slf.borrow_mut(py);
match slf_ref.inner_state {
InnerResponseState::Read => {
let content = slf_ref.content.clone();
drop(slf_ref);
Ok(PyResponseAsyncBytesIterator {
ready_content: content,
stream: None,
content_returned: false,
parent_response: Some(slf),
})
}
InnerResponseState::Unread => {
slf_ref.inner_state = InnerResponseState::Streaming;
let response = slf_ref
.inner
.take()
.ok_or(ImpitPyError(impit::errors::ImpitError::StreamClosed))?;
drop(slf_ref);
let stream: Pin<Box<dyn Stream<Item = reqwest::Result<Bytes>> + Send>> =
Box::pin(response.bytes_stream());
let shared_stream = Arc::new(AsyncMutex::new(Some(stream)));
Ok(PyResponseAsyncBytesIterator {
ready_content: None,
stream: Some(shared_stream),
content_returned: false,
parent_response: Some(slf),
})
}
InnerResponseState::Streaming | InnerResponseState::StreamingClosed => {
drop(slf_ref);
Err(ImpitPyError(impit::errors::ImpitError::StreamConsumed).into())
}
}
}
fn iter_bytes(slf: Py<Self>, py: Python) -> PyResult<PyResponseBytesIterator> {
let runtime = pyo3_async_runtimes::tokio::get_runtime().handle().clone();
let mut slf_ref = slf.borrow_mut(py);
match slf_ref.inner_state {
InnerResponseState::Read => {
let content = slf_ref.content.clone();
drop(slf_ref);
Ok(PyResponseBytesIterator {
ready_content: content,
stream: None,
runtime,
content_returned: false,
parent_response: Some(slf),
})
}
InnerResponseState::Unread => {
slf_ref.inner_state = InnerResponseState::Streaming;
let response = slf_ref
.inner
.take()
.ok_or(ImpitPyError(impit::errors::ImpitError::StreamClosed))?;
drop(slf_ref);
let stream: Pin<Box<dyn Stream<Item = reqwest::Result<Bytes>> + Send + Sync>> =
Box::pin(response.bytes_stream());
Ok(PyResponseBytesIterator {
ready_content: None,
stream: Some(stream),
runtime,
content_returned: false,
parent_response: Some(slf),
})
}
InnerResponseState::Streaming | InnerResponseState::StreamingClosed => {
drop(slf_ref);
Err(ImpitPyError(impit::errors::ImpitError::StreamConsumed).into())
}
}
}
fn aread(slf: Py<Self>, py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
pyo3_async_runtimes::tokio::future_into_py(py, async move {
let (state, response_option, content_option, is_stream_consumed) =
Python::attach(|py| {
let mut slf_ref = slf.borrow_mut(py);
(
slf_ref.inner_state,
slf_ref.inner.take(),
slf_ref.content.clone(),
slf_ref.is_stream_consumed,
)
});
match state {
InnerResponseState::Read => Ok(content_option.unwrap_or_default()),
InnerResponseState::Unread => {
if let Some(response) = response_option {
let content =
response.bytes().await.map(|b| b.to_vec()).map_err(|_| {
ImpitPyError(impit::errors::ImpitError::NetworkError)
})?;
Python::attach(|py| {
let mut slf_ref = slf.borrow_mut(py);
slf_ref.content = Some(content.clone());
slf_ref.inner_state = InnerResponseState::Read;
slf_ref.is_stream_consumed = true;
slf_ref.is_closed = true;
});
Ok(content)
} else {
Err(ImpitPyError(impit::errors::ImpitError::StreamClosed).into())
}
}
InnerResponseState::Streaming | InnerResponseState::StreamingClosed => {
if is_stream_consumed {
Err(ImpitPyError(impit::errors::ImpitError::StreamConsumed).into())
} else {
Err(ImpitPyError(impit::errors::ImpitError::StreamClosed).into())
}
}
}
})
}
pub fn close(&mut self) -> PyResult<()> {
if self.is_closed {
return Ok(());
}
self.inner = None;
self.inner_state = match self.inner_state {
InnerResponseState::Streaming => InnerResponseState::StreamingClosed,
_ => self.inner_state,
};
self.is_closed = true;
Ok(())
}
#[getter]
fn content(&mut self, py: Python<'_>) -> PyResult<Vec<u8>> {
self.read(py)
}
#[getter]
fn text(&mut self, py: Python<'_>) -> PyResult<String> {
if let Some(cached_text) = &self.text {
return Ok(cached_text.clone());
}
let content_bytes = self.read(py)?;
let decoder = encoding_from_whatwg_label(&self.encoding);
let decoded_text = impit::utils::decode(&content_bytes, decoder);
self.text = Some(decoded_text.clone());
Ok(decoded_text)
}
fn json(&mut self, py: Python<'_>) -> PyResult<Py<PyAny>> {
let text = self.text(py)?;
let json_module = py.import("json")?;
let parsed = json_module.call_method1("loads", (text,))?;
Ok(parsed.into())
}
fn read(&mut self, py: Python<'_>) -> PyResult<Vec<u8>> {
match self.inner_state {
InnerResponseState::Read => self
.content
.as_ref()
.cloned()
.ok_or_else(|| ImpitPyError(impit::errors::ImpitError::ResponseNotRead).into()),
InnerResponseState::Streaming | InnerResponseState::StreamingClosed => {
if self.is_stream_consumed {
Err(ImpitPyError(impit::errors::ImpitError::StreamConsumed).into())
} else {
Err(ImpitPyError(impit::errors::ImpitError::StreamClosed).into())
}
}
InnerResponseState::Unread => {
let response = self
.inner
.take()
.ok_or(ImpitPyError(impit::errors::ImpitError::StreamClosed))?;
let runtime = pyo3_async_runtimes::tokio::get_runtime();
let content = py.detach(|| {
runtime.block_on(async {
response
.bytes()
.await
.map(|b| b.to_vec())
.map_err(|_| ImpitPyError(impit::errors::ImpitError::NetworkError))
})
})?;
self.content = Some(content.clone());
self.inner_state = InnerResponseState::Read;
self.is_stream_consumed = true;
self.is_closed = true;
Ok(content)
}
}
}
}
impl ImpitPyResponse {
fn close_async_impl(slf: Py<Self>) -> PyResult<()> {
Python::attach(|py| {
let mut slf_ref = slf.borrow_mut(py);
slf_ref.close()
})
}
pub async fn from_async(
val: Response,
preferred_encoding: Option<String>,
stream: bool,
) -> Result<Self, ImpitError> {
let status_code = val.status().as_u16();
let url = val.url().to_string();
let reason_phrase = val
.status()
.canonical_reason()
.unwrap_or_default()
.to_string();
let http_version = match val.version() {
Version::HTTP_09 => "HTTP/0.9".to_string(),
Version::HTTP_10 => "HTTP/1.0".to_string(),
Version::HTTP_11 => "HTTP/1.1".to_string(),
Version::HTTP_2 => "HTTP/2".to_string(),
Version::HTTP_3 => "HTTP/3".to_string(),
_ => "Unknown".to_string(),
};
let is_redirect = val.status().is_redirection();
let headers = HashMap::from_iter(val.headers().iter().map(|(k, v)| {
(
k.as_str().to_string(),
v.as_bytes().iter().map(|&b| b as char).collect::<String>(),
)
}));
let content_type_charset = headers
.get("content-type")
.and_then(|ct| ContentType::from(ct).ok())
.and_then(|ct| ct.into());
let (content, inner_state, encoding, inner, is_closed, is_stream_consumed) = if !stream {
let content = val
.bytes()
.await
.map(|b| b.to_vec())
.map_err(|e| ImpitError::from(e, None))?;
let encoding = preferred_encoding
.and_then(|e| encoding_from_whatwg_label(&e))
.or(content_type_charset)
.or(impit::utils::determine_encoding(content.as_slice()))
.unwrap_or(impit::utils::encodings::UTF_8);
(
Some(content),
InnerResponseState::Read,
encoding,
None,
true,
true,
)
} else {
let encoding = preferred_encoding
.and_then(|e| encoding_from_whatwg_label(&e))
.or(content_type_charset)
.unwrap_or(impit::utils::encodings::UTF_8);
(
None,
InnerResponseState::Unread,
encoding,
Some(val),
false,
false,
)
};
Ok(ImpitPyResponse {
status_code,
url,
reason_phrase,
http_version,
is_redirect,
headers,
encoding: encoding.name().to_string(),
text: None,
content,
is_closed,
is_stream_consumed,
inner_state,
inner,
})
}
}