├── Ch06 ├── hello-wasm │ ├── .cargo-ok │ ├── client │ │ ├── .gitignore │ │ ├── index.js │ │ ├── .travis.yml │ │ ├── bootstrap.js │ │ ├── index.html │ │ ├── webpack.config.js │ │ ├── .bin │ │ │ └── create-wasm-app.js │ │ ├── package.json │ │ ├── LICENSE-MIT │ │ ├── README.md │ │ └── LICENSE-APACHE │ ├── .gitignore │ ├── tests │ │ └── web.rs │ ├── .appveyor.yml │ ├── src │ │ ├── lib.rs │ │ └── utils.rs │ ├── Cargo.toml │ ├── LICENSE_MIT │ ├── README.md │ ├── .travis.yml │ └── LICENSE_APACHE ├── wasm-image-processing │ ├── .cargo-ok │ ├── client │ │ ├── .gitignore │ │ ├── .travis.yml │ │ ├── bootstrap.js │ │ ├── webpack.config.js │ │ ├── index.html │ │ ├── .bin │ │ │ └── create-wasm-app.js │ │ ├── package.json │ │ ├── LICENSE-MIT │ │ ├── index.js │ │ ├── README.md │ │ └── LICENSE-APACHE │ ├── .gitignore │ ├── tests │ │ └── web.rs │ ├── .appveyor.yml │ ├── src │ │ ├── utils.rs │ │ └── lib.rs │ ├── LICENSE_MIT │ ├── Cargo.toml │ ├── README.md │ ├── .travis.yml │ └── LICENSE_APACHE └── yew-image-processing │ ├── .cargo-ok │ ├── static │ ├── style.scss │ └── index.html │ ├── .gitignore │ ├── bootstrap.js │ ├── netlify │ ├── todomvc.wasm │ ├── index.html │ └── todomvc.js │ ├── tests │ └── web.rs │ ├── .github │ └── workflows │ │ ├── check.yml │ │ └── deploy.yml │ ├── src │ ├── lib.rs │ └── app.rs │ ├── package.json │ ├── README.md │ ├── Cargo.toml │ ├── LICENSE_MIT │ ├── webpack.config.js │ └── LICENSE_APACHE ├── Ch02 ├── catdex │ ├── 3 │ ├── migrations │ │ ├── .gitkeep │ │ ├── 2020-05-26-192813_create_cats │ │ │ ├── down.sql │ │ │ └── up.sql │ │ └── 00000000000000_diesel_initial_setup │ │ │ ├── down.sql │ │ │ └── up.sql │ ├── .gitignore │ ├── static │ │ ├── image │ │ │ ├── persian.jpg │ │ │ ├── ragdoll.jpg │ │ │ ├── Selection_224.png │ │ │ ├── extreme_origami.pdf │ │ │ └── british-short-hair.jpg │ │ ├── css │ │ │ └── index.css │ │ ├── cat.html │ │ ├── add.html │ │ └── index.html │ ├── src │ │ ├── schema.rs │ │ ├── models.rs │ │ └── main.rs │ ├── diesel.toml │ ├── start_database.sh │ └── Cargo.toml └── hello-world │ ├── .gitignore │ ├── Cargo.toml │ └── src │ └── main.rs ├── Ch03 └── rest_api │ └── catdex │ ├── .gitignore │ ├── migrations │ ├── .gitkeep │ ├── 2020-05-26-192813_create_cats │ │ ├── down.sql │ │ └── up.sql │ └── 00000000000000_diesel_initial_setup │ │ ├── down.sql │ │ └── up.sql │ ├── static │ ├── css │ │ ├── cat.css │ │ └── index.css │ ├── image │ │ ├── persian.jpg │ │ ├── ragdoll.jpg │ │ ├── Selection_224.png │ │ └── british-short-hair.jpg │ ├── add.html │ ├── cat.html │ └── index.html │ ├── src │ ├── schema.rs │ ├── models.rs │ ├── errors.rs │ └── main.rs │ ├── diesel.toml │ ├── create_cert.sh │ ├── start_database.sh │ └── Cargo.toml ├── Ch05 ├── serverless-catdex │ ├── .gitignore │ ├── Cargo.toml │ ├── package.json │ ├── client │ │ └── dist │ │ │ ├── css │ │ │ └── index.css │ │ │ ├── index.html │ │ │ └── add.html │ ├── cats │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── cat_post │ │ ├── Cargo.toml │ │ └── src │ │ │ └── main.rs │ ├── .github │ │ └── workflows │ │ │ └── main.yml │ ├── serverless.yml │ └── README.md └── serverless-hello-world │ ├── Cargo.toml │ └── src │ └── main.rs ├── .gitattributes ├── 9781484265888.jpg ├── Ch04 └── websocket │ ├── pre-commit │ ├── client │ ├── index.html │ ├── index.js │ ├── chat.js │ ├── chat.html │ └── json_chat.html │ ├── examples │ ├── echo_server.rs │ ├── chat_server.rs │ ├── push_notification.rs │ ├── unresponsive_client.rs │ ├── broadcast_client.rs │ ├── json_chat_server.rs │ ├── 5_sec_ping_timer.rs │ ├── unresponsive_timer.rs │ └── broadcast.rs │ └── Cargo.toml ├── errata.md ├── README.md ├── Contributing.md └── LICENSE.txt /Ch06/hello-wasm/.cargo-ok: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Ch02/catdex/migrations/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Ch02/catdex/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/.cargo-ok: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/.cargo-ok: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Ch02/hello-world/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/migrations/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/client/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | -------------------------------------------------------------------------------- /Ch05/serverless-catdex/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .serverless 3 | target -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/client/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /Ch05/serverless-catdex/Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["cats", "cat_post"] 3 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/client/index.js: -------------------------------------------------------------------------------- 1 | import * as wasm from "hello-wasm"; 2 | 3 | wasm.greet(); 4 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/static/css/cat.css: -------------------------------------------------------------------------------- 1 | img { 2 | max-width: 90vw; 3 | max-height: 80vh; 4 | } 5 | -------------------------------------------------------------------------------- /9781484265888.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/practical-rust-web-projects/HEAD/9781484265888.jpg -------------------------------------------------------------------------------- /Ch06/hello-wasm/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | bin/ 5 | pkg/ 6 | wasm-pack.log 7 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | bin/ 5 | pkg/ 6 | wasm-pack.log 7 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/static/style.scss: -------------------------------------------------------------------------------- 1 | $background: #f5f5f5; 2 | 3 | body { 4 | background: $background; 5 | } 6 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/client/.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: "10" 3 | 4 | script: 5 | - ./node_modules/.bin/webpack 6 | -------------------------------------------------------------------------------- /Ch02/catdex/migrations/2020-05-26-192813_create_cats/down.sql: -------------------------------------------------------------------------------- 1 | -- This file should undo anything in `up.sql` 2 | DROP TABLE cats 3 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/client/.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: "10" 3 | 4 | script: 5 | - ./node_modules/.bin/webpack 6 | -------------------------------------------------------------------------------- /Ch02/catdex/static/image/persian.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/practical-rust-web-projects/HEAD/Ch02/catdex/static/image/persian.jpg -------------------------------------------------------------------------------- /Ch02/catdex/static/image/ragdoll.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/practical-rust-web-projects/HEAD/Ch02/catdex/static/image/ragdoll.jpg -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/migrations/2020-05-26-192813_create_cats/down.sql: -------------------------------------------------------------------------------- 1 | -- This file should undo anything in `up.sql` 2 | DROP TABLE cats 3 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | bin/ 5 | pkg/ 6 | dist/ 7 | wasm-pack.log 8 | node_modules 9 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/bootstrap.js: -------------------------------------------------------------------------------- 1 | import './static/style.scss'; 2 | 3 | import("./pkg").then(module => { 4 | module.run_app(); 5 | }); 6 | -------------------------------------------------------------------------------- /Ch02/catdex/static/image/Selection_224.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/practical-rust-web-projects/HEAD/Ch02/catdex/static/image/Selection_224.png -------------------------------------------------------------------------------- /Ch02/catdex/static/image/extreme_origami.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/practical-rust-web-projects/HEAD/Ch02/catdex/static/image/extreme_origami.pdf -------------------------------------------------------------------------------- /Ch04/websocket/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | echo "Running pre-commit checks..." 3 | cargo fmt 4 | # find . -name main.rs | xargs rustfmt --check 5 | -------------------------------------------------------------------------------- /Ch02/catdex/src/schema.rs: -------------------------------------------------------------------------------- 1 | table! { 2 | cats (id) { 3 | id -> Int4, 4 | name -> Varchar, 5 | image_path -> Varchar, 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/static/image/persian.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/practical-rust-web-projects/HEAD/Ch03/rest_api/catdex/static/image/persian.jpg -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/static/image/ragdoll.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/practical-rust-web-projects/HEAD/Ch03/rest_api/catdex/static/image/ragdoll.jpg -------------------------------------------------------------------------------- /Ch06/yew-image-processing/netlify/todomvc.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/practical-rust-web-projects/HEAD/Ch06/yew-image-processing/netlify/todomvc.wasm -------------------------------------------------------------------------------- /Ch02/catdex/static/image/british-short-hair.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/practical-rust-web-projects/HEAD/Ch02/catdex/static/image/british-short-hair.jpg -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/src/schema.rs: -------------------------------------------------------------------------------- 1 | table! { 2 | cats (id) { 3 | id -> Int4, 4 | name -> Varchar, 5 | image_path -> Varchar, 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/static/image/Selection_224.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/practical-rust-web-projects/HEAD/Ch03/rest_api/catdex/static/image/Selection_224.png -------------------------------------------------------------------------------- /Ch02/catdex/diesel.toml: -------------------------------------------------------------------------------- 1 | # For documentation on how to configure this file, 2 | # see diesel.rs/guides/configuring-diesel-cli 3 | 4 | [print_schema] 5 | file = "src/schema.rs" 6 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/static/image/british-short-hair.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/practical-rust-web-projects/HEAD/Ch03/rest_api/catdex/static/image/british-short-hair.jpg -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/diesel.toml: -------------------------------------------------------------------------------- 1 | # For documentation on how to configure this file, 2 | # see diesel.rs/guides/configuring-diesel-cli 3 | 4 | [print_schema] 5 | file = "src/schema.rs" 6 | -------------------------------------------------------------------------------- /Ch02/catdex/migrations/2020-05-26-192813_create_cats/up.sql: -------------------------------------------------------------------------------- 1 | -- Your SQL goes here 2 | CREATE TABLE cats ( 3 | id SERIAL PRIMARY KEY, 4 | name VARCHAR NOT NULL, 5 | image_path VARCHAR NOT NULL 6 | ) 7 | -------------------------------------------------------------------------------- /Ch04/websocket/client/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/migrations/2020-05-26-192813_create_cats/up.sql: -------------------------------------------------------------------------------- 1 | -- Your SQL goes here 2 | CREATE TABLE cats ( 3 | id SERIAL PRIMARY KEY, 4 | name VARCHAR NOT NULL, 5 | image_path VARCHAR NOT NULL 6 | ) 7 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/create_cert.sh: -------------------------------------------------------------------------------- 1 | openssl req -x509 -newkey rsa:4096 \ 2 | -keyout key.pem \ 3 | -out cert.pem \ 4 | -days 365 \ 5 | -sha256 \ 6 | -subj "/CN=localhost" 7 | 8 | openssl rsa -in key.pem -out key-no-password.pem 9 | -------------------------------------------------------------------------------- /Ch05/serverless-catdex/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "devDependencies": { 3 | "serverless": "^1.74.1", 4 | "serverless-rust": "^0.3.8" 5 | }, 6 | "name": "serverless-catdex", 7 | "dependencies": { 8 | "serverless-finch": "^2.6.0" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Ch04/websocket/examples/echo_server.rs: -------------------------------------------------------------------------------- 1 | extern crate ws; 2 | 3 | fn main() { 4 | ws::listen("127.0.0.1:8080", |out| { 5 | move |msg| { 6 | println!("Received message: {}", msg); 7 | out.send(msg) 8 | } 9 | }) 10 | .unwrap() 11 | } 12 | -------------------------------------------------------------------------------- /Ch02/catdex/static/css/index.css: -------------------------------------------------------------------------------- 1 | .cats { 2 | display: flex; 3 | } 4 | 5 | .cat { 6 | border: 1px solid grey; 7 | min-width: 200px; 8 | min-height: 350px; 9 | margin: 5px; 10 | padding: 5px; 11 | text-align: center; 12 | } 13 | 14 | .cat > img { 15 | width: 190px; 16 | } 17 | -------------------------------------------------------------------------------- /Ch04/websocket/examples/chat_server.rs: -------------------------------------------------------------------------------- 1 | extern crate ws; 2 | 3 | fn main() { 4 | ws::listen("127.0.0.1:8080", |out| { 5 | move |msg| { 6 | println!("Received message: {}", msg); 7 | out.broadcast(msg) 8 | } 9 | }) 10 | .unwrap() 11 | } 12 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Yew • TodoMVC 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/static/css/index.css: -------------------------------------------------------------------------------- 1 | .cats { 2 | display: flex; 3 | } 4 | 5 | .cat { 6 | border: 1px solid grey; 7 | min-width: 200px; 8 | min-height: 350px; 9 | margin: 5px; 10 | padding: 5px; 11 | text-align: center; 12 | } 13 | 14 | .cat > img { 15 | width: 190px; 16 | } 17 | -------------------------------------------------------------------------------- /errata.md: -------------------------------------------------------------------------------- 1 | # Errata for *Practical Rust Web Projects* 2 | 3 | On **page xx** [Summary of error]: 4 | 5 | Details of error here. Highlight key pieces in **bold**. 6 | 7 | *** 8 | 9 | On **page xx** [Summary of error]: 10 | 11 | Details of error here. Highlight key pieces in **bold**. 12 | 13 | *** -------------------------------------------------------------------------------- /Ch05/serverless-catdex/client/dist/css/index.css: -------------------------------------------------------------------------------- 1 | .cats { 2 | display: flex; 3 | } 4 | 5 | .cat { 6 | border: 1px solid grey; 7 | min-width: 200px; 8 | min-height: 350px; 9 | margin: 5px; 10 | padding: 5px; 11 | text-align: center; 12 | } 13 | 14 | .cat > img { 15 | width: 190px; 16 | } 17 | -------------------------------------------------------------------------------- /Ch02/hello-world/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hello-world" 3 | version = "0.1.0" 4 | authors = ["Shing Lyu "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | actix-web = "3" 11 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/client/bootstrap.js: -------------------------------------------------------------------------------- 1 | // A dependency graph that contains any wasm must all be imported 2 | // asynchronously. This `bootstrap.js` file does the single async import, so 3 | // that no one else needs to worry about it again. 4 | import("./index.js") 5 | .catch(e => console.error("Error importing `index.js`:", e)); 6 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/tests/web.rs: -------------------------------------------------------------------------------- 1 | //! Test suite for the Web and headless browsers. 2 | 3 | #![cfg(target_arch = "wasm32")] 4 | 5 | extern crate wasm_bindgen_test; 6 | use wasm_bindgen_test::*; 7 | 8 | wasm_bindgen_test_configure!(run_in_browser); 9 | 10 | #[wasm_bindgen_test] 11 | fn pass() { 12 | assert_eq!(1 + 1, 2); 13 | } 14 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/client/bootstrap.js: -------------------------------------------------------------------------------- 1 | // A dependency graph that contains any wasm must all be imported 2 | // asynchronously. This `bootstrap.js` file does the single async import, so 3 | // that no one else needs to worry about it again. 4 | import("./index.js") 5 | .catch(e => console.error("Error importing `index.js`:", e)); 6 | -------------------------------------------------------------------------------- /Ch04/websocket/client/index.js: -------------------------------------------------------------------------------- 1 | const ws = new WebSocket("ws://127.0.0.1:8080") 2 | 3 | ws.addEventListener("open", function (event) { 4 | console.log("Sending message to server: Meow!") 5 | ws.send("Meow!") 6 | }) 7 | 8 | ws.addEventListener("message", function (event) { 9 | console.log("Message from server:", event.data) 10 | }) 11 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/tests/web.rs: -------------------------------------------------------------------------------- 1 | //! Test suite for the Web and headless browsers. 2 | 3 | #![cfg(target_arch = "wasm32")] 4 | 5 | extern crate wasm_bindgen_test; 6 | use wasm_bindgen_test::*; 7 | 8 | wasm_bindgen_test_configure!(run_in_browser); 9 | 10 | #[wasm_bindgen_test] 11 | fn pass() { 12 | assert_eq!(1 + 1, 2); 13 | } 14 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/tests/web.rs: -------------------------------------------------------------------------------- 1 | //! Test suite for the Web and headless browsers. 2 | 3 | #![cfg(target_arch = "wasm32")] 4 | 5 | extern crate wasm_bindgen_test; 6 | use wasm_bindgen_test::*; 7 | 8 | wasm_bindgen_test_configure!(run_in_browser); 9 | 10 | #[wasm_bindgen_test] 11 | fn pass() { 12 | assert_eq!(1 + 1, 2); 13 | } 14 | -------------------------------------------------------------------------------- /Ch02/catdex/start_database.sh: -------------------------------------------------------------------------------- 1 | # Run this the first time: 2 | # docker run --name catdex-db -e POSTGRES_PASSWORD=mypassword -p 5432:5432 -d postgres:12.3-alpine 3 | 4 | # From the second time, run this instead: 5 | docker start catdex-db 6 | 7 | echo "Run this to set the databse URL:" 8 | echo "export DATABASE_URL=postgres://postgres:mypassword@localhost" 9 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/start_database.sh: -------------------------------------------------------------------------------- 1 | # Run this the first time: 2 | # docker run --name catdex-db -e POSTGRES_PASSWORD=mypassword -p 5432:5432 -d postgres:12.3-alpine 3 | 4 | # From the second time, run this instead: 5 | docker start catdex-db 6 | 7 | echo "Run this to set the databse URL:" 8 | echo "export DATABASE_URL=postgres://postgres:mypassword@localhost" 9 | -------------------------------------------------------------------------------- /Ch05/serverless-catdex/cats/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cats" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | [dependencies] 7 | tokio = { version = "0.2", features = ["macros"] } 8 | lambda_http = { git = "https://github.com/awslabs/aws-lambda-rust-runtime/", branch = "master"} 9 | serde_json = "1.0" 10 | rusoto_core = "0.45.0" 11 | rusoto_dynamodb = "0.45.0" 12 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/client/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Hello wasm-pack! 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Ch04/websocket/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "websocket" 3 | version = "0.1.0" 4 | authors = ["Shing Lyu "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | ws = "0.9.1" 11 | serde = "1.0.104" 12 | serde_json = "1.0.48" 13 | serde_derive= "1.0.104" 14 | -------------------------------------------------------------------------------- /Ch02/catdex/migrations/00000000000000_diesel_initial_setup/down.sql: -------------------------------------------------------------------------------- 1 | -- This file was automatically created by Diesel to setup helper functions 2 | -- and other internal bookkeeping. This file is safe to edit, any future 3 | -- changes will be added to existing projects as new migrations. 4 | 5 | DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); 6 | DROP FUNCTION IF EXISTS diesel_set_updated_at(); 7 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/client/webpack.config.js: -------------------------------------------------------------------------------- 1 | const CopyWebpackPlugin = require("copy-webpack-plugin"); 2 | const path = require('path'); 3 | 4 | module.exports = { 5 | entry: "./bootstrap.js", 6 | output: { 7 | path: path.resolve(__dirname, "dist"), 8 | filename: "bootstrap.js", 9 | }, 10 | mode: "development", 11 | plugins: [ 12 | new CopyWebpackPlugin(['index.html']) 13 | ], 14 | }; 15 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/migrations/00000000000000_diesel_initial_setup/down.sql: -------------------------------------------------------------------------------- 1 | -- This file was automatically created by Diesel to setup helper functions 2 | -- and other internal bookkeeping. This file is safe to edit, any future 3 | -- changes will be added to existing projects as new migrations. 4 | 5 | DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); 6 | DROP FUNCTION IF EXISTS diesel_set_updated_at(); 7 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/.appveyor.yml: -------------------------------------------------------------------------------- 1 | install: 2 | - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe 3 | - if not defined RUSTFLAGS rustup-init.exe -y --default-host x86_64-pc-windows-msvc --default-toolchain nightly 4 | - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin 5 | - rustc -V 6 | - cargo -V 7 | 8 | build: false 9 | 10 | test_script: 11 | - cargo test --locked 12 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/client/webpack.config.js: -------------------------------------------------------------------------------- 1 | const CopyWebpackPlugin = require("copy-webpack-plugin"); 2 | const path = require('path'); 3 | 4 | module.exports = { 5 | entry: "./bootstrap.js", 6 | output: { 7 | path: path.resolve(__dirname, "dist"), 8 | filename: "bootstrap.js", 9 | }, 10 | mode: "development", 11 | plugins: [ 12 | new CopyWebpackPlugin(['index.html']) 13 | ], 14 | }; 15 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/.appveyor.yml: -------------------------------------------------------------------------------- 1 | install: 2 | - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe 3 | - if not defined RUSTFLAGS rustup-init.exe -y --default-host x86_64-pc-windows-msvc --default-toolchain nightly 4 | - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin 5 | - rustc -V 6 | - cargo -V 7 | 8 | build: false 9 | 10 | test_script: 11 | - cargo test --locked 12 | -------------------------------------------------------------------------------- /Ch02/catdex/static/cat.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {{name}} 6 | 12 | 13 | 14 |

