Skip to content

About

No description or website provided.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

73 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Camunda Orchestration Cluster API – PHP SDK (Technical Preview)

Packagist Version PHP Version

A fully typed PHP client for the Camunda 8 Orchestration Cluster REST API. Fully compliant with the Camunda OpenAPI spec, with a hand-written runtime for authentication, configuration, and job workers.

  • Sync and async — CamundaClient (synchronous) and CamundaAsyncClient (promise-based)
  • Semantic value objects — distinct types for every identifier, checked at PHPStan level max
  • Zero-config — reads CAMUNDA_* environment variables (12-factor style)
  • Job workers — long-poll workers with optional pcntl process forking
  • OAuth & Basic auth — pluggable authentication with automatic token management
  • PSR standards — PSR-4 autoloading, PSR-18/PSR-7 HTTP via Guzzle

Support status

This is a Technical Preview of the PHP client for the Camunda 8 Orchestration Cluster API, provided for evaluation and feedback. It gives you a stable foundation to build on now, with a clear path to full support: we do not intend to make breaking changes to the application integration surface, but we do not guarantee that we will not. The SDK will become fully supported with an SLA in a future release.

We don't anticipate major changes — and your feedback is what helps close that gap.

As a Technical Preview, the API surface may still evolve before it is declared fully supported. Pin a specific version if you need stability.

Installing the SDK to your project

Requirements

  • PHP 8.2 or later
  • Composer
  • ext-json; ext-pcntl is optional (enables forked job workers)

Stable release (recommended for production)

The stable version tracks the latest supported Camunda server release.

composer require camunda8/orchestration-cluster-api

Versioning

This SDK has a different release cadence from the Camunda server. The major version of the SDK signals a 1:1 type coherence with the server API for a Camunda minor release.

SDK version n.y.z → server version 8.n, so the type surface of SDK version 10.y.z matches the API surface of Camunda 8.10.

Using the matching SDK major version for the server minor version provides the strongest guarantees about runtime reliability.

Using the SDK

The SDK provides two clients with matching surfaces:

  • CamundaClient — synchronous. Every method blocks until the response arrives. Use it in scripts, CLI tools, and traditional request/response applications.
  • CamundaAsyncClient — asynchronous. Every operation returns a Guzzle PromiseInterface. Use it when you want to issue concurrent requests.
function readme_sync_client(): void
{
    $client = CamundaClient::fromEnvironment();

    $result = $client->deployResourcesFromFiles(__DIR__ . '/resources/order-process.bpmn');
    // ...
}
function readme_async_client(): void
{
    $client = CamundaAsyncClient::fromEnvironment();

    $client->deployResourcesFromFilesAsync(__DIR__ . '/resources/order-process.bpmn')
        ->then(static function ($result): void {
            // handle the DeploymentResult once the request resolves
        })
        ->wait();
}

Parallel async reads

function parallel_async_reads(CamundaAsyncClient $client): void
{
    // Requests are issued before either promise is awaited.
    $topologyPromise = $client->getTopology();
    $definitionsPromise = $client->searchProcessDefinitions();

    $topology = $topologyPromise->wait();
    $definitions = $definitionsPromise->wait();

    if ($topology instanceof TopologyResponse) {
        printf("Connected to %d broker(s).\n", count($topology->getBrokers()));
    }
    if ($definitions instanceof ProcessDefinitionSearchQueryResult) {
        printf("Found %d process definitions.\n", count($definitions->getItems()));
    }
}

Semantic Types

The SDK uses distinct value objects for identifiers like ProcessDefinitionId, ProcessInstanceKey, JobKey, TenantId, and so on, defined in the Camunda\Orchestration\Semantic namespace.

Why they exist

Camunda's API has many operations that accept string keys. Without semantic types it is easy to accidentally pass a process-instance key where a process-definition id is expected. When everything is a string, static analysis cannot help you.

