Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 29 additions & 13 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 1 addition & 3 deletions crates/capabilities/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@ http = "1"
bytes = "1.4"
futures-core = "0.3"
anyhow = "1"
# TODO: Replace this temporary libdatadog PR rev with the official release/tag
# that contains DataDog/libdatadog#2235, then regenerate Cargo.lock.
libdd-capabilities = { git = "https://github.com/DataDog/libdatadog.git", rev = "8cd68ab922fb7aade0f089ccfc91291d874673af" }
libdd-capabilities = { git = "https://github.com/DataDog/libdatadog.git", rev = "3081603d3c74f209be4e3be951f78a1a7469397f" }

[dev-dependencies]
wasm-bindgen-test = "0.3"
156 changes: 156 additions & 0 deletions crates/capabilities/src/file.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
// Copyright 2026-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0

//! Wasm implementation of [`FileCapability`] backed by Node.js `fs`.
//!
//! The JS transport is imported via `wasm_bindgen(module = ...)` from
//! `file_transport.js`, which ships alongside the wasm output.

use std::future::Future;

use bytes::Bytes;
use js_sys::{self, Reflect, Uint8Array};
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;

use libdd_capabilities::file::{FileCapability, FileError, FileMetadata};
use libdd_capabilities::maybe_send::MaybeSend;

#[wasm_bindgen(module = "/src/file_transport.js")]
extern "C" {
#[wasm_bindgen(js_name = "readFile", catch)]
fn js_read_file(path: &str) -> Result<js_sys::Promise, JsValue>;

#[wasm_bindgen(js_name = "writeFile", catch)]
fn js_write_file(path: &str, data: &[u8]) -> Result<js_sys::Promise, JsValue>;

#[wasm_bindgen(js_name = "metadata", catch)]
fn js_metadata(path: &str) -> Result<js_sys::Promise, JsValue>;

#[wasm_bindgen(js_name = "exists", catch)]
fn js_exists(path: &str) -> Result<js_sys::Promise, JsValue>;
}

#[derive(Debug, Clone)]
pub struct WasmFileCapability;

impl FileCapability for WasmFileCapability {
fn new() -> Self {
Self
}

#[allow(clippy::manual_async_fn)]
fn read(&self, path: &str) -> impl Future<Output = Result<Bytes, FileError>> + MaybeSend {
let path = path.to_owned();
async move {
let promise =
js_read_file(&path).map_err(|e| map_js_error(&e, &path))?;
let value = JsFuture::from(promise)
.await
.map_err(|e| map_js_error(&e, &path))?;
let array = Uint8Array::new(&value);
Ok(Bytes::from(array.to_vec()))
Comment on lines +51 to +52

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't value really a Uint8Array already? Uint8Array::new(&value) is going to do an extra copy. Is that necessary? Can't you use Uint8Array::unchecked_from_js(value) instead?

}
}

#[allow(clippy::manual_async_fn)]
fn write(
&self,
path: &str,
contents: Bytes,
) -> impl Future<Output = Result<(), FileError>> + MaybeSend {
let path = path.to_owned();
async move {
let promise = js_write_file(&path, &contents)
.map_err(|e| map_js_error(&e, &path))?;
JsFuture::from(promise)
.await
.map_err(|e| map_js_error(&e, &path))?;
Ok(())
}
}

#[allow(clippy::manual_async_fn)]
fn metadata(
&self,
path: &str,
) -> impl Future<Output = Result<FileMetadata, FileError>> + MaybeSend {
let path = path.to_owned();
async move {
let promise =
js_metadata(&path).map_err(|e| map_js_error(&e, &path))?;
let value = JsFuture::from(promise)
.await
.map_err(|e| map_js_error(&e, &path))?;
parse_metadata(&value, &path)
}
}

#[allow(clippy::manual_async_fn)]
fn exists(&self, path: &str) -> impl Future<Output = Result<bool, FileError>> + MaybeSend {
let path = path.to_owned();
async move {
let promise = js_exists(&path).map_err(|e| map_js_error(&e, &path))?;
let value = JsFuture::from(promise)
.await
.map_err(|e| map_js_error(&e, &path))?;
value
.as_bool()
.ok_or_else(|| FileError::Io(anyhow::anyhow!("exists({path}) did not return a boolean")))
}
}
}

