Beam Data Operator

Beam Data Operator #

BeamDataOperator (module cz.o2.proxima:proxima-beam-core) integrates Proxima’s data model with Apache Beam, allowing the same batch and streaming pipelines to run across DirectRunner, Apache Flink, Apache Spark, and Google Cloud Dataflow.

Instantiating the Operator #

Add cz.o2.proxima:proxima-beam-core (plus proxima-direct-core and your IO/scheme modules) to your build:

Repository repo = Repository.of(ConfigFactory.load("test-readme.conf").resolve());
BeamDataOperator beam = repo.getOrCreateOperator(BeamDataOperator.class);
Model model = Model.wrap(repo);

Automatic Coder Registration: Whenever BeamDataOperator attaches a source to a Pipeline, it automatically registers coders for StreamElement (StreamElementCoder), EntityDescriptor (EntityDescriptorCoder), AttributeDescriptor (AttributeDescriptorCoder), and Pair (PairCoder).

Reading Data into PCollection<StreamElement> #

BeamDataOperator exposes three primary source methods corresponding to Proxima’s three storage archetypes.

1. Streaming Commit Log (getStream) #

Reads an unbounded (or bounded when stopAtCurrent = true) commit log:

Pipeline p = Pipeline.create();

PCollection<StreamElement> events = beam.getStream(
    "ReadEvents",                         // optional consumer name
    p,
    Position.OLDEST,                      // OLDEST, NEWEST, or CURRENT
    /* stopAtCurrent */ false,            // true makes the stream bounded at current head
    /* useEventTime */ true,              // assign StreamElement.getStamp() as Beam event time
    model.getEvent().getDataDescriptor());

PCollection<BaseEvent> parsed = events.apply(
    FlatMapElements.into(TypeDescriptor.of(BaseEvent.class))
        .via(e -> model.getEvent().getDataDescriptor()
            .valueOf(e)
            .stream()
            .collect(Collectors.toList())));

2. Batch Updates (getBatchUpdates) #

Reads historical update logs from a batch-updates family (e.g., GCS, S3, HDFS), optionally bounded by [startStamp, endStamp):

long endStamp = System.currentTimeMillis();
long startStamp = endStamp - TimeUnit.DAYS.toMillis(7);

// Bounded batch PCollection
PCollection<StreamElement> updates = beam.getBatchUpdates(
    p, startStamp, endStamp, model.getEvent().getDataDescriptor());

// Replay historical batch updates as a watermarked stream (asStream = true)
PCollection<StreamElement> replayedStream = beam.getBatchUpdates(
    p, startStamp, endStamp, /* asStream */ true, model.getEvent().getDataDescriptor());

3. Batch Snapshot (getBatchSnapshot) #

Reads a compacted point-in-time snapshot of one or more attributes:

PCollection<StreamElement> userSnapshot = beam.getBatchSnapshot(
    p,
    model.getUser().getDetailsDescriptor(),
    model.getUser().getPreferencesDescriptor());

// Or snapshot bounded by time range [fromStamp, untilStamp)
PCollection<StreamElement> historicalSnapshot = beam.getBatchSnapshot(
    p, fromStamp, untilStamp, model.getUser().getDetailsDescriptor());

If an attribute has a family with access: batch-snapshot, BeamDataOperator scans it directly. Otherwise, it automatically reads batch-updates and compacts them into a snapshot using PCollectionTools.reduceAsSnapshot (preserving the winning element’s event timestamp via TimestampCombiner.LATEST).

Writing Data with ProximaIO #

To persist a PCollection<StreamElement> back into Proxima, apply ProximaIO.write(repo.asFactory()). Always pass repo.asFactory() (which is serializable) rather than repo itself:

Pipeline p = Pipeline.create();
PCollection<StreamElement> elements = beam.getStream(
    "InputEvents",
    p,
    Position.CURRENT,
    /* stopAtCurrent */ false,
    /* useEventTime */ true,
    model.getEvent().getDataDescriptor());

PCollection<StreamElement> outputs = elements
    .apply(FlatMapElements.into(TypeDescriptor.of(BaseEvent.class))
        .via(e -> model.getEvent().getDataDescriptor()
            .valueOf(e)
            .stream()
            .collect(Collectors.toList())))
    .apply(Filter.by(e -> e.getAction().equals(Action.BUY)))
    .apply(new ProcessUserBuys());

// Persist outputs to each StreamElement's primary attribute family
outputs.apply(ProximaIO.write(repo.asFactory()));

p.run().waitUntilFinish();

