rong_rt 0.3.1

Async runtime, HTTP client, and platform services for RongJS
Documentation
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
use bytes::Bytes;
use http::Request as HttpRequest;
use http::header;
use http::{HeaderValue, Method, StatusCode, header::HeaderName};
use http_body::Frame;
use http_body_util::{BodyExt, StreamBody, combinators::BoxBody};
use std::io::Error;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::io::AsyncReadExt;
use tokio::sync::{mpsc, oneshot, watch};
use tokio_stream::StreamExt as _;
use tokio_stream::wrappers::ReceiverStream;

use crate::client::{HttpBody, RequestTimeouts, send_request_with_timeout};

const UPLOAD_CHUNK_SIZE: usize = 64 * 1024;
const UPLOAD_BODY_CHAN_CAP: usize = 16;
const UPLOAD_EVENT_CHAN_CAP: usize = 128;

#[derive(Clone, Debug)]
pub struct UploadOptions {
    url: String,
    file_path: PathBuf,
    method: Method,
    headers: Vec<(String, String)>,
    content_type: Option<String>,
    request_timeout: Option<Duration>,
    connect_timeout: Option<Duration>,
}

impl UploadOptions {
    /// Build upload options for a file path and destination URL.
    pub fn new(url: impl Into<String>, file_path: impl AsRef<Path>) -> Self {
        Self {
            url: url.into(),
            file_path: file_path.as_ref().to_path_buf(),
            method: Method::PUT,
            headers: Vec::new(),
            content_type: None,
            request_timeout: None,
            connect_timeout: None,
        }
    }

    /// Override the HTTP method used for the upload request.
    pub fn with_method(mut self, method: Method) -> Self {
        self.method = method;
        self
    }

    /// Add a request header to the upload request.
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// Set the `Content-Type` header for the upload request.
    pub fn with_content_type(mut self, content_type: impl Into<String>) -> Self {
        self.content_type = Some(content_type.into());
        self
    }

    /// Override the request timeout for this upload.
    pub fn with_request_timeout(mut self, timeout: Duration) -> Self {
        self.request_timeout = Some(timeout);
        self
    }

    /// Override the socket-connect timeout for this upload.
    pub fn with_connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = Some(timeout);
        self
    }

    fn timeouts(&self) -> RequestTimeouts {
        RequestTimeouts {
            request_timeout: self.request_timeout,
            connect_timeout: self.connect_timeout,
        }
    }
}

/// Terminal upload response returned after the request finishes.
#[derive(Clone, Debug)]
pub struct UploadResponse {
    pub status: StatusCode,
    pub body: Bytes,
}

/// Upload lifecycle events surfaced by the streaming upload API.
#[derive(Clone, Debug)]
pub enum UploadEvent {
    Progress {
        uploaded_bytes: u64,
        total_bytes: Option<u64>,
    },
    Success(UploadResponse),
}

/// Handle for a background upload operation.
pub struct UploadTask {
    pub events: mpsc::Receiver<Result<UploadEvent, String>>,
    cancel_tx: Option<oneshot::Sender<()>>,
}

/// Start an upload and receive progress events from a background task.
pub fn spawn_upload(
    options: UploadOptions,
    abort_rx: Option<oneshot::Receiver<()>>,
) -> Result<UploadTask, String> {
    request_upload(options, abort_rx)
}

/// Upload a file on the current task and return only the terminal response.
pub async fn upload(
    options: UploadOptions,
    abort_rx: Option<oneshot::Receiver<()>>,
) -> Result<UploadResponse, String> {
    let mut task = request_upload(options, abort_rx)?;
    while let Some(event) = task.events.recv().await {
        match event? {
            UploadEvent::Progress { .. } => {}
            UploadEvent::Success(response) => return Ok(response),
        }
    }
    Err("upload task ended without a terminal response".to_string())
}

impl UploadTask {
    pub fn cancel(&mut self) {
        if let Some(tx) = self.cancel_tx.take() {
            let _ = tx.send(());
        }
    }

    pub fn into_parts(
        mut self,
    ) -> (
        mpsc::Receiver<Result<UploadEvent, String>>,
        Option<oneshot::Sender<()>>,
    ) {
        let (_dummy_tx, dummy_rx) = mpsc::channel(1);
        let events = std::mem::replace(&mut self.events, dummy_rx);
        (events, self.cancel_tx.take())
    }