Semantic types make these identifiers distinct at the type level. PHPStan flags an error if you pass the wrong identifier type, catching bugs before runtime. Each value object validates its format on construction and implements Stringable and JsonSerializable, so it serializes transparently to and from JSON.

How to use them

function readme_semantic_types(): void
{
    // Identifiers are distinct value objects — you cannot accidentally pass a
    // process-definition id where a tenant id is expected.
    $instruction = (new ProcessInstanceCreationInstructionById())
        ->setProcessDefinitionId(ProcessDefinitionId::of('order-process'))
        ->setVariables(['orderId' => 'ORD-42']);

    // Value objects validate their format on construction and stringify cleanly.
    $definitionId = new ProcessDefinitionId('order-process');
    echo (string) $definitionId, "\n";
}

When you construct a model from an array, raw strings are automatically lifted into their semantic value objects, so you can stay ergonomic where you want to.

Configuration

Zero-config from the environment

The client reads the standard CAMUNDA_* environment variables and auto-detects the authentication strategy (NONE, BASIC, or OAUTH).

function readme_zero_config(): void
{
    // Reads CAMUNDA_REST_ADDRESS and auto-detects the auth strategy from the
    // ambient environment (NONE / BASIC / OAUTH).
    $client = CamundaClient::fromEnvironment();
}

Programmatic configuration

function readme_programmatic_config(): void
{
    $config = new CamundaConfiguration(
        restAddress: 'https://my-cluster.example.com/v2',
        authStrategy: 'OAUTH',
        clientId: 'my-client-id',
        clientSecret: 'my-client-secret',
    );

    $client = CamundaClient::fromConfiguration($config);
}

Basic auth

function readme_basic_auth(): void
{
    $client = CamundaClient::fromEnvironment([
        'CAMUNDA_AUTH_STRATEGY' => 'BASIC',
        'CAMUNDA_BASIC_AUTH_USERNAME' => 'demo',
        'CAMUNDA_BASIC_AUTH_PASSWORD' => 'demo',
    ]);
}

Loading a .env file

Set CAMUNDA_LOAD_ENVFILE=true to read .env in the working directory, or set it to an explicit path. This optional capability requires vlucas/phpdotenv.

function env_file_client(): CamundaClient
{
    // Set CAMUNDA_LOAD_ENVFILE=true (or a path) before starting PHP. Real
    // environment variables and explicit overrides still take precedence.
    return CamundaClient::fromEnvironment();
}

Mutual TLS

function mtls_client(): CamundaClient
{
    return CamundaClient::fromConfiguration(new CamundaConfiguration(
        restAddress: 'https://my-cluster.example.com/v2',
        authStrategy: 'OAUTH',
        clientId: 'my-client-id',
        clientSecret: 'my-client-secret',
        mtlsCertPath: '/run/secrets/client.crt',
        mtlsKeyPath: '/run/secrets/client.key',
        mtlsCaPath: '/run/secrets/cluster-ca.pem',
    ));
}

Custom Guzzle middleware

function custom_http_client(CamundaConfiguration $configuration): CamundaClient
{
    // Supplying a Guzzle client replaces the SDK-built stack. Add the SDK auth
    // middleware and any proxy, tracing, or mTLS options your application needs.
    $stack = HandlerStack::create();
    $stack->push(new AuthMiddleware(AuthProviderFactory::fromConfiguration($configuration)), 'camunda_auth');

    return CamundaClient::fromConfiguration(
        $configuration,
        new GuzzleClient(['handler' => $stack, 'http_errors' => false]),
    );
}

Retry and backoff

The SDK-built HTTP client retries transient failures with exponential backoff and full jitter. Option names, environment variables and defaults match the JS SDK:

