10 Using Datamodels In The Odl

Using Datamodels In The ODL

The Operative Data Layer (ODL) is the platform's store for datamodel objects. A route can save any object of a released datamodel in it, read it back by id, search for it, delete it, and let other routes react when it changes. The objects are also visible in klok.dev and through a REST API.

This page covers the whole path for a developer:

  1. design a datamodel that works well in the ODL;
  2. create and build it;
  3. add it to an integration project;
  4. save, get, search and delete its objects from routes;
  5. react to changes;
  6. test the result.

It also explains how to read and filter on the first-level fields of an object, and which parts of that are not built yet.

The running example is a class C model, CustomerV1, of a tenant acme in the domain sales. It is stored by a customer import and read by other routes. Today only the tenant klok has an ODL (see Where The ODL Runs below); the example uses acme to show which names come from the tenant.

What The ODL Is

Idea What it means
One object, one address An object is stored under its type and its id. Writing the same type and id again replaces the object.
The type is the Java class The type is the fully qualified name of the generated datamodel class, for example dev.klok.acme.datamodel.domain.sales.customer_v1.CustomerV1. Never write it by hand: the framework takes it from the class.
The id is yours Normally the business key of the object, such as a customer number. The framework never invents one.
One index per type Each type has its own OpenSearch index, klok-odl-<tenant>-<slug of the type>. The stored document is an envelope of klok_* fields (who wrote it, when, in which domain) around the object, which is kept under payload.
A change event for every write After the store has saved an object, it publishes a change event. The event arrives at least once, in order per object, and never before the object can be read.
A service, not a library Routes never talk to OpenSearch. They send KlokOdl_v1 messages on the broker, in the tenant's common domain, and the ODL service answers.

The ODL is platform solution KLK002:

  • klok-egress-opensearch stores objects, answers requests and publishes the change events.
  • klok-api-odl is the REST API.
  • klok.dev shows the data under Run → Operative data.
your route ── odl() ──► persistent://<tenant>/common/KlokOdlPersistV1 ─────► klok-egress-opensearch ──► OpenSearch
           ◄─ reply ─── persistent://<tenant>/common/ReqRes_KlokOdlGetV1_…     (KLK002)                 klok-odl-<tenant>-…
                                                                                   │
                  persistent://<tenant>/<domain>/KlokOdlObjectEventV1_<Type> ◄─┘  change event, in the object's domain

Where The ODL Runs

Today the ODL serves one tenant, klok:

  • klok-egress-opensearch, klok-api-odl and the task API klok-api-tasks are configured for the tenant klok (klok.tenant=klok) and run once, in the klok namespace of the cluster.
  • They serve only the topics of the klok tenant's common namespace. Only klok-egress-opensearch holds OpenSearch credentials.
  • A route of any other tenant sends its ODL messages to its own tenant's common namespace, where no ODL service answers. It cannot use the ODL.
  • klok.dev and the REST API show the klok tenant's ODL.

Other tenants are not supported today; tracked in klok-deploy-manifests#10 and frontend-klok-dev#64.

When To Use It

Good uses:

  • Operational state an integration looks up. The last known version of an object, a mapping between the ids of two systems, a watermark of a scheduled job.
  • Enrichment. A processing route that adds customer data to an order reads the customer from the ODL, instead of calling the CRM for every message.
  • Snapshots that people and other services should see and search. Tasks, AI transcripts and import batches are stored this way.
  • "Masterdata light" for tenant settings. A Klok standard default lives in Git with the service. A tenant's override is stored in the ODL, typed by a datamodel, edited in klok.dev, and read by the service on every run.

Poor uses:

  • The system of record for customer data. The owning system stays the truth. The ODL holds an operational copy.
  • Files and images. Put them in the claim check store and keep the reference in the object (see Claim Check, Sync Over Async, And Other Tactics).
  • A queue between routes. Publish on the broker instead. When a route must react to a stored object, subscribe to its change events rather than polling.
  • History and analytics. The ODL keeps the current version of each object, not every version.

Step 1: Design The Model For The ODL

The ODL stores any datamodel, but a model designed with the ODL in mind is much easier to list, filter and show.

  1. Give every object an id. Name the field id and make it the stable business key. The framework then finds it without help (getId()), and the same key is used as the broker message key. The datamodel template already starts with such a field.
  2. Put what you search, list, filter and sort on at the first level, as simple types. Examples: status, country, customerNo, updatedAt. Put details that are read together with the whole object into nested types, such as an address or order lines.
  • klok.dev shows and edits the first level of an object as a form, and nested parts as JSON.
  • The first level is also what first-level reads are built on (see Reading And Filtering On First-Level Fields below).
  1. Choose the XSD type by how the field will be queried. The store maps each field from the JSON it receives: | XSD type | Stored as | Good for | | --- | --- | --- | | xs:string | text, plus an exact keyword for values up to 256 characters | exact match, prefix, sort and grouping on short values; free-text search on long ones | | enumeration (xs:enumeration) | the same as a string | exact match, IN, grouping. The best type for a status. | | xs:dateTime, xs:date | a date (the JSON is ISO-8601) | ranges (GT, LT, RANGE), date histograms | | xs:boolean | a boolean | exact match | | xs:long, xs:int | a whole number | exact match, ranges, sums | | amounts | see rule 4 | |

  2. The first value decides how a field is stored. The index mapping of a field is set by the first object that has it, and it cannot change afterwards. This has two consequences:

  • An amount first written as 1000 becomes a whole-number field, and later decimals are cut off in searches and sums.
  • An amount written as 1000.50 becomes a single-precision float, which rounds large amounts. Store amounts you filter or sum on in minor units (öre, cents) as xs:long, for example creditLimitMinor. Never change a field's type within a major version.
  1. Remember that arrays of objects are flattened. A search for "a contact with role billing and country NO" also matches an object with one billing contact in Sweden and another contact in Norway. When you need such a search, lift the value to the first level (billingCountry) or filter in code.
  2. Keep large text out of the first level when lists of the model should stay light, such as a 50 KB description. Put it in a nested part.
  3. Document every field with xs:documentation. klok.dev shows it next to the field, and the generated documentation is written from it.

