From af66ff6cb9aaab3b6a85a3481037b13ff677fc31 Mon Sep 17 00:00:00 2001 From: crwen <1543720935@qq.com> Date: Wed, 27 Nov 2024 11:21:27 +0800 Subject: [PATCH] make window available in web worker --- fusio/Cargo.toml | 2 ++ fusio/src/impls/disk/opfs/fs.rs | 6 +++--- fusio/src/impls/disk/opfs/mod.rs | 23 +++++++++++++++-------- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/fusio/Cargo.toml b/fusio/Cargo.toml index 44e87e5..eff8e96 100644 --- a/fusio/Cargo.toml +++ b/fusio/Cargo.toml @@ -124,6 +124,8 @@ web-sys = { version = "0.3", optional = true, features = [ "Storage", "StorageManager", "Window", + "WorkerGlobalScope", + "WorkerNavigator", ] } diff --git a/fusio/src/impls/disk/opfs/fs.rs b/fusio/src/impls/disk/opfs/fs.rs index 3044153..fcb7c6f 100644 --- a/fusio/src/impls/disk/opfs/fs.rs +++ b/fusio/src/impls/disk/opfs/fs.rs @@ -19,7 +19,7 @@ use crate::{ error::wasm_err, fs::{FileMeta, FileSystemTag, Fs, OpenOptions}, path::Path, - Error, MaybeSend, + Error, }; pub struct OPFS; @@ -122,7 +122,7 @@ impl OPFS { path: &Path, options: &FileSystemGetDirectoryOptions, ) -> Result { - let mut parent = storage().await; + let mut parent = storage().await?; let segments: Vec<&str> = path.as_ref().trim_matches('/').split("/").collect(); if segments.len() == 1 && segments[0].is_empty() { @@ -148,7 +148,7 @@ impl OPFS { path: &Path, options: &FileSystemGetDirectoryOptions, ) -> Result { - let mut parent = storage().await; + let mut parent = storage().await?; let segments: Vec<&str> = path.as_ref().trim_matches('/').split("/").collect(); let part_len = segments.len(); diff --git a/fusio/src/impls/disk/opfs/mod.rs b/fusio/src/impls/disk/opfs/mod.rs index 95f9ff4..912c219 100644 --- a/fusio/src/impls/disk/opfs/mod.rs +++ b/fusio/src/impls/disk/opfs/mod.rs @@ -8,7 +8,7 @@ use wasm_bindgen_futures::JsFuture; use web_sys::{ wasm_bindgen::JsCast, window, File, FileSystemCreateWritableOptions, FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemWritableFileStream, ReadableStreamDefaultReader, - ReadableStreamReadResult, + ReadableStreamReadResult, WorkerGlobalScope, }; use crate::{error::wasm_err, Error, IoBuf, IoBufMut, Read, Write}; @@ -257,11 +257,18 @@ impl Read for OPFSFile { } } -pub(crate) async fn storage() -> FileSystemDirectoryHandle { - let storage_promise = window().unwrap().navigator().storage().get_directory(); - JsFuture::from(storage_promise) - .await - .unwrap() - .dyn_into::() - .unwrap() +pub(crate) async fn storage() -> Result { + let storage_promise = match window() { + Some(window) => window.navigator().storage(), + None => match js_sys::eval("self") + .unwrap() + .dyn_into::() + { + Ok(worker) => worker.navigator().storage(), + Err(err) => return Err(wasm_err(err)), + }, + } + .get_directory(); + + promise::(storage_promise).await }