weblocks

Crates.ioweblocks
lib.rsweblocks
version0.1.0
created_at2025-10-22 06:18:40.720753+00
updated_at2025-10-22 06:18:40.720753+00
descriptionRAII-style Rust wrapper for the Web Locks API (navigator.locks) for wasm32
homepage
repositoryhttps://github.com/anchpop/weblocks
max_upload_size
id1895063
size34,754
Andre Popovitch (anchpop)

documentation

README

weblocks

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.

Status

  • Requires web_sys unstable APIs: build with --cfg web_sys_unstable_apis.
  • Works only on wasm32-unknown-unknown in a browser with Web Locks support.

Setup

  • 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
      

Quick start

  • Add to your Cargo.toml in 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?;

Notes

  • This crate uses js_sys/web_sys directly to set LockOptions properties for broad compatibility.
  • If the request is aborted, acquire returns an Err(JsValue).

Building docs locally

RUSTDOCFLAGS="--cfg web_sys_unstable_apis" cargo doc --open --target wasm32-unknown-unknown

License

  • MIT or Apache-2.0, at your option.

Demo workspace

  • 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 with ifAvailable to probe availability.
  • Build both and run a simple web demo:
    • cd testproj
    • npm run build # runs wasm-pack in each crate
    • npm run serve # serves web/ (requires Node.js; uses npx)
    • Open the served URL and use the buttons to acquire/release and probe locks.
Commit count: 0

cargo fmt