Create session windows

Question:

If I have time-series events in a Kafka topic, how can I group them into variable-size, non-overlapping time intervals based on a configurable inactivity period?

Edit this page

Example use case:

Given a topic of click events on a website, there are various ways that we can process it. As well as simply counting the number of clicks in a regular time frame (using hopping or tumbling windows), we can also perform sessionization on the data. Here the length of the time window is based on the concept of a session, which is defined based on a period of inactivity. A given user might visit a website multiple times a day, but in distinct visits. Using session windows, we can analyze the number of clicks and duration per visit.

Code example:





Short Answer

To use SessionWindows use the SessionWindows.with method inside a windowedBy call.



builder.stream(<INPUT TOPIC>, Consumed.with(<KEY SERDE>, <VALUE SERDE>))
                .groupByKey()
                .windowedBy(SessionWindows.with(Duration.ofMinutes(5)).grace(Duration.ofSeconds(30)))
                .<Aggergation Operation>....

The SessionsWindows.with call determinines the length inactivity before you consider the session closed. The grace method determines is how much time elapses after the window closes before out-of-order are rejected.

Session windows aggregate events (by key) into sessions. A session represents a period of activity followed by inactivity period. Once the defined time for inactivity elapses, the session is considered closed. Session windows are a bit different from other window types (hopping, tumbling) because they don’t have a fixed window size. As long as new records arrive for a key within the inactivity gap, the window continues to grow in size, meaning the amount of time the window spans, not the total number of records in the window. Another way to view session windows is that they are driven by behavior while other window types are solely time based.

Try it

1
Initialize the project

To get started, make a new directory anywhere you’d like for this project:

mkdir session-windows && cd session-windows

Next, create a directory for configuration data:

mkdir configuration

2
Sign up for Confluent Cloud and provision resources

Sign up for Confluent Cloud, a fully-managed Apache Kafka service. Then provision your resources:

  1. After you log in to Confluent Cloud, click on Add cloud environment and name the environment learn-kafka. Using a new environment keeps your learning resources separate from your other Confluent Cloud resources.

  2. From the Billing & payment section in the Menu, apply the promo code CC100KTS to receive an additional $100 free usage on Confluent Cloud (details).

  3. Click on LEARN and follow the instructions to launch a Kafka cluster and to enable Schema Registry.

Confluent Cloud

3
Create a properties file with Confluent Cloud information

From the Confluent Cloud UI, navigate to your Kafka cluster and click on Clients and then select Java.

Create new credentials for your Kafka cluster and Schema Registry, and then Confluent Cloud will show a configuration similar to below with your new credentials automatically populated (make sure show API keys is checked). Copy and paste it into a configuration/ccloud.properties file on your machine.

# Required connection configs for Kafka producer, consumer, and admin
bootstrap.servers={{ BOOTSTRAP_SERVERS }}
security.protocol=SASL_SSL
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule   required username='{{ CLUSTER_API_KEY }}'   password='{{ CLUSTER_API_SECRET }}';
sasl.mechanism=PLAIN
# Required for correctness in Apache Kafka clients prior to 2.6
client.dns.lookup=use_all_dns_ips

# Best practice for Kafka producer to prevent data loss
acks=all

# Required connection configs for Confluent Cloud Schema Registry
schema.registry.url={{ SR_URL }}
basic.auth.credentials.source=USER_INFO
basic.auth.user.info={{ SR_API_KEY }}:{{ SR_API_SECRET }}
Do not directly copy and paste the above configuration. You must copy it from the UI so that it includes your Confluent Cloud information and credentials.

4
Download and setup the Confluent Cloud CLI

Instructions for installing Confluent Cloud CLI and configuring it to your Confluent Cloud environment is available from within the Confluent Cloud UI. Navigate to your Kafka cluster, click on the CLI and tools section, and run through the steps in the CCloud CLI tab.

5
Configure the project

Create the following Gradle build file, named build.gradle for the project:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "com.commercehub.gradle.plugin:gradle-avro-plugin:0.22.0"
        classpath "com.github.jengelman.gradle.plugins:shadow:6.0.0"
    }
}

