RAII-style Rust wrapper for the Web Locks API (navigator.locks) for wasm32 targets. Converts the callback-based Web Locks API into an ergonomic Rust API.
*Note: this project is 100% AI generated. However I've tested it and it seems to work, and the code seems correct to me.
- Requires
web_sysunstable APIs: build with--cfg web_sys_unstable_apis. - Works only on
wasm32-unknown-unknownin a browser with Web Locks support.
- Enable the required cfg (choose one):
- Via
.cargo/config.toml(recommended):[target.wasm32-unknown-unknown] rustflags = ["--cfg=web_sys_unstable_apis"]
- Or via environment when building:
RUSTFLAGS="--cfg web_sys_unstable_apis" \ cargo build --target wasm32-unknown-unknown
- Via
- Add to your
Cargo.tomlin a wasm project. - Build with
RUSTFLAGS="--cfg=web_sys_unstable_apis".
Example
use weblocks::{acquire, AcquireOptions};
// Acquire an exclusive lock; it is released when `_guard` is dropped.
async fn run() -> Result<(), wasm_bindgen::JsValue> {
let _guard = acquire("my_resource", AcquireOptions::exclusive()).await?;
// do work while holding lock
Ok(())
}Options
use weblocks::{acquire, AcquireOptions, LockMode};
let opts = AcquireOptions {
mode: LockMode::Shared,
if_available: Some(true),
steal: None,
abort_signal: None,
};
let guard = acquire("shared_name", opts).await?;- This crate uses
js_sys/web_sysdirectly to setLockOptionsproperties for broad compatibility. - If the request is aborted,
acquirereturns anErr(JsValue).
Building docs locally
RUSTDOCFLAGS="--cfg web_sys_unstable_apis" cargo doc --open --target wasm32-unknown-unknown
- MIT or Apache-2.0, at your option.
- A demo workspace lives in
testproj/with two wasm crates:lockshim: wraps this crate for JS with acquire/release functions.otherlib: tries a shared lock withifAvailableto probe availability.
- Build both and run a simple web demo:
cd testprojnpm run build# runs wasm-pack in each cratenpm run serve# servesweb/(requires Node.js; uses npx)- Open the served URL and use the buttons to acquire/release and probe locks.