import { ZeebeGrpcClient } from '../zb/ZeebeGrpcClient'; import { StatefulLogInterceptor } from './StatefulLogInterceptor'; import { IZBJobWorker, Job, JobCompletionInterface, ZBGrpc, ZBWorkerTaskHandler } from './interfaces-1.0'; import { StreamActivatedJobsRequest } from './interfaces-grpc-1.0'; /** * Options controlling how `streamJobs` reports and recovers from a job stream * that dies (stream error, server-side end/close, or a failed open). */ export interface StreamJobsRecoveryOptions { /** * Called when the job stream fails: a stream `error` event, or a failed * attempt to open the stream. Exceptions thrown by the callback, and * rejections of a returned promise, are caught and logged. */ onStreamError?: (error: Error) => void | Promise; /** * Called when the server ends or closes the job stream without an error. * Exceptions thrown by the callback, and rejections of a returned * promise, are caught and logged. */ onStreamEnd?: () => void | Promise; /** * Called just before each attempt to re-open a dead stream. `attempt` is * the number of consecutive failed streams or open attempts, starting at 1. * It resets once a re-opened stream delivers a job or stays up for at least * `maxDelayMs`. Exceptions thrown by the callback, and rejections of a * returned promise, are caught and logged. */ onStreamReconnect?: (attempt: number) => void | Promise; /** * Re-open the stream when it dies. Defaults to `true`, with exponential * backoff starting at 1000ms, capped at 30000ms, and full jitter applied * (each delay is a uniform random value in `[0, cap]`, so a fleet of * workers whose streams die together does not reconnect in lockstep). * Pass `false` to disable reconnection (the `onStream*` callbacks still * fire), or an object to tune the backoff. `random` is a random source * returning `[0, 1)` (like `Math.random`); inject a deterministic one in * tests. After a re-opened stream is established, one backfill poll runs * to pick up jobs that were created while the stream was down. */ streamReconnect?: boolean | { initialDelayMs?: number; maxDelayMs?: number; random?: () => number; }; /** * Retry a backlog activation (the initial backfill, a reconnect backfill, * or a sidecar poll) that fails with a transient error * (RESOURCE_EXHAUSTED, UNAVAILABLE, DEADLINE_EXCEEDED). Defaults to * exponential backoff from 50ms by a factor of 1.6, capped at 5000ms, * with full jitter — each delay is a uniform random value in `[0, cap]`, * so a fleet that is throttled together does not retry in lockstep. * Pass `false` to restore the old behaviour (no retry), or an object to * tune the retry. With `false`, a failed initial startup backfill rejects * `streamJobs()` before recurring polling is scheduled; a later failed * activation is recovered by the next sidecar poll only when recurring * polling is enabled (`pollInterval` > 0). `jitter` is the * jitter width as a fraction of the capped base delay: `1` (the default) * is full jitter `[0, cap]`, `0.1` is ±10% around the base, `0` disables * jitter. `random` is a random source returning `[0, 1)`; inject a * deterministic one in tests. */ backlogRetry?: false | { minDelayMs?: number; maxDelayMs?: number; factor?: number; jitter?: number; random?: () => number; }; /** * Back off the recurring sidecar poll while it keeps returning no jobs * and the stream is open, like the Camunda Java client's * `streamNoJobsBackoffSupplier`. Each empty poll schedules the next one * after `min(current * factor, maxDelayMs)`, jittered by ±`jitter` * (a fraction of the delay); a poll that activates at least one job, or a * poll while the stream is down, resets the delay to `pollInterval`. * Defaults match the Java client: factor 1.6, jitter 0.1, max 60000ms. * Pass `false` to poll at a fixed `pollInterval`. `random` is a random * source returning `[0, 1)`; inject a deterministic one in tests. */ streamNoJobsBackoff?: false | StreamNoJobsBackoffOptions; } /** Options for `streamNoJobsBackoffDelayMs`; see `StreamJobsRecoveryOptions.streamNoJobsBackoff`. */ export interface StreamNoJobsBackoffOptions { maxDelayMs?: number; factor?: number; jitter?: number; random?: () => number; } export declare const STREAM_NO_JOBS_BACKOFF_MAX_DELAY_MS = 60000; /** * The next sidecar poll delay after an empty poll while the stream is open: * grows from the current (un-jittered) delay by `factor`, capped at * `maxDelayMs` (never below `baseDelayMs`). Returns the un-jittered `next` * delay, to grow from on the following empty poll, and the jittered `delay` * to actually wait. */ export declare const streamNoJobsBackoffDelayMs: (currentDelayMs: number, baseDelayMs: number, options?: StreamNoJobsBackoffOptions) => { next: number; delay: number; }; export declare const DRAIN_RETRY_MIN_DELAY_MS = 50; export declare const DRAIN_RETRY_MAX_DELAY_MS = 5000; /** * Whether an activation error is temporary (broker backpressure, gateway * unavailable, deadline exceeded) and the activation should be retried. */ export declare const isTransientActivationError: (e: unknown) => boolean; /** * Delay before reconnect `attempt` (1-based): exponential, capped, with full * jitter — a uniform random value in `[0, cap]`, where `cap` is the * deterministic exponential delay for the attempt. * * Jitter is not optional: when a gateway restarts, every worker's stream dies * at the same moment, and an unjittered backoff (1s, 2s, 4s…) makes the whole * fleet reconnect — and backfill-poll — in lockstep on every attempt. Full * jitter spreads the herd across the backoff window while keeping the * exponential cap as the expected upper bound. * * `random` is injectable (returning `[0, 1)`, like `Math.random`) so tests can * pin the delay sequence. */ export declare const backoffDelayMs: (attempt: number, initialDelayMs: number, maxDelayMs: number, random?: () => number) => number; /** Options for `drainRetryDelayMs`; see `StreamJobsRecoveryOptions.backlogRetry`. */ export interface DrainRetryOptions { minDelayMs?: number; maxDelayMs?: number; factor?: number; jitter?: number; random?: () => number; } /** * Delay before the `attempt`-th retry (1-based) of a failed backlog * activation: exponential from `minDelayMs` by `factor`, capped at * `maxDelayMs`, jittered by `random`. * * `jitter` is the jitter width as a fraction of the capped base delay: `1` * (the default) is full jitter, a uniform value in `[0, cap]`; `0.1` is ±10% * around the base (the Java client's default); `0` is the plain exponential * curve. Defaults match the Java client's curve (50ms → 5s, factor 1.6) with * full jitter. */ export declare const drainRetryDelayMs: (attempt: number, options?: DrainRetryOptions) => number; export declare class ZBStreamWorker implements IZBJobWorker { private grpcClient; private logger; private zbClient; private streams; private closed; private pollTimers; private reconnectTimers; private retryWaits; constructor({ grpcClient, log, zbClient, }: { grpcClient: ZBGrpc; log: StatefulLogInterceptor; zbClient: ZeebeGrpcClient; }); streamJobs(req: StreamActivatedJobsRequest & { inputVariableDto: { new (...args: any[]): Readonly; }; customHeadersDto: { new (...args: any[]): Readonly; }; taskHandler: ZBWorkerTaskHandler; /** * Optional jitter in milliseconds. When provided, the worker will wait * a random period up to this value before polling and opening the stream. * Useful for staggering multiple stream workers. */ jitter?: number; /** * Maximum number of jobs to activate per poll cycle (both the initial * backfill and the recurring sidecar polls). Defaults to 32. */ pollMaxJobsToActivate?: number; /** * Maximum number of jobs this registration handles concurrently, * counting jobs from the stream and from backlog polls. Stream * jobs that arrive while the worker is at capacity are buffered * and started as handlers settle, so both delivery paths share * the limit. Polls never activate more than the free capacity, * and while a backlog exists the worker polls again as soon as * fewer than 30% of this many jobs are in flight, rather than * waiting for a whole batch to finish (like the Java client's * `maxJobsActive`). Defaults to `pollMaxJobsToActivate`. */ maxJobsActive?: number; /** * Interval in milliseconds between sidecar poll cycles. The sidecar poll * is a low-frequency safety net that picks up jobs the stream may have * missed (e.g. jobs re-queued after a timeout). Each poll is a command on * the broker, so keep this value high to minimise load. * * Defaults to 30000 (30 seconds). Set to 0 or -1 to disable recurring * polling (the initial backfill poll still runs). */ pollInterval?: number; } & StreamJobsRecoveryOptions): Promise<{ close: () => void; }>; close(): Promise; log(msg: JSON): void; debug(msg: JSON): void; error(msg: JSON): void; protected makeCompleteHandlers(thisJob: Job, taskType: string): JobCompletionInterface & JobCompletionInterface; private failJob; private completeJob; private errorJob; }