{{name}}

15 | 16 |

17 | Back 18 |

19 | 20 | 21 | -------------------------------------------------------------------------------- /Ch02/catdex/src/models.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | use super::schema::cats; 3 | 4 | 5 | #[derive(Queryable, Serialize)] 6 | pub struct Cat { 7 | pub id: i32, 8 | pub name: String, 9 | pub image_path: String 10 | } 11 | 12 | #[derive(Insertable, Serialize, Deserialize)] 13 | #[table_name = "cats"] 14 | pub struct NewCat { 15 | // id will be added by the database 16 | pub name: String, 17 | pub image_path: String 18 | } 19 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/src/models.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | use super::schema::cats; 3 | 4 | 5 | #[derive(Queryable, Serialize)] 6 | pub struct Cat { 7 | pub id: i32, 8 | pub name: String, 9 | pub image_path: String 10 | } 11 | 12 | #[derive(Insertable, Serialize, Deserialize)] 13 | #[table_name = "cats"] 14 | pub struct NewCat { 15 | // id will be added by the database 16 | pub name: String, 17 | pub image_path: String 18 | } 19 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/src/lib.rs: -------------------------------------------------------------------------------- 1 | mod utils; 2 | 3 | use wasm_bindgen::prelude::*; 4 | 5 | // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global 6 | // allocator. 7 | #[cfg(feature = "wee_alloc")] 8 | #[global_allocator] 9 | static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; 10 | 11 | #[wasm_bindgen] 12 | extern { 13 | fn alert(s: &str); 14 | } 15 | 16 | #[wasm_bindgen] 17 | pub fn greet() { 18 | alert("Hello, hello-wasm!"); 19 | } 20 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/netlify/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Yew • TodoMVC 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Ch02/hello-world/src/main.rs: -------------------------------------------------------------------------------- 1 | use actix_web::{web, App, HttpResponse, HttpServer, Responder}; 2 | 3 | async fn hello() -> impl Responder { 4 | HttpResponse::Ok().body("Hello world") 5 | } 6 | 7 | #[actix_web::main] 8 | async fn main() -> std::io::Result<()> { 9 | println!("Listening on port 8080"); 10 | HttpServer::new(|| { 11 | App::new() 12 | .route("/hello", web::get().to(hello)) 13 | }) 14 | .bind("127.0.0.1:8080")? 15 | .run() 16 | .await 17 | } 18 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/src/utils.rs: -------------------------------------------------------------------------------- 1 | pub fn set_panic_hook() { 2 | // When the `console_error_panic_hook` feature is enabled, we can call the 3 | // `set_panic_hook` function at least once during initialization, and then 4 | // we will get better error messages if our code ever panics. 5 | // 6 | // For more details see 7 | // https://github.com/rustwasm/console_error_panic_hook#readme 8 | #[cfg(feature = "console_error_panic_hook")] 9 | console_error_panic_hook::set_once(); 10 | } 11 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/src/utils.rs: -------------------------------------------------------------------------------- 1 | pub fn set_panic_hook() { 2 | // When the `console_error_panic_hook` feature is enabled, we can call the 3 | // `set_panic_hook` function at least once during initialization, and then 4 | // we will get better error messages if our code ever panics. 5 | // 6 | // For more details see 7 | // https://github.com/rustwasm/console_error_panic_hook#readme 8 | #[cfg(feature = "console_error_panic_hook")] 9 | console_error_panic_hook::set_once(); 10 | } 11 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/.github/workflows/check.yml: -------------------------------------------------------------------------------- 1 | name: Cargo Check 2 | on: [pull_request] 3 | jobs: 4 | check: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v2 8 | - name: Setup Rust 9 | uses: actions-rs/toolchain@v1 10 | with: 11 | toolchain: stable 12 | - name: Run fmt 13 | run: cargo fmt -- --check 14 | - name: Run clippy 15 | run: cargo clippy -- --deny=warnings 16 | - name: Run check 17 | run: cargo check -------------------------------------------------------------------------------- /Ch02/catdex/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "catdex" 3 | version = "0.1.0" 4 | authors = ["Shing Lyu "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | actix-web = "3" 11 | actix-files = "0.3.0" 12 | serde_json = "1.0.53" 13 | handlebars = { version = "3.0.1", features = ["dir_source"] } 14 | diesel = { version = "1.4.4", features = ["postgres", "r2d2"] } 15 | serde = "1.0.110" 16 | r2d2 = "0.8.8" 17 | awmp = "0.6.0" 18 | -------------------------------------------------------------------------------- /Ch04/websocket/client/chat.js: -------------------------------------------------------------------------------- 1 | document.addEventListener("DOMContentLoaded", function(){ 2 | const socket = new WebSocket("ws://127.0.0.1:8080"); 3 | socket.onmessage = function (event) { 4 | const messages = document.getElementById("messages"); 5 | messages.value += `${event.data}\n`; 6 | }; 7 | 8 | const sendButton= document.getElementById("send"); 9 | sendButton.addEventListener("click", (event) => { 10 | const message = document.getElementById("message"); 11 | socket.send(message.value) 12 | message.value = ""; 13 | }) 14 | }); 15 | -------------------------------------------------------------------------------- /Ch05/serverless-hello-world/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "serverless-hello-world" 3 | version = "0.1.0" 4 | authors = ["Shing Lyu "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | lambda_runtime = "0.2.1" 11 | serde = "^1" 12 | serde_json = "^1" 13 | serde_derive = "^1" 14 | tokio = "0.1" 15 | log = "^0.4" 16 | simple_logger = "^1.11.0" 17 | simple-error = "^0.1" 18 | 19 | [[bin]] 20 | name = "bootstrap" 21 | path = "src/main.rs" 22 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![recursion_limit = "512"] 2 | 3 | mod app; 4 | 5 | use wasm_bindgen::prelude::*; 6 | 7 | // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global 8 | // allocator. 9 | #[cfg(feature = "wee_alloc")] 10 | #[global_allocator] 11 | static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; 12 | 13 | // This is the entry point for the web app 14 | #[wasm_bindgen] 15 | pub fn run_app() -> Result<(), JsValue> { 16 | wasm_logger::init(wasm_logger::Config::default()); 17 | yew::start_app::(); 18 | Ok(()) 19 | } 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apress Source Code 2 | 3 | This repository accompanies [*Practical Rust Web Projects*](https://www.apress.com/9781484265888) by Shing Lyu (Apress, 2021). 4 | 5 | [comment]: #cover 6 | ![Cover image](9781484265888.jpg) 7 | 8 | Download the files as a zip using the green button, or clone the repository to your machine using Git. 9 | 10 | ## Releases 11 | 12 | Release v1.0 corresponds to the code in the published book, without corrections or updates. 13 | 14 | ## Contributions 15 | 16 | See the file Contributing.md for more information on how you can contribute to this repository. -------------------------------------------------------------------------------- /Ch04/websocket/client/chat.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | WebSocket Chat 6 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Ch05/serverless-catdex/cat_post/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cat_post" 3 | version = "0.1.0" 4 | authors = ["Shing Lyu "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | tokio = { version = "0.2", features = ["macros"] } 11 | lambda_http = { git = "https://github.com/awslabs/aws-lambda-rust-runtime/", branch = "master"} 12 | serde_json = "1.0" 13 | rusoto_core = "0.45.0" 14 | rusoto_dynamodb = "0.45.0" 15 | serde = "1.0.114" 16 | rusoto_s3 = "0.45.0" 17 | rusoto_credential = "0.45.0" 18 | -------------------------------------------------------------------------------- /Ch04/websocket/examples/push_notification.rs: -------------------------------------------------------------------------------- 1 | extern crate ws; 2 | 3 | use std::{thread, time}; 4 | use ws::{Handler, Sender, WebSocket}; 5 | 6 | struct Server { 7 | out: Sender, 8 | } 9 | 10 | impl Handler for Server {} 11 | 12 | fn main() { 13 | let server = WebSocket::new(|out| Server { out }).unwrap(); 14 | 15 | let broadcaster = server.broadcaster(); 16 | 17 | let periodic = thread::spawn(move || loop { 18 | broadcaster.send("Meow!").unwrap(); 19 | thread::sleep(time::Duration::from_secs(1)); 20 | }); 21 | server.listen("127.0.0.1:8080").unwrap(); 22 | periodic.join().unwrap(); 23 | } 24 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/client/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Cat image processor 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Ch02/catdex/static/add.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Catdex 6 | 7 | 8 | 9 |