An XSD that follows these rules:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="dev.klok.acme.sales"
           targetNamespace="dev.klok.acme.sales" elementFormDefault="qualified" version="1.0">

  <xs:element name="Customer_v1">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="customer" type="tns:CustomerV1"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:simpleType name="CustomerStatusType">
    <xs:restriction base="xs:string">
      <xs:enumeration value="PROSPECT"/>
      <xs:enumeration value="ACTIVE"/>
      <xs:enumeration value="BLOCKED"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:complexType name="CustomerV1">
    <xs:annotation><xs:documentation>A customer of the sales domain as the CRM owns it. Produced by the customer
      import (ACM010I1), stored in the ODL under its customer number, read by order enrichment.</xs:documentation></xs:annotation>
    <xs:sequence>
      <!-- first level: what lists show and what filters use -->
      <xs:element name="id" type="xs:string">
        <xs:annotation><xs:documentation>Customer number in the CRM; the ODL id and the message key.</xs:documentation></xs:annotation>
      </xs:element>
      <xs:element name="name" type="xs:string"/>
      <xs:element name="status" type="tns:CustomerStatusType"/>
      <xs:element name="country" type="xs:string" minOccurs="0">
        <xs:annotation><xs:documentation>ISO 3166-1 alpha-2 code of the billing country.</xs:documentation></xs:annotation>
      </xs:element>
      <xs:element name="creditLimitMinor" type="xs:long" minOccurs="0">
        <xs:annotation><xs:documentation>Credit limit in minor units (öre), so that ranges and sums are exact.</xs:documentation></xs:annotation>
      </xs:element>
      <xs:element name="updatedAt" type="xs:dateTime">
        <xs:annotation><xs:documentation>When the customer last changed in the CRM.</xs:documentation></xs:annotation>
      </xs:element>
      <!-- nested: details read together with the whole object -->
      <xs:element name="address" type="tns:CustomerAddressV1" minOccurs="0"/>
      <xs:element name="contacts" type="tns:CustomerContactV1" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="CustomerAddressV1">
    <xs:sequence>
      <xs:element name="street" type="xs:string" minOccurs="0"/>
      <xs:element name="postalCode" type="xs:string" minOccurs="0"/>
      <xs:element name="city" type="xs:string" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="CustomerContactV1">
    <xs:sequence>
      <xs:element name="name" type="xs:string"/>
      <xs:element name="email" type="xs:string" minOccurs="0"/>
      <xs:element name="role" type="xs:string" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

Step 2: Create And Build The Datamodel

Creating A Datamodel explains which class to choose and where the repository goes. In short:

  1. Create the repository as Creating A Datamodel describes. For the example, the repository is acme/datamodel/domain/sales/customer-v1, with the XSD schema-definition-xsd/customer-v1.xsd.
  2. Write the XSD on a branch. Also write the klok-docs/ pages: what the model is, the important fields, and who produces and who consumes it. Mention that it is stored in the ODL, and under which id.
  3. Open a merge request. Its pipeline is the build:
  • it validates the XSD (klok datamodel validate, the job validate_xsd);
  • it generates the Avro schema with avrotize;
  • it generates the Java project. A red pipeline names the line and the problem, such as an undeclared prefix, a referenced type that does not exist, or a name that is not a valid Java identifier.
  1. Merge. The pipeline on main then does three things:
  • it publishes the Java, Python and TypeScript packages;
  • it writes the new version into the tenant's dependency catalog, acme/framework/acme-gradle-dependency-catalog (a klok model goes into the platform catalog, klok/framework/klok-gradle-dependency-catalog);
  • it publishes the model's documentation to docs.klok.dev.

You can run the XSD check locally before you push:

klok datamodel validate

It checks every XSD under schema-definition-xsd/ with the same rules as the pipeline and klok.dev's editor. The Java classes are generated only in the pipeline. An integration project can use the model once its merge request is merged and the pipeline on main has finished.

What the example gets:

Thing Value
Maven artifact dev.klok.acme.datamodel:customer-v1
Catalog alias customerV1, used as tenantLibs.customerV1
Java class dev.klok.acme.datamodel.domain.sales.customer_v1.CustomerV1
ODL type the same, dev.klok.acme.datamodel.domain.sales.customer_v1.CustomerV1
ODL index klok-odl-acme-dev-klok-acme-datamodel-domain-sales-customer-v1-customerv1
Change event topic persistent://acme[_<env>]/sales/KlokOdlObjectEventV1_CustomerV1

