| 103 | } |
| 104 | |
| 105 | fn __anext__<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> { |
| 106 | if let Some(content) = self.ready_content.take() { |
| 107 | self.content_returned = true; |
| 108 | let future = |
| 109 | pyo3_async_runtimes::tokio::future_into_py::<_, Vec<u8>>(py, async move { |
| 110 | Ok(content) |
| 111 | })?; |
| 112 | return Ok(future); |
| 113 | } |
| 114 | |
| 115 | if self.content_returned { |
| 116 | return Err(pyo3::exceptions::PyStopAsyncIteration::new_err("")); |
| 117 | } |
| 118 | |
| 119 | if let Some(parent) = &self.parent_response { |
| 120 | let is_closed = parent.borrow(py).is_closed; |
| 121 | if is_closed { |
| 122 | self.content_returned = true; |
| 123 | return Err(pyo3::exceptions::PyStopAsyncIteration::new_err( |
| 124 | "Response is closed", |
| 125 | )); |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | let stream_arc = match &self.stream { |
| 130 | Some(arc) => arc.clone(), |
| 131 | None => { |
| 132 | self.content_returned = true; |
| 133 | return Err(pyo3::exceptions::PyStopAsyncIteration::new_err( |
| 134 | "No stream available", |
| 135 | )); |
| 136 | } |
| 137 | }; |
| 138 | |
| 139 | let parent_response = self.parent_response.as_ref().map(|p| p.clone_ref(py)); |
| 140 | |
| 141 | let future = pyo3_async_runtimes::tokio::future_into_py::<_, Vec<u8>>(py, async move { |
| 142 | let chunk_result = { |
| 143 | let mut stream_guard = stream_arc.lock().await; |
| 144 | if let Some(stream) = stream_guard.as_mut() { |
| 145 | stream.next().await |
| 146 | } else { |
| 147 | None |
| 148 | } |
| 149 | }; |
| 150 | match chunk_result { |
| 151 | Some(Ok(chunk)) => Ok(chunk.to_vec()), |
| 152 | Some(Err(e)) => { |
| 153 | if let Some(parent) = parent_response { |
| 154 | Python::attach(|py| { |
| 155 | if let Ok(mut parent_ref) = parent.try_borrow_mut(py) { |
| 156 | parent_ref.inner_state = InnerResponseState::StreamingClosed; |
| 157 | parent_ref.is_stream_consumed = true; |
| 158 | parent_ref.is_closed = true; |
| 159 | } |
| 160 | }); |
| 161 | } |
| 162 | Err(ImpitPyError(ImpitError::from(e, None)).into()) |