2024-01-01 14:58:21 -05:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2023-03-22 00:13:24 -04:00
|
|
|
|
2024-09-16 16:39:37 -04:00
|
|
|
use std::borrow::Cow;
|
2023-03-22 00:13:24 -04:00
|
|
|
use std::cell::RefCell;
|
2023-09-29 14:40:36 -04:00
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::env::current_dir;
|
|
|
|
use std::io::ErrorKind;
|
2023-03-22 00:13:24 -04:00
|
|
|
use std::marker::PhantomData;
|
|
|
|
use std::path::Path;
|
|
|
|
use std::path::PathBuf;
|
|
|
|
use std::rc::Rc;
|
2024-05-23 10:35:16 -04:00
|
|
|
use std::sync::Arc;
|
2023-08-18 05:34:16 -04:00
|
|
|
use std::sync::Mutex;
|
2023-10-31 07:13:57 -04:00
|
|
|
use std::sync::OnceLock;
|
2023-03-22 00:13:24 -04:00
|
|
|
|
|
|
|
use async_trait::async_trait;
|
|
|
|
use deno_core::error::type_error;
|
|
|
|
use deno_core::error::AnyError;
|
2023-08-23 19:03:05 -04:00
|
|
|
use deno_core::unsync::spawn_blocking;
|
2023-03-22 00:13:24 -04:00
|
|
|
use deno_core::OpState;
|
2024-09-28 07:55:01 -04:00
|
|
|
use deno_path_util::normalize_path;
|
2023-11-29 00:04:07 -05:00
|
|
|
pub use denokv_sqlite::SqliteBackendError;
|
2024-05-23 10:35:16 -04:00
|
|
|
use denokv_sqlite::SqliteConfig;
|
2023-12-05 08:21:46 -05:00
|
|
|
use denokv_sqlite::SqliteNotifier;
|
2023-10-31 07:13:57 -04:00
|
|
|
use rand::SeedableRng;
|
2023-03-22 06:49:29 -04:00
|
|
|
use rusqlite::OpenFlags;
|
2023-03-22 00:13:24 -04:00
|
|
|
|
|
|
|
use crate::DatabaseHandler;
|
|
|
|
|
2023-12-05 08:21:46 -05:00
|
|
|
static SQLITE_NOTIFIERS_MAP: OnceLock<Mutex<HashMap<PathBuf, SqliteNotifier>>> =
|
2023-10-31 07:13:57 -04:00
|
|
|
OnceLock::new();
|
2023-08-18 05:34:16 -04:00
|
|
|
|
2023-03-22 00:13:24 -04:00
|
|
|
pub struct SqliteDbHandler<P: SqliteDbHandlerPermissions + 'static> {
|
|
|
|
pub default_storage_dir: Option<PathBuf>,
|
2023-10-31 07:13:57 -04:00
|
|
|
versionstamp_rng_seed: Option<u64>,
|
2023-03-22 00:13:24 -04:00
|
|
|
_permissions: PhantomData<P>,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub trait SqliteDbHandlerPermissions {
|
2024-09-16 16:39:37 -04:00
|
|
|
#[must_use = "the resolved return value to mitigate time-of-check to time-of-use issues"]
|
|
|
|
fn check_read(
|
|
|
|
&mut self,
|
|
|
|
p: &str,
|
|
|
|
api_name: &str,
|
|
|
|
) -> Result<PathBuf, AnyError>;
|
|
|
|
#[must_use = "the resolved return value to mitigate time-of-check to time-of-use issues"]
|
|
|
|
fn check_write<'a>(
|
|
|
|
&mut self,
|
|
|
|
p: &'a Path,
|
|
|
|
api_name: &str,
|
|
|
|
) -> Result<Cow<'a, Path>, AnyError>;
|
2023-03-22 00:13:24 -04:00
|
|
|
}
|
|
|
|
|
2024-06-06 23:37:53 -04:00
|
|
|
impl SqliteDbHandlerPermissions for deno_permissions::PermissionsContainer {
|
|
|
|
#[inline(always)]
|
2024-09-16 16:39:37 -04:00
|
|
|
fn check_read(
|
|
|
|
&mut self,
|
|
|
|
p: &str,
|
|
|
|
api_name: &str,
|
|
|
|
) -> Result<PathBuf, AnyError> {
|
2024-06-06 23:37:53 -04:00
|
|
|
deno_permissions::PermissionsContainer::check_read(self, p, api_name)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline(always)]
|
2024-09-16 16:39:37 -04:00
|
|
|
fn check_write<'a>(
|
|
|
|
&mut self,
|
|
|
|
p: &'a Path,
|
|
|
|
api_name: &str,
|
|
|
|
) -> Result<Cow<'a, Path>, AnyError> {
|
|
|
|
deno_permissions::PermissionsContainer::check_write_path(self, p, api_name)
|
2024-06-06 23:37:53 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-22 00:13:24 -04:00
|
|
|
impl<P: SqliteDbHandlerPermissions> SqliteDbHandler<P> {
|
2023-10-31 07:13:57 -04:00
|
|
|
pub fn new(
|
|
|
|
default_storage_dir: Option<PathBuf>,
|
|
|
|
versionstamp_rng_seed: Option<u64>,
|
|
|
|
) -> Self {
|
2023-03-22 00:13:24 -04:00
|
|
|
Self {
|
|
|
|
default_storage_dir,
|
2023-10-31 07:13:57 -04:00
|
|
|
versionstamp_rng_seed,
|
2023-03-22 00:13:24 -04:00
|
|
|
_permissions: PhantomData,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[async_trait(?Send)]
|
|
|
|
impl<P: SqliteDbHandlerPermissions> DatabaseHandler for SqliteDbHandler<P> {
|
2023-10-31 07:13:57 -04:00
|
|
|
type DB = denokv_sqlite::Sqlite;
|
2023-03-22 00:13:24 -04:00
|
|
|
|
|
|
|
async fn open(
|
|
|
|
&self,
|
|
|
|
state: Rc<RefCell<OpState>>,
|
|
|
|
path: Option<String>,
|
|
|
|
) -> Result<Self::DB, AnyError> {
|
2024-09-16 16:39:37 -04:00
|
|
|
#[must_use = "the resolved return value to mitigate time-of-check to time-of-use issues"]
|
|
|
|
fn validate_path<P: SqliteDbHandlerPermissions + 'static>(
|
|
|
|
state: &RefCell<OpState>,
|
|
|
|
path: Option<String>,
|
|
|
|
) -> Result<Option<String>, AnyError> {
|
|
|
|
let Some(path) = path else {
|
|
|
|
return Ok(None);
|
|
|
|
};
|
|
|
|
if path == ":memory:" {
|
|
|
|
return Ok(Some(path));
|
|
|
|
}
|
|
|
|
if path.is_empty() {
|
|
|
|
return Err(type_error("Filename cannot be empty"));
|
|
|
|
}
|
|
|
|
if path.starts_with(':') {
|
|
|
|
return Err(type_error(
|
|
|
|
"Filename cannot start with ':' unless prefixed with './'",
|
|
|
|
));
|
|
|
|
}
|
|
|
|
{
|
|
|
|
let mut state = state.borrow_mut();
|
|
|
|
let permissions = state.borrow_mut::<P>();
|
|
|
|
let path = permissions.check_read(&path, "Deno.openKv")?;
|
|
|
|
let path = permissions.check_write(&path, "Deno.openKv")?;
|
|
|
|
Ok(Some(path.to_string_lossy().to_string()))
|
2023-03-22 00:13:24 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-09-16 16:39:37 -04:00
|
|
|
let path = validate_path::<P>(&state, path)?;
|
2023-10-31 07:13:57 -04:00
|
|
|
let default_storage_dir = self.default_storage_dir.clone();
|
2024-05-23 10:35:16 -04:00
|
|
|
type ConnGen =
|
|
|
|
Arc<dyn Fn() -> rusqlite::Result<rusqlite::Connection> + Send + Sync>;
|
|
|
|
let (conn_gen, notifier_key): (ConnGen, _) = spawn_blocking(move || {
|
2023-10-31 07:13:57 -04:00
|
|
|
denokv_sqlite::sqlite_retry_loop(|| {
|
2023-12-05 08:21:46 -05:00
|
|
|
let (conn, notifier_key) = match (path.as_deref(), &default_storage_dir)
|
|
|
|
{
|
2024-05-23 10:35:16 -04:00
|
|
|
(Some(":memory:"), _) | (None, None) => (
|
|
|
|
Arc::new(rusqlite::Connection::open_in_memory) as ConnGen,
|
|
|
|
None,
|
|
|
|
),
|
2023-12-05 08:21:46 -05:00
|
|
|
(Some(path), _) => {
|
|
|
|
let flags =
|
|
|
|
OpenFlags::default().difference(OpenFlags::SQLITE_OPEN_URI);
|
|
|
|
let resolved_path = canonicalize_path(&PathBuf::from(path))
|
|
|
|
.map_err(anyhow::Error::from)?;
|
2024-05-23 10:35:16 -04:00
|
|
|
let path = path.to_string();
|
2023-12-05 08:21:46 -05:00
|
|
|
(
|
2024-05-23 10:35:16 -04:00
|
|
|
Arc::new(move || {
|
|
|
|
rusqlite::Connection::open_with_flags(&path, flags)
|
|
|
|
}) as ConnGen,
|
2023-12-05 08:21:46 -05:00
|
|
|
Some(resolved_path),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
(None, Some(path)) => {
|
|
|
|
std::fs::create_dir_all(path).map_err(anyhow::Error::from)?;
|
|
|
|
let path = path.join("kv.sqlite3");
|
2024-05-23 10:35:16 -04:00
|
|
|
let path2 = path.clone();
|
|
|
|
(
|
|
|
|
Arc::new(move || rusqlite::Connection::open(&path2)) as ConnGen,
|
|
|
|
Some(path),
|
|
|
|
)
|
2023-12-05 08:21:46 -05:00
|
|
|
}
|
|
|
|
};
|
2023-06-13 20:49:57 -04:00
|
|
|
|
2023-12-05 08:21:46 -05:00
|
|
|
Ok::<_, SqliteBackendError>((conn, notifier_key))
|
2023-09-29 14:40:36 -04:00
|
|
|
})
|
2023-03-22 00:13:24 -04:00
|
|
|
})
|
2023-10-31 07:13:57 -04:00
|
|
|
.await
|
|
|
|
.unwrap()?;
|
2023-03-22 00:13:24 -04:00
|
|
|
|
2023-12-05 08:21:46 -05:00
|
|
|
let notifier = if let Some(notifier_key) = notifier_key {
|
|
|
|
SQLITE_NOTIFIERS_MAP
|
2023-10-31 07:13:57 -04:00
|
|
|
.get_or_init(Default::default)
|
|
|
|
.lock()
|
|
|
|
.unwrap()
|
2023-12-05 08:21:46 -05:00
|
|
|
.entry(notifier_key)
|
2023-10-31 07:13:57 -04:00
|
|
|
.or_default()
|
|
|
|
.clone()
|
|
|
|
} else {
|
2023-12-05 08:21:46 -05:00
|
|
|
SqliteNotifier::default()
|
2023-10-31 07:13:57 -04:00
|
|
|
};
|
2023-03-22 00:13:24 -04:00
|
|
|
|
2024-05-23 10:35:16 -04:00
|
|
|
let versionstamp_rng_seed = self.versionstamp_rng_seed;
|
|
|
|
|
|
|
|
let config = SqliteConfig {
|
|
|
|
batch_timeout: None,
|
|
|
|
num_workers: 1,
|
|
|
|
};
|
2023-03-22 00:13:24 -04:00
|
|
|
|
2024-05-23 10:35:16 -04:00
|
|
|
denokv_sqlite::Sqlite::new(
|
|
|
|
move || {
|
|
|
|
let conn = conn_gen()?;
|
|
|
|
conn.pragma_update(None, "journal_mode", "wal")?;
|
|
|
|
Ok((
|
|
|
|
conn,
|
|
|
|
match versionstamp_rng_seed {
|
|
|
|
Some(seed) => Box::new(rand::rngs::StdRng::seed_from_u64(seed)),
|
|
|
|
None => Box::new(rand::rngs::StdRng::from_entropy()),
|
|
|
|
},
|
|
|
|
))
|
|
|
|
},
|
|
|
|
notifier,
|
|
|
|
config,
|
|
|
|
)
|
2023-03-22 00:13:24 -04:00
|
|
|
}
|
|
|
|
}
|
2023-09-26 23:06:57 -04:00
|
|
|
|
2023-09-29 14:40:36 -04:00
|
|
|
/// Same as Path::canonicalize, but also handles non-existing paths.
|
|
|
|
fn canonicalize_path(path: &Path) -> Result<PathBuf, AnyError> {
|
2024-08-22 14:45:20 -04:00
|
|
|
let path = normalize_path(path);
|
2023-09-29 14:40:36 -04:00
|
|
|
let mut path = path;
|
|
|
|
let mut names_stack = Vec::new();
|
|
|
|
loop {
|
|
|
|
match path.canonicalize() {
|
|
|
|
Ok(mut canonicalized_path) => {
|
|
|
|
for name in names_stack.into_iter().rev() {
|
|
|
|
canonicalized_path = canonicalized_path.join(name);
|
|
|
|
}
|
|
|
|
return Ok(canonicalized_path);
|
|
|
|
}
|
|
|
|
Err(err) if err.kind() == ErrorKind::NotFound => {
|
|
|
|
let file_name = path.file_name().map(|os_str| os_str.to_os_string());
|
|
|
|
if let Some(file_name) = file_name {
|
|
|
|
names_stack.push(file_name.to_str().unwrap().to_string());
|
|
|
|
path = path.parent().unwrap().to_path_buf();
|
|
|
|
} else {
|
|
|
|
names_stack.push(path.to_str().unwrap().to_string());
|
|
|
|
let current_dir = current_dir()?;
|
2024-06-14 07:40:57 -04:00
|
|
|
path.clone_from(¤t_dir);
|
2023-09-29 14:40:36 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(err) => return Err(err.into()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|