From b2f50881c777b15b2b1a5f3394499123de8b360b Mon Sep 17 00:00:00 2001 From: Angel M De Miguel Date: Wed, 12 Jul 2023 18:16:33 +0200 Subject: [PATCH 1/5] docs: add the HTTP request documentation. Improve features' docs --- docs/docs/features/_category_.json | 5 +- docs/docs/features/all.md | 38 +++++ docs/docs/features/dynamic-routes.md | 14 +- docs/docs/features/environment-variables.md | 12 +- docs/docs/features/http-requests.md | 41 +++++ docs/docs/features/key-value.md | 12 +- docs/docs/features/mount-folders.md | 10 ++ docs/docs/features/static-assets.md | 4 +- docs/docs/languages/go.md | 131 ++++++++++++++++ docs/docs/languages/javascript.md | 81 ++++++++++ docs/docs/languages/python.md | 8 + docs/docs/languages/ruby.md | 8 + docs/docs/languages/rust.md | 158 ++++++++++++++++++++ 13 files changed, 514 insertions(+), 8 deletions(-) create mode 100644 docs/docs/features/all.md create mode 100644 docs/docs/features/http-requests.md diff --git a/docs/docs/features/_category_.json b/docs/docs/features/_category_.json index bd5d8a56..f2c10da4 100644 --- a/docs/docs/features/_category_.json +++ b/docs/docs/features/_category_.json @@ -2,6 +2,7 @@ "label": "Features", "position": 2, "link": { - "type": "generated-index" + "type": "doc", + "id": "all" } -} \ No newline at end of file +} diff --git a/docs/docs/features/all.md b/docs/docs/features/all.md new file mode 100644 index 00000000..46c2c6a2 --- /dev/null +++ b/docs/docs/features/all.md @@ -0,0 +1,38 @@ +# Features + +Wasm Workers Server provides different features to develop serverless applications. Some of these features are related to the server like the static asset management, while others relate to the workers like sending HTTP requests. + +For that reason, we usually distinguish between server and worker features: + +* **Server features**: customizes or expands Wasm Worker Server capabilities. For example, you can expose static assets by saving these files in a `public` folder. + +* **Worker features**: expose new features to the individual workers so they can perform more complex tasks. For example, workers can access to a K/V store or use environment variables. + +## Available features + +### Server + +* [Static assets' management](./static-assets.md) +* [Multiple language runtimes](./multiple-language-runtimes.md) + +### Workers + +* [Key / Value store](./key-value.md) +* [HTTP Requests (fetch)](./http-requests.md) +* [Dynamic routes](./dynamic-routes.md) +* [Environment variables](./environment-variables.md) +* [Mount folders](./environment-variables.md) + +## Language compatibility + +You can develop workers in different languages. However, not all of them support all features. **The goal is to support all of them**, although there are some constraints that makes some features more complex to implement in certain languages. + +The following table shows the language compatibility for the different worker's functions: + +| Language | K/V Store | Environment Variables | Dynamic Routes | Folders | HTTP Requests | +| --- | --- | --- | --- | --- | --- | +| JavaScript | ✅ | ✅ | ✅ | ❌ | ✅ | +| Rust | ✅ | ✅ | ✅ | ✅ | ✅ | +| Go | ✅ | ✅ | ✅ | ✅ | ✅ | +| Ruby | ✅ | ✅ | ✅ | ✅ | ❌ | +| Python | ✅ | ✅ | ✅ | ✅ | ❌ | diff --git a/docs/docs/features/dynamic-routes.md b/docs/docs/features/dynamic-routes.md index c4dea997..db457578 100644 --- a/docs/docs/features/dynamic-routes.md +++ b/docs/docs/features/dynamic-routes.md @@ -1,5 +1,5 @@ --- -sidebar_position: 3 +sidebar_position: 4 --- # Dynamic routes @@ -48,4 +48,14 @@ $ tree . └── show.js ``` -In this case, the `./[resource]/[id]/show.js` worker replies to URLs like `/articles/2/show`. \ No newline at end of file +In this case, the `./[resource]/[id]/show.js` worker replies to URLs like `/articles/2/show`. + +## Language compatibility + +| Language | Dynamic routes | +| --- | --- | +| JavaScript | ✅ | +| Rust | ✅ | +| Go | ✅ | +| Ruby | ✅ | +| Python | ✅ | diff --git a/docs/docs/features/environment-variables.md b/docs/docs/features/environment-variables.md index 4df03032..aeefefc5 100644 --- a/docs/docs/features/environment-variables.md +++ b/docs/docs/features/environment-variables.md @@ -39,4 +39,14 @@ JSON_MESSAGE = "Hello 👋! This message comes from an environment variable" TOKEN = "$TOKEN" ``` -This feature allows you to configure environment variables dynamically. \ No newline at end of file +This feature allows you to configure environment variables dynamically. + +## Language compatibility + +| Language | Environment variables | +| --- | --- | +| JavaScript | ✅ | +| Rust | ✅ | +| Go | ✅ | +| Ruby | ✅ | +| Python | ✅ | diff --git a/docs/docs/features/http-requests.md b/docs/docs/features/http-requests.md new file mode 100644 index 00000000..8484c022 --- /dev/null +++ b/docs/docs/features/http-requests.md @@ -0,0 +1,41 @@ +--- +sidebar_position: 3 +--- + +# HTTP Requests (fetch) + +Many times, workers require to access data from an external resource like a website or an API. This feature allows workers to perform HTTP requests to external resources from a worker. It follows the capability-based model, so workers cannot perform any HTTP request until you configure the allowed hosts and HTTP methods. + +In this configuration, you are allowing a worker to perform `GET` and `POST` HTTP requests to the [{JSON} Placeholder API](https://jsonplaceholder.typicode.com/): + +```toml +name = "fetch" +version = "1" + +[features] +[features.http_requests] +allowed_methods = ["GET", "POST"] +allowed_hosts = ["jsonplaceholder.typicode.com"] +``` + +Now, your worker can perform HTTP requests following those rules. + +## Send HTTP requests in different languages + +Depending on the language, the different kits exposes this feature in a different way. The goal is to use a common API to perform HTTP requests in that language. For example, to perform HTTP requests in JavaScript you can use the [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API. + +Check these guides to perform HTTP requests in the different supported languages: + +* [HTTP requests on JavaScript workers](../languages/javascript.md#send-an-http-request-fetch) +* [HTTP requests on Rust workers](../languages/rust.md#send-an-http-request) +* [HTTP requests on Go workers](../languages/go.md#send-an-http-request) + +## Language compatibility + +| Language | HTTP Requests | +| --- | --- | +| JavaScript | ✅ | +| Rust | ✅ | +| Go | ✅ | +| Ruby | ❌ | +| Python | ❌ | diff --git a/docs/docs/features/key-value.md b/docs/docs/features/key-value.md index f077183d..de2bf483 100644 --- a/docs/docs/features/key-value.md +++ b/docs/docs/features/key-value.md @@ -24,4 +24,14 @@ The worker may access all the data and perform changes over it. Then, a new K/V ## Limitations -A known limitation of the snapshot approach is the data override when concurrent requests are writing to the same namespace. In the future, we will implement a consolidation mechanism or a different store type for applications that require to write intensively. \ No newline at end of file +A known limitation of the snapshot approach is the data override when concurrent requests are writing to the same namespace. In the future, we will implement a consolidation mechanism or a different store type for applications that require to write intensively. + +## Language compatibility + +| Language | K/V store | +| --- | --- | +| JavaScript | ✅ | +| Rust | ✅ | +| Go | ✅ | +| Ruby | ✅ | +| Python | ✅ | diff --git a/docs/docs/features/mount-folders.md b/docs/docs/features/mount-folders.md index d0fde8fb..ba34c466 100644 --- a/docs/docs/features/mount-folders.md +++ b/docs/docs/features/mount-folders.md @@ -31,3 +31,13 @@ to = "/mnt/assets" In the previous example, all folders starts with an underscore character (`_`). This folder name convention tells `wws` to ignore any file inside it when detecting available workers. Note that those folders may include files that `wws` recognizes as workers (like `.js` or `.py`). By prefixing those folders with an `_`, you ensure `wws` won't process those files as workers. + +## Language compatibility + +| Language | Mount folders | +| --- | --- | +| JavaScript | ❌ | +| Rust | ✅ | +| Go | ✅ | +| Ruby | ✅ | +| Python | ✅ | diff --git a/docs/docs/features/static-assets.md b/docs/docs/features/static-assets.md index 2360f33f..5efd98f5 100644 --- a/docs/docs/features/static-assets.md +++ b/docs/docs/features/static-assets.md @@ -1,5 +1,5 @@ --- -sidebar_position: 4 +sidebar_position: 5 --- # Static assets @@ -44,4 +44,4 @@ The `about.html` file will be served as `/about`. ## Index file in public -An `index.html` can be added to the `public` folder and it will be mounted in `/`. Note that static files have a lower priority, so if there's an `/index.js` and `/public/index.html` files, the `/` route will be served by the former. \ No newline at end of file +An `index.html` can be added to the `public` folder and it will be mounted in `/`. Note that static files have a lower priority, so if there's an `/index.js` and `/public/index.html` files, the `/` route will be served by the former. diff --git a/docs/docs/languages/go.md b/docs/docs/languages/go.md index 46820289..505f677a 100644 --- a/docs/docs/languages/go.md +++ b/docs/docs/languages/go.md @@ -234,6 +234,127 @@ To add a KV store to your worker, follow these steps: 1. Finally, open in your browser. +## Send an HTTP request + +Wasm Workers allows you to send HTTP requests from your workers. Read more information about this feature in the [HTTP Requests](../features/http-requests.md) section. + +To perform a HTTP requests from your worker, follow these steps: + +1. Create a new Go project: + + ```bash + go mod init fetch + ``` + +1. Add the Wasm Workers Server Go dependency + + ``` + go get -u github.com/vmware-labs/wasm-workers-server/kits/go/worker@v1.4.0 + ``` + +1. Create a `fetch.go` file with the following contents: + + ```go title="fetch.go" + package main + + import ( + "io" + "net/http" + + "github.com/vmware-labs/wasm-workers-server/kits/go/worker" + + "github.com/tidwall/gjson" + ) + + func main() { + worker.ServeFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("x-generated-by", "wasm-workers-server") + w.Write([]byte("Hello wasm!")) + }) + } + ``` + +1. Then, let's create the `http.Request` instance and pass it to the `worker.SendHttpRequest` method. In this example, we will call the [{JSON} Placeholder API](https://jsonplaceholder.typicode.com/) to retrieve a `Post`. You will read the content of the response using the `gjson` API: + + ```go title="fetch.go" + package main + + import ( + "io" + "net/http" + + "github.com/vmware-labs/wasm-workers-server/kits/go/worker" + + "github.com/tidwall/gjson" + ) + + func main() { + worker.ServeFunc(func(w http.ResponseWriter, r *http.Request) { + url := "https://jsonplaceholder.typicode.com/posts" + + // Create the request + req, err := http.NewRequest(http.MethodGet, url, nil) + if err != nil { + panic(err) + } + + // Send the request + res, err := worker.SendHttpRequest(req) + if err != nil { + panic(err) + } + + // Read the response and parse the title + resBody, err := io.ReadAll(res.Body) + if err != nil { + panic(err) + } + res.Body.Close() + + title := gjson.Get(resBody, "title") + + w.Header().Set("x-generated-by", "wasm-workers-server") + w.Write([]byte(title.String())) + }) + } + ``` + +1. Compile the project to Wasm ([WASI](https://wasi.dev/)): + + ```bash + tinygo build -o fetch.wasm -target wasi fetch.go + ``` + +1. Create a `fetch.toml` file with the following content. It enables the worker to perform the HTTP request to that host. By default, HTTP requests are forbidden. + + Note the name of the TOML file must match the name of the worker. In this case we have `fetch.wasm` and `fetch.toml` in the same folder: + + ```toml title="fetch.toml" + name = "fetch" + version = "1" + + [features] + [features.http_requests] + allowed_methods = ["GET"] + allowed_hosts = ["jsonplaceholder.typicode.com"] + ``` + +1. Run your worker with `wws`. If you didn't download the `wws` server yet, check our [Getting Started](../get-started/quickstart.md) guide. + + ```bash + wws . + + ⚙️ Preparing the project from: . + ⚙️ Loading routes from: . + ⏳ Loading workers from 1 routes... + ✅ Workers loaded in 135.717667ms. + - http://127.0.0.1:8080/fetch + => ./fetch.wasm + 🚀 Start serving requests at http://127.0.0.1:8080 + ``` + +1. Finally, open in your browser. + ## Dynamic routes You can define [dynamic routes by adding route parameters to your worker files](../features/dynamic-routes.md) (like `[id].wasm`). To read them in Go, follow these steps: @@ -328,4 +449,14 @@ If you prefer, you can configure the environment variable value dynamically by f * [Basic](https://github.com/vmware-labs/wasm-workers-server/tree/main/examples/go-basic) * [Counter](https://github.com/vmware-labs/wasm-workers-server/tree/main/examples/go-kv) +## Contributors + The Go kit was originally authored by Mohammed Nafees ([@mnafees](https://github.com/mnafees)) + +## Feature compatibility + +[Workers' features](../features/all.md) that are available in Go: + +| [K/V Store](../features/key-value.md) | [Environment Variables](../features/environment-variables.md) | [Dynamic Routes](../features/dynamic-routes.md) | [Folders](../features/mount-folders.md) | [HTTP Requests](../features/http-requests.md) | +| --- | --- | --- | --- | --- | +| ✅ | ✅ | ✅ | ✅ | ✅ | diff --git a/docs/docs/languages/javascript.md b/docs/docs/languages/javascript.md index 2a79f470..da1d9b63 100644 --- a/docs/docs/languages/javascript.md +++ b/docs/docs/languages/javascript.md @@ -137,6 +137,79 @@ To add a KV store to your worker, follow these steps: 1. Finally, open in your browser. +## Send an HTTP request (fetch) + +Wasm Workers allows you to send HTTP requests from your workers. Read more information about this feature in the [HTTP Requests](../features/http-requests.md) section. + +To perform a HTTP requests from your worker, follow these steps: + +1. First, create an `index.js` file. It will call the [{JSON} Placeholder API](https://jsonplaceholder.typicode.com/) using the [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) method: + + ```javascript title="./index.js" + const reply = async (_req) => { + // Body response + let body; + + try { + let res = await fetch('https://jsonplaceholder.typicode.com/posts/1'); + let json = await res.json(); + + // Build a new response. + // Add some basic sanitization + body = ` + + JSON Placeholder request + + + + +
+

