Skip to main content

Wasmer based WebAssembly loader in JEE

Wasmer logo

Currently I'm experimenting a little bit with WASM and java. I found a java runtime from wasmer at https://github.com/wasmerio/wasmer-java. This acts as a JNI wrapper around the wasmer runtime. So this has to be installed on the execution node.

Combining it with quarkus, I created a solution, thats load some calculation functions provided in a WASM file on the classpath:

 

import java.io.InputStream;
import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;

import org.wasmer.Instance;


@ApplicationScoped
public class WasmBean implements Serializable{
public static String WASM = "calculator.wasm";
Instance instance = null;
public WasmBean() {
}

@PreDestroy
void preDestroy(){
instance.close();
}
@PostConstruct
void postConstruct() {
try {
InputStream instream = WasmBean.class.getClassLoader().getResourceAsStream(WASM);
// Reads the WebAssembly module as bytes.
byte[] wasmBytes = instream.readAllBytes();
// Instantiates the WebAssembly module.
instance = new Instance(wasmBytes);
} catch(Exception ex){
throw new RuntimeException(ex);
}
}

public Object[] invoke(String function, Object ... args) {

return instance.exports.getFunction(function).apply(args);
}
}
 
 

This can be used by a REST service afterwards as follows:

 

@GET
@Path("/add")
@Produces(MediaType.TEXT_PLAIN)
public String add(@QueryParam("a") int first, @QueryParam("b") int second) {
LOG.info("call"+first +"+"+second);
Object[] results =bean.invoke("add", first, second);
StringBuilder b = new StringBuilder();
for (Object o : results) {
b.append(o.toString());
}
return b.toString();
}


 

Since WASM modules can be created from several origins, not only Rust and C, but also COBOL (https://github.com/cloudflare/cobweb), this enables secure reuse of existing old function libraries via WASM modules...

 

The complete source code can be found at https://github.com/hurzelpurzel/wasm-experiments.git


 


Comments