The dev in the index name comes from the Java package dev.klok…, not from an environment.

The package is part of the stored data. Because the ODL type is the class name, moving the model to another repository path, class or package gives it a new type and a new index. The objects already stored stay under the old type. That is a data migration, which a person plans and runs as a reindex; it is not only a code change.

Step 3: Add The Datamodel To The Integration Project

  1. Refresh the project's copies of the catalogs, and commit them:
./gradlew updateKlokLibsToml
git add gradle/klok-libs.versions.toml gradle/tenant-libs.versions.toml
  1. Reference the alias in build.gradle. Never type a version. A model of your own tenant is in tenantLibs, a klok model in klokLibs:
dependencies {
    implementation tenantLibs.customerV1
}
  1. Import the generated class, dev.klok.acme.datamodel.domain.sales.customer_v1.CustomerV1, in the routes.

What you do not need to add: the ODL client and its messages. KlokOdl, KlokOdlDocuments and the KlokOdl_v1 messages (dev.klok.klok.datamodel.common.klok_odl_v1.*) come with the Klok Quarkus extension.

Three things to check:

  • The catalog must know the model first. Every pipeline runs updateKlokLibsToml against the catalogs' main, so an alias that is not merged there makes the consumer's build fail with an unknown-property error for customerV1. Wait for the model's pipeline on main, then run the consumer's pipeline again.
  • The application must belong to the tenant klok. No other tenant has an ODL (see Where The ODL Runs). In another tenant, synchronous calls fail with UPSTREAM_UNAVAILABLE: Timed out waiting for reply, and fire-and-forget writes are never stored.
  • The application's broker client needs publish and consume on the tenant's common namespace, where the ODL topics are. Nothing grants this automatically. For a klok service it is a namespace grant in ansible-master/playbooks/group_vars/all/pulsar_tenant_klok.yml of klok-environment-setup, requested in klok.dev or added there by a merge request, and applied to the broker (see Topics On The Klok Broker). The service checks it at startup; from klok-quarkus-extension 3.14.0 a route that calls odl() is held (not started) without it, while the rest of the service runs, and starts by itself once the grant exists. An older extension version stops the whole service's start instead.

Step 4: Get The ODL Into A Route

Every route pattern has odl(), which returns the KlokOdl bean, and invocationContext(exchange), which returns the context every ODL call takes. The context carries the tenant, the domain and the correlation id of the chain, so the stored object and its change event can be traced back to the message that caused them.

odl(), odlPersist(...) and persistToOdl() use the application's one KlokOdl bean, whether or not anything injects it. You can also inject it, as the example does; an injected field is easy to replace in a test (see Step 10):

@ApplicationScoped
public class ACM010P1_OrderEnrichment extends KlokProcessingRoute<OrderV1, OrderV1> {

    @Inject
    KlokOdl odl;

    @Override
    public OrderV1 transformBody(OrderV1 order, Message message, Exchange exchange) {
        KlokInvocationContext ctx = invocationContext(exchange);
        odl.get(CustomerV1.class, order.getCustomerId(), ctx)
           .ifPresent(customer -> order.setCustomerName(customer.getName()));
        return order;
    }
}

In an async task worker the context is task.invocation() of the KlokTaskContext. A helper bean that is not a route takes the context as a parameter from the route that calls it.

The imports used on this page:

import dev.klok.framework.helpers.odl.KlokOdl;
import dev.klok.framework.helpers.odl.KlokOdlDocuments;
import dev.klok.framework.logging.KlokInvocationContext;
import dev.klok.klok.datamodel.common.klok_odl_v1.*;   // KlokOdlSearchV1, KlokOdlFilterV1, KlokOdlHitV1, ...

Step 5: Save

Store What A Route Produces

The onramp, processing and offramp patterns have a hook. When persistToOdl() returns true, the route stores the object transformBody returned, before it is published or delivered:

@ApplicationScoped
public class ACM010I1_CustomerImport extends KlokOnrampRoute<CrmCustomer, CustomerV1> {

    @Override
    protected boolean persistToOdl() {
        return true;
    }

    @Override
    public CustomerV1 transformBody(CrmCustomer in, Message message, Exchange exchange) {
        CustomerV1 customer = new CustomerV1();
        customer.setId(in.getCustomerNo());
        customer.setName(in.getName());
        customer.setStatus(CustomerStatusType.valueOf(in.getState()));
        customer.setUpdatedAt(in.getModified());
        return customer;
    }
}

In a custom route, put the processor where you want it and say where the id comes from:

@Override
protected void configureBeforeTo(RouteDefinition route) {
    route.process(this::toCustomer)
         .process(odlPersist(CustomerV1::getId));
}

The id is taken from the first of these that exists:

  1. the function given to odlPersist(...);
  2. the klok-odl-id header (KlokOdlPersistProcessor.ID_HEADER);
  3. the body's getId() or id().

A body with no id fails the invocation with VALIDATION_FAILED. A null body stores nothing.

The hook and odlPersist are fire and forget. The route continues as soon as the broker has taken the message; it does not wait for the store, and it does not learn whether the write succeeded. That is right for "keep a copy of what passed through". A failed write is retried by the ODL service and ends in its dead letter topic.

