refactor: use deno_cache_dir crate (#20092)

Uses https://github.com/denoland/deno_cache/pull/26
This commit is contained in:
David Sherret 2023-08-08 10:23:02 -04:00 committed by GitHub
parent a037ed77a2
commit 05f838a57c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 221 additions and 1946 deletions

View file

@ -1,9 +1,9 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use super::http_cache::url_to_filename;
use super::CACHE_PERM;
use crate::util::fs::atomic_write_file;
use deno_cache_dir::url_to_filename;
use deno_core::url::Host;
use deno_core::url::Url;
use std::ffi::OsStr;

View file

@ -1,42 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use std::path::Path;
use deno_core::url::Url;
pub fn base_url_to_filename_parts(
url: &Url,
port_separator: &str,
) -> Option<Vec<String>> {
let mut out = Vec::with_capacity(2);
let scheme = url.scheme();
out.push(scheme.to_string());
match scheme {
"http" | "https" => {
let host = url.host_str().unwrap();
let host_port = match url.port() {
// underscores are not allowed in domains, so adding one here is fine
Some(port) => format!("{host}{port_separator}{port}"),
None => host.to_string(),
};
out.push(host_port);
}
"data" | "blob" => (),
scheme => {
log::debug!("Don't know how to create cache name for scheme: {}", scheme);
return None;
}
};
Some(out)
}
pub fn read_file_bytes(path: &Path) -> std::io::Result<Option<Vec<u8>>> {
match std::fs::read(path) {
Ok(s) => Ok(Some(s)),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err),
}
}

View file