plugins {
    id "java"
    id "com.google.cloud.tools.jib" version "2.8.0"
    id "idea"
    id "eclipse"
}

sourceCompatibility = "1.8"
targetCompatibility = "1.8"
version = "0.0.1"

repositories {
    mavenCentral()
    maven {
        url "https://packages.confluent.io/maven"
    }
}

apply plugin: "com.commercehub.gradle.plugin.avro"
apply plugin: "com.github.johnrengelman.shadow"

dependencies {
    implementation "org.apache.avro:avro:1.10.2"
    implementation "org.slf4j:slf4j-simple:1.7.30"
    implementation "org.apache.kafka:kafka-streams:2.7.0"
    implementation('io.confluent:kafka-streams-avro-serde:6.1.1') {
        // this transitive dependency exclusion
        // is needed as kafka-clients:6.1.0-ccs has a version
        // of FixedOrderMap which throws an exception from
        // the clear method so we need AK kafka-clients
        exclude group:'org.apache.kafka', module: 'kafka-clients'
    }
    implementation "org.apache.kafka:kafka-clients:2.7.0"
    testImplementation "org.apache.kafka:kafka-streams-test-utils:2.7.0"
    testImplementation "junit:junit:4.13.2"
    testImplementation 'org.hamcrest:hamcrest:2.2'
}

test {
    testLogging {
        outputs.upToDateWhen { false }
        showStandardStreams = true
        exceptionFormat = "full"
    }
}

jar {
  manifest {
    attributes(
      "Class-Path": configurations.compileClasspath.collect { it.getName() }.join(" "),
      "Main-Class": "io.confluent.developer.SessionWindow"
    )
  }
}

shadowJar {
    archiveBaseName = "session-windows-standalone"
    archiveClassifier = ''
}

And be sure to run the following command to obtain the Gradle wrapper:

gradle wrapper

Then create a development configuration file at configuration/dev.properties:

application.id=session-windows
replication.factor=3

input.topic.name=page-views
input.topic.partitions=6
input.topic.replication.factor=3

output.topic.name=output-topic
output.topic.partitions=6
output.topic.replication.factor=3

6
Update the properties file with Confluent Cloud information

Using the command below, append the contents of configuration/ccloud.properties (with your Confluent Cloud configuration) to configuration/dev.properties (with the application properties).

cat configuration/ccloud.properties >> configuration/dev.properties

7
Create a schema for the model object

Create a directory for the schemas that represent the events in the stream:

mkdir -p src/main/avro

Then create the following Avro schema file at src/main/avro/clicks.avsc for our Clicks object:

{
  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "Clicks",
  "fields": [
    { "name": "ip", "type": "string" },
    { "name": "timestamp", "type": "long" } ,
    { "name": "url", "type": "string" }
  ]
}

Because we will use an Avro schema in our Java code, we’ll need to compile it. The Gradle Avro plugin is a part of the build, so it will see your new Avro files, generate Java code for them, and compile those and all other Java sources. Run this command to get it all done:

./gradlew build

8
Create a timestamp extractor

First, create a directory for the Java files in this project:

mkdir -p src/main/java/io/confluent/developer

Before you create the Kafka Streams application you’ll need to create an instance of a TimestampExtractor. In Kafka Streams, timestamps drive the progress of records in the application. By default, Kafka Streams uses the timestamps contained in the ConsumerRecord. But you can configure your application to use timestamps embedded in the record payload itself. You do this by creating an class implementing the TimestampExtractor interface and provide the class name when configuring your Kafka Streams application like so:

 props.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, ClickEventTimestampExtractor.class.getName());

We’re going to create a custom TimestampExtractor so the Kafka Streams application uses the timestamps embedded in our generated click events.

You aren’t required to use a custom TimestampExtractor in all cases. We’re using one here as it helps drive home the point of how sessions work and we can use synthetic timestamps to ensure we get distinct sessions.

Create the following file at src/main/java/io/confluent/developer/ClickEventTimestampExtractor.java

package io.confluent.developer;

import io.confluent.developer.avro.Clicks;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.streams.processor.TimestampExtractor;

