-
Notifications
You must be signed in to change notification settings - Fork 1
feat: added file capability [APMSP-3780] #177
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Aaalibaba42
wants to merge
8
commits into
main
Choose a base branch
from
jwiriath/file-caps
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
9e13e69
feat: added file capability
Aaalibaba42 ba4247d
fix: JS tomfoolery
Aaalibaba42 a1b4699
chore: change input to main now that libdatadog's side was merged
Aaalibaba42 1723eb3
fix: post bump fixes
Aaalibaba42 676357a
fix: review
Aaalibaba42 7dfc90e
fix: address comments
Aaalibaba42 3a77c8d
fix: detached buffer thing
Aaalibaba42 01bc290
fix: transport for files renamed, uniform lazy loading
Aaalibaba42 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| //! `filesystem.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/filesystem.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::unchecked_from_js(value); | ||
| Ok(Bytes::from(array.to_vec())) | ||
| } | ||
| } | ||
|
|
||
| #[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"))) | ||
| } | ||
|
|
||
| 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}`" | ||
| )) | ||
| }) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| // Lazy `require('node:fs')` — see http_transport.js. The cached accessor | ||
| // avoids paying the module-resolution cost on every call. | ||
|
|
||
| 'use strict' | ||
|
|
||
| let _fs | ||
| function fs () { | ||
| return _fs ??= require('node:fs') | ||
| } | ||
|
|
||
| module.exports.readFile = function (path) { | ||
| return fs().promises.readFile(path) | ||
| } | ||
|
|
||
| module.exports.writeFile = function (path, data) { | ||
| // 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) { | ||
| return fs().promises.stat(path, { bigint: true }).then(s => ({ | ||
| size: s.size, | ||
| inode: s.ino, | ||
| is_file: s.isFile(), | ||
| is_dir: s.isDirectory(), | ||
| })) | ||
| } | ||
|
Aaalibaba42 marked this conversation as resolved.
|
||
|
|
||
| module.exports.exists = function (path) { | ||
| return fs().promises.stat(path).then( | ||
| () => true, | ||
| (error) => { | ||
| if (error && error.code === 'ENOENT') return false | ||
| throw error | ||
| }, | ||
| ) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.