Skip to content

Polyglot

actor4j-polyglot runs the logic of a pod as a script in another language. A PolyglotFunctionPod is a function pod whose function is a JavaScript or Python script. The script is executed with GraalVM Polyglot inside the pod actor. It receives the incoming message and an API to send messages and to log, and its return value becomes the reply to the client.

This allows, for example, business rules or small transformations to be written in a scripting language while deployment, replication, sharding and addressing are handled by Actor4j.

PolyglotFunctionPod extends ActorPod of Actor4j - Core and behaves like a FunctionPod. It is deployed with PodDeployment, addressed via its domain as alias, and can be replicated and sharded (a shard gets the alias domain + shardId). Pods, function pods, Reply and PodDeployment are described in Pods and are not repeated here.

Artifact Content
actor4j-polyglot-api ActorPolyglotAPI and ActorPolyglotMessage (the objects a script sees), mappers from GraalVM Value to Java and to JSON
actor4j-polyglot-pod PolyglotFunctionPod, state store, streams and query services for scripts
actor4j-polyglot-js GraalVM JavaScript (dependency only, packaging pom)
actor4j-polyglot-python GraalVM Python (dependency only, packaging pom)
actor4j-polyglot-java GraalVM Java (Espresso), not yet integrated
actor4j-polyglot-wasm GraalVM WebAssembly, not yet integrated

actor4j-polyglot depends on Actor4j - Core 2.5.0. As long as this version is not on Maven Central, install actor4j-core from source first, then actor4j (both with mvn install). Java 21 or newer is required.

Add the pod module and at least one language module. The language modules are POM modules, so they must be included with <type>pom</type>:

<dependency>
<groupId>io.actor4j</groupId>
<artifactId>actor4j-polyglot-pod</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.actor4j</groupId>
<artifactId>actor4j-polyglot-js</artifactId> <!-- or actor4j-polyglot-python -->
<version>2.5.0</version>
<type>pom</type>
</dependency>
  • GraalVM Polyglot: the languages come as regular Maven dependencies (GraalVM Polyglot 25.0.3), a GraalVM JDK is not needed. Do not repackage them into a fat jar. Truffle needs its original jars (multi-release) on the class path or module path.
  • Runtime: an application also needs a runtime of Actor4j - Core, e.g. actor4j-core-runtime (see SDK and Runtimes).
  • JSON: the result of a script is mapped to JsonObject or JsonArray of Actor4j - Core. This needs a JSON implementation on the class path, e.g. actor4j-dataformat-json-org (or -json-jackson, -json-vertx).
<dependency>
<groupId>io.actor4j</groupId>
<artifactId>actor4j-core-runtime</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.actor4j</groupId>
<artifactId>actor4j-dataformat-json-org</artifactId>
<version>2.5.0</version>
</dependency>

A polyglot pod defines its domain, the language (PolyglotContext.LANGUAGE_ID_JS or LANGUAGE_ID_PYTHON) and the script. The script must define a function execute(api, message).

public class HelloScriptPod extends PolyglotFunctionPod {
@Override
public String domain() {
return "HelloScriptPod";
}
@Override
public String languageId() {
return PolyglotContext.LANGUAGE_ID_JS;
}
@Override
public CharSequence script() {
return """
function execute(api, message) {
api.info(message.value());
return {value: "Hello " + message.value() + "!", tag: 42};
}
""";
}
}

The pod is deployed and addressed like any other pod:

ActorSystem system = ActorSystem.create(ActorRuntime.factory(), ActorSystemConfig.builder().serverMode().build());
system.deployPods(() -> new HelloScriptPod(), new PodDeployment(1, 1));
ActorId client = system.addActor(() -> new Actor() {
@Override
public void receive(ActorMessage<?> message) {
// tag 42, value {"value":"Hello Test!","tag":42}
System.out.println(message.tag() + " " + message.valueAsJsonObject());
}
});
system.start();
system.sendViaAlias(ActorMessage.create("Test", 0, client, null), "HelloScriptPod");

The same pod in Python. Only the language and the script change:

public class HelloPythonPod extends PolyglotFunctionPod {
@Override
public String domain() {
return "HelloPythonPod";
}
@Override
public String languageId() {
return PolyglotContext.LANGUAGE_ID_PYTHON;
}
@Override
public CharSequence script() {
return """
def execute(api, message):
api.info(message.value())
return {"value": "Hello Test!", "tag": 42}
""";
}
}

The return value of execute becomes the reply to the sender of the message:

Return value Reply
object (JS) or dict (Python) JsonObject with all fields, the field tag sets the tag of the reply (default 0)
array (JS) or list (Python) JsonArray, tag 0
string, number, boolean the value itself, tag 0
nothing (undefined, None) no reply

The whole object is the value of the reply, including the field tag. A negative tag sends no reply (-1 marks the reply as pending, see Reply). If the script throws an exception, the reply is {"error": "<message>"} with tag 0.

api is an ActorPolyglotAPI:

