Functions
Purpose
Section titled “Purpose”A function pod is a pod whose logic fits into one function. actor4j-functions extends this idea by a context. The function gets a FunctionPodContext with access to the host actor, the PodContext and four optional services:
| Service | Created by (override in the pod) | Access in the function | Operations |
|---|---|---|---|
StateStore<K, V> |
createStateStore(ctx) |
ctx.stateStore() |
a Cache<K, V>: get, put, containsKey, compareAndSet, remove, clear, evict, … |
AsyncStreams |
createStreams(ctx) |
ctx.streams() |
publish(topic, value), subscribe(topic), unsubscribe(topic) |
AsyncQueryRequest |
createQueryRequest(ctx) |
ctx.queryRequest() |
execute(value), returns an Object (e.g. a request id) |
AsyncIORequest |
createIORequest(ctx) |
ctx.ioRequest() |
execute(value, interaction) |
The services are thin wrappers around a handler (AsyncStreamsHandler, AsyncQueryRequestHandler, AsyncIORequestHandler) or a Cache. The pod decides how they are implemented, e.g. streams via a broker actor or queries via GraphQL. A service that is not created stays null in the context.
Relation to Actor4j - Core
Section titled “Relation to Actor4j - Core”Actor4j - Core already contains a simple function pod (see Example: Function Pod). actor4j-functions uses the same mechanism: the same Reply (io.actor4j.core.utils) and the same proxy handlers of the core, which call the function and send the answer back. The classes have the same names, but different packages and factory methods:
| Actor4j - Core | actor4j-functions | |
|---|---|---|
| Package | io.actor4j.core.pods.functions |
io.actor4j.functions.pods |
| Factory method | createFunction(ActorRef host, PodContext context) |
createPodFunction(FunctionPodContext ctx) |
| Function | new PodFunction(host, context) |
new PodFunction(ctx) |
| Remote variant | RemoteFunctionPod |
RemoteFunctionPod with createPodRemoteFunction(ctx) |
| Services, hooks | none | see above, preStart, postStop, isExposed |
Maven Dependency
Section titled “Maven Dependency”<dependency> <groupId>io.actor4j</groupId> <artifactId>actor4j-functions</artifactId> <version>2.5.0</version></dependency>The module only depends on actor4j-core-sdk. The application adds the runtime of its choice (e.g. actor4j-core-runtime).
Example: State Store and Streams
Section titled “Example: State Store and Streams”The example is based on the tests of the module. The pod keeps a counter in the state store and subscribes to a topic of a broker actor (BrokerActor, Publish and Subscribe from actor4j-data, registered under the alias broker). Each published value increments the counter, and the new value is published to a second topic.
public class CounterFunctionPod extends FunctionPod { @Override public String domain() { return "CounterFunctionPod"; }
@Override public StateStore<?, ?> createStateStore(FunctionPodContext ctx) { return new StateStore<String, Integer>(new CacheAsMap<>()); }
@Override public AsyncStreams createStreams(FunctionPodContext ctx) { return new AsyncStreams(new AsyncStreamsHandler() { @Override public void publish(String topic, Object value) { ctx.host().sendViaAlias( ActorMessage.create(new Publish<Object>(topic, value), 0, ctx.host().self(), null), "broker"); }
@Override public void subscribe(String topic) { ctx.host().sendViaAlias( ActorMessage.create(new Subscribe(topic), 0, ctx.host().self(), null), "broker"); }
@Override public void unsubscribe(String topic) { ctx.host().sendViaAlias( ActorMessage.create(new Unsubscribe(topic), 0, ctx.host().self(), null), "broker"); } }); }
@Override public void preStart(FunctionPodContext ctx) { ctx.stateStore().put("counter", 0); ctx.streams().subscribe("counter_in"); }
@Override public PodFunction createPodFunction(FunctionPodContext ctx) { return new PodFunction(ctx) { @Override public Reply handle(ActorMessage<?> message, UUID interaction, boolean replyAllowed) { StateStore<String, Integer> stateStore = ctx.stateStore(); stateStore.put("counter", stateStore.get("counter")+1); ctx.streams().publish("counter_out", stateStore.get("counter"));
return Reply.none(); } }; }}Deployment and use as for every pod:
ActorSystem system = ActorSystem.create(ActorRuntime.factory(), ActorSystemConfig.builder().serverMode().build());
ActorId broker = system.addActor(() -> new BrokerActor());system.setAlias(broker, "broker");
system.deployPods(() -> new CounterFunctionPod(), new PodDeployment(1, 1));ActorId subscriber = system.addActor(() -> new Actor() { @Override public void receive(ActorMessage<?> message) { if (message.value() instanceof Publish<?> p) System.out.println(p.topic() + ": " + p.value()); }});system.start();
system.send(ActorMessage.create(new Subscribe("counter_out"), 0, subscriber, broker));system.send(ActorMessage.create(new Publish<Integer>("counter_in", 1), 0, null, broker));Asynchronous Replies
Section titled “Asynchronous Replies”The function returns a Reply. Reply.of(value, tag) answers directly, Reply.none() sends no answer. For asynchronous work, the function returns Reply.pending(). The pod then remembers the request under its interaction. Later, the result arrives as a new message at the pod, and the function returns Reply.of(value, tag, interaction) with the interaction of the request. The answer goes to the sender of the original request.
In the example, the I/O request runs in another thread and sends the result back to the pod (tag 1):
public class WeatherFunctionPod extends FunctionPod { @Override public String domain() { return "WeatherFunctionPod"; }
@Override public AsyncIORequest createIORequest(FunctionPodContext ctx) { return AsyncIORequest.create((value, interaction) -> CompletableFuture.supplyAsync(() -> "sunny in " + value) .thenAccept(result -> ctx.host().getSystem().send(ActorMessage.create( result, 1, ctx.host().getSystem().SYSTEM_ID(), ctx.host().getId(), interaction)))); }
@Override public PodFunction createPodFunction(FunctionPodContext ctx) { return new PodFunction(ctx) { @Override public Reply handle(ActorMessage<?> message, UUID interaction, boolean replyAllowed) { if (message.tag()==0) { // request of a client ctx.ioRequest().execute(message.value(), interaction); return Reply.pending(); } else // tag 1: result of the I/O request return Reply.of(message.value(), 42, interaction); } }; }}
// client request with its own interactionsystem.sendViaAlias(ActorMessage.create("Berlin", 0, client, null, UUID.randomUUID()), "WeatherFunctionPod");The handlers of the services may be called from other threads (here the thread of the CompletableFuture). They should only send messages, e.g. via ctx.host().getSystem().send(...), and not change the state of the pod. handleQueryRequest and handleIoRequest of PodFunction are not called by the pod itself. They can be called from handle to separate the results of queries and I/O requests from the requests of clients.
Remote Function Pods
Section titled “Remote Function Pods”For requests from outside the actor system (see Remote Pods), RemoteFunctionPod is extended and createPodRemoteFunction returns a PodRemoteFunction. It handles remote requests (RemotePodMessage) and local messages in two methods. The services and hooks are the same as in FunctionPod.
public class ExampleRemoteFunctionPod extends RemoteFunctionPod { @Override public String domain() { return "ExampleRemoteFunctionPod"; }
@Override public PodRemoteFunction createPodRemoteFunction(FunctionPodContext ctx) { return new PodRemoteFunction(ctx) { @Override public Reply handle(RemotePodMessage remoteMessage, UUID interaction, boolean replyExpected) { return Reply.of("Hello " + remoteMessage.remotePodMessageDTO().payload() + "!", 42); }
@Override public Reply handle(ActorMessage<?> message, UUID interaction, boolean replyAllowed) { return Reply.of("Hello " + message.value() + "!", 42); } }; }}The answer to a remote request is passed to the InternalServerCallback of the runtime configuration, if the request expects a reply. If the function returns Reply.none() for such a request, the client gets the status PodStatus.CONFLICT.
preStart(ctx)andpostStop(ctx)are called when the pod actor starts and stops. The services are already created inpreStart.isExposed()(defaulttrue) makes the pod actor reachable from outside with its global id.- The pod actor is registered under the alias
domain(), for sharded pods underdomain()plus the shard id.
Known Limitations
Section titled “Known Limitations”- Pending requests are kept in the pod actor. If the pod actor is restarted by the supervision (e.g. after an exception in
handle), they are lost. A result that arrives afterwards is sent to the sender of the result instead of the client. - Pending requests have no timeout. If no result arrives, the client gets no answer.
- The answer carries the
interactionof the request. Asynchronous requests should therefore be sent with aninteraction, otherwise the client cannot assign the answers.