@ -1,296 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::time::SystemTime;
use deno_core::error::AnyError;
use deno_core::serde_json;
use deno_core::url::Url;
use thiserror::Error;
use crate::cache::CACHE_PERM;
use crate::http_util::HeadersMap;
use crate::util;
use crate::util::fs::atomic_write_file;
use super::common::base_url_to_filename_parts;
use super::common::read_file_bytes;
use super::CachedUrlMetadata;
use super::HttpCache;
use super::HttpCacheItemKey;
#[derive(Debug, Error)]
#[error("Can't convert url (\"{}\") to filename.", .url)]
pub struct UrlToFilenameConversionError {
pub(super) url: String,
}
/// Turn provided `url` into a hashed filename.
/// URLs can contain a lot of characters that cannot be used
/// in filenames (like "?", "#", ":"), so in order to cache
/// them properly they are deterministically hashed into ASCII
/// strings.
pub fn url_to_filename(
url: &Url,
) -> Result<PathBuf, UrlToFilenameConversionError> {
let Some(mut cache_filename) = base_url_to_filename(url) else {
return Err(UrlToFilenameConversionError { url: url.to_string() });
};
let mut rest_str = url.path().to_string();
if let Some(query) = url.query() {
rest_str.push('?');
rest_str.push_str(query);
}
// NOTE: fragment is omitted on purpose - it's not taken into
// account when caching - it denotes parts of webpage, which
// in case of static resources doesn't make much sense
let hashed_filename = util::checksum::gen(&[rest_str.as_bytes()]);
cache_filename.push(hashed_filename);
Ok(cache_filename)
}
// Turn base of url (scheme, hostname, port) into a valid filename.
/// This method replaces port part with a special string token (because
/// ":" cannot be used in filename on some platforms).
/// Ex: $DENO_DIR/deps/https/deno.land/
fn base_url_to_filename(url: &Url) -> Option<PathBuf> {
base_url_to_filename_parts(url, "_PORT").map(|parts| {
let mut out = PathBuf::new();
for part in parts {
out.push(part);
}
out
})
}
#[derive(Debug)]
pub struct GlobalHttpCache(PathBuf);
impl GlobalHttpCache {
pub fn new(path: PathBuf) -> Self {
assert!(path.is_absolute());
Self(path)
}
// Deprecated to discourage using this as where the file is stored and
// how it's stored should be an implementation detail of the cache.
#[deprecated(note = "Should only be used for deno info.")]
pub fn get_global_cache_location(&self) -> &PathBuf {
&self.0
}
// DEPRECATED: Where the file is stored and how it's stored should be an implementation
// detail of the cache.
#[deprecated(note = "Do not assume the cache will be stored at a file path.")]
pub fn get_global_cache_filepath(
&self,
url: &Url,
) -> Result<PathBuf, AnyError> {
Ok(self.0.join(url_to_filename(url)?))
}
fn get_cache_filepath(&self, url: &Url) -> Result<PathBuf, AnyError> {
Ok(self.0.join(url_to_filename(url)?))
}
#[inline]
fn key_file_path<'a>(&self, key: &'a HttpCacheItemKey) -> &'a PathBuf {
// The key file path is always set for the global cache because
// the file will always exist, unlike the local cache, which won't
// have this for redirects.
key.file_path.as_ref().unwrap()
}
}
impl HttpCache for GlobalHttpCache {
fn cache_item_key<'a>(
&self,
url: &'a Url,
) -> Result<HttpCacheItemKey<'a>, AnyError> {
Ok(HttpCacheItemKey {
#[cfg(debug_assertions)]
is_local_key: false,
url,
file_path: Some(self.get_cache_filepath(url)?),
})
}
fn contains(&self, url: &Url) -> bool {
let Ok(cache_filepath) = self.get_cache_filepath(url) else {
return false
};
cache_filepath.is_file()
}
fn read_modified_time(
&self,
key: &HttpCacheItemKey,
) -> Result<Option<SystemTime>, AnyError> {
#[cfg(debug_assertions)]
debug_assert!(!key.is_local_key);
match std::fs::metadata(self.key_file_path(key)) {
Ok(metadata) => Ok(Some(metadata.modified()?)),
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err.into()),
}
}
fn set(
&self,
url: &Url,
headers: HeadersMap,
content: &[u8],
) -> Result<(), AnyError> {
let cache_filepath = self.get_cache_filepath(url)?;
// Cache content
atomic_write_file(&cache_filepath, content, CACHE_PERM)?;
let metadata = CachedUrlMetadata {
time: SystemTime::now(),
url: url.to_string(),
headers,
};
write_metadata(&cache_filepath, &metadata)?;
Ok(())
}
fn read_file_bytes(
&self,
key: &HttpCacheItemKey,
) -> Result<Option<Vec<u8>>, AnyError> {
#[cfg(debug_assertions)]
debug_assert!(!key.is_local_key);
Ok(read_file_bytes(self.key_file_path(key))?)
}
fn read_metadata(
&self,
key: &HttpCacheItemKey,
) -> Result<Option<CachedUrlMetadata>, AnyError> {
#[cfg(debug_assertions)]
debug_assert!(!key.is_local_key);
match read_metadata(self.key_file_path(key))? {
Some(metadata) => Ok(Some(metadata)),
None => Ok(None),
}
}
}
fn read_metadata(path: &Path) -> Result<Option<CachedUrlMetadata>, AnyError> {
let path = path.with_extension("metadata.json");
match read_file_bytes(&path)? {
Some(metadata) => Ok(Some(serde_json::from_slice(&metadata)?)),
None => Ok(None),
}
}
fn write_metadata(
path: &Path,
meta_data: &CachedUrlMetadata,
) -> Result<(), AnyError> {
let path = path.with_extension("metadata.json");
let json = serde_json::to_string_pretty(meta_data)?;
atomic_write_file(&path, json, CACHE_PERM)?;
Ok(())
}
#[cfg(test)]
mod test {
use super::*;
use std::collections::HashMap;
use test_util::TempDir;
#[test]
fn test_url_to_filename() {
let test_cases = [
("https://deno.land/x/foo.ts", "https/deno.land/2c0a064891b9e3fbe386f5d4a833bce5076543f5404613656042107213a7bbc8"),
(
"https://deno.land:8080/x/foo.ts",
"https/deno.land_PORT8080/2c0a064891b9e3fbe386f5d4a833bce5076543f5404613656042107213a7bbc8",
),
("https://deno.land/", "https/deno.land/8a5edab282632443219e051e4ade2d1d5bbc671c781051bf1437897cbdfea0f1"),
(
"https://deno.land/?asdf=qwer",
"https/deno.land/e4edd1f433165141015db6a823094e6bd8f24dd16fe33f2abd99d34a0a21a3c0",
),
// should be the same as case above, fragment (#qwer) is ignored
// when hashing
(
"https://deno.land/?asdf=qwer#qwer",
"https/deno.land/e4edd1f433165141015db6a823094e6bd8f24dd16fe33f2abd99d34a0a21a3c0",
),
(
"data:application/typescript;base64,ZXhwb3J0IGNvbnN0IGEgPSAiYSI7CgpleHBvcnQgZW51bSBBIHsKICBBLAogIEIsCiAgQywKfQo=",
"data/c21c7fc382b2b0553dc0864aa81a3acacfb7b3d1285ab5ae76da6abec213fb37",
),
(
"data:text/plain,Hello%2C%20Deno!",
"data/967374e3561d6741234131e342bf5c6848b70b13758adfe23ee1a813a8131818",
)
];
for (url, expected) in test_cases.iter() {
let u = Url::parse(url).unwrap();
let p = url_to_filename(&u).unwrap();
assert_eq!(p, PathBuf::from(expected));
}
}
#[test]
fn test_create_cache() {
let dir = TempDir::new();
let cache_path = dir.path().join("foobar");
// HttpCache should be created lazily on first use:
// when zipping up a local project with no external dependencies
// "$DENO_DIR/deps" is empty. When unzipping such project
// "$DENO_DIR/deps" might not get restored and in situation
// when directory is owned by root we might not be able
// to create that directory. However if it's not needed it
// doesn't make sense to return error in such specific scenarios.
// For more details check issue:
// https://github.com/denoland/deno/issues/5688
let cache = GlobalHttpCache::new(cache_path.to_path_buf());
assert!(!cache.0.exists());
let url = Url::parse("http://example.com/foo/bar.js").unwrap();
cache
.set(&url, HeadersMap::new(), b"hello world")
.expect("Failed to add to cache");
assert!(cache_path.is_dir());
assert!(cache.get_cache_filepath(&url).unwrap().is_file());
}
#[test]
fn test_get_set() {
let dir = TempDir::new();
let cache = GlobalHttpCache::new(dir.path().to_path_buf());
let url = Url::parse("https://deno.land/x/welcome.ts").unwrap();
let mut headers = HashMap::new();
headers.insert(
"content-type".to_string(),
"application/javascript".to_string(),
);
headers.insert("etag".to_string(), "as5625rqdsfb".to_string());
let content = b"Hello world";
let r = cache.set(&url, headers, content);
eprintln!("result {r:?}");
assert!(r.is_ok());
let key = cache.cache_item_key(&url).unwrap();
let content =
String::from_utf8(cache.read_file_bytes(&key).unwrap().unwrap()).unwrap();
let headers = cache.read_metadata(&key).unwrap().unwrap().headers;
assert_eq!(content, "Hello world");
assert_eq!(
headers.get("content-type").unwrap(),
"application/javascript"
);
assert_eq!(headers.get("etag").unwrap(), "as5625rqdsfb");
assert_eq!(headers.get("foobar"), None);
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,77 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use deno_core::error::AnyError;
use deno_core::serde::Deserialize;
use deno_core::serde::Serialize;
use deno_core::url::Url;
use std::path::PathBuf;
use std::time::SystemTime;
use crate::http_util::HeadersMap;
mod common;
mod global;
mod local;
pub use global::url_to_filename;
pub use global::GlobalHttpCache;
pub use local::LocalHttpCache;
pub use local::LocalLspHttpCache;
/// Cached metadata about a url.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct CachedUrlMetadata {
pub headers: HeadersMap,
pub url: String,
#[serde(default = "SystemTime::now", rename = "now")]
pub time: SystemTime,
}
impl CachedUrlMetadata {
pub fn is_redirect(&self) -> bool {
self.headers.contains_key("location")
}
}
/// Computed cache key, which can help reduce the work of computing the cache key multiple times.
pub struct HttpCacheItemKey<'a> {
// The key is specific to the implementation of HttpCache,
// so keep these private to the module. For example, the
// fact that these may be stored in a file is an implementation
// detail.
#[cfg(debug_assertions)]
pub(super) is_local_key: bool,
pub(super) url: &'a Url,
/// This will be set all the time for the global cache, but it
/// won't ever be set for the local cache because that also needs
/// header information to determine the final path.
pub(super) file_path: Option<PathBuf>,
}
pub trait HttpCache: Send + Sync + std::fmt::Debug {
/// A pre-computed key for looking up items in the cache.
fn cache_item_key<'a>(
&self,
url: &'a Url,
) -> Result<HttpCacheItemKey<'a>, AnyError>;
fn contains(&self, url: &Url) -> bool;
fn set(
&self,
url: &Url,
headers: HeadersMap,
content: &[u8],
) -> Result<(), AnyError>;
fn read_modified_time(
&self,
key: &HttpCacheItemKey,
) -> Result<Option<SystemTime>, AnyError>;
fn read_file_bytes(
&self,
key: &HttpCacheItemKey,
) -> Result<Option<Vec<u8>>, AnyError>;
fn read_metadata(
&self,
key: &HttpCacheItemKey,
) -> Result<Option<CachedUrlMetadata>, AnyError>;
}

