Skip to content

Commit

Permalink
feat(worker): context is available for scripting
Browse files Browse the repository at this point in the history
* the context contains the current job and the Zeebe client
* get rid of Spring Boot
  • Loading branch information
saig0 committed Dec 21, 2018
1 parent 5f913a0 commit 56ab5a9
Show file tree
Hide file tree
Showing 8 changed files with 268 additions and 58 deletions.
13 changes: 6 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
# zeebe-script-worker

This is a Zeebe worker to evaluate scripts. Scripts are useful to create/modify the payload, to do (simple) calculations or for prototyping.
A Zeebe worker to evaluate scripts. Scripts are useful to create/modify the payload, to do (simple) calculations or for prototyping.

* the worker is registered for the type `script`
* required custom headers:
* `language` (String) - the name of the script language
* `script` (String) - the script to evaluate
* output payload contains `result` - the result of the evaluation
* available context in script:
* `job` (ActivatedJob) - the current job
* `zeebeClient` (ZeebeClient) - the client of the worker

Available script languages:
* javascript (Oracle Nashorn)
* [groovy](http://groovy-lang.org/)
* [feel](https://github.com/camunda/feel-scala)

_This is a community project meant for playing around with Zeebe. It is not officially supported by the Zeebe Team (i.e. no gurantees). Everybody is invited to contribute!_

## Usage

The service task:
Expand Down Expand Up @@ -55,11 +56,9 @@ Execute the JAR file via

## How to configure

The worker can be configured via environment variables or a properties file `application.properties`.
You can set the following environment variables to configure the worker.

```
zeebe.client.broker.contactPoint=127.0.0.1:26500
```
* `zeebe.client.broker.contactPoint`- default: `127.0.0.1:26500`

## Examples
Some examples for common use cases:
Expand Down
58 changes: 40 additions & 18 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<name>Zeebe Script Worker</name>
Expand Down Expand Up @@ -38,13 +40,6 @@
<scope>import</scope>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.0.3.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

Expand All @@ -55,11 +50,6 @@
<artifactId>zeebe-client-java</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<!-- script languages -->
<dependency>
<groupId>org.codehaus.groovy</groupId>
Expand All @@ -73,11 +63,25 @@
<version>${version.feel}</version>
</dependency>

<!-- logging -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.1</version>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.11.1</version>
</dependency>

<!-- test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
<version>4.12</version>
</dependency>

<dependency>
Expand All @@ -87,25 +91,43 @@
<scope>test</scope>
</dependency>

<dependency>
<groupId>io.zeebe</groupId>
<artifactId>zeebe-test</artifactId>
<scope>test</scope>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.0.3.RELEASE</version>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>io.zeebe.script.ZeebeScriptWorkerApplication</mainClass>
</manifest>
</archive>
<finalName>${project.artifactId}-${project.version}</finalName>
<appendAssemblyId>false</appendAssemblyId>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>repackage</goal>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

<repositories>
<repository>
<id>zeebe</id>
Expand Down
2 changes: 0 additions & 2 deletions src/main/java/io/zeebe/script/ScriptEvaluator.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.springframework.stereotype.Component;

@Component
public class ScriptEvaluator {

private final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
Expand Down
24 changes: 16 additions & 8 deletions src/main/java/io/zeebe/script/ScriptJobHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,34 +15,42 @@
*/
package io.zeebe.script;

import io.zeebe.client.ZeebeClient;
import io.zeebe.client.api.clients.JobClient;
import io.zeebe.client.api.response.ActivatedJob;
import io.zeebe.client.api.subscription.JobHandler;
import java.util.Collections;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ScriptJobHandler implements JobHandler {

private static final String HEADER_LANGUAGE = "language";
private static final String HEADER_SCRIPT = "script";

@Autowired private ScriptEvaluator scriptEvaluator;
private final ScriptEvaluator scriptEvaluator = new ScriptEvaluator();

private final ZeebeClient zeebeClient;

public ScriptJobHandler(ZeebeClient zeebeClient) {
this.zeebeClient = zeebeClient;
}

@Override
public void handle(JobClient client, ActivatedJob job) {
public void handle(JobClient jobClient, ActivatedJob job) {

final Map<String, Object> customHeaders = job.getCustomHeaders();
final String language = getLanguage(customHeaders);
final String script = getScript(customHeaders);

final Map<String, Object> payload = job.getPayloadAsMap();

// add context
payload.put("job", job);
payload.put("zeebeClient", zeebeClient);

final Object result = scriptEvaluator.evaluate(language, script, payload);

client
jobClient
.newCompleteCommand(job.getKey())
.payload(Collections.singletonMap("result", result))
.send();
Expand All @@ -52,7 +60,7 @@ private String getLanguage(Map<String, Object> customHeaders) {
final Object language = customHeaders.get(HEADER_LANGUAGE);
if (language == null) {
throw new RuntimeException(
String.format("Missing required custom header '%'", HEADER_LANGUAGE));
String.format("Missing required custom header '%s'", HEADER_LANGUAGE));
} else {
return String.valueOf(language);
}
Expand All @@ -62,7 +70,7 @@ private String getScript(Map<String, Object> customHeaders) {
final Object script = customHeaders.get(HEADER_SCRIPT);
if (script == null) {
throw new RuntimeException(
String.format("Missing required custom header '%'", HEADER_SCRIPT));
String.format("Missing required custom header '%s'", HEADER_SCRIPT));
} else {
return String.valueOf(script);
}
Expand Down
49 changes: 49 additions & 0 deletions src/main/java/io/zeebe/script/ZeebeScriptWorker.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright © 2017 camunda services GmbH ([email protected])
*
* 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.
*/
package io.zeebe.script;

import io.zeebe.client.ZeebeClient;
import io.zeebe.client.api.subscription.JobWorker;
import java.time.Duration;

public class ZeebeScriptWorker {

private final String contactPoint;

private JobWorker jobWorker;

public ZeebeScriptWorker(String contactPoint) {
this.contactPoint = contactPoint;
}

public void start() {
final ZeebeClient client =
ZeebeClient.newClientBuilder()
.brokerContactPoint(contactPoint)
.defaultJobWorkerName("script-worker")
.defaultJobTimeout(Duration.ofSeconds(10))
.build();

final ScriptJobHandler jobHandler = new ScriptJobHandler(client);
jobWorker = client.jobClient().newWorker().jobType("script").handler(jobHandler).open();
}

public void stop() {
if (jobWorker != null) {
jobWorker.close();
}
}
}
41 changes: 18 additions & 23 deletions src/main/java/io/zeebe/script/ZeebeScriptWorkerApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,36 +15,31 @@
*/
package io.zeebe.script;

import io.zeebe.client.ZeebeClient;
import java.time.Duration;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ZeebeScriptWorkerApplication {

@Value("${zeebe.client.broker.contactPoint:127.0.0.1:26500}")
private String contactPoint;
public static final String ENV_CONTACT_POINT = "zeebe.client.broker.contactPoint";
private static final String DEFAULT_CONTACT_POINT = "127.0.0.1:26500";

@Autowired private ScriptJobHandler jobHandler;
private static Logger LOG = LoggerFactory.getLogger("zeebe-script-worker");

public static void main(String[] args) {
SpringApplication.run(ZeebeScriptWorkerApplication.class, args);
}

@PostConstruct
public void start() {
final String contactPoint =
Optional.ofNullable(System.getenv(ENV_CONTACT_POINT)).orElse(DEFAULT_CONTACT_POINT);

LOG.info("Connecting worker to {}", contactPoint);

final ZeebeClient client =
ZeebeClient.newClientBuilder()
.brokerContactPoint(contactPoint)
.defaultJobWorkerName("script-worker")
.defaultJobTimeout(Duration.ofSeconds(10))
.build();
final ZeebeScriptWorker worker = new ZeebeScriptWorker(contactPoint);
worker.start();

client.jobClient().newWorker().jobType("script").handler(jobHandler).open();
try {
new CountDownLatch(1).await();
} catch (InterruptedException e) {
}
}
}
19 changes: 19 additions & 0 deletions src/main/resources/log4j2.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">

<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>

<Loggers>
<Logger name="io.zeebe" level="info"/>
<Logger name="io.zeebe.script" level="debug"/>

<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>

</Configuration>
Loading

0 comments on commit 56ab5a9

Please sign in to comment.