lingxia-lxapp 0.4.3

LxApp (lightweight application) container and runtime for LingXia framework
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
use super::uri as lx_uri;
use crate::info;
use crate::plugin;
use crate::warn;
use base64::Engine;
use base64::engine::general_purpose;
use http::{Method, Request, Response, StatusCode, Uri};
use lingxia_platform::traits::app_runtime::AppRuntime;
use lingxia_webview::{SystemPipeReader, WebResourceResponse};
use rong_http as net;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use crate::error;
use crate::error::LxAppError;
use crate::lxapp::LxApp;
use crate::page::Page;

impl LxApp {
    /// Handler for lx:// scheme requests to access static app assets (images, CSS, JS, etc.)
    /// HTML files are handled separately through generate_page_html and load_data
    pub(crate) fn lingxia_handler(
        &self,
        page: &Page,
        req: Request<Vec<u8>>,
    ) -> Option<WebResourceResponse> {
        let uri = req.uri();
        match uri.host() {
            Some(lx_uri::HOST_PROXY) => {
                let target_uri = match Self::extract_proxy_target(uri) {
                    Some(target_uri) => target_uri,
                    None => {
                        return Some(self.create_error_response(
                            StatusCode::BAD_REQUEST,
                            "Invalid Proxy URL",
                            "Proxy URL must be lx://proxy/<base64-https-url>.",
                        ));
                    }
                };
                return self.handle_lingxia_proxy(target_uri);
            }
            Some(lx_uri::HOST_ASSETS) => {
                return self.handle_sdk_asset(uri);
            }
            Some(lx_uri::HOST_LXAPP)
            | Some(lx_uri::HOST_PLUGIN)
            | Some(lx_uri::HOST_USER_CACHE)
            | Some(lx_uri::HOST_USER_DATA) => {}
            Some(other) => {
                error!("Unknown lx host: {}", other).with_appid(self.appid.clone());
                return Some(self.create_error_response(
                    StatusCode::BAD_REQUEST,
                    "Unknown Host",
                    &format!("Unknown lx host '{}'.", other),
                ));
            }
            None => {
                error!("lx request missing host: {}", uri).with_appid(self.appid.clone());
                return Some(self.create_error_response(
                    StatusCode::BAD_REQUEST,
                    "Invalid URL",
                    "The URL is missing a host component and cannot be processed.",
                ));
            }
        }

        let asset_path = match self.resolve_lx_uri(page, uri) {
            Ok(path) => path,
            Err(e) => {
                error!("resolve_lx_uri failed for {}: {}", uri.path(), e)
                    .with_appid(self.appid.clone());
                return Some(self.create_error_response(
                    StatusCode::NOT_FOUND,
                    "Asset Not Found",
                    &format!("The requested asset '{}' could not be found.", uri.path()),
                ));
            }
        };

        let metadata = match fs::metadata(&asset_path) {
            Ok(meta) => meta,
            Err(e) => {
                error!(
                    "Failed to read asset metadata: {} - {}",
                    asset_path.display(),
                    e
                )
                .with_appid(self.appid.clone());
                return Some(self.create_error_response(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "Asset Error",
                    "Failed to read asset metadata.",
                ));
            }
        };

        let file_len = metadata.len();
        let mime_type = Self::infer_mime_type(uri.path());

        let mut builder = Response::builder()
            .status(StatusCode::OK)
            .header("Content-Type", mime_type)
            .header("Access-Control-Allow-Origin", "null");

        if let Ok(value) = http::HeaderValue::from_str(&file_len.to_string()) {
            builder = builder.header("Content-Length", value);
        }

        let response = builder.body(()).unwrap_or_else(|_| {
            Response::builder()
                .status(StatusCode::INTERNAL_SERVER_ERROR)
                .body(())
                .expect("Failed to build fallback empty response")
        });

        let (parts, _) = response.into_parts();
        self.touch_user_cache_access_time(&asset_path);
        Some((parts, asset_path).into())
    }