public class ClickEventTimestampExtractor implements TimestampExtractor {
    @Override
    public long extract(ConsumerRecord<Object, Object> record, long previousTimestamp) {
        return ((Clicks)record.value()).getTimestamp();
    }
}

You’ll take care of the configuration when you create the Kafka Streams topology in the next step.

9
Create the Kafka Streams topology

In this tutorial you’ll learn about using SessionWindows with Kafka Streams. Session windows are driven by user behavior, as opposed to time.

   builder.stream(inputTopic, Consumed.with(Serdes.String(), clicksSerde))
                .groupByKey() (1)
                .windowedBy(SessionWindows.with(Duration.ofMinutes(5)).grace(Duration.ofSeconds(30))) (2)
                .count() (3)
                .toStream()
                .map((windowedKey, count) ->  { (4)
                    String start = timeFormatter.format(windowedKey.window().startTime());
                    String end = timeFormatter.format(windowedKey.window().endTime());
                    String sessionInfo = String.format("Session info started: %s ended: %s with count %s", start, end, count);
                    return KeyValue.pair(windowedKey.key(), sessionInfo);
                })
1 Grouping by key, a prerequisite for aggregation operations
2 Specifying a session window for the windowing operation
3 Counting the number of clicks by key per session
4 Formatting the results. You probably won’t do this in practice, but it’s done in this tutorial to make the concept of a session more clear.

For this session window, once there is a period of inactivity of 5 minutes or more for a given key the current session is closed and any new records arriving after that time start a new session.

Session windows aggregate events (by key) into sessions. A session represents a period of activity followed by inactivity period. Once the defined time for inactivity elapses, the session is considered closed. Session windows are a bit different from other window types (hopping, tumbling) because they don’t have a fixed window size. As long as new records arrive for a key within the inactivity gap, the window continues to grow in size, meaning the amount of time the window spans, not the total number of records in the window. Another way to view session windows is that they are driven by behavior while other window types are solely time based.

NOTE: This in this example the incoming records have keys. If your input topic is not keyed, you’ll need to use the KStream.groupBy method and provide a KeyValueMapper instance to select to key to use for grouping.

That wraps up our discussion for the finer points of the code for this tutorial. Now create the following file at src/main/java/io/confluent/developer/SessionWindow.java

package io.confluent.developer;

import io.confluent.developer.avro.Clicks;
import io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import org.apache.avro.specific.SpecificRecord;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.kstream.SessionWindows;

import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;

import static io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG;

public class SessionWindow {