function retry_config_client(): CamundaClient
{
    // Same options and defaults as the JS SDK: 3 attempts, 100 ms base delay, 2 s cap.
    // Equivalent environment variables: CAMUNDA_SDK_HTTP_RETRY_MAX_ATTEMPTS,
    // CAMUNDA_SDK_HTTP_RETRY_BASE_DELAY_MS and CAMUNDA_SDK_HTTP_RETRY_MAX_DELAY_MS.
    return CamundaClient::fromConfiguration(new CamundaConfiguration(
        restAddress: 'https://my-cluster.example.com/v2',
        authStrategy: 'NONE',
        httpRetryMaxAttempts: 5,
        httpRetryBaseDelayMs: 200,
        httpRetryMaxDelayMs: 5_000,
    ));
}

What is retried:

  • HTTP 429, always.
  • HTTP 503 and 500 that signal broker backpressure (problem title or, for 500, detail containing RESOURCE_EXHAUSTED). Any other 500 or 503 is returned after a single request, as before.
  • Connection failures (no response received), for idempotent methods only (GET, HEAD, PUT, DELETE, OPTIONS). A transport failure on a POST may have happened after the cluster accepted the command, so it is never replayed.

The wait before retry n + 1 is a random value between 0 and min(CAMUNDA_SDK_HTTP_RETRY_BASE_DELAY_MS * 2^(n-1), CAMUNDA_SDK_HTTP_RETRY_MAX_DELAY_MS). When the response carries a usable Retry-After header the wait is raised to at least that value (bounded at 60 seconds). Set CAMUNDA_SDK_HTTP_RETRY_MAX_ATTEMPTS=1 to disable retry.

When every attempt fails, the SDK throws RetryExhaustedException, a subclass of ApiException. getCode() is the HTTP status of the final attempt (0 if the final attempt received no response), the response headers and body are those of the final response, and getAttempts() reports how many requests were sent:

function retry_exhausted(CamundaClient $client): void
{
    try {
        $client->completeJob('2251799813686200');
    } catch (RetryExhaustedException $e) {
        // The final status (429 here) and the number of requests actually sent.
        error_log(sprintf('gave up with HTTP %d after %d attempts', $e->getCode(), $e->getAttempts()));
    }
}

Notes:

  • Job activation is not retried inside the long poll. JobWorker activation requests (POST /jobs/activation) are sent exactly once; a failed activation surfaces to the worker loop as it always has. Retrying inside a long poll would hold it open for several times its request timeout.
  • A Guzzle client you supply is not modified. Retry is part of the SDK-built client only. Push RetryMiddleware onto your own handler stack to get the same behaviour:
function custom_http_client_with_retry(CamundaConfiguration $configuration): CamundaClient
{
    // A client you supply is not wrapped by the SDK: push the retry middleware yourself
    // if you want the same behaviour.
    $stack = HandlerStack::create();
    // Push retry before auth so that every attempt picks up a fresh auth header.
    $stack->push(new RetryMiddleware(maxAttempts: 3, baseDelayMs: 100, maxDelayMs: 2_000), 'camunda_retry');
    $stack->push(new AuthMiddleware(AuthProviderFactory::fromConfiguration($configuration)), 'camunda_auth');

    return CamundaClient::fromConfiguration(
        $configuration,
        new GuzzleClient(['handler' => $stack, 'http_errors' => false]),
    );
}

Credentials in debug output

CamundaConfiguration redacts clientSecret, basicAuthPassword and mtlsKeyPassphrase on the debug surfaces PHP lets an object intercept: var_dump() and print_r(), which both honour __debugInfo(), and json_encode(), which uses the configuration's JsonSerializable implementation. A credential that is set shows as ***; one that is not set stays null. CamundaClient and CamundaAsyncClient do the same on var_dump() and print_r() and additionally summarise their Guzzle client by class name, because its options carry the mTLS key passphrase. The clients have no public properties, so json_encode() of a client contains no credentials either. Reading $config->clientSecret in your own code still returns the real value.

Two surfaces are exceptions, and both still print credentials:

  • var_export() builds a __set_state() literal from the object's properties with no hook to intercept, and it exports private and protected properties just the same, so no change of property visibility would alter that.
  • Symfony's VarDumper does not use __debugInfo() as the source of the values it shows: it dumps the object's real properties (checked with symfony/var-dumper 7.4, where $config->clientSecret appears in clear text next to the redacted debug view). That covers Symfony's dump() and dd() and Laravel's dump() and dd(), which are built on it, so debug pages and error screens that use them can show a credential.

