Unit tests
KlokBrokerClientMetadataTest checks the properties the client adds to a message (context ids, sent time, body type,
legacy names) without a broker; extend it when a property is added, because the Python and TypeScript clients mirror the
same list.
KlokPulsarClientManagerTest checks what every Pulsar client is built with: hostname verification on, the CA file
trusted, and the OAuth2 plugin created through the public AuthenticationFactory of the shaded Pulsar 5.0.0 client (it
fails when pulsar-client-admin-api, which that client needs at run time, is missing). PendingRepliesTest covers the
expiry of the pending requests of request/reply (each kept as long as its own request waits, no size limit),
KlokBrokerClientSyncNotSentTest which failures of a request prove that it never left (KlokRequestNotSentException)
and which do not (a send timeout, a producer closed under the send), and KlokBrokerClientListenerExecutorTest the
names (klok-broker-listener-<n>) and the non-daemon flag of the listener threads.
Missing topics and grants (see Authentication and subscriptions):
KlokTopicProvisioningFixtureTest runs the message cases of klok-common's topic-provisioning-cases.json through
KlokTopicMissingException, KlokTopicAccessDeniedException and KlokTopicErrors.classify (from a Pulsar error
wrapped in CompletionException and ExecutionException): every message is the contract's text, character for
character. It reads the cases from the klok-common jar, so a new klok-common release brings new cases with it.
KlokTopicErrorsTest covers which Pulsar errors mean missing and denied, the unwrapping, simple names, and that a
timeout or an authentication failure stays a Pulsar error.
KlokBrokerClientTopicProvisioningTest drives every path on a mocked Pulsar client: send, subscribe and batch
subscribe, verifyPublish (one producer, cached) and verifyConsume (a reader named <subscription>-verify-<hex>,
closed again, no consumer), a producer Pulsar closed (created once more, no loop), a consumer failed for good (the loop
stops with the reason, the diagnosing lookup never creates the topic), a missing _DLQ (negatively acknowledged once,
the loop stops), request/reply (a missing request topic and a missing reply topic, nothing sent before the reply
consumer exists, a refused reply) and KLOK_DEV_URL.
The Python client (python/klok-brokerclient-python, pytest) runs the fixture cases of the vendored wire contract,
checks every name against it, and tests publishing, handler outcomes and dead letters against a fake Pulsar with the
package the Gradle plugin generated for KlokTaskEvent_v1 and bytes Java encoded (tests/fixtures/).
test_servicelog.py runs the service logging cases of the contract and decodes the log events of every outcome
(finished, retried, dead lettered, redelivered, undecodable, warnings, scripts) with the V6 classes, reads V6 and V4
events back with read_log_event, and runs correlation-cases.json, the global id rules of the contract.
test_wire_contract.py also runs topic-provisioning-cases.json and the companionTopics naming cases and checks the
companion rules and message templates against the contract; test_provisioning.py maps pulsar.TopicNotFound,
pulsar.AuthorizationError and pulsar.NotAllowedError and checks publish, subscribe, request and a missing _DLQ
against a fake Pulsar that refuses topics; test_request_failures.py checks which failures of a request raise
KlokRequestNotSentException, and that a pending request is kept for its own timeout. test_receive_loop_failures.py
runs the real receive and reply loops on a consumer that fails where the test says (a BaseException from a handler, an
acknowledge, a negative acknowledge, the invocation's log, _give_up, a reply that cannot be read, a consumer or reader
closed under the loop) and checks that the thread goes on with the next message, that SystemExit and
KeyboardInterrupt close the client and come out of run_forever(), and what KlokSubscriptionHealth reports. With
KLOK_TEST_PULSAR_URL set it also runs against a real broker; the pipeline starts a Pulsar standalone as a service for
that.
The TypeScript client (typescript/klok-brokerclient-typescript, vitest) does the same in TypeScript:
npm test runs the unit tests against a fake Pulsar (tests/fakes.ts, the interface KlokPulsar the real client is
adapted to): the fixture cases of the vendored wire contract (topic naming, property forms, service logging), every name
and default against the contract, the payloads (the Java-encoded KlokTaskStatusEventV1 fixture, round trips, the
schema strings against the Python client's), the topic provisioning cases and the companion rules, the Node client's
TopicNotFound and AuthorizationError results mapped to the typed errors on every path
(tests/provisioning.test.ts), publishing, the handler outcomes, retries and dead letters, the log events of every
outcome decoded with the vendored V4 classes, the receive loops (concurrency, a failed receive, closing with a running
handler and during a backoff), request/reply (the reader before the first request, concurrent requests, a 45 s timeout
whose reply comes after 35 s, domains, the reader's prefix in klok-reply-subscription, a foreign reply passed over
undecoded, a reply keyed with the request's reply subscription by a key-based batching producer, which failed sends
raise KlokRequestNotSentException) and the lifecycle (close(), runUntilSignal()). The datamodel packages are the
Gradle plugin's output (tests/fixtures/, vendor/).
npm run smoke packs the built package, installs the tarball into a scratch project and imports it as an ES module and
as CommonJS, runs an invocation through both, loads the native Pulsar binding and type-checks a consumer with NodeNext
and Bundler resolution.
npm run test:integration builds the package and runs tests/integration/ against the broker in KLOK_TEST_PULSAR_URL
/ KLOK_TEST_PULSAR_ADMIN_URL: publish and subscribe, the registered schema byte for byte, concurrency, request/reply
across clients and domains, no reply subscription left after close or after the requester is killed, the reader's
subscription named <prefix>-reader-<random> and the replies keyed with the prefix, a reply keyed with the reply
subscription an addressed request names, dead letters, the log events of an invocation, that a worker process exits
after close() and after SIGTERM, and (provisioning.test.ts) that a missing topic fails publish and subscribe with
the contract message until the admin API creates it and that a missing _DLQ stops the subscription. With python3
available (or KLOK_TEST_PYTHON), it installs the repository's Python client into a virtual environment and runs the
cross-language tests: TypeScript publishes and the Python client consumes, and the other way round, with the same
payload, correlation id, key and CloudEvents attributes.
Tests against a broker
Java tests that need a real broker are tagged broker, left out of ./gradlew test and run by ./gradlew integrationTest against the broker in KLOK_TEST_PULSAR_URL (with an external listener) and
KLOK_TEST_PULSAR_ADMIN_URL. The pipeline job java-integration-test starts a Pulsar 5.0.0 standalone
(apachepulsar/pulsar:5.0.0, bin/pulsar standalone -nss -nfw, metadata in RocksDB, no ZooKeeper) as a service for
them, as the Python and TypeScript jobs do; the runners have no Docker, so nothing in the tests starts a container.
KlokRequestReplyBrokerTest asks and answers on the public/default namespace of the standalone and reads the topic
stats of the admin API: the reply is keyed with the requester's reply subscription, two requesters on one reply topic
each get their own reply, and the reply subscription is non-durable and gone from the response topic once its requester
has closed, and once a requester in another JVM (KlokReplyRequesterProcess) has been killed with SIGKILL.
KlokTopicProvisioningBrokerTest behaves as klok5: it turns automatic topic creation off for its own namespace
(klokit/topics, the namespace policy autoTopicCreation overrides the broker's setting, so the job's ordinary
standalone serves), then checks that publishing, verifyPublish, subscribing, verifyConsume and a request fail with
the contract's TOPIC_MISSING message and create nothing, that creating the topic through the admin API makes the same
calls work and verifyConsume leaves no subscription behind, that a message whose _DLQ is missing stays on the
subscription and stops the loop and is dead lettered once the _DLQ exists, and that a consumer whose topic is deleted
stops with the contract message. The TypeScript and Python clients have the same tests
(tests/integration/provisioning.test.ts, tests/test_integration_provisioning.py) in namespaces of their own.
KlokTopicAccessBrokerTest (tag broker-auth) needs a broker with authorization: token authentication, no automatic
topic creation, superuser admin. It signs its own tokens with the broker's secret key, then checks that a role without
a grant gets the contract's TOPIC_ACCESS_DENIED message for publish and consume (also from the verify methods), that a
consume grant allows consuming and not publishing, that a produce grant allows publishing, and that a missing topic
is reported as denied without a grant and as missing with a namespace grant. The pipeline job
java-integration-test-auth starts such a standalone as a service; its key and the superuser's token are test fixtures
of that throwaway broker. The TypeScript and Python clients map the same denied results (AuthorizationError) in their
unit tests, taken from such a broker; their connections authenticate only with OAuth2, so they are not run against it.
Locally, a Pulsar standalone with the external listener (as described in the Python client's
tests/test_integration.py) and:
KLOK_TEST_PULSAR_URL=pulsar://localhost:6650 KLOK_TEST_PULSAR_ADMIN_URL=http://localhost:8080 ./gradlew integrationTest
KlokTopicProvisioningBrokerTest alone also runs against a standalone started as klok5, with -e PULSAR_PREFIX_allowAutoTopicCreation=false (KlokRequestReplyBrokerTest needs the default, since it uses
public/default):
KLOK_TEST_PULSAR_URL=pulsar://localhost:6650 KLOK_TEST_PULSAR_ADMIN_URL=http://localhost:8080 ./gradlew integrationTest --tests '*KlokTopicProvisioningBrokerTest'
The broker with authorization for KlokTopicAccessBrokerTest (the values are the CI job's test fixtures):
docker run -d --name klok-pulsar-auth -p 26651:6650 -p 28081:8080 \
-e PULSAR_PREFIX_advertisedListeners="internal:pulsar://localhost:6650,external:pulsar://localhost:26651" \
-e PULSAR_PREFIX_internalListenerName=internal \
-e PULSAR_PREFIX_allowAutoTopicCreation=false \
-e PULSAR_PREFIX_authenticationEnabled=true -e PULSAR_PREFIX_authorizationEnabled=true \
-e PULSAR_PREFIX_authenticationProviders=org.apache.pulsar.broker.authentication.AuthenticationProviderToken \
-e PULSAR_PREFIX_tokenSecretKey="data:;base64,a2xvay1icm9rZXJjbGllbnQtdGVzdC1vbmx5LWtleS1ub3QtYS1zZWNyZXQtMDAwMQ==" \
-e PULSAR_PREFIX_superUserRoles=admin \
-e PULSAR_PREFIX_brokerClientAuthenticationPlugin=org.apache.pulsar.client.impl.auth.AuthenticationToken \
-e PULSAR_PREFIX_brokerClientAuthenticationParameters="token:eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiJ9.7tuftEwcmO_u4J4OGAyICKxm4itDmU0I4YuDZ3QaiDI" \
apachepulsar/pulsar:5.0.0 bash -c "bin/apply-config-from-env.py conf/standalone.conf && exec bin/pulsar standalone -nss -nfw"
KLOK_TEST_PULSAR_AUTH_URL=pulsar://localhost:26651 KLOK_TEST_PULSAR_AUTH_ADMIN_URL=http://localhost:28081 \
KLOK_TEST_PULSAR_TOKEN_SECRET_KEY=a2xvay1icm9rZXJjbGllbnQtdGVzdC1vbmx5LWtleS1ub3QtYS1zZWNyZXQtMDAwMQ== \
./gradlew integrationTest -PklokTestTags=broker-auth
Tests against RustFS
The claim check store's tests against a real S3 store (KlokClaimCheckStoreRustFsTest, tag claimcheck, and the
TypeScript tests/integration/claimcheck.test.ts) need KLOK_TEST_S3_URL, KLOK_TEST_S3_ACCESS_KEY and
KLOK_TEST_S3_SECRET_KEY. CI starts RustFS in the version klok-ai runs as a service of typescript-package-test and
java-integration-test; each test creates a bucket of its own, since the store never does. On a laptop:
docker run -d --name klok-bc-rustfs -p 127.0.0.1:59000:9000 -e RUSTFS_ACCESS_KEY=klok-claimcheck-test \
-e RUSTFS_SECRET_KEY=klok-claimcheck-test-only-not-a-secret rustfs/rustfs:1.0.0-beta.4
export KLOK_TEST_S3_URL=http://127.0.0.1:59000 KLOK_TEST_S3_ACCESS_KEY=klok-claimcheck-test \
KLOK_TEST_S3_SECRET_KEY=klok-claimcheck-test-only-not-a-secret
./gradlew integrationTest -PklokTestTags=claimcheck
(cd typescript/klok-brokerclient-typescript && npx vitest run --config vitest.integration.config.ts tests/integration/claimcheck.test.ts)
The unit tests need no store: KlokClaimCheckRefTest and tests/claimcheck.test.ts run the shared cases of
src/test/resources/claim-check-cases.json (references the extension's class wrote, the key layout and the Signature
Version 4 examples of the S3 documentation), and KlokClaimCheckStoreTest and the TypeScript store tests drive the
store against a stand-in S3 that records every call.
Consumers of the client
Applications built on the Quarkus extension do not test against a broker at all: the extension creates its clients
through a CDI KlokBrokerClientFactory, and the test support module replaces it with a recording factory that captures
every publish and dispatches subscriptions in process. See the extension's testing page.
Running the build
./gradlew build
Besides Maven Central the build resolves from the GitLab group registry
(https://<host>/api/v4/groups/<tenant>/-/packages/maven), where klok-common lands before it reaches Central. Locally
it authenticates with a personal access token from klokGitAuthToken in ~/.gradle/gradle.properties or
KLOK_GIT_AUTH_TOKEN; the host is klokGitlabBaseUrl (host only, a scheme is stripped). The build prints the registry
URL, never the token.
Publishing (./gradlew publish jreleaserFullRelease) is done by the main pipeline only; it needs the Vault secrets of
the CI environment and waits for Maven Central to confirm the deployment, which can take up to an hour.
The subscription loop
The body of the receive loop is the package-private KlokBrokerClient.dispatch(consumer, message, topic, options, handler): it decodes the Pulsar message, runs the handler and acknowledges or negatively acknowledges.
KlokBrokerClientDispatchTest drives it with a mocked Pulsar consumer and message, so the acknowledgement rules (return
acknowledges, throw negatively acknowledges, a requested NEGATIVE_ACKNOWLEDGE negatively acknowledges without an
error) are verified without a broker, and so is the undecodable message: dead lettered with its original bytes,
properties, key and DECODE_ERROR, then acknowledged; negatively acknowledged without a DLQ or when the dead letter
publish fails. KlokBrokerClientSyncReplyTest covers the reply loop body, where an undecodable reply fails its request.
KlokBrokerClientSyncAddressedReplyTest covers addressed request/reply on a mocked Pulsar client: the reply consumer is
non-durable from Latest, every request names the reply subscription in klok-reply-subscription, a reply is keyed with
it and batched by key, and a reply no request waits for is passed over without decoding it.
KlokBrokerClientReceiveLoopTest runs the loop itself on a stubbed consumer that reports itself disconnected, returns
nothing and fails a receive, as a reconnecting consumer does, and checks that the next message is still handled and the
loop still counted by runningReceiveLoops; that a consumer closed while the client is open ends every loop and says
why (receiveLoopFailure); and that a closed client ends every loop. KlokBrokerClientConcurrencyTest covers several
loops on one consumer.
KlokBrokerClientHandlerErrorTest throws what a real handler can: a recursion that overflows the stack and an array too
large for any heap. It checks that the message is negatively acknowledged and the next one handled, on the single
message and batch loops of both clients and the reply loop; what each kind of Error does to subscriptionHealth();
and that a payload that overflows the decoder is dead lettered; that the next message does not meet what the handler
left on its thread; and that a loop that keeps failing leaves the pool its size. KlokHandlerErrorBrokerTest (tag
broker) does the same against a real broker, where the message comes back and the subscription keeps reading.
KlokConnectionWatchdogTest holds the RECEIVE_LOOP_STOPPED and FATAL_ERROR lines to the log contract.
The connection watchdog
KlokConnectionWatchdogTest drives a watchdog of its own with a clock it moves by hand, on a mocked Pulsar client, so
nothing waits for real seconds. It checks the exact line format, which is the contract the console-log alerts match. It
also checks:
- a disconnect within the grace period stays quiet;
- a producer disconnected past it is logged on every check;
- after a minute the producer is created again, and its return is logged;
- a failed recovery is logged and retried after the retry interval;
- a durable consumer is reported but left to Pulsar;
- a send or a request that times out drops its producer;
- a requester's reply consumer is subscribed again;
- a producer disconnected for more than a minute is dropped before a send.
The test task turns the JVM's own watchdog off (klok.broker.health.enabled=false), so it never acts on the other
tests' mocks.
KlokConnectionRecoveryBrokerTest (tag broker) checks against a real broker:
- a topic unload is a normal reconnect: the same producer carries on, and nothing is logged;
- a request producer and a reply consumer created again by the watchdog carry the next request;
KlokConnectionHealth.ofAllClients() lists the producers and consumers of a request.
A real outage cannot be staged in the pipeline, which has no Docker. It was checked locally against a Pulsar 5.0.0
standalone: requests every 3 seconds, with the watchdog's timing shortened through the KLOK_BROKER_HEALTH_* variables,
while the standalone was frozen with docker pause for 90 seconds and then unpaused. The result is in the merge request
that added the watchdog (#34).
KlokBytesBrokerClientTest runs the bytes client through the same loop body, receive loop and reply loop, and covers
what is its own: the bytes schema, the octet stream body type, the canonical-only properties, the request handler and
the _Request/_Response pairing.
Benchmark
./gradlew benchmark runs the tests tagged benchmark, which ./gradlew test leaves out, and prints the results;
nothing is asserted about speed. KlokBrokerClientBenchmark measures the per message payload and properties cost of the
typed and the bytes client without a broker, and, when KLOK_BENCHMARK_SERVICE_URL is set, publishes and consumes
through a broker without authentication. A throwaway standalone is enough; the client asks for the external listener,
so the broker must advertise one:
docker run -d --name klok-brokerclient-bench -p 36650:6650 -p 38080:8080 \
-e PULSAR_PREFIX_advertisedListeners="internal:pulsar://localhost:6650,external:pulsar://localhost:36650" \
-e PULSAR_PREFIX_internalListenerName=internal \
apachepulsar/pulsar:5.0.0 bash -c "bin/apply-config-from-env.py conf/standalone.conf && exec bin/pulsar standalone -nss -nfw"
KLOK_BENCHMARK_SERVICE_URL=pulsar://localhost:36650 ./gradlew benchmark
The published results, with the environment and the network they were measured on, are in the user guide: Broker
Throughput And Capacity. Record
the machine, the broker, the versions and the round trip time with any new figures.