ProximaIO.write writes asynchronously with bounded in-flight concurrency, flushes all pending writes at @FinishBundle, and automatically retries transactional writes on TransactionRejectedException.

Tuning via ProximaPipelineOptions #

ProximaPipelineOptions registers pipeline CLI flags automatically:

OptionDefaultDescription
--proximaIOWriteFinalizeTimeoutMs30000Max milliseconds to wait for pending writes to confirm in @FinishBundle.
--proximaIOMaxPendingWrites1000Maximum weighted in-flight asynchronous writes per worker bundle.
--proximaIOTransactionWriteWeight50Weight assigned to each transactional write against proximaIOMaxPendingWrites.
--startBatchReadDelayMs0Optional delay in ms before starting BatchLogRead.
--preserveUDFJar / --udfJarDirPathtrue / nullControls temporary UDF JAR handling for dynamic Groovy console pipelines.

Built-in Beam Transforms #

cz.o2.proxima.beam.core.transforms ships reusable PTransforms tailored for Proxima streams:

  • PCollectionTools.reduceAsSnapshot(name, input): Reduces a PCollection<StreamElement> of updates into latest-per-(entity, key, attribute) snapshot preserving element timestamps.
  • AssignEventTime: Assigns StreamElement.getStamp() as the Beam element timestamp.
  • ExtractKeyToKv: Converts PCollection<StreamElement> to PCollection<KV<String, StreamElement>> keyed by entity key.
  • StreamElementFilter: Filters elements by entity/attribute descriptors or predicate.
  • FilterLatecomers: Drops elements arriving past allowed lateness.
  • CalendarWindows: Calendar-aligned windowing (days, weeks, months, years) with explicit TimeZone.
  • WatermarkShift / BufferUntilCheckpoint: Watermark alignment and checkpoint-synchronized buffering.
  • Retractable Stream Joins (cz.o2.proxima.beam.core.transforms.retract): RetractPCollection and RetractJoin model changelog streams with additions/retractions ordered by SequentialInstant, enabling dynamic stream-to-stream and stream-to-table joins that emit updated results whenever either side changes.

Native Beam IO vs. Direct-Backed IO #

BeamDataOperator supports two IO layers:

  1. Native Beam IO (e.g., cz.o2.proxima:proxima-beam-io-pubsub for Google Cloud Pub/Sub) — delegates directly to Beam’s native IO connector.
  2. Direct-wrapped IO (DirectDataAccessorWrapper, automatic whenever proxima-direct-core is on the classpath) — wraps any proxima-direct-io-* connector as a Splittable DoFn (CommitLogRead / BatchLogRead) or UnboundedSource/BoundedSource, ensuring identical semantics across DirectDataOperator and BeamDataOperator for Kafka, Cassandra, HBase, Bigtable, GCS, S3, HDFS, JDBC, and inmem://.

End-to-End Pipeline Testing #

Using DirectRunner and inmem:// storage (or TestStreamStorage from proxima-beam-core-testing for deterministic event-time watermark control), you can test complete pipelines in-process:

Repository repo = Repository.ofTest(ConfigFactory.load("test-readme.conf").resolve());
Model model = Model.wrap(repo);
DirectDataOperator direct = repo.getOrCreateOperator(DirectDataOperator.class);
BeamDataOperator beam = repo.getOrCreateOperator(BeamDataOperator.class);

Pipeline p = Pipeline.create();
OnlineAttributeWriter eventWriter =
    Optionals.get(direct.getWriter(model.getEvent().getDataDescriptor()));

long now = System.currentTimeMillis();
writeEvent("user1", now, eventWriter);
writeEvent("user2", now, eventWriter);
writeEvent("user1", now + 1, eventWriter);

// stopAtCurrent = true turns the commit log into a bounded input for testing
PCollection<StreamElement> inputs = beam.getStream(
    p, Position.OLDEST, /* stopAtCurrent */ true, /* useEventTime */ true,
    model.getEvent().getDataDescriptor());

PCollection<StreamElement> outputs = inputs.apply(new MyUserPreferenceTransform(model));
outputs.apply(ProximaIO.write(repo.asFactory()));

p.run().waitUntilFinish();

// Verify materialized results via DirectDataOperator
RandomAccessReader reader =
    Optionals.get(direct.getRandomAccess(model.getUser().getPreferencesDescriptor()));

assertTrue(reader.get("user1", model.getUser().getPreferencesDescriptor()).isPresent());
assertTrue(reader.get("user2", model.getUser().getPreferencesDescriptor()).isPresent());