pub mod backend;
mod client;
mod common;
mod cursor;
mod database;
mod factory;
pub mod inspection;
pub mod key;
pub mod keypath;
pub mod memory;
pub mod server;
#[cfg(feature = "indexeddb-sqlite")]
pub mod sqlite;
mod store;
pub mod svalue;
use core::ffi::c_void;
use std::collections::HashSet;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock, RwLock};
use std::time::Duration;
use crate::context::ContextId;
use crate::glue;
use crate::webapi::util::*;
pub const DEFAULT_QUOTA: u64 = 1 << 30;
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
pub(crate) fn next_id() -> u64 {
NEXT_ID.fetch_add(1, Ordering::Relaxed)
}
pub use server::{set_backend_factory, BackendFactory};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum IdbEncryption {
Plaintext,
Encrypted([u8; 32]),
Decrypting { old_key: [u8; 32] },
}
pub trait IndexedDbHost: Send + Sync {
fn folder(&self) -> Result<std::path::PathBuf, String>;
fn encryption(&self) -> Result<IdbEncryption, String> {
Ok(IdbEncryption::Plaintext)
}
fn quota_bytes(&self, _usage: u64) -> u64 {
DEFAULT_QUOTA
}
fn describe(&self) -> String;
fn migrated(&self) {}
}
static HOST: RwLock<Option<&'static dyn IndexedDbHost>> = RwLock::new(None);
struct ConfiguredHost {
folder: std::path::PathBuf,
key: Option<[u8; 32]>,
quota: u64,
}
impl IndexedDbHost for ConfiguredHost {
fn folder(&self) -> Result<std::path::PathBuf, String> {
Ok(self.folder.clone())
}
fn encryption(&self) -> Result<IdbEncryption, String> {
Ok(match self.key {
Some(k) => IdbEncryption::Encrypted(k),
None => IdbEncryption::Plaintext,
})
}
fn quota_bytes(&self, _usage: u64) -> u64 {
self.quota
}
fn describe(&self) -> String {
self.folder.display().to_string()
}
}
pub fn configure(folder: std::path::PathBuf, key: Option<[u8; 32]>, quota: u64) -> Result<(), String> {
if server::started() {
return Err("IndexedDB is already in use; its folder and key were latched at the first use".into());
}
let quota = if quota == 0 { DEFAULT_QUOTA } else { quota };
set_host(Box::leak(Box::new(ConfiguredHost { folder, key, quota })));
Ok(())
}
pub fn set_host(h: &'static dyn IndexedDbHost) {
*HOST.write().unwrap() = Some(h);
config_changed();
}
pub fn host() -> Option<&'static dyn IndexedDbHost> {
*HOST.read().unwrap()
}
fn latched() -> &'static Mutex<Option<String>> {
static L: OnceLock<Mutex<Option<String>>> = OnceLock::new();
L.get_or_init(|| Mutex::new(None))
}
pub(crate) fn latch(desc: String) {
*latched().lock().unwrap() = Some(desc);
}
pub fn config_changed() {
if !server::started() {
return;
}
let at = latched().lock().unwrap().clone().unwrap_or_else(|| "this process's memory".into());
advise(
"config-changed",
format!(
"IndexedDB is already open in {at}; the new storage folder / encryption applies at the next start. \
Existing databases are not moved."
),
);
}
fn advised() -> &'static Mutex<(HashSet<String>, Vec<String>)> {
static A: OnceLock<Mutex<(HashSet<String>, Vec<String>)>> = OnceLock::new();
A.get_or_init(|| Mutex::new((HashSet::new(), Vec::new())))
}
pub(crate) fn advise(key: &str, msg: String) {
let mut a = advised().lock().unwrap();
if !a.0.insert(key.to_string()) {
return;
}
eprintln!("[redjs] {msg}");
a.1.push(msg);
}
pub fn advisories() -> Vec<String> {
advised().lock().unwrap().1.clone()
}
pub(crate) fn advise_memory_only(desc: &str) {
let why = if cfg!(feature = "indexeddb-sqlite") {
"no storage host is installed (IndexedDbHost / redjs_idb_configure)"
} else {
"this build has no persistent backend (the `indexeddb-sqlite` feature is off)"
};
advise(
"memory-only",
format!("IndexedDB: {why} — databases live in {desc}. This run is IN MEMORY ONLY: nothing survives a restart."),
);
}
pub(crate) fn advise_locked(name: &[u16], detail: &str) {
let n = String::from_utf16_lossy(name);
advise(
&format!("locked:{n}"),
format!(
"IndexedDB: database \"{n}\" is open in another instance of the app ({detail}); open() fails with \
UnknownError. Give the second instance its own storage folder (SK_APP_NAME=…)."
),
);
}
pub(crate) fn advise_folder_locked(detail: &str) {
advise(
"locked-folder",
format!(
"IndexedDB: the storage folder is in use by another instance of the app ({detail}); databases() and \
open() fail with UnknownError. Give the second instance its own storage folder (SK_APP_NAME=…)."
),
);
}
pub(crate) fn advise_d1() {
advise(
"IDB-D1",
"IndexedDB (IDB-D1): a transaction was created in a timer / requestAnimationFrame callback. This runtime \
drains microtasks once per frame, so it stays active until the end of the frame's pump, not the end of that \
callback — more permissive than a browser, never stricter. Code that expects TransactionInactiveError from a \
later callback in the same frame will not see it."
.into(),
);
}
pub(crate) fn advise_big_value(bytes: usize) {
advise(
"IDB-D4",
format!(
"IndexedDB (IDB-D4): a value of {} MiB was read back; Blob values materialize in memory on read.",
bytes >> 20
),
);
}
#[derive(Clone, Copy)]
pub(crate) struct Intrinsics {
pub ident_re: u64,
pub regexp_exec: u64,
}
pub(crate) fn intrinsics(g: *mut c_void) -> Option<Intrinsics> {
let c = client::try_cl(g)?;
let c = c.borrow();
Some(Intrinsics { ident_re: c.ident_re, regexp_exec: c.regexp_exec })
}
unsafe fn keep(g: *mut c_void, v: u64) -> u64 {
if is_cell(v) {
crate::ffi::redjs_protect(g, v);
}
v
}
pub unsafe fn install(g: *mut c_void, ev_proto: u64, et_proto: u64) {
let Some(ctx) = crate::context::id_of(g) else { return };
if client::try_cl(g).is_some() {
return;
}
let cls = factory::install_classes(g, ev_proto, et_proto);
let global = glue::rjs_global(g);
let re_ctor = get(g, global, "RegExp");
let re_args = [js_string(g, keypath::IDENT_RE), js_string(g, "u")];
let mut ident_re = UNDEF;
glue::rjs_construct(g, re_ctor, re_args.as_ptr(), 2, &mut ident_re);
let regexp_exec = get(g, get(g, re_ctor, "prototype"), "exec");
let inbox = server::register_inbox(ctx);
client::put(
g,
client::Client {
ctx,
inbox,
cls,
s_bag: atom_priv(g, "redjs#idb"),
ident_re: keep(g, ident_re),
regexp_exec: keep(g, regexp_exec),
factory: UNDEF,
storage: UNDEF,
reqs: Default::default(),
txs: Default::default(),
conns: Default::default(),
promises: Default::default(),
fresh: Vec::new(),
inflight: 0,
blocked: Default::default(),
opaque: false,
},
);
let factory = keep(g, host_create(g, cls.factory, cls.factory_proto, client::Unit));
let storage = keep(g, host_create(g, cls.storage_manager, cls.storage_manager_proto, client::Unit));
{
let c = client::cl(g);
let mut c = c.borrow_mut();
c.factory = factory;
c.storage = storage;
}
let getter = make_fn(g, "get indexedDB", 0, factory::get_indexed_db);
let a = atom(g, "indexedDB");
glue::rjs_define_accessor(g, global, a, getter, UNDEF, 0);
glue::rjs_atom_free(g, a);
let nav_ctor = get(g, global, "Navigator");
let nav_proto = if is_cell(nav_ctor) { get(g, nav_ctor, "prototype") } else { UNDEF };
let target = if is_cell(nav_proto) { nav_proto } else { get(g, global, "navigator") };
if is_cell(target) {
let getter = make_fn(g, "get storage", 0, factory::get_storage);
let a = atom(g, "storage");
glue::rjs_define_accessor(g, target, a, getter, UNDEF, 0);
glue::rjs_atom_free(g, a);
}
crate::web::on_checkpoint(client::on_checkpoint);
crate::web::register_pump_source(crate::web::PumpSource {
inflight: client::src_inflight,
ready: client::src_ready,
drain: client::src_drain,
});
}
pub unsafe fn set_opaque_origin(g: *mut c_void, opaque: bool) {
if let Some(c) = client::try_cl(g) {
c.borrow_mut().opaque = opaque;
}
}
pub(crate) fn forget(gone: crate::context::Gone) {
client::remove(gone.key);
context_gone(gone.id);
}
pub fn context_gone(id: ContextId) {
if server::started() {
server::send(server::ToServer::ContextGone { ctx: id });
}
server::drop_inbox(id);
}
pub fn shutdown(timeout: Duration) -> bool {
if !server::started() {
return true;
}
let (tx, rx) = std::sync::mpsc::channel();
server::send(server::ToServer::Shutdown { done: tx });
rx.recv_timeout(timeout).is_ok()
}
#[cfg(test)]
mod tests;