Class SseEventParser

java.lang.Object
com.langfuse.client.core.SseEventParser

public final class SseEventParser extends Object
Utility class for parsing Server-Sent Events with support for discriminated unions.

Handles two discrimination patterns:

  1. Data-level discrimination: The discriminator (e.g., 'type') is inside the JSON data payload. Jackson's polymorphic deserialization handles this automatically.
  2. Event-level discrimination: The discriminator (e.g., 'event') is at the SSE envelope level. This requires constructing the full SSE envelope for Jackson to process.
  • Method Details

    • parseEventLevelUnion

      public static <T> T parseEventLevelUnion(String eventType, String data, String id, Long retry, Class<T> unionClass, String discriminatorProperty)
      Parse an SSE event using event-level discrimination.

      Constructs the full SSE envelope object with event, data, id, and retry fields, then deserializes it to the target union type.

      Type Parameters:
      T - The target type
      Parameters:
      eventType - The SSE event type (from event: field)
      data - The SSE data content (from data: field)
      id - The SSE event ID (from id: field), may be null
      retry - The SSE retry value (from retry: field), may be null
      unionClass - The target union class
      discriminatorProperty - The property name used for discrimination (e.g., "event")
      Returns:
      The deserialized object
    • parseDataLevelUnion

      public static <T> T parseDataLevelUnion(String data, Class<T> valueType)
      Parse an SSE event using data-level discrimination.

      Simply parses the data field as JSON and deserializes it to the target type. Jackson's polymorphic deserialization handles the discrimination automatically.

      Type Parameters:
      T - The target type
      Parameters:
      data - The SSE data content (from data: field)
      valueType - The target type
      Returns:
      The deserialized object
    • isEventLevelDiscrimination

      public static boolean isEventLevelDiscrimination(String discriminatorProperty)
      Determines if the given discriminator property indicates event-level discrimination. Event-level discrimination occurs when the discriminator is an SSE envelope field.
      Parameters:
      discriminatorProperty - The discriminator property name
      Returns:
      true if event-level discrimination, false otherwise
    • findDiscriminatorProperty

      public static Optional<String> findDiscriminatorProperty(Class<?> unionClass)
      Attempts to find the discriminator property from the union class's Jackson annotations.
      Parameters:
      unionClass - The union class to inspect
      Returns:
      The discriminator property name, or empty if not found