Do not pass a configuration or client object to either, and keep their output out of log context.

Supported environment variables

Variable Default Description
CAMUNDA_REST_ADDRESS http://localhost:8080/v2 Cluster REST endpoint. /v2 is appended automatically when absent.
ZEEBE_REST_ADDRESS — Legacy alias for CAMUNDA_REST_ADDRESS (used only when the latter is unset).
CAMUNDA_AUTH_STRATEGY — NONE, BASIC, or OAUTH. Auto-detected from the supplied credentials when unset.
CAMUNDA_CLIENT_ID — OAuth client id.
CAMUNDA_CLIENT_SECRET — OAuth client secret.
CAMUNDA_CLIENT_AUTH_CLIENTID — Legacy alias for CAMUNDA_CLIENT_ID.
CAMUNDA_CLIENT_AUTH_CLIENTSECRET — Legacy alias for CAMUNDA_CLIENT_SECRET.
CAMUNDA_OAUTH_URL https://login.cloud.camunda.io/oauth/token OAuth token endpoint.
CAMUNDA_TOKEN_AUDIENCE zeebe.camunda.io OAuth token audience.
CAMUNDA_BASIC_AUTH_USERNAME — Basic-auth username.
CAMUNDA_BASIC_AUTH_PASSWORD — Basic-auth password.
CAMUNDA_TENANT_ID — Default tenant id applied to tenant-scoped commands when the caller passes none (<default> when unset).
CAMUNDA_TENANT_IDS — Comma-separated default tenant ids (e.g. for job activation).
CAMUNDA_SDK_LOG_LEVEL warn SDK log level (error, warn, info, debug).
CAMUNDA_WORKER_MAX_CONCURRENT_JOBS 32 Default maximum number of jobs a worker activates at once.
CAMUNDA_WORKER_TIMEOUT 60000 Default job activation timeout, in milliseconds.
CAMUNDA_WORKER_REQUEST_TIMEOUT 10000 Default long-poll request timeout, in milliseconds.
CAMUNDA_WORKER_NAME — Default worker name reported when activating jobs.
CAMUNDA_SDK_HTTP_RETRY_MAX_ATTEMPTS 3 Maximum total HTTP attempts (including the first) for transient failures: 429, broker backpressure (RESOURCE_EXHAUSTED on 500/503) and, for idempotent methods, connection failures. 1 disables retry. Applies to the SDK-built HTTP client only; the job-activation long poll is never retried.
CAMUNDA_SDK_HTTP_RETRY_BASE_DELAY_MS 100 Base delay in milliseconds for exponential backoff with full jitter between HTTP retries. A Retry-After header raises the wait to at least the server value (capped at 60 seconds).
CAMUNDA_SDK_HTTP_RETRY_MAX_DELAY_MS 2000 Maximum delay cap in milliseconds for HTTP retry backoff.
CAMUNDA_MTLS_CERT_PATH — Path to the client certificate for mutual TLS.
CAMUNDA_MTLS_KEY_PATH — Path to the client private key for mutual TLS.
CAMUNDA_MTLS_CA_PATH — Path to the CA bundle used to verify the server certificate.
CAMUNDA_MTLS_KEY_PASSPHRASE — Passphrase protecting the mTLS client key, if any.
CAMUNDA_LOAD_ENVFILE — Load configuration from a .env file. Set to true or a file path.

Deploying resources

Pass a readable filesystem path for every BPMN, DMN, or Form resource. Anchor paths with __DIR__ so deployment is independent of the shell's current working directory. The repository includes runnable deployment resources; replace those paths with your application's models.