    fn handle_sdk_asset(&self, uri: &Uri) -> Option<WebResourceResponse> {
        let path = uri.path().trim_start_matches('/');
        if path.is_empty() {
            return Some(self.create_error_response(
                StatusCode::BAD_REQUEST,
                "Invalid Asset Path",
                "Asset path is empty.",
            ));
        }
        if lx_uri::has_invalid_segment(path) {
            return Some(self.create_error_response(
                StatusCode::BAD_REQUEST,
                "Invalid Asset Path",
                "Asset path contains invalid segments.",
            ));
        }

        let mut reader = match self.runtime.read_asset(path) {
            Ok(reader) => reader,
            Err(e) => {
                error!("Failed to read sdk asset {}: {}", path, e).with_appid(self.appid.clone());
                return Some(self.create_error_response(
                    StatusCode::NOT_FOUND,
                    "Asset Not Found",
                    &format!("The requested asset '{}' could not be found.", path),
                ));
            }
        };

        let mut data = Vec::new();
        if let Err(e) = reader.read_to_end(&mut data) {
            error!("Failed to read sdk asset {}: {}", path, e).with_appid(self.appid.clone());
            return Some(self.create_error_response(
                StatusCode::INTERNAL_SERVER_ERROR,
                "Asset Read Error",
                "Failed to read asset data.",
            ));
        }

        let mime_type = Self::infer_mime_type(path);
        let mut builder = Response::builder()
            .status(StatusCode::OK)
            .header("Content-Type", mime_type)
            .header("Access-Control-Allow-Origin", "null");

        if let Ok(value) = http::HeaderValue::from_str(&data.len().to_string()) {
            builder = builder.header("Content-Length", value);
        }

        let response = builder.body(()).unwrap_or_else(|_| {
            Response::builder()
                .status(StatusCode::INTERNAL_SERVER_ERROR)
                .body(())
                .expect("Failed to build fallback empty response")
        });

        let (parts, _) = response.into_parts();
        Some((parts, data).into())
    }

    fn handle_lingxia_proxy(&self, target_uri: Uri) -> Option<WebResourceResponse> {
        let target_str = target_uri.to_string();

        //info!("lingxia_proxy: forwarding request to {}", target_str).with_appid(self.appid.clone());

        if target_uri.scheme_str() != Some("https") {
            return Some(self.create_error_response(
                StatusCode::BAD_REQUEST,
                "Unsupported Scheme",
                "Only https URLs are allowed in proxy requests.",
            ));
        }

        let proxy_request = match Request::builder()
            .method(Method::GET)
            .uri(target_uri)
            .body(Vec::new())
        {
            Ok(req) => req,
            Err(e) => {
                error!(
                    "lingxia_proxy: failed to build proxy request {}: {}",
                    target_str, e
                )
                .with_appid(self.appid.clone());

                return Some(self.create_error_response(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "Proxy Request Error",
                    &format!("Failed to prepare proxy request: {}", e),
                ));
            }
        };

        self.https_handler(proxy_request)
    }

    fn extract_proxy_target(uri: &Uri) -> Option<Uri> {
        if uri.host() != Some(lx_uri::HOST_PROXY) {
            return None;
        }

        let encoded = uri.path().trim_start_matches('/');
        if encoded.is_empty() {
            return None;
        }

        let decoded = general_purpose::URL_SAFE_NO_PAD
            .decode(encoded)
            .or_else(|_| general_purpose::URL_SAFE.decode(encoded))
            .ok()?;
        let decoded_str = std::str::from_utf8(&decoded).ok()?.trim();
        if !decoded_str.starts_with("https://") {
            return None;
        }

        Uri::from_str(decoded_str).ok()
    }

