Python client and workers
klok-brokerclient (in python/klok-brokerclient-python/) is the broker client for Python. It puts the same bytes and
properties on the broker as the Java client and the Quarkus extension, so a Python process can be a full member of an
integration chain: consume what a Java route publishes, publish what a Java route consumes, answer requests and ask
questions. The typical use is a worker, for example an AI worker that takes tasks from a topic and publishes
results.
Installing
pip install klok-brokerclient klok-datamodel-klok-ai-v1 \
--index-url "https://__token__:<token>@git.klok.dev/api/v4/groups/<group id>/-/packages/pypi/simple"
Payloads are the classes of the datamodel packages every datamodel publishes (<tenant>-datamodel-<name>, see
"Python datamodel packages" in the Gradle plugin documentation). They carry the Avro schema Java registers on the topic;
the client registers exactly that string, so Java and Python share one schema version. A plain dict or a hand written
class is refused, since it could not be read by a Java consumer.
A worker
from klok_brokerclient import KlokBrokerClient, SubscriptionOptions
from klok_datamodel_klok_ai_v1 import KlokAiTaskRequestV1, KlokAiTaskResultV1
client = KlokBrokerClient() # configuration from the environment
def handle(message): # KlokBrokerMessage[KlokAiTaskRequestV1]
result = KlokAiTaskResultV1(taskId=message.task_id, status="FINISHED")
client.publish(client.topic(KlokAiTaskResultV1, purpose="summaries"), result, key=message.key)
# returning None acknowledges the message
client.subscribe(client.topic(KlokAiTaskRequestV1, purpose="summaries"), KlokAiTaskRequestV1, handle,
SubscriptionOptions("ACM010P1_Summarize", concurrency=4))
client.run_forever() # until SIGTERM, then a clean shutdown
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.
examples/kloker_worker.py is a complete worker that answers the prompts of a KlokAiTaskRequestV1 with Kloker through
the OpenAI-compatible gateway (KLOKER_BASE_PATH, KLOKER_API_KEY, KLOKER_MODEL).
Configuration
KlokBrokerClientConfig.from_env() reads the variables of the wire contract and the identity of the process:
| 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 certifi's public roots, 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 (klok_dev_url) |
The connection uses the listener name external, like the Java client. It trusts the Klok Root CA (or the configured CA
file), and the public roots from certifi so that the native client can verify the OAuth2 issuer (trust_file_path), and
verifies the broker's host name (tls_validate_hostname=True): on a TLS connection 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. The client depends on
pulsar-client>=3.6,<4 (3.13.0 is the latest) and talks to the platform's Pulsar 5.0.0 broker. Every keyword of
KlokBrokerClientConfig can be passed to from_env to override the environment.
Topics
client.topic(Model, purpose=None, domain=None) names a datamodel topic
persistent://<tenant>[_<env>]/<domain>/<Model>[_<purpose>]; a simple name given to publish or subscribe is
resolved the same way and a full name is used as it is. Request/reply uses ReqRes_<Req>_<Reply>[_<purpose>]_Request
and _Response. The naming functions are in klok_brokerclient.naming and run the fixture cases of the wire contract.
naming.parse_topic_name(name) takes a topic name apart, as KlokNamingConventions.parseTopicName in Java does, and
raises ValueError for a name that breaks the conventions. It returns a frozen KlokTopicName (persistent, tenant,
environment, domain, simple_name, model, purpose, request_model, reply_model, request_reply_side,
dlq); to_dict() gives the same fields with the wire contract's names (simpleName, requestReplySide, ...):
from klok_brokerclient import naming
name = naming.parse_topic_name("persistent://acme_test/common/InvoiceV1_created_DLQ")
(name.tenant, name.environment, name.model, name.purpose, name.dlq) # ('acme', 'test', 'InvoiceV1', 'created', True)
The purpose is the one the publisher chose; who reads a topic is never part of its name.
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, event_type= overrides it |
ce-datacontenttype |
the Avro body type |
ce-subject |
subject=, the business id of the object |
ce-dataschema |
urn:klok:schema:<docId>:<Record>:<Java version> from the datamodel package |
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, and klok-corr-service and klok-corr-global-source, which never
go on a message. The 0.2 names (klokSolutionId and friends) are never written or read, as the wire 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.
Context
A KlokContext carries the three correlation ids of the klok-common page Log Fields And
Correlation: corr_global with
corr_global_source, corr_platform and corr_service, next to the invocation, parent invocation and task ids and the
identity. correlation_id is kept as a read-only, deprecated name of corr_global (and with_values and
with_defaults accept it); the constructor takes corr_global.
| Where the context comes from |
Global id |
Platform id |
Service id |
a consumed message (the handler's context, KlokContext.from_properties(...).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.from_http_headers(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.new_chain()) |
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 id whose parent is the producer's invocation, and this process as tenant, domain, route and
instance. publish inside a handler uses that context unless one is given, so a chain can be followed across Java and
Python by klok-corr-global and klok-corr-platform. current_context() returns it, and KlokContextLogFilter adds
it to log records under the MDC keys (%(klok.corr-global)s, %(klok.corr-platform)s, %(klok.corr-service)s, ...);
properties.log_field(name) gives the OpenSearch field of a key (klok_corr_global) for a JSON formatter.
client.invocation() fills whatever id a given context lacks, so none of the three is empty inside an invocation. The
global id rules are exported on their own (global_from_headers, global_or_new, platform_from_message, module
klok_brokerclient.correlation) and run the correlation-cases.json of the wire contract.
Subscriptions and outcomes
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, the initial position
is Latest. concurrency runs that many handlers at once on one consumer. route_id (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 None or HandlerOutcome.ACKNOWLEDGE |
acknowledged |
FINISHED |
| raises anything else |
called again inside the same invocation by retry (a RetryPolicy, the Java defaults: 5 retries, 1 s backoff doubling up to 60 s); when they are used up, dead lettered (or negatively acknowledged with dlq_enabled=False) |
PROGRESS at ERROR per retry, then FAILED QUARANTINED (or UNRESOLVED) |
returns DEAD_LETTER or raises 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, then acknowledged |
FAILED QUARANTINED |
returns NEGATIVE_ACKNOWLEDGE or raises KlokNegativeAcknowledgement |
not retried: given back to the broker, whose redelivery is a new invocation |
FAILED UNRESOLVED |
raises a BaseException that is not an Exception (asyncio.CancelledError, GeneratorExit, a library's own) |
not retried and not dead lettered: given back to the broker, logged at ERROR with its traceback; the thread goes on |
FAILED UNRESOLVED |
raises SystemExit or KeyboardInterrupt |
a request to stop: the message goes back to the broker and the client closes (see When a receive thread ends) |
FAILED UNRESOLVED, klok.error-code STOP_REQUESTED |
A message that cannot be decoded is dead lettered with DECODE_ERROR at once, since no retry can help it.
MemoryError and RecursionError are exceptions in Python, and they are handled as any other: retried, then dead
lettered. Why, and why the Java client does otherwise with an OutOfMemoryError, is on Design
decisions, A failure in a handler does not end a Python receive thread.
When a receive thread ends
Nothing a message brings about ends a receive thread. An acknowledge or a negative acknowledge that fails (a closed
consumer, a lost connection), a failure while the invocation is logged, a dead letter that fails for any reason but a
missing or refused _DLQ: the invocation ends FAILED UNRESOLVED, the message is negatively acknowledged, the
failure is logged at ERROR with its traceback, and the thread receives the next message. A negative acknowledge that
fails too is logged, and the broker redelivers the message when its consumer reconnects or its ack_timeout_ms runs
out.
Three things end a thread while the client is open:
| What |
What happens |
a _DLQ that is missing or refused |
the thread stops, with the contract message in subscription.failure (see Missing topics and grants) |
| a consumer the Pulsar client closed under the thread |
the thread stops |
SystemExit or KeyboardInterrupt from a handler |
the client closes, on a thread klok-stop of its own, and client.stop_request holds what was raised; run_forever() raises it again on the main thread once the client is closed, so sys.exit(3) in a handler ends the process with 3 |
Each of them is seen. client.subscription_health() returns a KlokSubscriptionHealth, the counterpart of the Java
class of that name (see Connection health), and
KlokSubscriptionHealth.of_all_clients() the same for every open client in the process. Each
KlokSubscriptionHealth.Subscription names its topic, subscription, owner (route id) and instance, how many
threads run (running_threads), how many ended while the client was open (stopped_threads), since when
(stopped_since, epoch seconds) and why (failure). stopped() lists the subscriptions with a thread that ended,
stop_request says what a handler raised to stop, and healthy() says there is neither. A thread that ends because its
subscription or client is closed is not counted, and a client a stop request ended stays in of_all_clients() until the
process ends.
A worker with a health endpoint reports DOWN, for its liveness probe, while KlokSubscriptionHealth.of_all_clients() is
not healthy, since nothing but a restart brings a thread back. A worker without one keeps running on what is left, and
every thread that ends is logged at ERROR with its topic and reason.
from klok_brokerclient import KlokSubscriptionHealth
def live() -> bool: # the worker's liveness endpoint
return KlokSubscriptionHealth.of_all_clients().healthy()
The reply reader of request is not in it: when its loop ends while the client is open, the reader is closed and
forgotten, and the next request on that reply topic reads it again. A reply that cannot be read fails its own request
with a KlokRequestReplyException, and the loop goes on.
Every consumer is created with the metadata klok-route-id (the subscription's route_id), 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.consumer_metadata and
properties.producer_metadata build them. 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 Python client reports both
with typed exceptions whose message is the wire contract's text, word for word what the Java and TypeScript clients say:
| Exception |
code |
Python Pulsar client exception behind it |
KlokTopicMissingException |
TOPIC_MISSING |
pulsar.TopicNotFound |
KlokTopicAccessDeniedException |
TOPIC_ACCESS_DENIED |
pulsar.AuthorizationError, pulsar.NotAllowedError |
Both extend KlokTopicProvisioningException (a KlokBrokerClientException) with topic, role
(service-account-<auth_client_id>, client.broker_role), operation (publish or consume), code and retryable = False, and chain the Pulsar exception as __cause__. publish, reply, subscribe and serve raise them;
request raises a KlokRequestNotSentException (a KlokRequestReplyException) with the contract message whose cause
is the typed exception (exceptions.find_topic_provisioning_failure finds it), and a missing reply topic fails it
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
thread with the contract message in subscription.failure, instead of redelivering the message forever.
klok_brokerclient.provisioning holds the rendering (topic_missing_message, topic_access_denied_message,
request_url, role_of_client), the contract's templates and topic_provisioning_failure for any Pulsar error;
naming.companion_topics(topic) lists a topic's companions (topics.companions: its _DLQ, and for a _Request topic
its _Response and that topic's _DLQ).
try:
client.publish("persistent://acme/finance/InvoiceV1_created", invoice)
except KlokTopicMissingException as missing:
log.error("%s", missing) # what is missing, the klok.dev request link, who approves it, the Git entry
raise
Logging
The client logs every invocation the way the Quarkus extension does, following serviceLogging of the wire contract:
START when a message arrives, 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 logger
klok_brokerclient.service, [START] ACM010P1_Summarize 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); KlokContextLogFilter gives every other record of the handler the context ids too;
- 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 (a warning's or an error's text as it
is, otherwise the status name and what the route said); the outcome values have fields of their own and a route's own
values go in fields. Publishing goes through a bounded queue and a background thread; when the broker is away events
are dropped with a throttled warning, never blocking a handler. client.close() sends what is queued before it closes.
A handler adds entries to its invocation through client.log:
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
A fatal error is an exception out of the handler: retried, then FAILED. A script or a producer loop that is not a
handler becomes an invocation with client.invocation(), which logs START, then FINISHED, or FAILED when the
block raises; what it publishes inside carries the invocation's context:
with client.invocation(route_id="ACM010I1_ImportArticles") as invocation: # direction IN, from the leg letter
for article in fetch_articles():
client.publish(client.topic(ArticleV1), article)
invocation.warning("3 articles without a title were skipped")
The client carries the V6 classes in _kloklogevent_v6/, the files of the wheel the datamodel pipeline of
klok/datamodel/common/klok-log-event-v6 published (1.0.0.post261116125437), unchanged (see its README). The V4
classes (_kloklogevent_v4/) stay for reading the events of services built before V6.
When a producer used another version of the schema (an older or newer datamodel release), the client fetches that
version from the topic's schema registry once and lets Avro resolve it to the package's schema.
Reading the log events
read_log_event(event) reads a KlokLogEventV6, and still a KlokLogEventV4, into one LogEntry with the V6 names in
snake case (corr_global, corr_platform, corr_service, route_id, error_code, fields, ...);
read_log_event_payload(topic, data) decodes the Avro bytes of either topic first. A V4 event reads as the transition
of the page says: globalChainId is both corr_global and corr_platform, it has no corr_service, WARNING reads as
WARN and FATAL as ERROR. A subscription that reads the log event topic sets log_events=False, or every event it
handles brings another.
Request/reply
reply = client.request(KlokOdlSearchV1(...), KlokOdlSearchResponseV1, timeout_ms=5000) # asks
client.serve(KlokOdlSearchV1, KlokOdlSearchResponseV1, lambda m: build_answer(m.payload), "ACM010P1_Search") # answers
request resolves both topics in the client's own domain (KLOK_DOMAIN), so it reaches a service that answers in
another domain, such as the ODL search in common, only when the client's domain is that one
(#12). The request carries klok-reply-topic
and klok-reqres-id; the reply goes to that topic with the same id.
- Replies are read with a non-durable reader. The Python Pulsar client (
pulsar-client 3.x, checked at 3.13.0) has no
non-durable consumer, so the client reads each reply topic with one reader from the latest message, created before the
first request on the topic is sent. Its subscription, <reply_subscription>-reader-<random>, exists only while the
reader is connected: it is gone after close() and after the process dies
(#10); before, the reply consumer was a
durable subscription that was never removed. A reader takes no properties, so the reply subscription carries no consumer
metadata.
- A request names the reader's prefix. The random part of a reader's subscription name is chosen by the Pulsar client
and not exposed, so every reader of a client has the same subscription role prefix,
client.reply_subscription
(reply-subscriber-<clientId>-<uuid>, unique per client instance since the client id ends in a uuid of its own), and
every request carries that prefix 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 reply thread still pairs replies by
klok-reqres-id and passes over any other reply without decoding it, as on a broker without the filter.
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 use BatchingType.KeyBased, so one batch holds replies to one subscription only, which is what 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.
- A request is pending as long as it waits. A pending request is kept for its own
timeout_ms, the wire contract's
requestReply.pendingReplyLifetime. Up to 0.3.13 every pending request expired after 30 seconds, so a reply that took
longer was lost to a request that waited longer
(#9).
- A request that never left says so.
request raises a KlokRequestNotSentException, a KlokRequestReplyException
that is safe to send again, when its reply topic could not be read, a topic is not provisioned, its producer could not
be created or its send failed before the message went over the connection. A timeout, and a send that failed with
pulsar.Timeout or pulsar.AlreadyClosed, after which the broker may have stored it all the same, raise a plain
KlokRequestReplyException. The client creates the request producer before it sends, so that a producer that could not
be created is told apart from a send that failed. Why: A request that never left says so in Design
decisions.
Verified against Java
The broker client's tests run the contract fixtures (naming, properties, service logging), and against a real Pulsar
(KLOK_TEST_PULSAR_URL) publish and subscribe, concurrency, request/reply, dead letters, the registered schema and the
log events of an invocation; with KLOK_TEST_PULSAR_ADMIN_URL also that the reply subscription is non-durable, named
<reply_subscription>-reader-<random> and gone after close() and after the requesting process is killed, that the
replies to the client's requests are keyed with its prefix, and that a reply to an addressed request is keyed with its
reply subscription; the CI job and the local runs use a Pulsar 5.0.0 standalone. By hand, against a Pulsar 4.0.4
standalone with klok-brokerclient-java 0.3.2 on the other side and the KlokTaskEvent_v1 datamodel: Java publishes
and Python consumes, Python publishes and Java consumes (enum, nested list, microsecond timestamp, correlation and
parent invocation intact), Java requests and Python serves, Python requests and Java serves. The log events of a Python
worker (START, a warning, a retry at ERROR level, FINISHED) were decoded by klok-brokerclient-java with the
KlokLogEventV4 class of the catalog's jar, the one klok-egress-opensearch reads them with. That check was of the V4
events; the V6 events of this release carry the schema of the released V6 packages (a test compares the Python and
TypeScript copies) and have not been decoded by a Java consumer yet.
Not there yet
- Async task semantics (adopting a
klok-task-id, publishing KlokTaskStatusEventV1 progress the way the Quarkus
extension's task workers do) are not part of the client; a worker publishes its result and any status events itself.
Tracked in klok/framework/klok-brokerclient-java#3.
request cannot address a service in another domain
(#12); the TypeScript client takes a domain
option.
- The OAuth2 login has been exercised against a local broker without authentication only; the first worker on
broker.ipaas.se is where the client credentials flow meets Keycloak.
OpenTelemetry metrics are not in the Python client: the wire contract names the Java meters an implementation detail of
the Java client.