One JVM connector · Java and Kotlin

Learn CoAkka Runtime with Java + Kotlin/JVM

Choose Maven or Gradle and the JVM language you use. Kotlin is the primary learning path with explicit named arguments; Java includes exact first-run and typed-deadletter samples against the same 3.3.2 connector. Advanced lessons move the same target to a peer, File Lane, Stream Lane and Monitor.

Beginner · 01 / 04

Choose Java/Kotlin and Maven/Gradle

The lessons use JDK 17 as a repeatable build environment. The JVM connector retains a Java 8 consumer floor, but that package floor does not require an old build tool. Choose only one path below.

1. Install a JDK and verify it

Install a trusted JDK 17 distribution, set JAVA_HOME, add $JAVA_HOME/bin to PATH, then run:

Terminal
java -version

2. Choose one build tool

3. Create the project

Terminal
mkdir -p coakka-kotlin-demo/src/main/kotlin
cd coakka-kotlin-demo
If you chose Maven: create pom.xml
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>dev.coakka.learning</groupId>
  <artifactId>coakka-runtime-kotlin-demo</artifactId>
  <version>1.0-SNAPSHOT</version>

  <properties>
    <kotlin.version>2.3.10</kotlin.version>
    <exec.mainClass>MainKt</exec.mainClass>
    <maven.compiler.release>17</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>io.github.phuong-tran.coakka</groupId>
      <artifactId>runtime</artifactId>
      <version>3.3.2</version>
    </dependency>
  </dependencies>

  <build>
    <sourceDirectory>src/main/kotlin</sourceDirectory>
    <plugins>
      <plugin>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-maven-plugin</artifactId>
        <version>${kotlin.version}</version>
        <executions>
          <execution>
            <id>compile</id>
            <phase>compile</phase>
            <goals><goal>compile</goal></goals>
          </execution>
        </executions>
        <configuration>
          <jvmTarget>17</jvmTarget>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>3.6.2</version>
        <configuration>
          <mainClass>${exec.mainClass}</mainClass>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
If you chose Gradle: create build.gradle.kts
build.gradle.kts
plugins {
    kotlin("jvm") version "2.3.10"
    application
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("io.github.phuong-tran.coakka:runtime:3.3.2")
}

kotlin {
    jvmToolchain(17)
}

application {
    mainClass.set(
        providers.gradleProperty("mainClass").orElse("MainKt"),
    )
}

tasks.named<JavaExec>("run") {
    standardInput = System.`in`
}

Both files pin io.github.phuong-tran.coakka:runtime:3.3.2 from Maven Central. You do not clone a repository or configure a native library path.

4. Create src/main/kotlin/Main.kt

Main.kt
import coakka.v2.connector.CoAkka
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val runtime = CoAkka.local(
        systemName = "hello",
        nodeId = "hello-1",
    )

    try {
        runtime.handler(target = "hello.accept") { payload ->
            "accepted-$payload"
        }

        val reply = runtime.ask(
            target = "hello.accept",
            payloadUtf8 = "hello",
            timeoutMs = 2_000,
        )
        println(reply)
    } finally {
        runtime.shutdown()
    }
}

5. Run with the tool you chose

Maven
mvn -q compile exec:java
Gradle
gradle run

Expected output

accepted-hello
CoAkka.local(systemName = …, nodeId = …)
Creates the local-first owner for one JVM process. Named arguments make both identities explicit.
handler(target = …)
Registers same-process business work; network remains Embedded.
ask(target = …, payloadUtf8 = …, timeoutMs = …)
Sends a request and awaits a terminal reply or deadletter in the coroutine.
shutdown()
Waits for CoAkka Runtime to stop before the JVM exits.
Use Java instead of Kotlin

Java uses the same coordinate and native Core. Create src/main/java/FirstRun.java; no Kotlin plugin is required.

Maven pom.xml

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>dev.coakka.learning</groupId>
  <artifactId>coakka-runtime-java-demo</artifactId>
  <version>1.0-SNAPSHOT</version>

  <properties>
    <exec.mainClass>FirstRun</exec.mainClass>
    <maven.compiler.release>17</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>io.github.phuong-tran.coakka</groupId>
      <artifactId>runtime</artifactId>
      <version>3.3.2</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.14.1</version>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>3.6.2</version>
        <configuration>
          <mainClass>${exec.mainClass}</mainClass>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Gradle build.gradle.kts

