2023-03-22 00:13:24 -04:00
|
|
|
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
|
|
|
|
|
|
|
|
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;
|
2023-06-13 20:49:57 -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;
|
2023-09-29 14:40:36 -04:00
|
|
|
use deno_node::PathClean;
|
2023-11-29 00:04:07 -05:00
|
|
|
pub use denokv_sqlite::SqliteBackendError;
|
2023-10-31 07:13:57 -04:00
|
|
|
use rand::RngCore;
|
|
|
|
use rand::SeedableRng;
|
2023-03-22 06:49:29 -04:00
|
|
|
use rusqlite::OpenFlags;
|
2023-10-31 07:13:57 -04:00
|
|
|
use tokio::sync::Notify;
|
2023-03-22 00:13:24 -04:00
|
|
|
|
|
|
|
use crate::DatabaseHandler;
|
|
|
|
|
2023-10-31 07:13:57 -04:00
|
|
|
static QUEUE_WAKER_MAP: OnceLock<Mutex<HashMap<PathBuf, Arc<Notify>>>> =
|
|
|
|
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 {
|
|
|
|
fn check_read(&mut self, p: &Path, api_name: &str) -> Result<(), AnyError>;
|
|
|
|
fn check_write(&mut self, p: &Path, api_name: &str) -> Result<(), AnyError>;
|
|
|
|
}
|
|
|
|
|
|
|
|
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> {
|
2023-06-02 14:12:26 -04:00
|
|
|
// Validate path
|
|
|
|
if let Some(path) = &path {
|
|
|
|
if path != ":memory:" {
|
2023-03-22 06:49:29 -04:00
|
|
|
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 './'",
|
|
|
|
));
|
|
|
|
}
|
2023-03-22 00:13:24 -04:00
|
|
|
let path = Path::new(path);
|
|
|
|
{
|
|
|
|
let mut state = state.borrow_mut();
|
|
|
|
let permissions = state.borrow_mut::<P>();
|
2023-03-22 15:23:36 -04:00
|
|
|
permissions.check_read(path, "Deno.openKv")?;
|
|
|
|
permissions.check_write(path, "Deno.openKv")?;
|
2023-03-22 00:13:24 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-31 07:13:57 -04:00
|
|
|
let path = path.clone();
|
|
|
|
let default_storage_dir = self.default_storage_dir.clone();
|
|
|
|
let (conn, queue_waker_key) = spawn_blocking(move || {
|
|
|
|
denokv_sqlite::sqlite_retry_loop(|| {
|
|
|
|
let (conn, queue_waker_key) =
|
|
|
|
match (path.as_deref(), &default_storage_dir) {
|
|
|
|
(Some(":memory:"), _) | (None, None) => {
|
|
|
|
(rusqlite::Connection::open_in_memory()?, None)
|
2023-06-02 14:12:26 -04:00
|
|
|
}
|
2023-10-31 07:13:57 -04:00
|
|
|
(Some(path), _) => {
|
|
|
|
let flags =
|
|
|
|
OpenFlags::default().difference(OpenFlags::SQLITE_OPEN_URI);
|
2023-11-29 00:04:07 -05:00
|
|
|
let resolved_path = canonicalize_path(&PathBuf::from(path))
|
|
|
|
.map_err(|_| SqliteBackendError::DatabaseClosed)?;
|
2023-10-31 07:13:57 -04:00
|
|
|
(
|
|
|
|
rusqlite::Connection::open_with_flags(path, flags)?,
|
|
|
|
Some(resolved_path),
|
|
|
|
)
|
2023-06-02 14:12:26 -04:00
|
|
|
}
|
2023-10-31 07:13:57 -04:00
|
|
|
(None, Some(path)) => {
|
2023-11-29 00:04:07 -05:00
|
|
|
std::fs::create_dir_all(path)
|
|
|
|
.map_err(|_| SqliteBackendError::DatabaseClosed)?;
|
2023-10-31 07:13:57 -04:00
|
|
|
let path = path.join("kv.sqlite3");
|
|
|
|
(rusqlite::Connection::open(path.clone())?, Some(path))
|
2023-06-02 14:12:26 -04:00
|
|
|
}
|
2023-10-31 07:13:57 -04:00
|
|
|
};
|
2023-06-13 20:49:57 -04:00
|
|
|
|
2023-10-31 07:13:57 -04:00
|
|
|
conn.pragma_update(None, "journal_mode", "wal")?;
|
2023-06-13 20:49:57 -04:00
|
|
|
|
2023-11-29 00:04:07 -05:00
|
|
|
Ok::<_, SqliteBackendError>((conn, queue_waker_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-10-31 07:13:57 -04:00
|
|
|
let dequeue_notify = if let Some(queue_waker_key) = queue_waker_key {
|
|
|
|
QUEUE_WAKER_MAP
|
|
|
|
.get_or_init(Default::default)
|
|
|
|
.lock()
|
|
|
|
.unwrap()
|
|
|
|
.entry(queue_waker_key)
|
|
|
|
.or_default()
|
|
|
|
.clone()
|
|
|
|
} else {
|
|
|
|
Arc::new(Notify::new())
|
|
|
|
};
|
2023-03-22 00:13:24 -04:00
|
|
|
|
2023-10-31 07:13:57 -04:00
|
|
|
let versionstamp_rng: Box<dyn RngCore + Send> =
|
|
|
|
match &self.versionstamp_rng_seed {
|
|
|
|
Some(seed) => Box::new(rand::rngs::StdRng::seed_from_u64(*seed)),
|
|
|
|
None => Box::new(rand::rngs::StdRng::from_entropy()),
|
|
|
|
};
|
2023-03-22 00:13:24 -04:00
|
|
|
|
2023-10-31 07:13:57 -04:00
|
|
|
denokv_sqlite::Sqlite::new(conn, dequeue_notify, versionstamp_rng)
|
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> {
|
|
|
|
let path = path.to_path_buf().clean();
|
|
|
|
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()?;
|
|
|
|
path = current_dir.clone();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(err) => return Err(err.into()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|