    fn resolve_lx_uri(&self, page: &Page, uri: &Uri) -> Result<PathBuf, LxAppError> {
        match uri.host() {
            Some(lx_uri::HOST_LXAPP) => self.resolve_lxapp_uri(page, uri),
            Some(lx_uri::HOST_PLUGIN) => self.resolve_plugin_uri(page, uri),
            Some(lx_uri::HOST_USER_CACHE) => self.resolve_user_dir_uri(uri, &self.user_cache_dir),
            Some(lx_uri::HOST_USER_DATA) => self.resolve_user_dir_uri(uri, &self.user_data_dir),
            _ => Err(LxAppError::ResourceNotFound(uri.to_string())),
        }
    }

    fn resolve_user_dir_uri(&self, uri: &Uri, base_dir: &Path) -> Result<PathBuf, LxAppError> {
        let decoded_path = lx_uri::decode_lx_path(uri.path());
        let rel = decoded_path.trim_matches('/');
        if rel.is_empty()
            || lx_uri::has_invalid_segment(rel)
            || rel.contains(':')
            || rel.contains('\\')
        {
            return Err(LxAppError::ResourceNotFound(uri.to_string()));
        }

        let absolute = base_dir.join(rel);
        let absolute_str = absolute.to_string_lossy();
        self.resolve_accessible_path(absolute_str.as_ref())
    }

    fn resolve_lxapp_uri(&self, page: &Page, uri: &Uri) -> Result<PathBuf, LxAppError> {
        let decoded_path = lx_uri::decode_lx_path(uri.path());
        if Path::new(&decoded_path).is_absolute() {
            if let Ok(local_path) = self.resolve_accessible_path(&decoded_path) {
                return Ok(local_path);
            }
        }
        let raw_path = decoded_path.trim_start_matches('/');
        // Support both:
        // - lx://lxapp/<appid>/<path> (explicit)
        // - lx://lxapp/<path>         (implicit appid = current page's appid)
        //
        // The implicit form enables common web patterns like <img src="/public/logo.png">,
        // which resolve (via URL rules) to lx://lxapp/public/logo.png (appid omitted).
        let (first, rest) = raw_path.split_once('/').unwrap_or(("", raw_path));
        let normalized = if first == self.appid.as_str() {
            rest.trim_matches('/')
        } else {
            raw_path.trim_matches('/')
        };
        if normalized.is_empty() {
            return Err(LxAppError::ResourceNotFound(uri.to_string()));
        }
        if lx_uri::has_invalid_segment(normalized) {
            return Err(LxAppError::ResourceNotFound(uri.to_string()));
        }

        if let Ok(local_path) = self.resolve_accessible_path(normalized) {
            return Ok(local_path);
        }

        if let Some(stripped) =
            lx_uri::strip_base_dir(page, normalized, lx_uri::HOST_LXAPP, &self.appid)
        {
            if let Ok(local_path) = self.resolve_accessible_path(&stripped) {
                return Ok(local_path);
            }
        }

        let absolute_path = format!("/{}", normalized);
        if let Ok(local_path) = self.resolve_accessible_path(&absolute_path) {
            return Ok(local_path);
        }

        Err(LxAppError::ResourceNotFound(uri.to_string()))
    }

    fn resolve_plugin_uri(&self, page: &Page, uri: &Uri) -> Result<PathBuf, LxAppError> {
        let decoded_path = lx_uri::decode_lx_path(uri.path());
        let raw_path = decoded_path.trim_start_matches('/');
        let (plugin_name, rest) = raw_path
            .split_once('/')
            .ok_or_else(|| LxAppError::ResourceNotFound(uri.to_string()))?;

        let normalized = rest.trim_matches('/');
        if normalized.is_empty() {
            return Err(LxAppError::ResourceNotFound(uri.to_string()));
        }
        if lx_uri::has_invalid_segment(normalized) {
            return Err(LxAppError::ResourceNotFound(uri.to_string()));
        }

        let mut last_err = match plugin::resolve_plugin_resource_path(
            &self.runtime,
            &self.config.plugins,
            plugin_name,
            normalized,
        ) {
            Ok(local_path) => return Ok(local_path),
            Err(e) => e,
        };

        if let Some(stripped) =
            lx_uri::strip_base_dir(page, normalized, lx_uri::HOST_PLUGIN, plugin_name)
        {
            match plugin::resolve_plugin_resource_path(
                &self.runtime,
                &self.config.plugins,
                plugin_name,
                &stripped,
            ) {
                Ok(local_path) => return Ok(local_path),
                Err(e) => last_err = e,
            }
        }

        Err(last_err)
    }