build.gradle.kts
plugins {
    application
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("io.github.phuong-tran.coakka:runtime:3.3.2")
}

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(17))
    }
}

application {
    mainClass.set(
        providers.gradleProperty("mainClass").orElse("FirstRun"),
    )
}
FirstRun.java
import coakka.v2.connector.ConnectorOrchestrator;
import coakka.v2.connector.RuntimeClient;
import coakka.v2.connector.RuntimeStartSpec;
import coakka.v2.connector.protocol.ConnectorDeliveryHint;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public final class FirstRun {
    private FirstRun() {
    }

    public static void main(String[] args) throws Exception {
        String target = "hello.accept";
        RuntimeStartSpec startSpec = new RuntimeStartSpec(
            "hello",
            "hello-1",
            Collections.singletonList(RuntimeClient.localRoute(target))
        );

        ConnectorOrchestrator runtime = ConnectorOrchestrator.start(startSpec);
        Throwable primaryFailure = null;
        try {
            runtime.registerTextHandler(target, payload -> "accepted-" + payload);

            String reply = runtime.getJava().askTextBlocking(
                "hello-client",
                target,
                "hello",
                2_000,
                "accept",
                ConnectorDeliveryHint.ROUTER_DEFAULT
            );
            System.out.println(reply);
        } catch (Exception | Error failure) {
            primaryFailure = failure;
            throw failure;
        } finally {
            try {
                runtime.getJava().shutdown().get(3, TimeUnit.SECONDS);
            } catch (Exception | Error cleanup) {
                if (primaryFailure == null) {
                    throw cleanup;
                }
                primaryFailure.addSuppressed(cleanup);
            }
        }
    }
}
Maven
mvn -q compile exec:java -Dexec.mainClass=FirstRun
Gradle
gradle run -PmainClass=FirstRun

ConnectorOrchestrator is the Java-friendly Level 2 owner in JVM package 3.3.2; it is not an API inferred from an old sample. getJava() exposes CompletableFuture and blocking helpers.

View Maven Central artifact 3.3.2 (optional)

Beginner · 02 / 04

Name the work

Replace Main.kt. orders.quote is the business address; the route chooses an owner and the handler calculates the quote.

Main.kt
import coakka.v2.connector.CoAkka
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val runtime = CoAkka.local(
        systemName = "orders",
        nodeId = "orders-1",
    )

    try {
        runtime.handler(target = "orders.quote") { payload ->
            val quantity = payload.toInt()
            "${quantity * 120_000} VND"
        }

        for (quantity in listOf(1, 2)) {
            val quote = runtime.ask(
                target = "orders.quote",
                payloadUtf8 = quantity.toString(),
                timeoutMs = 2_000,
            )
            println("quantity=$quantity quote=$quote")
        }
    } finally {
        runtime.shutdown()
    }
}

Run mvn -q compile exec:java or gradle run again.

Expected output

quantity=1 quote=120000 VND
quantity=2 quote=240000 VND

Add quantity 3. This remains one process so you learn the contract before adding a network.

Beginner · 03 / 04

Read a deadletter

This lesson opens Level 2 to retain a valid route while deliberately calling a missing target. JVM package 3.3.2 names its Level 2 owner ConnectorOrchestrator; it appears only when explicit routes, outcomes or effective state are needed.

Main.kt
import coakka.v2.connector.ConnectorOrchestrator
import coakka.v2.connector.DeadletterException
import coakka.v2.connector.RuntimeClient
import coakka.v2.connector.RuntimeStartSpec
import coakka.v2.connector.TextHandler
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val runtime = ConnectorOrchestrator.start(
        startSpec = RuntimeStartSpec(
            systemName = "orders",
            nodeId = "orders-1",
            routes = RuntimeClient.localRoutes(
                targets = listOf("orders.quote"),
            ),
        ),
    )

    try {
        runtime.registerTextHandler(
            target = "orders.quote",
            handler = TextHandler { payload ->
                "${payload.toInt() * 120_000} VND"
            },
        )

        try {
            runtime.kotlin.askText(
                source = "checkout",
                target = "orders.missing",
                payloadUtf8 = "2",
                timeoutMs = 2_000,
            )
        } catch (failure: DeadletterException) {
            val deadletter = failure.deadletter
            println(
                "deadletter reason=${deadletter.reason.value} " +
                    "target=${deadletter.originalEnvelope?.target}",
            )
        }

        val quote = runtime.kotlin.askText(
            source = "checkout",
            target = "orders.quote",
            payloadUtf8 = "2",
            timeoutMs = 2_000,
        )
        println("quantity=2 quote=$quote")
    } finally {
        runtime.kotlin.shutdown()
    }
}

