wasm cleanup

This commit is contained in:
John Smith
2022-07-12 08:02:22 -04:00
parent b73511142a
commit b9acd532db
19 changed files with 248 additions and 335 deletions

View File

@@ -11,10 +11,10 @@ pub fn get_timestamp() -> u64 {
}
}
pub fn get_timestamp_string() -> String {
let dt = chrono::Utc::now();
dt.time().format("%H:%M:%S.3f").to_string()
}
// pub fn get_timestamp_string() -> String {
// let dt = chrono::Utc::now();
// dt.time().format("%H:%M:%S.3f").to_string()
// }
pub fn random_bytes(dest: &mut [u8]) -> EyreResult<()> {
let mut rng = rand::thread_rng();
@@ -83,26 +83,26 @@ where
}
}
pub fn spawn_with_local_set<Out>(
future: impl Future<Output = Out> + Send + 'static,
) -> MustJoinHandle<Out>
where
Out: Send + 'static,
{
cfg_if! {
if #[cfg(feature="rt-async-std")] {
spawn(future)
} else if #[cfg(feature="rt-tokio")] {
MustJoinHandle::new(tokio::task::spawn_blocking(move || {
let rt = tokio::runtime::Handle::current();
rt.block_on(async {
let local = tokio::task::LocalSet::new();
local.run_until(future).await
})
}))
}
}
}
// pub fn spawn_with_local_set<Out>(
// future: impl Future<Output = Out> + Send + 'static,
// ) -> MustJoinHandle<Out>
// where
// Out: Send + 'static,
// {
// cfg_if! {
// if #[cfg(feature="rt-async-std")] {
// spawn(future)
// } else if #[cfg(feature="rt-tokio")] {
// MustJoinHandle::new(tokio::task::spawn_blocking(move || {
// let rt = tokio::runtime::Handle::current();
// rt.block_on(async {
// let local = tokio::task::LocalSet::new();
// local.run_until(future).await
// })
// }))
// }
// }
// }
pub fn spawn_detached<Out>(future: impl Future<Output = Out> + Send + 'static)
where

View File

@@ -1,11 +1,11 @@
use super::utils;
use crate::xx::*;
use crate::*;
use async_executors::{Bindgen, LocalSpawnHandleExt /*, SpawnHandleExt*/};
use async_executors::{Bindgen, LocalSpawnHandleExt, SpawnHandleExt, Timer};
use futures_util::future::{select, Either};
use js_sys::*;
use wasm_bindgen_futures::*;
use web_sys::*;
//use web_sys::*;
#[wasm_bindgen]
extern "C" {
@@ -26,17 +26,17 @@ pub fn get_timestamp() -> u64 {
}
}
pub fn get_timestamp_string() -> String {
let date = Date::new_0();
let hours = Date::get_utc_hours(&date);
let minutes = Date::get_utc_minutes(&date);
let seconds = Date::get_utc_seconds(&date);
let milliseconds = Date::get_utc_milliseconds(&date);
format!(
"{:02}:{:02}:{:02}.{}",
hours, minutes, seconds, milliseconds
)
}
// pub fn get_timestamp_string() -> String {
// let date = Date::new_0();
// let hours = Date::get_utc_hours(&date);
// let minutes = Date::get_utc_minutes(&date);
// let seconds = Date::get_utc_seconds(&date);
// let milliseconds = Date::get_utc_milliseconds(&date);
// format!(
// "{:02}:{:02}:{:02}.{}",
// hours, minutes, seconds, milliseconds
// )
// }
pub fn random_bytes(dest: &mut [u8]) -> EyreResult<()> {
let len = dest.len();
@@ -72,43 +72,21 @@ pub fn get_random_u64() -> u64 {
}
pub async fn sleep(millis: u32) {
if utils::is_browser() {
let wait_millis = if millis > u32::MAX {
i32::MAX
} else {
millis as i32
};
let promise = Promise::new(&mut |yes, _| {
let win = window().unwrap();
win.set_timeout_with_callback_and_timeout_and_arguments_0(&yes, wait_millis)
.unwrap();
});
JsFuture::from(promise).await.unwrap();
} else if utils::is_nodejs() {
let promise = Promise::new(&mut |yes, _| {
nodejs_global_set_timeout_with_callback_and_timeout_and_arguments_0(&yes, millis)
.unwrap();
});
JsFuture::from(promise).await.unwrap();
} else {
panic!("WASM requires browser or nodejs environment");
}
Bindgen.sleep(Duration::from_millis(millis.into())).await
}
pub fn system_boxed<'a, Out>(
future: impl Future<Output = Out> + 'a,
future: impl Future<Output = Out> + Send + 'a,
) -> SystemPinBoxFutureLifetime<'a, Out> {
Box::pin(future)
}
pub fn spawn<Out>(future: impl Future<Output = Out> + 'static) -> MustJoinHandle<Out>
pub fn spawn<Out>(future: impl Future<Output = Out> + Send + 'static) -> MustJoinHandle<Out>
where
Out: Send + 'static,
{
MustJoinHandle::new(Bindgen
.spawn_handle_local(future)
.spawn_handle(future)
.expect("wasm-bindgen-futures spawn should never error out"))
}
@@ -121,16 +99,16 @@ where
.expect("wasm-bindgen-futures spawn_local should never error out"))
}
pub fn spawn_with_local_set<Out>(
future: impl Future<Output = Out> + 'static,
) -> MustJoinHandle<Out>
where
Out: Send + 'static,
{
spawn(future)
}
// pub fn spawn_with_local_set<Out>(
// future: impl Future<Output = Out> + Send + 'static,
// ) -> MustJoinHandle<Out>
// where
// Out: Send + 'static,
// {
// spawn(future)
// }
pub fn spawn_detached<Out>(future: impl Future<Output = Out> + 'static)
pub fn spawn_detached<Out>(future: impl Future<Output = Out> + Send + 'static)
where
Out: Send + 'static,
{
@@ -142,13 +120,13 @@ where
pub fn interval<F, FUT>(freq_ms: u32, callback: F) -> SystemPinBoxFuture<()>
where
F: Fn() -> FUT + 'static,
FUT: Future<Output = ()>,
F: Fn() -> FUT + Send + Sync + 'static,
FUT: Future<Output = ()> + Send,
{
let e = Eventual::new();
let ie = e.clone();
let jh = spawn_local(Box::pin(async move {
let jh = spawn(Box::pin(async move {
while timeout(freq_ms, ie.instance_clone(())).await.is_err() {
callback().await;
}

View File

@@ -13,6 +13,7 @@ struct TableStoreInner {
pub struct TableStore {
config: VeilidConfig,
inner: Arc<Mutex<TableStoreInner>>,
async_lock: Arc<AsyncMutex<()>>,
}
impl TableStore {
@@ -25,14 +26,17 @@ impl TableStore {
Self {
config,
inner: Arc::new(Mutex::new(Self::new_inner())),
async_lock: Arc::new(AsyncMutex::new(())),
}
}
pub async fn init(&self) -> EyreResult<()> {
let _async_guard = self.async_lock.lock().await;
Ok(())
}
pub async fn terminate(&self) {
let _async_guard = self.async_lock.lock().await;
assert!(
self.inner.lock().opened.len() == 0,
"all open databases should have been closed"
@@ -66,18 +70,21 @@ impl TableStore {
}
pub async fn open(&self, name: &str, column_count: u32) -> EyreResult<TableDB> {
let _async_guard = self.async_lock.lock().await;
let table_name = self.get_table_name(name)?;
let mut inner = self.inner.lock();
if let Some(table_db_weak_inner) = inner.opened.get(&table_name) {
match TableDB::try_new_from_weak_inner(table_db_weak_inner.clone()) {
Some(tdb) => {
return Ok(tdb);
}
None => {
inner.opened.remove(&table_name);
}
};
{
let mut inner = self.inner.lock();
if let Some(table_db_weak_inner) = inner.opened.get(&table_name) {
match TableDB::try_new_from_weak_inner(table_db_weak_inner.clone()) {
Some(tdb) => {
return Ok(tdb);
}
None => {
inner.opened.remove(&table_name);
}
};
}
}
let db = Database::open(table_name.clone(), column_count)
.await
@@ -86,22 +93,28 @@ impl TableStore {
let table_db = TableDB::new(table_name.clone(), self.clone(), db);
inner.opened.insert(table_name, table_db.weak_inner());
{
let mut inner = self.inner.lock();
inner.opened.insert(table_name, table_db.weak_inner());
}
Ok(table_db)
}
pub async fn delete(&self, name: &str) -> EyreResult<bool> {
let _async_guard = self.async_lock.lock().await;
trace!("TableStore::delete {}", name);
let table_name = self.get_table_name(name)?;
let inner = self.inner.lock();
if inner.opened.contains_key(&table_name) {
trace!(
"TableStore::delete {}: Not deleting, still open.",
table_name
);
bail!("Not deleting table that is still opened");
{
let inner = self.inner.lock();
if inner.opened.contains_key(&table_name) {
trace!(
"TableStore::delete {}: Not deleting, still open.",
table_name
);
bail!("Not deleting table that is still opened");
}
}
if utils::is_nodejs() {

View File

@@ -44,39 +44,39 @@ pub fn is_browser() -> bool {
res
}
pub fn is_browser_https() -> bool {
static CACHE: AtomicI8 = AtomicI8::new(-1);
let cache = CACHE.load(Ordering::Relaxed);
if cache != -1 {
return cache != 0;
}
// pub fn is_browser_https() -> bool {
// static CACHE: AtomicI8 = AtomicI8::new(-1);
// let cache = CACHE.load(Ordering::Relaxed);
// if cache != -1 {
// return cache != 0;
// }
let res = js_sys::eval("window.location.protocol === 'https'")
.map(|res| res.is_truthy())
.unwrap_or_default();
// let res = js_sys::eval("window.location.protocol === 'https'")
// .map(|res| res.is_truthy())
// .unwrap_or_default();
CACHE.store(res as i8, Ordering::Relaxed);
// CACHE.store(res as i8, Ordering::Relaxed);
res
}
// res
// }
pub fn node_require(module: &str) -> JsValue {
if !is_nodejs() {
return JsValue::UNDEFINED;
}
// pub fn node_require(module: &str) -> JsValue {
// if !is_nodejs() {
// return JsValue::UNDEFINED;
// }
let mut home = env!("CARGO_MANIFEST_DIR");
if home.len() == 0 {
home = ".";
}
// let mut home = env!("CARGO_MANIFEST_DIR");
// if home.len() == 0 {
// home = ".";
// }
match js_sys::eval(format!("require(\"{}/{}\")", home, module).as_str()) {
Ok(v) => v,
Err(e) => {
panic!("node_require failed: {:?}", e);
}
}
}
// match js_sys::eval(format!("require(\"{}/{}\")", home, module).as_str()) {
// Ok(v) => v,
// Err(e) => {
// panic!("node_require failed: {:?}", e);
// }
// }
// }
#[derive(ThisError, Debug, Clone, Eq, PartialEq)]
#[error("JsValue error")]