    pub fn into_stream(self) -> UploadEventStream {
        let (events, cancel_tx) = self.into_parts();
        UploadEventStream {
            inner: ReceiverStream::new(events),
            cancel_tx,
        }
    }
}

impl Drop for UploadTask {
    fn drop(&mut self) {
        self.cancel();
    }
}

pub struct UploadEventStream {
    inner: ReceiverStream<Result<UploadEvent, String>>,
    cancel_tx: Option<oneshot::Sender<()>>,
}

impl UploadEventStream {
    pub fn cancel(&mut self) {
        if let Some(tx) = self.cancel_tx.take() {
            let _ = tx.send(());
        }
    }
}

impl Drop for UploadEventStream {
    fn drop(&mut self) {
        self.cancel();
    }
}

impl tokio_stream::Stream for UploadEventStream {
    type Item = Result<UploadEvent, String>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.inner).poll_next(cx)
    }
}

pub fn request_upload(
    options: UploadOptions,
    abort_rx: Option<oneshot::Receiver<()>>,
) -> Result<UploadTask, String> {
    let (events_tx, events_rx) =
        mpsc::channel::<Result<UploadEvent, String>>(UPLOAD_EVENT_CHAN_CAP);
    let (cancel_tx, cancel_rx) = oneshot::channel::<()>();
    let network_access_guard = crate::http::current_network_access_guard();

    crate::RongExecutor::global().spawn(async move {
        crate::http::scope_network_access_guard_opt(
            network_access_guard,
            run_upload_worker(options, abort_rx, cancel_rx, events_tx),
        )
        .await;
    });

    Ok(UploadTask {
        events: events_rx,
        cancel_tx: Some(cancel_tx),
    })
}

async fn run_upload_worker(
    options: UploadOptions,
    abort_rx: Option<oneshot::Receiver<()>>,
    cancel_rx: oneshot::Receiver<()>,
    events_tx: mpsc::Sender<Result<UploadEvent, String>>,
) {
    let (stop_tx, stop_rx) = watch::channel(false);

    let stop_tx_cancel = stop_tx.clone();
    tokio::task::spawn(async move {
        let _ = cancel_rx.await;
        let _ = stop_tx_cancel.send(true);
    });
    if let Some(abort_rx) = abort_rx {
        let stop_tx_abort = stop_tx.clone();
        tokio::task::spawn(async move {
            let _ = abort_rx.await;
            let _ = stop_tx_abort.send(true);
        });
    }

    let mut file = match tokio::fs::File::open(&options.file_path).await {
        Ok(f) => f,
        Err(e) => {
            let _ = events_tx
                .send(Err(format!(
                    "open upload file '{}': {}",
                    options.file_path.display(),
                    e
                )))
                .await;
            return;
        }
    };

    let total_bytes = match file.metadata().await {
        Ok(meta) => Some(meta.len()),
        Err(_) => None,
    };

    let (body_tx, body_rx) = mpsc::channel::<Result<Bytes, Error>>(UPLOAD_BODY_CHAN_CAP);
    let body_stream = ReceiverStream::new(body_rx).map(|item| item.map(Frame::data));
    let request_body: BoxBody<Bytes, Error> = StreamBody::new(body_stream).boxed();
    let request = match build_request(&options, total_bytes, request_body) {
        Ok(req) => req,
        Err(e) => {
            let _ = events_tx.send(Err(e)).await;
            return;
        }
    };
    if let Err(err) = crate::http::check_current_network_access(&request) {
        let _ = events_tx
            .send(Err(format!("upload request failed: {}", err)))
            .await;
        return;
    }

    let progress_tx = events_tx.clone();
    let stop_rx_reader = stop_rx.clone();
    let reader_handle = tokio::task::spawn(async move {
        let mut uploaded: u64 = 0;
        let mut chunk = vec![0u8; UPLOAD_CHUNK_SIZE];
        loop {
            if *stop_rx_reader.borrow() {
                break;
            }
            let n = file
                .read(&mut chunk)
                .await
                .map_err(|e| format!("read upload file: {}", e))?;
            if n == 0 {
                break;
            }

            let bytes = Bytes::copy_from_slice(&chunk[..n]);
            uploaded = uploaded.saturating_add(n as u64);
            if body_tx.send(Ok(bytes)).await.is_err() {
                break;
            }

            let _ = progress_tx
                .try_send(Ok(UploadEvent::Progress {
                    uploaded_bytes: uploaded,
                    total_bytes,
                }))
                .ok();
        }
        Ok::<(), String>(())
    });

    let (net_abort_tx, net_abort_rx) = oneshot::channel::<()>();
    let mut stop_rx_net = stop_rx.clone();
    tokio::task::spawn(async move {
        loop {
            if *stop_rx_net.borrow() {
                let _ = net_abort_tx.send(());
                break;
            }
            if stop_rx_net.changed().await.is_err() {
                break;
            }
        }
    });

    let response =
        match send_request_with_timeout(request, 0, Some(net_abort_rx), options.timeouts()).await {
            Ok(resp) => resp,
            Err(e) => {
                let _ = events_tx
                    .send(Err(format!("upload request failed: {}", e)))
                    .await;
                return;
            }
        };

    match reader_handle.await {
        Err(join_err) => {
            let _ = events_tx
                .send(Err(format!("upload reader task failed: {}", join_err)))
                .await;
            return;
        }
        Ok(Err(err)) => {
            let _ = events_tx.send(Err(err)).await;
            return;
        }
        Ok(Ok(())) => {}
    }

    if *stop_rx.borrow() {
        let _ = events_tx.send(Err("upload aborted".to_string())).await;
        return;
    }

    let body = match collect_response_body(response.body).await {
        Ok(body) => body,
        Err(e) => {
            let _ = events_tx
                .send(Err(format!("read upload response body: {}", e)))
                .await;
            return;
        }
    };

    let event = UploadEvent::Success(UploadResponse {
        status: response.status,
        body,
    });
    let _ = events_tx.send(Ok(event)).await;
}