fn map_js_error(err: &JsValue, path: &str) -> FileError {
let code = Reflect::get(err, &JsValue::from_str("code"))
.ok()
.and_then(|v| v.as_string());
match code.as_deref() {
Some("ENOENT") => FileError::NotFound(path.to_owned()),
Some("EACCES") | Some("EPERM") => FileError::PermissionDenied(path.to_owned()),
_ => {
let message = Reflect::get(err, &JsValue::from_str("message"))
.ok()
.and_then(|v| v.as_string())
.unwrap_or_else(|| format!("{err:?}"));
FileError::Io(anyhow::anyhow!("{message} (path: {path})"))
}
}
}

fn parse_metadata(value: &JsValue, path: &str) -> Result<FileMetadata, FileError> {
let size = read_bigint_u64(value, "size", path)?;
// Node populates `stat().ino` on every platform, so `inode` is always Some.
let inode = Some(read_bigint_u64(value, "inode", path)?);
let is_file = read_bool(value, "is_file", path)?;
let is_dir = read_bool(value, "is_dir", path)?;
Ok(FileMetadata {
size,
inode,
is_file,
is_dir,
})
}

fn read_bigint_u64(value: &JsValue, key: &str, path: &str) -> Result<u64, FileError> {
let v = Reflect::get(value, &JsValue::from_str(key))
.map_err(|_| FileError::Io(anyhow::anyhow!("metadata({path}) could not read field `{key}`")))?;
if v.is_undefined() || v.is_null() {
return Err(FileError::Io(anyhow::anyhow!("metadata({path}) missing field `{key}`")));
}
let bigint = js_sys::BigInt::try_from(v)
.map_err(|_| FileError::Io(anyhow::anyhow!("metadata({path}) field `{key}` is not a BigInt")))?;
u64::try_from(bigint)
.map_err(|_| FileError::Io(anyhow::anyhow!("metadata({path}) field `{key}` overflows u64")))
}
Comment thread
Aaalibaba42 marked this conversation as resolved.

fn read_bool(value: &JsValue, key: &str, path: &str) -> Result<bool, FileError> {
Reflect::get(value, &JsValue::from_str(key))
.ok()
.and_then(|v| v.as_bool())
.ok_or_else(|| {
FileError::Io(anyhow::anyhow!(
"metadata({path}) is missing boolean field `{key}`"
))
})
}
36 changes: 36 additions & 0 deletions crates/capabilities/src/file_transport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Lazy `require('node:fs')` — see http_transport.js.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nit: Is it really transport ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mmh I mostly tried to have the same nomenclature as existing in the repository for the js side. Even sleep capability is part of the http_transport.js currently. I think it's something that could be worth refactoring at some point but idk if it's currently a big deal.


'use strict'

module.exports.readFile = function (path) {
const fs = require('node:fs')
return fs.promises.readFile(path)
}

module.exports.writeFile = function (path, data) {
const fs = require('node:fs')
// Copy off the wasm-memory view before the async write; a memory grow would
// otherwise detach the underlying ArrayBuffer mid-write.
return fs.promises.writeFile(path, Buffer.from(data))
}

module.exports.metadata = function (path) {
const fs = require('node:fs')
return fs.promises.stat(path, { bigint: true }).then(s => ({
size: s.size,
inode: s.ino,
is_file: s.isFile(),
is_dir: s.isDirectory(),
}))
}
Comment thread
Aaalibaba42 marked this conversation as resolved.

module.exports.exists = function (path) {
const fs = require('node:fs')
return fs.promises.stat(path).then(
() => true,
(error) => {
if (error && error.code === 'ENOENT') return false
throw error
},
)
}
Loading
Loading