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

feat: module for Polyglot Context injection #15

Open
wants to merge 1 commit into
base: 1.0.x
Choose a base branch
from
Open
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
22 changes: 22 additions & 0 deletions graal-languages-core/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
plugins {
id("io.micronaut.build.internal.graal-languages-module")
}
dependencies {
api(libs.managed.graal.polyglot)
implementation(mn.micronaut.context)
testRuntimeOnly(libs.managed.graal.js)
testImplementation(mn.micronaut.http.server.netty)
testImplementation(mn.micronaut.jackson.databind)
testImplementation(mn.micronaut.http.client)
testAnnotationProcessor(mn.micronaut.inject.java)
testImplementation(mnTest.micronaut.test.junit5)
testRuntimeOnly(libs.junit.jupiter.engine)
}
tasks.withType<Test> {
useJUnitPlatform()
}
micronautBuild {
binaryCompatibility {
enabled.set(false)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright 2017-2024 original 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
*
* https://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.
*/
package io.micronaut.graallanguages;

import io.micronaut.context.annotation.Factory;
import io.micronaut.core.annotation.Internal;
import io.micronaut.runtime.context.scope.ThreadLocal;
import jakarta.inject.Singleton;
import org.graalvm.polyglot.Context;

@Internal
@Factory
class ContextFactory {
@Singleton
Context.Builder createContextBuilder() {
return Context.newBuilder();
}

@ThreadLocal
ContextProvider createContext(Context.Builder builder) {
ContextProvider contextProvider = new ContextProvider();
contextProvider.setContext(builder.build());
return contextProvider;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright 2017-2024 original 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
*
* https://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.
*/
package io.micronaut.graallanguages;

import io.micronaut.core.annotation.Experimental;
import org.graalvm.polyglot.Context;

/**
* Wrapper around {@link Context} since it is a final class and cannot be proxied after its instantiation in a factory.
* @author Sergio del Amo
* @since 1.1.0
*/
@Experimental
public class ContextProvider {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to the comments on the PR, contexts should be pooled.
The best would be to have something like:

<R> R useContext(Function<Context, R> fn);

With the implementation:

  • get the context from the pool
  • invoke lambda
  • return the context to the pool
  • return the lambda result

WDYT @steve-s @mikehearn ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks nice. There is still one issue: you can get Java objects that wrap JavaScript/Python/... objects that are associated with given context. Example:

Value fun = useContext(ctx -> ctx.eval("js", "x => x + 1"));
fun.execute(42); // <-- this will execute the function in the `Context` where it originated from

thinking about this, I am not sure there can ever be some "compile-time safety net" for this, users will have to understand the constraints and make sure they do not hold onto Value instances from the Context outside of the lambda.

@mikehearn used try-with-resources for his Context pool (but that doesn't solve this issue either).

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Techically we can check what type is being returned from the method, but that would have to be an implementation specific check

Copy link
Contributor

@steve-s steve-s Sep 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Side note: it is even trickier with the proxy feature:

Value pythonClassInstance = ctx.eval("python", """
   class MyPythonClass:
      def foo(x): return x+1

   MyPythonClass() # create instance
""")

MyJavaInterface javaProxy = pythonClassInstance.as(MyJavaInterface.class);
// now javaProxy looks like plain Java object, but internally it is backed by `Value`

assert javaProxy.foo(42) == 43 // evaluates Python function "foo" in the Context ctx

private Context context;

/**
* Empty Constructor.
*/
public ContextProvider() {
}

/**
*
* @param context Graal Languages {@link Context}
*/
public void setContext(Context context) {
this.context = context;
}

/**
*
* @return Graal Languages {@link Context}
*/
public Context getContext() {
return context;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package io.micronaut.graallanguages.core;

import io.micronaut.context.annotation.Property;
import io.micronaut.context.annotation.Requires;
import io.micronaut.graallanguages.ContextProvider;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Produces;
import org.graalvm.polyglot.Value;

@Requires(property = "spec.name", value = "HomeControllerTest")
//tag::controller[]
@Controller
public class HomeController {
private final ContextProvider contextProvider;

HomeController(ContextProvider contextProvider) {
this.contextProvider = contextProvider;
}

@Produces(MediaType.TEXT_PLAIN)
@Get
HttpResponse<String> index() {
Value f = contextProvider.getContext().eval("js", "x => x + 1");
if (f.canExecute()) {
return HttpResponse.ok("" + f.execute(41).asInt());
}
return HttpResponse.serverError();
}
}
//end::controller[]
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package io.micronaut.graallanguages.core;

import io.micronaut.context.annotation.Property;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.MediaType;
import io.micronaut.http.client.BlockingHttpClient;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

@Property(name = "spec.name", value = "HomeControllerTest")
@MicronautTest
class HomeControllerTest {

@Test
void jsembedding(@Client("/") HttpClient httpClient) {
BlockingHttpClient client = httpClient.toBlocking();
HttpRequest<?> request = HttpRequest.GET("/").accept(MediaType.TEXT_PLAIN_TYPE);
assertEquals("42", client.retrieve(request));
}
}
2 changes: 2 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ micronaut-test = { module = "io.micronaut.test:micronaut-test-bom", version.ref
junit-jupiter-api = { module = "org.junit.jupiter:junit-jupiter-api" }
junit-jupiter-engine = { module = "org.junit.jupiter:junit-jupiter-engine" }

managed-graal-js = { module = 'org.graalvm.js:js', version.ref = 'managed-graalpy' }
managed-graal-polyglot = { module = 'org.graalvm.polyglot:polyglot', version.ref = 'managed-graalpy' }
managed-graalpy = { module = 'org.graalvm.python:python', version.ref = 'managed-graalpy' }
managed-graalpy-embedding = { module = 'org.graalvm.python:python-embedding', version.ref = 'managed-graalpy' }

1 change: 1 addition & 0 deletions settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ rootProject.name = 'micronaut-graal-languages'

include 'graalpy'
include 'graal-languages-bom'
include 'graal-languages-core'
include 'test-suite-graalpy'

enableFeaturePreview 'TYPESAFE_PROJECT_ACCESSORS'
Expand Down
11 changes: 11 additions & 0 deletions src/main/docs/guide/embedding.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
You can embed https://www.graalvm.org/latest/reference-manual/languages/[Graal Languages] in your application. For example, to embed Javascript you could add the following dependencies:

dependency:io.micronaut.micronaut-graal-languages:micronaut-graal-languages-core[scope=compile]

dependency:org.graalvm.js:js[scope=runtime]

[source,java]
.src/main/java/example/micronaut/HomeController.java
----
include::{sourceDir}/graal-languages-core/src/test/java/io/micronaut/graallanguages/core/HomeController.java[tag=controller, indent=0]
----
1 change: 1 addition & 0 deletions src/main/docs/guide/toc.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
introduction: Introduction
releaseHistory: Release History
embedding: Embedding Graal Languages
graalPy:
title: GraalPy
gettingStarted: Getting Started
Expand Down
Loading