Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WASM support #31

Merged
merged 8 commits into from
May 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,28 @@ jobs:
after_success:
- bash <(curl -s https://codecov.io/bash)

- os: linux
name: wasm32-unknown-unknown
before_script:
- |
cargo install wasm-bindgen-cli
rustup target add wasm32-unknown-unknown
wget https://github.com/emscripten-core/emsdk/archive/master.zip
unzip master.zip
./emsdk-master/emsdk install latest
./emsdk-master/emsdk activate latest
script:
- |
source emsdk-master/emsdk_env.sh
cd matrix_sdk/examples/wasm_command_bot
cargo build --target wasm32-unknown-unknown
cd -

cd matrix_sdk_base
cargo test --target wasm32-unknown-unknown --no-default-features



before_script:
- rustup component add rustfmt

Expand Down
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ members = [
"matrix_sdk",
"matrix_sdk_base",
"matrix_sdk_test",
"matrix_sdk_test_macros",
"matrix_sdk_crypto",
"matrix_sdk_common",
]
10 changes: 3 additions & 7 deletions matrix_sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ encryption = ["matrix-sdk-base/encryption"]
sqlite-cryptostore = ["matrix-sdk-base/sqlite-cryptostore"]

[dependencies]
futures = "0.3.4"
http = "0.2.1"
reqwest = "0.10.4"
serde_json = "1.0.52"
thiserror = "1.0.16"
tracing = "0.1.13"
url = "2.1.1"
uuid = { version = "0.8.1", features = ["v4"] }
futures-timer = "3.0.2"


matrix-sdk-common = { version = "0.1.0", path = "../matrix_sdk_common" }

Expand All @@ -38,11 +38,6 @@ version = "0.2.4"
default-features = false
features = ["std", "std-future"]

[dependencies.tokio]
version = "0.2.20"
default-features = false
features = ["time"]

[dev-dependencies]
async-trait = "0.1.30"
dirs = "2.0.2"
Expand All @@ -54,3 +49,4 @@ tracing-subscriber = "0.2.5"
tempfile = "3.1.0"
mockito = "0.25.1"
lazy_static = "1.4.0"
futures = "0.3.4"
7 changes: 7 additions & 0 deletions matrix_sdk/examples/wasm_command_bot/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
node_modules
pkg
target
Cargo.lock
*.swp
dist
package-lock.json
19 changes: 19 additions & 0 deletions matrix_sdk/examples/wasm_command_bot/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[package]
name = "wasm"
version = "0.1.0"
authors = ["stoically <stoically@protonmail.com>"]
edition = "2018"

# Config mostly pulled from: https://github.com/rustwasm/wasm-bindgen/blob/master/examples/fetch/Cargo.toml

[lib]
crate-type = ["cdylib"]

[dependencies]
matrix-sdk = { path = "../..", default-features = false }
url = "2.1.1"
wasm-bindgen = { version = "0.2.62", features = ["serde-serialize"] }
wasm-bindgen-futures = "0.4.12"
web-sys = { version = "0.3.39", features = ["console"] }

[workspace]
12 changes: 12 additions & 0 deletions matrix_sdk/examples/wasm_command_bot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
## Example usage of matrix-rust-sdk from WASM

You can build the example locally with:

npm install
npm run serve

and then visiting http://localhost:8080 in a browser should run the example!

Note: Encryption isn't supported yet

This example is loosely based off of [this example](https://github.com/seanmonstar/reqwest/tree/master/examples/wasm_github_fetch), an example usage of `fetch` from `wasm-bindgen`.
7 changes: 7 additions & 0 deletions matrix_sdk/examples/wasm_command_bot/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const rust = import('./pkg');

rust
.then(m => {
return m.run()
})
.catch(console.error);
14 changes: 14 additions & 0 deletions matrix_sdk/examples/wasm_command_bot/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"scripts": {
"build": "webpack",
"serve": "webpack-dev-server"
},
"devDependencies": {
"@wasm-tool/wasm-pack-plugin": "1.0.1",
"text-encoding": "^0.7.0",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.29.4",
"webpack-cli": "^3.1.1",
"webpack-dev-server": "^3.1.0"
}
}
74 changes: 74 additions & 0 deletions matrix_sdk/examples/wasm_command_bot/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
use matrix_sdk::{
api::r0::sync::sync_events::Response as SyncResponse,
events::collections::all::RoomEvent,
events::room::message::{MessageEvent, MessageEventContent, TextMessageEventContent},
identifiers::RoomId,
Client, ClientConfig, SyncSettings,
};
use url::Url;
use wasm_bindgen::prelude::*;
use web_sys::console;

struct WasmBot(Client);

impl WasmBot {
async fn on_room_message(&self, room_id: &RoomId, event: RoomEvent) {
let msg_body = if let RoomEvent::RoomMessage(MessageEvent {
content: MessageEventContent::Text(TextMessageEventContent { body: msg_body, .. }),
..
}) = event
{
msg_body.clone()
} else {
return;
};

console::log_1(&format!("Received message event {:?}", &msg_body).into());

if msg_body.starts_with("!party") {
let content = MessageEventContent::Text(TextMessageEventContent::new_plain(
"🎉🎊🥳 let's PARTY with wasm!! 🥳🎊🎉".to_string(),
));

self.0.room_send(&room_id, content, None).await.unwrap();
}
}
async fn on_sync_response(&self, response: SyncResponse) {
console::log_1(&format!("Synced").into());

for (room_id, room) in response.rooms.join {
for event in room.timeline.events {
if let Ok(event) = event.deserialize() {
self.on_room_message(&room_id, event).await
}
}
}
}
}

#[wasm_bindgen]
pub async fn run() -> Result<JsValue, JsValue> {
let homeserver_url = "http://localhost:8008";
let username = "user";
let password = "password";

let client_config = ClientConfig::new();
let homeserver_url = Url::parse(&homeserver_url).unwrap();
let client = Client::new_with_config(homeserver_url, None, client_config).unwrap();

client
.login(username, password, None, Some("rust-sdk-wasm"))
.await
.unwrap();

let bot = WasmBot(client.clone());

client.sync(SyncSettings::default()).await.unwrap();

let settings = SyncSettings::default().token(client.sync_token().await.unwrap());
client
.sync_forever(settings, |response| bot.on_sync_response(response))
.await;

Ok(JsValue::NULL)
}
26 changes: 26 additions & 0 deletions matrix_sdk/examples/wasm_command_bot/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");

module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
},
devtool: 'source-map',
plugins: [
new HtmlWebpackPlugin(),
new WasmPackPlugin({
crateDirectory: path.resolve(__dirname, ".")
}),
// Have this example work in Edge which doesn't ship `TextEncoder` or
// `TextDecoder` at this time.
new webpack.ProvidePlugin({
TextDecoder: ['text-encoding', 'TextDecoder'],
TextEncoder: ['text-encoding', 'TextEncoder']
})
],
mode: 'development'
};
Loading