Basic Rust Application
Prerequisites
Section titled “Prerequisites”- Language-specific tools - Install Heim Prerequisites
- Heim cli and runtime - Install Heim
- Text Editor - VsCode is a great option with language-specific plugins
- Terminal - Heim is accessed through its command-line interface
Start by running
heim newto create a project from a template.Use the up/down arrow keys to select the template and press enter:
Heim Cli heim@system:~/repos$ heim new? Select template: ›csharp-httpcsharp-http-asyncpython-http...❯ rust-http...typescript-httpNext, we will choose the HTTP method that the application will respond on.
For this we will choose the default value of
GET:Heim Cli ✔ Select template: · rust-http? Http trigger method POST/GET, Default (GET) ›Next, we need to choose the path that the application will listen on.
Once the trigger path is set, we’ll be able to go to the trigger path, and use the HTTP method we set to trigger the application.
Heim Cli ✔ Select template: · rust-http✔ Http trigger method POST/GET, Default · GET? Http trigger path /??? , Default (/hello) › /myappLast, we will need to set the name of the application.
Heim Cli ✔ Select template: · rust-http✔ Http trigger method POST/GET, Default · GET✔ Http trigger path /??? , Default · /myapp? Package name, (Required) › myappRendered Template: ""/tmp/heimQ2z7DE/myapp/component.toml""Rendered Template: ""/tmp/heimQ2z7DE/myapp/application.toml""Rendered Template: ""/tmp/heimQ2z7DE/myapp/src/lib.rs""Rendered Template: ""/tmp/heimQ2z7DE/myapp/Cargo.toml""[00:00:00] ######################################## 5/5 SuccessINFO [ Heim new ] New component created: Some("/home/heim/repos/myapp")Once we’ve gone through all the previous steps, we’ll have a project ready to go.
Let’s open the project in your text editor to check on what our new application looks like…
Now, you will have an application folder with this structure:
Directorysrc/
- lib.rs
- .gitignore
- Cargo.toml
- component.toml
- application.toml
Take note of the marked configuration files. Let’s take a look at these files, next.
component.toml
Section titled “component.toml”The component.toml file, defines a component, and one or more components make up an application in Heim.
component.tomlname = "myapp" # Component nameversion = "0.1.0"[commands] # Custom commands that can be used from the heim clirun = "wasmtime serve -S cli target/wasm32-wasip2/debug/myapp.wasm --addr=127.0.0.1:8080"run_production = "wasmtime serve -S cli target/wasm32-wasip2/release/myapp.wasm --addr=127.0.0.1:8080"[build.dev] # Dev build command and outputbuild = "cargo build --target=wasm32-wasip2"wasm_path = "target/wasm32-wasip2/debug/myapp.wasm"[build.prod] # Prod build command and outputbuild = "cargo build --target=wasm32-wasip2 --release"wasm_path = "target/wasm32-wasip2/release/myapp.wasm"a simple component.toml, with explanatory comments
application.toml
Section titled “application.toml”The application.toml is what defines an application. A application.toml is required for deploying an application to Heim.
application.tomlname = "myapp" # application namecomponent_target = 'myapp:0.1.0' # component to target[[trigger]] # Trigger definitiontype = 'http'path = '/myapp'method = 'GET'a simple application.toml, with explanatory comments
Open
src/lib.rsand take a look at the code we have:lib.rsuse waki::{handler, ErrorCode, Request, Response};#[handler]fn hello(req: Request) -> Result<Response, ErrorCode> {Response::builder().status_code(200).body("Hello World").build()}The lib.rs file contains boilerplate source code.
Now, we want to start the application. Read on to learn the steps needed to start an application.
Run heim start, to start the heim runtime:
heim runtime heim@system:~/repos$ heim startStarting Runtime with Config:...Http server listening on: http://127.0.0.1:3000Heim portal: http://127.0.0.1:3000/heim/portal/Note that the Heim portal comes included with any Heim installation, and that it will be available on
http://127.0.0.1:3000/heim/portal/once you’ve installed Heim.To build the application and deploy it to our local-instance, we will run heim deploy. By default, this will create a debug build, but we can change it to a release build with the
--releaseflag:heim cli heim@system:~/repos$ heim deployINFO [ heim_cli::wasm::build ] Building Component: myappCompiling myapp v0.1.0 (/home/work/repos/myapp)...Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.18sCreating component target/wasm32-wasip2/debug/myapp.wasmINFO [ heim_registry::registry ] "myapp":"0.1.0":cb4abe161542a7b146fe27c5f5cdb60970d68a369f5703bde252664ddbe2eedfINFO [ Heim::Deploy ] Heim application `myapp` is now built and written to registry.INFO [ Heim::Pipeline ] Starting pipeline 'Deploy application'INFO [ Heim::Pipeline ] Storing unoptimized component stateINFO [ Heim::Pipeline ] Checking if defined regions in app definition is validINFO [ Heim::Pipeline ] Continuing with localhost region heim-localhostINFO [ Heim::Pipeline ] Getting region specific application environment valuesINFO [ Heim::Pipeline ] Set environment values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting region specific application scaling valuesINFO [ Heim::Pipeline ] Set scaling values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting capabilitiesINFO [ Heim::Pipeline ] Set capabilities values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting triggersINFO [ Heim::Pipeline ] Set trigger values for region 'heim-localhost'INFO [ Heim::Pipeline ] Component environment values are valid for all regionsINFO [ Heim::Pipeline ] Checking for region with changes to buildINFO [ Heim::Pipeline ] Region "heim-localhost" has been changed and will be builtINFO [ Heim::Pipeline ] Storing component and optimized componentINFO [ Heim::Pipeline ] Stored component at ''INFO [ Heim::Pipeline ] Stored optimized component at ''INFO [ Heim::Pipeline ] Storing region statesINFO [ Heim::Pipeline ] Stored state for region(s) heim-localhost successfullyINFO [ Heim::Pipeline ] Creating and caching application(s)INFO [ Heim::Pipeline ] Creating and caching application(s) for region(s) heim-localhostINFO [ Heim::Pipeline ] Created application with hash 8aba8efca7c309fe7cafce25df43fe78bbe9d0479f9b709cea97f9d507048a11 for region(s) heim-localhostINFO [ Heim::Pipeline ] Application has been deployed for region(s) heim-localhostINFO [ Heim::Pipeline ] Pipeline 'Deploy application' finished with status 'Success'INFO [ Heim::Deploy ] Heim deploy pipeline was successfulINFO [ Heim::Deploy ] Application is accaccessible at:INFO [ Heim::Deploy ] [GET] http://127.0.0.1:3000/myappINFO [ Heim::Deploy ] Written and deployed application `myapp`.From here, you can see that we are able to access the application on
http://127.0.0.1:3000/myapp:curl heim@system:~/repos$ curl http://127.0.0.1:3000/myappHello World!To deploy the application to the cloud instance, we will run heim deploy with the
--cloudflag. This will generate a release build as default, but it can be changed to a debug with the the--devflag.This will deploy the application to your subdomain at
my-subdomain.cloud.heim.devheim cli heim@system:~/repos$ heim deploy --cloudINFO [ heim_registry::registry ] "myapp":"0.1.0":02f6d7d3c34210438f293efc1ff2f8e9494f783a402e5dcbe6a308fea40d870eINFO [ Heim::Deploy ] Heim application `myapp` is now built and written to registry.INFO [ Heim::Pipeline ] Starting pipeline 'Deploy application'INFO [ Heim::Pipeline ] Storing unoptimized component stateINFO [ Heim::Pipeline ] Checking if defined regions in app definition is validINFO [ Heim::Pipeline ] Continuing with localhost region heim-localhostINFO [ Heim::Pipeline ] Getting region specific application environment valuesINFO [ Heim::Pipeline ] Set environment values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting region specific application scaling valuesINFO [ Heim::Pipeline ] Set scaling values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting capabilitiesINFO [ Heim::Pipeline ] Set capabilities values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting triggersINFO [ Heim::Pipeline ] Set trigger values for region 'heim-localhost'INFO [ Heim::Pipeline ] Component environment values are valid for all regionsINFO [ Heim::Pipeline ] Checking for region with changes to buildINFO [ Heim::Pipeline ] Region "heim-localhost" has been changed and will be builtINFO [ Heim::Pipeline ] Optimizing base componentINFO [ Heim::Pipeline ] Optimized base component, size before optimization: 2881425 bytes, size after optimization: 2278867 bytesINFO [ Heim::Pipeline ] Storing component and optimized componentINFO [ Heim::Pipeline ] Stored component at ''INFO [ Heim::Pipeline ] Stored optimized component at ''INFO [ Heim::Pipeline ] Storing region statesINFO [ Heim::Pipeline ] Stored state for region(s) heim-localhost successfullyINFO [ Heim::Pipeline ] Creating and caching application(s)INFO [ Heim::Pipeline ] Creating and caching application(s) for region(s) heim-localhostINFO [ Heim::Pipeline ] Created application with hash 62fd854418968a7c0cc383e962382dfc8e2d420b7fa5a4d48c6058ebb8544a05 for region(s) heim-localhostINFO [ Heim::Pipeline ] Application has been deployed for region(s) heim-localhostINFO [ Heim::Pipeline ] Pipeline 'Deploy application' finished with status 'Success'INFO [ Heim::Deploy ] Heim deploy pipeline was successfulINFO [ Heim::Deploy ] Application is accaccessible at:INFO [ Heim::Deploy ] [GET] https://my-subdomain.cloud.heim.dev/myappINFO [ Heim::Deploy ] Written and deployed application `myapp`.And, in the heim runtime you will see something like this, if you started the runtime with the
--verboseflag:INFO WasmComponentHandler{app_id="localhost:00000000-0000-0000-0000-000000000000:00000000-0000-0000-0000-000000000000:myapp:bbcb756cbf72e572fd47f3c299f44e1d083522aaa2696c3b0b24653deb884d3c"uri=/myapp}:heim_runtime::services::handlers::wasm_component_handler: 48:app_id="localhost:00000000-0000-0000-0000-000000000000:00000000-0000-0000-0000-000000000000:myapp:bbcb756cbf72e572fd47f3c299f44e1d083522aaa2696c3b0b24653deb884d3c"uri=/myapp method=GETtrigger=Trigger {app_id: AppId("localhost:00000000-0000-0000-0000-000000000000:00000000-0000-0000-0000-000000000000:myapp:bbcb756cbf72e572fd47f3c299f44e1d083522aaa2696c3b0b24653deb884d3c"),path: "/myapp",method: "GET",function_target: None,hash: "",domain: "127.0.0.1"}The Heim runtime output above summarizes all the basic information about your application.
Now, we can make our specific Rust application a little bit easier to work with, by adding a couple of useful dependencies.
Add serde and serde_json to the
Cargo.tomlyou’ll find in the application folder. This will allow us to easily work with json:Cargo.toml[package]name = "myapp"version = "0.1.0"edition = "2021"[lib]crate-type = ["cdylib"][package.metadata.component]package = "myorg:myapp"proxy = false[dependencies]waki = { version = "0.5.0", features = ["json"] }serde = { version = "1.0.216", features = ["derive"] }serde_json = "1.0.133"# reduce wasm binary size[profile.release]lto = truestrip = "symbols"Let’s add an environment variable to our
component.toml, while we’re at it:component.tomlname = "myapp"version = "0.1.0"[commands]run = "wasmtime serve -S cli target/wasm32-wasip2/debug/myapp.wasm --addr=127.0.0.1:8080"run_production = "wasmtime serve -S cli target/wasm32-wasip2/release/myapp.wasm --addr=127.0.0.1:8080"[build.dev]build = "cargo build --target=wasm32-wasip2"wasm_path = "target/wasm32-wasip2/debug/myapp.wasm"[build.prod]build = "cargo build --target=wasm32-wasip2 --release"wasm_path = "target/wasm32-wasip2/release/myapp.wasm"[input.env]HELLO_MESSAGE = { type = "String" }While we’re at it we can change the
HTTP methodtoPOST, and set thepathto a new value. Furthermore, we’ll set a value to theHELLO_MESSAGEenvironment variable:application.tomlname = "myapp"component_target = 'myapp:0.1.0'[trigger.http]type = 'http'path = '/mypath'path = '/myapp'method = 'POST'method = 'GET'[env]HELLO_MESSAGE = "Hi"Finally, we’ll update the code to use the new environment variable, and modify our code to expect a JSON body, and return another JSON body:
src/lib.rsuse serde::{Deserialize, Serialize};use waki::{handler, ErrorCode, Request, Response};#[derive(Deserialize)]struct MyRequestBody {name: String,}#[derive(Serialize)]struct MyResponseBody {error: Option<String>,name: Option<String>,msg: Option<String>,}#[handler]fn hello(req: Request) -> Result<Response, ErrorCode> {let message = std::env::var("HELLO_MESSAGE").expect("HELLO_MESSAGE is not set");let body = match req.json::<MyRequestBody>() {Ok(b) => b,Err(_) => {return Response::builder().status_code(400).json(&MyResponseBody {error: Some("Missing request body".to_string()),name: None,msg: None}).build();},};Response::builder().status_code(200).json(&MyResponseBody {error: None,name: Some(body.name.clone()),msg: Some(format!("{} {}", message, body.name))}).body("Hello World").build()}Since the runtime is already running, we just need to build and deploy the application again, for our changes to take effect.
heim cli heim@system:~/repos$ heim deployINFO [ heim_cli::wasm::build ] Building Component: myappCompiling myapp v0.1.0 (/home/work/repos/myapp)...Finished `release` profile [optimized] target(s) in 0.05sINFO [ heim_registry::registry ] "myapp":"0.1.0":382c7a9e524efcc78f954ce0441933576d07974001bce9a36460ac32a94a5a8eINFO [ Heim::Deploy ] Heim application `myapp` is now built and written to registry.INFO [ Heim::Pipeline ] Starting pipeline 'Deploy application'INFO [ Heim::Pipeline ] Storing unoptimized component stateINFO [ Heim::Pipeline ] Checking if defined regions in app definition is validINFO [ Heim::Pipeline ] Continuing with localhost region heim-localhostINFO [ Heim::Pipeline ] Getting region specific application environment valuesINFO [ Heim::Pipeline ] Set environment values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting region specific application scaling valuesINFO [ Heim::Pipeline ] Set scaling values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting capabilitiesINFO [ Heim::Pipeline ] Set capabilities values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting triggersINFO [ Heim::Pipeline ] Set trigger values for region 'heim-localhost'INFO [ Heim::Pipeline ] Component environment values are valid for all regionsINFO [ Heim::Pipeline ] Checking for region with changes to buildINFO [ Heim::Pipeline ] Region "heim-localhost" has been changed and will be builtINFO [ Heim::Pipeline ] Storing component and optimized componentINFO [ Heim::Pipeline ] Stored component at ''INFO [ Heim::Pipeline ] Stored optimized component at ''INFO [ Heim::Pipeline ] Storing region statesINFO [ Heim::Pipeline ] Stored state for region(s) heim-localhost successfullyINFO [ Heim::Pipeline ] Creating and caching application(s)INFO [ Heim::Pipeline ] Creating and caching application(s) for region(s) heim-localhostINFO [ Heim::Pipeline ] Created application with hash db42889eeb46b4f4053adbf48239592c5a84e2c87ffe6d32f65d056f5d318c8e for region(s) heim-localhostINFO [ Heim::Pipeline ] Application has been deployed for region(s) heim-localhostINFO [ Heim::Pipeline ] Pipeline 'Deploy application' finished with status 'Success'INFO [ Heim::Deploy ] Heim deploy pipeline was successfulINFO [ Heim::Deploy ] Application is accaccessible at:INFO [ Heim::Deploy ] [POST] http://127.0.0.1:3000/mypathINFO [ Heim::Deploy ] Written and deployed application `myapp`.curl heim@system:~/repos$ curl http://127.0.0.1:3000/mypath -X POST{"error":"Missing request body","name":null,"msg":null}heim@system:~/repos$ curl http://127.0.0.1:3000/mypath -d '{ "name": "heim" }'{"error":null,"name":"heim","msg":"HI heim"}When we are done, we can use the shortcut
Ctrl+Cto shut down the runtime.To clean up any resources from the guide you can run
heim clear. This will remove all data from the cache.
Summary
Section titled “Summary”-
- run
heim new - select the rust-http
template - choose
HTTP method - choose trigger
path - set application
name
- run
-
- open the created application folder/project in your text editor
Take note of the configuration files:
-
- open
lib.rsin thesrcfolder:
- run
heim startto start the Heim runtime
- run
heim deployto build and deploy the application.
- run
heim deploy --cloudto deploy the application to the cloud instance.
- open
-
- edit the
Cargo.tomlfile to add useful dependencies - edit the
component.tomlfile to add environment variables - edit the
application.tomlfile to change the HTTP method - edit the
application.tomlfile to change the trigger path - edit the
application.tomlfile to set environment variable values - edit the
src/lib.rsfile to use new environment variables - edit the
src/lib.rsfile to set up return and accept values - deploy the application again to see your changes
- edit the
-
- use the
Ctrl+Cshortcut to shut down the Heim runtime - use the
heim clearcommand to remove all data from cache
- use the