liveBook · Manning

oneOf

As explained in Kafka Streams in Action, Second Edition

oneOf is a Protocol Buffers field construct that permits a message to contain one member from a set of alternative fields.

oneOf lets a Protocol Buffers message carry one member from several alternative fields. It must live inside a message, not stand alone at the top level. section 3.6

For a topic containing related customer events, an outer Events message can select PurchaseEvent, LoginEvent, or SearchEvent while preserving their ordering in one topic. Generated Java code represents the alternatives through the wrapper’s type field. section 3.6 section 4.6.1

Producing and consuming Events

Configure KafkaProtobufSerializer and use Events as the KafkaProducer value type. On consumption, configure KafkaProtobufDeserializer with Events.class, then inspect hasLoginEvent(), hasSearchEvent(), or hasPurchaseEvent(); alternatively, switch on Events.getTypeCase() and process the selected object. section 4.6.1 section 4.6.2

Listing 3.38 Protobuf file with references
syntax = "proto3";

package bbejeck.chapter_3.proto;

import "purchase_event.proto";        #1
import "login_event.proto";
import "search_event.proto";

option java_multiple_files = true;
option java_outer_classname = "EventsProto";

message Events {

  oneof type {                          #2
    PurchaseEvent purchase_event = 1;
    LoginEvent login_event = 2;
    SearchEvent search_event = 3;
  }
  string key = 4;
}

Review the complete proto3 definition, including imported event schemas, the oneOf alternatives, and the wrapper key. section 3.6

switch (event.getTypeCase()) {
    case LOGIN_EVENT -> {                   #1
        logins.add(event.getLoginEvent());    #2
    }
    case SEARCH_EVENT -> {
        searches.add(event.getSearchEvent());
    }
    case PURCHASE_EVENT ->  {
        purchases.add(event.getPurchaseEvent());
    }
}

Compare enum-based dispatch branches for login, search, and purchase events. section 4.6.2

How Kafka Streams in Action, Second Edition covers it

How deep it goes
Explains message placement, generated Java APIs, producer configuration, and consumer dispatch, but stops short of wire-format internals.
Examples
Uses purchase, login, and search events with proto3 definitions, Java producer configuration, and TypeCase-based consumer branches.
What it assumes
Assumes familiarity with Protocol Buffers schemas and Kafka clients while demonstrating the wrapper and generated APIs required for oneOf.
What you can do after
Apply it via Kafka Java producers and consumers that serialize an Events wrapper and dispatch its selected generated event type.
How it connects
Connects Protocol Buffers oneOf with Kafka serialization, deserialization, Schema Registry references, and Avro unions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kafka Streams in Action, Second Edition. The section links point to the parts of the book it draws on.