├── .cargo └── config.toml ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── LICENSE ├── README.md ├── examples ├── ethereum │ ├── Cargo.toml │ ├── README.md │ └── src │ │ └── main.rs ├── kafka │ ├── Cargo.toml │ ├── Dockerfile │ ├── README.md │ ├── docker-compose.yml │ ├── order.json │ └── src │ │ └── main.rs ├── order │ ├── Cargo.toml │ ├── Dockerfile │ ├── README.md │ ├── docker-compose.yml │ ├── order.json │ └── src │ │ └── main.rs └── order_conn │ ├── Cargo.toml │ └── src │ └── main.rs └── mega_etl ├── Cargo.toml └── src └── lib.rs /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [build] 2 | target="wasm32-wasi" 3 | 4 | [target.wasm32-wasi] 5 | runner = "wasmedge" -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | logLevel: 7 | description: 'Log level' 8 | required: true 9 | default: 'info' 10 | push: 11 | branches: [ main ] 12 | pull_request: 13 | branches: [ main ] 14 | 15 | jobs: 16 | build: 17 | 18 | runs-on: ubuntu-20.04 19 | 20 | steps: 21 | - uses: actions/checkout@v2 22 | 23 | - name: Install apt-get packages 24 | run: | 25 | sudo ACCEPT_EULA=Y apt-get update 26 | sudo ACCEPT_EULA=Y apt-get upgrade 27 | sudo apt-get install wget git curl software-properties-common build-essential 28 | 29 | - name: Install and run MySQL 30 | run: | 31 | sudo apt-get update 32 | sudo apt-get -y install mysql-server libmysqlclient-dev curl 33 | sudo service mysql start 34 | mysql -e "SET GLOBAL max_allowed_packet = 36700160;" -uroot -proot 35 | mysql -e "SET @@GLOBAL.ENFORCE_GTID_CONSISTENCY = WARN;" -uroot -proot 36 | mysql -e "SET @@GLOBAL.ENFORCE_GTID_CONSISTENCY = ON;" -uroot -proot 37 | mysql -e "SET @@GLOBAL.GTID_MODE = OFF_PERMISSIVE;" -uroot -proot 38 | mysql -e "SET @@GLOBAL.GTID_MODE = ON_PERMISSIVE;" -uroot -proot 39 | mysql -e "SET @@GLOBAL.GTID_MODE = ON;" -uroot -proot 40 | mysql -e "PURGE BINARY LOGS BEFORE now();" -uroot -proot 41 | 42 | - name: Install and run Redpanda 43 | run: | 44 | curl -1sLf 'https://dl.redpanda.com/nzc4ZYQK3WRGd9sy/redpanda/cfg/setup/bash.deb.sh' | sudo -E bash 45 | sudo apt install redpanda -y 46 | sudo systemctl start redpanda 47 | 48 | - name: Install Rust target for wasm 49 | run: | 50 | rustup target add wasm32-wasi 51 | 52 | - name: Install WasmEdge 53 | run: | 54 | VERSION=0.11.2 55 | curl -sSf https://raw.githubusercontent.com/WasmEdge/WasmEdge/master/utils/install.sh | sudo bash -s -- --version=$VERSION -p /usr/local 56 | 57 | - name: Run the webhook ETL service on MySQL 58 | run: | 59 | cd examples/order 60 | cargo clean 61 | cargo build --target wasm32-wasi --release 62 | wasmedgec target/wasm32-wasi/release/order.wasm order.wasm 63 | nohup wasmedge --env "DATABASE_URL=mysql://root:root@127.0.0.1:3306/mysql" order.wasm > wasm.log 2>&1 & 64 | echo $! > wasmedge.pid 65 | echo $'\nSleep for 15s' 66 | sleep 15 67 | echo $'\nDone!' 68 | 69 | - name: Test the webhook ETL service 70 | run: | 71 | cd examples/order 72 | echo $'\nSend an order' 73 | curl http://localhost:3344/ -X POST -d @order.json 74 | echo $'\nQuery DB' 75 | mysql -u root -proot mysql -e "select * from orders" 76 | echo $'\Delete DB' 77 | mysql -u root -proot mysql -e "drop table orders" 78 | echo $'\nDone!' 79 | kill -9 `cat wasmedge.pid` 80 | rm wasmedge.pid 81 | cat wasm.log 82 | 83 | - name: Run the Redpanda ETL service on MySQL 84 | run: | 85 | cd examples/kafka 86 | cargo clean 87 | cargo build --target wasm32-wasi --release 88 | wasmedgec target/wasm32-wasi/release/kafka.wasm kafka.wasm 89 | nohup wasmedge --env "DATABASE_URL=mysql://root:root@127.0.0.1:3306/mysql" --env "KAFKA_URL=kafka://127.0.0.1:9092/order" kafka.wasm > wasm.log 2>&1 & 90 | echo $! > wasmedge.pid 91 | echo $'\nSleep for 15s' 92 | sleep 15 93 | echo $'\nDone!' 94 | 95 | - name: Test the Redpanda ETL service 96 | run: | 97 | cd examples/kafka 98 | # echo $'\nCreate a queue topic' 99 | # rpk topic create order 100 | echo $'\nSend an order' 101 | cat order.json | rpk topic produce order 102 | sleep 5 103 | echo $'\nQuery DB' 104 | mysql -u root -proot mysql -e "select * from orders" 105 | echo $'\Delete DB' 106 | mysql -u root -proot mysql -e "drop table orders" 107 | echo $'\nDone!' 108 | kill -9 `cat wasmedge.pid` 109 | rm wasmedge.pid 110 | cat wasm.log 111 | 112 | 113 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /**/target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # A serverless ETL runtime for cloud databases 2 | 3 | MEGA stands for **Make ETLs Great Again!** [Checkout a video demo!](https://www.youtube.com/watch?v=sQCRQeTnBgo) 4 | 5 | This project is a cloud-native ETL (Extract, Transform, Load) application framework based on the [WasmEdge](https://github.com/WasmEdge) WebAssembly runtime for developers to filter, map, and transform data pipelines going into cloud databases. We are currently targetting any MySQL compatible database as the backend. 6 | 7 | ETL tools are crucial for the modern data analytics pipeline. However, ETL for cloud databases has its own challenges. Since the public cloud is fundamentally a multi-tenancy environment, all user-defined ETL functions are isolated outside of the database in separate VMs or secure containers. That is a complex and heavyweight setup, which is not suited for simple functions that need to process sporadic streams of data. 8 | 9 | With the MEGA framework, developers will be able to create secure, lightweight, fast and cross-platform ETL functions that are located close to or even embedded in cloud databases' infrastructure. The MEGA ETL functions can be deployed as serverless functions and receive data from a variety of sources including event queues, webhook callbacks and data streaming pipelines. The outcomes are written into the designated cloud database for later analysis. 10 | 11 | ## Examples 12 | 13 | * [examples/order](examples/order) is an example to take orders from an e-commerce application via a HTTP webhook, and store the orders into a database. It is the example we will go through in this document. There is also [an alternative implementation](examples/order_conn) for this example -- it uses a direct connection to the backend database for more flexibility. 14 | * [examples/kafka](examples/kafka) is an example to take those e-commerce orders from a Kafka / Redpanda queue, and store the orders into a database. 15 | * [examples/ethereum](examples/ethereum) is an example to filter, transform, and store Ethereum transactions in a relational database. 16 | 17 | ## Prerequisites 18 | 19 | The [WasmEdge](https://github.com/WasmEdge) WebAssembly Runtime is an open source project under the CNCF. It provides a safer and lighter alternative than Linux containers to run compiled (i.e., high-performance) ETL functions. They can be deployed to the edge cloud close to the data source or even colocate with the cloud database servers in the same firewall. Specially, you will need 20 | 21 | * [Install Rust](https://www.rust-lang.org/tools/install). The framework is currently written in the Rust language. A JavaScript version is in the works. 22 | * [Install WasmEdge](https://wasmedge.org/book/en/quick_start/install.html). You need it to run the ETL functions. 23 | * Install a MySQL compatible analytical database or sign up for a cloud database. We recommend [TiDB Cloud](https://tidbcloud.com/). The ETL transformed data is written into this database for later analysis. 24 | 25 | On Linux, you can use the following commands to install Rust and WasmEdge. 26 | 27 | ```bash 28 | # Install Rust 29 | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh 30 | source $HOME/.cargo/env 31 | # Install WebAssembly target for Rust 32 | rustup target add wasm32-wasi 33 | 34 | # Install WasmEdge 35 | curl -sSf https://raw.githubusercontent.com/WasmEdge/WasmEdge/master/utils/install.sh | bash -s -- -e all 36 | source $HOME/.wasmedge/env 37 | ``` 38 | 39 | ## Create the ETL function 40 | 41 | First, add the MEGA crate to your Rust project. 42 | 43 | ```toml 44 | [dependencies] 45 | mega_etl = "0.1" 46 | ``` 47 | 48 | Next, in your Rust code, you will need to implement the following. 49 | 50 | * Define a struct that models database table. Each column in the table is represented by a data field in the `struct`. 51 | * Implement a required `transform()` function to give the above struct the `Transformer` trait. The function takes a `Vec` byte array as input argument, and returns a SQL string for the database. 52 | * Set variables for the connection string to TiDB and configurations for the inbound connector where the input `Vec` would be retrieved (eg from a Kafka queue or a HTTP service or a temp database table in Redis). 53 | 54 | First, let's define the data structure for the database table. It is a table for order records for an e-commerce web site. 55 | 56 | ```rust 57 | #[derive(Serialize, Deserialize, Debug)] 58 | struct Order { 59 | order_id: i32, 60 | product_id: i32, 61 | quantity: i32, 62 | amount: f32, 63 | shipping: f32, 64 | tax: f32, 65 | shipping_address: String, 66 | } 67 | ``` 68 | 69 | Next, define the ETL `transform()` function that transforms inbound data into a set of SQL statements for the database. The inbound data is simply a byte array that is recived from any data source (e.g., a POST request on the web hook, or a message in Kafka). In this example, the inbound data is a JSON string that represents the `order`. 70 | 71 | ```rust 72 | #[async_trait] 73 | impl Transformer for Order { 74 | async fn transform(inbound_data: Vec) -> TransformerResult> { 75 | let s = std::str::from_utf8(&inbound_data) 76 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 77 | let order: Order = serde_json::from_str(String::from(s).as_str()) 78 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 79 | log::info!("{:?}", &order); 80 | let mut ret = vec![]; 81 | let sql_string = format!( 82 | r"INSERT INTO orders VALUES ({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, CURRENT_TIMESTAMP);", 83 | order.order_id, 84 | order.product_id, 85 | order.quantity, 86 | order.amount, 87 | order.shipping, 88 | order.tax, 89 | order.shipping_address, 90 | ); 91 | dbg!(sql_string.clone()); 92 | ret.push(sql_string); 93 | Ok(ret) 94 | } 95 | } 96 | ``` 97 | 98 | Finally, in the main application we will configure an outbound database (a cloud database instance specified in `DATABASE_URL`) and an inbound data source (a webhook at `http://my.ip:3344`). Other inbound methods are also supported. For example, you can configure the ETL function to receive messages from a [Kafka or Redpanda queue](examples/kafka) or a Redis table. 99 | 100 | ```bash 101 | #[tokio::main(flavor = "current_thread")] 102 | async fn main() -> anyhow::Result<()> { 103 | env_logger::init(); 104 | 105 | let uri = std::env::var("DATABASE_URL")?; 106 | let mut pipe = Pipe::new(uri, "http://0.0.0.0:3344".to_string()).await; 107 | 108 | // This is async because this calls the async transform() function in Order 109 | pipe.start::().await?; 110 | Ok(()) 111 | } 112 | ``` 113 | 114 | Optionally, you can define an `init()` function. It will be executed the first time when the ETL starts up. Here, we use the `init()` to create and empty `orders` table in the database. 115 | 116 | ```rust 117 | #[async_trait] 118 | impl Transformer for Order { 119 | async fn init() -> TransformerResult { 120 | Ok(String::from( 121 | r"CREATE TABLE IF NOT EXISTS orders (order_id INT, product_id INT, quantity INT, amount FLOAT, shipping FLOAT, tax FLOAT, shipping_address VARCHAR(50), date_registered TIMESTAMP DEFAULT CURRENT_TIMESTAMP);", 122 | )) 123 | } 124 | } 125 | ``` 126 | 127 | ## Build 128 | 129 | Use the Rust `cargo` tool to build the ETL application. 130 | 131 | ```bash 132 | cargo build --target wasm32-wasi --release 133 | ``` 134 | 135 | Optionally, you could AOT compile it to improve performance (could be 100x faster for compute-intensive ETL functions). 136 | 137 | ```bash 138 | wasmedgec target/wasm32-wasi/release/order.wasm order.wasm 139 | ``` 140 | 141 | ## Run 142 | 143 | With WasmEdge, you have many deployment options. You could run the compiled ETL function program in any serverless infra that supports WasmEdge, which includes almost all [Kubernetes variations](https://wasmedge.org/book/en/use_cases/kubernetes.html), [Dapr](https://github.com/second-state/dapr-wasm), Docker, [Podman](https://github.com/KWasm/podman-wasm) and hosted function schedulers such as [essa-rs](https://github.com/essa-project/essa-rs) and [flows.network](https://flows.network/). 144 | 145 | But in this example, we will just use the good old `wasmedge` CLI tool to run the ETL function-as-a-service. 146 | 147 | ```bash 148 | wasmedge --env "DATABASE_URL=mysql://user:pass@ip.address:3306/mysql" order.wasm 149 | ``` 150 | 151 | It starts an HTTP server on port 3344 and waits for the inbound data. Open another terminal, and send it some inbound data via `curl`. 152 | 153 | ```bash 154 | curl http://localhost:3344/ -X POST -d @order.json 155 | ``` 156 | 157 | The JSON data in `order.json` is sent to the ETL `transform()` function as inbound data. The function parses it and generates the SQL string, which is automatically executed on the connected TiDB Cloud instance. You can now connect to TiDB Cloud from your database browser and see the `order` record in the database. 158 | 159 | ### Resources 160 | 161 | * [WasmEdge Runtime](https://github.com/WasmEdge/) 162 | * [WasmEdge book](https://wasmedge.org/book/en/) 163 | * [Second State](https://www.secondstate.io/) 164 | * [TiDB project](https://github.com/pingcap/tidb) 165 | * [TiDB Cloud](https://tidbcloud.com/) 166 | 167 | ### Join us! 168 | 169 | * [Twitter @realwasmedge](https://twitter.com/realwasmedge) 170 | * [Discord](https://discord.gg/JHxMj9EQbA) 171 | * [Email list](https://groups.google.com/g/wasmedge/) 172 | * [Slack #WasmEdge](https://slack.cncf.io/) 173 | 174 | -------------------------------------------------------------------------------- /examples/ethereum/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "transaction" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | anyhow = "1.0.65" 10 | mega_etl = {path = "../../mega_etl", version = "0.1"} 11 | tokio_wasi = {version = '1.21', features = ["rt", "macros"]} 12 | env_logger = "0.9" 13 | log = "0.4" 14 | serde = { version = "1.0", features = ["derive"] } 15 | serde_json = "1.0" 16 | http_req_wasi = "0.10" 17 | lazy_static = "1.4.0" 18 | -------------------------------------------------------------------------------- /examples/ethereum/README.md: -------------------------------------------------------------------------------- 1 | # Blockchain transactions to relational database table mapping (TRM) 2 | 3 | **[Checkout a video demo!](https://www.youtube.com/watch?v=sQCRQeTnBgo)** 4 | 5 | ## Prerequisites 6 | 7 | * [Install Rust](https://www.rust-lang.org/tools/install). The framework is currently written in the Rust language. A JavaScript version is in the works. 8 | * [Install WasmEdge](https://wasmedge.org/book/en/quick_start/install.html). You need it to run the ETL functions. 9 | * [Sign up for TiDB Cloud](https://tidbcloud.com/). The ETL transformed transaction data is written into this database for later analysis. 10 | * [Sign up for mempool API](https://www.blocknative.com/api). This service will call your webhook when a new Ethereum transaction enters the mempool or is confirmed on the blockchain. 11 | * [Sign up for Etherscan API](https://etherscan.io/apis). You need this to look up ETH to USD exchange rate in real time to convert input ETH values into USD and then save to TiDB. 12 | 13 | On Linux, you can use the following commands to install Rust and WasmEdge. 14 | 15 | ```bash 16 | # Install Rust 17 | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh 18 | source $HOME/.cargo/env 19 | # Install WebAssembly target for Rust 20 | rustup target add wasm32-wasi 21 | 22 | # Install WasmEdge 23 | curl -sSf https://raw.githubusercontent.com/WasmEdge/WasmEdge/master/utils/install.sh | bash -s -- -e all 24 | source $HOME/.wasmedge/env 25 | ``` 26 | 27 | ## Build 28 | 29 | Use the following command to build the microservice. A WebAssembly bytecode file (`wasm` file) will be created. 30 | 31 | ```bash 32 | cargo build --target wasm32-wasi --release 33 | ``` 34 | 35 | You can run the AOT compiler on the `wasm` file. It could significantly improvement the performance of compute-intensive applications. This microservice, however, is a network intensitive application. Our use of async HTTP networking (Tokio and hyper) and async MySQL connectors are crucial for the performance of this microservice. 36 | 37 | ```bash 38 | wasmedgec target/wasm32-wasi/release/transaction.wasm transaction.wasm 39 | ``` 40 | 41 | ## Run 42 | 43 | You can use the `wasmedge` command to run the `wasm` application. It will start the server. Make sure that you pass the following env variables to the command. 44 | 45 | * The `DATABASE_URL` is the [TiDB Cloud instance URL you signed up for](https://tidbcloud.com/). Make sure that you replace the `user` and `pass` with your own. 46 | * The `PRICE_API_KEY` is the [Etherscan ETH/USD price lookup service you signed up for](https://etherscan.io/apis). 47 | 48 | ```bash 49 | nohup wasmedge --env DATABASE_URL=mysql://user:pass@gateway01.us-west-2.prod.aws.tidbcloud.com:4000/demo --env PRICE_API_KEY=ABCD1234 --env RUST_LOG=info transaction.wasm 2>&1 & 50 | ``` 51 | 52 | Once the server is running and listening at the `3344` port, go to the [Blocknative mempool API console you signed up for](https://www.blocknative.com/api), and enter the ETL function's URL (e.g., `http://my-aws-ec2.ip:3344/`) as the webhook URL. 53 | 54 | ## See it in action 55 | 56 | The `nohup.out` file contains the raw transactions the ETL received from the mempool service. Use the following command to see live updates on the server. 57 | 58 | ```bash 59 | tail -f nohup.out 60 | ``` 61 | 62 | In the TiDB Cloud console, go to "Connect -> Web SQL Shell", you can execute SQL statements to see the content in the database table. 63 | 64 | ```sql 65 | USE demo; 66 | SELECT * from transactions; 67 | ``` 68 | -------------------------------------------------------------------------------- /examples/ethereum/src/main.rs: -------------------------------------------------------------------------------- 1 | use mega_etl::{async_trait, Pipe, Transformer, TransformerError, TransformerResult}; 2 | use serde::{Deserialize, Serialize}; 3 | use serde_json::Value; 4 | use tokio::sync::Mutex; 5 | 6 | use std::time::{Duration, SystemTime}; 7 | 8 | #[derive(Debug)] 9 | struct EthPrice { 10 | price: Option, 11 | update_time: SystemTime, 12 | } 13 | 14 | impl EthPrice { 15 | pub fn new() -> Self { 16 | EthPrice { 17 | price: None, 18 | update_time: SystemTime::now(), 19 | } 20 | } 21 | } 22 | 23 | lazy_static::lazy_static! { 24 | static ref PRICE: Mutex = Mutex::new(EthPrice::new()); 25 | } 26 | 27 | #[derive(Serialize, Deserialize, Debug, Clone)] 28 | struct Transaction { 29 | hash: String, 30 | from_address: String, 31 | to_address: String, 32 | value_usd: f64, 33 | value_eth: f64, 34 | gas: u64, 35 | confirmed: bool, 36 | } 37 | 38 | #[async_trait] 39 | impl Transformer for Transaction { 40 | async fn transform(inbound_data: &Vec) -> TransformerResult> { 41 | log::info!("Receive data."); 42 | let s = std::str::from_utf8(&inbound_data) 43 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 44 | let transaction: Value = 45 | serde_json::from_str(s).map_err(|e| TransformerError::Custom(e.to_string()))?; 46 | let status = serde_json::from_value::(transaction["status"].clone()) 47 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 48 | let hash = serde_json::from_value::(transaction["hash"].clone()) 49 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 50 | let from_address = serde_json::from_value::(transaction["from"].clone()) 51 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 52 | let to_address = serde_json::from_value::(transaction["to"].clone()) 53 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 54 | let value_eth = serde_json::from_value::(transaction["value"].clone()) 55 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 56 | if value_eth == "0" { 57 | // ignore smart contracts 58 | log::info!("Skip smart contract"); 59 | return Err(TransformerError::Skip); 60 | } 61 | // get value in usd 62 | let now = SystemTime::now(); 63 | let mut price = PRICE.lock().await; 64 | let current_price = if price.price.is_none() 65 | || now 66 | .duration_since(price.update_time) 67 | .map_err(|e| TransformerError::Custom(e.to_string()))? 68 | > Duration::from_secs(600) 69 | { 70 | log::debug!("try to get eth price"); 71 | let mut buf = Vec::new(); //container for body of a response 72 | let api_key = std::env::var("PRICE_API_KEY") 73 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 74 | let res = http_req::request::get( 75 | format!( 76 | "https://api.etherscan.io/api?module=stats&action=ethprice&apikey={}", 77 | api_key 78 | ), 79 | &mut buf, 80 | ) 81 | .unwrap(); 82 | 83 | if !res.status_code().is_success() { 84 | return Err(TransformerError::Custom(format!( 85 | "Request error: {}, get code: {}", 86 | res.reason(), 87 | res.status_code() 88 | ))); 89 | } 90 | let response = 91 | std::str::from_utf8(&buf).map_err(|e| TransformerError::Custom(e.to_string()))?; 92 | let response: Value = serde_json::from_str(response) 93 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 94 | serde_json::from_value::(response["result"]["ethusd"].clone()) 95 | .map_err(|e| TransformerError::Custom(e.to_string()))? 96 | .parse::() 97 | .map_err(|e| TransformerError::Custom(e.to_string()))? 98 | } else { 99 | log::debug!("use cached price"); 100 | price.price.unwrap() 101 | }; 102 | price.update_time = now; 103 | price.price = Some(current_price); 104 | // release the lock 105 | drop(price); 106 | let value_eth = value_eth 107 | .parse::() 108 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 109 | let value_eth = value_eth / 1_000_000_000_000_000_000.0; 110 | let value_usd = value_eth * current_price; 111 | let gas = serde_json::from_value::(transaction["gas"].clone()) 112 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 113 | let tx = Transaction { 114 | hash, 115 | from_address, 116 | to_address, 117 | value_eth, 118 | value_usd, 119 | gas, 120 | confirmed: status == "confirmed", 121 | }; 122 | log::info!("{:?}", tx); 123 | log::debug!("before insert"); 124 | if tx.confirmed { 125 | let sql_string = format!( 126 | r"INSERT INTO transactions (hash, from_address, to_address, value_usd, value_eth, gas, confirmed) VALUES({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) ON DUPLICATE KEY UPDATE confirmed=1;", 127 | tx.hash, 128 | tx.from_address, 129 | tx.to_address, 130 | tx.value_usd, 131 | tx.value_eth, 132 | tx.gas, 133 | tx.confirmed 134 | ); 135 | log::debug!("insert successfully"); 136 | Ok(vec![sql_string]) 137 | } else if status == "pending" { 138 | log::debug!("Insert pending record"); 139 | let sql_string = format!( 140 | r"INSERT INTO transactions (hash, from_address, to_address, value_usd, value_eth, gas, confirmed) VALUES({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?});", 141 | tx.hash, 142 | tx.from_address, 143 | tx.to_address, 144 | tx.value_usd, 145 | tx.value_eth, 146 | tx.gas, 147 | tx.confirmed 148 | ); 149 | log::debug!("insert successfully"); 150 | Ok(vec![sql_string]) 151 | } else { 152 | log::debug!("Skip other records"); 153 | // failing cases 154 | log::info!("Skip other records"); 155 | Err(TransformerError::Skip) 156 | } 157 | } 158 | 159 | async fn init() -> TransformerResult { 160 | Ok(String::from( 161 | r"CREATE TABLE IF NOT EXISTS transactions (hash VARCHAR(80), from_address VARCHAR(50), to_address VARCHAR(50), value_usd FLOAT, value_eth FLOAT, gas BIGINT UNSIGNED, confirmed BOOL, date_registered TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hash));", 162 | )) 163 | } 164 | } 165 | 166 | #[tokio::main(flavor = "current_thread")] 167 | async fn main() -> anyhow::Result<()> { 168 | env_logger::init(); 169 | 170 | // can use builder later 171 | let uri = std::env::var("DATABASE_URL")?; 172 | let mut pipe = Pipe::new(uri, "http://0.0.0.0:3344".to_string()).await; 173 | 174 | pipe.start::().await?; 175 | Ok(()) 176 | } 177 | -------------------------------------------------------------------------------- /examples/kafka/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "kafka" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | anyhow = "1.0.65" 10 | mega_etl = {git = "https://github.com/second-state/MEGA.git"} 11 | tokio_wasi = {version = '1.21', features = ["rt", "macros"]} 12 | env_logger = "0.9" 13 | log = "0.4" 14 | serde = { version = "1.0", features = ["derive"] } 15 | serde_json = "1.0" 16 | http_req_wasi = "0.10" 17 | lazy_static = "1.4.0" 18 | -------------------------------------------------------------------------------- /examples/kafka/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM --platform=$BUILDPLATFORM rust:1.64 AS buildbase 2 | RUN <&1 & 44 | ``` 45 | 46 | The server log will appear in the `nohup.out` file. 47 | 48 | ## See it in action 49 | 50 | The ETL program (i.e., the server from above) has already created and connected to the `order` queue in Redpanda when it started. You can produce data from the `order` topic using the [rpk](https://docs.redpanda.com/docs/platform/quickstart/rpk-install/) CLI tool. The ETL program will receive the data from the queue, parse it, process it, and save it to the database. 51 | 52 | ```bash 53 | cat order.json | rpk topic produce order 54 | ``` 55 | 56 | > You can also use the `rpk` command to create a new topic for the ETL program to listen to. Just do `rpk topic create order`. 57 | 58 | You can now log into the database to see the `orders` table and its content. 59 | 60 | ## Docker 61 | 62 | With WasmEdge support in Docker, you can also use Docker Compose to build and start this multi-container application in a single command without installing any dependencies. 63 | 64 | * [Install Docker Desktop + Wasm (Beta)](https://docs.docker.com/desktop/wasm/) 65 | * or [Install Docker CLI + Wasm](https://github.com/chris-crone/wasm-day-na-22/tree/main/server) 66 | 67 | Then, you just need to type one command. 68 | 69 | ```bash 70 | docker compose up 71 | ``` 72 | 73 | This will build the Rust source code, run the Wasm server for the ETL function, and startup contaniners for a Redpanda server and a MySQL backing database. 74 | 75 | To try it out, log into the Redpanda container and send a message to the queue topic `order` as follows. 76 | 77 | ```bash 78 | $ docker compose exec redpanda /bin/bash 79 | redpanda@1add2615774b:/$ cd /app 80 | redpanda@1add2615774b:/app$ cat order.json | rpk topic produce order 81 | Produced to partition 0 at offset 0 with timestamp 1667922788523. 82 | ``` 83 | 84 | To see the data in the database container, you can use the following commands. 85 | 86 | ```bash 87 | $ docker compose exec db /bin/bash 88 | root@c97c472db02e:/# mysql -u root -pwhalehello mysql 89 | mysql> select * from orders; 90 | ... ... 91 | ``` 92 | -------------------------------------------------------------------------------- /examples/kafka/docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | redpanda: 3 | image: docker.redpanda.com/vectorized/redpanda:v22.2.2 4 | command: 5 | - redpanda start 6 | - --smp 1 7 | - --overprovisioned 8 | - --node-id 0 9 | - --kafka-addr PLAINTEXT://0.0.0.0:29092,OUTSIDE://0.0.0.0:9092 10 | - --advertise-kafka-addr PLAINTEXT://redpanda:29092,OUTSIDE://redpanda:9092 11 | - --pandaproxy-addr 0.0.0.0:8082 12 | - --advertise-pandaproxy-addr localhost:8082 13 | ports: 14 | - 8081:8081 15 | - 8082:8082 16 | - 9092:9092 17 | - 9644:9644 18 | - 29092:29092 19 | volumes: 20 | - ./:/app 21 | etl: 22 | image: etl-kafka 23 | platform: wasi/wasm 24 | build: 25 | context: . 26 | environment: 27 | DATABASE_URL: mysql://root:whalehello@db:3306/mysql 28 | KAFKA_URL: kafka://redpanda:9092/order 29 | RUST_BACKTRACE: full 30 | RUST_LOG: info 31 | restart: unless-stopped 32 | runtime: io.containerd.wasmedge.v1 33 | db: 34 | image: mariadb:10.9 35 | environment: 36 | MYSQL_ROOT_PASSWORD: whalehello 37 | -------------------------------------------------------------------------------- /examples/kafka/order.json: -------------------------------------------------------------------------------- 1 | {"order_id": 1,"product_id": 12,"quantity": 2,"amount": 56.0,"shipping": 15.0,"tax": 2.0,"shipping_address": "Mataderos 2312"} 2 | -------------------------------------------------------------------------------- /examples/kafka/src/main.rs: -------------------------------------------------------------------------------- 1 | use mega_etl::{async_trait, Pipe, Transformer, TransformerError, TransformerResult}; 2 | 3 | use serde::{Deserialize, Serialize}; 4 | #[derive(Serialize, Deserialize, Debug)] 5 | struct Order { 6 | order_id: i32, 7 | product_id: i32, 8 | quantity: i32, 9 | amount: f32, 10 | shipping: f32, 11 | tax: f32, 12 | shipping_address: String, 13 | } 14 | 15 | #[async_trait] 16 | impl Transformer for Order { 17 | async fn transform(inbound_data: &Vec) -> TransformerResult> { 18 | let s = std::str::from_utf8(&inbound_data) 19 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 20 | let order: Order = serde_json::from_str(String::from(s).as_str()) 21 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 22 | log::info!("{:?}", &order); 23 | let mut ret = vec![]; 24 | let sql_string = format!( 25 | r"INSERT INTO orders VALUES ({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, CURRENT_TIMESTAMP);", 26 | order.order_id, 27 | order.product_id, 28 | order.quantity, 29 | order.amount, 30 | order.shipping, 31 | order.tax, 32 | order.shipping_address, 33 | ); 34 | dbg!(sql_string.clone()); 35 | ret.push(sql_string); 36 | Ok(ret) 37 | } 38 | 39 | async fn init() -> TransformerResult { 40 | Ok(String::from( 41 | r"CREATE TABLE IF NOT EXISTS orders (order_id INT, product_id INT, quantity INT, amount FLOAT, shipping FLOAT, tax FLOAT, shipping_address VARCHAR(50), date_registered TIMESTAMP DEFAULT CURRENT_TIMESTAMP);", 42 | )) 43 | } 44 | } 45 | 46 | #[tokio::main(flavor = "current_thread")] 47 | async fn main() -> anyhow::Result<()> { 48 | env_logger::init(); 49 | 50 | // can use builder later 51 | let database_uri = std::env::var("DATABASE_URL")?; 52 | let kafka_uri = std::env::var("KAFKA_URL")?; 53 | let mut pipe = Pipe::new(database_uri, kafka_uri).await; 54 | 55 | // This is async because this calls the async transform() function in Order 56 | pipe.start::().await?; 57 | Ok(()) 58 | } 59 | -------------------------------------------------------------------------------- /examples/order/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "order" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | anyhow = "1.0.65" 10 | mega_etl = {git = "https://github.com/second-state/MEGA.git"} 11 | tokio_wasi = {version = '1.21', features = ["rt", "macros"]} 12 | env_logger = "0.9" 13 | log = "0.4" 14 | serde = { version = "1.0", features = ["derive"] } 15 | serde_json = "1.0" 16 | http_req_wasi = "0.10" 17 | lazy_static = "1.4.0" 18 | -------------------------------------------------------------------------------- /examples/order/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM --platform=$BUILDPLATFORM rust:1.64 AS buildbase 2 | RUN <&1 & 43 | ``` 44 | 45 | The server log will appear in the `nohup.out` file. 46 | 47 | ## See it in action 48 | 49 | You can send data to the webhook using `curl`. 50 | 51 | ```bash 52 | curl http://localhost:3344/ -X POST -d @order.json 53 | ``` 54 | 55 | You can now log into the database to see the `orders` table and its content. 56 | 57 | ## Docker 58 | 59 | With WasmEdge support in Docker, you can also use Docker Compose to build and start this multi-container application in a single command without installing any dependencies. 60 | 61 | * [Install Docker Desktop + Wasm (Beta)](https://docs.docker.com/desktop/wasm/) 62 | * or [Install Docker CLI + Wasm](https://github.com/chris-crone/wasm-day-na-22/tree/main/server) 63 | 64 | Then, you just need to type one command. 65 | 66 | ```bash 67 | docker compose up 68 | ``` 69 | 70 | This will build the Rust source code, run the Wasm server for the ETL function, and startup a MySQL backing database. You can then use [the curl commands](#see-it-in-action) to send data to the webhook for the ETL. 71 | 72 | To see the data in the database container, you can use the following commands. 73 | 74 | ```bash 75 | docker compose exec db /bin/bash 76 | root@c97c472db02e:/# mysql -u root -pwhalehello mysql 77 | mysql> select * from orders; 78 | ... ... 79 | ``` 80 | -------------------------------------------------------------------------------- /examples/order/docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | etl: 3 | image: etl-webhook 4 | platform: wasi/wasm 5 | build: 6 | context: . 7 | ports: 8 | - 3344:3344 9 | environment: 10 | DATABASE_URL: mysql://root:whalehello@db:3306/mysql 11 | RUST_BACKTRACE: full 12 | restart: unless-stopped 13 | runtime: io.containerd.wasmedge.v1 14 | db: 15 | image: mariadb:10.9 16 | environment: 17 | MYSQL_ROOT_PASSWORD: whalehello 18 | -------------------------------------------------------------------------------- /examples/order/order.json: -------------------------------------------------------------------------------- 1 | { 2 | "order_id": 1, 3 | "product_id": 12, 4 | "quantity": 2, 5 | "amount": 56.0, 6 | "shipping": 15.0, 7 | "tax": 2.0, 8 | "shipping_address": "Mataderos 2312" 9 | } 10 | -------------------------------------------------------------------------------- /examples/order/src/main.rs: -------------------------------------------------------------------------------- 1 | use mega_etl::{async_trait, Pipe, Transformer, TransformerError, TransformerResult}; 2 | 3 | use serde::{Deserialize, Serialize}; 4 | #[derive(Serialize, Deserialize, Debug)] 5 | struct Order { 6 | order_id: i32, 7 | product_id: i32, 8 | quantity: i32, 9 | amount: f32, 10 | shipping: f32, 11 | tax: f32, 12 | shipping_address: String, 13 | } 14 | 15 | #[async_trait] 16 | impl Transformer for Order { 17 | async fn transform(inbound_data: &Vec) -> TransformerResult> { 18 | let s = std::str::from_utf8(&inbound_data) 19 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 20 | let order: Order = serde_json::from_str(String::from(s).as_str()) 21 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 22 | log::info!("{:?}", &order); 23 | let mut ret = vec![]; 24 | let sql_string = format!( 25 | r"INSERT INTO orders VALUES ({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, CURRENT_TIMESTAMP);", 26 | order.order_id, 27 | order.product_id, 28 | order.quantity, 29 | order.amount, 30 | order.shipping, 31 | order.tax, 32 | order.shipping_address, 33 | ); 34 | dbg!(sql_string.clone()); 35 | ret.push(sql_string); 36 | Ok(ret) 37 | } 38 | 39 | async fn init() -> TransformerResult { 40 | Ok(String::from( 41 | r"CREATE TABLE IF NOT EXISTS orders (order_id INT, product_id INT, quantity INT, amount FLOAT, shipping FLOAT, tax FLOAT, shipping_address VARCHAR(50), date_registered TIMESTAMP DEFAULT CURRENT_TIMESTAMP);", 42 | )) 43 | } 44 | } 45 | 46 | #[tokio::main(flavor = "current_thread")] 47 | async fn main() -> anyhow::Result<()> { 48 | env_logger::init(); 49 | 50 | // can use builder later 51 | let uri = std::env::var("DATABASE_URL")?; 52 | let mut pipe = Pipe::new(uri, "http://0.0.0.0:3344".to_string()).await; 53 | 54 | // This is async because this calls the async transform() function in Order 55 | pipe.start::().await?; 56 | Ok(()) 57 | } 58 | -------------------------------------------------------------------------------- /examples/order_conn/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "order_conn" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | anyhow = "1.0.65" 10 | mega_etl = {path = "../../mega_etl", version = "0.1.1"} 11 | tokio_wasi = {version = '1.21', features = ["rt", "macros"]} 12 | env_logger = "0.9" 13 | log = "0.4" 14 | serde = { version = "1.0", features = ["derive"] } 15 | serde_json = "1.0" 16 | http_req_wasi = "0.10" 17 | lazy_static = "1.4.0" 18 | -------------------------------------------------------------------------------- /examples/order_conn/src/main.rs: -------------------------------------------------------------------------------- 1 | use mega_etl::prelude::*; 2 | use mega_etl::{ 3 | async_trait, params, Conn, Params, Pipe, Transformer, TransformerError, TransformerResult, 4 | }; 5 | 6 | use serde::{Deserialize, Serialize}; 7 | use std::sync::Arc; 8 | use tokio::sync::Mutex; 9 | 10 | #[derive(Serialize, Deserialize, Debug)] 11 | struct Order { 12 | order_id: i32, 13 | product_id: i32, 14 | quantity: i32, 15 | amount: f32, 16 | shipping: f32, 17 | tax: f32, 18 | shipping_address: String, 19 | } 20 | 21 | #[async_trait] 22 | impl Transformer for Order { 23 | async fn transform_save( 24 | inbound_data: &Vec, 25 | conn: Arc>, 26 | ) -> TransformerResult<()> { 27 | let s = std::str::from_utf8(&inbound_data) 28 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 29 | let order: Order = serde_json::from_str(String::from(s).as_str()) 30 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 31 | log::info!("{:?}", &order); 32 | let mut conn = conn.lock().await; 33 | let result = conn 34 | .exec::(r"SHOW TABLES LIKE 'orders';", ()) 35 | .await 36 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 37 | if result.len() == 0 { 38 | // table doesn't exist, create a new one 39 | conn.exec::(r"CREATE TABLE orders (order_id INT, product_id INT, quantity INT, amount FLOAT, shipping FLOAT, tax FLOAT, shipping_address VARCHAR(50), date_registered TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP );", ()) 40 | .await 41 | .map_err(|e| TransformerError::Custom(e.to_string()))?; 42 | log::debug!("create new table"); 43 | } 44 | log::debug!("before insert"); 45 | conn.exec::(String::from(r"INSERT INTO orders (order_id, product_id, quantity, amount, shipping, tax, shipping_address) 46 | VALUES (:order_id, :product_id, :quantity, :amount, :shipping, :tax, :shipping_address)"), params! { 47 | "order_id" => order.order_id, 48 | "product_id" => order.product_id, 49 | "quantity" => order.quantity, 50 | "amount" => order.amount, 51 | "shipping" => order.shipping, 52 | "tax" => order.tax, 53 | "shipping_address" => &order.shipping_address, 54 | }).await.map_err(|e| TransformerError::Custom(e.to_string()))?; 55 | log::debug!("insert successfully"); 56 | 57 | Ok(()) 58 | } 59 | } 60 | 61 | #[tokio::main(flavor = "current_thread")] 62 | async fn main() -> anyhow::Result<()> { 63 | env_logger::init(); 64 | 65 | // can use builder later 66 | let uri = std::env::var("DATABASE_URL")?; 67 | let mut pipe = Pipe::new(uri, "http://0.0.0.0:3344".to_string()).await; 68 | 69 | // This is async because this calls the async transform() function in Order 70 | pipe.start::().await?; 71 | Ok(()) 72 | } 73 | -------------------------------------------------------------------------------- /mega_etl/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "mega_etl" 3 | version = "0.1.1" 4 | edition = "2021" 5 | authors = ["Tricster ", "Michael Yuan ", "Miley Fu "] 6 | license = "Apache-2.0" 7 | readme = "../README.md" 8 | repository = "https://github.com/second-state/MEGA" 9 | homepage = "https://github.com/second-state/MEGA" 10 | description = """ 11 | A cloud-native ETL (Extract, Transform, Load) application framework based on the WasmEdge WebAssembly runtime for developers to filter, map, and transform data pipelines going into cloud databases. 12 | """ 13 | categories = ["asynchronous", "network-programming"] 14 | keywords = ["etl", "database", "streaming", "serverless", "wasm"] 15 | 16 | 17 | [dependencies] 18 | async-trait = "0.1.57" 19 | mysql_async_wasi = "0.31" 20 | thiserror = "1.0" 21 | url = "2.3.1" 22 | hyper_wasi = {version = "0.15", features = ["full"]} 23 | anyhow = "1.0.65" 24 | tokio_wasi = {version = "1", features = ["net"]} 25 | log = "0.4.17" 26 | rskafka_wasi = "0.3" 27 | futures-util = "0.3" 28 | -------------------------------------------------------------------------------- /mega_etl/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub use async_trait::async_trait; 2 | use futures_util::StreamExt; 3 | use hyper::service::{make_service_fn, service_fn}; 4 | use hyper::Server; 5 | use hyper::{Body, Request, Response}; 6 | pub use mysql_async::prelude::*; 7 | pub use mysql_async::*; 8 | use rskafka::client::{ 9 | consumer::{StartOffset, StreamConsumerBuilder}, 10 | partition::UnknownTopicHandling, 11 | ClientBuilder, 12 | }; 13 | use std::convert::Infallible; 14 | use std::net::ToSocketAddrs; 15 | use std::sync::Arc; 16 | use thiserror::Error; 17 | use tokio::sync::Mutex; 18 | use url::Url; 19 | 20 | #[derive(Error, Debug)] 21 | pub enum TransformerError { 22 | #[error("function is unimplemented")] 23 | Unimplemented, 24 | #[error("Error: {0}")] 25 | Custom(String), 26 | #[error("unknown data store error")] 27 | Unknown, 28 | #[error("skip the data")] 29 | Skip, 30 | } 31 | 32 | pub type TransformerResult = std::result::Result; 33 | 34 | macro_rules! impl_from_transformer_error { 35 | ($error:ty) => { 36 | impl From<$error> for TransformerError { 37 | fn from(value: $error) -> Self { 38 | TransformerError::Custom(value.to_string()) 39 | } 40 | } 41 | }; 42 | } 43 | 44 | impl_from_transformer_error!(rskafka::client::error::Error); 45 | impl_from_transformer_error!(mysql_async::Error); 46 | impl_from_transformer_error!(mysql_async::ParseError); 47 | impl_from_transformer_error!(std::io::Error); 48 | impl_from_transformer_error!(hyper::Error); 49 | 50 | enum DataSource { 51 | Hyper(String, u16), 52 | Redis, 53 | Kafka(String, u16, String), 54 | Unknown, 55 | } 56 | 57 | impl DataSource { 58 | pub fn parse_uri(uri: &str) -> std::result::Result { 59 | let url = Url::parse(uri)?; 60 | match url.scheme() { 61 | "http" => { 62 | let host = if let Some(host) = url.host_str() { 63 | host 64 | } else { 65 | return Err(url::ParseError::EmptyHost); 66 | }; 67 | let port = if let Some(port) = url.port_or_known_default() { 68 | port 69 | } else { 70 | return Err(url::ParseError::InvalidPort); 71 | }; 72 | Ok(DataSource::Hyper(host.to_string(), port)) 73 | } 74 | "redis" => Ok(DataSource::Redis), 75 | "kafka" => { 76 | let host = if let Some(host) = url.host_str() { 77 | host 78 | } else { 79 | return Err(url::ParseError::EmptyHost); 80 | }; 81 | let port = if let Some(port) = url.port_or_known_default() { 82 | port 83 | } else { 84 | return Err(url::ParseError::InvalidPort); 85 | }; 86 | let topic = url 87 | .path_segments() 88 | .expect("rskafka: get invaild path") 89 | .nth(0) 90 | .expect("rskafka: get empty path"); 91 | Ok(DataSource::Kafka(host.to_string(), port, topic.to_string())) 92 | } 93 | _ => Ok(DataSource::Unknown), 94 | } 95 | } 96 | } 97 | 98 | #[async_trait] 99 | pub trait Transformer { 100 | async fn transform(_inbound_data: &Vec) -> TransformerResult> { 101 | Err(TransformerError::Unimplemented.into()) 102 | } 103 | 104 | async fn transform_save( 105 | _inbound_data: &Vec, 106 | _conn: Arc>, 107 | ) -> TransformerResult<()> { 108 | Err(TransformerError::Unimplemented.into()) 109 | } 110 | 111 | async fn init() -> TransformerResult { 112 | Err(TransformerError::Unimplemented.into()) 113 | } 114 | } 115 | 116 | async fn handle_request( 117 | req: Request, 118 | conn: Arc>, 119 | ) -> anyhow::Result> { 120 | log::debug!("receive data"); 121 | let content = hyper::body::to_bytes(req.into_body()) 122 | .await 123 | .unwrap() 124 | .to_vec(); 125 | 126 | match T::transform(&content).await { 127 | Ok(sql_strings) => { 128 | // exec the query string 129 | // conn.lock().await.exec(stmt, params) 130 | for sql_string in sql_strings { 131 | log::debug!("receive {sql_string:?}"); 132 | 133 | if let Err(e) = conn 134 | .lock() 135 | .await 136 | .exec::(sql_string, ()) 137 | .await 138 | { 139 | return Ok(Response::new(Body::from(e.to_string()))); 140 | } 141 | } 142 | return Ok(Response::new(Body::from("Success"))); 143 | } 144 | Err(TransformerError::Unimplemented) => { 145 | log::debug!("skip transform"); 146 | } 147 | Err(TransformerError::Custom(err)) => return Ok(Response::new(Body::from(err))), 148 | Err(TransformerError::Unknown) => return Ok(Response::new(Body::from("Unknown error"))), 149 | Err(TransformerError::Skip) => return Ok(Response::new(Body::from("skip this data"))), 150 | } 151 | match T::transform_save(&content, conn).await { 152 | Ok(_) => { 153 | // exec the query string 154 | // conn.lock().await.exec(stmt, params) 155 | return Ok(Response::new(Body::from("Success"))); 156 | } 157 | Err(TransformerError::Unimplemented) => { 158 | log::debug!("skip transform_save"); 159 | } 160 | Err(TransformerError::Custom(err)) => return Ok(Response::new(Body::from(err))), 161 | Err(TransformerError::Unknown) => return Ok(Response::new(Body::from("Unknown error"))), 162 | Err(TransformerError::Skip) => return Ok(Response::new(Body::from("skip this data"))), 163 | } 164 | Ok(Response::new(Body::from( 165 | "One of transform and transform_save must be implemented.", 166 | ))) 167 | } 168 | 169 | async fn kafka_handle_request( 170 | content: Vec, 171 | conn: Arc>, 172 | ) -> TransformerResult<()> { 173 | log::debug!("receive data"); 174 | match T::transform(&content).await { 175 | Ok(sql_strings) => { 176 | // exec the query string 177 | // conn.lock().await.exec(stmt, params) 178 | for sql_string in sql_strings { 179 | log::debug!("receive {sql_string:?}"); 180 | 181 | if let Err(_e) = conn 182 | .lock() 183 | .await 184 | .exec::(sql_string, ()) 185 | .await 186 | { 187 | log::error!("{:?}", _e.to_string()); 188 | return Ok(()); 189 | } 190 | } 191 | return Ok(()); 192 | } 193 | Err(TransformerError::Unimplemented) => { 194 | log::debug!("skip transform"); 195 | } 196 | Err(TransformerError::Custom(_err)) => { 197 | log::error!("{:?}", _err.to_string()); 198 | return Ok(()); 199 | } 200 | Err(TransformerError::Unknown) => return Ok(()), 201 | Err(TransformerError::Skip) => return Ok(()), 202 | } 203 | match T::transform_save(&content, conn).await { 204 | Ok(_) => { 205 | // exec the query string 206 | // conn.lock().await.exec(stmt, params) 207 | return Ok(()); 208 | } 209 | Err(TransformerError::Unimplemented) => { 210 | log::debug!("skip transform_save"); 211 | } 212 | Err(TransformerError::Custom(_err)) => { 213 | log::error!("{:?}", _err.to_string()); 214 | return Ok(()); 215 | } 216 | Err(TransformerError::Unknown) => return Ok(()), 217 | Err(TransformerError::Skip) => return Ok(()), 218 | } 219 | Ok(()) 220 | } 221 | 222 | pub struct Pipe { 223 | mysql_conn: Arc, 224 | connector_uri: Option, 225 | } 226 | 227 | impl Pipe { 228 | pub async fn new>(mysql_uri: Str, data_source_uri: String) -> Self { 229 | let opts = Opts::from_url(mysql_uri.as_ref()).unwrap(); 230 | let builder = OptsBuilder::from_opts(opts); 231 | let pool_opts = PoolOpts::default(); 232 | let pool = Pool::new(builder.pool_opts(pool_opts)); 233 | return Pipe { 234 | mysql_conn: Arc::new(pool), 235 | connector_uri: Some(data_source_uri), 236 | }; 237 | } 238 | 239 | pub async fn start(&mut self) -> TransformerResult<()> { 240 | // init the table 241 | match T::init().await { 242 | Ok(sql_string) => { 243 | let mut conn = self.mysql_conn.get_conn().await?; 244 | let _ = conn.exec::(sql_string, ()).await?; 245 | } 246 | Err(e) => return Err(e), 247 | } 248 | let uri = self.connector_uri.as_ref().unwrap(); 249 | match DataSource::parse_uri(uri)? { 250 | DataSource::Hyper(addr, port) => { 251 | let addr = (addr, port).to_socket_addrs()?.nth(0); 252 | let addr = if addr.is_none() { 253 | return Err(TransformerError::Custom("Empty addr".into())); 254 | } else { 255 | addr.unwrap() 256 | }; 257 | 258 | let make_svc = make_service_fn(|_| { 259 | let pool = self.mysql_conn.clone(); 260 | async move { 261 | let conn = Arc::new(Mutex::new(pool.get_conn().await.unwrap())); 262 | Ok::<_, Infallible>(service_fn(move |req| { 263 | let conn = conn.clone(); 264 | handle_request::(req, conn) 265 | })) 266 | } 267 | }); 268 | let server = Server::bind(&addr).serve(make_svc); 269 | server.await?; 270 | Ok(()) 271 | } 272 | DataSource::Kafka(host, port, topic) => { 273 | log::debug!("{} {} {}", host, port, topic); 274 | let connection = format!("{}:{}", host, port); 275 | let timeout = tokio::time::timeout( 276 | std::time::Duration::from_secs(3), 277 | ClientBuilder::new(vec![connection]).build(), 278 | ) 279 | .await; 280 | let client = if let Ok(client) = timeout { 281 | client? 282 | } else { 283 | panic!("Cannot connect Kafka in 3s."); 284 | }; 285 | 286 | let partition_client = Arc::new( 287 | client 288 | .partition_client( 289 | topic, 290 | 0, // partition 291 | UnknownTopicHandling::Retry, 292 | ) 293 | .await?, 294 | ); 295 | let mut stream = 296 | StreamConsumerBuilder::new(Arc::clone(&partition_client), StartOffset::Latest) 297 | .with_max_wait_ms(500) 298 | .build(); 299 | // use loop to listen incoming records. 300 | loop { 301 | log::debug!("wait a record"); 302 | let (mut record, _high_watermark) = stream 303 | .next() 304 | .await 305 | .ok_or(TransformerError::Custom("kafka stream return error".into()))??; 306 | if let Some(incoming_data) = record.record.value.take() { 307 | log::debug!("get a record"); 308 | let conn = Arc::new(Mutex::new(self.mysql_conn.get_conn().await?)); 309 | kafka_handle_request::(incoming_data, conn).await?; 310 | } else { 311 | log::debug!("skip empty kafka record"); 312 | } 313 | } 314 | } 315 | DataSource::Redis => Err(TransformerError::Unimplemented), 316 | DataSource::Unknown => Err(TransformerError::Custom("Unknown data source".to_string())), 317 | } 318 | } 319 | } 320 | --------------------------------------------------------------------------------