Expected output

deadletter reason=2 target=orders.missing
quantity=2 quote=240000 VND

DeadletterException.deadletter carries the Core-issued reason and original envelope. Never infer the outcome by parsing an error string. Look up all Deadletter fields and checks.

The same outcome in Java
RouteMiss.java
import coakka.v2.connector.ConnectorOrchestrator;
import coakka.v2.connector.DeadletterException;
import coakka.v2.connector.RuntimeClient;
import coakka.v2.connector.RuntimeStartSpec;

import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public final class RouteMiss {
    private RouteMiss() {
    }

    public static void main(String[] args) throws Exception {
        String liveTarget = "orders.quote";
        String missingTarget = "orders.missing";
        RuntimeStartSpec startSpec = new RuntimeStartSpec(
            "orders",
            "orders-1",
            Collections.singletonList(RuntimeClient.localRoute(liveTarget))
        );

        ConnectorOrchestrator runtime = ConnectorOrchestrator.start(startSpec);
        Throwable primaryFailure = null;
        try {
            runtime.registerTextHandler(
                liveTarget,
                quantity -> Integer.parseInt(quantity) * 120_000 + " VND"
            );

            try {
                runtime.getJava().askText(
                    "checkout",
                    missingTarget,
                    "2"
                ).get(3, TimeUnit.SECONDS);
                throw new IllegalStateException("expected route miss");
            } catch (ExecutionException failure) {
                if (!(failure.getCause() instanceof DeadletterException deadletterFailure)) {
                    throw failure;
                }
                System.out.println(
                    "deadletter reason=" + deadletterFailure.getDeadletter().getReason().getValue()
                        + " target=" + missingTarget
                );
            }

            String quote = runtime.getJava().askTextBlocking(
                "checkout",
                liveTarget,
                "2"
            );
            System.out.println("quantity=2 quote=" + quote);
        } catch (Exception | Error failure) {
            primaryFailure = failure;
            throw failure;
        } finally {
            try {
                runtime.getJava().shutdown().get(3, TimeUnit.SECONDS);
            } catch (Exception | Error cleanup) {
                if (primaryFailure == null) {
                    throw cleanup;
                }
                primaryFailure.addSuppressed(cleanup);
            }
        }
    }
}
Maven
mvn -q compile exec:java -Dexec.mainClass=RouteMiss
Gradle
gradle run -PmainClass=RouteMiss

Beginner · 04 / 04

Integrate the owner

Keep one owner for the application lifecycle. requestQuote is the seam used by an existing HTTP endpoint, job or consumer.

Main.kt
import coakka.v2.connector.CoAkka
import coakka.v2.connector.LocalRuntime
import kotlinx.coroutines.runBlocking

class QuoteApplication {
    private val runtime: LocalRuntime = CoAkka.local(
        systemName = "checkout",
        nodeId = "checkout-1",
    ).handler(target = "orders.quote") { payload ->
        "${payload.toInt() * 120_000} VND"
    }

    suspend fun requestQuote(quantity: Int): String = runtime.ask(
        target = "orders.quote",
        payloadUtf8 = quantity.toString(),
        timeoutMs = 2_000,
    )

    suspend fun shutdown() {
        runtime.shutdown()
    }
}

fun main() = runBlocking {
    val application = QuoteApplication()
    try {
        println("order quote: ${application.requestQuote(quantity = 3)}")
    } finally {
        application.shutdown()
    }
}

Expected output

order quote: 360000 VND

Do not create a runtime per request. Business authorization and handlers belong to the app; routing, transport, bounds and outcome facts belong to Core.

Advanced · 05

Move the handler to a peer

The target and caller stay unchanged. The quote service opens a loopback network node; checkout is outbound-only and routes to its advertised endpoint. This is direct distributed execution without Kubernetes.

1. Create QuoteService.kt

