forked from denoland/deno_cache_dir
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
1366 lines (1254 loc) · 38.4 KB
/
mod.rs
File metadata and controls
1366 lines (1254 loc) · 38.4 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
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
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018-2025 the Deno authors. MIT license.
use std::borrow::Cow;
use std::collections::HashMap;
use std::io::Read;
use std::path::Path;
use std::path::PathBuf;
use std::time::SystemTime;
use boxed_error::Boxed;
use data_url::DataUrl;
use deno_error::JsError;
use deno_media_type::MediaType;
use deno_path_util::url_to_file_path;
use http::header;
use http::header::ACCEPT;
use http::header::AUTHORIZATION;
use http::header::IF_NONE_MATCH;
use http::header::LOCATION;
use log::debug;
use sys_traits::FsFileMetadata;
use sys_traits::FsMetadataValue;
use sys_traits::FsOpen;
use sys_traits::OpenOptions;
use sys_traits::SystemTimeNow;
use thiserror::Error;
use url::Url;
use self::http_util::CacheSemantics;
use crate::CacheEntry;
use crate::CacheReadFileError;
use crate::Checksum;
use crate::ChecksumIntegrityError;
use crate::cache::HttpCacheRc;
use crate::common::HeadersMap;
use crate::sync::MaybeSend;
use crate::sync::MaybeSync;
mod auth_tokens;
mod http_util;
pub use auth_tokens::AuthDomain;
pub use auth_tokens::AuthToken;
pub use auth_tokens::AuthTokenData;
pub use auth_tokens::AuthTokens;
pub use http::HeaderMap;
pub use http::HeaderName;
pub use http::HeaderValue;
pub use http::StatusCode;
/// Indicates how cached source files should be handled.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum CacheSetting {
/// Only the cached files should be used. Any files not in the cache will
/// error. This is the equivalent of `--cached-only` in the CLI.
Only,
/// No cached source files should be used, and all files should be reloaded.
/// This is the equivalent of `--reload` in the CLI.
ReloadAll,
/// Only some cached resources should be used. This is the equivalent of
/// `--reload=jsr:@std/http/file-server` or
/// `--reload=jsr:@std/http/file-server,jsr:@std/assert/assert-equals`.
ReloadSome(Vec<String>),
/// The usability of a cached value is determined by analyzing the cached
/// headers and other metadata associated with a cached response, reloading
/// any cached "non-fresh" cached responses.
RespectHeaders,
/// The cached source files should be used for local modules. This is the
/// default behavior of the CLI.
Use,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum FileOrRedirect {
File(File),
Redirect(Url),
}
impl FileOrRedirect {
fn from_deno_cache_entry(
url: &Url,
cache_entry: CacheEntry,
) -> Result<Self, RedirectResolutionError> {
if let Some(redirect_to) = cache_entry.metadata.headers.get("location") {
let redirect =
url
.join(redirect_to)
.map_err(|source| RedirectResolutionError {
url: url.clone(),
location: redirect_to.clone(),
source,
})?;
Ok(FileOrRedirect::Redirect(redirect))
} else {
Ok(FileOrRedirect::File(File {
url: url.clone(),
mtime: None,
maybe_headers: Some(cache_entry.metadata.headers),
#[allow(clippy::disallowed_types)] // ok for source
source: std::sync::Arc::from(cache_entry.content),
loaded_from: LoadedFrom::Cache,
}))
}
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum CachedOrRedirect {
Cached,
Redirect(Url),
}
impl From<FileOrRedirect> for CachedOrRedirect {
fn from(value: FileOrRedirect) -> Self {
match value {
FileOrRedirect::File(_) => CachedOrRedirect::Cached,
FileOrRedirect::Redirect(url) => CachedOrRedirect::Redirect(url),
}
}
}
#[allow(clippy::disallowed_types)] // ok for source
type FileSource = std::sync::Arc<[u8]>;
/// A structure representing a source file.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct File {
/// The _final_ specifier for the file. The requested specifier and the final
/// specifier maybe different for remote files that have been redirected.
pub url: Url,
pub mtime: Option<SystemTime>,
pub maybe_headers: Option<HashMap<String, String>>,
/// The source of the file.
pub source: FileSource,
/// Where the file was loaded from.
pub loaded_from: LoadedFrom,
}
#[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum LoadedFrom {
/// The module was loaded from a remote source.
Remote,
/// The module was loaded from a local source.
Local,
/// The module was loaded from a cache for remote sources.
Cache,
/// The source of the module is unknown.
Unknown,
}
impl File {
pub fn resolve_media_type_and_charset(&self) -> (MediaType, Option<&str>) {
deno_media_type::resolve_media_type_and_charset_from_content_type(
&self.url,
self
.maybe_headers
.as_ref()
.and_then(|h| h.get("content-type"))
.map(|v| v.as_str()),
)
}
}
#[allow(clippy::disallowed_types)]
pub type MemoryFilesRc = crate::sync::MaybeArc<dyn MemoryFiles>;
pub trait MemoryFiles: std::fmt::Debug + MaybeSend + MaybeSync {
fn get(&self, url: &Url) -> Option<File>;
}
/// Implementation of `MemoryFiles` that always returns `None`.
#[derive(Debug, Clone, Default)]
pub struct NullMemoryFiles;
impl MemoryFiles for NullMemoryFiles {
fn get(&self, _url: &Url) -> Option<File> {
None
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum SendResponse {
NotModified,
Redirect(HeaderMap),
Success(HeaderMap, Vec<u8>),
}
#[derive(Debug)]
pub enum SendError {
Failed(Box<dyn std::error::Error + Send + Sync>),
NotFound,
StatusCode(http::StatusCode),
}
#[derive(Debug, Error, JsError)]
#[class(inherit)]
#[error("Failed resolving redirect from '{url}' to '{location}'.")]
pub struct RedirectResolutionError {
pub url: Url,
pub location: String,
#[source]
#[inherit]
pub source: url::ParseError,
}
#[derive(Debug, Error, JsError)]
#[class(inherit)]
#[error("Unable to decode data url.")]
pub struct DataUrlDecodeError {
#[source]
source: DataUrlDecodeSourceError,
}
#[derive(Debug, Error, JsError)]
#[class(uri)]
pub enum DataUrlDecodeSourceError {
#[error(transparent)]
DataUrl(data_url::DataUrlError),
#[error(transparent)]
InvalidBase64(data_url::forgiving_base64::InvalidBase64),
}
#[derive(Debug, Error, JsError)]
#[class(inherit)]
#[error("Failed reading cache entry for '{url}'.")]
pub struct CacheReadError {
pub url: Url,
#[source]
#[inherit]
pub source: std::io::Error,
}
#[derive(Debug, Error, JsError)]
#[class(generic)]
#[error("Failed reading location header for '{}'{}", .request_url, .maybe_location.as_ref().map(|location| format!(" to '{}'", location)).unwrap_or_default())]
pub struct RedirectHeaderParseError {
pub request_url: Url,
pub maybe_location: Option<String>,
#[source]
pub maybe_source: Option<Box<dyn std::error::Error + Send + Sync>>,
}
#[derive(Debug, Error, JsError)]
#[class(inherit)]
#[error("Import '{url}' failed.")]
pub struct FailedReadingLocalFileError {
pub url: Url,
#[source]
#[inherit]
pub source: std::io::Error,
}
#[derive(Debug, Error, JsError)]
#[class("Http")]
#[error("Fetch '{0}' failed, too many redirects.")]
pub struct TooManyRedirectsError(pub Url);
// this message list additional `npm` and `jsr` schemes, but they should actually be handled
// before `file_fetcher.rs` APIs are even hit.
#[derive(Debug, Error, JsError)]
#[class(type)]
#[error(
"Unsupported scheme \"{scheme}\" for module \"{url}\". Supported schemes:\n - \"blob\"\n - \"data\"\n - \"file\"\n - \"http\"\n - \"https\"\n - \"jsr\"\n - \"npm\""
)]
pub struct UnsupportedSchemeError {
pub scheme: String,
pub url: Url,
}
/// Gets if the provided scheme was valid.
pub fn is_valid_scheme(scheme: &str) -> bool {
matches!(
scheme,
"blob" | "data" | "file" | "http" | "https" | "jsr" | "npm"
)
}
#[derive(Debug, Boxed, JsError)]
pub struct FetchNoFollowError(pub Box<FetchNoFollowErrorKind>);
#[derive(Debug, Error, JsError)]
pub enum FetchNoFollowErrorKind {
#[class(inherit)]
#[error(transparent)]
UrlToFilePath(#[from] deno_path_util::UrlToFilePathError),
#[class("NotFound")]
#[error("Import '{0}' failed, not found.")]
NotFound(Url),
#[class(generic)]
#[error("Import '{url}' failed.")]
ReadingBlobUrl {
url: Url,
#[source]
source: std::io::Error,
},
#[class(inherit)]
#[error(transparent)]
ReadingFile(#[from] FailedReadingLocalFileError),
#[class(generic)]
#[error("Import '{url}' failed.")]
FetchingRemote {
url: Url,
#[source]
source: Box<dyn std::error::Error + Send + Sync>,
},
#[class(generic)]
#[error("Import '{url}' failed: {status_code}")]
ClientError {
url: Url,
status_code: http::StatusCode,
},
#[class("NoRemote")]
#[error(
"A remote specifier was requested: \"{0}\", but --no-remote is specified."
)]
NoRemote(Url),
#[class(inherit)]
#[error(transparent)]
DataUrlDecode(DataUrlDecodeError),
#[class(inherit)]
#[error(transparent)]
RedirectResolution(#[from] RedirectResolutionError),
#[class(inherit)]
#[error(transparent)]
ChecksumIntegrity(#[from] ChecksumIntegrityError),
#[class(inherit)]
#[error(transparent)]
CacheRead(#[from] CacheReadError),
#[class(generic)]
#[error("Failed caching '{url}'.")]
CacheSave {
url: Url,
#[source]
source: std::io::Error,
},
// this message list additional `npm` and `jsr` schemes, but they should actually be handled
// before `file_fetcher.rs` APIs are even hit.
#[class(inherit)]
#[error(transparent)]
UnsupportedScheme(#[from] UnsupportedSchemeError),
#[class(type)]
#[error(transparent)]
RedirectHeaderParse(#[from] RedirectHeaderParseError),
#[class("NotCached")]
#[error(
"Specifier not found in cache: \"{url}\", --cached-only is specified."
)]
NotCached { url: Url },
#[class(type)]
#[error("Failed setting header '{name}'.")]
InvalidHeader {
name: &'static str,
#[source]
source: header::InvalidHeaderValue,
},
}
#[derive(Debug, Boxed, JsError)]
pub struct FetchCachedError(pub Box<FetchCachedErrorKind>);
#[derive(Debug, Error, JsError)]
pub enum FetchCachedErrorKind {
#[class(inherit)]
#[error(transparent)]
TooManyRedirects(TooManyRedirectsError),
#[class(inherit)]
#[error(transparent)]
ChecksumIntegrity(#[from] ChecksumIntegrityError),
#[class(inherit)]
#[error(transparent)]
CacheRead(#[from] CacheReadError),
#[class(inherit)]
#[error(transparent)]
RedirectResolution(#[from] RedirectResolutionError),
}
#[derive(Debug, Boxed, JsError)]
pub struct FetchLocalError(pub Box<FetchLocalErrorKind>);
#[derive(Debug, Error, JsError)]
pub enum FetchLocalErrorKind {
#[class(inherit)]
#[error(transparent)]
UrlToFilePath(#[from] deno_path_util::UrlToFilePathError),
#[class(inherit)]
#[error(transparent)]
ReadingFile(#[from] FailedReadingLocalFileError),
}
impl From<FetchLocalError> for FetchNoFollowError {
fn from(err: FetchLocalError) -> Self {
match err.into_kind() {
FetchLocalErrorKind::UrlToFilePath(err) => err.into(),
FetchLocalErrorKind::ReadingFile(err) => err.into(),
}
}
}
#[derive(Debug, Boxed, JsError)]
struct FetchCachedNoFollowError(pub Box<FetchCachedNoFollowErrorKind>);
#[derive(Debug, Error, JsError)]
enum FetchCachedNoFollowErrorKind {
#[class(inherit)]
#[error(transparent)]
ChecksumIntegrity(ChecksumIntegrityError),
#[class(inherit)]
#[error(transparent)]
CacheRead(#[from] CacheReadError),
#[class(inherit)]
#[error(transparent)]
RedirectResolution(#[from] RedirectResolutionError),
}
impl From<FetchCachedNoFollowError> for FetchCachedError {
fn from(err: FetchCachedNoFollowError) -> Self {
match err.into_kind() {
FetchCachedNoFollowErrorKind::ChecksumIntegrity(err) => err.into(),
FetchCachedNoFollowErrorKind::CacheRead(err) => err.into(),
FetchCachedNoFollowErrorKind::RedirectResolution(err) => err.into(),
}
}
}
impl From<FetchCachedNoFollowError> for FetchNoFollowError {
fn from(err: FetchCachedNoFollowError) -> Self {
match err.into_kind() {
FetchCachedNoFollowErrorKind::ChecksumIntegrity(err) => err.into(),
FetchCachedNoFollowErrorKind::CacheRead(err) => err.into(),
FetchCachedNoFollowErrorKind::RedirectResolution(err) => err.into(),
}
}
}
#[async_trait::async_trait(?Send)]
pub trait HttpClient: std::fmt::Debug + MaybeSend + MaybeSync {
/// Send a request getting the response.
///
/// The implementation MUST not follow redirects. Return `SendResponse::Redirect`
/// in that case.
///
/// The implementation may retry the request on failure.
async fn send_no_follow(
&self,
url: &Url,
headers: HeaderMap,
) -> Result<SendResponse, SendError>;
}
#[derive(Debug, Clone)]
pub struct BlobData {
pub media_type: String,
pub bytes: Vec<u8>,
}
#[derive(Debug, Clone, Default)]
pub struct NullBlobStore;
#[async_trait::async_trait(?Send)]
impl BlobStore for NullBlobStore {
async fn get(&self, _url: &Url) -> std::io::Result<Option<BlobData>> {
Ok(None)
}
}
#[async_trait::async_trait(?Send)]
pub trait BlobStore: std::fmt::Debug + MaybeSend + MaybeSync {
async fn get(&self, url: &Url) -> std::io::Result<Option<BlobData>>;
}
#[derive(Debug, Default)]
pub struct FetchNoFollowOptions<'a> {
pub local: FetchLocalOptions,
pub maybe_auth: Option<(header::HeaderName, header::HeaderValue)>,
pub maybe_checksum: Option<Checksum<'a>>,
pub maybe_accept: Option<&'a str>,
pub maybe_cache_setting: Option<&'a CacheSetting>,
}
#[derive(Debug, Clone, Default)]
pub struct FetchLocalOptions {
pub include_mtime: bool,
}
#[derive(Debug)]
pub struct FileFetcherOptions {
pub allow_remote: bool,
pub cache_setting: CacheSetting,
pub auth_tokens: AuthTokens,
}
#[sys_traits::auto_impl]
pub trait FileFetcherSys: FsOpen + SystemTimeNow {}
/// A structure for resolving, fetching and caching source files.
#[derive(Debug)]
pub struct FileFetcher<
TBlobStore: BlobStore,
TSys: FileFetcherSys,
THttpClient: HttpClient,
> {
blob_store: TBlobStore,
sys: TSys,
http_cache: HttpCacheRc,
http_client: THttpClient,
memory_files: MemoryFilesRc,
allow_remote: bool,
cache_setting: CacheSetting,
auth_tokens: AuthTokens,
}
impl<TBlobStore: BlobStore, TSys: FileFetcherSys, THttpClient: HttpClient>
FileFetcher<TBlobStore, TSys, THttpClient>
{
pub fn new(
blob_store: TBlobStore,
sys: TSys,
http_cache: HttpCacheRc,
http_client: THttpClient,
memory_files: MemoryFilesRc,
options: FileFetcherOptions,
) -> Self {
Self {
blob_store,
sys,
http_cache,
http_client,
memory_files,
allow_remote: options.allow_remote,
auth_tokens: options.auth_tokens,
cache_setting: options.cache_setting,
}
}
pub fn cache_setting(&self) -> &CacheSetting {
&self.cache_setting
}
/// Fetch cached remote file.
pub fn fetch_cached(
&self,
url: &Url,
redirect_limit: i64,
) -> Result<Option<File>, FetchCachedError> {
if !matches!(url.scheme(), "http" | "https") {
return Ok(None);
}
let mut url = Cow::Borrowed(url);
for _ in 0..=redirect_limit {
match self.fetch_cached_no_follow(&url, None)? {
Some(FileOrRedirect::File(file)) => {
return Ok(Some(file));
}
Some(FileOrRedirect::Redirect(redirect_url)) => {
url = Cow::Owned(redirect_url);
}
None => {
return Ok(None);
}
}
}
Err(
FetchCachedErrorKind::TooManyRedirects(TooManyRedirectsError(
url.into_owned(),
))
.into_box(),
)
}
/// Fetches without following redirects.
///
/// You should verify permissions of the specifier before calling this function.
pub async fn fetch_no_follow(
&self,
url: &Url,
options: FetchNoFollowOptions<'_>,
) -> Result<FileOrRedirect, FetchNoFollowError> {
// note: this debug output is used by the tests
debug!("FileFetcher::fetch_no_follow - specifier: {}", url);
self
.fetch_no_follow_with_strategy(&FetchStrategy(self), url, options)
.await
}
/// Ensures the data is cached without following redirects.
///
/// You should verify permissions of the specifier before calling this function.
pub async fn ensure_cached_no_follow(
&self,
url: &Url,
options: FetchNoFollowOptions<'_>,
) -> Result<CachedOrRedirect, FetchNoFollowError> {
// note: this debug output is used by the tests
debug!("FileFetcher::ensure_cached_no_follow - specifier: {}", url);
self
.fetch_no_follow_with_strategy(&EnsureCachedStrategy(self), url, options)
.await
}
async fn fetch_no_follow_with_strategy<
TStrategy: FetchOrEnsureCacheStrategy,
>(
&self,
strategy: &TStrategy,
url: &Url,
options: FetchNoFollowOptions<'_>,
) -> Result<TStrategy::ReturnValue, FetchNoFollowError> {
let scheme = url.scheme();
if let Some(file) = self.memory_files.get(url) {
Ok(strategy.handle_memory_file(file))
} else if scheme == "file" {
match strategy.handle_local(url, &options.local)? {
Some(file) => Ok(file),
None => Err(FetchNoFollowErrorKind::NotFound(url.clone()).into_box()),
}
} else if scheme == "data" {
strategy
.handle_data_url(url)
.map_err(|e| FetchNoFollowErrorKind::DataUrlDecode(e).into_box())
} else if scheme == "blob" {
strategy.handle_blob_url(url).await
} else if scheme == "https" || scheme == "http" {
if !self.allow_remote {
Err(FetchNoFollowErrorKind::NoRemote(url.clone()).into_box())
} else {
self
.fetch_remote_no_follow(
strategy,
url,
options.maybe_accept,
options.maybe_cache_setting.unwrap_or(&self.cache_setting),
options.maybe_checksum,
options.maybe_auth,
)
.await
}
} else {
Err(
FetchNoFollowErrorKind::UnsupportedScheme(UnsupportedSchemeError {
scheme: scheme.to_string(),
url: url.clone(),
})
.into_box(),
)
}
}
fn fetch_cached_no_follow(
&self,
url: &Url,
maybe_checksum: Option<Checksum<'_>>,
) -> Result<Option<FileOrRedirect>, FetchCachedNoFollowError> {
debug!("FileFetcher::fetch_cached_no_follow - specifier: {}", url);
let cache_key =
self
.http_cache
.cache_item_key(url)
.map_err(|source| CacheReadError {
url: url.clone(),
source,
})?;
match self.http_cache.get(&cache_key, maybe_checksum) {
Ok(Some(entry)) => {
Ok(Some(FileOrRedirect::from_deno_cache_entry(url, entry)?))
}
Ok(None) => Ok(None),
Err(CacheReadFileError::Io(source)) => Err(
FetchCachedNoFollowErrorKind::CacheRead(CacheReadError {
url: url.clone(),
source,
})
.into_box(),
),
Err(CacheReadFileError::ChecksumIntegrity(err)) => {
Err(FetchCachedNoFollowErrorKind::ChecksumIntegrity(*err).into_box())
}
}
}
/// Convert a data URL into a file, resulting in an error if the URL is
/// invalid.
fn fetch_data_url(&self, url: &Url) -> Result<File, DataUrlDecodeError> {
fn parse(
url: &Url,
) -> Result<(Vec<u8>, HashMap<String, String>), DataUrlDecodeError> {
let url = DataUrl::process(url.as_str()).map_err(|source| {
DataUrlDecodeError {
source: DataUrlDecodeSourceError::DataUrl(source),
}
})?;
let (bytes, _) =
url.decode_to_vec().map_err(|source| DataUrlDecodeError {
source: DataUrlDecodeSourceError::InvalidBase64(source),
})?;
let headers = HashMap::from([(
"content-type".to_string(),
url.mime_type().to_string(),
)]);
Ok((bytes, headers))
}
debug!("FileFetcher::fetch_data_url() - specifier: {}", url);
let (bytes, headers) = parse(url)?;
Ok(File {
url: url.clone(),
mtime: None,
maybe_headers: Some(headers),
loaded_from: LoadedFrom::Local,
#[allow(clippy::disallowed_types)] // ok for source
source: std::sync::Arc::from(bytes),
})
}
/// Get a blob URL.
async fn fetch_blob_url(
&self,
url: &Url,
) -> Result<File, FetchNoFollowError> {
debug!("FileFetcher::fetch_blob_url() - specifier: {}", url);
let blob = self
.blob_store
.get(url)
.await
.map_err(|err| FetchNoFollowErrorKind::ReadingBlobUrl {
url: url.clone(),
source: err,
})?
.ok_or_else(|| FetchNoFollowErrorKind::NotFound(url.clone()))?;
let headers =
HashMap::from([("content-type".to_string(), blob.media_type.clone())]);
Ok(File {
url: url.clone(),
mtime: None,
maybe_headers: Some(headers),
loaded_from: LoadedFrom::Local,
#[allow(clippy::disallowed_types)] // ok for source
source: std::sync::Arc::from(blob.bytes),
})
}
async fn fetch_remote_no_follow<TStrategy: FetchOrEnsureCacheStrategy>(
&self,
strategy: &TStrategy,
url: &Url,
maybe_accept: Option<&str>,
cache_setting: &CacheSetting,
maybe_checksum: Option<Checksum<'_>>,
maybe_auth: Option<(header::HeaderName, header::HeaderValue)>,
) -> Result<TStrategy::ReturnValue, FetchNoFollowError> {
debug!("FileFetcher::fetch_remote_no_follow - specifier: {}", url);
if self.should_use_cache(url, cache_setting)
&& let Some(value) =
strategy.handle_fetch_cached_no_follow(url, maybe_checksum)?
{
return Ok(value);
}
if *cache_setting == CacheSetting::Only {
return Err(
FetchNoFollowErrorKind::NotCached { url: url.clone() }.into_box(),
);
}
strategy
.handle_fetch_remote_no_follow_no_cache(
url,
maybe_accept,
maybe_checksum,
maybe_auth,
)
.await
}
async fn fetch_remote_no_follow_no_cache(
&self,
url: &Url,
maybe_accept: Option<&str>,
maybe_checksum: Option<Checksum<'_>>,
maybe_auth: Option<(header::HeaderName, header::HeaderValue)>,
) -> Result<FileOrRedirect, FetchNoFollowError> {
let maybe_etag_cache_entry = self
.http_cache
.cache_item_key(url)
.ok()
.and_then(|key| self.http_cache.get(&key, maybe_checksum).ok().flatten())
.and_then(|mut cache_entry| {
cache_entry
.metadata
.headers
.remove("etag")
.map(|etag| (cache_entry, etag))
});
let maybe_auth_token = self.auth_tokens.get(url);
match self
.send_request(SendRequestArgs {
url,
maybe_accept,
maybe_auth: maybe_auth.clone(),
maybe_auth_token,
maybe_etag: maybe_etag_cache_entry
.as_ref()
.map(|(_, etag)| etag.as_str()),
})
.await?
{
SendRequestResponse::NotModified => {
let (cache_entry, _) = maybe_etag_cache_entry.unwrap();
FileOrRedirect::from_deno_cache_entry(url, cache_entry).map_err(|err| {
FetchNoFollowErrorKind::RedirectResolution(err).into_box()
})
}
SendRequestResponse::Redirect(redirect_url, headers) => {
self.http_cache.set(url, headers, &[]).map_err(|source| {
FetchNoFollowErrorKind::CacheSave {
url: url.clone(),
source,
}
})?;
Ok(FileOrRedirect::Redirect(redirect_url))
}
SendRequestResponse::Code(bytes, headers) => {
self.http_cache.set(url, headers.clone(), &bytes).map_err(
|source| FetchNoFollowErrorKind::CacheSave {
url: url.clone(),
source,
},
)?;
if let Some(checksum) = &maybe_checksum {
checksum
.check(url, &bytes)
.map_err(|err| FetchNoFollowErrorKind::ChecksumIntegrity(*err))?;
}
Ok(FileOrRedirect::File(File {
url: url.clone(),
mtime: None,
maybe_headers: Some(headers),
#[allow(clippy::disallowed_types)] // ok for source
source: std::sync::Arc::from(bytes),
loaded_from: LoadedFrom::Remote,
}))
}
}
}
/// Returns if the cache should be used for a given specifier.
fn should_use_cache(&self, url: &Url, cache_setting: &CacheSetting) -> bool {
match cache_setting {
CacheSetting::ReloadAll => false,
CacheSetting::Use | CacheSetting::Only => true,
CacheSetting::RespectHeaders => {
let Ok(cache_key) = self.http_cache.cache_item_key(url) else {
return false;
};
let Ok(Some(headers)) = self.http_cache.read_headers(&cache_key) else {
return false;
};
let Ok(Some(download_time)) =
self.http_cache.read_download_time(&cache_key)
else {
return false;
};
let cache_semantics =
CacheSemantics::new(headers, download_time, self.sys.sys_time_now());
cache_semantics.should_use()
}
CacheSetting::ReloadSome(list) => {
let mut url = url.clone();
url.set_fragment(None);
if list.iter().any(|x| x == url.as_str()) {
return false;
}
url.set_query(None);
let mut path = PathBuf::from(url.as_str());
loop {
if list.contains(&path.to_str().unwrap().to_string()) {
return false;
}
if !path.pop() {
break;
}
}
true
}
}
}
/// Asynchronously fetches the given HTTP URL one pass only.
/// If no redirect is present and no error occurs,
/// yields Code(ResultPayload).
/// If redirect occurs, does not follow and
/// yields Redirect(url).
async fn send_request(
&self,
args: SendRequestArgs<'_>,
) -> Result<SendRequestResponse, FetchNoFollowError> {
let mut headers = HeaderMap::with_capacity(3);
if let Some(etag) = args.maybe_etag {
let if_none_match_val =
HeaderValue::from_str(etag).map_err(|source| {
FetchNoFollowErrorKind::InvalidHeader {
name: "etag",
source,
}
})?;
headers.insert(IF_NONE_MATCH, if_none_match_val);
}
if let Some(auth_token) = args.maybe_auth_token {
let authorization_val = HeaderValue::from_str(&auth_token.to_string())
.map_err(|source| FetchNoFollowErrorKind::InvalidHeader {
name: "authorization",
source,
})?;
headers.insert(AUTHORIZATION, authorization_val);
} else if let Some((header, value)) = args.maybe_auth {
headers.insert(header, value);
}
if let Some(accept) = args.maybe_accept {
let accepts_val = HeaderValue::from_str(accept).map_err(|source| {
FetchNoFollowErrorKind::InvalidHeader {
name: "accept",
source,
}
})?;
headers.insert(ACCEPT, accepts_val);
}
match self.http_client.send_no_follow(args.url, headers).await {
Ok(resp) => match resp {
SendResponse::NotModified => Ok(SendRequestResponse::NotModified),
SendResponse::Redirect(headers) => {
let new_url = resolve_redirect_from_headers(args.url, &headers)
.map_err(|err| {
FetchNoFollowErrorKind::RedirectHeaderParse(*err).into_box()
})?;
Ok(SendRequestResponse::Redirect(
new_url,
response_headers_to_headers_map(headers),
))
}
SendResponse::Success(headers, body) => Ok(SendRequestResponse::Code(
body,
response_headers_to_headers_map(headers),
)),
},
Err(err) => match err {
SendError::Failed(err) => Err(
FetchNoFollowErrorKind::FetchingRemote {
url: args.url.clone(),
source: err,
}
.into_box(),
),
SendError::NotFound => {
Err(FetchNoFollowErrorKind::NotFound(args.url.clone()).into_box())
}
SendError::StatusCode(status_code) => Err(
FetchNoFollowErrorKind::ClientError {
url: args.url.clone(),
status_code,
}
.into_box(),
),
},
}
}
/// Fetch a source file from the local file system.
pub fn fetch_local(
&self,
url: &Url,
options: &FetchLocalOptions,
) -> Result<Option<File>, FetchLocalError> {
let local = url_to_file_path(url)?;
let Some(file) = self.handle_open_file(url, &local)? else {
return Ok(None);
};
match self.fetch_local_inner(file, url, &local, options) {
Ok(file) => Ok(Some(file)),
Err(err) => Err(
FetchLocalErrorKind::ReadingFile(FailedReadingLocalFileError {
url: url.clone(),
source: err,
})
.into_box(),
),
}
}
fn handle_open_file(
&self,
url: &Url,
path: &Path,
) -> Result<Option<TSys::File>, FetchLocalError> {