fn build_request(
    options: &UploadOptions,
    total_bytes: Option<u64>,
    body: BoxBody<Bytes, Error>,
) -> Result<HttpRequest<BoxBody<Bytes, Error>>, String> {
    let mut builder = HttpRequest::builder()
        .method(options.method.clone())
        .uri(&options.url)
        .header(header::ACCEPT, "*/*");
    if let Some(headers) = builder.headers_mut() {
        let user_agent = crate::get_user_agent();
        let user_agent = HeaderValue::from_str(&user_agent)
            .map_err(|e| format!("invalid user agent header: {}", e))?;
        headers.insert(header::USER_AGENT, user_agent);

        if let Some(content_type) = &options.content_type {
            let content_type = HeaderValue::from_str(content_type)
                .map_err(|e| format!("invalid content-type header: {}", e))?;
            headers.insert(header::CONTENT_TYPE, content_type);
        }

        if let Some(total) = total_bytes {
            let content_len = HeaderValue::from_str(&total.to_string())
                .map_err(|e| format!("invalid content-length header: {}", e))?;
            headers.insert(header::CONTENT_LENGTH, content_len);
        }

        for (name, value) in &options.headers {
            let name = HeaderName::from_bytes(name.as_bytes())
                .map_err(|e| format!("invalid upload header name '{}': {}", name, e))?;
            let value = HeaderValue::from_str(value)
                .map_err(|e| format!("invalid upload header '{}' value: {}", name, e))?;
            headers.insert(name, value);
        }
    }

    builder
        .body(body)
        .map_err(|e| format!("build upload request: {}", e))
}

