Search in sources :

Example 1 with JobWorker

use of io.camunda.zeebe.client.api.worker.JobWorker in project zeebe-test-container by camunda-community-hub.

the class TriggerTimerCatchEventTest method shouldTriggerTimerStartEvent.

@Test
@Timeout(value = 5, unit = TimeUnit.MINUTES)
void shouldTriggerTimerStartEvent() {
    // given
    final ZeebeClock clock = ZeebeClock.newDefaultClock(zeebeContainer);
    final BpmnModelInstance process = Bpmn.createExecutableProcess("process").startEvent().intermediateCatchEvent().timerWithDate(TIMER_DATE.toString()).serviceTask("task", b -> b.zeebeJobType(JOB_TYPE)).endEvent().done();
    final List<ActivatedJob> activatedJobs = new CopyOnWriteArrayList<>();
    final Instant brokerTime;
    // when
    final JobHandler handler = (client, job) -> activatedJobs.add(job);
    try (final ZeebeClient client = newZeebeClient(zeebeContainer);
        final JobWorker worker = newJobWorker(handler, client)) {
        client.newDeployCommand().addProcessModel(process, "process.bpmn").send().join();
        client.newCreateInstanceCommand().bpmnProcessId("process").latestVersion().send().join();
        brokerTime = clock.addTime(TIME_OFFSET);
        Awaitility.await("until a job has been activated by the worker").untilAsserted(() -> Assertions.assertThat(activatedJobs).hasSize(1));
    }
    // then
    Assertions.assertThat(activatedJobs).as("the timer event was triggered and a job is now available").hasSize(1);
    Assertions.assertThat(brokerTime).as("the modified time is at least equal to one day from now").isAfterOrEqualTo(TIMER_DATE);
}
Also used : ActivatedJob(io.camunda.zeebe.client.api.response.ActivatedJob) JobHandler(io.camunda.zeebe.client.api.worker.JobHandler) Testcontainers(org.testcontainers.junit.jupiter.Testcontainers) ZeebeContainer(io.zeebe.containers.ZeebeContainer) Bpmn(io.camunda.zeebe.model.bpmn.Bpmn) Instant(java.time.Instant) ZeebeClock(io.zeebe.containers.clock.ZeebeClock) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) List(java.util.List) Duration(java.time.Duration) ZeebeClient(io.camunda.zeebe.client.ZeebeClient) ActivatedJob(io.camunda.zeebe.client.api.response.ActivatedJob) JobHandler(io.camunda.zeebe.client.api.worker.JobHandler) BpmnModelInstance(io.camunda.zeebe.model.bpmn.BpmnModelInstance) Assertions(org.assertj.core.api.Assertions) JobWorker(io.camunda.zeebe.client.api.worker.JobWorker) Awaitility(org.awaitility.Awaitility) Timeout(org.junit.jupiter.api.Timeout) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Container(org.testcontainers.junit.jupiter.Container) ZeebeClock(io.zeebe.containers.clock.ZeebeClock) Instant(java.time.Instant) ZeebeClient(io.camunda.zeebe.client.ZeebeClient) BpmnModelInstance(io.camunda.zeebe.model.bpmn.BpmnModelInstance) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) JobWorker(io.camunda.zeebe.client.api.worker.JobWorker) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 2 with JobWorker

use of io.camunda.zeebe.client.api.worker.JobWorker in project zeebe by camunda.

the class JobWorkerCreator method main.

public static void main(final String[] args) {
    final String defaultAddress = "localhost:26500";
    final String envVarAddress = System.getenv("ZEEBE_ADDRESS");
    final ZeebeClientBuilder clientBuilder;
    if (envVarAddress != null) {
        /* Connect to Camunda Cloud Cluster, assumes that credentials are set in environment variables.
       * See JavaDoc on class level for details
       */
        clientBuilder = ZeebeClient.newClientBuilder().gatewayAddress(envVarAddress);
    } else {
        // connect to local deployment; assumes that authentication is disabled
        clientBuilder = ZeebeClient.newClientBuilder().gatewayAddress(defaultAddress).usePlaintext();
    }
    final String jobType = "foo";
    try (final ZeebeClient client = clientBuilder.build()) {
        System.out.println("Opening job worker.");
        try (final JobWorker workerRegistration = client.newWorker().jobType(jobType).handler(new ExampleJobHandler()).timeout(Duration.ofSeconds(10)).open()) {
            System.out.println("Job worker opened and receiving jobs.");
            // run until System.in receives exit command
            waitUntilSystemInput("exit");
        }
    }
}
Also used : ZeebeClient(io.camunda.zeebe.client.ZeebeClient) ZeebeClientBuilder(io.camunda.zeebe.client.ZeebeClientBuilder) JobWorker(io.camunda.zeebe.client.api.worker.JobWorker)

