Skip to main content

ohos_web_binding/protocol/
http_body_stream.rs

1use std::ptr::NonNull;
2
3use ohos_web_sys::{
4    ArkWeb_HttpBodyStream, OH_ArkWebHttpBodyStream_GetSize, OH_ArkWebHttpBodyStream_GetUserData,
5    OH_ArkWebHttpBodyStream_Init, OH_ArkWebHttpBodyStream_IsChunked, OH_ArkWebHttpBodyStream_IsEof,
6    OH_ArkWebHttpBodyStream_IsInMemory, OH_ArkWebHttpBodyStream_Read,
7    OH_ArkWebHttpBodyStream_SetReadCallback, OH_ArkWebHttpBodyStream_SetUserData,
8    OH_ArkWebResourceRequest_DestroyHttpBodyStream,
9};
10
11use crate::HttpBodyStreamError;
12
13/// An owned request body stream, confined to the ArkWeb I/O thread.
14///
15/// Reads consume the stream, so only one operation can use it at a time.
16/// [`Self::read`] returns ownership with the bytes; [`Self::read_to_end`] closes
17/// it on completion. Both initialize lazily, without rewinding subsequent reads.
18/// Callbacks may run inline and must own their captures (`'static`).
19///
20/// Once submitted, an operation owns the stream and buffer until its callback.
21/// If native code never completes it, those resources must remain allocated:
22/// ArkWeb provides no cancellation acknowledgement for outstanding writes.
23pub struct HttpBodyStream {
24    raw: NonNull<ArkWeb_HttpBodyStream>,
25    initialized: bool,
26}
27
28impl HttpBodyStream {
29    /// Take exclusive ownership of a native body stream.
30    ///
31    /// # Safety
32    ///
33    /// `raw` must be null or a live stream returned by
34    /// `OH_ArkWebResourceRequest_GetHttpBodyStream`, with no operations in flight.
35    /// The caller must be on the ArkWeb I/O thread. No other owner may use,
36    /// destroy, or change callbacks/userData on this stream after this call.
37    pub unsafe fn new(raw: *mut ArkWeb_HttpBodyStream) -> Result<Self, HttpBodyStreamError> {
38        Ok(Self {
39            raw: NonNull::new(raw).ok_or(HttpBodyStreamError::NullStream)?,
40            initialized: false,
41        })
42    }
43
44    /// Initialize without reading, returning the stream for metadata queries.
45    /// Already initialized streams are returned without another native Init.
46    /// All errors are delivered once through the callback, possibly inline.
47    pub fn initialize<F>(self, callback: F)
48    where
49        F: FnOnce(Result<Self, HttpBodyStreamError>) + 'static,
50    {
51        self.read(0, move |result| callback(result.map(|(stream, _)| stream)));
52    }
53
54    pub fn is_chunked(&self) -> Result<bool, HttpBodyStreamError> {
55        self.ensure_initialized()?;
56        Ok(unsafe { OH_ArkWebHttpBodyStream_IsChunked(self.raw.as_ptr()) })
57    }
58
59    pub fn is_eof(&self) -> Result<bool, HttpBodyStreamError> {
60        self.ensure_initialized()?;
61        Ok(unsafe { OH_ArkWebHttpBodyStream_IsEof(self.raw.as_ptr()) })
62    }
63
64    pub fn is_in_memory(&self) -> Result<bool, HttpBodyStreamError> {
65        self.ensure_initialized()?;
66        Ok(unsafe { OH_ArkWebHttpBodyStream_IsInMemory(self.raw.as_ptr()) })
67    }
68
69    /// Total body size after initialization: `None` for unknown-length chunked
70    /// bodies, `Some(0)` for known empty bodies. Before initialization, errors.
71    pub fn size(&self) -> Result<Option<u64>, HttpBodyStreamError> {
72        if self.is_chunked()? {
73            Ok(None)
74        } else {
75            Ok(Some(unsafe {
76                OH_ArkWebHttpBodyStream_GetSize(self.raw.as_ptr())
77            }))
78        }
79    }
80
81    /// Read at most `size` bytes, returning the stream at its new position.
82    /// A zero-sized read initializes but never calls native Read.
83    /// On error the stream is closed. The callback is the sole result channel.
84    ///
85    /// Ownership prevents overlapping reads at compile time:
86    /// ```compile_fail,E0382
87    /// # use ohos_web_binding::HttpBodyStream;
88    /// fn overlap(stream: HttpBodyStream) {
89    ///     stream.read(1, |_| {});
90    ///     stream.read(1, |_| {}); // stream has moved into the first operation
91    /// }
92    /// ```
93    pub fn read<F>(self, size: usize, callback: F)
94    where
95        F: FnOnce(Result<(Self, Vec<u8>), HttpBodyStreamError>) + 'static,
96    {
97        BodyReader::start(self, size, false, Box::new(callback));
98    }
99
100    /// Collect the remaining body through EOF and close the stream. Handles
101    /// short reads and unknown lengths; errors also close the stream.
102    pub fn read_to_end<F>(self, callback: F)
103    where
104        F: FnOnce(Result<Vec<u8>, HttpBodyStreamError>) + 'static,
105    {
106        BodyReader::start(
107            self,
108            64 * 1024,
109            true,
110            Box::new(move |result| {
111                callback(result.map(|(_, bytes)| bytes));
112            }),
113        );
114    }
115
116    fn ensure_initialized(&self) -> Result<(), HttpBodyStreamError> {
117        self.initialized
118            .then_some(())
119            .ok_or(HttpBodyStreamError::NotInitialized)
120    }
121}
122
123impl Drop for HttpBodyStream {
124    fn drop(&mut self) {
125        // A submitted operation owns this stream, so no native write is pending.
126        unsafe { OH_ArkWebResourceRequest_DestroyHttpBodyStream(self.raw.as_ptr()) };
127    }
128}
129
130type ReadCallback = Box<dyn FnOnce(Result<(HttpBodyStream, Vec<u8>), HttpBodyStreamError>)>;
131
132enum Completion {
133    Initialized(i32),
134    Read { buffer: *mut u8, count: i32 },
135}
136
137/// A single operation owns everything the native callback can access.
138struct BodyReader {
139    stream: HttpBodyStream,
140    callback: ReadCallback,
141    buffer: Vec<u8>,
142    data: Vec<u8>,
143    to_end: bool,
144    driving: bool,
145    completion: Option<Completion>,
146}
147
148impl BodyReader {
149    fn start(stream: HttpBodyStream, size: usize, to_end: bool, callback: ReadCallback) {
150        if size > i32::MAX as usize {
151            drop(stream);
152            callback(Err(HttpBodyStreamError::InvalidReadSize(size)));
153            return;
154        }
155        let native = stream.raw.as_ptr();
156        let reader = Box::into_raw(Box::new(Self {
157            stream,
158            callback,
159            buffer: vec![0; size],
160            data: Vec::new(),
161            to_end,
162            driving: true,
163            completion: None,
164        }));
165        // Transfer the Box to the pending operation. No Rust reference to it
166        // crosses Init/Read: either may reenter through the registered callback.
167        unsafe {
168            let status = OH_ArkWebHttpBodyStream_SetUserData(native, reader.cast());
169            if status != 0 {
170                Self::finish(reader, Err(HttpBodyStreamError::SetUserDataFailed(status)));
171                return;
172            }
173            let status = OH_ArkWebHttpBodyStream_SetReadCallback(native, Some(read_callback));
174            if status != 0 {
175                Self::finish(
176                    reader,
177                    Err(HttpBodyStreamError::SetReadCallbackFailed(status)),
178                );
179                return;
180            }
181            if (*reader).stream.initialized {
182                (*reader).completion = Some(Completion::Initialized(0));
183            } else {
184                let status = OH_ArkWebHttpBodyStream_Init(native, Some(initialized));
185                if status != 0 {
186                    (*reader).completion = Some(Completion::Initialized(status));
187                }
188            }
189            Self::drive(reader);
190        }
191    }
192
193    unsafe fn drive(reader: *mut Self) {
194        (*reader).driving = true;
195        while let Some(completion) = (*reader).completion.take() {
196            match (*reader).accept(completion) {
197                Ok(false) => {}
198                result => {
199                    Self::finish(reader, result.map(|_| ()));
200                    return; // finish reclaimed the Box; never access it again.
201                }
202            }
203            let native = (*reader).stream.raw.as_ptr();
204            let buffer = (*reader).buffer.as_mut_ptr();
205            let length = (*reader).buffer.len() as i32;
206            // Inline callbacks only record completion. Processing after Read
207            // returns prevents stack growth and premature buffer destruction.
208            OH_ArkWebHttpBodyStream_Read(native, buffer, length);
209        }
210        (*reader).driving = false; // A later callback resumes this loop.
211    }
212
213    fn accept(&mut self, completion: Completion) -> Result<bool, HttpBodyStreamError> {
214        match completion {
215            Completion::Initialized(status) => {
216                if status != 0 {
217                    return Err(HttpBodyStreamError::InitializationFailed(status));
218                }
219                self.stream.initialized = true;
220            }
221            Completion::Read { buffer, count } => {
222                if count < 0 {
223                    return Err(HttpBodyStreamError::ReadFailed(count));
224                }
225                if count as usize > self.buffer.len() {
226                    return Err(HttpBodyStreamError::InvalidReadCount {
227                        count,
228                        capacity: self.buffer.len(),
229                    });
230                }
231                if buffer != self.buffer.as_mut_ptr() {
232                    return Err(HttpBodyStreamError::UnexpectedBuffer);
233                }
234                if count == 0 && !self.stream.is_eof()? {
235                    return Err(HttpBodyStreamError::NoProgress);
236                }
237                if !self.to_end {
238                    self.buffer.truncate(count as usize);
239                    return Ok(true);
240                }
241                self.data.extend_from_slice(&self.buffer[..count as usize]);
242            }
243        }
244        if self.buffer.is_empty() || self.stream.is_eof()? {
245            self.buffer.clear();
246            Ok(true)
247        } else {
248            Ok(false)
249        }
250    }
251
252    unsafe fn complete(native: *const ArkWeb_HttpBodyStream, completion: Completion) {
253        let reader = OH_ArkWebHttpBodyStream_GetUserData(native).cast::<Self>();
254        (*reader).completion = Some(completion);
255        if !(*reader).driving {
256            Self::drive(reader);
257        }
258    }
259
260    unsafe fn finish(reader: *mut Self, result: Result<(), HttpBodyStreamError>) {
261        let Self {
262            stream,
263            callback,
264            buffer,
265            data,
266            to_end,
267            ..
268        } = *Box::from_raw(reader);
269        // The native write is complete. Retire the callback before returning
270        // ownership: user code may immediately start another read on this stream.
271        // SetUserData(null) is not supported by every ArkWeb version; the next
272        // operation replaces it before submitting work, or Drop destroys it.
273        OH_ArkWebHttpBodyStream_SetReadCallback(stream.raw.as_ptr(), None);
274        callback(result.map(|()| (stream, if to_end { data } else { buffer })));
275    }
276}
277
278unsafe extern "C" fn initialized(stream: *const ArkWeb_HttpBodyStream, status: i32) {
279    BodyReader::complete(stream, Completion::Initialized(status));
280}
281
282unsafe extern "C" fn read_callback(
283    stream: *const ArkWeb_HttpBodyStream,
284    buffer: *mut u8,
285    count: i32,
286) {
287    BodyReader::complete(stream, Completion::Read { buffer, count });
288}