Create a function with WebAssembly
Compile and instantiate a WebAssembly module inside a function, from a byte array in the code or from a .wasm file the handler fetches.
A function compiles and instantiates a WebAssembly module with the WebAssembly API, inside the handler. Azion Runtime provides that API with the interface MDN defines. For the static methods and constructors it carries, refer to WebAssembly.
The steps below use Azion Console. The module on this page exports one operation, increment, and the handler returns its result in the response body. The module bytes reach the handler in two ways: as a byte array in the function code, or as a .wasm file the handler fetches over HTTP.
Prerequisites
- An Azion account. To create one, refer to How to create an account on Azion.
- The Edit Functions permission on the account. It grants permission to create, edit, and remove functions, and it also requires the permission View Functions. Refer to Teams Permissions.
Create the function with an embedded module
The wasmCode array holds the module, so the handler compiles it without a network request. To create the function:
Access Azion Console > Products Menu > Libraries > Functions.
Enter a name for the function. For example: wasm-increment.
In the Code tab, paste the following code:
The function is saved and available to instantiate on an application.
The wasmCode array is the binary form of the following WAT module, which adds 1 to its i32 parameter and returns the result:
A byte array is part of the function source code, so the module counts toward the code size limit: 6 MB in Azion Console, and 20 MB through the Azion API. Refer to Functions limits.
Load the module from a URL
A handler reads the module bytes over HTTP instead of carrying them. Replace the byte array with a fetch call, and pass the response body to WebAssembly.instantiate():
The handler compiles whatever the URL returns, so a new build of the module reaches the function without a code change. Each fetch call counts as a sub-request, and an invocation makes at most 50 of them. Refer to Functions limits.
Verify the response
A function runs only after a function instance binds it to an application, and a Rules Engine rule selects that instance. To build that chain, refer to Functions quickstart.
To read the response, request the URI set in the rule:
The module increments the default value, 0:
The handler reads the value request header when the request carries one. To increment a different integer, send it in that header:
The response body carries the result the WebAssembly module computed.