Direct Data Operator #
DirectDataOperator (module cz.o2.proxima:proxima-direct-core) provides low-latency, direct JVM access to storages configured in your Repository. It powers microservices, IngestServer, ReplicationController, TransactionManagerServer, and serves as the underlying IO engine for both BeamDataOperator and proxima-flink-core.
Core Primitives #
| Interface | Role | Typical Backends |
|---|---|---|
OnlineAttributeWriter | Asynchronous single-record writes (upserts, deletes, wildcard deletes) | Kafka, Pub/Sub, Cassandra, HBase, Bigtable, Elasticsearch, JDBC, HTTP |
BulkAttributeWriter | Watermark-driven batched file uploads with rollback support | GCS, S3, HDFS/Hadoop, Pub/Sub bulk |
CommitLogReader | Unbounded/bounded streaming observation with offset confirmation and watermarks | Kafka, Pub/Sub, WebSocket, InMem |
RandomAccessReader | Low-latency point lookups (get), wildcard prefix scans (scanWildcard), and key listings | Cassandra, HBase, Bigtable, JDBC, InMem |
BatchLogReader | Partitioned historical update scans and full snapshot scans | GCS, S3, HDFS/Hadoop, Cassandra, HBase, Bigtable, JDBC |
CachedView | In-memory materialized random-access cache backed by a compacted commit log | Kafka (compacted topic), InMem |
Creating the Operator #
Using the e-commerce model (test-readme.conf) with a generated
Model:
Repository repo = Repository.of(ConfigFactory.load("test-readme.conf").resolve());
Model model = Model.wrap(repo);
DirectDataOperator direct = repo.getOrCreateOperator(DirectDataOperator.class);
You can optionally supply a custom ExecutorService factory when creating the operator:
DirectDataOperator direct = repo.getOrCreateOperator(
DirectDataOperator.class,
op -> op.withExecutorFactory(() -> Executors.newFixedThreadPool(8)));
Call direct.close() on application shutdown to close all open writers, readers, and thread pools.
Writing Data #
Online Writes (OnlineAttributeWriter)
#
direct.getWriter(attributeDescriptor) returns the OnlineAttributeWriter for the attribute’s primary family (automatically wrapped with thread-safety synchronization if needed, or with TransactionalOnlineAttributeWriter if the attribute is transactional):
OnlineAttributeWriter writer = direct
.getWriter(model.getEvent().getDataDescriptor())
.orElseThrow(() -> new IllegalStateException("Missing writer for event.data"));
BaseEvent event = BaseEvent.newBuilder()
.setProductId("product-42")
.setUserId("user-1")
.setAction(Action.BUY)
.build();
StreamElement element = model
.getEvent()
.getDataDescriptor()
.upsert(UUID.randomUUID().toString(), System.currentTimeMillis(), event);
// Write asynchronously; callback fires once persisted in the primary family
writer.write(
element,
(success, error) -> {
if (success) {
log.info("Event successfully written.");
} else {
log.warn("Error writing element {}", element, error);
}
});
Deletes and wildcard deletes use the exact same writer.write(...) call with StreamElement.delete(...) or StreamElement.deleteWildcard(...) (or descriptor.delete(...) / descriptor.deleteWildcard(...)).
Bulk Writes (BulkAttributeWriter)
#
Bulk writers (such as GCS, S3, or HDFS) are obtained from the resolved family descriptor (direct.resolveRequired(family).getWriter().get().bulk()) and take a watermark timestamp alongside each element so the writer knows when time windows can be closed and flushed. On consumer rebalance or failure, call bulkWriter.rollback().
Reading Streaming Data (CommitLogReader)
#
Consuming a commit log is called observing. CommitLogReader provides two consumption styles:
- Named consumer group (
observe/observeBulk): Load-balances partitions across all instances sharing the same observer name and persists committed offsets back to the broker (e.g., Kafka consumer group). - Explicit partitions or offsets (
observePartitions/observeBulkPartitions/observeBulkOffsets): Used by distributed engines (Beam, Flink) or manual partition assignment.
CommitLogReader reader = direct
.getCommitLogReader(model.getEvent().getDataDescriptor())
.orElseThrow(() -> new IllegalStateException("Missing commit log for event.data"));
ObserveHandle handle = reader.observe(
"EventsProcessor",
Position.NEWEST, // or Position.OLDEST / Position.CURRENT
new CommitLogObserver() {
@Override
public boolean onNext(StreamElement element, OnNextContext context) {
Optional<BaseEvent> maybeEvent =
model.getEvent().getDataDescriptor().valueOf(element);
if (maybeEvent.isPresent()) {
handleEventAsync(maybeEvent.get(), context);
} else {
log.warn("Failed to parse value from {}", element);
// Always confirm (or nack/fail) so offset progression does not stall!
context.confirm();
}
// Return true to continue observing, false to stop
return true;
}
@Override
public boolean onError(Throwable error) {
log.error("Commit log error", error);
// Return true to retry observation, false to terminate
return true;
}
@Override
public void onIdle(OnIdleContext context) {
log.debug("Consumer idle at watermark {}", context.getWatermark());
}
private void handleEventAsync(BaseEvent event, OnNextContext context) {
executor.submit(() -> {
try {
processEvent(event);
// Confirm once processing succeeds
context.confirm();
} catch (Throwable err) {
// Signal failure (or context.nack() to reject without failing)
context.fail(err);
}
});
}
});
// Later, when shutting down:
handle.close();
Important: In
CommitLogObserver.onNext, you must invokecontext.confirm()(orcontext.nack()/context.fail(Throwable)) for every received element, either synchronously or from an async worker thread. Failing to confirm blocks offset commits.
Reading Random-Access Data (RandomAccessReader)
#
Use RandomAccessReader for point lookups, wildcard prefix scans, and primary-key iteration:
RandomAccessReader reader = direct
.getRandomAccess(model.getUser().getDetailsDescriptor())
.orElseThrow(() -> new IllegalStateException("Missing random access for user.details"));
// 1. Point lookup for a scalar attribute
String userId = "user-1";
Optional<KeyValue<UserDetails>> maybeDetails =
reader.get(userId, model.getUser().getDetailsDescriptor());
maybeDetails.ifPresent(kv -> {
UserDetails userDetails = kv.getParsedRequired();
log.info("Retrieved details {} for user {}", TextFormat.shortDebugString(userDetails), userId);
});
// 2. Scan a wildcard attribute with optional pagination (offset + limit)
RandomAccessReader eventReader = direct
.getRandomAccess(model.getUser().getEventDescriptor())
.orElseThrow();
List<KeyValue<BaseEvent>> recentEvents = new ArrayList<>();
eventReader.scanWildcard(
userId,
model.getUser().getEventDescriptor(),
/* offset */ null,
/* limit */ 50,
recentEvents::add);
// 3. List entity keys (requires family access `list-primary-key`)
eventReader.listEntities(
/* offset */ null,
/* limit */ 100,
keyPair -> log.info("Entity key: {}", keyPair.getSecond()));
When attributes of an entity live across multiple random-access families, direct.getRandomAccess(attr1, attr2, ...) automatically composes a unified reader (backed by MultiAccessBuilder).
Reading Batch Data (BatchLogReader)
#
BatchLogReader reads historical updates (batch-updates) or table snapshots (batch-snapshot) across partitions:
AttributeDescriptor<BaseEvent> eventData = model.getEvent().getDataDescriptor();
BatchLogReader batchReader = direct
.getBatchLogReader(eventData)
.orElseThrow(() -> new IllegalStateException("Missing batch reader for event.data"));
long endStamp = System.currentTimeMillis();
long startStamp = endStamp - TimeUnit.DAYS.toMillis(1);
// Discover partitions intersecting the requested time range
List<Partition> partitions = batchReader.getPartitions(startStamp, endStamp);
CountDownLatch done = new CountDownLatch(1);
cz.o2.proxima.direct.core.batch.ObserveHandle handle = batchReader.observe(
partitions,
Collections.singletonList(eventData),
new BatchLogObserver() {
@Override
public boolean onNext(StreamElement element, OnNextContext context) {
eventData.getValueSerializer()
.deserialize(element.getValue())
.ifPresent(e -> log.info("Historical event {}: {}", element.getKey(), e));
return true;
}
@Override
public void onCompleted() {
done.countDown();
}
@Override
public boolean onError(Throwable error) {
log.error("Batch scan failed", error);
done.countDown();
return false;
}
});
done.await();
handle.close();
For large-scale distributed batch processing, prefer
BeamDataOperator, which parallelizes BatchLogReader partitions across cluster workers automatically.
Creating a Cached View (CachedView)
#
When an attribute family is backed by a compacted state-commit-log with access: [ commit-log, state-commit-log, cached-view ], CachedView materializes the commit log into local memory for sub-millisecond random-access reads without an external NoSQL database:
CachedView view = direct
.getCachedView(model.getUser().getDetailsDescriptor())
.orElseThrow(() -> new IllegalStateException(
"Missing family with access 'cached-view' for user.details"));
// Assign partitions and block until initial catch-up completes
view.assign(view.getPartitions());
String userId = "user-1";
Optional<KeyValue<UserDetails>> maybeDetails =
view.get(userId, model.getUser().getDetailsDescriptor());
maybeDetails.ifPresent(kv ->
log.info("Cached details for {}: {}", userId, kv.getParsedRequired()));
// Close when done to stop background consumer threads
view.close();
Testing with In-Memory Storage #
Add the proxima-direct-core test JAR (classifier = "tests") to your test dependencies to enable inmem:// and inmem-bulk:// URIs. Every inmem:// URI supports commit-log, random-access, cached-view, batch-updates, batch-snapshot, and list-primary-key, making fast, deterministic unit tests effortless:
Repository repo = Repository.ofTest(ConfigFactory.load("test-reference.conf").resolve());
DirectDataOperator direct = repo.getOrCreateOperator(DirectDataOperator.class);
// Write via direct.getWriter(...) and immediately assert via direct.getRandomAccess(...)