@klok-integration/brokerclient (in typescript/klok-brokerclient-typescript/) is the broker client for Node.js and
TypeScript. Version 0.3 follows the Python client 0.3 point by point: it puts the same bytes and properties on the
broker as the Java client and the Quarkus extension, so a Node process — a web backend, a worker, klok-cli — is a full
member of an integration chain. It replaces the 0.1 client (@klok/klok-brokerclient-typescript), which followed none
of the platform's conventions and could not be imported
(#2,
#11). The typical uses are a publisher,
such as a web backend or klok-cli bringing something into the platform, and a worker that takes messages from a
topic.
Installing
npm install @klok-integration/brokerclient
The package is public on registry.npmjs.org under the Apache-2.0 licence, ships ES modules and CommonJS with types, and
needs Node 18 or later. It depends on pulsar-client (the Apache Pulsar Node client, a native addon) and avsc.
The platform broker runs Pulsar 5.0.0. pulsar-client 1.18.0, the latest Node client, connects to it with the same
protocol as before; the tests below run against a Pulsar 5.0.0 standalone.
pulsar-client downloads a prebuilt binary for the platform in its install script. Version 1.18.0 has prebuilt binaries
for Linux x64 and arm64 with glibc and with musl (Alpine images such as node:22-alpine), macOS x64 and arm64, and
Windows; the install needs network access to archive.apache.org. npm 12 runs no install script of a dependency unless
the project allows it, so a project on npm 12 adds this to its package.json:
"allowScripts": { "pulsar-client": true }
If archive.apache.org is slow or resets the connection, the install script compiles the module instead, which needs
Python and the Pulsar C headers and fails on most images with an error that says nothing about the network. The download
can be pointed at a mirror with the environment variable npm_config_pulsar_binary_host_mirror, which node-pre-gyp
reads. It replaces the scheme and host of the default https://archive.apache.org/dist/pulsar/pulsar-client-node/, so
the mirror must serve the same path below its address:
npm_config_pulsar_binary_host_mirror=https://mirror.example.com/dist/pulsar/pulsar-client-node/ npm install
Klok's own CI sets it on its runners, to a caching proxy on the runner host, so a job in a container the runner starts
needs nothing, and an image build declares ARG npm_config_pulsar_binary_host_mirror before its npm ci (klok docs read klok-environment-build-ci-templates, Installing pulsar-client). An empty value is ignored. npm 12 warns Unknown env config about the variable, because node-pre-gyp reads it without npm; the install works. Elsewhere, such as a
laptop or the customer's own CI, nothing is set and the download goes to archive.apache.org.
Payloads are the classes of the TypeScript datamodel packages every datamodel publishes
(@klok-integration/datamodel-<artifact> for public datamodels, @<tenant>/datamodel-<artifact> in the tenant's GitLab
registry; klok-gradle-plugin#2). They carry the
Avro schema Java registers on the topic (KLOK_AVRO_SCHEMA) and encode themselves (toAvroBuffer / fromAvroBuffer);
the client registers exactly that string, so Java and TypeScript share one schema version. A plain object or a
hand-written class is refused, since a Java consumer could not read it.
A Next.js application keeps both packages out of its server bundle, since pulsar-client loads a native module:
// next.config.js
module.exports = { serverExternalPackages: ['@klok-integration/brokerclient', 'pulsar-client'] };
A publisher
A web backend, klok-cli or any other process that brings something into the platform publishes a record. The examples
use the AI datamodel, a tenant wide model of tenant klok, so its package @klok/datamodel-klok-ai-v1 is in the GitLab
npm registry rather than on npmjs.org:
import { KlokBrokerClient } from '@klok-integration/brokerclient';
import { KlokAiTaskRequestV1 } from '@klok/datamodel-klok-ai-v1';
const client = new KlokBrokerClient(); // configuration from the environment, one per process
const sent = await client.publish(client.topic(KlokAiTaskRequestV1, 'summaries'), new KlokAiTaskRequestV1({ ... }), {
subject: document.id, // ce-subject: the business id
});
sent.corrGlobal; // follow the call in the Klok logs (klok_corr_global)
publish resolves when the broker has acknowledged the message and rejects with a KlokSendMessageException otherwise.
The client keeps one producer per topic, made by the first publish there; a topic carries one record class.
A worker
import { KlokBrokerClient } from '@klok-integration/brokerclient';
import { KlokAiTaskRequestV1, KlokAiTaskResultV1 } from '@klok/datamodel-klok-ai-v1';
const client = new KlokBrokerClient(); // configuration from the environment
await client.subscribe(client.topic(KlokAiTaskRequestV1, 'summaries'), KlokAiTaskRequestV1, async (message) => {
const result = new KlokAiTaskResultV1({ taskId: message.taskId, status: 'FINISHED' });
await client.publish(client.topic(KlokAiTaskResultV1, 'summaries'), result, { key: message.key });
// returning nothing acknowledges the message
}, { subscriptionName: 'ACM010P1_Summarize', concurrency: 4 });
await client.runUntilSignal(); // until SIGTERM or SIGINT, then a clean shutdown; the process exits
Every message the worker handles shows up in the Klok logs like a Java route's invocation (see Logging below) without a
line of code for it.
Configuration
configFromEnv() reads the variables of the wire contract (connection) and the identity of the process; new KlokBrokerClient() without arguments uses it. createConfig({...}) builds a configuration from explicit values and the
same defaults, without the environment.
| Variable |
Default |
Meaning |
KLOK_BROKER_SERVICE_URL |
pulsar+ssl://broker.ipaas.se:6651 |
broker |
KLOK_BROKER_AUTH_URL |
https://auth.ipaas.se/auth/realms/klok |
OAuth2 issuer; an empty string turns authentication off (a local standalone) |
KLOK_BROKER_AUTH_CLIENT_ID, KLOK_BROKER_AUTH_CLIENT_SECRET |
required with an issuer |
client credentials |
KLOK_BROKER_AUTH_AUDIENCE |
pulsar |
|
KLOK_BROKER_TLS_TRUST_CERTS_FILE_PATH (or KLOK_CA_FILE_PATH) |
the bundled Klok Root CA |
the client gives Pulsar a copy followed by the certificates Node trusts, for the OAuth2 issuer |
KLOK_TENANT, KLOK_ENVIRONMENT, KLOK_DOMAIN |
|
topic names and the context of new chains |
KLOK_SOLUTION_ID, KLOK_ROUTE_ID |
|
klok-solution-id, klok-route-id, ce-source |
KLOK_INSTANCE (or KLOK_INSTANCE_NAME) |
|
klok-instance |
KLOK_LOGEVENTS_ENABLED |
true |
publish the invocation log events (the log lines are always written) |
KLOK_LOGEVENTS_TOPIC_PURPOSE |
|
suffix of the log event topic, as klok.logevents.topic-purpose in Java |
KLOK_DEV_URL |
https://klok.dev |
base URL of the request link in the messages of a missing topic or grant (klokDevUrl) |
The connection uses the listener name external and OAuth2 client credentials, like the Java and Python clients. The
Klok Root CA ships with the package (klok-root-ca.cert.pem, the same file as the Java and Python clients'). A TLS
connection (a pulsar+ssl:// or https:// service URL, or any URL with a CA file configured) trusts that CA, and the
certificates Node trusts (its roots and NODE_EXTRA_CA_CERTS) so that the native client can verify the OAuth2 issuer
(trustFilePath), and verifies the broker's host name (tlsValidateHostname: true): the certificate must name the host
the client connects to. That is a Klok rule, set explicitly in all three clients, not a library default; the broker
certificates carry the advertised names. A pulsar:// connection (a local standalone) has no TLS.
Topics, properties and CloudEvents
naming holds the topic rules of KlokNamingConventions (persistent://<tenant>[_<env>]/<domain>/<Model>[_<purpose>],
ReqRes_<Req>_<Reply>[_<purpose>]_Request / _Response, <topic>_DLQ), properties the klok-* names and the
invocation context (KlokContext), cloudevents the ce-* attributes in binary mode. The package vendors the wire
contract of klok-common (wire-contract/, shipped in the package) and its tests run topic-naming-cases.json,
property-forms-cases.json and topic-provisioning-cases.json and check every name, rule and message template against
it.
naming.companionTopics(topic) lists the topics that exist together with a topic (topics.companions in the contract):
its _DLQ, and for a ReqRes_…_Request topic also the _Response topic and its _DLQ; a _DLQ topic has none. The
rules are naming.COMPANION_RULES, the contract's data.
naming.parseTopicName(name) takes a topic name apart, as KlokNamingConventions.parseTopicName in Java does, and
throws a TypeError for a name that breaks the conventions:
import { naming } from '@klok-integration/brokerclient';
naming.parseTopicName('persistent://klok/common/KlokAiTaskRequestV1_ai.chat_DLQ');
// { persistent: true, tenant: 'klok', environment: 'prod', domain: 'common',
// simpleName: 'KlokAiTaskRequestV1_ai.chat_DLQ', model: 'KlokAiTaskRequestV1', purpose: 'ai.chat',
// requestModel: null, replyModel: null, requestReplySide: null, dlq: true }
A request/reply topic gives requestModel, replyModel and requestReplySide (Request or Response) instead of
model; a simple name gives null for the scheme, tenant, environment and domain. The purpose is the one the publisher
chose; who reads a topic is never part of its name. The 0.2 names (klokSolutionId and friends) are never written or
read, as the contract requires of every client except Java 0.3; klokChainId, the oldest name of the global id, is read
(never written) by the correlation rules below.
What a published message carries
| Property |
Value |
klok-corr-global, klok-corr-platform, klok-invocation-id, klok-parent-invocation-id, klok-task-id, klok-task-type |
the context (below) |
klok-correlation-id |
the global id again, for services built before the three ids (the transition) |
klok-tenant, klok-domain, klok-environment, klok-solution-id, klok-route-id, klok-instance |
the configuration |
klok-body-type |
application/vnd.apache.avro+binary |
klok-sent-time |
epoch milliseconds |
ce-specversion, ce-id, ce-time, ce-source, ce-type |
CloudEvents binary mode; ce-type defaults to dev.klok.<tenant>.<domain>.<Model>.published, eventType overrides it |
ce-datacontenttype |
the Avro body type |
ce-subject |
subject, the business id of the object |
ce-dataschema |
KLOK_DATA_SCHEMA of the record class: urn:klok:schema:<docId>:<Record>:<Java version> |
ce-klok* |
every context property as an extension attribute (ce-klokcorrglobal, ...) |
The message key is the global id unless key is given. properties are added last and win, except klok-instance and
klok-sent-time, which are always this client's (properties passed on from a consumed message must not publish the
upstream's), and klok-corr-service and klok-corr-global-source, which never go on a message. Message ids are written
as the Java client writes them (ledger:entry:partition[:batchIndex]), not in the (ledger,entry,...) form of the C++
client underneath, so klok-original-message-id and klok.quarantine-ref read the same from every client.
Context
The context of a message is a KlokContext: the three correlation ids of the klok-common page Log Fields And
Correlation (corrGlobal with
corrGlobalSource, corrPlatform, corrService), invocationId, parentInvocationId, taskId, taskType and the
identity (tenant, domain, environment, solutionId, routeId, instance). correlationId is kept as a
deprecated name of corrGlobal, as a getter and as an input of the constructor.
| Where the context comes from |
Global id |
Platform id |
Service id |
a consumed message (the handler's context, KlokContext.fromProperties(...).child()) |
the message's, by the order of the page (klok-corr-global, then klok-correlation-id, klokChainId, traceparent, ...), else new |
klok-corr-platform, else klok-correlation-id, then klokChainId, else new |
new |
an HTTP request (KlokContext.fromHttpHeaders(headers)) |
from the headers by the same order, else new |
new: an HTTP caller is outside the platform |
new |
a timer, a script, a file, or a publish outside a handler (KlokContext.newChain()) |
new (generated) |
new |
new |
a sub invocation in the same service (context.sub()) |
kept |
kept |
kept |
A handler runs in the context derived from the message it received (the same global and platform ids and task, a new
service id, a new invocation whose parent is the producer's, this process as tenant, domain, route and instance), and
publish inside it uses that context unless one is given. client.invocation() fills whatever id the given context
lacks, so none of the three is empty inside an invocation. The running context follows asynchronous calls through
AsyncLocalStorage, the Node counterpart of Python's context variable, so concurrent handlers never see each other's
context; currentContext() returns it and logFields() returns it under the log keys (klok.corr-global,
klok.corr-platform, klok.corr-service, klok.corr-global-source, ...) for a logger that adds fields to every entry,
such as a pino mixin; logField(name) gives the OpenSearch field of a key (klok_corr_global) for a logger that
writes JSON. runInContext(context, fn) runs code in a given context.
The global id rules are also exported on their own, for code that receives a request itself, such as a web framework's
middleware: globalFromHeaders(headers) gives { value, source } or null, globalOrNew(headers) creates one when
nothing usable arrived, and platformFromMessage(properties) reads the platform id of a consumed message
(correlation.* has the constants). They run the correlation-cases.json of the wire contract.
Subscriptions and outcomes
subscribe(topic, RecordClass, handler, options) resolves once the consumer is subscribed. SubscriptionOptions
mirrors the Java options: the subscription name is the route id of the consumer by convention, the type is Exclusive by
default and becomes Shared when concurrency is above 1 and no type is given (Failover and KeyShared can be
chosen), the initial position is Latest; negativeAckRedeliveryDelayMs, ackTimeoutMs and receiverQueueSize pass
through to Pulsar. routeId (default: the client's KLOK_ROUTE_ID, else the subscription name) is the route the
handler implements, and its leg letter gives the direction of its log entries unless one is given.
| Handler does |
Outcome |
Logged |
returns nothing or 'ACKNOWLEDGE' |
acknowledged |
FINISHED |
| throws anything else |
called again inside the same invocation by retry (the Java defaults: 5 retries, 1 s backoff doubling up to 60 s); when they are used up, dead lettered (or negatively acknowledged with retry: { dlqEnabled: false }) |
PROGRESS at ERROR per retry, then FAILED QUARANTINED (or UNRESOLVED) |
returns 'DEAD_LETTER' or throws new KlokDeadLetter(message, code) |
not retried: republished to <topic>_DLQ with klok-error-code, klok-error-message, klok-retry-count, klok-original-topic, klok-original-message-id, klok-failed-route-id (the handler's route), then acknowledged |
FAILED QUARANTINED with klok.quarantine-ref = <dlq topic>#<message id of the copy> |
returns 'NEGATIVE_ACKNOWLEDGE' or throws KlokNegativeAcknowledgement |
not retried: given back to the broker, whose redelivery is a new invocation |
FAILED UNRESOLVED |
A message that cannot be decoded is dead lettered with DECODE_ERROR at once, since no retry can help it. A dead letter
carries the original bytes and properties and is published with the payload's schema; when it cannot be published the
message is negatively acknowledged instead. Closing a subscription while a handler waits in a retry backoff ends the
wait and gives the message back to the broker (UNRESOLVED).
Concurrency is concurrency receive loops on one consumer, as in the Java and Python clients: each loop awaits
consumer.receive(), handles the message and acknowledges it, so up to concurrency messages of the subscription are
in flight in one process. The loops await receive() without a timeout on purpose: the Node Pulsar client serves that
call asynchronously in its C++ client, whereas receive(timeout) and a reader's readNext() occupy a thread of Node's
libuv pool (four by default, shared with file system, DNS and crypto work) for as long as they wait. A loop ends only
when its subscription or the client is closed; while Pulsar reconnects a consumer the receive simply waits, and a failed
receive is retried after a pause that doubles up to 5 s. subscription.runningLoops counts the loops, and
subscription.close() stops one subscription.
Every consumer is created with the metadata klok-route-id (the subscription's route), klok-instance and
klok-subscription-concurrency, and every producer with klok-route-id (the client's KLOK_ROUTE_ID) and
klok-instance; the broker shows them in the topic stats. properties.consumerMetadata and
properties.producerMetadata build them, properties.CONSUMER_METADATA_KEYS and PRODUCER_METADATA_KEYS name them.
The reply reader of request/reply carries none, because the Node Pulsar reader takes no properties. How to read them is
in Authentication and subscriptions.
Missing topics and grants
Topics on the Klok broker are never created automatically, and a role publishes and consumes only where its grants allow
(see Missing topics and grants). The Node client reports both
with typed errors whose message is the wire contract's text, word for word what the Java and Python clients say:
| Error |
code |
Node client result behind it |
KlokTopicMissingException |
TOPIC_MISSING |
Failed to create producer: TopicNotFound (and consumer, reader) |
KlokTopicAccessDeniedException |
TOPIC_ACCESS_DENIED |
AuthorizationError, NotAllowedError |
Both extend KlokTopicProvisioningException (a KlokBrokerClientException) with topic, role
(service-account-<authClientId>, client.brokerRole), operation (publish or consume), code and retryable: false. publish and reply reject with them, subscribe and serve too; request rejects with a
KlokRequestNotSentException (a KlokRequestReplyException) that carries the contract message and has the typed error
as its cause (findTopicProvisioningFailure(error) finds it). A missing reply topic fails the request before anything
is sent. A producer that could not be created is not kept, so the next publish tries again once the topic exists.
A dead letter to a _DLQ that is missing or refused negatively acknowledges the message once and stops that receive
loop with the contract message; subscription.failure holds the error and subscription.runningLoops drops, so the
message is not redelivered forever. provisioning holds the rendering (topicMissingMessage,
topicAccessDeniedMessage, requestUrl, roleOfClient) and the contract's templates, and topicProvisioningFailure
maps any Node client error.
try {
await client.publish('persistent://acme/finance/InvoiceV1_created', invoice);
} catch (error) {
if (error instanceof KlokTopicMissingException) {
console.error(error.message); // what is missing, the klok.dev request link, who approves it, the Git entry
}
throw error;
}
Request/reply
// asks: an ODL search in the platform's common domain, whatever the caller's own domain is
const reply = await client.request(new KlokOdlSearchV1({ ... }), KlokOdlSearchResponseV1, { domain: 'common', timeoutMs: 5000 });
// answers: the handler returns the reply payload
await client.serve(KlokOdlSearchV1, KlokOdlSearchResponseV1, (message) => buildAnswer(message.payload), 'ACM010P1_Search');
The request goes to ReqRes_<Req>_<Reply>[_<purpose>]_Request with klok-reply-topic and klok-reqres-id; the reply
goes to that topic with the same id and continues the request's chain. domain resolves both topics of the pair in
another domain (platform services answer in common), requestTopic and replyTopic take names no rule covers, and
serve(..., { domain }) answers there.
- The client reads a reply topic with one non-durable reader per topic, created before the first request is sent, so
the first reply is never missed, and shared by all concurrent requests, which it completes by
klok-reqres-id; replies
to other requesters on the same topic are passed over. A reader's subscription (<replySubscription>-reader-<random>)
exists only while the reader is connected: it is gone after close() and after the process dies, so no durable
subscription is left accumulating every reply on the broker
(#10). A non-durable cursor has nothing to
acknowledge, so the contract's "acknowledges every reply" holds trivially. The reader delivers through a listener, which
the Node client runs on its own listener thread; readNext() would hold a libuv thread.
- A request names the reader's prefix. The Node
ReaderConfig takes a subscriptionRolePrefix and a readerName (the
consumer's name, not the subscription's), and the random part of the subscription name is not exposed, so every reader
of a client has the prefix client.replySubscription (reply-subscriber-<clientId>-<uuid>, unique per client instance)
and every request carries it in klok-reply-subscription (a value passed in properties is replaced). The broker's
entry filter delivers a reply keyed with it to the reader alone; the client still completes replies by klok-reqres-id
and passes over any other reply without decoding it.
reply and serve key addressed replies: a request that carries klok-reply-subscription (from any current requester)
gets a reply keyed with that value and carrying the property; any other reply is keyed by its correlation id. Reply
producers are created with batchingType: 'KeyBasedBatching', so one batch holds replies to one subscription only,
which the broker's entry filter
(klok-pulsar-entry-filter) needs to deliver each reply
to its requester alone. Why: Addressed replies on non-durable reply subscriptions in Design
decisions.
- Each pending reply is kept exactly as long as its own
timeoutMs (default 5000), the wire contract's
requestReply.pendingReplyLifetime; there is no shared 30 s time to live, so a slow service with a long timeout can be
called (#9). A timeout, a send failure or a
reply that cannot be decoded rejects with a KlokRequestReplyException, and close() rejects the requests still
waiting.
- A request that provably never left rejects with the subclass
KlokRequestNotSentException, which is safe to send again:
its reply topic could not be read, a topic is not provisioned, or its send failed with another result than TimeOut or
AlreadyClosed. The Node client rejects a send with Failed to send message: <result>, and after those two the broker
may have stored the request all the same; a producer that could not be created (Failed to create producer: ...) sent
nothing. Why: A request that never left says so in Design decisions.
Logging
The client logs work the way the Quarkus extension logs an invocation, following serviceLogging of the wire contract:
START when it begins, PROGRESS entries while it runs, then exactly one FINISHED or FAILED. ERROR and WARN are
levels, not statuses, so a retry that ends well gives a FINISHED chain with an error counted. The levels are the five
of every log type: TRACE, DEBUG, INFO, WARN, ERROR.
Each entry is written twice:
- a log line on the client's logger,
[START] ACM010I1_ImportArticles started (global=... invocation=... 0ms), with the
klok.* keys (klok.status, klok.leg-id, klok.duration-ms, the three correlation ids and the other context ids) as
fields. The logger is the console unless one is passed (new KlokBrokerClient(config, { logger })): any object with
debug, info, warn and error(message, fields), so pino or winston plug in with a line of adapter code;
- a
KlokLogEventV6 on persistent://<tenant>[_<env>]/common/KlokLogEventV6[_<purpose>], keyed by the global id, which
klok-egress-opensearch indexes under the field names of Log Fields And
Correlation and aggregates into
the transaction, exactly as for Java routes. Its message is the readable text: the text of a warning or an error as it
is, otherwise the status name and what the route said (PROGRESS called kloker, FAILED failed (QUARANTINED): CODE text). The outcome values have fields of their own (outcome.step, outcome.retryAttempt, outcome.errorCode, ...),
and a route's own values ({ upstream: 'kloker' }) go in fields. Events go through a bounded queue (10000) that is
sent in the background, never on the caller's path; when the broker refuses one it is left alone for a minute and events
are dropped with a throttled warning. close() sends what is queued before it closes. Without KLOK_TENANT there is no
log event topic and only the lines are written.
Work that is not a subscription handler, a web request that publishes, a klok-cli command or a script, becomes an
invocation with client.invocation(): START before, FINISHED after, FAILED when it throws (and the error is
thrown on). What it publishes carries the invocation's context:
await client.invocation({ routeId: 'ACM010I1_ImportArticles' }, async (invocation) => { // direction IN, from the leg
for (const article of await fetchArticles()) {
await client.publish(client.topic(ArticleV1), article);
}
invocation.warning('3 articles without a title were skipped');
});
Inside an invocation or a handler, client.log adds entries to the running invocation:
client.log.progress('called kloker'); // PROGRESS, INFO, klok.step
client.log.warning('slow upstream', { upstream: 'kloker' }); // PROGRESS, WARN, message (+ fields)
client.log.error('one prompt refused', error, { prompt: 'p2' }); // PROGRESS, ERROR: counted, the invocation goes on
An error's code (a string, as KlokDeadLetter carries) becomes klok.error-code, else INTERNAL as in Java; so a
Node system error reports its own code (ECONNREFUSED). A log event's threadId names the receive loop (Node has no
threads), main outside one; in Kubernetes process.podName and process.namespaceName name the pod. The client
carries the V6 classes in vendor/kloklogevent-v6/, the npm package the datamodel pipeline of
klok/datamodel/common/klok-log-event-v6 published (1.0.0-build.261116125437), copied unchanged, and exports them
(below). The V4 classes (vendor/kloklogevent-v4/) stay for reading the events of services built before V6.
Reading the log events
A process that follows the log events itself, as klok.dev's Run → Logs does beside the receivers of KLK001, subscribes
to the log event topics with the models the client exports, and reads each event with readLogEvent. It reads a
KlokLogEventV6 and, while services built before V6 still publish, a KlokLogEventV4, into one LogEntry with the V6
names:
import { KlokBrokerClient, KlokLogEventV4, KlokLogEventV6, readLogEvent, servicelog } from '@klok-integration/brokerclient';
const client = new KlokBrokerClient();
const options = { subscriptionName: 'klok-dev-log-transactions', subscriptionType: 'Failover', logEvents: false } as const;
await client.subscribe(servicelog.logEventTopic('klok', 'prod'), KlokLogEventV6, async (message) => {
const entry = readLogEvent(message.payload);
// entry.status, entry.level, entry.corrGlobal, entry.corrPlatform, entry.corrService, entry.invocationId,
// entry.routeId, entry.errorCode, entry.fields['klok.file.name'], ...
}, options);
// the transition: the same reader for the services that still publish V4
await client.subscribe('persistent://klok/common/KlokLogEventV4', KlokLogEventV4,
async (message) => { const entry = readLogEvent(message.payload); /* entry.version === 4 */ }, options);
readLogEventPayload(topic, data) decodes the Avro bytes of either topic itself (V4 when the topic's model is
KlokLogEventV4, V6 otherwise), for a reader that does not go through subscribe.
logEvents: false on that subscription. Every handled message is otherwise an invocation with its own log events,
published onto the topic the subscription reads: each event would bring another. The receivers in
klok-egress-opensearch turn them off the same way (KLK001.logevents.enabled=false).
- What
readLogEvent gives. The fields of the page Log Fields And
Correlation, without klok_ and
in camel case: version (6 or 4), the status, level and direction; corrGlobal, corrGlobalSource, corrPlatform,
corrService, the invocation, parent invocation and task ids and the task type; tenant, environment, domain, solution,
leg, route and route instance; instance, host, pod and namespace; the trace and span ids; the time and duration; the
error code, the step, the retry attempt and maximum, the disposition, outcome and quarantine reference; the exception;
the message ids and endpoint; message, the readable text; fields, the route's own values by name, and headers. An
empty text reads as null.
- A V4 event reads as the transition says.
globalChainId is both corrGlobal and corrPlatform, there is no
corrService, WARNING reads as WARN and FATAL as ERROR, message is the text of a warning or an error (klok.message)
or else the status the event carried, and fields holds every extraInfo entry.
- What it leaves to the reader.
status is null for a V4 message that is not one of the contract's statuses: the
forms of 1.x routes (IN_START, OUT_DONE, 202, ...) or free text, which message carries as sent. A reader that
counts them, as the receivers do (ServiceStatusMapping in klok-egress-opensearch), maps them itself. The chain
status of a set of invocations is servicelog.chainStatus, the contract's rule.
- The record classes are exported with their generated names:
KlokLogEventV6, LogContextV6, LogOutcomeV6,
LogExceptionV6, LogProcessV6, LogMessageInfoV6, LogKeyValueV6 and the LogLevelV6, LogStatusV6 and
LogDirectionV6 values; and KlokLogEventV4, LogMessageType, LogMessageExceptionType, LogMetadataInfoType,
LogRuntimeInfoType, extraInfo, businessContextId and the LogLevelType values.
Lifecycle
One client is one connection; create it once per process and share it. close() stops the subscriptions (their running
handlers finish, up to timeoutMs, 10 s by default; a handler waiting in a retry backoff stops waiting and its message
goes back to the broker), closes the reply readers and rejects the requests still waiting, sends the queued log events,
flushes and closes the producers and closes the connection. It resolves when all of that is done, and nothing of the
client keeps the process alive afterwards, so a script or a CLI command simply ends. Publishing keeps working while a
handler finishes during the close; new subscriptions and requests are refused.
runUntilSignal() is the end of a worker: it keeps the process running until SIGINT or SIGTERM (or until close() is
called elsewhere), then closes the client and resolves. A second signal during the close ends the process the default
way. A web backend that shares one client across requests closes it from its own shutdown hook instead.
Receiving another version of a schema
The Java and Python clients decode a message with the schema version its producer used, looked up in the topic's schema
registry, and let Avro resolve it to their own. The Node Pulsar client cannot: its Message has no schema version
(checked in pulsar-client 1.18.0, whose typings and native binding expose topic, properties, data, ids, keys and
timestamps, but not the version the C++ client carries). The TypeScript client therefore decodes every message with the
schema of its datamodel package. When a producer used another version of the datamodel, the bytes usually do not fit
(avsc reports a truncated buffer or trailing data), and the message is dead lettered with DECODE_ERROR instead of
being misread; a change that keeps the byte layout, such as a field of the same type replaced in the same position of
the (alphabetical) reflected schema, would be read with the new field names. Keep the producers and consumers of a topic
on one datamodel release until the Node client exposes the schema version. The generated packages already take a writer
schema (fromAvroBuffer(data, writerSchema)), so the client can use it the day it is available.
Verified
- Unit tests (
npm test, 392): the fixture cases of the vendored wire contract (the correlation cases included), the
contract's names and defaults, the TLS settings, payloads and the Java-encoded fixture, publishing, outcomes, retries,
dead letters, log events of every outcome and reading them back (readLogEvent, V6 and V4), receive loops,
request/reply and the lifecycle, against a fake Pulsar.
- A real broker (
npm run test:integration, Pulsar 5.0.0 standalone): the registered schema is KLOK_AVRO_SCHEMA
byte for byte (admin API); publish and subscribe; concurrency; request/reply across clients and domains; no reply
subscription left after close or after the requester is killed; dead letters; the log events of an invocation; a worker
process exits after close() and after SIGTERM.
- Python (the same run): TypeScript publishes and the Python client 0.3 consumes, and the other way round, with the
same payload (enum, nested list, timestamp), global and platform ids, key, parent invocation and CloudEvents attributes.
- Java, by hand on 2026-09-25 against a Pulsar 4.0.4 standalone, with
klok-brokerclient-java 0.3.3 of this
repository and the KlokTaskEvent_v1 jar whose reflected schema is the fixture's byte for byte: TypeScript publishes
and Java consumes (payload, key, correlation and invocation ids, CloudEvents attributes, and the message carries the
schema version Java has, 0, so both share one version); Java publishes and TypeScript consumes (a microsecond timestamp
arrives with milliseconds); and Java decodes the TypeScript client's log events (START and FINISHED of an invocation()
and of a handler) with the KlokLogEventV4 class of the catalog's jar, the one klok-egress-opensearch reads them
with.
- Platforms: the pack-and-import smoke test and the unit and integration tests passed in
node:22-alpine (musl) on
linux/amd64 and linux/arm64 and in node:22-bookworm-slim (glibc) on both, with the prebuilt pulsar-client binaries,
against a Pulsar 4.0.4 standalone; against Pulsar 5.0.0 they pass on macOS arm64 with Node 26 and in the CI test job
(node:22-bookworm-slim).
Releases
Releases follow npm's recommendation, the same way klok-cli is published (klok-docs/distribution/public-cli.md in
klok/application/klok-integration-agent): the pipeline only stages a version, and a person publishes it with 2FA.
No token bypasses 2FA.
- Every change on
main.
typescript-package-test runs the unit, integration, cross-language and smoke tests; merge requests run it too.
typescript-package-build runs npm run release -- pack. That sets the version <major.minor>.<pipeline iid> from
package.json, builds, runs npm pack and smoke tests the tarball, which the job keeps as an artifact for a week.
typescript-package-release runs npm run release -- publish on the Klok build image. That stages the tarball with
npm stage publish and skips a version the registry already has.
- A maintainer then approves the staged version with 2FA, under Staged Packages on npmjs.com or with
npm stage approve <id>.
- Staging needs npm 11.15 and Node 22.14 or newer; the build image carries npm 12, and the script checks both.
- The token.
NPM_TOKEN is in tenant klok's CI environment object in Vault, which the build image's Vault login
exports with the tenant CI role klok-ci, as for every pipeline of the tenant (Authentication in CI and deployment in
build-ci-templates).
It is the same stage-only token klok-cli uses: Read and write (stage only), no 2FA bypass, with
@klok-integration/brokerclient among its packages and scopes.
- The first version is published by hand, from the pipeline's tarball. A package that does not exist cannot be staged.
The release job then stages nothing, logs where the tarball is and exits with code 3, which the pipeline shows as a
warning. A person with 2FA downloads the tarball from the artifacts of
typescript-package-build in that pipeline and
publishes it:
npm login # web login against registry.npmjs.org, with 2FA
npm publish klok-integration-brokerclient-<version>.tgz --access public
If the stage-only token lists packages rather than the whole @klok-integration scope, the new package is then added to
it on npmjs.com. The next change on main is staged as usual. The first version is the exact tarball the pipeline built
and smoke tested, never a build from a laptop.
Timestamped versions from the dependency catalog, as the Java client has, are
#20.
Not there yet
- The schema version of a received message is not known (above); needs
getSchemaVersion() in the Node Pulsar client
(#24).
- Async task semantics: creating a task and publishing its request the way
KlokTaskService does, adopting a
klok-task-id, publishing KlokTaskStatusEventV1 progress
(#25;
#3 for the Python client). A worker publishes
its result and any status events itself.
- Claim check references on the message (
klok-claimcheck-ref): the client has the claim check store
(KlokClaimCheckStore, Claim check) but neither resolves the property before decoding nor stores a
payload above a threshold on publish (#27).
- Releases are versioned per pipeline and not written to the dependency catalog
(#20).
- On the platform broker the client publishes in every
klok_docs_send job: klok-cli's klok docs send sends each
documentation payload with it, logged in with the tenant's CI broker client credentials. Verifying subscriptions and
request/reply against broker.ipaas.se over a long-running connection is
#32.
- OpenTelemetry metrics are not in the client, as in the Python client. The Pulsar client's own warnings go to the
client's logger through a handler that is global to the process, so the last client created in a process owns it.