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

Add a Quarkus REST service example #46

Closed
wants to merge 4 commits into from
Closed
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
1 change: 1 addition & 0 deletions examples/jbang/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
example
3 changes: 3 additions & 0 deletions examples/jbang/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#! /bin/bash

jbang export native --force example.java
1 change: 1 addition & 0 deletions examples/jbang/demo-rust/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.wasm
6 changes: 6 additions & 0 deletions examples/jbang/demo-rust/compile.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#! /bin/bash
set -euxo pipefail

# rustup target add wasm32-unknown-unknown

rustc $1.rs --target=wasm32-unknown-unknown --crate-type=cdylib -C opt-level=0 -C debuginfo=0 -o $1.wasm
23 changes: 23 additions & 0 deletions examples/jbang/demo-rust/count.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use std::mem;
use std::slice;
use std::str;

#[no_mangle]
pub extern "C" fn alloc(len: i32) -> *const u8 {
let mut buf = Vec::with_capacity(len as usize);
let ptr = buf.as_mut_ptr();
// tell Rust not to clean this up
mem::forget(buf);
ptr
}

#[no_mangle]
pub extern fn count(ptr: i32, len: i32) -> i32 {
let bytes = unsafe { slice::from_raw_parts(ptr as *const u8, len as usize) };
let s = str::from_utf8(bytes).unwrap();
let mut count: i32 = 0;
for ch in s.chars() {
count += 1;
}
count
}
27 changes: 27 additions & 0 deletions examples/jbang/demo-rust/count_vowels.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const VOWELS: &[char] = &['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'];

use std::mem;
use std::slice;
use std::str;

#[no_mangle]
pub extern "C" fn alloc(len: i32) -> *const u8 {
let mut buf = Vec::with_capacity(len as usize);
let ptr = buf.as_mut_ptr();
// tell Rust not to clean this up
mem::forget(buf);
ptr
}

#[no_mangle]
pub extern fn count(ptr: i32, len: i32) -> i32 {
let bytes = unsafe { slice::from_raw_parts(ptr as *const u8, len as usize) };
let s = str::from_utf8(bytes).unwrap();
let mut count: i32 = 0;
for ch in s.chars() {
if VOWELS.contains(&ch) {
count += 1;
}
}
count
}
Binary file added examples/jbang/demo.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
29 changes: 29 additions & 0 deletions examples/jbang/example.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
///usr/bin/env jbang "$0" "$@" ; exit $?

//DEPS com.dylibso.chicory:wasm:1.0-SNAPSHOT
//DEPS com.dylibso.chicory:runtime:1.0-SNAPSHOT

import static java.lang.System.*;

import com.dylibso.chicory.runtime.Module;
import com.dylibso.chicory.wasm.types.Value;

public class example {

public static void main(String... args) {
if (args.length != 2) {
err.println("Please pass as argument a wasm file and a sentence");
}

var instance = Module.build(args[0]).instantiate();
var alloc = instance.getExport("alloc");
var countVowels = instance.getExport("count");
var memory = instance.getMemory();
var len = args[1].getBytes().length;
var ptr = alloc.apply(Value.i32(len)).asInt();
memory.put(ptr, args[1]);
var result = countVowels.apply(Value.i32(ptr), Value.i32(len));

out.println("Count is: " + result.asInt());
}
}
2 changes: 2 additions & 0 deletions examples/quarkus/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.idea
target
37 changes: 37 additions & 0 deletions examples/quarkus/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Eclipse
.project
.classpath
.settings/
bin/

# IntelliJ
.idea
*.ipr
*.iml
*.iws

# NetBeans
nb-configuration.xml

# Visual Studio Code
.vscode

# OSX
.DS_Store

# Vim
*.swp
*.swo

# patch
*.orig
*.rej

# Maven
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
release.properties

lib/*.jar
117 changes: 117 additions & 0 deletions examples/quarkus/.mvn/wrapper/MavenWrapperDownloader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;

public class MavenWrapperDownloader {

private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";

/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";

/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";

/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";

public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());

// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);

File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}

private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}

}
Binary file added examples/quarkus/.mvn/wrapper/maven-wrapper.jar
Binary file not shown.
2 changes: 2 additions & 0 deletions examples/quarkus/.mvn/wrapper/maven-wrapper.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
38 changes: 38 additions & 0 deletions examples/quarkus/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@

# Quarkus integration example

## Build

To build the container image run:

```
./build-docker.sh
```

## Run

Run with docker:

```
docker run --rm -it -p 8080:8080 docker.io/andreatp/chicory-demo
```

Compile the rust demo program:

```
(cd demo-rust && ./compile.sh)
```

You can now use the minimal UI available at: http://localhost:8080

Or use curl to send the program to the Quarkus application:

```
curl -v 'http://localhost:8080/wasm' -H 'Content-Type: application/octet-stream' --data-binary @demo-rust/main.wasm
```

and now the server can process with the WASM code your requests:

```
curl -v 'http://localhost:8080/compute' -H 'Content-Type: application/json' --data-raw '{"content": "foo"}'
```
8 changes: 8 additions & 0 deletions examples/quarkus/build-docker.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#! /bin/bash
set -euxo pipefail

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

$SCRIPT_DIR/copy-libs.sh

docker build -f $SCRIPT_DIR/src/main/docker/Dockerfile.native-scratch -t andreatp/chicory-demo $SCRIPT_DIR
7 changes: 7 additions & 0 deletions examples/quarkus/copy-libs.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#! /bin/bash
set -euxo pipefail

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

cp $SCRIPT_DIR/../../wasm/target/wasm-1.0-SNAPSHOT.jar lib/wasm.jar
cp $SCRIPT_DIR/../../runtime/target/runtime-1.0-SNAPSHOT.jar lib/runtime.jar
1 change: 1 addition & 0 deletions examples/quarkus/demo-rust/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.wasm
6 changes: 6 additions & 0 deletions examples/quarkus/demo-rust/compile.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#! /bin/bash
set -euxo pipefail

# rustup target add wasm32-unknown-unknown

rustc main.rs --target=wasm32-unknown-unknown --crate-type=cdylib -C opt-level=0 -C debuginfo=0 -o main.wasm
38 changes: 38 additions & 0 deletions examples/quarkus/demo-rust/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const VOWELS: &[char] = &['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'];

use std::mem;
use std::slice;
use std::str;

#[no_mangle]
pub extern "C" fn alloc(len: i32) -> *const u8 {
let mut buf = Vec::with_capacity(len as usize);
let ptr = buf.as_mut_ptr();
// tell Rust not to clean this up
mem::forget(buf);
ptr
}

#[no_mangle]
pub extern fn count(ptr: i32, len: i32) -> i32 {
let bytes = unsafe { slice::from_raw_parts(ptr as *const u8, len as usize) };
let s = str::from_utf8(bytes).unwrap();
let mut count: i32 = 0;
for ch in s.chars() {
if VOWELS.contains(&ch) {
count += 1;
}
}
count
}

// #[no_mangle]
// pub extern fn count(ptr: i32, len: i32) -> i32 {
// let bytes = unsafe { slice::from_raw_parts(ptr as *const u8, len as usize) };
// let s = str::from_utf8(bytes).unwrap();
// let mut count: i32 = 0;
// for ch in s.chars() {
// count += 1;
// }
// count
// }
Empty file added examples/quarkus/lib/.git-keep
Empty file.
Loading
Loading