    private final DateTimeFormatter timeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.LONG)
            .withLocale(Locale.US)
            .withZone(ZoneId.systemDefault());

    public Topology buildTopology(Properties allProps) {
        final StreamsBuilder builder = new StreamsBuilder();
        final String inputTopic = allProps.getProperty("input.topic.name");
        final String outputTopic = allProps.getProperty("output.topic.name");
        final SpecificAvroSerde<Clicks> clicksSerde = getSpecificAvroSerde(allProps);

        builder.stream(inputTopic, Consumed.with(Serdes.String(), clicksSerde))
                .groupByKey()
                .windowedBy(SessionWindows.with(Duration.ofMinutes(5)).grace(Duration.ofSeconds(30)))
                .count()
                .toStream()
                .map((windowedKey, count) ->  {
                    String start = timeFormatter.format(windowedKey.window().startTime());
                    String end = timeFormatter.format(windowedKey.window().endTime());
                    String sessionInfo = String.format("Session info started: %s ended: %s with count %s", start, end, count);
                    return KeyValue.pair(windowedKey.key(), sessionInfo);
                })
                .to(outputTopic, Produced.with(Serdes.String(), Serdes.String()));

        return builder.build();
    }


    static <T extends SpecificRecord> SpecificAvroSerde<T> getSpecificAvroSerde(final Properties allProps) {
        final SpecificAvroSerde<T> specificAvroSerde = new SpecificAvroSerde<>();
        final Map<String, String> serdeConfig = (Map)allProps;
        specificAvroSerde.configure(serdeConfig, false);
        return specificAvroSerde;
    }
    public void createTopics(Properties allProps) {
        try (AdminClient client = AdminClient.create(allProps)) {
            List<NewTopic> topicList = new ArrayList<>();

            NewTopic sessionInput = new NewTopic(allProps.getProperty("input.topic.name"),
                    Integer.parseInt(allProps.getProperty("input.topic.partitions")),
                    Short.parseShort(allProps.getProperty("input.topic.replication.factor")));
            topicList.add(sessionInput);

            NewTopic counts = new NewTopic(allProps.getProperty("output.topic.name"),
                    Integer.parseInt(allProps.getProperty("output.topic.partitions")),
                    Short.parseShort(allProps.getProperty("output.topic.replication.factor")));

            topicList.add(counts);
            client.createTopics(topicList);
        }
    }

    public Properties loadEnvProperties(String fileName) throws IOException {
        Properties allProps = new Properties();
        FileInputStream input = new FileInputStream(fileName);
        allProps.load(input);
        input.close();

        return allProps;
    }

    public static void main(String[] args) throws Exception {

        if (args.length < 1) {
            throw new IllegalArgumentException("This program takes one argument: the path to an environment configuration file.");
        }

        SessionWindow tw = new SessionWindow();
        Properties allProps = tw.loadEnvProperties(args[0]);
        allProps.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        allProps.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);
        allProps.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, ClickEventTimestampExtractor.class);
        Topology topology = tw.buildTopology(allProps);

        tw.createTopics(allProps);
        ClicksDataGenerator dataGenerator = new ClicksDataGenerator(allProps);
        dataGenerator.generate();

        final KafkaStreams streams = new KafkaStreams(topology, allProps);
        final CountDownLatch latch = new CountDownLatch(1);

        // Attach shutdown handler to catch Control-C.
        Runtime.getRuntime().addShutdownHook(new Thread("streams-shutdown-hook") {
            @Override
            public void run() {
                streams.close(Duration.ofSeconds(5));
                latch.countDown();
            }
        });

        try {
            streams.cleanUp();
            streams.start();
            latch.await();
        } catch (Throwable e) {
            System.exit(1);
        }
        System.exit(0);
    }

    static class ClicksDataGenerator {
        final Properties properties;


        public ClicksDataGenerator(final Properties properties) {
            this.properties = properties;
        }

        public void generate() {
            properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class);
            properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

            try (Producer<String, Clicks> producer = new KafkaProducer<>(properties)) {
                String topic = properties.getProperty("input.topic.name");
                List<Clicks> sessionClicks = new ArrayList<>();
                final String keyOne = "51.56.119.117";
                final String keyTwo = "53.170.33.192";

                Instant instant = Instant.now();
                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(instant.toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("vestibulum/vestibulum/ante/ipsum/primis/in.json").setTimestamp(instant.plusMillis(9000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/mauris/morbi/non.jpg").setTimestamp(instant.plusMillis(24000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/nullam/orci/pede/venenatis.json").setTimestamp(instant.plusMillis(38000).toEpochMilli()).build());

                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(instant.plusMillis(10000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/mauris/morbi/non.jpg").setTimestamp(instant.plusMillis(32000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/nec/euismod/scelerisque/quam.xml").setTimestamp(instant.plusMillis(44000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/nullam/orci/pede/venenatis.json").setTimestamp(instant.plusMillis(58000).toEpochMilli()).build());

                Instant newSessionInstant = instant.plus(2, ChronoUnit.HOURS);

                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(newSessionInstant.toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("vestibulum/vestibulum/ante/ipsum/primis/in.json").setTimestamp(newSessionInstant.plusMillis(2000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/mauris/morbi/non.jpg").setTimestamp(newSessionInstant.plusMillis(4000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/nullam/orci/pede/venenatis.json").setTimestamp(newSessionInstant.plusMillis(10000).toEpochMilli()).build());

                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(newSessionInstant.plusMillis(11000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/mauris/morbi/non.jpg").setTimestamp(newSessionInstant.plusMillis(12000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/nec/euismod/scelerisque/quam.xml").setTimestamp(newSessionInstant.plusMillis(14000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/nullam/orci/pede/venenatis.json").setTimestamp(newSessionInstant.plusMillis(28000).toEpochMilli()).build());

                sessionClicks.forEach(click -> {
                    producer.send(new ProducerRecord<>(topic, click.getIp(), click), (metadata, exception) -> {
                            if (exception != null) {
                                exception.printStackTrace(System.out);
                            } else {
                                System.out.printf("Produced record at offset %d to topic %s \n", metadata.offset(), metadata.topic());
                            }
                    });
                });
            }
        }
    }
}

10
Compile and run the Kafka Streams program

Now that we have data generation working, let’s build your application by running:

./gradlew shadowJar

Now that you have an uberjar for the Kafka Streams application, you can launch it locally.

When you run the following, the prompt won’t return, because the application will run until you exit it. There is always another message to process, so streaming applications don’t exit until you force them.

java -jar build/libs/session-windows-standalone-0.0.1.jar configuration/dev.properties
This Kafka Streams application includes record generator to populate the topic with "sessionized" data. The first part of running the application will populate data in the input topic for the streams application to process. If you decide to re-run the application the data-generator will run again, giving you slightly different results. In practice, you don’t want to include something like this in a production application.

11
Consume data from the output topic

Now that your Kafka Streams application is running, open a new terminal window, change directories (cd) into the session-windows directory and start a console-consumer to confirm the output:

ccloud kafka topic consume output-topic --from-beginning --print-key

You will be prompted for the Confluent Cloud Schema Registry credentials as shown below, which you can find in the configuration/ccloud.properties configuration file. Look for the configuration parameter basic.auth.user.info, whereby the ":" is the delimiter between the key and secret.

Enter your Schema Registry API key:
Enter your Schema Registry API secret:

Your results should look something like this:


51.56.119.117 : Session info started: 1:13:45 PM EST ended: 1:14:23 PM EST with count 4
53.170.33.192 : Session info started: 1:13:55 PM EST ended: 1:14:43 PM EST with count 4
51.56.119.117 : Session info started: 3:13:45 PM EST ended: 3:13:55 PM EST with count 4
53.170.33.192 : Session info started: 3:13:56 PM EST ended: 3:14:13 PM EST with count 4
Processed a total of 4 messages

12
Teardown Confluent Cloud resources

You may try another Kafka tutorial, but if you don’t plan on doing other tutorials, use the Confluent Cloud UI or CLI to destroy all the resources you created. Verify they are destroyed to avoid unexpected charges.

Test it

1
Create a test configuration file

First, create a test file at configuration/test.properties:

application.id=session-windows-test
bootstrap.servers=localhost:29092
schema.registry.url=mock://localhost:8081

input.topic.name=temp-readings
input.topic.partitions=1
input.topic.replication.factor=1

output.topic.name=output-topic
output.topic.partitions=1
output.topic.replication.factor=1

2
Write a test

Create a directory for the tests to live in:

mkdir -p src/test/java/io/confluent/developer

Testing a Kafka streams application requires a bit of test harness code, but happily the org.apache.kafka.streams.TopologyTestDriver class makes this much more pleasant that it would otherwise be.

There is only one method in SessionWindowTest annotated with @Test, and that is sessionWindowTest(). This method actually runs our Streams topology using the TopologyTestDriver and some mocked data that is set up inside the test method.

This test is straightforward, but there is one section we should look into a little more

final int expectedNumberOfSessions = 2;
final String key = "51.56.119.117";
final List<Clicks> sessionClicks = new ArrayList<>();
Instant instant = Instant.now();

sessionClicks.add(Clicks.newBuilder().setIp(key).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(instant.toEpochMilli()).build()); (1)

Instant newSessionInstant = instant.plus(6,ChronoUnit.MINUTES); (2)

sessionClicks.add(Clicks.newBuilder().setIp(key).setUrl("/mauris/morbi/non.jpg").setTimestamp(newSessionInstant.toEpochMilli()).build());(3)
1 Creating a record for the first "session"
2 Increasing the time to beyond inactivity period, the test should yield 2 sessions in the results
3 Adding record for second "session"

The TestInputTopic provides useful methods when testing your topology. Here you’re using the pipeKeyValueList to provide the records to the steams application. Here you’re not specifying any timestamp activity as the streams application pulls the timestamps embedded in the TemperatureReading objects you created above.

Now create the following file at src/test/java/io/confluent/developer/SessionWindowTest.java.

package io.confluent.developer;


import io.confluent.developer.avro.Clicks;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.TestInputTopic;
import org.apache.kafka.streams.TestOutputTopic;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.TopologyTestDriver;
import org.junit.Test;

import java.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

import static org.junit.Assert.assertEquals;


public class SessionWindowTest {

    private final static String TEST_CONFIG_FILE = "configuration/test.properties";

    @Test
    public void sessionWindowTest() throws IOException {
        final SessionWindow instance = new SessionWindow();
        final Properties allProps = instance.loadEnvProperties(TEST_CONFIG_FILE);

        final String sessionDataInputTopic = allProps.getProperty("input.topic.name");
        final String outputTopicName = allProps.getProperty("output.topic.name");

        final Topology topology = instance.buildTopology(allProps);
        try (final TopologyTestDriver testDriver = new TopologyTestDriver(topology, allProps)) {

            final SpecificAvroSerde<Clicks> exampleAvroSerde = SessionWindow.getSpecificAvroSerde(allProps);

            final Serializer<String> keySerializer = Serdes.String().serializer();
            final Serializer<Clicks> exampleSerializer = exampleAvroSerde.serializer();
            final Deserializer<String> valueDeserializer = Serdes.String().deserializer();
            final Deserializer<String> keyDeserializer = Serdes.String().deserializer();

            final TestInputTopic<String, Clicks>  inputTopic = testDriver.createInputTopic(sessionDataInputTopic,
                                                                                              keySerializer,
                                                                                              exampleSerializer);

            final TestOutputTopic<String, String> outputTopic = testDriver.createOutputTopic(outputTopicName, keyDeserializer, valueDeserializer);
            final String key = "51.56.119.117";
            final List<Clicks> sessionClicks = new ArrayList<>();
            Instant instant = Instant.now();
            final int expectedNumberOfSessions = 2;
            sessionClicks.add(Clicks.newBuilder().setIp(key).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(instant.toEpochMilli()).build());
            Instant newSessionInstant = instant.plus(6,ChronoUnit.MINUTES);
            sessionClicks.add(Clicks.newBuilder().setIp(key).setUrl("/mauris/morbi/non.jpg").setTimestamp(newSessionInstant.toEpochMilli()).build());
            List<KeyValue<String, Clicks>> keyValues = sessionClicks.stream().map(o -> KeyValue.pair(o.getIp(),o)).collect(Collectors.toList());
            inputTopic.pipeKeyValueList(keyValues);

            final List<KeyValue<String, String>> actualResults = outputTopic.readKeyValuesToList();
            // Should result in two sessions
            assertEquals(expectedNumberOfSessions, actualResults.size());
        }
    }
}

3
Invoke the tests

Now run the test, which is as simple as:

./gradlew test

Take it to production

1
Create a production configuration file

First, create a new configuration file at configuration/prod.properties with the following content. Be sure to fill in the addresses of your production hosts and change any other parameters that make sense for your setup.

application.id=session-windows
bootstrap.servers=<<FILL ME IN>>
schema.registry.url=<<FILL ME IN>>

input.topic.name=temp-readings
input.topic.partitions=<<FILL ME IN>>
input.topic.replication.factor=<<FILL ME IN>>

output.topic.name=output-topic
output.topic.partitions=<<FILL ME IN>>
output.topic.replication.factor=<<FILL ME IN>>

2
Build a Docker image

In your terminal, execute the following to invoke the Jib plugin to build an image:

gradle jibDockerBuild --image=io.confluent.developer/session-windows-join:0.0.1

3
Launch the container

Finally, launch the container using your preferred container orchestration service. If you want to run it locally, you can execute the following:

docker run -v $PWD/configuration/prod.properties:/config.properties io.confluent.developer/session-windows-join:0.0.1 config.properties