async fn collect_response_body(body: HttpBody) -> Result<Bytes, String> {
    match body {
        HttpBody::Empty => Ok(Bytes::new()),
        HttpBody::Small(bytes) => Ok(bytes),
        HttpBody::Stream(mut rx) => {
            let mut out = Vec::new();
            while let Some(chunk) = rx.recv().await {
                let bytes = chunk?;
                out.extend_from_slice(&bytes);
            }
            Ok(Bytes::from(out))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use tokio_stream::StreamExt;

    // Pool starts lazily on first spawn/handle; nothing to do here.

    struct DenyExampleGuard;

    impl crate::http::NetworkAccessGuard for DenyExampleGuard {
        fn check_access(&self, uri: &crate::http::Uri) -> Result<(), crate::http::HttpError> {
            if uri.host() == Some("denied.example.com") {
                return Err(crate::http::HttpError::access_denied(
                    "network access denied",
                ));
            }
            Ok(())
        }
    }

    async fn spawn_upload_server() -> std::net::SocketAddr {
        use axum::Router;
        use axum::body::Bytes as AxumBytes;
        use axum::http::HeaderMap;
        use axum::routing::any;

        let app = Router::new().route(
            "/upload",
            any(
                |method: Method, headers: HeaderMap, body: AxumBytes| async move {
                    let len = body.len();
                    let tag = headers
                        .get("x-upload-tag")
                        .and_then(|v| v.to_str().ok())
                        .unwrap_or("-");
                    (
                        StatusCode::OK,
                        format!("method={},uploaded={},tag={}", method, len, tag),
                    )
                },
            ),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });
        addr
    }

    #[test]
    fn spawn_upload_reports_progress_and_success() {
        let _guard = crate::client::test_guard();
        let handle = crate::RongExecutor::global().handle();
        handle.block_on(async {
            let addr = spawn_upload_server().await;
            let path = std::env::temp_dir().join(format!(
                "rong_upload_test_{}.bin",
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .subsec_nanos()
            ));
            let payload = vec![7u8; 100 * 1024 + 77];
            tokio::fs::write(&path, &payload).await.unwrap();

            let options = UploadOptions::new(format!("http://{}/upload", addr), &path)
                .with_content_type("application/octet-stream")
                .with_header("x-upload-tag", "spawn")
                .with_connect_timeout(Duration::from_secs(1));
            let task = spawn_upload(options, None).expect("upload task should start");
            let mut stream = task.into_stream();

            let mut saw_progress = false;
            let mut success = None;
            while let Some(item) = stream.next().await {
                match item.expect("upload event should be ok") {
                    UploadEvent::Progress { uploaded_bytes, .. } => {
                        saw_progress = true;
                        assert!(uploaded_bytes > 0);
                    }
                    UploadEvent::Success(resp) => {
                        success = Some(resp);
                        break;
                    }
                }
            }

            assert!(saw_progress, "expected at least one progress event");
            let resp = success.expect("success event expected");
            assert_eq!(resp.status, StatusCode::OK);
            assert_eq!(
                resp.body,
                Bytes::from(format!("method=PUT,uploaded={},tag=spawn", payload.len()))
            );
            let _ = tokio::fs::remove_file(&path).await;
        });
    }

    #[test]
    fn upload_convenience_returns_response() {
        let _guard = crate::client::test_guard();
        let handle = crate::RongExecutor::global().handle();
        handle.block_on(async {
            let addr = spawn_upload_server().await;
            let path = std::env::temp_dir().join(format!(
                "rong_upload_direct_test_{}.bin",
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .subsec_nanos()
            ));
            let payload = vec![3u8; 4096];
            tokio::fs::write(&path, &payload).await.unwrap();

            let response = upload(
                UploadOptions::new(format!("http://{}/upload", addr), &path)
                    .with_method(Method::POST)
                    .with_header("x-upload-tag", "direct")
                    .with_content_type("application/octet-stream")
                    .with_request_timeout(Duration::from_secs(5))
                    .with_connect_timeout(Duration::from_secs(1)),
                None,
            )
            .await
            .expect("upload should succeed");

            assert_eq!(response.status, StatusCode::OK);
            assert_eq!(
                response.body,
                Bytes::from(format!("method=POST,uploaded={},tag=direct", payload.len()))
            );
            let _ = tokio::fs::remove_file(&path).await;
        });
    }

    #[test]
    fn scoped_network_access_guard_blocks_spawn_upload() {
        let handle = crate::RongExecutor::global().handle();
        handle.block_on(async {
            let path = std::env::temp_dir().join(format!(
                "rong_upload_denied_test_{}.bin",
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .subsec_nanos()
            ));
            tokio::fs::write(&path, b"denied").await.unwrap();

            let err = crate::http::scope_network_access_guard(Arc::new(DenyExampleGuard), async {
                upload(
                    UploadOptions::new("http://denied.example.com/upload", &path),
                    None,
                )
                .await
                .expect_err("upload should be denied")
            })
            .await;

            assert_eq!(err, "upload request failed: network access denied");
            let _ = tokio::fs::remove_file(&path).await;
        });
    }
}