QuoteService.kt
import coakka.v2.connector.ConnectorOrchestrator
import coakka.v2.connector.RuntimeClient
import coakka.v2.connector.RuntimeNetworkConfig
import coakka.v2.connector.RuntimeStartSpec
import coakka.v2.connector.TextHandler
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val runtime = ConnectorOrchestrator.start(
        startSpec = RuntimeStartSpec(
            systemName = "pricing",
            nodeId = "pricing-1",
            routes = RuntimeClient.localRoutes(
                targets = listOf("orders.quote"),
            ),
            network = RuntimeNetworkConfig.networkNode(
                bindHost = "127.0.0.1",
                bindPort = 19_321,
                advertiseHost = "127.0.0.1",
                advertisePort = 19_321,
            ),
        ),
    )

    try {
        runtime.registerTextHandler(
            target = "orders.quote",
            handler = TextHandler { payload ->
                "${payload.toInt() * 120_000} VND"
            },
        )
        println("quote service ready at 127.0.0.1:19321")
        println("Press Enter to stop.")
        readlnOrNull()
        Unit
    } finally {
        runtime.kotlin.shutdown()
    }
}
Terminal 1 · Maven
mvn -q compile exec:java -Dexec.mainClass=QuoteServiceKt
Terminal 1 · Gradle
gradle run -PmainClass=QuoteServiceKt

Wait for quote service ready at 127.0.0.1:19321 and keep the terminal open.

2. Create Checkout.kt

Checkout.kt
import coakka.v2.connector.ConnectorOrchestrator
import coakka.v2.connector.RuntimeEndpointFlags
import coakka.v2.connector.RuntimeEndpointSpec
import coakka.v2.connector.RuntimeNetworkConfig
import coakka.v2.connector.RuntimeRouteSpec
import coakka.v2.connector.RuntimeRouteStrategy
import coakka.v2.connector.RuntimeStartSpec
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val runtime = ConnectorOrchestrator.start(
        startSpec = RuntimeStartSpec(
            systemName = "checkout",
            nodeId = "checkout-1",
            routes = listOf(
                RuntimeRouteSpec(
                    target = "orders.quote",
                    endpoints = listOf(
                        RuntimeEndpointSpec(
                            host = "127.0.0.1",
                            port = 19_321,
                            weight = 1,
                            flags = RuntimeEndpointFlags.NONE,
                        ),
                    ),
                    strategy = RuntimeRouteStrategy.SINGLE_OWNER,
                ),
            ),
            network = RuntimeNetworkConfig.outboundOnly(),
        ),
    )

    try {
        val quote = runtime.kotlin.askText(
            source = "checkout",
            target = "orders.quote",
            payloadUtf8 = "3",
            timeoutMs = 2_000,
        )
        println("order quote: $quote")
    } finally {
        runtime.kotlin.shutdown()
    }
}
Terminal 2 · Maven
mvn -q compile exec:java -Dexec.mainClass=CheckoutKt
Terminal 2 · Gradle
gradle run -PmainClass=CheckoutKt

Expected output

order quote: 360000 VND
networkNode(bindHost = …, advertiseHost = …)
Bind controls the listener; advertise is what peers reach.
outboundOnly()
The caller opens no inbound listener.
SINGLE_OWNER
This route has one owner. weight = 1 is a route weight, not a retry count.
Omitted connection strategy
Preserves Core's MULTIPLEXING default.

Understand direct distribution · Move from laptop to edge or Kubernetes

Advanced · 06

Transfer a file with File Lane

File Lane is an independent data plane for a file with a known size and SHA-256. This example puts sender and receiver in one process only to teach lifecycle.

FileLaneDemo.kt
import coakka.v2.connector.FileLane
import coakka.v2.connector.FileLaneConfig
import coakka.v2.connector.FileLaneFlags
import coakka.v2.connector.FileReceiveSpec
import coakka.v2.connector.FileTransferDirection
import coakka.v2.connector.FileTransferSnapshot
import coakka.v2.connector.LaneOwnerConfig
import java.nio.file.Files
import java.nio.file.Path
import java.util.Comparator

fun main() {
    val directory = Files.createTempDirectory("coakka-file-lane-")
    val source = directory.resolve("source.txt")
    val destination = directory.resolve("received.txt")
    Files.writeString(source, "hello from File Lane\n")

    val receiver = FileLane.openOwned(
        config = FileLaneConfig(
            flags = FileLaneFlags.RECEIVER,
            bindHost = "127.0.0.1",
            bindPort = 0,
        ),
        owner = LaneOwnerConfig(
            ownerInstanceId = "receiver-1",
            advertisedHost = "127.0.0.1",
        ),
    )
    val sender = FileLane.open(
        config = FileLaneConfig(flags = FileLaneFlags.SENDER),
    )

    try {
        val digest = FileLane.sha256(path = source)
        val grant = receiver.prepareReceiveGrant(
            spec = FileReceiveSpec(
                transferId = "portal-file-1",
                authorizationToken = "study-token",
                destinationPath = destination,
                expectedSize = digest.size,
                expectedSha256 = digest.sha256,
            ),
        )
        sender.submitSend(
            spec = grant.toSendSpec(
                sourcePath = source,
                timeoutMs = 5_000,
            ),
        )

        val sent = sender.awaitTerminal(
            transferId = grant.transferId,
            direction = FileTransferDirection.SEND,
        )
        val received = receiver.awaitTerminal(
            transferId = grant.transferId,
            direction = FileTransferDirection.RECEIVE,
        )
        check(sent.completed && received.completed)
        println(Files.readString(destination).trim())

        sender.forget(
            transferId = grant.transferId,
            direction = FileTransferDirection.SEND,
        )
        receiver.forget(
            transferId = grant.transferId,
            direction = FileTransferDirection.RECEIVE,
        )
    } finally {
        sender.close()
        receiver.close()
        Files.walk(directory).use { paths ->
            paths.sorted(Comparator.reverseOrder()).forEach(Files::deleteIfExists)
        }
    }
}

private fun FileLane.awaitTerminal(
    transferId: String,
    direction: FileTransferDirection,
): FileTransferSnapshot {
    var afterUpdateSequence = 0L
    while (true) {
        val snapshot = waitTransfer(
            transferId = transferId,
            direction = direction,
            afterUpdateSequence = afterUpdateSequence,
            timeoutMs = 5_000,
        )
        if (snapshot.terminal) return snapshot
        afterUpdateSequence = snapshot.updateSequence
    }
}
Maven
mvn -q compile exec:java -Dexec.mainClass=FileLaneDemoKt
Gradle
gradle run -PmainClass=FileLaneDemoKt

Expected output

hello from File Lane

Production sends the owner grant through an authenticated control plane, waits for both SEND and RECEIVE terminal receipts, records the outcome, then forgets both records. Read the complete File Lane contract.

Advanced · 07

Send a stream with Stream Lane

Stream Lane uses source and consumer callbacks plus a bounded receive window. A ByteBuffer is borrowed only during the callback; copy before retaining it.

StreamLaneDemo.kt
import coakka.v2.connector.LaneOwnerConfig
import coakka.v2.connector.StreamConsumer
import coakka.v2.connector.StreamConsumerDecision
import coakka.v2.connector.StreamDirection
import coakka.v2.connector.StreamFrameFlags
import coakka.v2.connector.StreamLane
import coakka.v2.connector.StreamLaneConfig
import coakka.v2.connector.StreamLaneFlags
import coakka.v2.connector.StreamPublishSpec
import coakka.v2.connector.StreamSessionSnapshot
import coakka.v2.connector.StreamSource
import coakka.v2.connector.StreamSourceResult

fun main() {
    val frames = listOf("frame-one", "frame-two").map(String::toByteArray)
    var nextFrame = 0
    val receivedFrames = mutableListOf<String>()

    val publisher = StreamLane.openOwned(
        config = StreamLaneConfig(
            flags = StreamLaneFlags.PUBLISHER,
            bindHost = "127.0.0.1",
            bindPort = 0,
            maxFrameBytes = 1_024,
            maxWindowBytes = 4_096,
        ),
        owner = LaneOwnerConfig(
            ownerInstanceId = "publisher-1",
            advertisedHost = "127.0.0.1",
        ),
    )
    val subscriber = StreamLane.open(
        config = StreamLaneConfig(
            flags = StreamLaneFlags.SUBSCRIBER,
            maxFrameBytes = 1_024,
            maxWindowBytes = 4_096,
        ),
    )

    try {
        val grant = publisher.preparePublishGrant(
            spec = StreamPublishSpec(
                sessionId = "portal-stream-1",
                authorizationToken = "study-token",
                formatId = 1,
                maxFrameBytes = 1_024,
                source = StreamSource { destination ->
                    if (nextFrame == frames.size) {
                        StreamSourceResult.End
                    } else {
                        val frame = frames[nextFrame++]
                        destination.put(frame)
                        StreamSourceResult.Frame(
                            size = frame.size,
                            capturedMonoNs = System.nanoTime(),
                            flags = if (nextFrame == 1) StreamFrameFlags.KEYFRAME else 0,
                        )
                    }
                },
            ),
        )
        subscriber.subscribe(
            spec = grant.toSubscribeSpec(
                initialWindowBytes = 4_096,
                timeoutMs = 5_000,
                consumer = StreamConsumer { data, _ ->
                    val copied = ByteArray(data.remaining())
                    data.get(copied)
                    receivedFrames += copied.toString(Charsets.UTF_8)
                    StreamConsumerDecision.CONTINUE
                },
            ),
        )

        val published = publisher.awaitTerminal(
            sessionId = grant.sessionId,
            direction = StreamDirection.PUBLISH,
        )
        val subscribed = subscriber.awaitTerminal(
            sessionId = grant.sessionId,
            direction = StreamDirection.SUBSCRIBE,
        )
        check(published.completed && subscribed.completed)
        println(receivedFrames.joinToString(separator = ", "))

        publisher.forget(
            sessionId = grant.sessionId,
            direction = StreamDirection.PUBLISH,
        )
        subscriber.forget(
            sessionId = grant.sessionId,
            direction = StreamDirection.SUBSCRIBE,
        )
    } finally {
        subscriber.close()
        publisher.close()
    }
}

private fun StreamLane.awaitTerminal(
    sessionId: String,
    direction: StreamDirection,
): StreamSessionSnapshot {
    var afterUpdateSequence = 0L
    while (true) {
        val snapshot = waitSession(
            sessionId = sessionId,
            direction = direction,
            afterUpdateSequence = afterUpdateSequence,
            timeoutMs = 5_000,
        )
        if (snapshot.terminal) return snapshot
        afterUpdateSequence = snapshot.updateSequence
    }
}
Maven
mvn -q compile exec:java -Dexec.mainClass=StreamLaneDemoKt
Gradle
gradle run -PmainClass=StreamLaneDemoKt

Expected output

frame-one, frame-two

maxFrameBytes and initialWindowBytes are resource bounds, not decorative tuning. Look up flow control, pressure and failure.

Advanced · 08

Observe Monitor and effective state

Enabling Monitor is startup intent. A snapshot is latest copied state; awaitNext waits on a bounded doorbell and returns null for no signal in the window, not for closure or failure.

Monitoring.kt
import coakka.v2.connector.ConnectorOrchestrator
import coakka.v2.connector.RuntimeClient
import coakka.v2.connector.RuntimeMonitorOptions
import coakka.v2.connector.RuntimeStartSpec
import coakka.v2.connector.TextHandler
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val runtime = ConnectorOrchestrator.start(
        startSpec = RuntimeStartSpec(
            systemName = "orders",
            nodeId = "orders-1",
            routes = RuntimeClient.localRoutes(
                targets = listOf("orders.quote"),
            ),
            monitor = RuntimeMonitorOptions(enabled = true),
        ),
    )

    try {
        runtime.registerTextHandler(
            target = "orders.quote",
            handler = TextHandler { payload ->
                "${payload.toInt() * 120_000} VND"
            },
        )
        runtime.kotlin.askText(
            source = "checkout",
            target = "orders.quote",
            payloadUtf8 = "2",
            timeoutMs = 2_000,
        )

        val latest = runtime.monitor.snapshot()
        val next = runtime.monitor.awaitNext(timeoutMs = 250)
        println("monitor enabled=${runtime.monitor.isEnabled()}")
        println("latest state=${latest.health.runtimeStateName}")
        println("next signal=${next?.signalCount ?: "none in 250 ms"}")
    } finally {
        runtime.kotlin.shutdown()
    }
}
Maven
mvn -q compile exec:java -Dexec.mainClass=MonitoringKt
Gradle
gradle run -PmainClass=MonitoringKt

One valid output

monitor enabled=true
latest state=started
next signal=1

The signal count can vary with timing; verify enabled state, readable snapshots and the distinction between no-signal and failure.

Run the configuration lab · Operations & Evidence