    /// Handler for HTTPS requests:
    /// - Only accepts GET; other methods are rejected
    /// - All GETs to allowed domains are treated as downloadable resources
    ///   with per-app cache; miss -> stream via system pipe while saving
    pub(crate) fn https_handler(&self, req: Request<Vec<u8>>) -> Option<WebResourceResponse> {
        let uri = req.uri();

        // Check if the domain is allowed
        if let Some(host) = uri.host() {
            // First check domain whitelist
            if !self
                .state
                .lock()
                .unwrap()
                .network_security
                .is_domain_allowed(host)
            {
                return Some(self.create_error_response(
                    StatusCode::FORBIDDEN,
                    "Domain Access Denied",
                    &format!(
                        "Access to domain '{}' is not allowed by the security policy.",
                        host
                    ),
                ));
            }

            // Only accept GET; reject others
            if req.method() != http::Method::GET {
                return Some(self.create_error_response(
                    StatusCode::METHOD_NOT_ALLOWED,
                    "Method Not Allowed",
                    &format!(
                        "Only GET is allowed in WebView: method={} {}",
                        req.method(),
                        uri
                    ),
                ));
            }

            let url_str = uri.to_string();
            // Decide extension from URL or query
            let ext_opt = url_ext_from_uri(uri);
            let ext = ext_opt.as_deref().unwrap_or("bin");
            let cache = match self.cache() {
                Ok(c) => c,
                Err(e) => {
                    return Some(self.create_error_response(
                        StatusCode::INTERNAL_SERVER_ERROR,
                        "Cache Not Ready",
                        &format!("Cache unavailable: {}", e),
                    ));
                }
            };

            match cache.resolve_path_with_ext(&url_str, ext) {
                crate::cache::ResolveResult::Exists(file_path) => {
                    info!(
                        "https cache hit -> url={}, file={}",
                        url_str,
                        file_path.display()
                    )
                    .with_appid(self.appid.clone());
                    // Cached: serve file path
                    let mime_type = ext_opt
                        .as_deref()
                        .map(Self::infer_mime_type_ext)
                        .unwrap_or_else(|| Self::infer_mime_type(uri.path()));
                    let builder = http::Response::builder()
                        .status(StatusCode::OK)
                        .header("Content-Type", mime_type)
                        .header("Access-Control-Allow-Origin", "null");
                    let response = builder.body(()).unwrap_or_else(|_| {
                        http::Response::builder()
                            .status(StatusCode::INTERNAL_SERVER_ERROR)
                            .body(())
                            .expect("Failed to build cached file response")
                    });
                    let (parts, _) = response.into_parts();
                    self.touch_user_cache_access_time(&file_path);
                    return Some((parts, file_path).into());
                }
                crate::cache::ResolveResult::NonExists(dest_path) => {
                    #[cfg(unix)]
                    {
                        // Coordinate in-flight downloads using a file lock next to cache destination.
                        let hash_id = dest_path
                            .file_stem()
                            .and_then(|s| s.to_str())
                            .unwrap_or_default()
                            .to_string();
                        let lock_path = dest_path
                            .parent()
                            .unwrap_or_else(|| std::path::Path::new("."))
                            .join(format!("{}.lock", hash_id));
                        let part_path = dest_path.with_extension("part");

                        let try_acquire_lock = || {
                            fs::OpenOptions::new()
                                .write(true)
                                .create_new(true)
                                .open(&lock_path)
                                .is_ok()
                        };

                        let mut acquired_lock = try_acquire_lock();

                        if !acquired_lock {
                            // Self-heal: stale lock/part can be left behind when the process is killed
                            // mid-download (common during dev). We treat a lock as stale when:
                            // - `.part` doesn't exist OR hasn't been modified recently, and
                            // - the lock itself is older than a small threshold.
                            const STALE_AFTER: Duration = Duration::from_secs(60);
                            let now = SystemTime::now();

                            let part_recent = fs::metadata(&part_path)
                                .and_then(|m| m.modified())
                                .ok()
                                .and_then(|t| now.duration_since(t).ok())
                                .map(|age| age <= STALE_AFTER)
                                .unwrap_or(false);

                            let lock_old = fs::metadata(&lock_path)
                                .and_then(|m| m.modified())
                                .ok()
                                .and_then(|t| now.duration_since(t).ok())
                                .map(|age| age > STALE_AFTER)
                                .unwrap_or(false);

                            if lock_old && !part_recent {
                                let _ = fs::remove_file(&lock_path);
                                let _ = fs::remove_file(&part_path);
                                warn!(
                                    "https cache: removed stale lock/part -> url={}, dest={}",
                                    url_str,
                                    dest_path.display()
                                )
                                .with_appid(self.appid.clone());
                                acquired_lock = try_acquire_lock();
                            }
                        }

                        if !acquired_lock {
                            info!(
                                "https cache: in-flight lock exists, stream without caching -> url={}",
                                url_str
                            )
                            .with_appid(self.appid.clone());
                            // Another download is in progress. Serve existing cache file if present,
                            // otherwise stream a separate download without touching the cache path.
                            if dest_path.exists() {
                                let mime_type = ext_opt
                                    .as_deref()
                                    .map(Self::infer_mime_type_ext)
                                    .unwrap_or_else(|| Self::infer_mime_type(uri.path()));
                                let builder = http::Response::builder()
                                    .status(StatusCode::OK)
                                    .header("Content-Type", mime_type)
                                    .header("Access-Control-Allow-Origin", "null");
                                let response = builder.body(()).unwrap_or_else(|_| {
                                    http::Response::builder()
                                        .status(StatusCode::INTERNAL_SERVER_ERROR)
                                        .body(())
                                        .expect("Failed to build cached file response")
                                });
                                let (parts, _) = response.into_parts();
                                self.touch_user_cache_access_time(&dest_path);
                                return Some((parts, dest_path).into());
                            }

                            let unique_suffix = SystemTime::now()
                                .duration_since(UNIX_EPOCH)
                                .map(|d| d.as_millis())
                                .unwrap_or(0);
                            let tmp_dest_path = dest_path
                                .parent()
                                .unwrap_or_else(|| std::path::Path::new("."))
                                .join(format!("{}.stream.{}", hash_id, unique_suffix));
                            let tmp_part_path = tmp_dest_path.with_extension("part");

                            match create_pipe_sink() {
                                Ok((reader, sink)) => {
                                    let mime_type = ext_opt
                                        .as_deref()
                                        .map(Self::infer_mime_type_ext)
                                        .unwrap_or_else(|| Self::infer_mime_type(uri.path()));
                                    let builder = http::Response::builder()
                                        .status(StatusCode::OK)
                                        .header("Content-Type", mime_type)
                                        .header("Access-Control-Allow-Origin", "null");

                                    let response = builder.body(()).unwrap_or_else(|_| {
                                        http::Response::builder()
                                            .status(StatusCode::INTERNAL_SERVER_ERROR)
                                            .body(())
                                            .expect("Failed to build pipe response")
                                    });
                                    let (parts, _) = response.into_parts();

                                    match net::request_download(
                                        url_str.clone(),
                                        tmp_dest_path.clone(),
                                        None,
                                        Some(sink),
                                    ) {
                                        Ok(rx) => {
                                            let cleanup_tmp_dest_path = tmp_dest_path.clone();
                                            let cleanup_tmp_part_path = tmp_part_path.clone();
                                            let spawned = rong::bg::spawn(async move {
                                                let _ = rx.await;
                                                let _ = fs::remove_file(&cleanup_tmp_dest_path);
                                                let _ = fs::remove_file(&cleanup_tmp_part_path);
                                            });
                                            if spawned.is_err() {
                                                let _ = fs::remove_file(&tmp_dest_path);
                                                let _ = fs::remove_file(&tmp_part_path);
                                            }
                                            return Some((parts, reader).into());
                                        }
                                        Err(e) => {
                                            error!(
                                                "https cache: failed to start streaming download: url={}, err={}",
                                                url_str, e
                                            )
                                            .with_appid(self.appid.clone());
                                            return Some(self.create_error_response(
                                                StatusCode::BAD_GATEWAY,
                                                "Download Failed",
                                                &format!("Failed to start download: {}", e),
                                            ));
                                        }
                                    }
                                }
                                Err(e) => {
                                    error!(
                                        "https cache: failed to create pipe sink: url={}, err={}",
                                        url_str, e
                                    )
                                    .with_appid(self.appid.clone());
                                    return Some(self.create_error_response(
                                        StatusCode::INTERNAL_SERVER_ERROR,
                                        "Pipe Creation Failed",
                                        &e,
                                    ));
                                }
                            }
                        }

                        match create_pipe_sink() {
                            Ok((reader, sink)) => {
                                // info!(
                                //     "https_handler: cache miss, start pipe download -> {}",
                                //     dest_path.display()
                                // )
                                // .with_appid(self.appid.clone());

                                let mime_type = ext_opt
                                    .as_deref()
                                    .map(Self::infer_mime_type_ext)
                                    .unwrap_or_else(|| Self::infer_mime_type(uri.path()));
                                let builder = http::Response::builder()
                                    .status(StatusCode::OK)
                                    .header("Content-Type", mime_type)
                                    .header("Access-Control-Allow-Origin", "null");

                                let response = builder.body(()).unwrap_or_else(|_| {
                                    http::Response::builder()
                                        .status(StatusCode::INTERNAL_SERVER_ERROR)
                                        .body(())
                                        .expect("Failed to build pipe response")
                                });
                                let (parts, _) = response.into_parts();

                                match net::request_download(
                                    url_str.clone(),
                                    dest_path.clone(),
                                    None,
                                    Some(sink),
                                ) {
                                    Ok(rx) => {
                                        let cleanup_lock_path = lock_path.clone();
                                        let cleanup_part_path = part_path.clone();
                                        let spawned = rong::bg::spawn(async move {
                                            let res = rx.await.unwrap_or_else(|_| {
                                                Err("download dropped".to_string())
                                            });
                                            let _ = fs::remove_file(&cleanup_lock_path);
                                            if res.is_err() {
                                                let _ = fs::remove_file(&cleanup_part_path);
                                            }
                                        });
                                        if spawned.is_err() {
                                            let _ = fs::remove_file(&lock_path);
                                            let _ = fs::remove_file(&part_path);
                                        }
                                        info!(
                                            "https cache: streaming via pipe -> url={}, dest={}",
                                            url_str,
                                            dest_path.display()
                                        )
                                        .with_appid(self.appid.clone());
                                        return Some((parts, reader).into());
                                    }
                                    Err(e) => {
                                        let _ = fs::remove_file(&lock_path);
                                        let _ = fs::remove_file(&part_path);
                                        error!(
                                            "https cache: failed to start download: url={}, err={}",
                                            url_str, e
                                        )
                                        .with_appid(self.appid.clone());
                                        return Some(self.create_error_response(
                                            StatusCode::BAD_GATEWAY,
                                            "Download Failed",
                                            &format!("Failed to start download: {}", e),
                                        ));
                                    }
                                }
                            }
                            Err(e) => {
                                let _ = fs::remove_file(&lock_path);
                                error!(
                                    "https cache: failed to create pipe sink: url={}, err={}",
                                    url_str, e
                                )
                                .with_appid(self.appid.clone());
                                return Some(self.create_error_response(
                                    StatusCode::INTERNAL_SERVER_ERROR,
                                    "Pipe Creation Failed",
                                    &e,
                                ));
                            }
                        }
                    }
                    #[cfg(not(unix))]
                    {
                        // Fallback: no pipe support here; return 501
                        warn!(
                            "https_handler: pipe unsupported on this platform for {}",
                            uri
                        )
                        .with_appid(self.appid.clone());
                        return Some(self.create_error_response(
                            StatusCode::NOT_IMPLEMENTED,
                            "Pipe Unsupported",
                            "Streaming via pipe is not supported on this platform.",
                        ));
                    }
                }
            }
        }

        // URI doesn't have a host component
        Some(self.create_error_response(
            StatusCode::BAD_REQUEST,
            "Invalid URL",
            "The URL is missing a host component and cannot be processed.",
        ))
    }