Example 3 with JobWorker

use of io.camunda.zeebe.client.api.worker.JobWorker in project zeebe by zeebe-io.

the class WorkloadGenerator method performSampleWorkload.

/**
 * Given a client, deploy a process, start instances, work on service tasks, create and resolve
 * incidents and finish the instance.
 */
public static void performSampleWorkload(final ZeebeClient client) {
    client.newDeployResourceCommand().addProcessModel(SAMPLE_PROCESS, "sample_process.bpmn").send().join();
    final Map<String, Object> variables = new HashMap<>();
    variables.put("orderId", "foo-bar-123");
    variables.put("largeValue", "x".repeat(8192));
    variables.put("unicode", "Á");
    variables.put("nullable", null);
    final long processInstanceKey = client.newCreateInstanceCommand().bpmnProcessId("testProcess").latestVersion().variables(variables).send().join().getProcessInstanceKey();
    // create job worker which fails on first try and sets retries to 0 to create an incident
    final AtomicBoolean fail = new AtomicBoolean(true);
    final JobWorker worker = client.newWorker().jobType("work").handler((handlerClient, job) -> {
        if (fail.getAndSet(false)) {
            // fail job
            handlerClient.newFailCommand(job.getKey()).retries(0).errorMessage("failed").send().join();
        } else {
            handlerClient.newCompleteCommand(job.getKey()).send().join();
        }
    }).open();
    client.newPublishMessageCommand().messageName("catch").correlationKey("foo-bar-123").send().join();
    // wait for incident and resolve it
    final Record<IncidentRecordValue> incident = Awaitility.await("the incident was created").timeout(Duration.ofMinutes(1)).until(() -> RecordingExporter.incidentRecords(IncidentIntent.CREATED).withProcessInstanceKey(processInstanceKey).withElementId("task").findFirst(), Optional::isPresent).orElseThrow();
    client.newUpdateRetriesCommand(incident.getValue().getJobKey()).retries(3).send().join();
    client.newResolveIncidentCommand(incident.getKey()).send().join();
    // wrap up
    Awaitility.await("the process instance was completed").timeout(Duration.ofMinutes(1)).until(() -> RecordingExporter.processInstanceRecords(ProcessInstanceIntent.ELEMENT_COMPLETED).filter(r -> r.getKey() == processInstanceKey).exists());
    worker.close();
}
Also used : ProcessInstanceIntent(io.camunda.zeebe.protocol.record.intent.ProcessInstanceIntent) IncidentRecordValue(io.camunda.zeebe.protocol.record.value.IncidentRecordValue) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Bpmn(io.camunda.zeebe.model.bpmn.Bpmn) HashMap(java.util.HashMap) RecordingExporter(io.camunda.zeebe.test.util.record.RecordingExporter) Record(io.camunda.zeebe.protocol.record.Record) IncidentIntent(io.camunda.zeebe.protocol.record.intent.IncidentIntent) Duration(java.time.Duration) Map(java.util.Map) ZeebeClient(io.camunda.zeebe.client.ZeebeClient) BpmnModelInstance(io.camunda.zeebe.model.bpmn.BpmnModelInstance) Optional(java.util.Optional) JobWorker(io.camunda.zeebe.client.api.worker.JobWorker) Awaitility(org.awaitility.Awaitility) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) IncidentRecordValue(io.camunda.zeebe.protocol.record.value.IncidentRecordValue) JobWorker(io.camunda.zeebe.client.api.worker.JobWorker)

Example 4 with JobWorker

use of io.camunda.zeebe.client.api.worker.JobWorker in project zeebe by zeebe-io.

the class JobWorkerCreator method main.

public static void main(final String[] args) {
    final String defaultAddress = "localhost:26500";
    final String envVarAddress = System.getenv("ZEEBE_ADDRESS");
    final ZeebeClientBuilder clientBuilder;
    if (envVarAddress != null) {
        /* Connect to Camunda Cloud Cluster, assumes that credentials are set in environment variables.
       * See JavaDoc on class level for details
       */
        clientBuilder = ZeebeClient.newClientBuilder().gatewayAddress(envVarAddress);
    } else {
        // connect to local deployment; assumes that authentication is disabled
        clientBuilder = ZeebeClient.newClientBuilder().gatewayAddress(defaultAddress).usePlaintext();
    }
    final String jobType = "foo";
    try (final ZeebeClient client = clientBuilder.build()) {
        System.out.println("Opening job worker.");
        try (final JobWorker workerRegistration = client.newWorker().jobType(jobType).handler(new ExampleJobHandler()).timeout(Duration.ofSeconds(10)).open()) {
            System.out.println("Job worker opened and receiving jobs.");
            // run until System.in receives exit command
            waitUntilSystemInput("exit");
        }
    }
}
Also used : ZeebeClient(io.camunda.zeebe.client.ZeebeClient) ZeebeClientBuilder(io.camunda.zeebe.client.ZeebeClientBuilder) JobWorker(io.camunda.zeebe.client.api.worker.JobWorker)

Example 5 with JobWorker

use of io.camunda.zeebe.client.api.worker.JobWorker in project zeebe by camunda-cloud.

the class Worker method run.

@Override
public void run() {
    final WorkerCfg workerCfg = appCfg.getWorker();
    final String jobType = workerCfg.getJobType();
    final long completionDelay = workerCfg.getCompletionDelay().toMillis();
    final var variables = readVariables(workerCfg.getPayloadPath());
    final BlockingQueue<Future<?>> requestFutures = new ArrayBlockingQueue<>(10_000);
    final BlockingDeque<DelayedCommand> delayedCommands = new LinkedBlockingDeque<>(10_000);
    final ZeebeClient client = createZeebeClient();
    printTopology(client);
    final JobWorker worker = client.newWorker().jobType(jobType).handler((jobClient, job) -> {
        final var command = jobClient.newCompleteCommand(job.getKey()).variables(variables);
        if (workerCfg.isCompleteJobsAsync()) {
            delayedCommands.addLast(new DelayedCommand(Instant.now().plusMillis(completionDelay), command));
        } else {
            try {
                Thread.sleep(completionDelay);
            } catch (Exception e) {
                e.printStackTrace();
            }
            requestFutures.add(command.send());
        }
    }).open();
    final ResponseChecker responseChecker = new ResponseChecker(requestFutures);
    responseChecker.start();
    final var asyncJobCompleter = new DelayedCommandSender(delayedCommands, requestFutures);
    if (workerCfg.isCompleteJobsAsync()) {
        asyncJobCompleter.start();
    }
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        worker.close();
        client.close();
        asyncJobCompleter.close();
        responseChecker.close();
    }));
}
Also used : ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) Future(java.util.concurrent.Future) AppCfg(io.camunda.zeebe.config.AppCfg) BlockingDeque(java.util.concurrent.BlockingDeque) FinalCommandStep(io.camunda.zeebe.client.api.command.FinalCommandStep) ZeebeClient(io.camunda.zeebe.client.ZeebeClient) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) WorkerCfg(io.camunda.zeebe.config.WorkerCfg) BlockingQueue(java.util.concurrent.BlockingQueue) JobWorker(io.camunda.zeebe.client.api.worker.JobWorker) Instant(java.time.Instant) ZeebeClientBuilder(io.camunda.zeebe.client.ZeebeClientBuilder) WorkerCfg(io.camunda.zeebe.config.WorkerCfg) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) ZeebeClient(io.camunda.zeebe.client.ZeebeClient) JobWorker(io.camunda.zeebe.client.api.worker.JobWorker) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) Future(java.util.concurrent.Future)

Aggregations

JobWorker (io.camunda.zeebe.client.api.worker.JobWorker)14 ZeebeClient (io.camunda.zeebe.client.ZeebeClient)13 BpmnModelInstance (io.camunda.zeebe.model.bpmn.BpmnModelInstance)7 ZeebeClientBuilder (io.camunda.zeebe.client.ZeebeClientBuilder)6 Bpmn (io.camunda.zeebe.model.bpmn.Bpmn)6 Duration (java.time.Duration)6 Instant (java.time.Instant)5 Awaitility (org.awaitility.Awaitility)5 ProcessInstanceIntent (io.camunda.zeebe.protocol.record.intent.ProcessInstanceIntent)4 Map (java.util.Map)4 Test (org.junit.jupiter.api.Test)4 FinalCommandStep (io.camunda.zeebe.client.api.command.FinalCommandStep)3 AppCfg (io.camunda.zeebe.config.AppCfg)3 WorkerCfg (io.camunda.zeebe.config.WorkerCfg)3 Record (io.camunda.zeebe.protocol.record.Record)3 IncidentIntent (io.camunda.zeebe.protocol.record.intent.IncidentIntent)3 IncidentRecordValue (io.camunda.zeebe.protocol.record.value.IncidentRecordValue)3 RecordingExporter (io.camunda.zeebe.test.util.record.RecordingExporter)3 ZeebeContainer (io.zeebe.containers.ZeebeContainer)3 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)3