Một JVM connector · Java và Kotlin

Học CoAkka Runtime qua Java + Kotlin/JVM

Chọn Maven hoặc Gradle, sau đó chọn Java hoặc Kotlin. Kotlin là lối học chính với named arguments tường minh; Java có sample first-run và typed deadletter dùng đúng cùng connector 3.3.2. Advanced giữ nguyên target khi chuyển handler sang peer, File Lane, Stream Lane và Monitor.

Beginner · 01 / 04

Chọn Java/Kotlin và Maven/Gradle

Bài học dùng JDK 17 làm môi trường build dễ lặp lại. Connector JVM vẫn có consumer floor Java 8, nhưng floor của package không phải là lý do để học bằng một build tool cũ. Chỉ chọn một trong hai lối dưới.

1. Cài JDK và kiểm tra

Cài JDK 17 từ một nhà cung cấp đáng tin cậy, đặt JAVA_HOME, thêm $JAVA_HOME/bin vào PATH, rồi chạy:

Terminal
java -version

2. Chọn một build tool

3. Tạo project

Terminal
mkdir -p coakka-kotlin-demo/src/main/kotlin
cd coakka-kotlin-demo
Nếu chọn Maven: tạo 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>
Nếu chọn Gradle: tạo 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`
}

Cả hai file đều ghim đúng connector io.github.phuong-tran.coakka:runtime:3.3.2 từ Maven Central. Không cần clone repository hoặc tự đặt đường dẫn native library.

4. Tạo 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. Chạy bằng build tool đã chọn

Maven
mvn -q compile exec:java
Gradle
gradle run

Kết quả mong đợi

accepted-hello
CoAkka.local(systemName = …, nodeId = …)
Tạo owner local-first cho một process JVM. Named arguments làm rõ identity nào thuộc system và identity nào thuộc node.
handler(target = …)
Đăng ký business handler cùng process. Network mặc định là Embedded.
ask(target = …, payloadUtf8 = …, timeoutMs = …)
Gửi request và chờ terminal reply/deadletter trong coroutine.
shutdown()
Đợi CoAkka Runtime dừng trước khi process JVM kết thúc.
Dùng Java thay vì Kotlin

Java dùng cùng coordinate và native Core. Tạo src/main/java/FirstRun.java; không cần Kotlin plugin.

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 là Java-friendly Level 2 owner của package JVM 3.3.2; đây không phải API bị suy đoán từ sample cũ. getJava() trả surface dùng CompletableFuture hoặc blocking helper.

Xem artifact Maven Central 3.3.2 (tuỳ chọn)

Beginner · 02 / 04

Đặt tên cho việc cần làm

Thay nội dung Main.kt. Target orders.quote là địa chỉ nghiệp vụ; route chọn nơi xử lý, handler tính giá.

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()
    }
}

Chạy lại bằng mvn -q compile exec:java hoặc gradle run.

Kết quả mong đợi

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

Thử thêm quantity 3. Bài vẫn chỉ có một process để người học tập trung vào contract trước khi thêm network.

Beginner · 03 / 04

Đọc một deadletter

Bài này mở API Level 2 để cố ý giữ route hợp lệ nhưng gửi tới target không tồn tại. Package JVM 3.3.2 đặt tên owner Level 2 là ConnectorOrchestrator; nó chỉ xuất hiện khi cần explicit routes, outcomes hoặc effective state.

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()
    }
}

Chạy lại bằng Maven hoặc Gradle như tập 1.

Kết quả mong đợi

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

DeadletterException.deadletter chứa reason và original envelope do Core cấp. Không parse message text để suy đoán outcome. Tra toàn bộ Deadletter fields và checklist.

Cùng outcome bằng 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

Đưa vào ứng dụng thực tế

Giữ một owner theo vòng đời ứng dụng. Hàm requestQuote là seam để HTTP endpoint, job hoặc consumer hiện có gọi CoAkka Runtime.

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()
    }
}

Kết quả mong đợi

order quote: 360000 VND

Không tạo runtime theo từng request. Business authorization và handler thuộc app; routing, transport, bounds và outcome facts thuộc Core.

Advanced · 05

Chuyển handler sang peer

Target và caller không đổi. Quote service mở một network node trên loopback; checkout là outbound-only và route tới endpoint được công bố. Đây là distributed trực tiếp, không cần Kubernetes.

1. Tạo 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

Chờ dòng quote service ready at 127.0.0.1:19321 và giữ terminal mở.

2. Tạo 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

Kết quả mong đợi

order quote: 360000 VND
networkNode(bindHost = …, advertiseHost = …)
Bind là nơi listener mở; advertise là địa chỉ peer truy cập.
outboundOnly()
Caller gọi ra ngoài nhưng không mở listener nhận request.
SINGLE_OWNER
Route này có một owner. weight = 1 là route weight, không phải retry count.
Connection strategy bỏ trống
Giữ Core default MULTIPLEXING; connector không tự dựng bảng default.

Hiểu distributed trực tiếp · Từ laptop tới edge/Kubernetes

Advanced · 06

Chuyển file bằng File Lane

File Lane là data plane độc lập, dành cho file có size và SHA-256 xác định. Ví dụ tạo sender/receiver cùng process chỉ để học 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

Kết quả mong đợi

hello from File Lane

Production phải chuyển owner grant qua control plane đã xác thực, chờ cả SEND và RECEIVE terminal, ghi nhận outcome rồi forget record. Tra File Lane contract đầy đủ.

Advanced · 07

Gửi stream bằng Stream Lane

Stream Lane dùng callback source/consumer và bounded receive window. ByteBuffer chỉ được borrow trong callback; copy trước khi giữ lại.

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

Kết quả mong đợi

frame-one, frame-two

maxFrameBytes và initialWindowBytes là bounds, không phải tuning trang trí. Tra flow control, pressure và failure.

Advanced · 08

Quan sát Monitor và effective state

Bật Monitor là startup intent. Snapshot là latest copied state; awaitNext chờ doorbell có deadline và trả null khi không có signal trong cửa sổ, không tự biến thành lỗi.

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

Một kết quả hợp lệ

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

Signal count có thể khác theo timing; contract cần kiểm tra là enabled, snapshot đọc được và no-signal vẫn phân biệt với closure/failure.

Chạy configuration lab · Tra Operations & Evidence