    fn infer_mime_type(path: &str) -> &'static str {
        if path.ends_with(".js") {
            "application/javascript"
        } else if path.ends_with(".css") {
            "text/css"
        } else if path.ends_with(".png") {
            "image/png"
        } else if path.ends_with(".jpg") || path.ends_with(".jpeg") {
            "image/jpeg"
        } else if path.ends_with(".gif") {
            "image/gif"
        } else if path.ends_with(".svg") {
            "image/svg+xml"
        } else if path.ends_with(".webp") {
            "image/webp"
        } else if path.ends_with(".ico") {
            "image/x-icon"
        } else if path.ends_with(".json") {
            "application/json"
        } else if path.ends_with(".woff") {
            "font/woff"
        } else if path.ends_with(".woff2") {
            "font/woff2"
        } else if path.ends_with(".ttf") {
            "font/ttf"
        } else if path.ends_with(".mp3") {
            "audio/mpeg"
        } else if path.ends_with(".wav") {
            "audio/wav"
        } else if path.ends_with(".mp4") {
            "video/mp4"
        } else {
            "application/octet-stream"
        }
    }

    fn infer_mime_type_ext(ext: &str) -> &'static str {
        match ext.to_ascii_lowercase().as_str() {
            "js" => "application/javascript",
            "css" => "text/css",
            "png" => "image/png",
            "jpg" | "jpeg" => "image/jpeg",
            "gif" => "image/gif",
            "svg" => "image/svg+xml",
            "webp" => "image/webp",
            "ico" => "image/x-icon",
            "json" => "application/json",
            "woff" => "font/woff",
            "woff2" => "font/woff2",
            "ttf" => "font/ttf",
            "mp3" => "audio/mpeg",
            "wav" => "audio/wav",
            "mp4" => "video/mp4",
            _ => "application/octet-stream",
        }
    }

    fn touch_user_cache_access_time(&self, path: &Path) {
        if path.starts_with(&self.user_cache_dir) && path.exists() {
            crate::cache::touch_access_time(path);
        }
    }

    fn sanitize_for_filename(value: &str) -> String {
        value
            .chars()
            .map(|c| match c {
                'a'..='z' | 'A'..='Z' | '0'..='9' => c,
                _ => '_',
            })
            .collect()
    }
    /// Create a simple centered error response
    pub(crate) fn create_error_response(
        &self,
        status: StatusCode,
        title: &str,
        message: &str,
    ) -> WebResourceResponse {
        let html_content = format!(
            r#"<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{}</title>
    <style>
        body {{ font-family: system-ui, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; display: flex; justify-content: center; align-items: center; min-height: 100vh; }}
        .error {{ background: white; border-radius: 8px; padding: 40px; text-align: center; max-width: 500px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
        .code {{ font-size: 48px; font-weight: bold; color: #e74c3c; margin-bottom: 16px; }}
        .title {{ font-size: 24px; font-weight: 600; color: #2c3e50; margin-bottom: 16px; }}
        .message {{ font-size: 16px; color: #7f8c8d; line-height: 1.5; }}
    </style>
</head>
<body>
    <div class="error">
        <div class="code">{}</div>
        <div class="title">{}</div>
        <div class="message">{}</div>
    </div>
</body>
</html>"#,
            title,
            status.as_u16(),
            title,
            message
        );

        let mut target_dir = self.user_cache_dir.join("webview_errors");
        if let Err(e) = fs::create_dir_all(&target_dir) {
            error!("Failed to prepare error directory: {}", e).with_appid(self.appid.clone());
            target_dir = std::env::temp_dir().join("lingxia-webview-errors");
            let _ = fs::create_dir_all(&target_dir);
        }

        let file_name = format!(
            "{}_{}.html",
            status.as_u16(),
            Self::sanitize_for_filename(title)
        );
        let mut file_path = target_dir.join(file_name);

        if let Err(e) = fs::write(&file_path, html_content.as_bytes()) {
            error!(
                "Failed to write error response file ({}): {}",
                file_path.display(),
                e
            )
            .with_appid(self.appid.clone());
            let unique_suffix = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis())
                .unwrap_or(0);
            file_path = target_dir.join(format!(
                "{}_{}_{}.html",
                status.as_u16(),
                Self::sanitize_for_filename(title),
                unique_suffix
            ));
            let _ = fs::write(&file_path, html_content.as_bytes());
        }

        let file_len = fs::metadata(&file_path)
            .map(|meta| meta.len())
            .unwrap_or_else(|_| html_content.len() as u64);

        let mut builder = Response::builder()
            .status(status)
            .header("Content-Type", "text/html; charset=utf-8");

        if let Ok(value) = http::HeaderValue::from_str(&file_len.to_string()) {
            builder = builder.header("Content-Length", value);
        }

        let response = builder.body(()).unwrap_or_else(|_| {
            Response::builder()
                .status(StatusCode::INTERNAL_SERVER_ERROR)
                .body(())
                .expect("Failed to build fallback error response")
        });

        let (parts, _) = response.into_parts();
        (parts, file_path).into()
    }
}

fn url_ext_from_uri(uri: &Uri) -> Option<String> {
    // Try path first
    if let Some(ext) = ext_from_segment(uri.path()) {
        return Some(ext.to_string());
    }
    // Then try query (e.g., id=...UHD.jpg)
    if let Some(q) = uri.query() {
        let lower = q.to_ascii_lowercase();
        if let Some(pos) = lower.rfind('.') {
            let tail = &lower[pos + 1..];
            let end: String = tail
                .chars()
                .take_while(|c| c.is_ascii_alphanumeric())
                .collect();
            if !end.is_empty() && end.len() <= 8 {
                return Some(end);
            }
        }
    }
    None
}

fn ext_from_segment(path: &str) -> Option<&str> {
    let seg = path.rsplit('/').next().unwrap_or(path);
    let dot = seg.rfind('.')?;
    let ext = &seg[dot + 1..];
    if !ext.is_empty() && ext.len() <= 8 {
        Some(ext)
    } else {
        None
    }
}

#[cfg(unix)]
struct PipeBodySink {
    writer: std::os::unix::net::UnixStream,
}

#[cfg(unix)]
impl net::BodySink for PipeBodySink {
    fn write(&mut self, chunk: &[u8]) -> Result<(), String> {
        use std::io::Write;
        self.writer
            .write_all(chunk)
            .map_err(|e| format!("pipe write: {}", e))
    }

    fn close(&mut self, _result: &Result<(), String>) {
        use std::net::Shutdown;
        let _ = self.writer.shutdown(Shutdown::Write);
    }
}

#[cfg(unix)]
fn create_pipe_sink() -> Result<(SystemPipeReader, Box<dyn net::BodySink + Send>), String> {
    use std::os::fd::IntoRawFd;
    use std::os::unix::net::UnixStream;

    let (read_end, write_end) = UnixStream::pair().map_err(|e| format!("pipe: {}", e))?;
    let read_fd = read_end.into_raw_fd();
    let reader = unsafe { SystemPipeReader::from_raw_fd(read_fd) };
    let sink: Box<dyn net::BodySink + Send> = Box::new(PipeBodySink { writer: write_end });
    Ok((reader, sink))
}