diff --git a/Cargo.lock b/Cargo.lock index 9f0637c0..d9da5847 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -128,6 +128,17 @@ dependencies = [ "event-listener", ] +[[package]] +name = "async-recursion" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cda8f4bcc10624c4e85bc66b3f452cca98cfa5ca002dc83a16aad2367641bea" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "async-std" version = "1.11.0" @@ -307,10 +318,12 @@ version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" dependencies = [ + "js-sys", "libc", "num-integer", "num-traits", "time", + "wasm-bindgen", "winapi", ] @@ -1436,6 +1449,7 @@ name = "wnfs" version = "0.1.0" dependencies = [ "anyhow", + "async-recursion", "async-std", "async-trait", "chrono", @@ -1444,14 +1458,3 @@ dependencies = [ "multihash", "semver", ] - -[[package]] -name = "wnfs-tests" -version = "0.1.0" -dependencies = [ - "js-sys", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "wnfs", -] diff --git a/Cargo.toml b/Cargo.toml index 6e595547..8bdaf9bd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,5 @@ [workspace] members = [ - 'packages/tests', - 'packages/fs', - 'packages/wasm' + 'crates/fs', + 'crates/wasm' ] diff --git a/crates/LICENSE b/crates/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/crates/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/fs/Cargo.toml b/crates/fs/Cargo.toml similarity index 96% rename from packages/fs/Cargo.toml rename to crates/fs/Cargo.toml index 371105c9..0d50ddf8 100644 --- a/packages/fs/Cargo.toml +++ b/crates/fs/Cargo.toml @@ -24,6 +24,7 @@ anyhow = "1.0.56" hashbrown = "0.12.0" async-trait = "0.1.53" async-std = { version = "1.11.0", features = ["attributes"] } +async-recursion = "1.0.0" [lib] path = "lib.rs" diff --git a/packages/fs/README.md b/crates/fs/README.md similarity index 100% rename from packages/fs/README.md rename to crates/fs/README.md diff --git a/packages/fs/common/blockstore.rs b/crates/fs/common/blockstore.rs similarity index 63% rename from packages/fs/common/blockstore.rs rename to crates/fs/common/blockstore.rs index acc5d11c..4e3f6c16 100644 --- a/packages/fs/common/blockstore.rs +++ b/crates/fs/common/blockstore.rs @@ -1,17 +1,18 @@ //! Block store traits. -use super::FsError; +use std::borrow::Cow; + use anyhow::Result; use async_trait::async_trait; use hashbrown::HashMap; use libipld::{ - cbor::DagCborCodec, cid::Version, codec::{Codec, Decode}, Cid, IpldCodec, }; use multihash::{Code, MultihashDigest}; -use std::borrow::Cow; + +use super::FsError; //-------------------------------------------------------------------------------------------------- // Type Definitions @@ -27,7 +28,7 @@ pub trait BlockStoreLookup { #[async_trait] pub trait BlockStoreCidLoad { /// Loads a cbor model from the store with provided CID. - async fn load>(&self, cid: &Cid) -> Result; + async fn load, C: Codec>(&self, cid: &Cid, decoder: C) -> Result; } /// For types that implement block store operations. @@ -80,12 +81,55 @@ impl BlockStoreLookup for MemoryBlockStore { #[async_trait] impl BlockStoreCidLoad for MemoryBlockStore { /// Loads a cbor-encoded data from the store with provided CID. - async fn load>(&self, cid: &Cid) -> Result { + async fn load, C: Codec>(&self, cid: &Cid, decoder: C) -> Result { let bytes = self.get_block(cid).await?; - let decoded = DagCborCodec.decode(bytes.as_ref())?; + let decoded = decoder.decode(bytes.as_ref())?; Ok(decoded) } } #[cfg(test)] -mod blockstore_tests {} +mod blockstore_tests { + use libipld::{cbor::DagCborCodec, codec::Encode}; + + use super::*; + + #[async_std::test] + async fn items_inserted_fetched_successfully() { + let mut store = MemoryBlockStore::new(); + + let first_bytes = { + let mut tmp = vec![]; + vec![1, 2, 3, 4, 5] + .to_vec() + .encode(DagCborCodec, &mut tmp) + .unwrap(); + tmp + }; + + let second_bytes = { + let mut tmp = vec![]; + b"hello world" + .to_vec() + .encode(DagCborCodec, &mut tmp) + .unwrap(); + tmp + }; + + let first_cid = &store + .put_block(first_bytes, IpldCodec::DagCbor) + .await + .unwrap(); + + let second_cid = &store + .put_block(second_bytes, IpldCodec::DagCbor) + .await + .unwrap(); + + let first_loaded: Vec = store.load(first_cid, DagCborCodec).await.unwrap(); + let second_loaded: Vec = store.load(second_cid, DagCborCodec).await.unwrap(); + + assert_eq!(first_loaded, vec![1, 2, 3, 4, 5]); + assert_eq!(second_loaded, b"hello world".to_vec()); + } +} diff --git a/packages/fs/common/error.rs b/crates/fs/common/error.rs similarity index 99% rename from packages/fs/common/error.rs rename to crates/fs/common/error.rs index 8079f961..dedc8cf9 100644 --- a/packages/fs/common/error.rs +++ b/crates/fs/common/error.rs @@ -1,11 +1,12 @@ //! File system errors. -use anyhow::Result; use std::{ error::Error, fmt::{Debug, Display}, }; +use anyhow::Result; + #[derive(Debug, Clone, PartialEq, Eq)] pub enum FsError { CIDNotFoundInBlockstore, diff --git a/packages/fs/common/metadata.rs b/crates/fs/common/metadata.rs similarity index 52% rename from packages/fs/common/metadata.rs rename to crates/fs/common/metadata.rs index a6288563..069b0158 100644 --- a/packages/fs/common/metadata.rs +++ b/crates/fs/common/metadata.rs @@ -1,12 +1,27 @@ //! File system metadata. +use std::{ + io::{Read, Seek, Write}, + str::FromStr, +}; + +use anyhow::Result; use chrono::{DateTime, Utc}; +use libipld::{ + cbor::DagCborCodec, + codec::{Decode, Encode}, + DagCbor, +}; use semver::Version; +//-------------------------------------------------------------------------------------------------- +// Type Definitions +//-------------------------------------------------------------------------------------------------- + /// Represents the type of node in the UnixFS file system. /// /// See https://docs.ipfs.io/concepts/file-systems/#unix-file-system-unixfs -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Copy, DagCbor)] pub enum UnixFsNodeKind { Raw, File, @@ -21,7 +36,7 @@ pub enum UnixFsNodeKind { /// See /// - https://docs.ipfs.io/concepts/file-systems/#unix-file-system-unixfs /// - https://en.wikipedia.org/wiki/File-system_permissions#Numeric_notation -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, DagCbor)] pub enum UnixFsMode { NoPermissions = 0, OwnerReadWriteExecute = 700, @@ -41,21 +56,25 @@ pub enum UnixFsMode { /// The metadata of a node in the UnixFS file system. /// /// See https://docs.ipfs.io/concepts/file-systems/#unix-file-system-unixfs -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, DagCbor)] pub struct UnixFsMetadata { - created: DateTime, - modified: DateTime, - mode: UnixFsMode, - kind: UnixFsNodeKind, + pub(crate) created: i64, + pub(crate) modified: i64, + pub(crate) mode: UnixFsMode, + pub(crate) kind: UnixFsNodeKind, } /// The metadata of a node on the WNFS file system. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Metadata { - unixfs_metadata: UnixFsMetadata, - version: Version, + pub(crate) unix_fs: UnixFsMetadata, + pub(crate) version: Version, } +//-------------------------------------------------------------------------------------------------- +// Implementations +//-------------------------------------------------------------------------------------------------- + impl Metadata { /// Creates a new metadata representing a UnixFS node. pub fn new(time: DateTime, kind: UnixFsNodeKind) -> Self { @@ -66,8 +85,10 @@ impl Metadata { UnixFsMode::OwnerReadWriteExecuteGroupOthersReadExecute }; + let time = time.timestamp(); + Self { - unixfs_metadata: UnixFsMetadata { + unix_fs: UnixFsMetadata { created: time, modified: time, mode, @@ -78,5 +99,29 @@ impl Metadata { } } +impl Decode for Metadata { + fn decode(c: DagCborCodec, r: &mut R) -> Result { + let unix_fs = UnixFsMetadata::decode(c, r)?; + let version_str = String::decode(c, r)?; + let version = Version::from_str(&version_str)?; + + Ok(Self { unix_fs, version }) + } +} + +impl Encode for Metadata { + fn encode(&self, c: DagCborCodec, w: &mut W) -> Result<()> { + self.unix_fs.encode(c, w)?; + self.version.to_string().encode(c, w)?; + + Ok(()) + } +} + #[cfg(test)] -mod metadata_tests {} +mod metadata_tests { + #[async_std::test] + async fn metadata_encode_decode_successful() { + // TODO(appcypher): Implement this. + } +} diff --git a/packages/fs/common/mod.rs b/crates/fs/common/mod.rs similarity index 100% rename from packages/fs/common/mod.rs rename to crates/fs/common/mod.rs diff --git a/packages/fs/lib.rs b/crates/fs/lib.rs similarity index 100% rename from packages/fs/lib.rs rename to crates/fs/lib.rs diff --git a/crates/fs/public/directory.rs b/crates/fs/public/directory.rs new file mode 100644 index 00000000..0aa4d58e --- /dev/null +++ b/crates/fs/public/directory.rs @@ -0,0 +1,231 @@ +//! Public fs directory node. + +use std::{ + collections::BTreeMap, + io::{Read, Seek}, + rc::Rc, +}; + +use crate::{error, BlockStore, FsError, Metadata, UnixFsNodeKind}; +use anyhow::Result; +use async_recursion::async_recursion; +use chrono::{DateTime, Utc}; +use libipld::{ + cbor::DagCborCodec, + codec::{Decode, Encode}, + Cid, IpldCodec, +}; + +use super::{Link, PublicNode}; + +/// A directory in a WNFS public file system. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PublicDirectory { + pub(crate) metadata: Metadata, + pub(crate) userland: BTreeMap, + pub(crate) previous: Option, +} + +impl PublicDirectory { + /// Creates a new directory using the given metadata. + pub fn new(time: DateTime) -> Self { + Self { + metadata: Metadata::new(time, UnixFsNodeKind::Dir), + userland: BTreeMap::new(), + previous: None, + } + } + + /// Follows a path and fetches the node at the end of the path. + pub async fn get_node( + &self, + path_segments: &[String], + store: &B, + ) -> Result> { + if path_segments.is_empty() { + return error(FsError::InvalidPath); + } + + let mut working_node: Rc = Rc::new(PublicNode::Dir(self.clone())); + + // Iterate over the path segments until we get the node of the last segment. + for (index, segment) in path_segments.iter().enumerate() { + // Cast working node to directory. + let dir = working_node.as_dir(); + + // Fetch node representing path segment in working directory. + if let Some(node) = dir.lookup_node(segment, store).await? { + match node.as_ref() { + PublicNode::Dir(_) => { + // If the node is a directory, set it as the working node. + working_node = Rc::clone(&node); + } + PublicNode::File(_) => { + // If the node is a file, we return it if it's the last segment. + if index != path_segments.len() - 1 { + return error(FsError::InvalidPath); + } + working_node = Rc::clone(&node); + break; + } + } + + // We continue loop after setting the working node to a directory node. + continue; + } + + // If the node is not found, we return an error. + return error(FsError::NodeNotFound); + } + + Ok(working_node) + } + + /// Looks up a node by its path name in the current directory. + /// + /// TODO(appcypher): What is a valid path segment identifier? + pub async fn lookup_node( + &self, + path_segment: &str, + store: &B, + ) -> Result>> { + Ok(match self.userland.get(path_segment) { + Some(link) => Some(link.resolve(store).await?), + None => None, + }) + } + + /// Encode the directory as a CBOR object. + pub async fn encode(&self, store: &mut B) -> Result> { + let mut bytes = Vec::new(); + self.metadata.encode(DagCborCodec, &mut bytes)?; + + let new_userland = { + let mut tmp = BTreeMap::new(); + for (k, link) in self.userland.iter() { + let cid = link.seal(store).await?; + tmp.insert(k.clone(), cid); + } + tmp + }; + + new_userland.encode(DagCborCodec, &mut bytes)?; + + self.previous.encode(DagCborCodec, &mut bytes)?; + Ok(bytes) + } + + /// Stores WNFS directory as block(s) in chosen block store. + /// + /// This function can be recursive if the directory contains other directories. + #[async_recursion(?Send)] + pub async fn store(&self, store: &mut B) -> Result { + let bytes = self.encode(store).await?; + store.put_block(bytes, IpldCodec::DagCbor).await + } + + /// Writes a file to the directory. + /// + /// Rather than mutate the directory directly, we create a new directory and return it. + pub async fn write( + &self, + path: &[String], + content_cid: &Cid, + store: &mut B, + ) -> Result { + // TODO(appcypher): Implement this. + todo!() + } +} + +impl Decode for PublicDirectory { + fn decode(c: DagCborCodec, r: &mut R) -> Result { + let metadata = Metadata::decode(c, r)?; + let userland = BTreeMap::::decode(c, r)? + .into_iter() + .map(|(k, cid)| (k, Link::Cid(cid))) + .collect(); + + let previous = Option::::decode(c, r)?; + + Ok(Self { + metadata, + userland, + previous, + }) + } +} + +#[cfg(test)] +mod public_directory_tests { + use std::io::Cursor; + + use super::*; + use crate::{BlockStoreLookup, MemoryBlockStore}; + use chrono::Utc; + + // #[async_std::test] + // async fn files_added_to_directory_looked_up_unsuccessful() { + // let root = PublicDirectory::new(Utc::now()); + + // let mut store = MemoryBlockStore::default(); + + // let content_cid = &Cid::default(); + + // let root = root + // .write(&[String::from("text.txt")], content_cid, &mut store) + // .await + // .unwrap(); + + // let node = root.lookup_node("text.txt", &store).await; + + // assert!(node.is_ok()); + + // assert_eq!(node.unwrap(), None); + // } + + #[async_std::test] + async fn files_not_added_to_directory_not_looked_up_unsuccessful() { + let root = PublicDirectory::new(Utc::now()); + + let store = MemoryBlockStore::default(); + + let node = root.lookup_node("Unknown", &store).await; + + assert!(node.is_ok()); + + assert_eq!(node.unwrap(), None); + } + + #[async_std::test] + async fn directory_added_to_store_fetched_successfully() { + let root = PublicDirectory::new(Utc::now()); + + let mut store = MemoryBlockStore::default(); + + let cid = root.store(&mut store).await.unwrap(); + + let bytes = store.get_block(&cid).await.unwrap(); + + let mut cursor = Cursor::new(bytes); + + let decoded_root = PublicDirectory::decode(DagCborCodec, &mut cursor).unwrap(); + + assert_eq!(root, decoded_root); + } + + #[async_std::test] + async fn directory_encode_decode_successful() { + let root = PublicDirectory::new(Utc::now()); + + let mut store = MemoryBlockStore::default(); + + let encoded_bytes = root.encode(&mut store).await.unwrap(); + + let mut cursor = Cursor::new(encoded_bytes); + + let decoded_root = PublicDirectory::decode(DagCborCodec, &mut cursor).unwrap(); + + assert_eq!(root, decoded_root); + } +} diff --git a/crates/fs/public/file.rs b/crates/fs/public/file.rs new file mode 100644 index 00000000..6a84714c --- /dev/null +++ b/crates/fs/public/file.rs @@ -0,0 +1,61 @@ +//! Public fs file node. + +use anyhow::Result; +use chrono::{DateTime, Utc}; +use libipld::{cbor::DagCborCodec, prelude::Encode, Cid, DagCbor, IpldCodec}; + +use crate::{BlockStore, Metadata, UnixFsNodeKind}; + +/// A file in a WNFS public file system. +#[derive(Debug, Clone, PartialEq, Eq, DagCbor)] +pub struct PublicFile { + pub(crate) metadata: Metadata, + pub(crate) userland: Cid, + pub(crate) previous: Option, +} + +impl PublicFile { + /// Creates a new file using the given metadata and CID. + pub fn new(time: DateTime, userland: Cid) -> Self { + Self { + metadata: Metadata::new(time, UnixFsNodeKind::File), + userland, + previous: None, + } + } + + /// Stores WNFS block(s) in chosen block store. + pub async fn store(&self, store: &mut B) -> Result { + let bytes = { + let mut tmp = vec![]; + self.encode(DagCborCodec, &mut tmp)?; + tmp + }; + store.put_block(bytes, IpldCodec::DagCbor).await + } +} + +#[cfg(test)] +mod public_file_tests { + use std::io::Cursor; + + use chrono::Utc; + use libipld::prelude::Decode; + + use super::*; + + #[async_std::test] + async fn directory_encode_decode_successful() { + let file = PublicFile::new(Utc::now(), Cid::default()); + + let mut encoded_bytes = vec![]; + + file.encode(DagCborCodec, &mut encoded_bytes).unwrap(); + + let mut cursor = Cursor::new(encoded_bytes); + + let decoded_file = PublicFile::decode(DagCborCodec, &mut cursor).unwrap(); + + assert_eq!(file, decoded_file); + } +} diff --git a/crates/fs/public/link.rs b/crates/fs/public/link.rs new file mode 100644 index 00000000..0d05c45c --- /dev/null +++ b/crates/fs/public/link.rs @@ -0,0 +1,53 @@ +//! Node link. + +use std::rc::Rc; + +use anyhow::Result; +use libipld::{cbor::DagCborCodec, Cid}; + +use super::PublicNode; +use crate::BlockStore; + +/// A link to another node in the WNFS public file system. It can be held as a simple serialised CID or as a reference to the node itself. +/// +/// The public file system is a DAG so we don't have to worry bout cyclic references. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Link { + Cid(Cid), + Node(Rc), +} + +impl Link { + // Resolves a CID link in the file system to a node. + pub async fn resolve(&self, store: &B) -> Result> { + Ok(match self { + Link::Cid(cid) => { + let node = store.load(cid, DagCborCodec).await?; + Rc::new(node) + } + Link::Node(node) => Rc::clone(node), + }) + } + + // Stores the link in the block store and returns the CID. + pub async fn seal(&self, store: &mut B) -> Result { + Ok(match self { + Link::Cid(cid) => *cid, + Link::Node(node) => node.store(store).await?, + }) + } +} + + +#[cfg(test)] +mod public_link_tests { + #[async_std::test] + async fn node_link_sealed_successfully() { + // TODO(appcypher): Implement. + } + + #[async_std::test] + async fn cid_link_resolved_successfully() { + // TODO(appcypher): Implement. + } +} diff --git a/crates/fs/public/mod.rs b/crates/fs/public/mod.rs new file mode 100644 index 00000000..b68865d0 --- /dev/null +++ b/crates/fs/public/mod.rs @@ -0,0 +1,9 @@ +mod directory; +mod file; +mod link; +mod node; + +pub use directory::*; +pub use file::*; +pub use link::*; +pub use node::*; diff --git a/crates/fs/public/node.rs b/crates/fs/public/node.rs new file mode 100644 index 00000000..889b1ef5 --- /dev/null +++ b/crates/fs/public/node.rs @@ -0,0 +1,128 @@ +//! Public file system in-memory representation. + +use std::{ + collections::BTreeMap, + io::{Read, Seek}, +}; + +use anyhow::Result; +use libipld::{cbor::DagCborCodec, codec::Decode, Cid}; + +use super::{Link, PublicDirectory, PublicFile}; +use crate::{common::BlockStore, Metadata, UnixFsNodeKind}; + +/// A node in a WNFS public file system. This can either be a file or a directory. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PublicNode { + File(PublicFile), + Dir(PublicDirectory), +} + +impl PublicNode { + /// Stores a WNFS node as block(s) in chosen block store. + pub async fn store(&self, store: &mut B) -> Result { + Ok(match self { + PublicNode::File(file) => file.store(store).await?, + PublicNode::Dir(dir) => dir.store(store).await?, + }) + } + + /// Casts a node to a directory. + /// + /// # Panics + /// + /// Panics if the node is not a directory. + pub fn as_dir(&self) -> &PublicDirectory { + match self { + PublicNode::Dir(dir) => dir, + _ => unreachable!(), + } + } +} + +impl Decode for PublicNode { + fn decode(c: DagCborCodec, r: &mut R) -> Result { + let metadata = Metadata::decode(c, r)?; + let node = if matches!(metadata.unix_fs.kind, UnixFsNodeKind::File) { + let userland = Cid::decode(c, r)?; + let previous = >::decode(c, r)?; + + PublicNode::File(PublicFile { + metadata, + userland, + previous, + }) + } else { + let userland = BTreeMap::::decode(c, r)? + .into_iter() + .map(|(k, cid)| (k, Link::Cid(cid))) + .collect(); + + let previous = >::decode(c, r)?; + + PublicNode::Dir(PublicDirectory { + metadata, + userland, + previous, + }) + }; + + Ok(node) + } +} + +#[cfg(test)] +mod public_node_tests { + use std::io::Cursor; + + use chrono::Utc; + use libipld::{cbor::DagCborCodec, codec::Decode, Cid, prelude::Encode}; + + use crate::{ + public::{PublicDirectory, PublicFile, PublicNode}, + MemoryBlockStore, + }; + + // #[async_std::test] + // async fn encoded_public_file_decoded_successfully() { + // let file = PublicFile::new(Utc::now(), Cid::default()); + + // dbg!(&file); + + // let mut encoded_bytes = vec![]; + + // file.encode(DagCborCodec, &mut encoded_bytes).unwrap(); + + // dbg!(format!("{:02x?}", encoded_bytes)); + + // let mut cursor = Cursor::new(encoded_bytes); + + // let decoded_file = PublicNode::decode(DagCborCodec, &mut cursor).unwrap(); + + // assert_eq!(PublicNode::File(file), decoded_file); + // } + + #[async_std::test] + async fn encoded_public_directory_decoded_successfully() { + let directory = PublicDirectory::new(Utc::now()); + + let mut store = MemoryBlockStore::default(); + + let encoded_bytes = directory.encode(&mut store).await.unwrap(); + + let mut cursor = Cursor::new(encoded_bytes); + + let decoded_directory = PublicNode::decode(DagCborCodec, &mut cursor).unwrap(); + + assert_eq!(PublicNode::Dir(directory), decoded_directory); + } + + #[async_std::test] + async fn public_directory_casted_successfully() { + let directory = PublicDirectory::new(Utc::now()); + + let node = PublicNode::Dir(directory.clone()); + + assert_eq!(node.as_dir(), &directory); + } +} diff --git a/packages/wasm/.prettierrc b/crates/wasm/.prettierrc similarity index 100% rename from packages/wasm/.prettierrc rename to crates/wasm/.prettierrc diff --git a/packages/wasm/Cargo.toml b/crates/wasm/Cargo.toml similarity index 84% rename from packages/wasm/Cargo.toml rename to crates/wasm/Cargo.toml index e8b5c7b8..c33aeb89 100644 --- a/packages/wasm/Cargo.toml +++ b/crates/wasm/Cargo.toml @@ -21,7 +21,7 @@ wasm-bindgen = { version = "0.2.79", optional = true } wasm-bindgen-futures = { version = "0.4.29", optional = true } js-sys = { version = "0.3.56", optional = true } web-sys = { version = "0.3.56", optional = true } -chrono = "0.4.19" +chrono = { version = "0.4.19", features = ["wasmbind"] } anyhow = "1.0.56" [lib] @@ -31,6 +31,12 @@ crate-type = ["cdylib" , "rlib"] [features] default = ["js"] wasm = ["wnfs/wasm"] -js = ["wasm", "wasm-bindgen", "wasm-bindgen-futures", "js-sys"] +js = [ + "wasm", + "wasm-bindgen", + "wasm-bindgen-futures", + "js-sys", + "chrono/wasmbind", +] web = ["wasm", "web-sys"] diff --git a/packages/wasm/README.md b/crates/wasm/README.md similarity index 100% rename from packages/wasm/README.md rename to crates/wasm/README.md diff --git a/crates/wasm/fs/blockstore.rs b/crates/wasm/fs/blockstore.rs new file mode 100644 index 00000000..e69de29b diff --git a/crates/wasm/fs/mod.rs b/crates/wasm/fs/mod.rs new file mode 100644 index 00000000..460f6654 --- /dev/null +++ b/crates/wasm/fs/mod.rs @@ -0,0 +1,5 @@ +mod blockstore; +mod public; + +pub use blockstore::*; +pub use public::*; diff --git a/crates/wasm/fs/public/directory.rs b/crates/wasm/fs/public/directory.rs new file mode 100644 index 00000000..e69de29b diff --git a/crates/wasm/fs/public/file.rs b/crates/wasm/fs/public/file.rs new file mode 100644 index 00000000..e69de29b diff --git a/crates/wasm/fs/public/mod.rs b/crates/wasm/fs/public/mod.rs new file mode 100644 index 00000000..43350827 --- /dev/null +++ b/crates/wasm/fs/public/mod.rs @@ -0,0 +1,5 @@ +mod directory; +mod file; + +pub use directory::*; +pub use file::*; diff --git a/crates/wasm/index.html b/crates/wasm/index.html new file mode 100644 index 00000000..f94d7033 --- /dev/null +++ b/crates/wasm/index.html @@ -0,0 +1,11 @@ + + + + + + + Document + + + + diff --git a/crates/wasm/index.js b/crates/wasm/index.js new file mode 100644 index 00000000..164a9d80 --- /dev/null +++ b/crates/wasm/index.js @@ -0,0 +1,9 @@ +import init, { lookup_node } from "./pkg/wasm_wnfs.js"; + +init().then(async () => { + console.log(">>> Getting started 2"); + + const result = await lookup_node(); + + console.log(result); +}); diff --git a/packages/wasm/lib.rs b/crates/wasm/lib.rs similarity index 100% rename from packages/wasm/lib.rs rename to crates/wasm/lib.rs diff --git a/packages/wasm/package.json b/crates/wasm/package.json similarity index 100% rename from packages/wasm/package.json rename to crates/wasm/package.json diff --git a/packages/wasm/webpack.config.js b/crates/wasm/webpack.config.js similarity index 100% rename from packages/wasm/webpack.config.js rename to crates/wasm/webpack.config.js diff --git a/packages/wasm/yarn.lock b/crates/wasm/yarn.lock similarity index 100% rename from packages/wasm/yarn.lock rename to crates/wasm/yarn.lock diff --git a/packages/fs/public/filesystem.rs b/packages/fs/public/filesystem.rs deleted file mode 100644 index e2074d15..00000000 --- a/packages/fs/public/filesystem.rs +++ /dev/null @@ -1,39 +0,0 @@ -//! The public file system API. - -use super::PublicDirectory; -use crate::common::BlockStore; -use anyhow::Result; - -//-------------------------------------------------------------------------------------------------- -// Type Definitions -//-------------------------------------------------------------------------------------------------- - -/// The WNFS public file system. -struct PublicFileSystem<'s, T: BlockStore> { - blockstore: &'s T, - root_dir: PublicDirectory, -} - -//-------------------------------------------------------------------------------------------------- -// Implementations -//-------------------------------------------------------------------------------------------------- - -impl<'s, T: BlockStore> PublicFileSystem<'s, T> { - /// Creates a new WNFS public file system. - pub fn new(blockstore: &'s T, root_dir: PublicDirectory) -> Self { - Self { - blockstore, - root_dir, - } - } - - /// Reads file content at the specified path from the file system. - pub async fn read(path_segments: &[String]) -> Result<()> { - todo!( - r#" - This is entering javascript land. - We can make writing file blocks to linear memory and return the base address. - "# - ) - } -} diff --git a/packages/fs/public/mod.rs b/packages/fs/public/mod.rs deleted file mode 100644 index 107486c4..00000000 --- a/packages/fs/public/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -mod filesystem; -mod node; - -pub use filesystem::*; -pub use node::*; diff --git a/packages/fs/public/node.rs b/packages/fs/public/node.rs deleted file mode 100644 index acfcec6e..00000000 --- a/packages/fs/public/node.rs +++ /dev/null @@ -1,192 +0,0 @@ -//! Public file system in-memory representation. - -use crate::common::{error, BlockStore, FsError, Metadata, UnixFsNodeKind}; -use anyhow::Result; -use chrono::{DateTime, Utc}; -use hashbrown::HashMap; -use libipld::{cbor::DagCborCodec, codec::Decode, Cid}; -use std::{ops::Deref, rc::Rc}; - -//-------------------------------------------------------------------------------------------------- -// Type Definitions -//-------------------------------------------------------------------------------------------------- - -/// A node in a WNFS public file system. This can either be a file or a directory. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum PublicNode { - File(PublicFile), - Dir(PublicDirectory), -} - -/// A link to another node in the WNFS public file system. It can be held as a simple serialised CID or as a reference to the node itself. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Link { - Cid(Cid), - Node(Rc), -} - -/// A directory in a WNFS public file system. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PublicDirectory { - // metadata: Metadata, - userland: HashMap, - // previous: Option, -} - -/// A file in a WNFS public file system. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PublicFile { - metadata: Metadata, - userland: Cid, - previous: Option, -} - -//-------------------------------------------------------------------------------------------------- -// Implementations -//-------------------------------------------------------------------------------------------------- - -// TODO(appcypher) -impl Decode for PublicNode { - fn decode(c: DagCborCodec, r: &mut R) -> Result { - todo!() - } -} - -impl PublicNode { - /// Stores a WNFS node as block(s) in chosen block store. - pub async fn store(&self, store: &mut B) -> Cid { - match self { - PublicNode::File(file) => file.store(store).await, - PublicNode::Dir(dir) => dir.store(store).await, - } - } - - /// Casts a node to a directory. - /// - /// # Panics - /// - /// Panics if the node is not a directory. - pub fn as_dir(&self) -> &PublicDirectory { - match self { - PublicNode::Dir(dir) => dir, - _ => unreachable!(), - } - } -} - -impl PublicDirectory { - /// Creates a new directory using the given metadata. - pub fn new(time: DateTime) -> Self { - Self { - // metadata: Metadata::new(time, UnixFsNodeKind::Dir), - userland: HashMap::new(), - // previous: None, - } - } - - /// Follows a path and fetches the node at the end of the path. - pub async fn get_node( - &self, - path_segments: &[String], - store: &B, - ) -> Result> { - if path_segments.is_empty() { - return error(FsError::InvalidPath); - } - - let mut working_node: Rc = Rc::new(PublicNode::Dir(self.clone())); - - // Iterate over the path segments until we get the node of the last segment. - for (index, segment) in path_segments.iter().enumerate() { - // Cast working node to directory. - let dir = working_node.deref().as_dir(); - - // Fetch node representing path segment in working directory. - if let Some(node) = dir.lookup_node(segment, store).await? { - match node.as_ref() { - PublicNode::Dir(_) => { - // If the node is a directory, set it as the working node. - working_node = Rc::clone(&node); - } - PublicNode::File(_) => { - // If the node is a file, we return it if it's the last segment. - if index != path_segments.len() - 1 { - return error(FsError::InvalidPath); - } - working_node = Rc::clone(&node); - break; - } - } - - // We continue loop after setting the working node to a directory node. - continue; - } - - // If the node is not found, we return an error. - return error(FsError::NodeNotFound); - } - - Ok(working_node) - } - - /// Looks up a node by its path name in the current directory. - /// - /// TODO(appcypher): What is a valid path segment identifier? - pub async fn lookup_node( - &self, - path_segment: &str, - store: &B, - ) -> Result>> { - Ok(match self.userland.get(path_segment) { - Some(link) => Some(link.resolve(store).await?), - None => None, - }) - } - - /// Stores WNFS directory as block(s) in chosen block store. - pub async fn store(&self, store: &mut B) -> Cid { - todo!() - } -} - -impl PublicFile { - /// Stores WNFS block(s) in chosen block store. - pub async fn store(&self, store: &mut B) -> Cid { - todo!() - } -} - -impl Link { - // Resolves a CID link in the file system to a node. - pub async fn resolve(&self, store: &B) -> Result> { - Ok(match self { - Link::Cid(cid) => { - let node = store.load(cid).await?; - Rc::new(node) - } - Link::Node(node) => Rc::clone(node), - }) - } - - // Adds the link to the file system. - pub async fn seal(&self, store: &mut B) { - todo!() - } -} - -#[cfg(test)] -mod public_node_tests { - use super::PublicDirectory; - use crate::MemoryBlockStore; - use chrono::Utc; - - #[async_std::test] - async fn unadded_node_lookup_unsuccessful() { - let root = PublicDirectory::new(Utc::now()); - let store = MemoryBlockStore::default(); - let node = root.lookup_node("Unknown", &store).await; - dbg!(&node); - assert!(node.is_ok()); - assert_eq!(node.unwrap(), None); - } -} diff --git a/packages/tests/Cargo.toml b/packages/tests/Cargo.toml deleted file mode 100644 index 908a00a9..00000000 --- a/packages/tests/Cargo.toml +++ /dev/null @@ -1,31 +0,0 @@ -[package] -name = "wnfs-tests" -version = "0.1.0" -description = "WebNative filesystem integration tests" -keywords = ["wnfs", "webnative", "ipfs", "decentralisation"] -categories = [ - "filesystem", - "cryptography", - "web programming", -] -license-file = "../../LICENSE" -readme = "README.md" -edition = "2021" -repository = "https://github.com/fission-suite/rs-wnfs" -homepage = "https://fission.codes" -authors = ["The Fission Authors"] - -[dependencies] -wnfs = { path = "../fs", version = "0.1.0" } -wasm-bindgen = { version = "0.2.79", optional = true } -wasm-bindgen-futures = { version = "0.4.29", optional = true } -js-sys = { version = "0.3.56", optional = true } -web-sys = { version = "0.3.56", optional = true } - -[lib] -path = "lib.rs" - -[features] -default = ["wasm"] -wasm = ["wasm-bindgen", "wasm-bindgen-futures", "js-sys", "wnfs/wasm"] -web = ["wasm", "web-sys"] diff --git a/packages/tests/README.md b/packages/tests/README.md deleted file mode 100644 index 5984be26..00000000 --- a/packages/tests/README.md +++ /dev/null @@ -1 +0,0 @@ -## The Integration Tests diff --git a/packages/tests/lib.rs b/packages/tests/lib.rs deleted file mode 100644 index 693a9678..00000000 --- a/packages/tests/lib.rs +++ /dev/null @@ -1,7 +0,0 @@ -#[cfg(test)] -mod test { - #[test] - fn test_add() { - // assert!(1 + 1 == 2); - } -} diff --git a/packages/wasm/fs/mod.rs b/packages/wasm/fs/mod.rs deleted file mode 100644 index a4f34753..00000000 --- a/packages/wasm/fs/mod.rs +++ /dev/null @@ -1,28 +0,0 @@ -use chrono::Utc; -use wasm_bindgen::prelude::*; -use wnfs::{public::PublicDirectory, BlockStore, BlockStoreLookup, IpldCodec, MemoryBlockStore}; - -#[wasm_bindgen] -pub async fn lookup_node() -> String { - let root = PublicDirectory::new(Utc::now()); - - let store = MemoryBlockStore::default(); - - let node = root.lookup_node("Test", &store).await.unwrap(); - - format!("Node lookup done!: {:?}", node) -} - -// #[wasm_bindgen] -// pub async fn lookup_node() -> String { -// let mut store = MemoryBlockStore::default(); - -// let cid = store -// .put_block(vec![0, 255, 1], IpldCodec::DagCbor) -// .await -// .unwrap(); - -// let bytes = store.get_block(&cid).await.unwrap(); - -// format!("Node lookup done!: CID = {:?} | bytes = {:?}", cid, bytes) -// }