Add a new cat

10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | -------------------------------------------------------------------------------- /Ch02/catdex/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {{project_name}} 6 | 7 | 8 | 9 |

{{project_name}}

10 |

11 | Add a new cat 12 |

13 | 14 |
15 | {{#each cats}} 16 | 20 | {{/each}} 21 |
22 | 23 | 24 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/static/add.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Catdex 6 | 7 | 8 | 9 |

Add a new cat

10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | -------------------------------------------------------------------------------- /Ch04/websocket/examples/unresponsive_client.rs: -------------------------------------------------------------------------------- 1 | extern crate ws; 2 | 3 | use ws::{connect, CloseCode, Frame, Message, OpCode, Result}; 4 | 5 | struct Client { 6 | out: ws::Sender, 7 | } 8 | impl ws::Handler for Client { 9 | fn on_frame( 10 | &mut self, 11 | frame: Frame, 12 | ) -> Result> { 13 | if frame.opcode() == OpCode::Ping { 14 | println!( 15 | "Received a ping, but we are not responding" 16 | ); 17 | } 18 | 19 | Ok(None) 20 | } 21 | } 22 | 23 | fn main() { 24 | connect("ws://127.0.0.1:8080", |out| Client { out: out }) 25 | .unwrap(); 26 | } 27 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/client/.bin/create-wasm-app.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const { spawn } = require("child_process"); 4 | const fs = require("fs"); 5 | 6 | let folderName = '.'; 7 | 8 | if (process.argv.length >= 3) { 9 | folderName = process.argv[2]; 10 | if (!fs.existsSync(folderName)) { 11 | fs.mkdirSync(folderName); 12 | } 13 | } 14 | 15 | const clone = spawn("git", ["clone", "https://github.com/rustwasm/create-wasm-app.git", folderName]); 16 | 17 | clone.on("close", code => { 18 | if (code !== 0) { 19 | console.error("cloning the template failed!") 20 | process.exit(code); 21 | } else { 22 | console.log("🦀 Rust + 🕸 Wasm = ❤"); 23 | } 24 | }); 25 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/client/.bin/create-wasm-app.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const { spawn } = require("child_process"); 4 | const fs = require("fs"); 5 | 6 | let folderName = '.'; 7 | 8 | if (process.argv.length >= 3) { 9 | folderName = process.argv[2]; 10 | if (!fs.existsSync(folderName)) { 11 | fs.mkdirSync(folderName); 12 | } 13 | } 14 | 15 | const clone = spawn("git", ["clone", "https://github.com/rustwasm/create-wasm-app.git", folderName]); 16 | 17 | clone.on("close", code => { 18 | if (code !== 0) { 19 | console.error("cloning the template failed!") 20 | process.exit(code); 21 | } else { 22 | console.log("🦀 Rust + 🕸 Wasm = ❤"); 23 | } 24 | }); 25 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "scripts": { 4 | "test": "echo \"Error: no test specified\" && exit 1", 5 | "dev": "webpack --mode development", 6 | "build": "webpack --mode production", 7 | "start:dev": "webpack-dev-server --mode development" 8 | }, 9 | "devDependencies": { 10 | "@wasm-tool/wasm-pack-plugin": "^1.1.0", 11 | "copy-webpack-plugin": "^5.1.1", 12 | "css-loader": "^3.5.3", 13 | "sass": "^1.26.5", 14 | "sass-loader": "^8.0.2", 15 | "style-loader": "^1.2.1", 16 | "wasm-pack": "^0.9.1", 17 | "webpack": "^4.42.0", 18 | "webpack-cli": "^3.3.11", 19 | "webpack-dev-server": "^3.10.3" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "catdex" 3 | version = "0.1.0" 4 | authors = ["Shing Lyu "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | actix-web = { version = "3", features = ["openssl"] } 11 | actix-files = "0.3.0" 12 | serde_json = "1.0.53" 13 | diesel = { version = "1.4.4", features = ["postgres", "r2d2"] } 14 | serde = { version = "1.0.110", features = ["derive"] } 15 | r2d2 = "0.8.8" 16 | validator = "0.10.0" 17 | validator_derive = "0.10.0" 18 | derive_more = "0.99.8" 19 | env_logger = "0.7.1" 20 | log = "0.4.8" 21 | openssl = "0.10.30" 22 | actix-rt = "1.1.1" 23 | -------------------------------------------------------------------------------- /Contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Apress Source Code 2 | 3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for the relevant book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! -------------------------------------------------------------------------------- /Ch06/yew-image-processing/README.md: -------------------------------------------------------------------------------- 1 | [![Netlify Status](https://api.netlify.com/api/v1/badges/5ba03ba7-ff8b-4c54-94e7-cd5fd76a6737/deploy-status)](https://app.netlify.com/sites/yew-todomvc/deploys) 2 | 3 | ## About 4 | 5 | This template shows how to create a web app using Yew and wasm-pack. 6 | 7 | ## 🚴 Usage 8 | 9 | ### 🛠️ Build 10 | 11 | When building for the first time, ensure to install dependencies first. 12 | 13 | ``` 14 | yarn install 15 | ``` 16 | 17 | ``` 18 | yarn run build 19 | ``` 20 | 21 | ### 🔬 Serve locally 22 | 23 | ``` 24 | yarn run start:dev 25 | ``` 26 | 27 | 28 | ## 🔋 Batteries Included 29 | 30 | * [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) for communicating 31 | between WebAssembly and JavaScript. 32 | * [`wee_alloc`](https://github.com/rustwasm/wee_alloc), an allocator optimized 33 | for small code size. 34 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/static/cat.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Cat 6 | 7 | 8 | 9 |

Loading...

10 | 11 |

12 | Back 13 |

14 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy to Netlify 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | 7 | jobs: 8 | deploy: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | 13 | - name: Setup Rust 14 | uses: actions-rs/toolchain@v1 15 | with: 16 | toolchain: stable 17 | target: wasm32-unknown-unknown 18 | 19 | - name: Setup Node 20 | uses: actions/setup-node@v1 21 | with: 22 | node-version: 14 23 | 24 | - name: Install 25 | run: npm install 26 | 27 | - name: Build 28 | run: npm run build 29 | 30 | - name: Publish 31 | uses: netlify/actions/cli@master 32 | with: 33 | args: deploy --dir=dist --prod 34 | env: 35 | NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }} 36 | NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} 37 | 38 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/src/errors.rs: -------------------------------------------------------------------------------- 1 | use actix_web::{error, HttpResponse}; 2 | use actix_web::http::{StatusCode}; 3 | use derive_more::Display; 4 | use serde_json::json; 5 | 6 | #[derive(Display, Debug)] 7 | pub enum UserError { 8 | #[display(fmt="Invalid input parameter")] 9 | ValidationError, 10 | #[display(fmt="Internal server error")] 11 | InternalError, 12 | #[display(fmt="Not found")] 13 | NotFoundError, 14 | } 15 | 16 | impl error::ResponseError for UserError { 17 | fn error_response(&self) -> HttpResponse { 18 | HttpResponse::build(self.status_code()) 19 | .json(json!({ "msg": self.to_string() })) 20 | } 21 | fn status_code(&self) -> StatusCode { 22 | match *self { 23 | UserError::ValidationError => StatusCode::BAD_REQUEST, 24 | UserError::InternalError => StatusCode::INTERNAL_SERVER_ERROR, 25 | UserError::NotFoundError => StatusCode::NOT_FOUND, 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "yew-wasm-pack-template" 3 | version = "0.2.0" 4 | authors = ["Yew Maintainers Result<(), Box> { 21 | SimpleLogger::new().with_level(log::LevelFilter::Debug).init()?; 22 | lambda!(my_handler); 23 | 24 | Ok(()) 25 | } 26 | 27 | fn my_handler(e: CustomEvent, c: Context) -> Result { 28 | if e.first_name == "" { 29 | error!("Empty first name in request {}", c.aws_request_id); 30 | bail!("Empty first name"); 31 | } 32 | 33 | Ok(CustomOutput { 34 | message: format!("Hello, {}!", e.first_name), 35 | }) 36 | } 37 | -------------------------------------------------------------------------------- /Ch04/websocket/examples/broadcast_client.rs: -------------------------------------------------------------------------------- 1 | extern crate ws; 2 | 3 | use ws::{connect, CloseCode, Frame, Message, OpCode, Result}; 4 | 5 | struct Client { 6 | out: ws::Sender, 7 | } 8 | impl ws::Handler for Client { 9 | fn on_frame( 10 | &mut self, 11 | frame: Frame, 12 | ) -> Result> { 13 | if frame.opcode() == OpCode::Ping { 14 | println!( 15 | "Received a ping, but we are not responding" 16 | ); 17 | } 18 | 19 | Ok(None) 20 | 21 | // TODO: default frame validation 22 | } 23 | 24 | fn on_message(&mut self, msg: Message) -> Result<()> { 25 | println!("Received message {:?}", msg); 26 | Ok(()) 27 | } 28 | 29 | fn on_close(&mut self, code: CloseCode, reason: &str) { 30 | println!( 31 | "WebSocket closing for ({:?}) {}", 32 | code, reason 33 | ); 34 | } 35 | } 36 | 37 | fn main() { 38 | connect("ws://127.0.0.1:8080", |out| Client { out: out }) 39 | .unwrap(); 40 | } 41 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate web_sys; 2 | 3 | mod utils; 4 | 5 | // use image::ConvertBuffer; 6 | use image::{RgbaImage}; 7 | use image::imageops; 8 | 9 | use wasm_bindgen::prelude::*; 10 | 11 | // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global 12 | // allocator. 13 | #[cfg(feature = "wee_alloc")] 14 | #[global_allocator] 15 | static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; 16 | 17 | #[wasm_bindgen] 18 | pub fn shrink_by_half(original_image: Vec, width: u32, height: u32) -> Vec { 19 | let image: RgbaImage = 20 | image::ImageBuffer::from_vec(width, height, original_image).unwrap(); 21 | let output_image = imageops::resize(&image, width / 2, height / 2, imageops::FilterType::Nearest); 22 | 23 | output_image.into_vec() 24 | } 25 | 26 | #[wasm_bindgen] 27 | pub fn rotate90(original_image: Vec, width: u32, height: u32) -> Vec { 28 | let image: RgbaImage = 29 | image::ImageBuffer::from_vec(width, height, original_image).unwrap(); 30 | let output_image = imageops::rotate90(&image); 31 | 32 | output_image.into_vec() 33 | } 34 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "create-wasm-app", 3 | "version": "0.1.0", 4 | "description": "create an app to consume rust-generated wasm packages", 5 | "main": "index.js", 6 | "bin": { 7 | "create-wasm-app": ".bin/create-wasm-app.js" 8 | }, 9 | "scripts": { 10 | "build": "webpack --config webpack.config.js", 11 | "start": "webpack-dev-server" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/rustwasm/create-wasm-app.git" 16 | }, 17 | "keywords": [ 18 | "webassembly", 19 | "wasm", 20 | "rust", 21 | "webpack" 22 | ], 23 | "author": "Ashley Williams ", 24 | "license": "(MIT OR Apache-2.0)", 25 | "bugs": { 26 | "url": "https://github.com/rustwasm/create-wasm-app/issues" 27 | }, 28 | "homepage": "https://github.com/rustwasm/create-wasm-app#readme", 29 | "dependencies": { 30 | "hello-wasm": "file:../pkg" 31 | }, 32 | "devDependencies": { 33 | "webpack": "^4.29.3", 34 | "webpack-cli": "^3.1.0", 35 | "webpack-dev-server": "^3.1.5", 36 | "copy-webpack-plugin": "^5.0.0" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hello-wasm" 3 | version = "0.1.0" 4 | authors = ["Shing Lyu "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["cdylib", "rlib"] 9 | 10 | [features] 11 | default = ["console_error_panic_hook"] 12 | 13 | [dependencies] 14 | wasm-bindgen = "0.2" 15 | 16 | # The `console_error_panic_hook` crate provides better debugging of panics by 17 | # logging them with `console.error`. This is great for development, but requires 18 | # all the `std::fmt` and `std::panicking` infrastructure, so isn't great for 19 | # code size when deploying. 20 | console_error_panic_hook = { version = "0.1.1", optional = true } 21 | 22 | # `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size 23 | # compared to the default allocator's ~10K. It is slower than the default 24 | # allocator, however. 25 | # 26 | # Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now. 27 | wee_alloc = { version = "0.4.2", optional = true } 28 | 29 | [dev-dependencies] 30 | wasm-bindgen-test = "0.2" 31 | 32 | [profile.release] 33 | # Tell `rustc` to optimize for small code size. 34 | opt-level = "s" 35 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/client/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) [year] [name] 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "create-wasm-app", 3 | "version": "0.1.0", 4 | "description": "create an app to consume rust-generated wasm packages", 5 | "main": "index.js", 6 | "bin": { 7 | "create-wasm-app": ".bin/create-wasm-app.js" 8 | }, 9 | "scripts": { 10 | "build": "webpack --config webpack.config.js", 11 | "start": "webpack-dev-server" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/rustwasm/create-wasm-app.git" 16 | }, 17 | "keywords": [ 18 | "webassembly", 19 | "wasm", 20 | "rust", 21 | "webpack" 22 | ], 23 | "author": "Ashley Williams ", 24 | "license": "(MIT OR Apache-2.0)", 25 | "bugs": { 26 | "url": "https://github.com/rustwasm/create-wasm-app/issues" 27 | }, 28 | "homepage": "https://github.com/rustwasm/create-wasm-app#readme", 29 | "dependencies": { 30 | "wasm-image-processing": "file:../pkg" 31 | }, 32 | "devDependencies": { 33 | "webpack": "^4.29.3", 34 | "webpack-cli": "^3.1.0", 35 | "webpack-dev-server": "^3.1.5", 36 | "copy-webpack-plugin": "^5.0.0" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/LICENSE_MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 {{authors}} 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/client/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) [year] [name] 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/LICENSE_MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 Shing Lyu 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/LICENSE_MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 Shing Lyu 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const WasmPackPlugin = require('@wasm-tool/wasm-pack-plugin'); 3 | const CopyWebpackPlugin = require('copy-webpack-plugin'); 4 | 5 | const distPath = path.resolve(__dirname, "dist"); 6 | module.exports = (env, argv) => { 7 | return { 8 | devServer: { 9 | contentBase: distPath, 10 | compress: argv.mode === 'production', 11 | port: 8000 12 | }, 13 | entry: './bootstrap.js', 14 | output: { 15 | path: distPath, 16 | filename: "yew-image-processing.js", 17 | webassemblyModuleFilename: "yew-image-processing.wasm" 18 | }, 19 | module: { 20 | rules: [ 21 | { 22 | test: /\.s[ac]ss$/i, 23 | use: [ 24 | 'style-loader', 25 | 'css-loader', 26 | 'sass-loader', 27 | ], 28 | }, 29 | ], 30 | }, 31 | plugins: [ 32 | new CopyWebpackPlugin([ 33 | { from: './static', to: distPath } 34 | ]), 35 | new WasmPackPlugin({ 36 | crateDirectory: ".", 37 | extraArgs: "--no-typescript", 38 | }) 39 | ], 40 | watch: argv.mode !== 'production' 41 | }; 42 | }; 43 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "wasm-image-processing" 3 | version = "0.1.0" 4 | authors = ["Shing Lyu "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["cdylib", "rlib"] 9 | 10 | [features] 11 | default = ["console_error_panic_hook"] 12 | 13 | [dependencies] 14 | wasm-bindgen = "0.2" 15 | image = "0.23.2" 16 | 17 | # The `console_error_panic_hook` crate provides better debugging of panics by 18 | # logging them with `console.error`. This is great for development, but requires 19 | # all the `std::fmt` and `std::panicking` infrastructure, so isn't great for 20 | # code size when deploying. 21 | console_error_panic_hook = { version = "0.1.1", optional = true } 22 | 23 | # `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size 24 | # compared to the default allocator's ~10K. It is slower than the default 25 | # allocator, however. 26 | # 27 | # Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now. 28 | wee_alloc = { version = "0.4.2", optional = true } 29 | [dependencies.web-sys] 30 | version = "0.3.37" 31 | features = [ "console" ] 32 | 33 | [dev-dependencies] 34 | wasm-bindgen-test = "0.2" 35 | 36 | [profile.release] 37 | # Tell `rustc` to optimize for small code size. 38 | opt-level = "s" 39 | -------------------------------------------------------------------------------- /Ch02/catdex/migrations/00000000000000_diesel_initial_setup/up.sql: -------------------------------------------------------------------------------- 1 | -- This file was automatically created by Diesel to setup helper functions 2 | -- and other internal bookkeeping. This file is safe to edit, any future 3 | -- changes will be added to existing projects as new migrations. 4 | 5 | 6 | 7 | 8 | -- Sets up a trigger for the given table to automatically set a column called 9 | -- `updated_at` whenever the row is modified (unless `updated_at` was included 10 | -- in the modified columns) 11 | -- 12 | -- # Example 13 | -- 14 | -- ```sql 15 | -- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); 16 | -- 17 | -- SELECT diesel_manage_updated_at('users'); 18 | -- ``` 19 | CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ 20 | BEGIN 21 | EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s 22 | FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); 23 | END; 24 | $$ LANGUAGE plpgsql; 25 | 26 | CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ 27 | BEGIN 28 | IF ( 29 | NEW IS DISTINCT FROM OLD AND 30 | NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at 31 | ) THEN 32 | NEW.updated_at := current_timestamp; 33 | END IF; 34 | RETURN NEW; 35 | END; 36 | $$ LANGUAGE plpgsql; 37 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/migrations/00000000000000_diesel_initial_setup/up.sql: -------------------------------------------------------------------------------- 1 | -- This file was automatically created by Diesel to setup helper functions 2 | -- and other internal bookkeeping. This file is safe to edit, any future 3 | -- changes will be added to existing projects as new migrations. 4 | 5 | 6 | 7 | 8 | -- Sets up a trigger for the given table to automatically set a column called 9 | -- `updated_at` whenever the row is modified (unless `updated_at` was included 10 | -- in the modified columns) 11 | -- 12 | -- # Example 13 | -- 14 | -- ```sql 15 | -- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); 16 | -- 17 | -- SELECT diesel_manage_updated_at('users'); 18 | -- ``` 19 | CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ 20 | BEGIN 21 | EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s 22 | FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); 23 | END; 24 | $$ LANGUAGE plpgsql; 25 | 26 | CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ 27 | BEGIN 28 | IF ( 29 | NEW IS DISTINCT FROM OLD AND 30 | NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at 31 | ) THEN 32 | NEW.updated_at := current_timestamp; 33 | END IF; 34 | RETURN NEW; 35 | END; 36 | $$ LANGUAGE plpgsql; 37 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Freeware License, some rights reserved 2 | 3 | Copyright (c) 2021 Shing Lyu 4 | 5 | Permission is hereby granted, free of charge, to anyone obtaining a copy 6 | of this software and associated documentation files (the "Software"), 7 | to work with the Software within the limits of freeware distribution and fair use. 8 | This includes the rights to use, copy, and modify the Software for personal use. 9 | Users are also allowed and encouraged to submit corrections and modifications 10 | to the Software for the benefit of other users. 11 | 12 | It is not allowed to reuse, modify, or redistribute the Software for 13 | commercial use in any way, or for a user’s educational materials such as books 14 | or blog articles without prior permission from the copyright holder. 15 | 16 | The above copyright notice and this permission notice need to be included 17 | in all copies or substantial portions of the software. 18 | 19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 25 | SOFTWARE. 26 | 27 | 28 | -------------------------------------------------------------------------------- /Ch04/websocket/examples/json_chat_server.rs: -------------------------------------------------------------------------------- 1 | extern crate ws; 2 | extern crate serde; 3 | #[macro_use] 4 | extern crate serde_json; 5 | #[macro_use] 6 | extern crate serde_derive; 7 | 8 | use std::time::{SystemTime, UNIX_EPOCH}; 9 | use ws::{listen, Message}; 10 | 11 | #[derive(Serialize, Deserialize)] 12 | struct JSONMessage { 13 | name: String, 14 | message: String, 15 | } 16 | 17 | fn main() { 18 | listen("127.0.0.1:8080", |out| { 19 | move |msg: Message| { 20 | let msg_text = msg.as_text().unwrap(); 21 | if let Ok(json_message) = 22 | serde_json::from_str::(msg_text) 23 | { 24 | let now = SystemTime::now() 25 | .duration_since(UNIX_EPOCH) 26 | .expect("Time went backwards"); 27 | println!( 28 | "{} said: {} at {:?}", 29 | json_message.name, 30 | json_message.message, 31 | now.as_millis() 32 | ); 33 | let output_msg = json!({ 34 | "name": json_message.name, 35 | "message": json_message.message, 36 | "received_at": now.as_millis().to_string() 37 | }); 38 | 39 | out.broadcast(Message::Text( 40 | output_msg.to_string(), 41 | ))?; 42 | } 43 | Ok(()) 44 | } 45 | }).unwrap(); 46 | } 47 | -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Catdex 6 | 7 | 8 | 9 |

Catdex

10 |

11 | Add a new cat 12 |

13 | 14 |
15 |

No cats yet

16 |
17 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Ch04/websocket/client/json_chat.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | WebSocket Chat 6 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /Ch05/serverless-catdex/client/dist/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Catdex 6 | 7 | 8 | 9 |

Catdex

10 |

11 | Add a new cat 12 |

13 | 14 |
15 |

No cats yet

16 |
17 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Ch05/serverless-catdex/client/dist/add.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Catdex 6 | 7 | 8 | 9 | 43 |

Add a new cat

44 | 45 |
46 | 47 | 48 | 49 | 50 | 51 |
52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /Ch05/serverless-catdex/cats/src/main.rs: -------------------------------------------------------------------------------- 1 | use lambda_http::{handler, lambda, IntoResponse, Request, Context}; 2 | use lambda_http::http::{StatusCode, Response, HeaderValue}; 3 | use serde_json::json; 4 | use std::collections::HashMap; 5 | use rusoto_core::{Region}; 6 | use rusoto_dynamodb::{DynamoDb, DynamoDbClient, ScanInput}; 7 | 8 | type Error = Box; 9 | 10 | #[tokio::main] 11 | async fn main() -> Result<(), Error> { 12 | lambda::run(handler(cats)).await?; 13 | Ok(()) 14 | } 15 | 16 | async fn cats(_: Request, _: Context) -> Result { 17 | let client = DynamoDbClient::new(Region::EuCentral1); 18 | 19 | let scan_input = ScanInput { 20 | table_name: "shing_catdex".to_string(), 21 | limit: Some(100), 22 | ..Default::default() 23 | }; 24 | 25 | let mut response = match client.scan(scan_input).await { 26 | Ok(output) => { 27 | println!("{:?}", output); 28 | match output.items { 29 | Some(items) => { 30 | json!( 31 | items.into_iter().map(|item| 32 | item.into_iter().map(|(k, v)| (k, v.s.unwrap())).collect() 33 | ).collect::>>() 34 | ).into_response() 35 | } 36 | None => { 37 | Response::builder() 38 | .status(StatusCode::NOT_FOUND) 39 | .body("No cat yet".into()) 40 | .expect("Failed to render response") 41 | } 42 | } 43 | } 44 | Err(error) => { 45 | Response::builder() 46 | .status(StatusCode::INTERNAL_SERVER_ERROR) 47 | .body(format!("{:?}", error).into()) 48 | .expect("Failed to render response") 49 | } 50 | }; 51 | 52 | response.headers_mut().insert("Access-Control-Allow-Origin", HeaderValue::from_static("*")); 53 | Ok(response) 54 | } 55 | -------------------------------------------------------------------------------- /Ch05/serverless-catdex/.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Main 2 | 3 | on: push 4 | 5 | jobs: 6 | codestyle: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: Set up Rust 10 | uses: hecrj/setup-rust-action@v1 11 | with: 12 | components: rustfmt 13 | - uses: actions/checkout@v2 14 | - run: cargo fmt --all -- --check 15 | 16 | lint: 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Set up Rust 20 | uses: hecrj/setup-rust-action@v1 21 | with: 22 | components: clippy 23 | - uses: actions/checkout@v2 24 | - run: cargo clippy --all-targets -- -D clippy::all 25 | 26 | compile: 27 | runs-on: ubuntu-latest 28 | steps: 29 | - name: Set up Rust 30 | uses: hecrj/setup-rust-action@v1 31 | - uses: actions/checkout@v2 32 | - run: cargo check --all 33 | 34 | test: 35 | needs: [codestyle, lint, compile] 36 | runs-on: ubuntu-latest 37 | steps: 38 | - name: Setup Rust 39 | uses: hecrj/setup-rust-action@v1 40 | - name: Checkout 41 | uses: actions/checkout@v2 42 | - name: Test 43 | run: cargo test 44 | # deploy on pushes to master branch 45 | # assumes aws credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) 46 | # are configured in travis settings 47 | # see https://serverless.com/framework/docs/providers/aws/guide/credentials/ 48 | # for more information 49 | deploy: 50 | if: github.ref == 'refs/heads/master' 51 | runs-on: ubuntu-latest 52 | needs: [test] 53 | steps: 54 | - name: Set up Rust 55 | uses: hecrj/setup-rust-action@v1 56 | - name: Checkout 57 | uses: actions/checkout@v2 58 | - name: Deploy 59 | if: env.AWS_ACCESS_KEY_ID && env.AWS_SECRET_ACCESS_KEY 60 | env: 61 | AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} 62 | AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} 63 | AWS_DEFAULT_REGION: us-east-1 64 | #STAGE: prod 65 | run: | 66 | npm install 67 | npx serverless deploy --conceal -------------------------------------------------------------------------------- /Ch04/websocket/examples/5_sec_ping_timer.rs: -------------------------------------------------------------------------------- 1 | extern crate ws; 2 | 3 | use std::{thread, time}; 4 | use ws::util::{Timeout, Token}; 5 | use ws::{ 6 | CloseCode, Error, ErrorKind, Handler, Handshake, 7 | Result, Sender, WebSocket, 8 | }; 9 | 10 | const PING: Token = Token(0); 11 | 12 | struct Server { 13 | out: Sender, 14 | ping_timeout: Option, 15 | } 16 | 17 | impl Handler for Server { 18 | fn on_open(&mut self, _: Handshake) -> Result<()> { 19 | self.out.timeout(5_000, PING) 20 | } 21 | 22 | fn on_timeout(&mut self, event: Token) -> Result<()> { 23 | match event { 24 | PING => { 25 | println!("Pinging the client"); 26 | self.out.ping("".into())?; 27 | self.out.timeout(5_000, PING) 28 | } 29 | _ => Err(Error::new( 30 | ErrorKind::Internal, 31 | "Invalid timeout token encountered!", 32 | )), 33 | } 34 | } 35 | 36 | fn on_new_timeout( 37 | &mut self, 38 | event: Token, 39 | timeout: Timeout, 40 | ) -> Result<()> { 41 | match event { 42 | PING => { 43 | if let Some(timeout) = 44 | self.ping_timeout.take() { 45 | self.out.cancel(timeout)? 46 | } 47 | self.ping_timeout = Some(timeout); 48 | } 49 | _ => { 50 | eprintln!("Unknown event: {:?}", event); 51 | } 52 | } 53 | Ok(()) 54 | } 55 | 56 | fn on_close(&mut self, code: CloseCode, reason: &str) { 57 | println!( 58 | "WebSocket closing for ({:?}) {}", 59 | code, reason 60 | ); 61 | 62 | if let Some(timeout) = self.ping_timeout.take() { 63 | self.out.cancel(timeout).unwrap() 64 | } 65 | } 66 | } 67 | 68 | fn main() { 69 | let server = WebSocket::new(|out| Server { 70 | out: out, 71 | ping_timeout: None, 72 | }) 73 | .unwrap(); 74 | 75 | let broadcaster = server.broadcaster(); 76 | 77 | let periodic = thread::spawn(move || loop { 78 | broadcaster.send("Meow").unwrap(); 79 | thread::sleep(time::Duration::from_secs(1)); 80 | }); 81 | server.listen("127.0.0.1:8080").unwrap(); 82 | periodic.join().unwrap(); 83 | } 84 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

wasm-pack-template

4 | 5 | A template for kick starting a Rust and WebAssembly project using wasm-pack. 6 | 7 |

8 | Build Status 9 |

10 | 11 |

12 | Tutorial 13 | | 14 | Chat 15 |

16 | 17 | Built with 🦀🕸 by The Rust and WebAssembly Working Group 18 |
19 | 20 | ## About 21 | 22 | [**📚 Read this template tutorial! 📚**][template-docs] 23 | 24 | This template is designed for compiling Rust libraries into WebAssembly and 25 | publishing the resulting package to NPM. 26 | 27 | Be sure to check out [other `wasm-pack` tutorials online][tutorials] for other 28 | templates and usages of `wasm-pack`. 29 | 30 | [tutorials]: https://rustwasm.github.io/docs/wasm-pack/tutorials/index.html 31 | [template-docs]: https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html 32 | 33 | ## 🚴 Usage 34 | 35 | ### 🐑 Use `cargo generate` to Clone this Template 36 | 37 | [Learn more about `cargo generate` here.](https://github.com/ashleygwilliams/cargo-generate) 38 | 39 | ``` 40 | cargo generate --git https://github.com/rustwasm/wasm-pack-template.git --name my-project 41 | cd my-project 42 | ``` 43 | 44 | ### 🛠️ Build with `wasm-pack build` 45 | 46 | ``` 47 | wasm-pack build 48 | ``` 49 | 50 | ### 🔬 Test in Headless Browsers with `wasm-pack test` 51 | 52 | ``` 53 | wasm-pack test --headless --firefox 54 | ``` 55 | 56 | ### 🎁 Publish to NPM with `wasm-pack publish` 57 | 58 | ``` 59 | wasm-pack publish 60 | ``` 61 | 62 | ## 🔋 Batteries Included 63 | 64 | * [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) for communicating 65 | between WebAssembly and JavaScript. 66 | * [`console_error_panic_hook`](https://github.com/rustwasm/console_error_panic_hook) 67 | for logging panic messages to the developer console. 68 | * [`wee_alloc`](https://github.com/rustwasm/wee_alloc), an allocator optimized 69 | for small code size. 70 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/client/index.js: -------------------------------------------------------------------------------- 1 | import * as wasmImage from "wasm-image-processing" 2 | 3 | function setup(event) { 4 | const fileInput = document.getElementById('image-upload') 5 | fileInput.addEventListener('change', function(event) { 6 | 7 | const file = event.target.files[0] 8 | const imageUrl = window.URL.createObjectURL(file) 9 | 10 | const image = new Image() 11 | image.src = imageUrl 12 | 13 | image.addEventListener('load', (loadEvent) => { 14 | const canvas = document.getElementById('preview') 15 | canvas.width = image.naturalWidth 16 | canvas.height = image.naturalHeight 17 | canvas.getContext('2d').drawImage(image, 0, 0) 18 | }) 19 | }) 20 | 21 | const shrinkButton = document.getElementById('shrink') 22 | shrinkButton.addEventListener('click', function(event) { 23 | const canvas = document.getElementById('preview') 24 | const canvasContext = canvas.getContext('2d') 25 | const imageBuffer = canvasContext.getImageData(0, 0, canvas.width, canvas.height).data 26 | const outputBuffer = wasmImage.shrink_by_half(imageBuffer, canvas.width, canvas.height) 27 | const u8OutputBuffer = new ImageData(new Uint8ClampedArray(outputBuffer), canvas.width / 2) 28 | 29 | canvasContext.clearRect(0, 0, canvas.width, canvas.height); 30 | canvas.width = canvas.width / 2 31 | canvas.height = canvas.height / 2 32 | canvasContext.putImageData(u8OutputBuffer, 0, 0) 33 | }) 34 | 35 | const rotate90Button = document.getElementById('rotate90') 36 | rotate90Button.addEventListener('click', function(event) { 37 | const canvas = document.getElementById('preview') 38 | const canvasContext = canvas.getContext('2d') 39 | const imageBuffer = canvasContext.getImageData(0, 0, canvas.width, canvas.height).data 40 | const outputBuffer = wasmImage.rotate90(imageBuffer, canvas.width, canvas.height) 41 | const u8OutputBuffer = new ImageData(new Uint8ClampedArray(outputBuffer), canvas.height) 42 | 43 | canvasContext.clearRect(0, 0, canvas.width, canvas.height); 44 | const height = canvas.width 45 | const width = canvas.height 46 | canvas.width = width 47 | canvas.height = height 48 | canvasContext.putImageData(u8OutputBuffer, 0, 0) 49 | }) 50 | } 51 | 52 | if (document.readState !== 'loading') { 53 | setup() 54 | } else { 55 | window.addEventListener('DOMContentLoaded', setup); 56 | } 57 | 58 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

wasm-pack-template

4 | 5 | A template for kick starting a Rust and WebAssembly project using wasm-pack. 6 | 7 |

8 | Build Status 9 |

10 | 11 |

12 | Tutorial 13 | | 14 | Chat 15 |

16 | 17 | Built with 🦀🕸 by The Rust and WebAssembly Working Group 18 |
19 | 20 | ## About 21 | 22 | [**📚 Read this template tutorial! 📚**][template-docs] 23 | 24 | This template is designed for compiling Rust libraries into WebAssembly and 25 | publishing the resulting package to NPM. 26 | 27 | Be sure to check out [other `wasm-pack` tutorials online][tutorials] for other 28 | templates and usages of `wasm-pack`. 29 | 30 | [tutorials]: https://rustwasm.github.io/docs/wasm-pack/tutorials/index.html 31 | [template-docs]: https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html 32 | 33 | ## 🚴 Usage 34 | 35 | ### 🐑 Use `cargo generate` to Clone this Template 36 | 37 | [Learn more about `cargo generate` here.](https://github.com/ashleygwilliams/cargo-generate) 38 | 39 | ``` 40 | cargo generate --git https://github.com/rustwasm/wasm-pack-template.git --name my-project 41 | cd my-project 42 | ``` 43 | 44 | ### 🛠️ Build with `wasm-pack build` 45 | 46 | ``` 47 | wasm-pack build 48 | ``` 49 | 50 | ### 🔬 Test in Headless Browsers with `wasm-pack test` 51 | 52 | ``` 53 | wasm-pack test --headless --firefox 54 | ``` 55 | 56 | ### 🎁 Publish to NPM with `wasm-pack publish` 57 | 58 | ``` 59 | wasm-pack publish 60 | ``` 61 | 62 | ## 🔋 Batteries Included 63 | 64 | * [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) for communicating 65 | between WebAssembly and JavaScript. 66 | * [`console_error_panic_hook`](https://github.com/rustwasm/console_error_panic_hook) 67 | for logging panic messages to the developer console. 68 | * [`wee_alloc`](https://github.com/rustwasm/wee_alloc), an allocator optimized 69 | for small code size. 70 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/client/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

create-wasm-app

4 | 5 | An npm init template for kick starting a project that uses NPM packages containing Rust-generated WebAssembly and bundles them with Webpack. 6 | 7 |

8 | Build Status 9 |

10 | 11 |

12 | Usage 13 | | 14 | Chat 15 |

16 | 17 | Built with 🦀🕸 by The Rust and WebAssembly Working Group 18 |
19 | 20 | ## About 21 | 22 | This template is designed for depending on NPM packages that contain 23 | Rust-generated WebAssembly and using them to create a Website. 24 | 25 | * Want to create an NPM package with Rust and WebAssembly? [Check out 26 | `wasm-pack-template`.](https://github.com/rustwasm/wasm-pack-template) 27 | * Want to make a monorepo-style Website without publishing to NPM? Check out 28 | [`rust-webpack-template`](https://github.com/rustwasm/rust-webpack-template) 29 | and/or 30 | [`rust-parcel-template`](https://github.com/rustwasm/rust-parcel-template). 31 | 32 | ## 🚴 Usage 33 | 34 | ``` 35 | npm init wasm-app 36 | ``` 37 | 38 | ## 🔋 Batteries Included 39 | 40 | - `.gitignore`: ignores `node_modules` 41 | - `LICENSE-APACHE` and `LICENSE-MIT`: most Rust projects are licensed this way, so these are included for you 42 | - `README.md`: the file you are reading now! 43 | - `index.html`: a bare bones html document that includes the webpack bundle 44 | - `index.js`: example js file with a comment showing how to import and use a wasm pkg 45 | - `package.json` and `package-lock.json`: 46 | - pulls in devDependencies for using webpack: 47 | - [`webpack`](https://www.npmjs.com/package/webpack) 48 | - [`webpack-cli`](https://www.npmjs.com/package/webpack-cli) 49 | - [`webpack-dev-server`](https://www.npmjs.com/package/webpack-dev-server) 50 | - defines a `start` script to run `webpack-dev-server` 51 | - `webpack.config.js`: configuration file for bundling your js with webpack 52 | 53 | ## License 54 | 55 | Licensed under either of 56 | 57 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 58 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 59 | 60 | at your option. 61 | 62 | ### Contribution 63 | 64 | Unless you explicitly state otherwise, any contribution intentionally 65 | submitted for inclusion in the work by you, as defined in the Apache-2.0 66 | license, shall be dual licensed as above, without any additional terms or 67 | conditions. 68 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/client/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

create-wasm-app

4 | 5 | An npm init template for kick starting a project that uses NPM packages containing Rust-generated WebAssembly and bundles them with Webpack. 6 | 7 |

8 | Build Status 9 |

10 | 11 |

12 | Usage 13 | | 14 | Chat 15 |

16 | 17 | Built with 🦀🕸 by The Rust and WebAssembly Working Group 18 |
19 | 20 | ## About 21 | 22 | This template is designed for depending on NPM packages that contain 23 | Rust-generated WebAssembly and using them to create a Website. 24 | 25 | * Want to create an NPM package with Rust and WebAssembly? [Check out 26 | `wasm-pack-template`.](https://github.com/rustwasm/wasm-pack-template) 27 | * Want to make a monorepo-style Website without publishing to NPM? Check out 28 | [`rust-webpack-template`](https://github.com/rustwasm/rust-webpack-template) 29 | and/or 30 | [`rust-parcel-template`](https://github.com/rustwasm/rust-parcel-template). 31 | 32 | ## 🚴 Usage 33 | 34 | ``` 35 | npm init wasm-app 36 | ``` 37 | 38 | ## 🔋 Batteries Included 39 | 40 | - `.gitignore`: ignores `node_modules` 41 | - `LICENSE-APACHE` and `LICENSE-MIT`: most Rust projects are licensed this way, so these are included for you 42 | - `README.md`: the file you are reading now! 43 | - `index.html`: a bare bones html document that includes the webpack bundle 44 | - `index.js`: example js file with a comment showing how to import and use a wasm pkg 45 | - `package.json` and `package-lock.json`: 46 | - pulls in devDependencies for using webpack: 47 | - [`webpack`](https://www.npmjs.com/package/webpack) 48 | - [`webpack-cli`](https://www.npmjs.com/package/webpack-cli) 49 | - [`webpack-dev-server`](https://www.npmjs.com/package/webpack-dev-server) 50 | - defines a `start` script to run `webpack-dev-server` 51 | - `webpack.config.js`: configuration file for bundling your js with webpack 52 | 53 | ## License 54 | 55 | Licensed under either of 56 | 57 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 58 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 59 | 60 | at your option. 61 | 62 | ### Contribution 63 | 64 | Unless you explicitly state otherwise, any contribution intentionally 65 | submitted for inclusion in the work by you, as defined in the Apache-2.0 66 | license, shall be dual licensed as above, without any additional terms or 67 | conditions. 68 | -------------------------------------------------------------------------------- /Ch05/serverless-catdex/cat_post/src/main.rs: -------------------------------------------------------------------------------- 1 | use lambda_http::{handler, lambda, IntoResponse, Request, RequestExt, Context}; 2 | use lambda_http::http::{StatusCode, Response, HeaderValue}; 3 | use serde::Deserialize; 4 | use serde_json::json; 5 | use std::collections::HashMap; 6 | use rusoto_core::{Region}; 7 | use rusoto_dynamodb::{AttributeValue, DynamoDb, DynamoDbClient, PutItemInput}; 8 | use rusoto_s3::{PutObjectRequest}; 9 | use rusoto_s3::util::PreSignedRequest; 10 | use rusoto_credential::{ChainProvider, ProvideAwsCredentials}; 11 | 12 | type Error = Box; 13 | 14 | #[derive(Deserialize)] 15 | struct RequestBody { 16 | name: String, 17 | } 18 | 19 | #[tokio::main] 20 | async fn main() -> Result<(), Error> { 21 | lambda::run(handler(cat_post)).await?; 22 | Ok(()) 23 | } 24 | 25 | async fn cat_post(request: Request, _: Context) -> Result { 26 | 27 | let body: RequestBody = match request.payload() { 28 | Ok(Some(body)) => body, 29 | _ => {return Ok( 30 | Response::builder() 31 | .status(StatusCode::BAD_REQUEST) 32 | .body("Invalid payload".into()) 33 | .expect("Failed to render response") 34 | ) 35 | } 36 | }; 37 | 38 | let client = DynamoDbClient::new(Region::EuCentral1); 39 | 40 | let mut new_cat = HashMap::new(); 41 | new_cat.insert("name".to_string(), AttributeValue { s: Some(body.name.clone()), ..Default::default() }); 42 | let image_path = format!("image/{}.jpg", &body.name); 43 | new_cat.insert("image_path".to_string(), AttributeValue { s: Some(image_path.clone()), ..Default::default() }); 44 | 45 | let put_item_input = PutItemInput { 46 | table_name: "shing_catdex".to_string(), 47 | item: new_cat, 48 | ..Default::default() 49 | }; 50 | 51 | match client.put_item(put_item_input).await { 52 | Ok(_)=> (), 53 | _ => { 54 | return Ok(Response::builder() 55 | .status(StatusCode::INTERNAL_SERVER_ERROR) 56 | .body("Something went wrong when writing to the database".into()) 57 | .expect("Failed to render response")) 58 | } 59 | } 60 | 61 | let credentials = ChainProvider::new().credentials().await.unwrap(); 62 | 63 | let put_request = PutObjectRequest { 64 | bucket: "shing-catdex-frontend".to_string(), 65 | key: image_path, 66 | content_type: Some("image/jpeg".to_string()), 67 | ..Default::default() 68 | }; 69 | 70 | let presigned_url = put_request.get_presigned_url(&Region::EuCentral1, &credentials, &Default::default()); 71 | 72 | let mut response = json!({"upload_url": presigned_url}).into_response(); 73 | response.headers_mut().insert("Access-Control-Allow-Origin", HeaderValue::from_static("*")); 74 | 75 | Ok(response) 76 | } 77 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | sudo: false 3 | 4 | cache: cargo 5 | 6 | matrix: 7 | include: 8 | 9 | # Builds with wasm-pack. 10 | - rust: beta 11 | env: RUST_BACKTRACE=1 12 | addons: 13 | firefox: latest 14 | chrome: stable 15 | before_script: 16 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 17 | - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) 18 | - cargo install-update -a 19 | - curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s -- -f 20 | script: 21 | - cargo generate --git . --name testing 22 | # Having a broken Cargo.toml (in that it has curlies in fields) anywhere 23 | # in any of our parent dirs is problematic. 24 | - mv Cargo.toml Cargo.toml.tmpl 25 | - cd testing 26 | - wasm-pack build 27 | - wasm-pack test --chrome --firefox --headless 28 | 29 | # Builds on nightly. 30 | - rust: nightly 31 | env: RUST_BACKTRACE=1 32 | before_script: 33 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 34 | - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) 35 | - cargo install-update -a 36 | - rustup target add wasm32-unknown-unknown 37 | script: 38 | - cargo generate --git . --name testing 39 | - mv Cargo.toml Cargo.toml.tmpl 40 | - cd testing 41 | - cargo check 42 | - cargo check --target wasm32-unknown-unknown 43 | - cargo check --no-default-features 44 | - cargo check --target wasm32-unknown-unknown --no-default-features 45 | - cargo check --no-default-features --features console_error_panic_hook 46 | - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook 47 | - cargo check --no-default-features --features "console_error_panic_hook wee_alloc" 48 | - cargo check --target wasm32-unknown-unknown --no-default-features --features "console_error_panic_hook wee_alloc" 49 | 50 | # Builds on beta. 51 | - rust: beta 52 | env: RUST_BACKTRACE=1 53 | before_script: 54 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 55 | - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) 56 | - cargo install-update -a 57 | - rustup target add wasm32-unknown-unknown 58 | script: 59 | - cargo generate --git . --name testing 60 | - mv Cargo.toml Cargo.toml.tmpl 61 | - cd testing 62 | - cargo check 63 | - cargo check --target wasm32-unknown-unknown 64 | - cargo check --no-default-features 65 | - cargo check --target wasm32-unknown-unknown --no-default-features 66 | - cargo check --no-default-features --features console_error_panic_hook 67 | - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook 68 | # Note: no enabling the `wee_alloc` feature here because it requires 69 | # nightly for now. 70 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | sudo: false 3 | 4 | cache: cargo 5 | 6 | matrix: 7 | include: 8 | 9 | # Builds with wasm-pack. 10 | - rust: beta 11 | env: RUST_BACKTRACE=1 12 | addons: 13 | firefox: latest 14 | chrome: stable 15 | before_script: 16 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 17 | - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) 18 | - cargo install-update -a 19 | - curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s -- -f 20 | script: 21 | - cargo generate --git . --name testing 22 | # Having a broken Cargo.toml (in that it has curlies in fields) anywhere 23 | # in any of our parent dirs is problematic. 24 | - mv Cargo.toml Cargo.toml.tmpl 25 | - cd testing 26 | - wasm-pack build 27 | - wasm-pack test --chrome --firefox --headless 28 | 29 | # Builds on nightly. 30 | - rust: nightly 31 | env: RUST_BACKTRACE=1 32 | before_script: 33 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 34 | - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) 35 | - cargo install-update -a 36 | - rustup target add wasm32-unknown-unknown 37 | script: 38 | - cargo generate --git . --name testing 39 | - mv Cargo.toml Cargo.toml.tmpl 40 | - cd testing 41 | - cargo check 42 | - cargo check --target wasm32-unknown-unknown 43 | - cargo check --no-default-features 44 | - cargo check --target wasm32-unknown-unknown --no-default-features 45 | - cargo check --no-default-features --features console_error_panic_hook 46 | - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook 47 | - cargo check --no-default-features --features "console_error_panic_hook wee_alloc" 48 | - cargo check --target wasm32-unknown-unknown --no-default-features --features "console_error_panic_hook wee_alloc" 49 | 50 | # Builds on beta. 51 | - rust: beta 52 | env: RUST_BACKTRACE=1 53 | before_script: 54 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 55 | - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) 56 | - cargo install-update -a 57 | - rustup target add wasm32-unknown-unknown 58 | script: 59 | - cargo generate --git . --name testing 60 | - mv Cargo.toml Cargo.toml.tmpl 61 | - cd testing 62 | - cargo check 63 | - cargo check --target wasm32-unknown-unknown 64 | - cargo check --no-default-features 65 | - cargo check --target wasm32-unknown-unknown --no-default-features 66 | - cargo check --no-default-features --features console_error_panic_hook 67 | - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook 68 | # Note: no enabling the `wee_alloc` feature here because it requires 69 | # nightly for now. 70 | -------------------------------------------------------------------------------- /Ch02/catdex/3: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate diesel; 3 | #[macro_use] 4 | extern crate serde_json; 5 | 6 | use actix_files::Files; 7 | use actix_web::{web, App, HttpResponse, HttpServer}; 8 | use std::env; 9 | use diesel::prelude::*; 10 | use diesel::pg::PgConnection; 11 | use diesel::r2d2::{self, ConnectionManager}; 12 | use serde::{Serialize}; 13 | 14 | use self::models::*; 15 | 16 | use handlebars::Handlebars; 17 | 18 | mod models; 19 | mod schema; 20 | 21 | // PgConnection comes from diesel::prelude 22 | //type DbPool = r2d2::Pool>; 23 | 24 | #[derive(Serialize)] 25 | struct IndexTemplateData { 26 | project_name: String, 27 | cats: Vec 28 | } 29 | 30 | struct SharedData { 31 | hb: Handlebars<'static>, // ? 32 | pool: r2d2::Pool> 33 | 34 | } 35 | 36 | async fn index(resources: web::Data) -> HttpResponse { 37 | use self::schema::cats::dsl::*; // TODO: imports alias 38 | let connection = pool.get().expect("Can't get db connection from pool"); 39 | 40 | 41 | let cats_data = web::block(move || cats.limit(3).load::(&connection)) 42 | .await 43 | .map_err(|e| { 44 | HttpResponse::InternalServerError().finish() 45 | }); 46 | 47 | /* 48 | let database_url = env::var("DATABASE_URL") 49 | .expect("DATABASE_URL must be set"); 50 | let connection = PgConnection::establish(&database_url) 51 | .expect(&format!("Error connecting to {}", database_url)); 52 | 53 | 54 | 55 | let cats_data = cats.limit(3).load::(&connection).expect("Error loading Cats"); 56 | */ 57 | /* 58 | let data = json!({ 59 | "project_name": "Catdex", 60 | "cats": [ 61 | { 62 | "name": "British short hair", 63 | "image_path": "/static/image/british-short-hair.jpg" 64 | }, 65 | { 66 | "name": "Persian", 67 | "image_path": "/static/image/persian.jpg" 68 | }, 69 | { 70 | "name": "Ragdoll", 71 | "image_path": "/static/image/ragdoll.jpg" 72 | } 73 | ] 74 | }); 75 | */ 76 | let data = IndexTemplateData { 77 | project_name: "Catdex".to_string(), 78 | cats: cats_data, 79 | }; 80 | let body = resources.hb.render("index", &data).unwrap(); 81 | 82 | HttpResponse::Ok().body(body) 83 | } 84 | 85 | #[actix_rt::main] 86 | async fn main() -> std::io::Result<()> { 87 | let mut handlebars = Handlebars::new(); 88 | handlebars 89 | .register_templates_directory(".html", "./static/") 90 | .unwrap(); 91 | 92 | let database_url = env::var("DATABASE_URL") 93 | .expect("DATABASE_URL must be set"); 94 | let manager = ConnectionManager::::new(&database_url); 95 | let pool = r2d2::Pool::builder() 96 | .build(manager) 97 | .expect("Failed to create DB connection pool."); 98 | 99 | let resources = web::Data::new(SharedData { 100 | hb: handlebars, 101 | pool: pool.clone(), 102 | }); 103 | 104 | println!("Listening on port 8080"); 105 | HttpServer::new(move || { 106 | App::new() 107 | .app_data(resources.clone()) 108 | .service( 109 | Files::new("/static", "static") 110 | .show_files_listing(), 111 | ) 112 | .route("/", web::get().to(index)) 113 | }) 114 | .bind("127.0.0.1:8080")? 115 | .run() 116 | .await 117 | } 118 | -------------------------------------------------------------------------------- /Ch04/websocket/examples/unresponsive_timer.rs: -------------------------------------------------------------------------------- 1 | extern crate ws; 2 | 3 | use std::{thread, time}; 4 | use ws::util::{Timeout, Token}; 5 | use ws::{ 6 | CloseCode, Error, ErrorKind, Frame, Handler, Handshake, 7 | OpCode, Result, Sender, WebSocket, 8 | }; 9 | 10 | const PING: Token = Token(0); 11 | const CLIENT_UNRESPONSIVE: Token = Token(1); 12 | 13 | struct Server { 14 | out: Sender, 15 | ping_timeout: Option, 16 | client_unresponsive_timeout: Option, 17 | } 18 | impl Handler for Server { 19 | fn on_open(&mut self, _: Handshake) -> Result<()> { 20 | println!("Opened a connetion"); 21 | self.out.timeout(15_000, CLIENT_UNRESPONSIVE)?; 22 | self.out.timeout(5_000, PING) 23 | } 24 | 25 | fn on_timeout(&mut self, event: Token) -> Result<()> { 26 | println!("event: {:?}", event); 27 | match event { 28 | PING => { 29 | println!("Pinging the client"); 30 | self.out.ping("".into())?; 31 | match self.client_unresponsive_timeout { 32 | Some(_) => self.out.timeout(5_000, PING), 33 | None => Ok(()), // skip 34 | } 35 | } 36 | CLIENT_UNRESPONSIVE => { 37 | println!("Client is unresponsive, closing the connection"); 38 | 39 | // Otherwise, stop the timer and wait until it get dropped 40 | // TODO: Implement the disconnect 41 | self.client_unresponsive_timeout.take(); 42 | if let Some(timeout) = self.ping_timeout.take() { 43 | println!("timeout: {:?}", timeout); 44 | self.out.cancel(timeout)?; 45 | println!("canceled"); 46 | } 47 | 48 | // If the clinet still respond to a close frame, try to disconnect nicely 49 | self.out.close(CloseCode::Away) 50 | } 51 | _ => Err(Error::new( 52 | ErrorKind::Internal, 53 | "Invalid timeout token encountered!", 54 | )), 55 | } 56 | } 57 | 58 | fn on_new_timeout( 59 | &mut self, 60 | event: Token, 61 | timeout: Timeout, 62 | ) -> Result<()> { 63 | println!("new timeout: {:?}", timeout); 64 | match event { 65 | PING => { 66 | if let Some(timeout) = self.ping_timeout.take() { 67 | self.out.cancel(timeout)? 68 | } 69 | match self.client_unresponsive_timeout { 70 | Some(_) => self.ping_timeout = Some(timeout), 71 | None => self.ping_timeout = None, 72 | } 73 | } 74 | CLIENT_UNRESPONSIVE => { 75 | if let Some(timeout) = 76 | self.client_unresponsive_timeout.take() 77 | { 78 | self.out.cancel(timeout)? 79 | } 80 | self.client_unresponsive_timeout = Some(timeout) 81 | } 82 | _ => { 83 | eprintln!("Unknown event: {:?}", event); 84 | } 85 | } 86 | Ok(()) 87 | } 88 | 89 | fn on_frame( 90 | &mut self, 91 | frame: Frame, 92 | ) -> Result> { 93 | if frame.opcode() == OpCode::Pong { 94 | println!("Received a pong"); 95 | // Reset the CLIENT_UNRESPONSIVE timeout 96 | self.out.timeout(15_000, CLIENT_UNRESPONSIVE)?; 97 | } 98 | 99 | Ok(Some(frame)) 100 | } 101 | 102 | fn on_close(&mut self, code: CloseCode, reason: &str) { 103 | println!( 104 | "WebSocket closing for ({:?}) {}", 105 | code, reason 106 | ); 107 | 108 | if let Some(timeout) = self.ping_timeout.take() { 109 | self.out.cancel(timeout).unwrap() 110 | } 111 | } 112 | } 113 | 114 | fn main() { 115 | let server = WebSocket::new(|out| Server { 116 | out: out, 117 | ping_timeout: None, 118 | client_unresponsive_timeout: None, 119 | }) 120 | .unwrap(); 121 | let broadcaster = server.broadcaster(); 122 | 123 | let periodic = thread::spawn(move || loop { 124 | broadcaster.send("Meow").unwrap(); 125 | thread::sleep(time::Duration::from_secs(1)); 126 | }); 127 | server.listen("127.0.0.1:8080").unwrap(); 128 | periodic.join().unwrap(); 129 | } 130 | -------------------------------------------------------------------------------- /Ch02/catdex/src/main.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate diesel; 3 | 4 | use actix_files::Files; 5 | use actix_web::{http, web, App, Error, HttpResponse, HttpServer}; 6 | use awmp::Parts; 7 | use std::collections::HashMap; 8 | use std::env; 9 | use diesel::prelude::*; 10 | use diesel::pg::PgConnection; 11 | use diesel::r2d2::{self, ConnectionManager}; 12 | use serde::{Serialize}; 13 | 14 | use self::models::*; 15 | 16 | use handlebars::Handlebars; 17 | 18 | mod models; 19 | mod schema; 20 | use self::schema::cats::dsl::*; 21 | 22 | // PgConnection comes from diesel::prelude 23 | type DbPool = r2d2::Pool>; 24 | 25 | #[derive(Serialize)] 26 | struct IndexTemplateData { 27 | project_name: String, 28 | cats: Vec 29 | } 30 | 31 | async fn index(hb: web::Data>, pool: web::Data ) -> Result { 32 | let connection = pool.get().expect("Can't get db connection from pool"); 33 | 34 | let cats_data = web::block(move || cats.limit(100).load::(&connection)) 35 | .await 36 | .map_err(|_| { 37 | HttpResponse::InternalServerError().finish() 38 | })?; 39 | 40 | let data = IndexTemplateData { 41 | project_name: "Catdex".to_string(), 42 | cats: cats_data, 43 | }; 44 | let body = hb.render("index", &data).unwrap(); 45 | 46 | Ok(HttpResponse::Ok().body(body)) 47 | } 48 | 49 | async fn add(hb: web::Data>) -> Result { 50 | 51 | let body = hb.render("add", &{}).unwrap(); 52 | 53 | Ok(HttpResponse::Ok().body(body)) 54 | } 55 | 56 | async fn add_cat_form(pool: web::Data, mut parts: Parts) -> Result { 57 | 58 | let file_path = 59 | parts.files 60 | .take("image") 61 | .pop() 62 | .and_then(|f| f.persist_in("./static/image").ok()) 63 | .unwrap_or_default(); 64 | 65 | let text_fields: HashMap<_, _> = parts.texts.as_pairs().into_iter().collect(); 66 | 67 | let connection = pool.get().expect("Can't get db connection from pool"); 68 | 69 | let new_cat = NewCat { 70 | name: text_fields.get("name").unwrap().to_string(), 71 | image_path: file_path.to_string_lossy().to_string() 72 | }; 73 | 74 | web::block(move || 75 | diesel::insert_into(cats) 76 | .values(&new_cat) 77 | .execute(&connection) 78 | ) 79 | .await 80 | .map_err(|_| { 81 | HttpResponse::InternalServerError().finish() 82 | })?; 83 | // https://tools.ietf.org/html/rfc7231#section-6.4.4 84 | Ok(HttpResponse::SeeOther().header(http::header::LOCATION, "/").finish()) 85 | } 86 | 87 | async fn cat(hb: web::Data>, pool: web::Data, cat_id: web::Path) -> Result { 88 | let connection = pool.get().expect("Can't get db connection from pool"); 89 | 90 | let cat_data = web::block(move || cats.filter(id.eq(cat_id.into_inner())).first::(&connection)) 91 | .await 92 | .map_err(|_| { 93 | HttpResponse::InternalServerError().finish() 94 | })?; 95 | 96 | let body = hb.render("cat", &cat_data).unwrap(); 97 | 98 | Ok(HttpResponse::Ok().body(body)) 99 | } 100 | 101 | #[actix_web::main] 102 | async fn main() -> std::io::Result<()> { 103 | let mut handlebars = Handlebars::new(); 104 | handlebars 105 | .register_templates_directory(".html", "./static/") 106 | .unwrap(); 107 | 108 | let handlebars_ref = web::Data::new(handlebars); 109 | 110 | let database_url = env::var("DATABASE_URL") 111 | .expect("DATABASE_URL must be set"); 112 | let manager = ConnectionManager::::new(&database_url); 113 | let pool = r2d2::Pool::builder() 114 | .build(manager) 115 | .expect("Failed to create DB connection pool."); 116 | 117 | println!("Listening on port 8080"); 118 | HttpServer::new(move || { 119 | App::new() 120 | .app_data(handlebars_ref.clone()) 121 | .data(pool.clone()) 122 | .service( 123 | Files::new("/static", "static") 124 | .show_files_listing(), 125 | ) 126 | .route("/", web::get().to(index)) 127 | .route("/cat/{id}", web::get().to(cat)) 128 | .route("/add", web::get().to(add)) 129 | .route("/add_cat_form", web::post().to(add_cat_form)) 130 | }) 131 | .bind("127.0.0.1:8080")? 132 | .run() 133 | .await 134 | } 135 | -------------------------------------------------------------------------------- /Ch05/serverless-catdex/serverless.yml: -------------------------------------------------------------------------------- 1 | # Welcome to Serverless! 2 | # 3 | # This file is the main config file for your service. 4 | # It's very minimal at this point and uses default values. 5 | # You can always add more config options for more control. 6 | # We've included some commented out config examples here. 7 | # Just uncomment any of them to get that config option. 8 | # 9 | # For full config options, check the docs: 10 | # docs.serverless.com 11 | # 12 | # Happy Coding! 13 | service: serverless-catdex 14 | provider: 15 | name: aws 16 | runtime: rust 17 | memorySize: 128 18 | # you can overwrite defaults here 19 | # stage: dev 20 | region: eu-central-1 21 | 22 | # you can add statements to the Lambda function's IAM Role here 23 | # iamRoleStatements: 24 | # - Effect: "Allow" 25 | # Action: 26 | # - "s3:ListBucket" 27 | # Resource: { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "ServerlessDeploymentBucket" } ] ] } 28 | # - Effect: "Allow" 29 | # Action: 30 | # - "s3:PutObject" 31 | # Resource: 32 | # Fn::Join: 33 | # - "" 34 | # - - "arn:aws:s3:::" 35 | # - "Ref" : "ServerlessDeploymentBucket" 36 | # - "/*" 37 | iamRoleStatements: 38 | - Effect: "Allow" 39 | Action: 40 | - "dynamodb:Scan" 41 | - "dynamodb:PutItem" 42 | Resource: 43 | Fn::Join: 44 | - "" 45 | - - "arn:aws:dynamodb:*:*:table/" 46 | - "Ref": "CatdexTable" 47 | - Effect: "Allow" 48 | Action: 49 | - "s3:PutObject" 50 | - "s3:PutObjectAcl" 51 | Resource: 52 | Fn::Join: 53 | - "" 54 | - - "arn:aws:s3:::" 55 | - "Ref": "FrontendBucket" 56 | - "/*" 57 | 58 | # you can define service wide environment variables here 59 | # environment: 60 | # variable1: value1 61 | 62 | package: 63 | individually: true 64 | 65 | plugins: 66 | - serverless-rust 67 | - serverless-finch 68 | 69 | functions: 70 | # The following are a few example events you can configure 71 | # NOTE: Please make sure to change your handler code to work with those events 72 | # Check the event documentation for details 73 | # events: 74 | # - http: 75 | # path: users/create 76 | # method: get 77 | # - s3: ${env:BUCKET} 78 | # - schedule: rate(10 minutes) 79 | # - sns: greeter-topic 80 | # - stream: arn:aws:dynamodb:region:XXXXXX:table/foo/stream/1970-01-01T00:00:00.000 81 | # - alexaSkill: amzn1.ask.skill.xx-xx-xx-xx 82 | # - alexaSmartHome: amzn1.ask.skill.xx-xx-xx-xx 83 | # - iot: 84 | # sql: "SELECT * FROM 'some_topic'" 85 | # - cloudwatchEvent: 86 | # event: 87 | # source: 88 | # - "aws.ec2" 89 | # detail-type: 90 | # - "EC2 Instance State-change Notification" 91 | # detail: 92 | # state: 93 | # - pending 94 | # - cloudwatchLog: '/aws/lambda/hello' 95 | # - cognitoUserPool: 96 | # pool: MyUserPool 97 | # trigger: PreSignUp 98 | 99 | # Define function environment variables here 100 | # environment: 101 | # variable2: value2 102 | 103 | cats: 104 | handler: cats 105 | events: 106 | - http: 107 | path: /cats 108 | method: get 109 | cors: true 110 | cat_post: 111 | handler: cat_post 112 | events: 113 | - http: 114 | path: /cat 115 | method: post 116 | cors: true 117 | 118 | # you can add CloudFormation resource templates here 119 | #resources: 120 | # Resources: 121 | # NewResource: 122 | # Type: AWS::S3::Bucket 123 | # Properties: 124 | # BucketName: my-new-bucket 125 | # Outputs: 126 | # NewOutput: 127 | # Description: "Description for the output" 128 | # Value: "Some output value" 129 | 130 | resources: 131 | Resources: 132 | CatdexTable: 133 | Type: AWS::DynamoDB::Table 134 | Properties: 135 | TableName: shing_catdex 136 | AttributeDefinitions: 137 | - AttributeName: name 138 | AttributeType: S 139 | KeySchema: 140 | - AttributeName: name 141 | KeyType: HASH 142 | ProvisionedThroughput: 143 | ReadCapacityUnits: 1 144 | WriteCapacityUnits: 1 145 | FrontendBucket: 146 | Type: AWS::S3::Bucket 147 | Properties: 148 | BucketName: shing-catdex-frontend 149 | AccessControl: Private 150 | 151 | 152 | custom: 153 | client: 154 | bucketName: shing-catdex-frontend 155 | -------------------------------------------------------------------------------- /Ch04/websocket/examples/broadcast.rs: -------------------------------------------------------------------------------- 1 | extern crate ws; 2 | 3 | use std::{thread, time}; 4 | use ws::util::{Timeout, Token}; 5 | use ws::{ 6 | CloseCode, Error, ErrorKind, Frame, Handler, Handshake, 7 | OpCode, Result, Sender, WebSocket, 8 | }; 9 | 10 | const PING: Token = Token(0); 11 | const CLIENT_UNRESPONSIVE: Token = Token(1); 12 | 13 | struct Server { 14 | out: Sender, 15 | ping_timeout: Option, 16 | client_unresponsive_timeout: Option, 17 | } 18 | impl Handler for Server { 19 | fn on_open(&mut self, _: Handshake) -> Result<()> { 20 | println!("Opened a connetion"); 21 | self.out.timeout(15_000, CLIENT_UNRESPONSIVE)?; 22 | self.out.timeout(5_000, PING) 23 | } 24 | 25 | fn on_timeout(&mut self, event: Token) -> Result<()> { 26 | println!("event: {:?}", event); 27 | match event { 28 | PING => { 29 | println!("Pinging the client"); 30 | self.out.ping("".into())?; 31 | println!( 32 | "{:?}", 33 | self.client_unresponsive_timeout 34 | ); 35 | match self.client_unresponsive_timeout { 36 | Some(_) => self.out.timeout(5_000, PING), 37 | None => Ok(()), // skip 38 | } 39 | } 40 | CLIENT_UNRESPONSIVE => { 41 | println!("Client is unresponsive, closing the connection"); 42 | 43 | // Otherwise, stop the timer and wait until it get dropped 44 | // TODO: Implement the disconnect 45 | self.client_unresponsive_timeout.take(); 46 | if let Some(timeout) = self.ping_timeout.take() { 47 | println!("timeout: {:?}", timeout); 48 | self.out.cancel(timeout)?; 49 | println!("canceled"); 50 | } 51 | 52 | // If the clinet still respond to a close frame, try to disconnect nicely 53 | self.out.close(CloseCode::Away) 54 | } 55 | _ => Err(Error::new( 56 | ErrorKind::Internal, 57 | "Invalid timeout token encountered!", 58 | )), 59 | } 60 | } 61 | 62 | fn on_new_timeout( 63 | &mut self, 64 | event: Token, 65 | timeout: Timeout, 66 | ) -> Result<()> { 67 | println!("new timeout: {:?}", timeout); 68 | match event { 69 | PING => { 70 | if let Some(timeout) = self.ping_timeout.take() { 71 | self.out.cancel(timeout)? 72 | } 73 | match self.client_unresponsive_timeout { 74 | Some(_) => self.ping_timeout = Some(timeout), 75 | None => self.ping_timeout = None, 76 | } 77 | } 78 | CLIENT_UNRESPONSIVE => { 79 | if let Some(timeout) = 80 | self.client_unresponsive_timeout.take() 81 | { 82 | self.out.cancel(timeout)? 83 | } 84 | self.client_unresponsive_timeout = Some(timeout) 85 | } 86 | _ => { 87 | eprintln!("Unknown event: {:?}", event); 88 | } 89 | } 90 | Ok(()) 91 | } 92 | 93 | fn on_frame( 94 | &mut self, 95 | frame: Frame, 96 | ) -> Result> { 97 | if frame.opcode() == OpCode::Pong { 98 | println!("Received a pong"); 99 | // Reset the CLIENT_UNRESPONSIVE timeout 100 | self.out.timeout(15_000, CLIENT_UNRESPONSIVE)?; 101 | } 102 | 103 | Ok(Some(frame)) 104 | 105 | // TODO: default frame validation 106 | } 107 | 108 | fn on_close(&mut self, code: CloseCode, reason: &str) { 109 | println!( 110 | "WebSocket closing for ({:?}) {}", 111 | code, reason 112 | ); 113 | 114 | if let Some(timeout) = self.ping_timeout.take() { 115 | self.out.cancel(timeout).unwrap() 116 | } 117 | } 118 | } 119 | 120 | fn main() { 121 | let server = WebSocket::new(|out| Server { 122 | out: out, 123 | ping_timeout: None, 124 | client_unresponsive_timeout: None, 125 | }) 126 | .unwrap(); 127 | let broadcaster = server.broadcaster(); 128 | 129 | let periodic = thread::spawn(move || loop { 130 | broadcaster.send("Meow").unwrap(); 131 | thread::sleep(time::Duration::from_secs(1)); 132 | }); 133 | server.listen("127.0.0.1:8080").unwrap(); 134 | periodic.join().unwrap(); 135 | } 136 | -------------------------------------------------------------------------------- /Ch05/serverless-catdex/README.md: -------------------------------------------------------------------------------- 1 | # serverless AWS Rust multi-function template 2 | 3 | A sample template for bootstraping a multi function [Rustlang AWS Lambda](https://github.com/awslabs/aws-lambda-rust-runtime/) applications with ⚡ serverless framework ⚡ using [Cargo workspaces](https://doc.rust-lang.org/1.30.0/book/second-edition/ch14-03-cargo-workspaces.html) 4 | 5 | ## ✨ features 6 | 7 | * 🦀 Build Rustlang applications with ease 8 | - 🛵 Continuous integration testing with GitHub Actions 9 | - 🚀 Continuous deployment with GitHub Actions 10 | * 🧪 Getting started unit tests 11 | 12 | ## 📦 install 13 | 14 | Install the [serverless framework](https://www.serverless.com/framework/docs/getting-started/) cli. 15 | 16 | Then then run the following in your terminal 17 | 18 | ```bash 19 | $ npx serverless install \ 20 | --url https://github.com/softprops/serverless-aws-rust-multi \ 21 | --name my-new-multi-func-app 22 | ``` 23 | 24 | This will download the source of a sample Rustlang application and unpack it as a new service named 25 | "my-new-multi-func-app" in a directory called "my-new-multi-func-app" 26 | 27 | 28 | ## 🧙 how to be a wizard 29 | 30 | Assuming you have [aws credentials with appropriate deployment permissions configured](https://serverless.com/framework/docs/providers/aws/guide/credentials/) (if you already use any existing AWS tooling installed you likely already have this configured), you could impress your friends by creating a project 31 | that is _born_ in production. 32 | 33 | ```bash 34 | $ npx serverless install \ 35 | --url https://github.com/softprops/serverless-aws-rust-multi \ 36 | --name my-new-multi-func-app \ 37 | && cd my-new-multi-func-app \ 38 | && npm ci \ 39 | && npx serverless deploy 40 | ``` 41 | 42 | `npm ci` will make sure npm dependencies are installed based directly on your package-lock.json file. This only needs run once. 43 | The first time you run `npx serverless deploy` it will pull down and compile the base set 44 | of dependencies and your application. Unless the dependencies change afterwards, 45 | this should only happen once, resulting in an out of the box rapid deployment 46 | cycle. 47 | 48 | ## 🛵 continuous integration and deployment 49 | 50 | This template includes an example [GitHub actions](https://travis-ci.org/) [configuration file](.github/workflows/main.yml) which can unlock a virtuous cycle of continuous integration and deployment 51 | ( i.e all tests are run on prs and every push to master results in a deployment ). 52 | 53 | GitHub actions is managed simply by the presence of a file checked into your repository. To set up GitHub Actions to deploy to AWS you'll need to do a few things 54 | 55 | Firstly, version control your source. [Github](https://github.com/) is free for opensource. 56 | 57 | ```bash 58 | $ git init 59 | $ git remote add origin git@github.com:{username}/{my-new-service}.git 60 | ``` 61 | 62 | Store a `AWS_ACCESS_KEY_ID` `AWS_SECRET_ACCESS_KEY` used for aws deployment in your repositories secrets https://github.com/{username}/{my-new-service}/settings/secrets 63 | 64 | Add your changes to git and push them to GitHub. 65 | 66 | Finally, open https://github.com/{username}/{my-new-service}/actions in your browser and grab a bucket of popcorn 🍿 67 | 68 | ## 🔫 function triggering 69 | 70 | With your function deployed you can now start triggering it using `serverless` framework directly or 71 | the AWS integration you've configured to trigger it on your behalf 72 | 73 | ```sh 74 | $ npx serverless invoke -f hello -d '{"foo":"bar"}' 75 | ``` 76 | 77 | ## 🔬 logs 78 | 79 | With your function deployed you can now tail it's logs right from your project 80 | 81 | ```sh 82 | $ npx serverless logs -f hello 83 | ``` 84 | 85 | ```sh 86 | $ npx serverless logs -f world 87 | ``` 88 | 89 | ## 👴 retiring 90 | 91 | Good code should be easily replaceable. Good code is should also be easily disposable. Retiring applications should be as easy as creating and deploying them them. The dual of `serverless deploy` is `serverless remove`. Use this for retiring services and cleaning up resources. 92 | 93 | ```bash 94 | $ npx serverless remove 95 | ``` 96 | 97 | ## ℹ️ additional information 98 | 99 | * See the [serverless-rust plugin's documentation](https://github.com/softprops/serverless-rust) for more information on plugin usage. 100 | 101 | * See the [aws rust runtime's documentation](https://github.com/awslabs/aws-lambda-rust-runtime) for more information on writing Rustlang lambda functions 102 | 103 | ## 👯 Contributing 104 | 105 | This template's intent is to set a minimal baseline for getting engineers up an running with a set of repeatable best practices. See something you'd like in this template that would help others? Feel free to [open a new GitHub issue](https://github.com/softprops/serverless-aws-rust-multi/issues/new). Pull requests are also welcome. -------------------------------------------------------------------------------- /Ch03/rest_api/catdex/src/main.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate diesel; 3 | use actix_files::Files; 4 | use actix_web::{web, App, error, HttpResponse, HttpServer}; 5 | use actix_web::middleware::Logger; 6 | use log::{info, warn, error}; 7 | use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; 8 | use std::env; 9 | use serde::Deserialize; 10 | use diesel::prelude::*; 11 | use diesel::pg::PgConnection; 12 | use diesel::r2d2::{self, ConnectionManager}; 13 | use validator::{Validate}; 14 | use validator_derive::{Validate}; 15 | 16 | use self::models::*; 17 | 18 | mod models; 19 | mod schema; 20 | use self::schema::cats::dsl::*; 21 | 22 | mod errors; 23 | use self::errors::UserError; 24 | 25 | type DbPool = r2d2::Pool>; 26 | 27 | async fn cats_endpoint(pool: web::Data) -> Result { 28 | let connection = pool.get() 29 | .map_err(|_| { 30 | error!("Failed to get DB connection from pool"); 31 | UserError::InternalError 32 | })?; 33 | 34 | let cats_data = web::block(move || cats.limit(100).load::(&connection)) 35 | .await 36 | .map_err(|_| { 37 | error!("Failed to get cats"); 38 | UserError::InternalError 39 | })?; 40 | return Ok(HttpResponse::Ok().json(cats_data)) 41 | } 42 | 43 | #[derive(Deserialize, Validate)] 44 | struct CatEndpointPath{ 45 | #[validate(range(min=0, max=150))] 46 | id: i32 47 | } 48 | 49 | async fn cat_endpoint(pool: web::Data, cat_id: web::Path) -> Result { 50 | cat_id.validate().map_err(|_| { 51 | warn!("Parameter validation failed"); 52 | UserError::ValidationError 53 | })?; 54 | let connection = pool.get() 55 | .map_err(|_| { 56 | error!("Failed to get DB connection from pool"); 57 | UserError::InternalError 58 | })?; 59 | 60 | let query_id = cat_id.id.clone(); 61 | let cat_data = web::block(move || cats.filter(id.eq(query_id)).first::(&connection)) 62 | .await 63 | .map_err(|e| 64 | match e { 65 | error::BlockingError::Error(diesel::result::Error::NotFound) => { 66 | 67 | error!("Cat ID: {} not found in DB", &cat_id.id); 68 | UserError::NotFoundError 69 | }, 70 | _ => { 71 | error!("Unexpected error"); 72 | UserError::InternalError 73 | }, 74 | } 75 | )?; 76 | Ok(HttpResponse::Ok().json(cat_data)) 77 | } 78 | 79 | fn setup_database() -> DbPool { 80 | let database_url = env::var("DATABASE_URL") 81 | .expect("DATABASE_URL must be set"); 82 | let manager = ConnectionManager::::new(&database_url); 83 | r2d2::Pool::builder() 84 | .build(manager) 85 | .expect("Failed to create DB connection pool.") 86 | } 87 | 88 | fn api_config(cfg: & mut web::ServiceConfig) { 89 | cfg.service( 90 | web::scope("/api") 91 | .app_data(web::PathConfig::default().error_handler(|_, _| { 92 | UserError::ValidationError.into() 93 | })) 94 | .route("/cats", web::get().to(cats_endpoint)) 95 | .route("/cat/{id}", web::get().to(cat_endpoint)) 96 | ); 97 | } 98 | 99 | #[actix_web::main] 100 | async fn main() -> std::io::Result<()> { 101 | env_logger::init(); 102 | 103 | let mut builder = 104 | SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); 105 | builder 106 | .set_private_key_file("key-no-password.pem", SslFiletype::PEM) 107 | .unwrap(); 108 | builder.set_certificate_chain_file("cert.pem").unwrap(); 109 | 110 | let pool = setup_database(); 111 | 112 | 113 | info!("Listening on port 8080"); 114 | HttpServer::new(move || { 115 | App::new() 116 | .wrap(Logger::default()) 117 | .data(pool.clone()) 118 | .configure(api_config) 119 | .service( 120 | Files::new("/", "static") 121 | .show_files_listing(), 122 | ) 123 | }) 124 | .bind_openssl("127.0.0.1:8080", builder)? 125 | .run() 126 | .await 127 | } 128 | 129 | #[cfg(test)] 130 | mod tests { 131 | use super::*; 132 | use actix_web::{test, App}; 133 | 134 | #[actix_rt::test] 135 | async fn test_cats_endpoint_get() { 136 | let pool = setup_database(); 137 | let mut app = test::init_service( 138 | App::new() 139 | .data(pool.clone()) 140 | .configure(api_config) 141 | //.route("/api/cats", web::get().to(cats_endpoint)) 142 | ).await; 143 | let req = test::TestRequest::get().uri("/api/cats").to_request(); 144 | let resp = test::call_service(&mut app, req).await; 145 | assert!(resp.status().is_success()); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/src/app.rs: -------------------------------------------------------------------------------- 1 | use yew::services::reader::{File}; 2 | use yew::{html, ChangeData, Component, ComponentLink, Html, ShouldRender}; 3 | use wasm_bindgen::prelude::*; 4 | use wasm_bindgen::{JsCast, Clamped}; 5 | use std::rc::Rc; 6 | use image::{RgbaImage}; 7 | use image::imageops; 8 | 9 | pub struct App { 10 | link: ComponentLink, 11 | } 12 | 13 | pub enum Msg { 14 | LoadFile(Vec), 15 | Shrink 16 | } 17 | 18 | impl Component for App { 19 | type Message = Msg; 20 | type Properties = (); 21 | fn create(_: Self::Properties, link: ComponentLink) -> Self { 22 | Self { 23 | link, 24 | } 25 | } 26 | 27 | fn change(&mut self, _props: Self::Properties) -> ShouldRender { 28 | false 29 | } 30 | 31 | fn update(&mut self, msg: Self::Message) -> ShouldRender { 32 | match msg { 33 | Msg::LoadFile(files) => { 34 | let file = &files[0]; 35 | let file_url = web_sys::Url::create_object_url_with_blob(&file).unwrap(); 36 | let document = web_sys::window().unwrap().document().unwrap(); 37 | let image = Rc::new(document 38 | .create_element("img").unwrap() 39 | .dyn_into::().unwrap() 40 | ); 41 | image.set_src(&file_url); 42 | 43 | 44 | let image_clone = image.clone(); 45 | 46 | let callback = Closure::wrap(Box::new(move || { 47 | let canvas = document.get_element_by_id("preview").unwrap(); 48 | let canvas: web_sys::HtmlCanvasElement = canvas 49 | .dyn_into::() 50 | .map_err(|_| ()) 51 | .unwrap(); 52 | 53 | let context = canvas 54 | .get_context("2d") 55 | .unwrap() 56 | .unwrap() 57 | .dyn_into::() 58 | .unwrap(); 59 | canvas.set_width(image_clone.natural_width()); 60 | canvas.set_height(image_clone.natural_height()); 61 | context.draw_image_with_html_image_element(&image_clone, 0.0, 0.0).unwrap(); 62 | }) as Box); 63 | // .as_ref().unchecked_ref() can extract the &Function from the &JsValue 64 | image.set_onload(Some(callback.as_ref().unchecked_ref())); 65 | // Do not drop the Closure so the JS callback won't be invalidated after the 66 | // function exits 67 | callback.forget(); 68 | } 69 | Msg::Shrink => { 70 | // DO nothing yet 71 | let document = web_sys::window().unwrap().document().unwrap(); 72 | let canvas = document.get_element_by_id("preview").unwrap(); 73 | let canvas: web_sys::HtmlCanvasElement = canvas 74 | .dyn_into::() 75 | .map_err(|_| ()) 76 | .unwrap(); 77 | 78 | let context = canvas 79 | .get_context("2d") 80 | .unwrap() 81 | .unwrap() 82 | .dyn_into::() 83 | .unwrap(); 84 | let width: u32 = canvas.width(); 85 | let height: u32 = canvas.height(); 86 | let image_buffer = context.get_image_data(0.0, 0.0, width.into(), height.into()) 87 | .unwrap() 88 | .data(); 89 | let image: RgbaImage = 90 | image::ImageBuffer::from_vec(width, height, image_buffer.to_vec()).unwrap(); 91 | let output_image = imageops::resize(&image, width / 2, height / 2, imageops::FilterType::Nearest); 92 | let output_image_data = web_sys::ImageData::new_with_u8_clamped_array(Clamped(&mut output_image.into_vec()), width / 2).unwrap(); 93 | context.clear_rect(0.0, 0.0, width.into(), height.into()); 94 | canvas.set_width(width / 2); 95 | canvas.set_height(height / 2); 96 | context.put_image_data(&output_image_data, 0.0, 0.0).unwrap(); 97 | } 98 | } 99 | true 100 | } 101 | 102 | fn view(&self) -> Html { 103 | html! { 104 |
105 | 117 |
118 | 119 |
120 | 121 |
122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/LICENSE_APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/LICENSE_APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/LICENSE_APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /Ch06/hello-wasm/client/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Ch06/wasm-image-processing/client/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Ch06/yew-image-processing/netlify/todomvc.js: -------------------------------------------------------------------------------- 1 | !function(e){function b(b){for(var c,_,n=b[0],d=b[1],f=0,t=[];f{e.run_app()})}]); --------------------------------------------------------------------------------