Save From Code

KlokInvocationContext ctx = invocationContext(exchange);

// Fire and forget.
odl.persist(customer, customer.getId(), ctx);

// Wait for the store's answer. An ERROR answer is thrown; OK and CONFLICT are returned.
KlokOdlPersistResponseV1 answer = odl.persistSync(customer, customer.getId(), ctx);
if (answer.getResult() == KlokOdlResultType.CONFLICT) {
    // only with ifSeqNo / ifPrimaryTerm: someone wrote the object in between
}
boolean created = Boolean.TRUE.equals(answer.getCreated());   // true for a new object, false for a replacement

Use persistSync when the next step depends on the object being stored. Examples: the route answers a caller who will read the object at once, or a later step searches for it. persistSync answers after the object is stored, its change event is published and, with the default refresh policy, it is searchable.

What a synchronous answer becomes. The ODL service answers a failure with result = ERROR and the Klok error code first in resultDescription (UPSTREAM_UNAVAILABLE: Connection refused); it never lets the caller wait for a timeout. The typed helpers, get(Class, ...), searchAll and persistSync(Object, ...), throw an ERROR answer with that code: a 4xx code such as VALIDATION_FAILED is a Klok4XXException and is not retried, any other code is a Klok5XXException that the standard error handling retries and dead letters. NOT_FOUND stays an empty Optional, and persistSync(Object, ...) returns CONFLICT for your code to handle. The request methods, get(KlokOdlGetV1, ...), search, persistSync(KlokOdlPersistV1, ...) and deleteSync, return the answer as it is, ERROR included: check getResult() there.

A call whose answer does not come fails with UPSTREAM_UNAVAILABLE, which is retried. A missing ODL topic or grant fails with TOPIC_MISSING or TOPIC_ACCESS_DENIED and a message that names the fix; it is not retried, and the call keeps failing until the tenant's Pulsar file is changed and applied. The framework reference has the whole table: What the answers become.

Write Options

Options are set on the request. Build it with KlokOdlDocuments.persistFor(...), change it, then send it with persist or persistSync:

KlokOdlPersistV1 request = KlokOdlDocuments.persistFor(customer, customer.getId(), ctx,
        KlokOdlDocuments.options(KlokOdlRefreshPolicyType.WAIT_FOR, false));
request.getOptions().setSkipIfUnchanged(true);
request.getMeta().setIdempotencyKey(crmChangeId);   // the same when the same change is handled twice
KlokOdlDocuments.withMetadata(request.getMeta(), Map.of("source", "crm"));
odl.persist(request, ctx);
Option Default Use it when
refreshPolicy WAIT_FOR WAIT_FOR: the answer and the change event wait until the object is searchable. NONE: faster for large loads; the object can be read by id at once and is searchable within about a second. IMMEDIATE: forces searchability, and is expensive.
upsert false false replaces the stored object. true merges the fields you send into it. The framework leaves null fields out of the JSON, so an upsert cannot clear a field; replace the object when fields must disappear.
skipIfUnchanged false A sync job stores the same objects again and again. An unchanged object is then not written: no new version and no change event, so consumers are not woken up for nothing.
meta.idempotencyKey none The same message may be handled twice. A second write with the same key is skipped.
ifSeqNo + ifPrimaryTerm none Write only if the object has not changed since you read it (optimistic locking). A mismatch answers CONFLICT.
emitEvent true false writes without a change event. Use it for data that nobody reacts to.
meta.objectMetadata empty Free name and value pairs stored beside the object (withMetadata).