Hello from Wasm Workers Server 👋

+

The post title is: ${json.title}

+
+ `; + } catch (e) { + body = `There was an error with the request: ${e}`; + } + + return new Response(body); + } + + addEventListener("fetch", event => { + event.respondWith(reply(event.request)); + }); + ``` + +1. Create an `index.toml` file with the following content. It enables the worker to perform the HTTP request to that host. By default, HTTP requests are forbidden. + + Note the name of the TOML file must match the name of the worker. In this case we have `index.js` and `index.toml` in the same folder: + + ```toml title="./index.toml" + name = "fetch" + version = "1" + + [features] + [features.http_requests] + allowed_methods = ["GET"] + allowed_hosts = ["jsonplaceholder.typicode.com"] + ``` + +1. Save the file and run your worker with `wws`. If you didn't download the `wws` server yet, check our [Getting Started](../get-started/quickstart.md) guide. + + ```bash + wws + + ⚙️ Preparing the project from: . + ⚙️ Loading routes from: . + ⏳ Loading workers from 1 routes... + ✅ Workers loaded in 135.717667ms. + - http://127.0.0.1:8080/ + => ./index.js + 🚀 Start serving requests at http://127.0.0.1:8080 + ``` + +1. Finally, open in your browser. + ## Dynamic routes You can define [dynamic routes by adding route parameters to your worker files](../features/dynamic-routes.md) (like `[id].js`). To read them in JavaScript, access to the `req.params` object: @@ -203,3 +276,11 @@ If you prefer, you can configure the environment variable value dynamically by f * [JSON](https://github.com/vmware-labs/wasm-workers-server/tree/main/examples/js-json/) * [Redirect](https://github.com/vmware-labs/wasm-workers-server/tree/main/examples/js-redirect/) * [Tic Tac Toe](https://github.com/vmware-labs/wasm-workers-server/tree/main/examples/js-tictactoe/) + +## Feature compatibility + +[Workers' features](../features/all.md) that are available in JavaScript: + +| [K/V Store](../features/key-value.md) | [Environment Variables](../features/environment-variables.md) | [Dynamic Routes](../features/dynamic-routes.md) | [Folders](../features/mount-folders.md) | [HTTP Requests](../features/http-requests.md) | +| --- | --- | --- | --- | --- | +| ✅ | ✅ | ✅ | ❌ | ✅ | diff --git a/docs/docs/languages/python.md b/docs/docs/languages/python.md index 28c5dd3a..89e5b582 100644 --- a/docs/docs/languages/python.md +++ b/docs/docs/languages/python.md @@ -207,3 +207,11 @@ If you prefer, you can configure the environment variable value dynamically by f * [Basic](https://github.com/vmware-labs/wasm-workers-server/tree/main/examples/python-basic/) * [Key / Value](https://github.com/vmware-labs/wasm-workers-server/tree/main/examples/python-kv/) * [Environment variables](https://github.com/vmware-labs/wasm-workers-server/tree/main/examples/python-envs/) + +## Feature compatibility + +[Workers' features](../features/all.md) that are available in Python: + +| [K/V Store](../features/key-value.md) | [Environment Variables](../features/environment-variables.md) | [Dynamic Routes](../features/dynamic-routes.md) | [Folders](../features/mount-folders.md) | [HTTP Requests](../features/http-requests.md) | +| --- | --- | --- | --- | --- | +| ✅ | ✅ | ✅ | ✅ | ❌ | diff --git a/docs/docs/languages/ruby.md b/docs/docs/languages/ruby.md index 481f2a1b..65070123 100644 --- a/docs/docs/languages/ruby.md +++ b/docs/docs/languages/ruby.md @@ -187,3 +187,11 @@ If you prefer, you can configure the environment variable value dynamically by f * [Basic](https://github.com/vmware-labs/wasm-workers-server/tree/main/examples/ruby-basic/) * [Key / Value](https://github.com/vmware-labs/wasm-workers-server/tree/main/examples/ruby-kv/) * [Environment variables](https://github.com/vmware-labs/wasm-workers-server/tree/main/examples/ruby-envs/) + +## Feature compatibility + +[Workers' features](../features/all.md) that are available in Ruby: + +| [K/V Store](../features/key-value.md) | [Environment Variables](../features/environment-variables.md) | [Dynamic Routes](../features/dynamic-routes.md) | [Folders](../features/mount-folders.md) | [HTTP Requests](../features/http-requests.md) | +| --- | --- | --- | --- | --- | +| ✅ | ✅ | ✅ | ✅ | ❌ | diff --git a/docs/docs/languages/rust.md b/docs/docs/languages/rust.md index ec311f59..d5650c5d 100644 --- a/docs/docs/languages/rust.md +++ b/docs/docs/languages/rust.md @@ -231,6 +231,156 @@ To add a KV store to your worker, follow these steps: 1. Finally, open in your browser. +## Send an HTTP request + +Wasm Workers allows you to send HTTP requests from your workers. Read more information about this feature in the [HTTP Requests](../features/http-requests.md) section. + +To perform a HTTP requests from your worker, follow these steps: + +1. Create a new Rust project: + + ```bash + cargo new --name fetch fetch + ``` + +1. Add the dependencies to the `Cargo.toml` file: + + ```toml title="Cargo.toml" + [package] + name = "fetch" + version = "0.1.0" + edition = "2021" + + [dependencies] + anyhow = "1.0.63" + wasm-workers-rs = { git = "https://github.com/vmware-labs/wasm-workers-server/", tag = "v1.4.0" } + serde = { version = "1.0", features = ["derive"] } + serde_json = "1.0.85" + ``` + +1. Add the `reply` function to the `src/main.rs` file. You will need to import the required resources from the `wasm-workers-rs` crate, use the `worker` macro and the `bindings` module. In this case, you need to import also the `serde` library to deserialize the API response from the external API: + + ```rust title="src/main.rs" + use anyhow::Result; + use serde::{Deserialize, Serialize}; + use wasm_workers_rs::{ + worker, + bindings, + http::{self, Request, Response}, + Content, + }; + + #[worker] + fn reply(_req: Request) -> Result> { + Ok(http::Response::builder() + .status(200) + .header("x-generated-by", "wasm-workers-server") + .body(String::from("Hello wasm!").into())?) + } + ``` + +1. Then, let's create the `http::Request` instance and pass it to the `bindings::send_http_request` method. In this example, we will call the [{JSON} Placeholder API](https://jsonplaceholder.typicode.com/) to retrieve a `Post`. You need to create that `struct` to deserialize the request response with `serde`: + + ```rust title="src/main.rs" + use anyhow::Result; + use serde::{Deserialize, Serialize}; + use wasm_workers_rs::{ + worker, + http::{self, Request, Response}, + Cache, Content, + }; + + #[derive(Serialize, Deserialize)] + #[serde(rename_all = "camelCase")] + struct Post { + id: i32, + title: String, + body: String, + user_id: i32, + } + + #[worker(cache)] + fn reply(_req: Request, cache: &mut Cache) -> Result> { + let external_request = Request::builder() + .uri("https://jsonplaceholder.typicode.com/posts/1") + .body(String::new()) + .unwrap(); + + // Get the request + let res = bindings::send_http_request(external_request).unwrap(); + + // Parse the response + let data = res.body(); + + let post: Post = serde_json::from_slice(&data).unwrap(); + + // Applied changes here to use the Response method. This requires changes + // on signature and how it returns the data. + let response = format!( + " + + Wasm Workers Server + + + + +
+

{}

+

{}

+
+ ", + &post.title, &post.body + ); + + Ok(http::Response::builder() + .status(200) + .header("x-generated-by", "wasm-workers-server") + .body(response.into())?) + } + ``` + +1. Compile the project to Wasm ([WASI](https://wasi.dev/)): + + ```bash + # Install the component and build + rustup target add wasm32-wasi && \ + cargo build --release --target wasm32-wasi + ``` + +1. After you compiled the project, move the worker to the current folder: + + ```bash + mv ./target/wasm32-wasi/release/fetch.wasm ./ + ``` + +1. Create a `fetch.toml` file with the following content. It enables the worker to perform the HTTP request to that host. By default, HTTP requests are forbidden. + + Note the name of the TOML file must match the name of the worker. In this case we have `fetch.wasm` and `fetch.toml` in the same folder: + + ```toml title="fetch.toml" + name = "fetch" + version = "1" + + [features] + [features.http_requests] + allowed_methods = ["GET"] + allowed_hosts = ["jsonplaceholder.typicode.com"] + ``` + +1. Run your worker with `wws`. If you didn't download the `wws` server yet, check our [Getting Started](../get-started/quickstart.md) guide. + + ```bash + wws . --ignore "target/**" + + ⚙️ Loading routes from: . + 🗺 Detected routes: + - http://127.0.0.1:8080/fetch + => fetch.wasm (name: default) + 🚀 Start serving requests at http://127.0.0.1:8080 + ``` + +1. Finally, open in your browser. + ## Dynamic routes You can define [dynamic routes by adding route parameters to your worker files](../features/dynamic-routes.md) (like `[id].wasm`). To read them in Rust, follow these steps: @@ -318,3 +468,11 @@ If you prefer, you can configure the environment variable value dynamically by f * [Basic](https://github.com/vmware-labs/wasm-workers-server/tree/main/examples/rust-basic) * [Counter](https://github.com/vmware-labs/wasm-workers-server/tree/main/examples/rust-kv) + +## Feature compatibility + +[Workers' features](../features/all.md) that are available in Rust: + +| [K/V Store](../features/key-value.md) | [Environment Variables](../features/environment-variables.md) | [Dynamic Routes](../features/dynamic-routes.md) | [Folders](../features/mount-folders.md) | [HTTP Requests](../features/http-requests.md) | +| --- | --- | --- | --- | --- | +| ✅ | ✅ | ✅ | ✅ | ✅ | From 3b4ceec3de4e0e9697fe845dc82d1136e843b4c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81ngel=20M?= Date: Thu, 13 Jul 2023 08:53:14 +0200 Subject: [PATCH 2/5] docs: apply feedback on wording and code block types MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Rafael Fernández López --- docs/docs/features/all.md | 10 +++++----- docs/docs/features/http-requests.md | 4 ++-- docs/docs/languages/go.md | 10 +++++----- docs/docs/languages/javascript.md | 6 +++--- docs/docs/languages/rust.md | 14 +++++++------- 5 files changed, 22 insertions(+), 22 deletions(-) diff --git a/docs/docs/features/all.md b/docs/docs/features/all.md index 46c2c6a2..7b9b120a 100644 --- a/docs/docs/features/all.md +++ b/docs/docs/features/all.md @@ -1,6 +1,6 @@ # Features -Wasm Workers Server provides different features to develop serverless applications. Some of these features are related to the server like the static asset management, while others relate to the workers like sending HTTP requests. +Wasm Workers Server provides different features to develop serverless applications. Some of these features are related to the server like the static asset management, while others relate to workers like sending HTTP requests. For that reason, we usually distinguish between server and worker features: @@ -12,7 +12,7 @@ For that reason, we usually distinguish between server and worker features: ### Server -* [Static assets' management](./static-assets.md) +* [Static assets management](./static-assets.md) * [Multiple language runtimes](./multiple-language-runtimes.md) ### Workers @@ -21,13 +21,13 @@ For that reason, we usually distinguish between server and worker features: * [HTTP Requests (fetch)](./http-requests.md) * [Dynamic routes](./dynamic-routes.md) * [Environment variables](./environment-variables.md) -* [Mount folders](./environment-variables.md) +* [Mount folders](./mount-folders.md) ## Language compatibility -You can develop workers in different languages. However, not all of them support all features. **The goal is to support all of them**, although there are some constraints that makes some features more complex to implement in certain languages. +You can develop workers in different languages. However, not all of them support all features. **The goal is to support all of them**, although there are some constraints that make some features more complex to implement in certain languages. -The following table shows the language compatibility for the different worker's functions: +The following table shows the language compatibility for the different worker functions: | Language | K/V Store | Environment Variables | Dynamic Routes | Folders | HTTP Requests | | --- | --- | --- | --- | --- | --- | diff --git a/docs/docs/features/http-requests.md b/docs/docs/features/http-requests.md index 8484c022..4c4b8895 100644 --- a/docs/docs/features/http-requests.md +++ b/docs/docs/features/http-requests.md @@ -4,7 +4,7 @@ sidebar_position: 3 # HTTP Requests (fetch) -Many times, workers require to access data from an external resource like a website or an API. This feature allows workers to perform HTTP requests to external resources from a worker. It follows the capability-based model, so workers cannot perform any HTTP request until you configure the allowed hosts and HTTP methods. +Often times, workers require to access data from an external resource like a website or an API. This feature allows workers to perform HTTP requests to external resources. It follows the capability-based model, so workers cannot perform any HTTP request until you configure the allowed hosts and HTTP methods. In this configuration, you are allowing a worker to perform `GET` and `POST` HTTP requests to the [{JSON} Placeholder API](https://jsonplaceholder.typicode.com/): @@ -22,7 +22,7 @@ Now, your worker can perform HTTP requests following those rules. ## Send HTTP requests in different languages -Depending on the language, the different kits exposes this feature in a different way. The goal is to use a common API to perform HTTP requests in that language. For example, to perform HTTP requests in JavaScript you can use the [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API. +Depending on the language, the different kits expose this feature in a different way. The goal is to use a common API to perform HTTP requests in that language. For example, to perform HTTP requests in JavaScript you can use the [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API. Check these guides to perform HTTP requests in the different supported languages: diff --git a/docs/docs/languages/go.md b/docs/docs/languages/go.md index 505f677a..e0507b97 100644 --- a/docs/docs/languages/go.md +++ b/docs/docs/languages/go.md @@ -238,11 +238,11 @@ To add a KV store to your worker, follow these steps: Wasm Workers allows you to send HTTP requests from your workers. Read more information about this feature in the [HTTP Requests](../features/http-requests.md) section. -To perform a HTTP requests from your worker, follow these steps: +To perform HTTP requests from your worker, follow these steps: 1. Create a new Go project: - ```bash + ```shell-session go mod init fetch ``` @@ -321,11 +321,11 @@ To perform a HTTP requests from your worker, follow these steps: 1. Compile the project to Wasm ([WASI](https://wasi.dev/)): - ```bash + ```shell-session tinygo build -o fetch.wasm -target wasi fetch.go ``` -1. Create a `fetch.toml` file with the following content. It enables the worker to perform the HTTP request to that host. By default, HTTP requests are forbidden. +1. Create a `fetch.toml` file with the following content. It enables the worker to perform HTTP requests to that host given that, by default, HTTP requests are forbidden. Note the name of the TOML file must match the name of the worker. In this case we have `fetch.wasm` and `fetch.toml` in the same folder: @@ -341,7 +341,7 @@ To perform a HTTP requests from your worker, follow these steps: 1. Run your worker with `wws`. If you didn't download the `wws` server yet, check our [Getting Started](../get-started/quickstart.md) guide. - ```bash + ```shell-session wws . ⚙️ Preparing the project from: . diff --git a/docs/docs/languages/javascript.md b/docs/docs/languages/javascript.md index da1d9b63..17669fc0 100644 --- a/docs/docs/languages/javascript.md +++ b/docs/docs/languages/javascript.md @@ -141,7 +141,7 @@ To add a KV store to your worker, follow these steps: Wasm Workers allows you to send HTTP requests from your workers. Read more information about this feature in the [HTTP Requests](../features/http-requests.md) section. -To perform a HTTP requests from your worker, follow these steps: +To perform HTTP requests from your worker, follow these steps: 1. First, create an `index.js` file. It will call the [{JSON} Placeholder API](https://jsonplaceholder.typicode.com/) using the [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) method: @@ -180,7 +180,7 @@ To perform a HTTP requests from your worker, follow these steps: }); ``` -1. Create an `index.toml` file with the following content. It enables the worker to perform the HTTP request to that host. By default, HTTP requests are forbidden. +1. Create an `index.toml` file with the following content. It enables the worker to perform HTTP requests to that host given that, by default, HTTP requests are forbidden. Note the name of the TOML file must match the name of the worker. In this case we have `index.js` and `index.toml` in the same folder: @@ -196,7 +196,7 @@ To perform a HTTP requests from your worker, follow these steps: 1. Save the file and run your worker with `wws`. If you didn't download the `wws` server yet, check our [Getting Started](../get-started/quickstart.md) guide. - ```bash + ```shell-session wws ⚙️ Preparing the project from: . diff --git a/docs/docs/languages/rust.md b/docs/docs/languages/rust.md index d5650c5d..e7831e78 100644 --- a/docs/docs/languages/rust.md +++ b/docs/docs/languages/rust.md @@ -235,15 +235,15 @@ To add a KV store to your worker, follow these steps: Wasm Workers allows you to send HTTP requests from your workers. Read more information about this feature in the [HTTP Requests](../features/http-requests.md) section. -To perform a HTTP requests from your worker, follow these steps: +To perform HTTP requests from your worker, follow these steps: 1. Create a new Rust project: - ```bash + ```shell-session cargo new --name fetch fetch ``` -1. Add the dependencies to the `Cargo.toml` file: +1. Add dependencies to the `Cargo.toml` file: ```toml title="Cargo.toml" [package] @@ -341,7 +341,7 @@ To perform a HTTP requests from your worker, follow these steps: 1. Compile the project to Wasm ([WASI](https://wasi.dev/)): - ```bash + ```shell-session # Install the component and build rustup target add wasm32-wasi && \ cargo build --release --target wasm32-wasi @@ -349,11 +349,11 @@ To perform a HTTP requests from your worker, follow these steps: 1. After you compiled the project, move the worker to the current folder: - ```bash + ```shell-session mv ./target/wasm32-wasi/release/fetch.wasm ./ ``` -1. Create a `fetch.toml` file with the following content. It enables the worker to perform the HTTP request to that host. By default, HTTP requests are forbidden. +1. Create a `fetch.toml` file with the following content. It enables the worker to perform HTTP requests to that host given that, by default, HTTP requests are forbidden. Note the name of the TOML file must match the name of the worker. In this case we have `fetch.wasm` and `fetch.toml` in the same folder: @@ -369,7 +369,7 @@ To perform a HTTP requests from your worker, follow these steps: 1. Run your worker with `wws`. If you didn't download the `wws` server yet, check our [Getting Started](../get-started/quickstart.md) guide. - ```bash + ```shell-session wws . --ignore "target/**" ⚙️ Loading routes from: . From 59a8bae126a6185afaa833848f6c40856f0ffeb7 Mon Sep 17 00:00:00 2001 From: Angel M De Miguel Date: Thu, 13 Jul 2023 08:55:52 +0200 Subject: [PATCH 3/5] docs: fix a rust code example for making HTTP requests --- docs/docs/languages/rust.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/docs/languages/rust.md b/docs/docs/languages/rust.md index e7831e78..0686aa29 100644 --- a/docs/docs/languages/rust.md +++ b/docs/docs/languages/rust.md @@ -286,8 +286,9 @@ To perform HTTP requests from your worker, follow these steps: use serde::{Deserialize, Serialize}; use wasm_workers_rs::{ worker, + bindings, http::{self, Request, Response}, - Cache, Content, + Content, }; #[derive(Serialize, Deserialize)] @@ -299,8 +300,8 @@ To perform HTTP requests from your worker, follow these steps: user_id: i32, } - #[worker(cache)] - fn reply(_req: Request, cache: &mut Cache) -> Result> { + #[worker] + fn reply(_req: Request) -> Result> { let external_request = Request::builder() .uri("https://jsonplaceholder.typicode.com/posts/1") .body(String::new()) @@ -314,8 +315,7 @@ To perform HTTP requests from your worker, follow these steps: let post: Post = serde_json::from_slice(&data).unwrap(); - // Applied changes here to use the Response method. This requires changes - // on signature and how it returns the data. + // Prepare the final response let response = format!( " From a004bd532f55c988d0ff08fb867bc363b62e78db Mon Sep 17 00:00:00 2001 From: Angel M De Miguel Date: Thu, 13 Jul 2023 10:14:43 +0200 Subject: [PATCH 4/5] docs: fix indentation and improve Go HTTP request example --- docs/docs/languages/go.md | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/docs/docs/languages/go.md b/docs/docs/languages/go.md index e0507b97..75fd5b38 100644 --- a/docs/docs/languages/go.md +++ b/docs/docs/languages/go.md @@ -246,10 +246,11 @@ To perform HTTP requests from your worker, follow these steps: go mod init fetch ``` -1. Add the Wasm Workers Server Go dependency +1. Add the project dependencies: ``` - go get -u github.com/vmware-labs/wasm-workers-server/kits/go/worker@v1.4.0 + go get -u github.com/vmware-labs/wasm-workers-server/kits/go/worker@v1.4.0 \ + github.com/tidwall/gjson ``` 1. Create a `fetch.go` file with the following contents: @@ -259,9 +260,10 @@ To perform HTTP requests from your worker, follow these steps: import ( "io" + "fmt" "net/http" - "github.com/vmware-labs/wasm-workers-server/kits/go/worker" + "github.com/vmware-labs/wasm-workers-server/kits/go/worker" "github.com/tidwall/gjson" ) @@ -281,16 +283,17 @@ To perform HTTP requests from your worker, follow these steps: import ( "io" + "fmt" "net/http" - "github.com/vmware-labs/wasm-workers-server/kits/go/worker" + "github.com/vmware-labs/wasm-workers-server/kits/go/worker" "github.com/tidwall/gjson" ) func main() { worker.ServeFunc(func(w http.ResponseWriter, r *http.Request) { - url := "https://jsonplaceholder.typicode.com/posts" + url := "https://jsonplaceholder.typicode.com/posts/1" // Create the request req, err := http.NewRequest(http.MethodGet, url, nil) @@ -301,20 +304,30 @@ To perform HTTP requests from your worker, follow these steps: // Send the request res, err := worker.SendHttpRequest(req) if err != nil { - panic(err) + msg := fmt.Sprintf("Error when calling the API: %s", err); + + // Send the reponse + w.Write([]byte(msg)) + + return } // Read the response and parse the title resBody, err := io.ReadAll(res.Body) if err != nil { - panic(err) + msg := fmt.Sprintf("Error when reading the response body: %s", err); + + // Send the reponse + w.Write([]byte(msg)) + + return } res.Body.Close() - title := gjson.Get(resBody, "title") + title := gjson.Get(string(resBody), "title") w.Header().Set("x-generated-by", "wasm-workers-server") - w.Write([]byte(title.String())) + w.Write([]byte(fmt.Sprintf("Title: %s", title.String()))) }) } ``` @@ -368,7 +381,7 @@ You can define [dynamic routes by adding route parameters to your worker files]( "fmt" "net/http" - "github.com/vmware-labs/wasm-workers-server/kits/go/worker" +i"github.com/vmware-labs/wasm-workers-server/kits/go/worker" ) func main() { From 2a8921295a9d4d6c8229ee6a2f7a4dd5dbdb2e93 Mon Sep 17 00:00:00 2001 From: Angel M De Miguel Date: Thu, 13 Jul 2023 10:21:58 +0200 Subject: [PATCH 5/5] fix: typo error in a different example --- docs/docs/languages/go.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/languages/go.md b/docs/docs/languages/go.md index 75fd5b38..e374b399 100644 --- a/docs/docs/languages/go.md +++ b/docs/docs/languages/go.md @@ -381,7 +381,7 @@ You can define [dynamic routes by adding route parameters to your worker files]( "fmt" "net/http" -i"github.com/vmware-labs/wasm-workers-server/kits/go/worker" + "github.com/vmware-labs/wasm-workers-server/kits/go/worker" ) func main() {