function readme_deploy_resources(): void
{
    $client = CamundaClient::fromEnvironment();

    $result = $client->deployResourcesFromFiles(
        __DIR__ . '/resources/order-process.bpmn',
        __DIR__ . '/resources/pricing.dmn',
    );
    // $result is a DeploymentResult (or ProblemDetail on a handled error).
}

deployResourcesFromFiles() returns a DeploymentResult on success and a ProblemDetail for a handled API error. It throws a ConfigurationException when a local resource path cannot be read.

Job workers

A job worker long-polls for jobs of a given type and dispatches each to your handler. Returning an array auto-completes the job with those variables; you can also complete, fail, or raise a BPMN error explicitly via the handler's JobActionClient.

function readme_job_worker(): void
{
    $client = CamundaClient::fromEnvironment();

    $worker = $client->createJobWorker(new JobWorkerOptions(
        type: 'payment-processing',
        maxJobs: 5,
        timeoutMs: 30_000,
    ));

    $worker->run(function (ActivatedJobResult $job, JobActionClient $action): array {
        // ... perform the work ...
        return ['status' => 'paid'];
    });
}

When ext-pcntl is available and forked: true is set, each job is processed in its own child process, bounded to maxJobs concurrent children.

When a handler throws

If your handler throws, the worker catches the Throwable and fails the job for you, then carries on: the remaining jobs of the batch are still dispatched and the poll loop keeps running, so one bad job never stops the worker.

What you can rely on:

  • The job is failed with one retry consumed — retries - 1, floored at zero — so the broker schedules a retry while retries remain and creates an incident when they are exhausted. No retry back-off is set.
  • The failure message is the exception class and its message. The stack trace is never sent to the broker.
  • If your handler already completed the job, failed it, or raised a BPMN error before throwing, the worker leaves that terminal action alone and sends nothing further.
  • Auto-completion is skipped for a job whose handler threw.

To choose the retry count, the back-off, or the message yourself, catch the error inside your handler and call $action->fail(...) explicitly.

Note that a transport error raised while reporting the failure — for example broker backpressure on the fail call itself — still surfaces to the caller of run() or pollOnce(), exactly as a failing auto-completion does. The same holds when your handler calls $action->complete(), fail() or error() itself and that request fails: the worker surfaces the error rather than replacing the terminal action you asked for with one of its own.

In forked mode that last point works differently, because nothing crosses the process boundary. A handler exception is still turned into a job failure, in the child, before it exits. But a transport error while reporting the terminal action ends the child instead of reaching the parent: the parent reaps it and polls on, so the job is left to its lease timeout and you do not see the error. If your handler needs to observe its own transport failures, handle them inside the handler.

Object-oriented handlers

final class PaymentJobHandler implements JobHandler
{
    public function handle(ActivatedJobResult $job, JobActionClient $action): ?array
    {
        $variables = $job->getVariables();
        if (!isset($variables['paymentId'])) {
            $action->error('MISSING_PAYMENT_ID', 'The payment job has no payment id.');
            return null;
        }

        return ['paymentStatus' => 'approved'];
    }
}

function object_job_handler(CamundaClient $client): void
{
    $worker = $client->createJobWorker(new JobWorkerOptions(type: 'process-payment'));
    $worker->run(new PaymentJobHandler());
}

Job variables are untrusted input

Job variables and custom headers reach your handler through the cluster, but neither is shaped by your worker. Variables carry whatever is in scope for the task at activation — input supplied by whoever started the process instance, values written by earlier tasks, and data from any external caller along the way. Custom headers come from the deployed process model, so they are as trustworthy as your deployment pipeline and no more. Treat both as untrusted input.