55
cli/cache/mod.rs vendored
View file

@ -2,6 +2,7 @@
use crate::errors::get_error_class_name;
use crate::file_fetcher::FileFetcher;
use crate::util::fs::atomic_write_file;
use deno_core::futures;
use deno_core::futures::FutureExt;
@ -12,8 +13,10 @@ use deno_graph::source::LoadResponse;
use deno_graph::source::Loader;
use deno_runtime::permissions::PermissionsContainer;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::SystemTime;
mod cache_db;
mod caches;
@ -22,7 +25,6 @@ mod common;
mod deno_dir;
mod disk_cache;
mod emit;
mod http_cache;
mod incremental;
mod node;
mod parsed_source;
@ -34,11 +36,6 @@ pub use deno_dir::DenoDir;
pub use deno_dir::DenoDirProvider;
pub use disk_cache::DiskCache;
pub use emit::EmitCache;
pub use http_cache::CachedUrlMetadata;
pub use http_cache::GlobalHttpCache;
pub use http_cache::HttpCache;
pub use http_cache::LocalHttpCache;
pub use http_cache::LocalLspHttpCache;
pub use incremental::IncrementalCache;
pub use node::NodeAnalysisCache;
pub use parsed_source::ParsedSourceCache;
@ -46,6 +43,52 @@ pub use parsed_source::ParsedSourceCache;
/// Permissions used to save a file in the disk caches.
pub const CACHE_PERM: u32 = 0o644;
#[derive(Debug, Clone)]
pub struct RealDenoCacheEnv;
impl deno_cache_dir::DenoCacheEnv for RealDenoCacheEnv {
fn read_file_bytes(&self, path: &Path) -> std::io::Result<Option<Vec<u8>>> {
match std::fs::read(path) {
Ok(s) => Ok(Some(s)),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err),
}
}
fn atomic_write_file(
&self,
path: &Path,
bytes: &[u8],
) -> std::io::Result<()> {
atomic_write_file(path, bytes, CACHE_PERM)
}
fn modified(&self, path: &Path) -> std::io::Result<Option<SystemTime>> {
match std::fs::metadata(path) {
Ok(metadata) => Ok(Some(
metadata.modified().unwrap_or_else(|_| SystemTime::now()),
)),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err),
}
}
fn is_file(&self, path: &Path) -> bool {
path.is_file()
}
fn time_now(&self) -> SystemTime {
SystemTime::now()
}
}
pub type GlobalHttpCache = deno_cache_dir::GlobalHttpCache<RealDenoCacheEnv>;
pub type LocalHttpCache = deno_cache_dir::LocalHttpCache<RealDenoCacheEnv>;
pub type LocalLspHttpCache =
deno_cache_dir::LocalLspHttpCache<RealDenoCacheEnv>;
pub use deno_cache_dir::CachedUrlMetadata;
pub use deno_cache_dir::HttpCache;
/// A "wrapper" for the FileFetcher and DiskCache for the Deno CLI that provides
/// a concise interface to the DENO_DIR when building module graphs.
pub struct FetchCacher {