Optimistic locking needs values that reads do not give you yet. Take seqNo and primaryTerm from the answer of your own last persistSync. Hits from a get or a search should carry them, but do not yet (klok-egress-opensearch#10).

Many Objects At Once

Send a bulk request for large loads:

KlokOdlBulkPersistV1 bulk = new KlokOdlBulkPersistV1();
bulk.setItems(customers.stream().map(c -> KlokOdlDocuments.persistFor(c, c.getId(), ctx)).toList());
bulk.setMeta(KlokOdlDocuments.metaFrom(ctx));
bulk.setOptions(KlokOdlDocuments.options(KlokOdlRefreshPolicyType.NONE, false));
odl.bulkPersist(bulk, ctx);
  • The store writes the batch in one request and publishes one change event per stored object.
  • A batch in which some items fail is retried as a whole. Keep the writes idempotent: the same id, and skipIfUnchanged where it fits.
  • Keep batches to a few hundred objects. The whole batch travels as one broker message and is written as one bulk request.

Domain And Tenant

The domain of the invocation context goes with the write and becomes the object's klok_domain. The change event is published in that domain, and klok.dev shows the object as owned by it. A route in the sales domain therefore stores sales objects, whatever the model's own class is.

Step 6: Get

Optional<CustomerV1> customer = odl.get(CustomerV1.class, "4711", ctx);

get reads one object by id. An object is readable by id as soon as the write is stored; you do not have to wait for it to become searchable.

Two traps with get:

  • A fire-and-forget write may not be stored yet. A get just after persist from the same route can come back empty. Use persistSync when you must read your own write.
  • Only "not found" is empty. The typed get returns an empty Optional when the ODL answers NOT_FOUND, and throws when the store answered ERROR, with the code from resultDescription. A route that creates an object when none is found therefore never creates a duplicate because the store had a bad moment. Services built with an extension older than 3.8 returned empty on ERROR too; refresh the catalog and build them again.

To read several objects in one call, use a multi get:

KlokOdlGetV1 request = KlokOdlDocuments.getFor(CustomerV1.class, null, ctx);
request.setIds(List.of("4711", "4712", "4713"));
KlokOdlGetResponseV1 answer = odl.get(request, ctx);
List<CustomerV1> found = answer.getHits().stream()
        .map(hit -> KlokOdlDocuments.payloadOf(hit, CustomerV1.class))
        .toList();
List<String> missing = answer.getMissingIds();

The hits come in the order of the requested ids. hit.getVersion(), hit.getUpdatedAt() (when it was stored) and hit.getDomain() come from the envelope.

Step 7: Search

A search reads the objects of one type that match a query, one page at a time:

KlokOdlSearchV1 query = KlokOdlDocuments.searchFor(CustomerV1.class, null, 100, ctx);
query.getFilters().add(filter("status", KlokOdlFilterOperatorType.EQ, CustomerStatusType.ACTIVE.name()));
query.getFilters().add(filter("country", KlokOdlFilterOperatorType.IN, "SE", "NO"));
query.getFilters().add(filter("updatedAt", KlokOdlFilterOperatorType.GTE, since.toString()));
query.getSort().add(sort("name", KlokOdlSortDirectionType.ASC));

KlokOdlSearchResponseV1 page = odl.search(query, ctx);
List<CustomerV1> customers = page.getHits().stream()
        .map(hit -> KlokOdlDocuments.payloadOf(hit, CustomerV1.class))
        .toList();
long total = page.getTotal();

searchFor(model, freeText, pageSize, ctx) returns a request with empty, changeable lists of filters, sort, aggregations and fields. The framework has no builder for filters and sort yet (klok-egress-opensearch#11 designs one), so keep two small helpers in the project. Every value is passed as a string: Instant.toString(), enum.name(), String.valueOf(number).

static KlokOdlFilterV1 filter(String field, KlokOdlFilterOperatorType operator, String... values) {
    KlokOdlFilterV1 filter = new KlokOdlFilterV1();
    filter.setField(field);
    filter.setOperator(operator);
    switch (operator) {
        case IN, NOT_IN, RANGE -> filter.setValues(List.of(values));
        case EXISTS -> { }
        default -> filter.setValue(values[0]);
    }
    return filter;
}

static KlokOdlSortV1 sort(String field, KlokOdlSortDirectionType direction) {
    KlokOdlSortV1 sort = new KlokOdlSortV1();
    sort.setField(field);
    sort.setDirection(direction);
    return sort;
}

Fields

  • Payload fields are named by their path in the object: status, or address.city for a nested field.
  • Envelope fields start with klok_. They are always stored with an exact type, so they filter and sort reliably: | Envelope field | Meaning | | --- | --- | | klok_id | the object's id | | klok_domain | the domain that wrote the object | | klok_persisted_at | when the store saved it | | klok_timestamp | when the writing route sent it | | klok_source_route_id, klok_solution_id, klok_correlation_id | who wrote it, and in which chain | | klok_version | the store's version counter |

Filters

All filters must match (AND). There is no OR between filters; use IN for "one of these values".

Operator Value Use on Notes
EQ value strings, enumerations, numbers, booleans Exact and case-sensitive on strings. Not on dates, and not on strings of digits that start with 0; see Known limitations.
NE value the same as EQ Also matches objects that do not have the field.
IN, NOT_IN values strings, enumerations, numbers Do not mix numbers and text in one list.
GT, GTE, LT, LTE value numbers, dates (ISO-8601)
RANGE values = [from, to] numbers, dates Both ends included.
EXISTS none any field, including nested objects The object has a value for the field.
PREFIX value strings Case-sensitive.
WILDCARD value with * and ? strings Case-sensitive, and slow on large types, especially with a leading *.

freeText is a word search over every text field of the object, and it is not case-sensitive. Use it for a search box; use filters for rules in code.

Sort And Paging

Setting What it does
sort A list of {field, direction}. klok_id ascending is always added last, so the order is stable.
pageSize Default 100, at most 10000. 0 returns no hits, which is useful for aggregations only.
from Skips hits. Use it for the first few pages of a list.
cursor For deep paging: pass back the cursor of the previous answer. There is a cursor only when the page was full.

Sort only on string, enumeration and envelope fields today. Sorting on a number, date or boolean payload field is silently ignored (klok-egress-opensearch#9). For "newest first", sort on klok_persisted_at.

To walk every match, let searchAll follow the cursors:

KlokOdlSearchV1 query = KlokOdlDocuments.searchFor(CustomerV1.class, null, 500, ctx);
query.getFilters().add(filter("status", KlokOdlFilterOperatorType.EQ, "BLOCKED"));
long count = odl.searchAll(query, ctx, hits -> hits.forEach(hit -> notifyCredit(hit.getId())));

searchAll stops at the first empty page. A page answered ERROR is thrown, after the pages before it were handed to the consumer, so the consumer may have handled part of the matches. Make the consumer safe to run again, or page with search and check each page's result yourself.

Aggregations

To count or sum without reading the objects, set pageSize to 0 and add aggregations:

KlokOdlSearchV1 query = KlokOdlDocuments.searchFor(CustomerV1.class, null, 0, ctx);
KlokOdlAggregationV1 byStatus = new KlokOdlAggregationV1();
byStatus.setName("byStatus");
byStatus.setKind(KlokOdlAggregationKindType.TERMS);
byStatus.setField("status");
byStatus.setSize(10);
query.getAggregations().add(byStatus);

KlokOdlSearchResponseV1 answer = odl.search(query, ctx);
String json = answer.getAggregations().get(0).getJsonValue();   // {"buckets":[{"key":"ACTIVE","doc_count":120}, ...]}
Kind Use on
TERMS strings and enumerations (buckets of values with counts)
COUNT, CARDINALITY strings and enumerations
SUM, AVG, MIN, MAX numbers
DATE_HISTOGRAM dates, with interval such as 1d or 1M

The result is OpenSearch's own aggregation JSON; read it with KlokMarshalling.getJsonMapper(). TERMS, COUNT and CARDINALITY on number, date and boolean fields return nothing today (#9).

Raw Queries

queryDsl takes a raw OpenSearch query object as JSON. It replaces freeText; the filters still apply on top of it (AND). It is the escape hatch for what filters cannot express, such as an OR:

query.setQueryDsl("""
        {"bool": {"should": [
            {"term": {"payload.status.keyword": "BLOCKED"}},
            {"range": {"payload.creditLimitMinor": {"lt": 0}}}
        ], "minimum_should_match": 1}}""");

Payload fields are under payload.; exact string matching uses .keyword. A raw query ties the route to OpenSearch, so prefer filters wherever they work.

Step 8: Delete

odl.delete(CustomerV1.class, "4711", ctx);                      // fire and forget

KlokOdlDeleteResponseV1 answer =
        odl.deleteSync(KlokOdlDocuments.deleteFor(CustomerV1.class, "4711", ctx), ctx);
boolean existed = Boolean.TRUE.equals(answer.getFound());       // NOT_FOUND when there was nothing to delete

A delete publishes a deleted change event that carries the removed object.

Deleting many objects. The ODL also supports delete by query (KlokOdlDeleteByQueryV1, with the same filters as a search and a safety limit, maxObjects, default 10000). KlokOdl has no method for it yet. You have two options:

  • From a route: search for the ids, page by page, checking each page's result, and delete them one by one.
  • By hand: a writer can use POST /api/odl-admin/{type}/delete-by-query of the REST API (see below).

Step 9: React To Changes

Every stored change is published on KlokOdlObjectEventV1_<TypeSimpleName>, in the domain of the object. To act on changed customers, consume that topic with the ordinary patterns. The type's simple name is the topic purpose:

@ApplicationScoped
public class ACM010E1_CustomerToErp extends KlokOfframpRoute<KlokOdlObjectEventV1, ErpCustomer> {

    @Inject
    KlokOdl odl;

    @Override
    public String topicPurpose() {
        return "CustomerV1";                          // KlokOdlObjectEventV1_CustomerV1
    }

    @Override
    public ErpCustomer transformBody(KlokOdlObjectEventV1 event, Message message, Exchange exchange) {
        if (event.getChangeKind() == KlokOdlChangeKindType.DELETED) {
            return ErpCustomer.deactivated(event.getId());
        }
        CustomerV1 customer = event.getJsonPayload() != null
                ? read(event.getJsonPayload())
                : odl.get(CustomerV1.class, event.getId(), invocationContext(exchange)).orElseThrow();
        return ErpCustomer.from(customer);
    }

    private static CustomerV1 read(String json) {
        try {
            return KlokMarshalling.getJsonMapper().readValue(json, CustomerV1.class);
        } catch (JsonProcessingException e) {
            throw new Klok4XXException(KlokErrorCode.TRANSFORMATION_FAILED, "Unreadable CustomerV1 event", e, null);
        }
    }

    @Override
    protected String toUri() {
        return "direct:erp-customer";
    }
}

What a consumer can rely on:

  • The event carries the change. It has changeKind (CREATED, UPDATED, DELETED), version and previousVersion, the meta of the write, and the object in jsonPayload.
  • Large objects are not inline. For an object over 256 KB the event carries a claim check reference in payloadRef when the ODL service has a claim check store, and no payload when it has none. Read the object by id instead.
  • Events arrive at least once, and in order per object. A redelivered event has the same eventId (also the CloudEvent ce-id), which you can deduplicate on.
  • The object is always readable when its event arrives. With the default refresh policy it is also searchable.
  • The events are in the object's domain namespace. A consumer needs consume rights there, as on any topic; another domain's events need a consume grant on that topic. klok-egress-opensearch publishes the events, so it needs publish in that namespace too. The Pulsar grants in klok-environment-setup give it klok/common only.
  • The event topic exists before the first write. The broker creates no topics by itself, and a write whose change event topic is missing fails. klok.dev declares KlokOdlObjectEventV1_<Type> in Git and applies it: in common and in the domain a write names, for every type the ODL stores, every type a published datamodel schema describes, and before a write through the ODL editor. A consumer of the events subscribes like on any other topic.

klok-ingress-opensearch can also run a scheduled ODL query. On a timer it publishes the same event type for the objects of one type that changed since its last run, with the query's name as the purpose, in the common domain. It is off until a deployment configures a query.

Step 10: Test

Unit tests of a route's logic. Replace the injected KlokOdl with a subclass that keeps objects in a map:

class InMemoryOdl extends KlokOdl {
    final Map<String, Object> stored = new HashMap<>();

    @Override
    public void persist(Object body, String id, KlokInvocationContext context) {
        stored.put(body.getClass().getName() + "/" + id, body);
    }

    @Override
    public <T> Optional<T> get(Class<T> model, String id, KlokInvocationContext context) {
        return Optional.ofNullable(model.cast(stored.get(model.getName() + "/" + id)));
    }
}

route.odl = new InMemoryOdl();   // the @Inject field of the route under test

@QuarkusTest tests. Register the stub as a CDI alternative. It then replaces the real bean for every route, including persistToOdl() and odlPersist(...):

@Alternative
@Priority(1)
@ApplicationScoped
@Unremovable
public class StubOdl extends KlokOdl {
    // map-backed persist, persistSync, get, search and delete, as above
}

Asserting on the messages. To check the ODL messages themselves, use the recording broker client of the Klok test setup and read what was published:

// <tenant>_<environment> of the test configuration: klok_test in the extension's own tests
List<Published> writes = RecordingBrokerClient.publishedTo("persistent://klok_test/common/KlokOdlPersistV1");
KlokOdlPersistV1 write = (KlokOdlPersistV1) writes.get(0).body();
assertEquals(CustomerV1.class.getName(), write.getType());
assertEquals("4711", write.getId());

The recording client lives in the extension's integration-tests, and projects keep a copy under src/test/java/.../testsupport/. The extension's KlokOdlAndConcurrencyTest is the reference.

Reading The Same Data Outside Routes

klok.dev

Run → Operative data lists the types with their object counts, read from the ODL instance of your own tenant. Only tenant klok has one today, the REST API below; in another tenant the page says not activated for this tenant and never shows another tenant's data. Opening a type shows its objects:

  • The list has free text, filters and sort, with the field names and kinds of the type. An enumeration's filter is a list of its values, and a date's filter is a date picker.
  • The editor is a form for the first level. Nested parts are shown as JSON and edited in a dialog, one field at a time.

Saving in the editor replaces the stored object. klok.dev calls the API with your own token, so reading needs the realm role klok-odl-reader or klok-odl-writer, and writing needs klok-odl-writer. Keycloak gives klok-odl-writer to the groups /klok/admins and /klok/developers. klok.dev also passes a write on only for a developer or admin of the tenant or the domain.

The REST API

klok-api-odl turns HTTP into the same broker messages. It runs once, for the tenant klok, at https://odl.klok.ipaas.se. It takes a Keycloak token of the klok realm: the realm role klok-odl-reader may read and search, and klok-odl-writer may also store and delete. The type in the path is the fully qualified class name. The endpoints, their bodies and their status codes are documented with the service, in REST API.

A search from the command line, with ODL_TYPE set to the class name and TOKEN to your access token:

curl -s -X POST "https://odl.klok.ipaas.se/api/odl/$ODL_TYPE/search" -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"filters":[{"field":"status","operator":"EQ","value":"ACTIVE"}],"fields":["id","name","status"],"pageSize":20}'

Domains do not yet limit what a reader sees. A reader sees the objects of every domain of the tenant (klok-api-odl#2). Do not store anything in the ODL that some of the tenant's readers must not see.

Reading And Filtering On First-Level Fields

The first-level fields of an object are the fields of its root that hold a simple value: a string, a number, a boolean, a date or an enumeration. Arrays of such values count too. In the example they are id, name, status, country, creditLimitMinor and updatedAt. address and contacts are not first level.

The first level is the part of an object that lists, tables and filters are made of. Reading only the first level keeps an answer small when the objects have large nested parts: a list of 500 customers needs their names and statuses, not their contacts.

What Works Today

Filter on first-level fields. String, enumeration, boolean and number fields work with the filters above, and date fields work with the range operators. These are the fields to design for (see Step 1).

Fetch only the fields you need. A search takes fields, a projection. Only the named payload fields come back, while the envelope (id, version, domain, when it was stored) always does:

record CustomerRow(String id, String name, CustomerStatusType status, Instant updatedAt) {}

KlokOdlSearchV1 query = KlokOdlDocuments.searchFor(CustomerV1.class, null, 500, ctx);
query.getFilters().add(filter("status", KlokOdlFilterOperatorType.EQ, "ACTIVE"));
query.getFilters().add(filter("country", KlokOdlFilterOperatorType.EQ, "SE"));
query.getSort().add(sort("name", KlokOdlSortDirectionType.ASC));
query.getFields().addAll(List.of("id", "name", "status", "updatedAt"));

List<CustomerRow> rows = odl.search(query, ctx).getHits().stream()
        .map(hit -> row(hit.getJsonPayload()))
        .toList();

with a helper in the route class:

private static CustomerRow row(String json) {
    try {
        return KlokMarshalling.getJsonMapper().readValue(json, CustomerRow.class);
    } catch (JsonProcessingException e) {
        throw new Klok4XXException(KlokErrorCode.TRANSFORMATION_FAILED, "Unreadable ODL row", e, null);
    }
}

Rules for a projected hit:

  • Read it into your own small type, never into the model class. A CustomerV1 built from four fields looks complete, but its other fields are empty, and required numbers and booleans read as 0 and false.
  • Never write it back. Storing a partial object replaces the whole object and loses everything you did not fetch.

Find out which first-level fields a type has. GET /api/odl/{type}/fields answers the fields the store has seen, first level first, with their kinds. KlokOdl has no method for it yet. klok.dev prefers the datamodel's own schema (KlokDataModelSchemaV1) where one is published.

What Is Not Built Yet

  • The caller must list the fields, and nothing tells a reader that a hit is partial.
  • A get and a multi get cannot project, only a search can.
  • Sort and some filters on number, date and boolean fields do not work (#9).
  • The framework has no typed builder for filters, sort and projection.
  • klok.dev's lists fetch whole objects, although they only show the first level.

A first-level view is designed in klok-egress-opensearch#11. It is not built.

Changing A Model That Is Stored

  • A compatible change adds an optional field. New objects simply have it; objects stored earlier do not, until they are written again.
  • A breaking change is a new major version, CustomerV2. That is a new class, so a new type and a new index, and nothing moves on its own. Migrate by reading every CustomerV1 object and writing it as CustomerV2, with a one-off route or job. Keep the readers of both types working while you move, as for any breaking change (see Schema Evolution And Versioning).
  • A new package or class name for the same model is also a new type. Plan it as a reindex, which a person runs.

Known Limitations

Limitation Workaround Tracked in
The ODL serves only the tenant klok. None; an application of another tenant cannot use the ODL. –
Sort, TERMS, COUNT and CARDINALITY on number, date and boolean payload fields have no effect. EQ on a date never matches. EQ on a string of digits with a leading zero never matches. Sort on klok_persisted_at or a string field. Use RANGE for dates. Use queryDsl with a term on payload.<field>.keyword for digit strings. klok-egress-opensearch#9
Hits of a get or a search have no seqNo or primaryTerm, so optimistic locking after a read is impossible. Use the values from your own persistSync answer. klok-egress-opensearch#10
No first-level view; projection only on search. List the fields in fields. klok-egress-opensearch#11
KlokOdl has no delete by query and no fields call. See Step 8, and the REST API. klok-egress-opensearch#11
Readers see every domain's objects of the tenant. Store nothing a tenant reader must not see. klok-api-odl#2

Configuration

The ODL client's keys, the answer timeout klok.odl.client.timeout-ms and the broker identity, are in the framework reference, Operative Data Layer.

Troubleshooting

Symptom Likely cause
get right after persist returns nothing The fire-and-forget write is not stored yet. Use persistSync.
get finds the object, but a search does not The object was written with refresh NONE a moment ago. Or the filter hits one of the limitations above. Or the value differs in case (string filters are case-sensitive).
Nothing is found although klok.dev shows the objects The type differs, for example after a package change: compare the type in klok.dev with CustomerV1.class.getName().
VALIDATION_FAILED: No ODL id for … Give odlPersist(...) an id function, set the klok-odl-id header, or give the model an id field.
TOPIC_MISSING or TOPIC_ACCESS_DENIED on every synchronous call The ODL topic is not provisioned for the tenant, or the service's broker identity has no grant on it. The message names the line to add to the tenant's Pulsar file.
UPSTREAM_UNAVAILABLE: Timed out waiting for reply on every synchronous call The application's tenant is not klok, so no ODL service answers. Set the log category dev.klok.framework.helpers.odl to DEBUG to see the topics the ODL client uses.
A write answers ERROR with a mapping message A field was written with a type other than the one it was first stored with, such as text in a number field. Fix the writer; changing a field's type is a breaking change.
A write answers CONFLICT ifSeqNo / ifPrimaryTerm did not match: someone wrote the object in between. Read it again, and redo the change.
A sort has no effect Sorting on a number, date or boolean field (#9).
The broker shows a growing number of producers or reply subscriptions from one service The service was built with an extension older than 3.2.1, which removed KlokOdl when nothing injected it (klok-quarkus-extension#5). Refresh the catalog and build it again.

Checklist

  • [ ] The model has a stable id, and the fields to filter, list and sort on are simple first-level fields.
  • [ ] Amounts that are filtered or summed are whole numbers in minor units.
  • [ ] Fields are documented, and klok-docs/ says that the model is stored in the ODL, and under which id.
  • [ ] The application belongs to the tenant klok, the only tenant with an ODL.
  • [ ] The project uses the catalog alias, with no hand-written version.
  • [ ] The route uses persistSync wherever a later step reads the write, handles CONFLICT where it writes with ifSeqNo, and checks getResult() on the request methods.
  • [ ] Repeated writes are idempotent (the same id, skipIfUnchanged or an idempotency key).
  • [ ] Searches filter and sort only on fields that work today, or use klok_persisted_at.
  • [ ] Projected hits are read into a small type of their own, and never written back.
  • [ ] Consumers of change events deduplicate on eventId and handle DELETED.
  • [ ] Tests stub KlokOdl or assert on the recorded ODL messages.

The framework reference is Operative Data Layer. The message contract is documented in the klok-odl-v1 datamodel, and the query model and store in klok-egress-opensearch.