What the SDK does:

  • Deserialization is JSON only. Variables and custom headers are typed array<string,mixed> and are hydrated from json_decode alone. The top level is a PHP array; a nested JSON object arrives as a stdClass, a JSON array as a PHP array, and everything else as a scalar or null. No class is instantiated from the payload, and nothing in it reaches unserialize() or eval() — a string that looks like serialized PHP stays a string.
  • Nesting is bounded at json_decode's default depth of 512, applied to the whole response. A payload nested beyond that is rejected with an ApiException (Error JSON decoding server response) before your handler is called, so an over-deep payload cannot drive the SDK into unbounded recursion.
  • The SDK adds no variable content to its own output. There is no logger in the SDK, and it never appends a payload to an exception message it raises: a failed activation reports the title and detail the cluster returned, nothing more. Note that those two fields are the server's text, passed through unredacted, and that a generated ApiException still carries the raw HTTP response body on getResponseBody() — for an activation response that body is the variables. Log the exception's message, not the whole exception, if variable values are sensitive in your deployment.
  • Each job gets its own objects. Every dispatched job is given its own ActivatedJobResult and its own JobActionClient, and the variables handed to one handler call are a separate value from any other's, so no payload is shared or mutated across jobs. That is object isolation, not sandboxing: a stateful handler — properties, captured references, statics, globals — can still carry data from one job to the next, and forked mode separates jobs into processes for concurrency, not as a security boundary.

What the SDK does not do:

  • It enforces no payload size limit. There is no cap on the byte size of an activation response or of an individual variable. Note where a cap has to go: the activation response is read into a string and decoded in full before any handler is dispatched, so a check inside your handler runs far too late to protect the worker's memory. A size limit must be imposed upstream — on the cluster, or in the HTTP layer, for example a Guzzle middleware on a custom client that rejects an over-large response before it is buffered. A handler-side check is still worth having against individual values you are about to act on; it is just not a defence against an over-large response.
  • It does not validate or sanitise content. Type-checking, range-checking, schema validation, and escaping before use in SQL, a shell command, a file path or HTML are the handler author's responsibility. In particular, never use a variable value as a file path, a class name or a callable without checking it against a list you control.

Accessing every operation

Every one of the 244 API operations is exposed as a method directly on the client — the flat facade — so you rarely need to reach for an API group:

function readme_flat_facade(): void
{
    $client = CamundaClient::fromEnvironment();
    $instruction = new ProcessInstanceCreationInstructionById([
        'processDefinitionId' => 'order-process',
    ]);

    $topology = $client->getTopology();
    $result = $client->createProcessInstance($instruction);

    $async = CamundaAsyncClient::fromEnvironment();
    $async->getTopology()
        ->then(static function ($asyncTopology): void {
            // handle the asynchronous topology response
        })
        ->wait();
}

Beyond the ergonomic helpers and the flat facade, every API group is also reachable through the typed api() accessor:

function readme_api_accessor(): void
{
    $client = CamundaClient::fromEnvironment();
    $instruction = new ProcessInstanceCreationInstructionById([
        'processDefinitionId' => 'order-process',
    ]);

    $processInstances = $client->api(ProcessInstanceApi::class);
    $result = $processInstances->createProcessInstance($instruction);
}

See the examples/ directory for compilable, static-analysed usage of every REST API operation.

Advanced runnable examples

The examples/advanced/ directory contains self-verifying local-cluster scenarios for a test drive, resilient worker behavior, idempotent message correlation, and PHP process-forking.

Live example showcase

With a disposable Camunda cluster already running, execute the six scenario showcase and create its HTML proof report:

CAMUNDA_REST_ADDRESS=http://localhost:8080 \
CAMUNDA_AUTH_STRATEGY=NONE \
  make example-showcase

The showcase runs focused workflow scenarios for deployment, process lifecycle, job workers, user tasks, incidents, message correlation, and management operations. The report indexes every source-backed snippet alongside the live scenario that demonstrates its API area. It intentionally performs mutations and cluster-management requests; never run it against a shared, staging, or production cluster.

Run one scenario with make example-showcase SCENARIO=<name>. Open docs/example-validation.html after a run for the six outcomes and a searchable gallery of all source-backed snippets.

Contributing

See CONTRIBUTING.md and AGENTS.md for the development workflow, the generation pipeline, and the semantic-type machinery.

License

Apache-2.0. See LICENSE.

About

No description or website provided.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages