Skip to content

Commit

Permalink
Basic documentation (#244)
Browse files Browse the repository at this point in the history
Add basic documentation comments for rust docs
  • Loading branch information
pileks authored Oct 17, 2023
1 parent 0b89c29 commit 7d381f4
Show file tree
Hide file tree
Showing 26 changed files with 305 additions and 35 deletions.
28 changes: 28 additions & 0 deletions .github/workflows/cd-docs.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: Build and Deploy Documentation

on:
push:
branches:
main

jobs:
deploy-docs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3

- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: 1.72.0
override: true

- name: Generate reference
run: cargo doc --no-deps --workspace --exclude wrap_manifest_schemas --exclude polywrap_tests_utils

- name: Deploy documentation to GitHub Pages
uses: JamesIves/github-pages-deploy-action@v4
with:
branch: gh-pages-reference
folder: target/doc/
36 changes: 14 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Add this to your Cargo.toml:

```toml
[dependencies]
polywrap = 0.1.6
polywrap = 0.1.9
```

## Getting started
Expand All @@ -19,41 +19,33 @@ Create a new Polywrap Client Config Builder instance, add the bundles you want t

```rust
use polywrap::*;
use serde::*;

#[derive(Serialize)]
struct CatArgs {
cid: String,
#[serde(rename = "ipfsProvider")]
ipfs_provider: String,
struct Sha3_256Args {
message: String,
}

fn main() {
let mut config = PolywrapClientConfig::new();
let mut config = ClientConfig::new();
config.add(SystemClientConfig::default().into());
let client = PolywrapClient::new(config.build());
let client = Client::new(config.build());

let result = client.invoke::<ByteBuf>(
uri!("wrapscan.io/polywrap/ipfs-client@1.0"),
"cat",
let result = client.invoke::<String>(
&uri!("wrapscan.io/polywrap/sha3@1.0"),
"sha3_256",
Some(&to_vec(
&CatArgs {
cid: "QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR".to_string(),
ipfs_provider: "https://ipfs.io".to_string(),
&Sha3_256Args {
message: "Hello Polywrap!".to_string(),
}
).unwrap()),
None,
None
);

if result.is_err() {
// Handle error
};

println!(
"Cat Result: {}",
String::from_utf8(result.unwrap().to_vec()).unwrap()
);
match result {
Ok(v) => println!("{}", v),
Err(e) => panic!("{}", e),
}
}
```

Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.1.9
0.1.9
2 changes: 2 additions & 0 deletions packages/builder/src/polywrap_base_resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ use polywrap_resolvers::{
uri_resolver_aggregator::UriResolverAggregator,
};

/// Constructs a URI Resolver based on a set of default rules used by the `Client`.
pub struct PolywrapBaseResolver {}

/// Options for the construction of URI Resolver based on a set of default rules used by the `Client`.
#[derive(Default)]
pub struct PolywrapBaseResolverOptions {
pub static_resolver: Option<StaticResolver>,
Expand Down
1 change: 1 addition & 0 deletions packages/builder/src/polywrap_client_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use polywrap_resolvers::static_resolver::{StaticResolver, StaticResolverLike};

use crate::{PolywrapBaseResolver, PolywrapBaseResolverOptions, ClientConfigBuilder};

/// Struct representing the configuration of a `Client`.
#[derive(Default, Clone)]
pub struct ClientConfig {
pub interfaces: Option<InterfaceImplementations>,
Expand Down
120 changes: 118 additions & 2 deletions packages/builder/src/polywrap_client_config_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,35 +7,151 @@ use polywrap_core::{

use crate::ClientConfig;

/// Defines a type that uses the builder pattern to build a `ClientConfig`.
pub trait ClientConfigBuilder: CoreClientConfigBuilder {
/// Merges a `ClientConfig` with the current instance's state.
///
/// # Arguments
///
/// * `config` - A `ClientConfig` instance to be merged with the current state.
fn add(&mut self, config: ClientConfig) -> &mut Self;

/// Adds an environment configuration entry.
///
/// # Arguments
///
/// * `uri` - The `Uri` associated with the environment configuration.
/// * `env` - A msgpack buffer representing the environment configuration.
fn add_env(&mut self, uri: Uri, env: Vec<u8>) -> &mut Self;

/// Adds several environment configuration entries.
///
/// # Arguments
///
/// * `env` - A HashMap where the key is the `Uri` and the value is a msgpack buffer representing the environment configuration.
fn add_envs(&mut self, env: HashMap<Uri, Vec<u8>>) -> &mut Self;

/// Removes an environment entry by `Uri`.
///
/// # Arguments
///
/// * `uri` - The `Uri` of the environment entry to be removed.
fn remove_env(&mut self, uri: &Uri) -> &mut Self;

/// Adds an interface implementation entry.
///
/// # Arguments
///
/// * `interface_uri` - The `Uri` of the interface.
/// * `implementation_uri` - The `Uri` of the implementation.
fn add_interface_implementation(
&mut self,
interface_uri: Uri,
implementation_uri: Uri,
) -> &mut Self;

/// Adds several interface implementations.
///
/// # Arguments
///
/// * `interface_uri` - The `Uri` of the interface.
/// * `implementation_uris` - A list of implementation `Uri`s.
fn add_interface_implementations(
&mut self,
interface_uri: Uri,
implementation_uris: Vec<Uri>,
) -> &mut Self;

/// Removes an implementation from an interface.
///
/// # Arguments
///
/// * `interface_uri` - The `Uri` of the interface.
/// * `implementation_uri` - The `Uri` of the implementation to be removed.
fn remove_interface_implementation(
&mut self,
interface_uri: &Uri,
implementation_uri: &Uri,
) -> &mut Self;

/// Embeds a wrapper to the config.
/// When invoking this wrapper's `Uri`, it won't be fetched at runtime; but taken from the config instead.
///
/// # Arguments
///
/// * `uri` - The `Uri` of the `Wrapper`.
/// * `wrapper` - A `Wrapper` instance.
fn add_wrapper(&mut self, uri: Uri, wrapper: Arc<dyn Wrapper>) -> &mut Self;

/// Embeds several wrappers to the config.
///
/// # Arguments
///
/// * `wrappers` - A list of tuples where each tuple contains a `Uri` and a `Wrapper` instance.
fn add_wrappers(&mut self, wrappers: Vec<(Uri, Arc<dyn Wrapper>)>) -> &mut Self;

/// Removes an embedded wrapper.
///
/// # Arguments
///
/// * `uri` - The `Uri` of the wrapper to be removed.
fn remove_wrapper(&mut self, uri: &Uri) -> &mut Self;
fn add_packages(&mut self, packages: Vec<(Uri, Arc<dyn WrapPackage>)>) -> &mut Self;

/// Embeds a `WrapPackage` to the config.
/// When invoking this package's `Uri`, the embedded local instance will create a `Wrapper` and invoke it.
///
/// # Arguments
///
/// * `uri` - The `Uri` of the `WrapPackage`.
/// * `package` - A `WrapPackage` instance.
fn add_package(&mut self, uri: Uri, package: Arc<dyn WrapPackage>) -> &mut Self;

/// Embeds several `WrapPackage`s to the config.
///
/// # Arguments
///
/// * `packages` - A list of tuples where each tuple contains a `Uri` and a `WrapPackage` instance.
fn add_packages(&mut self, packages: Vec<(Uri, Arc<dyn WrapPackage>)>) -> &mut Self;

/// Removes an embedded `WrapPackage`.
///
/// # Arguments
///
/// * `uri` - The `Uri` of the `WrapPackage` to be removed.
fn remove_package(&mut self, uri: &Uri) -> &mut Self;

/// Specifies a `Uri` that should be redirected to another `Uri`.
///
/// # Arguments
///
/// * `from` - The original `Uri`.
/// * `to` - The `Uri` to which the original `Uri` should be redirected.
fn add_redirect(&mut self, from: Uri, to: Uri) -> &mut Self;

/// Specifies multiple `Uri`s that should be redirected to other `Uri`s.
///
/// # Arguments
///
/// * `redirects` - A HashMap where the key is the original `Uri` and the value is the `Uri` to which it should be redirected.
fn add_redirects(&mut self, redirects: HashMap<Uri, Uri>) -> &mut Self;

/// Removes a previously added redirect from one `Uri` to another.
///
/// # Arguments
///
/// * `from` - The original `Uri` of the redirect to be removed.
fn remove_redirect(&mut self, from: &Uri) -> &mut Self;
/// Adds a custom `Uri` resolver to the configuration.
///
/// # Arguments
///
/// * `resolver` - A UriResolver instance.
fn add_resolver(&mut self, resolver: Arc<dyn UriResolver>) -> &mut Self;
fn add_resolvers(&mut self, resolver: Vec<Arc<dyn UriResolver>>) -> &mut Self;

/// Adds multiple custom `Uri` resolvers to the configuration.
///
/// # Arguments
///
/// * `resolvers` - A list of UriResolver instances.
fn add_resolvers(&mut self, resolvers: Vec<Arc<dyn UriResolver>>) -> &mut Self;
}
27 changes: 27 additions & 0 deletions packages/client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use std::{

use crate::subinvoker::Subinvoker;

/// `Client` is a Polywrap client used for interacting, loading, resolving and invoking wraps.
#[derive(Clone, Debug)]
pub struct Client {
pub resolver: Arc<dyn UriResolver>,
Expand All @@ -33,6 +34,12 @@ pub struct Client {
}

impl Client {
/// Creates a new `Client` from a given `CoreClientConfig`.
/// Instead of manually building the `CoreClientConfig` instance, the `ClientConfigBuilder` can be used.
///
/// # Arguments
///
/// * `config`: A `CoreClientConfig` object containing the configuration for the client.
pub fn new(config: CoreClientConfig) -> Self {
let resolver = config.resolver;
let envs = config.envs;
Expand All @@ -44,6 +51,16 @@ impl Client {
}
}

/// Invokes a method on a given URI, decodes the result into `T` and returns it.
/// If the result of the invocation cannot be cast into `T`, an error will be thrown
///
/// # Arguments
///
/// * `uri`: `Uri` of the wrap to invoke.
/// * `method`: A string slice representing the method to be invoked.
/// * `args`: Optional msgpack buffer representing the arguments.
/// * `env`: Optional msgpack buffer representing the environment.
/// * `resolution_context`: Optional resolution context of invocation.
pub fn invoke<T: DeserializeOwned>(
&self,
uri: &Uri,
Expand All @@ -57,6 +74,16 @@ impl Client {
from_slice(result.as_slice()).map_err(Error::MsgpackError)
}

/// Invokes a method on a given `Wrapper` implementation instance, decodes the result into `TResult` and returns it
///
/// # Arguments
///
/// * `wrapper`: `Wrapper` implementation instance.
/// * `uri`: `Uri` of the wrap to invoke.
/// * `method`: A string slice representing the method to be invoked.
/// * `args`: Optional msgpack buffer representing the arguments.
/// * `env`: Optional msgpack buffer representing the environment.
/// * `resolution_context`: Optional resolution context of invocation.
pub fn invoke_wrapper<TResult: DeserializeOwned, TWrapper: Wrapper>(
&self,
wrapper: &TWrapper,
Expand Down
1 change: 1 addition & 0 deletions packages/client/src/subinvoker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use polywrap_core::{
resolution::uri_resolution_context::UriResolutionContext, uri::Uri,
};

/// `Subinvoker` implements wrap invocation capabilities, and is used by the `Client` to invoke wraps.
pub struct Subinvoker {
resolution_context: Arc<Mutex<UriResolutionContext>>,
invoker: Arc<dyn Invoker>,
Expand Down
1 change: 1 addition & 0 deletions packages/core/macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, LitStr};

/// Construct a URI from compatible types.
#[proc_macro]
pub fn uri(input: TokenStream) -> TokenStream {
// Parse the input tokens into a syntax tree
Expand Down
13 changes: 13 additions & 0 deletions packages/core/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@ use crate::uri_resolver_handler::UriResolverHandler;
use crate::wrap_invoker::WrapInvoker;
use crate::wrap_loader::WrapLoader;

/// A utility struct to store a URI redirect.
#[derive(Clone, Debug, PartialEq)]
pub struct UriRedirect {
/// Source URI
pub from: Uri,
/// Destination URI
pub to: Uri,
}

Expand All @@ -21,27 +24,37 @@ impl UriRedirect {
}
}

/// Allows conversion from a tuple of URIs to a UriRedirect.
impl From<(Uri, Uri)> for UriRedirect {
fn from((from, to): (Uri, Uri)) -> Self {
Self { from, to }
}
}

/// Allows conversion from a tuple of URI references to a UriRedirect.
impl From<(&Uri, &Uri)> for UriRedirect {
fn from((from, to): (&Uri, &Uri)) -> Self {
UriRedirect::new(from.to_owned(), to.to_owned())
}
}

/// Configuration struct for implementors of `Client`.
/// Can be built manually or through the `ClientConfigBuilder`
#[derive(Debug)]
pub struct CoreClientConfig {
pub resolver: Arc<dyn UriResolver>,
/// Environment variables configuration.
/// Should be a `HashMap` of `Uri` keys and msgpack buffer values
pub envs: Option<HashMap<Uri, Vec<u8>>>,
/// Interface implementations
pub interfaces: Option<InterfaceImplementations>,
}

/// Defines a type that can build a `CoreClientConfig`.
pub trait CoreClientConfigBuilder {
/// Builds a `CoreClientConfig` instance.
fn build(self) -> CoreClientConfig;
}

/// Defines a type that represents a Polywrap Client.
pub trait CoreClient: Invoker + WrapLoader + WrapInvoker + UriResolverHandler {}
Loading

0 comments on commit 7d381f4

Please sign in to comment.