Method Meaning
send(value, tag, interaction, globalId[, protocol]) sends value to an actor by its global id (string), also as sendViaGlobalId(...)
send(value, tag, interaction, routeId[, protocol]) sends value to a route (number), also as sendViaRouteId(...)
error(msg), warn(msg), info(msg), debug(msg), trace(msg) logging via the logger of Actor4j

interaction may be null. The value is mapped to JSON before it is sent.

message is an ActorPolyglotMessage:

Method Meaning
value(), tag(), interaction(), protocol(), domain() the fields of the incoming message
source(), dest() route ids of sender and receiver (-1 and -2), usable with api.send
sourceAsGlobalId(), destAsGlobalId() global ids of sender and receiver as strings

The following JavaScript sends an additional message back to the sender before it replies:

function execute(api, message) {
api.send({value: "Hello again!"}, 99, null, message.source());
return {value: "Hello Test!", tag: 42};
}

Further routes for api.send are registered in the pod with registerRoutes(Map<Long, ActorId> routes) (the ids -1 and -2 are reserved for sender and receiver). With filter(ActorMessage<?> message), the pod can transform a message before the script sees it, e.g. convert an ActorId into its global id as string:

@Override
public ActorMessage<?> filter(ActorMessage<?> message) {
return ((ActorMessage<String>)message).shallowCopy(message.valueAsId().globalId().toString());
}

Each pod actor has its own GraalVM context (sharing one engine). The context is restricted: no file or network I/O, no threads, no native access, no lookup of host classes and no access to other languages. Of Java objects, a script sees only the methods annotated with @Export (e.g. those of api and message). Pass values to scripts as strings, numbers, booleans, or convert them with filter.

Like a function pod, a polyglot pod can offer services to its script. They are created by overriding createStateStore, createStreams or createQueryRequest and are passed to execute as additional arguments, in this order: execute(api, message[, state][, queryRequest][, streams]). Only the services that exist are passed. preStart(PolyglotContext) and postStop(PolyglotContext) are called when the pod actor starts and stops.

PolyglotStateStore wraps a Cache<Object, Object> of Actor4j - Core, e.g. CacheAsMap. The state lives on the Java side and survives between messages.

public class CounterScriptPod extends PolyglotFunctionPod {
@Override
public String domain() {
return "CounterScriptPod";
}
@Override
public String languageId() {
return PolyglotContext.LANGUAGE_ID_JS;
}
@Override
public PolyglotStateStore createStateStore(PolyglotContext contextPolyglot) {
return new PolyglotStateStore(new CacheAsMap<>());
}
@Override
public void preStart(PolyglotContext contextPolyglot) {
contextPolyglot.stateStore().put("counter", 0);
}
@Override
public CharSequence script() {
return """
function execute(api, message, state) {
state.put("counter", state.get("counter")+1);
return {value: "Hello Test!", tag: state.get("counter")};
}
""";
}
}

PolyglotStreams delegates publish(topic, value), subscribe(topic) and unsubscribe(topic) to a PolyglotStreamsHandler. How topics are realized is up to the handler, e.g. with the BrokerActor of actor4j-data:

@Override
public PolyglotStreams createStreams(PolyglotContext contextPolyglot) {
return new PolyglotStreams(new PolyglotStreamsHandler() {
@Override
public void publish(String topic, Value value) {
contextPolyglot.api().host().sendViaAlias(
ActorMessage.create(new Publish<Object>(topic, ValueMapper.convertValue(value)), 0,
contextPolyglot.api().host().self(), null),
"broker");
}
@Override
public void subscribe(String topic) {
contextPolyglot.api().host().sendViaAlias(
ActorMessage.create(new Subscribe(topic), 0, contextPolyglot.api().host().self(), null),
"broker");
}
@Override
public void unsubscribe(String topic) {
// ...
}
});
}

In the script, streams.publish("MyTopic_out", value) publishes a value. Messages of a subscribed topic arrive at the pod and execute the script like any other message.

PolyglotQueryRequest delegates execute(value) to a PolyglotQueryRequestHandler (Value execute(Value value)). The script calls queryRequest.execute({...}), the handler converts the value (e.g. with ValueMapper.convertValue) and runs the query, e.g. against a GraphQL schema of actor4j-query-graphql.

The module is a preview. Known limitations of the current state:

  • The script is evaluated again for each message in the same context. In JavaScript, const, let or class on top level fail from the second message on. Top-level variables are reset with every message. Declare only functions on top level and keep state in the state store.
  • Python: nested dicts in a result are not mapped correctly (only the outer dict is). The Python wrapper passes only api and message, so state store, streams and query are not yet available for Python scripts.
  • Errors arrive at the client as a normal reply {"error": ...} with tag 0.
  • sourceAsGlobalId() and destAsGlobalId() fail for a message without sender or receiver.
  • replyAllowed (NO_REPLY) is not yet passed to the script. There is no remote variant of the polyglot pod yet, and PolyglotIORequest is not yet wired into the script.
  • Java (Espresso) and WebAssembly are not yet integrated. Only js and python are supported as languageId.
  • Each pod actor has its own GraalVM context. With many replicas or shards, this costs memory, especially for Python.