ktbuf
1.1.2indexedEnables Protocol Buffers serialization and deserialization, facilitating the creation and manipulation of binary data with ease and efficiency.
Enables Protocol Buffers serialization and deserialization, facilitating the creation and manipulation of binary data with ease and efficiency.
KtBuf is a Kotlin Multiplatform protocol-buffers toolkit. It provides:
ktbuf-library) that runs on JVM, Android, iOS/macOS, JavaScript and Linux..proto files via the protoc-gen-kt plugin: immutable data classes, builders, sealed-class enums and oneofs, and typed service stubs.ktbuf-rpc) that sends unary calls over HTTP and streaming calls over WebSockets on every supported platform.ktbuf-server) that serves generated services on the backend.ktbuf-patch) and test utilities (ktbuf-test).buf.validate validators generated
into the optional ktbuf-validate module.google.rpc.Status details (such as ErrorInfo) carried on HTTP and WebSocket failures.KtBuf is not gRPC. It reuses gRPC's status-code numbers and
grpc-statusheader name, but it has its own simple HTTP/1.1 + WebSocket protocol. A KtBuf client cannot call a standard gRPC server, and a gRPC client cannot call a KtBuf server. See Relationship to gRPC.
All artifacts are published to Maven Central under the group com.latenighthack.ktbuf.
// build.gradle.kts (Kotlin Multiplatform client)
kotlin {
sourceSets {
commonMain.dependencies {
implementation("com.latenighthack.ktbuf:ktbuf-library:1.2.0")
implementation("com.latenighthack.ktbuf:ktbuf-rpc:1.2.0")
}
}
}
// build.gradle.kts (JVM backend)
dependencies {
implementation("com.latenighthack.ktbuf:ktbuf-library:1.2.0")
implementation("com.latenighthack.ktbuf:ktbuf-server:1.2.0")
testImplementation("com.latenighthack.ktbuf:ktbuf-test:1.2.0")
testImplementation("com.latenighthack.ktbuf:ktbuf-rpc:1.2.0")
}
Built with Kotlin 2.3.10, kotlinx-coroutines 1.9.0, OkHttp 4.12.0 and Ktor 3.0.2. Android minSdk is 24.
All multiplatform modules target jvm, androidTarget, js (browser and Node), iosX64, iosArm64,
iosSimulatorArm64, macosX64, and .
The protobuf runtime, generated messages and ktbuf-patch work fully on Linux. Only the built-in transports are missing
there: HTTP, unary RPC and streaming RPC calls fail immediately with RpcResponseException and Codes.UNIMPLEMENTED, and
unsupported streaming calls never invoke their block or readiness callback. Supply your own HttpClient or RpcClient
for networking on Linux (see Custom transports).
KtBuf types are generated by protoc-gen-kt, a protoc plugin written in Go that lives in a separate repository. The
exact versions used by this repository are pinned in gradle/protobuf-tools.properties:
protoc=34.1
protocGenKt=37bc8004b83c5731df1546853b90520028ff58b9
protocGenKtTag=v0.2.0
# protoc: install exactly the pinned version (e.g. from https://github.com/protocolbuffers/protobuf/releases)
protoc --version # libprotoc 34.1
# protoc-gen-kt: install the pinned revision onto your PATH
go install latenighthack.com/protoc-gen-kt@37bc8004b83c5731df1546853b90520028ff58b9 # reports v0.2.0
protoc \
--plugin=protoc-gen-kt="$(go env GOPATH)/bin/protoc-gen-kt" \
--kt_out=build/generated/proto/kotlin \
-I src/commonMain/proto \
src/commonMain/proto/*.proto
For each foo.proto the plugin writes foo.data.kt, foo.builder.kt, foo.encoder.kt and foo.decoder.kt. When the
file declares services it also writes foo.service.kt (client stub) and foo.server.kt (server interface).
Plugin parameters go in --kt_opt, comma-separated. Both are off by default, and any other parameter is an error:
protoc --plugin=protoc-gen-kt=... --kt_out=out --kt_opt=validate=true,wkt_helpers=true -I proto proto/*.proto
Modules in this repository use the shared script gradle/protobuf-codegen.gradle. It registers a cacheable
generateProtoKotlin task that checks the tool versions, runs protoc, stages the output and only then replaces
the previous output in build/generated/proto/kotlin. To use it from another project, copy the script and the
properties file.
// conformance/build.gradle.kts
extra["protobufSourceDir"] = "src/commonMain/proto"
apply(from = rootProject.file("gradle/protobuf-codegen.gradle"))
val generateProtoKotlin = tasks.named("generateProtoKotlin")
kotlin {
sourceSets {
val commonMain by getting {
// Wiring the task provider makes every compile task depend on code generation.
kotlin.srcDir(generateProtoKotlin)
dependencies { api("com.latenighthack.ktbuf:ktbuf-library:1.2.0") }
}
}
}
Per-project extra[...] settings (set before applying the script): protobufSourceDir (required), protobufValidate
(default ; passes , see below), (default ; passes )
and (a list of directories searched for imports but never generated, merged with
). All of them are task inputs.
Executable contents and every configured schema import are task inputs, so changing the compiler, the generator or an
imported .proto invalidates the cached output.
and are generated like any other schema, into package (their ). To get them, put copies at and under your proto source directory (this repository vendors them in ), or pass them to explicitly from its directory. Helpers are opt-in: with the generator parameter (, or before applying ; combine with other options as ), for exactly those two files also writes with , , , , , , , , and . Without the flag no is written. The helpers need Kotlin 2.3.0 or newer (stable there), so with the flag does not compile on older compilers.
Pass --kt_opt=validate=true (Gradle: extra["protobufValidate"] = true) to also generate foo.validate.kt with, for
every message, fun Foo.validate(): List<Violation>, fun Foo.validateOrThrow() (throws ProtoValidationException)
and . Validation never runs implicitly during decode or encode. The default is off, in
which case options are ignored. Unknown generator parameters are errors.
Generated code needs the module (, , for //). Schemas import , which is proto2: put it (and ) on an include path only (), never in the source directory. / rules need those two files generated too (copy them into the source directory, as does).
Validation recurses into every embedded message (singular, repeated or map value) except google.protobuf.* well-known
types, including messages declared in other packages or modules, by calling that message's validateInto. Generation
fails closed rather than skipping them: every module whose messages are embedded must also be generated with
validate=true, otherwise the consumer does not compile (unresolved validateInto).
Violation and match Go protovalidate (, , ). Supported: string (), bytes (), bool , enum (), all numeric types (, floats also , including protovalidate's exclusive ranges), Duration (), Timestamp (those plus ), repeated (), map (), , , and on a oneof. Anything else (, , message , well-known string formats, , ...) makes generation fail with . accepts only an RE2 subset that behaves identically on JVM, JS and Native (no , , nested variable repetition); means end of input as in RE2. Expected results are compared with Go protovalidate by ().
The examples in this README use the conformance schema from conformance/src/commonMain/proto/conformance.proto
(abridged):
syntax = "proto3";
package conformance.v1;
option java_package = "com.latenighthack.ktbuf.conformance.v1";
message AllTypes {
int32 f_int32 = 1;
string f_string = 14;
bytes f_bytes = 15;
enum Kind { UNKNOWN = 0; A = 3; B = 4; C = 5; }
Kind f_enum = 16;
Inner f_inner = 17;
repeated int32 r_int32 = 18;
repeated Inner r_inner = 20;
message Inner { string str = 1; int32 an_int = 2; }
}
message OneOfHolder {
int32 lead = 1;
oneof choice {
int32 c_int = 2;
string c_string = 3;
AllTypes.Inner c_inner = 4;
}
}
message MapValue { int32 id = 1; string text = 2; }
message MapHolder {
map<string, int32> ints = 1;
map<int32, MapValue> messages = 2;
}
service Conformance {
rpc Unary(AllTypes) returns (AllTypes);
rpc ServerStream(AllTypes) returns (stream AllTypes);
rpc ClientStream(stream AllTypes) returns (AllTypes);
rpc Bidi(stream AllTypes) returns (stream AllTypes);
}
Every message is an immutable data class whose constructor parameters default to the proto3 defaults. Field names are
converted to camelCase.
import com.latenighthack.ktbuf.conformance.v1.AllTypes
val message = AllTypes(
fInt32 = 42,
fString = "héllo",
fBytes = byteArrayOf(0x00, 0x01),
fEnum = AllTypes.Kind.B,
fInner = AllTypes.Inner(str = "inner", anInt = 7),
rInt32 = listOf(1, 2, 3),
)
val changed = message.copy(fInt32 = 43)
The generated builders give you a DSL, which is especially handy for maps:
val holder = MapHolder {
ints { "a" to 3 }
messages { 1 to MapValue(id = 4) }
}
toByteArray() and fromByteArray() are generated extension functions in the message's package:
import com.latenighthack.ktbuf.conformance.v1.AllTypes
import com.latenighthack.ktbuf.conformance.v1.fromByteArray
import com.latenighthack.ktbuf.conformance.v1.toByteArray
val bytes: ByteArray = AllTypes(fInt32 = 21).toByteArray() // 08 15
val decoded: AllTypes = AllTypes.fromByteArray(bytes)
check(decoded.fInt32 == 21)
// An all-default message encodes to zero bytes, and zero bytes decode to the default message.
check(AllTypes().toByteArray().isEmpty())
For untrusted input, parse with explicit limits:
import com.latenighthack.ktbuf.ProtobufLimits
val limits = ProtobufLimits(
maxMessageBytes = 1 * 1024 * 1024, // default 16 MiB
maxDepth = 32, // default 64 levels of nesting
maxWork = 100_000, // default 1,000,000 decoding work units
)
val parsed = AllTypes.parseFrom(bytes, limits)
When a limit is exceeded, parsing throws ProtobufLimitException (a subclass of IllegalArgumentException). Malformed
input throws IllegalArgumentException or IndexOutOfBoundsException. Invalid UTF-8 in a string field is rejected.
By default, decoding is lenient: unknown fields are kept in unknownFields and re-emitted on encode, and unknown enum
values are preserved. For input that must match your schema exactly, decode strictly:
import com.latenighthack.ktbuf.ProtobufDecodeOptions
import com.latenighthack.ktbuf.ProtobufStrictDecodeException
import com.latenighthack.ktbuf.conformance.v1.decodeStrict
import com.latenighthack.ktbuf.conformance.v1.parseFrom
try {
val msg = AllTypes.decodeStrict(bytes)
// equivalent: AllTypes.parseFrom(bytes, ProtobufDecodeOptions.Strict)
} (e: ProtobufStrictDecodeException) {
println()
}
options = ProtobufDecodeOptions(rejectUnknownFields = , rejectUnknownEnumValues = )
parsed = AllTypes.parseFrom(bytes, options)
ProtobufDecodeOptions.Strict sets both rejectUnknownFields and rejectUnknownEnumValues. Strict decoding rejects:
rejectUnknownEnumValues) an enum value that has no declared constant.ProtobufStrictDecodeException (an IllegalArgumentException) carries fieldNumber and depth. Default decoding is
unchanged. Unknown-field rejection is enforced by the runtime reader, so it also works with code from older generators.
Unknown-enum rejection needs code regenerated with a current generator. A custom ProtobufReader implementation must
override rejectUnknownFields and rejectUnknownEnumValues.
import com.latenighthack.ktbuf.ProtobufEncodeOptions
import com.latenighthack.ktbuf.conformance.v1.toByteArray
import com.latenighthack.ktbuf.conformance.v1.toDeterministicByteArray
val a: ByteArray = msg.toDeterministicByteArray()
val b: ByteArray = msg.toByteArray(ProtobufEncodeOptions.Deterministic) // same bytes
Deterministic encoding matches Go's proto.MarshalOptions{Deterministic: true} byte for byte:
bool false before , signed integers numerically, unsigned
integers numerically, and strings by UTF-8 byte order. That differs from Kotlin's for supplementary
characters; the runtime uses .Equality with Go is tested against goldens produced by Go (tools/go-goldens).
As with Go, determinism is guaranteed only for the same schema and library version. It is not canonicalisation: two different encodings of the same message can still exist (for example, differently ordered unknown fields). If you sign or hash messages, verify the exact bytes you received rather than re-encoding them.
// Enums keep values this build doesn't recognize, so newer peers round-trip safely.
val future = AllTypes(fEnum = AllTypes.Kind.fromInt(99))
check(AllTypes.fromByteArray(future.toByteArray()).fEnum.value == 99)
// Oneofs
val holder = OneOfHolder(lead = 1, choice = OneOfHolder.OneOfChoice.cString("s"))
when (val choice = holder.choice) {
null -> println("not set")
else -> println(choice.getCString() ?: choice.getCInt())
}
Generated encoders write oneof fields before regular fields. The output is semantically identical to other protobuf
implementations, but it is not always byte-for-byte identical to the reference serializer's canonical order.
Generated code is built on two small interfaces in com.latenighthack.ktbuf, which you can also use directly.
import com.latenighthack.ktbuf.ProtobufOutputStream
val bytes = ProtobufOutputStream.encode {
encode(150, 1) // int32 field 1 -> 08 96 01
encode("hi", 14) // string field 14 -> 72 02 68 69
encodeSInt(-1, 5) // sint32 field 5 -> 28 01 (zigzag)
encode(17) { // nested message, field 17
encode("inner", )
}
}
ProtobufWriter has encode, encodeSInt and encodeFixed overloads for every scalar type, an overload for nested
messages, and encodeRaw for pre-encoded bytes. Passing null as the field number writes the value without a tag,
which is used for packed elements.
Encoding is bounded too. ProtobufOutputStream.encode(ProtobufOutputLimits(maxMessageBytes, maxDepth, maxWork)) { ... }
caps output size, nesting and work (the defaults are 16 MiB, 64 levels and 1,000,000 units), and throws
ProtobufOutputLimitException when a limit is exceeded.
ProtobufReader has a reader for every scalar type (readInt32, readSInt64, readFixedInt32, readBytes, ...)
and reports currentFieldNumber and . is the
concrete reader if you want to bypass .
ktbuf-library also provides URL-safe Base64 without padding: ByteArray.toBase64UrlString() and
String.fromBase64UrlString().
import com.latenighthack.ktbuf.conformance.v1.ConformanceServiceRpc
import com.latenighthack.ktbuf.rpc.HttpRpcClient
val rpc = HttpRpcClient("https://api.example.com")
val service = ConformanceServiceRpc(rpc)
The base URL accepts http://, https://, ws:// and . A bare defaults to plain /.
Unary calls use the HTTP form of the URL and streaming calls use the WebSocket form ( ↔ ). Whitespace, ,
and other schemes are rejected.
HttpRpcClient(serverPath, useApiGateway = true) switches to the API Gateway path style described in
URL format.
The generated ConformanceService interface has one method per RPC:
// Unary: one request, one response.
val reply: AllTypes = service.unary(AllTypes(fInt32 = 21))
// Server streaming: one request, a Flow of responses.
service.serverStream(AllTypes(fInt32 = 1))
.collect { println(it.fInt32) }
// Client streaming: a Flow of requests, one response.
val total: AllTypes = service.clientStream(flowOf(AllTypes(fInt32 = 1), AllTypes(fInt32 = 2)))
// Bidirectional streaming: a Flow of requests, a Flow of responses.
service.bidi(requests).collect { println(it) }
Streaming flows are cold: the WebSocket opens when you collect, and closes when collection completes or is cancelled. For bidirectional and client streaming, completing the request flow sends a half-close to the server, and the client keeps reading responses until the server ends the stream.
Streaming methods take an optional trailing readyCallback, which is invoked once the WebSocket is connected:
service.serverStream(request) { println("connected") }.collect { /* ... */ }
Generated stubs send no headers themselves. To add headers such as Authorization, wrap the transport in an
InterceptingRpcClient:
Interceptors can also rewrite the RpcMethodSpecifier (for example to add query parameters through
additionalParameters) and transform individual stream frames. Browsers cannot set WebSocket handshake headers, so in
browser JavaScript pass credentials as query parameters or cookies instead. Sec-WebSocket-Protocol is reserved and
cannot be set.
For browsers (and any client that cannot set handshake headers), HttpRpcClient can send a short-lived, single-use
ticket as a query parameter on the WebSocket handshake URL only. This keeps transport credentials out of generated
request parameters and additionalParameters.
val client = HttpRpcClient("https://api.example.com", false, StreamTicketProvider { method ->
myBackend.mintTicket(method.serviceName, method.methodName) // fetched over an authenticated unary call
})
// Server: read it in the context processor or handler, then invalidate it on first use.
val ticket = context.streamTicket() // GrpcRequestContext.streamTicket(parameter = "ktbuf-ticket")
The provider is called exactly once per streaming call, just before the handshake URL is built, never for unary calls,
and the result is never cached: a retry or reconnect asks again. Return null to send no ticket. If the provider
throws, the call fails with that exception. If additionalParameters already contains the parameter name (default
ktbuf-ticket, configurable with streamTicketParameter), the call fails with INVALID_ARGUMENT. The ticket is never
included in RpcResponseException.path, exception messages or library logs.
Tickets travel in the URL, so:
Response headers of unary calls are available on the raw RpcResponse.headers when you call RpcClient.unaryCall
yourself. Map<String, String>.rpcHeader(name) looks one up case-insensitively and joins repeated values with commas.
Every RPC failure reported by the server surfaces as com.latenighthack.ktbuf.net.RpcResponseException:
try {
service.unary(request)
} catch (e: RpcResponseException) {
println("${e.code} ${e.errorMessage}") // e.g. NOT_FOUND "no such user"
if (e.retriable()) { /* safe to retry */ }
}
e.code is a com.latenighthack.ktbuf.proto.Codes value. These use the standard gRPC numbering, plus one client-only
code:
A server can attach a google.rpc.Status with details. It is available as e.status
(com.latenighthack.ktbuf.wkt.RpcStatus, with code, message and details), and e.errorInfo returns the first
in it:
catch (e: RpcResponseException) {
val info = e.errorInfo
println("${info?.reason} ${info?.domain} ${info?.metadata}")
}
status and errorInfo are null when the server sent no details or they were malformed.
How errors surface on each platform:
By default, unary calls use the platform's timeouts. On JVM and Android, OkHttp waits at most 10 s between reads. For services whose responses legitimately take longer, give the client a total per-call budget (connect, send, wait and read):
val rpc = HttpRpcClient("https://api.example.com", useApiGateway = false, callTimeoutMillis = 60_000)
The budget applies to unary calls only, and streaming calls keep the platform defaults. JS reports an elapsed budget as
DEADLINE_EXCEEDED. On JVM and Android it surfaces as OkHttp's timeout IOException, and on Apple platforms as
CLIENT_TIMEOUT. The derived OkHttp client still shares the default connection pool and dispatcher.
Nothing is sent on the wire about deadlines. To bound any call, including a stream, use structured concurrency:
val reply = withTimeout(5_000) { service.unary(request) }
Cancelling the calling coroutine cancels the platform request or closes the WebSocket.
ktbuf-rpc includes exponential-backoff helpers in com.latenighthack.ktbuf.rpc. By default they retry when
RpcResponseException.retriable() is true, never retry encoding or decoding limit failures
(ProtobufLimitException, ProtobufOutputLimitException, ByteArrayLimitException), and retry any other exception:
import com.latenighthack.ktbuf.rpc.repeatWithBackoff
import com.latenighthack.ktbuf.rpc.retryWithBackoff
// Retry a unary call up to 5 times, starting at 100 ms and growing 1.5x with 40% jitter (max 15 s between tries).
val reply = repeatWithBackoff(retryLimit = 5) { attempt -> service.unary(request) }
// Resubscribe to a stream after retriable failures.
service.serverStream(request)
.retryWithBackoff(maxRetryTime = 30_000) { attempt -> println("reconnecting, attempt $attempt"); null }
.collect { /* ... */ }
Inside repeatWithBackoff, retry() forces another attempt and cancel() stops retrying. repeatWithBackoff throws
RetryLimitExceeded once the retry limit is used up.
rpc.close() // rejects new calls with CANCELLED and cancels active ones
rpc.closeAndJoin() // also waits for in-flight calls and their cleanup to finish
Calling closeAndJoin() from inside one of the same client's calls throws IllegalStateException. On JVM and Android,
every HttpRpcClient and PlatformHttpClient shares one lazily created OkHttpClient, so connection pools and threads
are reused across clients. It has no cookie jar, so credentials never leak between clients. Closing a client does not
shut that shared pool down.
HttpRpcClient is just one implementation of com.latenighthack.ktbuf.net.RpcClient:
Generated stubs accept any RpcClient. Implement it to add a new platform (such as Linux), route calls in process, or
put a different transport underneath. conformance/src/commonTest/.../FakeRpcClient.kt is a complete in-memory example.
ktbuf-server serves generated services with Ktor on the CIO engine. Each RPC method becomes one
route: unary methods are HTTP POST endpoints, and every streaming method is a WebSocket endpoint.
For each service, protoc-gen-kt generates an interface (ConformanceServer) and a descriptor
(ConformanceServer.Descriptor) that maps method names to decoders, encoders and handlers.
Streaming handlers return Flow<StreamControlEvent<T>>. Emit StreamControlEvent.Message(value) for each response, and
either let the flow complete or emit StreamControlEvent.Close() to end the stream successfully.
import com.latenighthack.ktbuf.server.runServer
import com.latenighthack.ktbuf.server.serveAll
import io.ktor.server.routing.routing
suspend fun main() = runServer {
routing {
serveAll(ConformanceService(), ConformanceServer.Descriptor)
// serveAll(OtherService(), OtherServer.Descriptor) ...
}
}
This registers:
POST /api/conformance.v1.Conformance/Unary
WEBSOCKET /api/conformance.v1.Conformance/ServerStream
WEBSOCKET /api/conformance.v1.Conformance/ClientStream
WEBSOCKET /api/conformance.v1.Conformance/Bidi
runServer is an opinionated entry point. It listens on port 8080, installs WebSockets (16 MiB max frame) and CORS
(any host, Content-Type allowed), and suspends until JVM shutdown. For control over the port and engine, use
defaultServer. It returns once the server is ready and the setup block has finished, and stops the server again if
setup fails:
import com.latenighthack.ktbuf.server.defaultServer
val server = defaultServer(config = { connector { port = 9000 } }) {
routing { serveAll(ConformanceService(), ConformanceServer.Descriptor) }
}
// ...
server.stop()
To mount services into an existing Ktor application, install Ktor's WebSockets plugin yourself and call serveAll
inside routing { }. serveUnary, serveStreamingOut and serveStreamingInOut register a single method if you need
finer control.
Every handler receives a GrpcRequestContext:
data class GrpcRequestContext(
val originalUrl: String, // request path
val headers: Map<String, String>, // first value of each header
val query: Map<String, String>, // first value of each query parameter
val extensions: Map<String, Any>, // your own per-request data
val serverDescriptor: ServerDescriptor,
val methodDescriptor: ServerMethodDescriptor<*, *, *>,
)
The contextProcessor argument to serveAll runs once per call, before the request body or any stream frame is
parsed. It is the place for authentication. Throw to reject the call, or return a context enriched with extensions:
routing {
serveAll(ConformanceService(), ConformanceServer.Descriptor) { context ->
val token = context.headers["Authorization"]?.removePrefix("Bearer ")
?: context.query["token"] // browsers: WebSockets cannot send headers
?: throw RpcResponseException(context.originalUrl, , Codes.UNAUTHENTICATED, )
user = verify(token)
?: RpcResponseException(context.originalUrl, , Codes.PERMISSION_DENIED, )
context.copy(extensions = context.extensions + ( to user))
}
}
user = context.extensions[] User
For streaming methods, the contextProcessor runs once per call. By default a thrown RpcResponseException closes the
upgraded socket with a close code (for example for ) rather than answering an HTTP , so
every client, browsers included, sees the same . Pass to
(or /) to reject the handshake over HTTP instead; see
the WebSocket protocol section below.
serveAll(server, descriptor, limits = ProtobufLimits(...), contextProcessor) bounds request decoding. Unary bodies
larger than maxMessageBytes are rejected while they are being read, and WebSocket frames are capped at the same size.
To send google.rpc.Status details to the client, pass a status:
import com.latenighthack.ktbuf.wkt.ErrorInfo
import com.latenighthack.ktbuf.wkt.RpcStatus
throw RpcResponseException(
path, verb, Codes.FAILED_PRECONDITION, "quota exceeded",
status = RpcStatus(
code = Codes.FAILED_PRECONDITION.value,
message = "quota exceeded",
details = listOf(ErrorInfo(reason = "QUOTA", domain = "example.com").toAny()),
),
)
The generator also emits LocalConformanceServiceRpc(server, extensions = emptyMap()), which implements the client
interface ConformanceService by calling a ConformanceServer directly, with no network or serialization. It is useful
for monoliths and tests.
This section specifies exactly what crosses the network. A minimal reference peer written in Python lives in
rpc/src/testFixtures/transport_peer.py, and the byte-level goldens are in
library/src/commonTest/kotlin/com/latenighthack/ktbuf/RpcWireGoldenTests.kt.
Every message is the plain protobuf encoding of the request or response type: no length prefix, no compression flag, no envelope.
{base}/api/{package}.{Service}/{Method}[?{key}={value}&...]
Example: https://api.example.com/api/conformance.v1.Conformance/Unary.
Path segments and query parameters are percent-encoded. Only A-Z a-z 0-9 - . _ ~ are left as is. Query parameters come
from RpcMethodSpecifier.additionalParameters. A WebSocket handshake may also carry a single-use connection ticket
(ktbuf-ticket by default) from a StreamTicketProvider; unary URLs never do.
API Gateway style (HttpRpcClient(url, useApiGateway = true)) flattens the path into one segment, for gateways that
route on a single path component:
{base}/ws_{package with '.' replaced by '_'}_{Service}_{Method}[?query]
Example: package p, service S, method M becomes /ws_p_S_M. ktbuf-server does not register these paths; the
gateway must rewrite them to the /api/... form.
Request
POST /api/conformance.v1.Conformance/Unary HTTP/1.1
Host: api.example.com
Content-Type: application/proto
Authorization: Bearer … (any headers added by interceptors)
Content-Length: 2
08 15
The body 08 15 is AllTypes(fInt32 = 21): the tag 0x08 (field 1, wire type 0 = varint) followed by the varint
0x15 (21).
Successful response
HTTP/1.1 200 OK
grpc-status: 0
Access-Control-Expose-Headers: grpc-status
08 2a
A 2xx status is success, and the body is the encoded response message. An empty body decodes to the default
message. ktbuf-server sends grpc-status: 0 on success and exposes the header to browser CORS callers.
Error response
HTTP/1.1 400 INVALID_ARGUMENT
grpc-status: 3
Content-Type: text/plain
fInt32 must be >= 0
The body is a UTF-8 error message. The client decides the code like this:
grpc-status header is present, its integer value is the code. The header must be a known code whose
Codes.toHttpCode() equals the HTTP status (for example grpc-status: 5 with 404). A malformed or contradictory
header is a protocol error and is reported as . A non-zero on a response is treated
as an error.The server always sends grpc-status, and chooses the HTTP status with Codes.toHttpCode() (the inverse of this
table). There are no trailers.
Structured error details. An error can also carry a serialized google.rpc.Status (for example with a
reason and domain) in the response header, encoded as standard
base64 (RFC 4648 section 4) without padding, as gRPC does. Decoders accept padded or unpadded input. Throw
from a server handler to send it; clients expose it as
(and , which is null rather than throwing on a malformed ).
The server forces to match the exception's code, and every unary response sets
so browsers can read both.
The header is advisory and bounded: the encoded value may be at most 8 KiB (MAX_STATUS_DETAILS_HEADER_BYTES). A
sender whose status exceeds that omits the header. A receiver that finds the header absent, oversized, not valid
base64, not a valid Status, or with a code different from grpc-status ignores it, and the call fails with the
code and message alone (status == null). Details are never a reason to fail a call.
Each streaming call opens its own WebSocket. Calls are never multiplexed onto one connection.
Handshake
GET /api/conformance.v1.Conformance/Bidi HTTP/1.1
Host: api.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: …
Sec-WebSocket-Protocol: ktbuf.stream.v1
Authorization: Bearer … (not possible from browsers)
HTTP/1.1 101 Switching Protocols
Sec-WebSocket-Protocol: ktbuf.stream.v1
The client offers the subprotocol ktbuf.stream.v1 on every streaming call, and ktbuf-server selects it on every
streaming route. Browsers fail the handshake if an offered subprotocol is not selected, so other servers must echo it
too. Once it is negotiated, the client may send the half-close marker described below. If the handshake is rejected with an HTTP status ≥ 400 (for example a gateway's 401), the status and
any grpc-status header are mapped exactly as for unary calls.
Status details over WebSockets. Close frames cannot carry a Status, so a client that understands details
offers a second subprotocol token, , after the first: . The server still selects only . If the call fails with
details, a server that selected and saw the capability token sends exactly one text frame,
(same base64 as the header, at most 16 KiB including the prefix,
), immediately before the close frame, which is unchanged. A server never sends the marker
otherwise, because older clients treat any text frame as a protocol error. A client accepts at most one marker; it
attaches it to the failure derived from the close code if it decodes and its code matches, and otherwise
ignores it. Any other text frame, a second marker, or a binary frame after the marker is a protocol error
().
When contextProcessor (for example authentication) throws RpcResponseException on a streaming route, the default
is to upgrade and close with 4000 + code and the safe reason, preceded by the status marker for clients that offered
ktbuf.status-details.v1. This is the 1.1.x behaviour, and browsers can read it, so for example an
UNAUTHENTICATED auth failure reaches them with its code and details.
Opt in with rejectStreamingHandshakes = true and the server instead rejects the upgrade request itself with the HTTP
status for that code plus grpc-status, grpc-status-details-bin and a CORS expose header. JVM, Android, Apple and
Node clients decode those details. Browsers cannot: the WebSocket API exposes nothing about a rejected upgrade, so
they report without details, and auth-refresh logic keyed on would not fire. That is
why handshake rejection is opt-in. Non- failures close as in both modes.
Frames
Close codes
A socket that closes before it finishes opening is reported as UNAVAILABLE.
Server streaming
client server
│── WebSocket handshake ─────────────────▶│
│── Binary: request ─────────────────────▶│
│◀──────────────────── Binary: response 1 ─│
│◀──────────────────── Binary: response 2 ─│
│◀──────────────────── Close 1000 ─────────│
The server reads exactly one request frame. The client does not send the half-close marker for server streaming.
Client and bidirectional streaming
client server
│── WebSocket handshake (ktbuf.stream.v1) ▶│
│── Binary: request 1 ───────────────────▶│
│◀──────────────────── Binary: response 1 ─│ (bidi: any interleaving)
│── Binary: request 2 ───────────────────▶│
│── Text: "ktbuf.requests.end" ──────────▶│ request flow completed
│◀──────────────────── Binary: response 2 ─│
│◀──────────────────── Close 1000 ─────────│ or +code
For client streaming, the server sends exactly one response frame. The client fails with DATA_LOSS if it receives zero
or more than one. The client waits for the first request (or for the request flow to complete) before opening the
socket.
Legacy peers. Every streaming route (server, client and bidirectional) is registered both with the ktbuf.stream.v1
subprotocol and without it, so peers that offer none are still served. Only the half-close marker requires the negotiated
protocol: on those connections a text frame is an error (INVALID_ARGUMENT), and the client's closeOutbound() fails with UNIMPLEMENTED
("Peer does not support request half-close").
Cancellation. There is no in-band cancel message. A client cancels by closing or aborting the socket, and the server's handler coroutine is cancelled when the connection goes away.
Limits. Each frame is limited to 16 MiB (ProtobufLimits().maxMessageBytes) in both directions, and the JVM and
Android clients enforce the same limit on unary request and response bodies. The client also
buffers at most 64 unread inbound frames and 16 MiB of unread inbound data; overflowing either fails the call with
RESOURCE_EXHAUSTED. Node's ws client is configured with maxPayload: 16777216 and per-message deflate disabled.
The protocol is simple enough to implement anywhere protobuf and WebSockets are available:
KtBuf borrows gRPC's vocabulary (.proto services, the Codes numbering, the grpc-status header name and names
like GrpcService and GrpcRequestContext), but not its wire protocol.
Because of these differences:
None of these bridges ship with KtBuf today.
ktbuf-test (JVM) helps you test services end to end:
import com.latenighthack.ktbuf.test.server.runTestWithServer
@Test
fun unaryRoundTrip() = runTestWithServer({
routing { serveAll(ConformanceService(), ConformanceServer.Descriptor) }
}) { server, _ ->
val service = ConformanceServiceRpc(HttpRpcClient(server.serverUrl))
val reply = withContext(Dispatchers.Default) { service.unary(AllTypes(fInt32 = 21)) }
assertEquals(42, reply.fInt32)
}
ktbuf-patch describes edits as field paths and applies them directly to encoded bytes, without decoding the whole
message. This is useful for syncing small changes to large documents.
import com.latenighthack.ktbuf.patch.*
// Replace field 2 of the first occurrence of sub-message field 3.
val path = Path(listOf(Path.Component(fieldNumber = 3, index = 0), Path.Component(fieldNumber = 2, index = 0)))
val newValue = ProtobufOutputStream.encode { encode(42, 2) }
val patched: ByteArray = original.applyChanges(listOf(
Change.Replace(path, newValue, skipFieldNumbers = emptyList()),
Change.Remove(Path(listOf(Path.Component(5, )))),
))
EditContext and EditorList<T> record changes as you edit, and are the building blocks for typed editors. The
generator for typed editors has been retired. patch/src/commonTest/kotlin/com/latenighthack/ktbuf/patch/v1/ModelEditors.kt
shows a hand-written editor that allows:
val patch: Patch = original.edit { anInt = 42; inner { innerInner { anInt = 9000 } } }
val updated = RootMessage.fromByteArray(original.toByteArray().applyChanges(patch.changes))
Code generation needs the pinned protoc and protoc-gen-kt on PATH (see Code generation).
./gradlew jvmTest # all JVM tests
./gradlew :server:test # end-to-end HTTP/WebSocket tests against a real Ktor server
./gradlew :conformance:jvmTest # generated code vs. wire, deterministic and protovalidate goldens
./gradlew :validate:jvmTest # ktbuf-validate runtime
./gradlew :rpc:jsBrowserTest jsNodeTest # JavaScript
./gradlew linuxX64Test macosArm64Test iosSimulatorArm64Test
./gradlew :android-consumer:assembleDebug
The generator pin protocGenKt identifies the reviewed source revision (a full commit SHA, enforced by
scripts/test-validation-gates.py). Its commits and the runtime commits must both be available before running remote
validation; workspace overrides allow local paired verification before any push.
When the pinned revision is also a tagged protoc-gen-kt release, go install …@<sha> reports the tag (for example
v0.2.0) instead of a pseudo-version. Set protocGenKtTag to that tag so the generation task's version check accepts
it; tagged module versions are immutable through the Go module proxy and checksum database.
For paired generator development, build protoc-gen-kt in its separate checkout and pass
-PprotocGenKtPath=/absolute/path/protoc-gen-kt. Generation stages output before replacing previously successful
bindings.
# Compile and run the generator's regression consumers against this runtime, without Maven Local.
scripts/validate-generator.sh /absolute/path/protoc-gen-kt-checkout
# Check unchanged-input caching and invalidation after compiler, generator and imported-schema changes.
python3 scripts/test-codegen-inputs.py --plugin /absolute/path/protoc-gen-kt
Version and group are set in the root build.gradle.kts (com.latenighthack.ktbuf). Publishing
uses the com.vanniktech.maven.publish plugin against the Maven Central portal.
To try a build locally without signing keys, run ./gradlew publishToMavenLocal.
Apache License 2.0. See LICENSE.
| Artifact | Kind | Contents |
|---|
ktbuf-library | Kotlin Multiplatform | Wire codec (ProtobufReader / ProtobufWriter) with strict-decode and deterministic-encode options, byte buffers, Base64URL, RpcClient interfaces, the GrpcService stub base class, status codes, and google.rpc.Status / Any / ErrorInfo (com.latenighthack.ktbuf.wkt). |
ktbuf-rpc | Kotlin Multiplatform | HttpRpcClient (HTTP + WebSocket transport, status details, single-use stream tickets), PlatformHttpClient, retry/backoff helpers. |
ktbuf-patch | Kotlin Multiplatform | Field-path edits applied directly to encoded bytes. |
ktbuf-validate | Kotlin Multiplatform | Runtime for generated buf.validate code (Violation, ProtoValidationException, ValidationClock). Only needed when generating with validate=true; see Optional validation. |
ktbuf-server | JVM (JDK 17) | Ktor routing for generated services: serveAll, runServer, defaultServer. |
ktbuf-test | JVM | TestServer, runTestWithServer, StubRpcClient. |
macosArm64linuxX64| Platform | Unary calls / raw HTTP | Streaming calls |
|---|
| JVM | OkHttp (one shared process-wide OkHttpClient) | OkHttp WebSocket |
| Android | OkHttp (same as JVM) | OkHttp WebSocket |
| iOS / macOS | NSURLSession.sharedSession | NSURLSessionWebSocketTask, one session per call |
| JS (browser) | XMLHttpRequest | Browser WebSocket. Custom handshake headers are not possible and fail with UNIMPLEMENTED; use a connection ticket instead. Details of a rejected handshake are not readable. |
| JS (Node) | fetch + AbortController | npm ws |
| Linux | Fails with UNIMPLEMENTED | Fails with UNIMPLEMENTED |
| Parameter | Effect |
|---|
validate=true | Also writes foo.validate.kt from buf.validate rules. See Optional validation. |
wkt_helpers=true | Also writes timestamp.wkt.kt / duration.wkt.kt helpers. See Well-known types. |
| Gradle property | Purpose |
|---|
-PprotocPath=/abs/path/protoc | Use an explicit compiler instead of the pinned one on PATH. |
-PprotocGenKtPath=/abs/path/protoc-gen-kt | Use a locally built generator (paired generator development). |
-PprotoIncludeDirs=dirA:dirB | Extra -I include directories, separated by the platform path separator. |
-PprotoSourceDir=... / -PprotoOutputDir=... | Override the source and output directories. |
falsevalidate=trueprotobufWktHelpersfalsewkt_helpers=trueprotobufIncludeDirs-PprotoIncludeDirsgoogle/protobuf/timestamp.protoduration.protocom.google.protobufjava_packagegoogle/protobuf/timestamp.protogoogle/protobuf/duration.protoconformance/src/commonMain/proto/google/protobufprotocincludewkt_helpers=true--kt_opt=wkt_helpers=trueextra["protobufWktHelpers"] = truegradle/protobuf-codegen.gradle--kt_opt=validate=true,wkt_helpers=trueprotoc-gen-kt*.wkt.kttoEpochMillisofEpochMillisofEpochSecondsisValidtoInstanttoProtoTimestamptoKotlinDurationtoProtoDurationofMillisofSeconds*.wkt.ktkotlin.time.Instanttimestamp.wkt.ktproto3 syntax. Fields with explicit presence (optional) are not supported and are rejected with
unsupported presence semantics.option java_package sets the Kotlin package of the generated code.repeated fields (numeric fields are packed), map<K, V>, oneof
and services with all four call shapes.Foo.decodeStrict, Foo.parseFrom(bytes, options)) and deterministic encoding
(toDeterministicByteArray(), toByteArray(options)). See Encoding and parsing.fun Foo.validateInto(out, path)buf.validatecom.latenighthack.ktbuf:ktbuf-validateViolationProtoValidationExceptionValidationClocklt_nowgt_nowwithinbuf/validate/validate.protogoogle/protobuf/*.protoprotobufIncludeDirsgoogle.protobuf.DurationTimestamp:conformancefieldPathruleIditems[2].owner_idlabels["k"]string.min_lenconst len min_len max_len len_bytes min_bytes max_bytes pattern prefix suffix contains not_contains in not_inconst len min_len max_len prefix suffix contains in not_inconstconst defined_only in not_inconst lt lte gt gte in not_infiniteconst lt lte gt gtelt_now gt_now withinmin_items max_items unique itemsmin_pairs max_pairs keys valuesrequiredignorerequiredcelcel_expressiononeofany<file>: <message>.<field>: unsupported buf.validate rule <rule>pattern\b \s \p{..}(?m)$:conformancetools/protovalidate-goldenstrueString.compareToProtoKeyOrderoptional (explicit presence).| Feature | Kotlin representation and behavior |
|---|
| Scalars | Int, Long, UInt, ULong, Float, Double, Boolean, String, ByteArray. sint*, fixed* and sfixed* use the matching signed or unsigned Kotlin type. |
| Sub-messages | Nullable (AllTypes().fInner == null). A present but empty sub-message is still encoded. |
repeated | List<T>. Numeric fields are written packed; both packed and unpacked input is accepted. |
map<K, V> | Map<K, V>. If a key appears twice, the last value wins. A missing key or value decodes to its default. |
| Enums | A sealed class implementing com.latenighthack.ktbuf.proto.Enum. .value is the declared number, not the ordinal. |
oneof | A nullable sealed class, e.g. OneOfHolder.OneOfChoice. If several cases appear on the wire, the last one wins. |
| Unknown fields | Preserved in unknownFields and re-emitted when the message is encoded again. |
| Equality | Value equality, including ByteArray contents. |
import com.latenighthack.ktbuf.ProtobufInputStream
data class Inner(val str: String)
data class Outer(val id: Int, val name: String, val inner: Inner?)
fun readInner(reader: com.latenighthack.ktbuf.ProtobufReader): Inner {
var str = ""
while (reader.nextField()) {
when (reader.currentFieldNumber) {
1 -> str = reader.readString()
else -> reader.skipField()
}
}
return Inner(str)
}
val input = ProtobufInputStream()
input.addBytes(bytes)
val outer = input.read { reader ->
var id = 0; var name = ""; var inner: Inner? = null
while (reader.nextField()) {
when (reader.currentFieldNumber) {
1 -> id = reader.readInt32()
14 -> name = reader.readString()
17 -> inner = reader.readField(::readInner) // length-delimited sub-message
else -> reader.skipField() // returns the raw bytes, e.g. to keep unknown fields
}
}
Outer(id, name, inner)
}
currentWireTypeScopedProtobufReader(LinkedByteArray, ProtobufLimits)ProtobufInputStreamwss://host:porthttpwshttpswss?#import com.latenighthack.ktbuf.net.*
class AuthInterceptor(private val token: () -> String) : UnaryRpcInterceptor, StreamingRpcInterceptor {
override suspend fun intercept(
method: RpcMethodSpecifier,
headers: Map<String, String>,
requestData: ByteArray,
next: UnaryRpcCallback,
): RpcResponse = next(method, headers + ("Authorization" to "Bearer ${token()}"), requestData)
// Streaming headers go on the WebSocket handshake.
override suspend fun interceptOpen(
method: RpcMethodSpecifier,
headers: Map<String, String>,
next: suspend (RpcMethodSpecifier, Map<String, String>) -> Unit,
) = next(method, headers + ("Authorization" to "Bearer ${token()}"))
override suspend fun interceptSend(
method: RpcMethodSpecifier,
request: ByteArray,
next: suspend (RpcMethodSpecifier, ByteArray) -> Unit,
) = next(method, request)
override suspend fun interceptReceive(
method: RpcMethodSpecifier,
next: suspend (RpcMethodSpecifier) -> ByteArray,
): ByteArray = next(method)
}
val service = ConformanceServiceRpc(
InterceptingRpcClient(HttpRpcClient("https://api.example.com"), listOf(AuthInterceptor { currentToken }))
)
| Code | Value | Retriable | Code | Value | Retriable |
|---|
OK | 0 | FAILED_PRECONDITION | 9 | |||
CANCELLED | 1 | ABORTED | 10 | ✓ | ||
UNKNOWN | 2 | ✓ | OUT_OF_RANGE | 11 | ||
INVALID_ARGUMENT | 3 | UNIMPLEMENTED | 12 | |||
DEADLINE_EXCEEDED | 4 | ✓ | INTERNAL | 13 | ✓ | |
NOT_FOUND | 5 | UNAVAILABLE | 14 | ✓ | ||
ALREADY_EXISTS | 6 | DATA_LOSS | 15 | |||
PERMISSION_DENIED | 7 | UNAUTHENTICATED | 16 | |||
RESOURCE_EXHAUSTED | 8 | ✓ | CLIENT_TIMEOUT | 100 | ✓ |
google.rpc.ErrorInfojava.io.IOExceptionRpcResponseExceptionUNAVAILABLE.NSURLErrorDomain errors: a cancelled request becomes CANCELLED, a timeout becomes
CLIENT_TIMEOUT, and anything else becomes UNAVAILABLE.DATA_LOSS.interface RpcClient {
suspend fun unaryCall(method: RpcMethodSpecifier, headers: Map<String, String>, request: ByteArray): RpcResponse
suspend fun serverStreamingCall(method: RpcMethodSpecifier, block: suspend RpcServerStream.() -> Unit, readyCallback: () -> Unit)
suspend fun serverStreamingCall(method: RpcMethodSpecifier, headers: Map<String, String>, block: suspend RpcServerStream.() -> Unit, readyCallback: () -> Unit)
}
interface RpcServerStream {
suspend fun receive(): ByteArray // throw ClosedReceiveChannelException at a clean end of stream
suspend fun send(bytes: ByteArray)
suspend fun closeOutbound() // request half-close
suspend fun closeInbound()
}
import com.latenighthack.ktbuf.conformance.v1.AllTypes
import com.latenighthack.ktbuf.conformance.v1.ConformanceServer
import com.latenighthack.ktbuf.net.GrpcRequestContext
import com.latenighthack.ktbuf.net.RpcResponseException
import com.latenighthack.ktbuf.net.StreamControlEvent
import com.latenighthack.ktbuf.proto.Codes
import kotlinx.coroutines.flow.*
class ConformanceService : ConformanceServer {
override suspend fun unary(context: GrpcRequestContext, request: AllTypes): AllTypes {
if (request.fInt32 < 0) {
throw RpcResponseException(context.originalUrl, "POST", Codes.INVALID_ARGUMENT, "fInt32 must be >= 0")
}
return request.copy(fInt32 = request.fInt32 * 2)
}
override fun serverStream(context: GrpcRequestContext, request: AllTypes): Flow<StreamControlEvent<AllTypes>> =
flow { for (i in 1..3) emit(AllTypes(fInt32 = request.fInt32 + i)) }
.map { StreamControlEvent.Message(it) }
override suspend fun clientStream(context: GrpcRequestContext, request: Flow<AllTypes>): AllTypes =
AllTypes(fInt32 = request.toList().sumOf { it.fInt32 })
override fun bidi(context: GrpcRequestContext, request: Flow<AllTypes>): Flow<StreamControlEvent<AllTypes>> =
request.map { StreamControlEvent.Message(AllTypes(fInt32 = it.fInt32 * 10)) }
}
4016UNAUTHENTICATED401RpcResponseException.coderejectStreamingHandshakes = trueserveAllserveStreamingOutserveStreamingInOut| Handler outcome | Unary (HTTP) response | Streaming (WebSocket) close |
|---|
| Returns normally | 200, grpc-status: 0, raw protobuf body | 1000 (normal) |
Throws RpcResponseException(code = C) | HTTP status C.toHttpCode(), header grpc-status: C.value, body = error message | close code 4000 + C.value, reason = message (≤ 123 bytes) |
Request exceeds ProtobufLimits | 429, grpc-status: 8 | 4008 |
| Response exceeds the same limits when encoded | 400, grpc-status: 11 (OUT_OF_RANGE) | 4011 |
| Malformed protobuf request | 400, grpc-status: 3 | 4003 |
| Any other exception (logged) | 500, grpc-status: 13, body Internal server error | 4013 |
| Unary | Server streaming | Client streaming | Bidi streaming |
|---|
| Transport | HTTP/1.1 POST | WebSocket | WebSocket | WebSocket |
| Requests | 1 (request body) | 1 binary frame | N binary frames + end marker | N binary frames + end marker |
| Responses | 1 (response body) | N binary frames | 1 binary frame | N binary frames |
| Status | HTTP status + grpc-status (+ grpc-status-details-bin) | close code (+ status marker frame) | close code (+ status marker frame) | close code (+ status marker frame) |
DATA_LOSSgrpc-status2xx| HTTP | Code | HTTP | Code |
|---|
| 400 | INVALID_ARGUMENT (or FAILED_PRECONDITION / OUT_OF_RANGE if the message contains failedprecondition / outofrange) | 499 | CANCELLED |
| 401 | UNAUTHENTICATED | 500 | INTERNAL if the message contains internal, DATA_LOSS if it contains dataloss, otherwise UNKNOWN |
| 403 | PERMISSION_DENIED | 501 | UNIMPLEMENTED |
| 404 | NOT_FOUND | 503 | UNAVAILABLE |
| 408 | CLIENT_TIMEOUT | 504 | DEADLINE_EXCEEDED |
| 409 | ALREADY_EXISTS if the message contains alreadyexists, otherwise ABORTED | 429 | RESOURCE_EXHAUSTED |
| other | UNKNOWN |
google.rpc.ErrorInfogrpc-status-details-binRpcResponseException(..., status = RpcStatus(...))RpcResponseException.statuserrorInfoErrorInfostatus.codeAccess-Control-Expose-Headers: grpc-status, grpc-status-details-binktbuf.status-details.v1Sec-WebSocket-Protocol: ktbuf.stream.v1, ktbuf.status-details.v1ktbuf.stream.v1ktbuf.stream.v1ktbuf.status:<base64 Status>MAX_STATUS_MARKER_BYTESINVALID_ARGUMENTUNAVAILABLEUNAUTHENTICATEDRpcResponseExceptionINTERNAL| Direction | Frame | Meaning |
|---|
| client → server | Binary | One encoded request message. |
| client → server | Text ktbuf.requests.end | Request half-close: no more requests will follow. Only valid if ktbuf.stream.v1 was negotiated. |
| server → client | Binary | One encoded response message. |
| server → client | Text ktbuf.status:… | Optional status marker, at most once, directly before an error Close (see above). |
| server → client | Other text | Protocol error. The client fails the call with INVALID_ARGUMENT. |
| either | Close | End of the call. The close code carries the status. |
| Close code | Meaning |
|---|
1000 | OK. The response flow completes normally. |
1001 | UNAVAILABLE (going away). |
1009 | OUT_OF_RANGE (message too big). |
4000 + n | Error with Codes value n, e.g. 4005 = NOT_FOUND, 4013 = INTERNAL, 4016 = UNAUTHENTICATED. The close reason is the error message, truncated to 123 UTF-8 bytes. |
anything else, including an abnormal 1006 | UNKNOWN. |
POST the bytes to /api/{package}.{Service}/{Method}. Treat 2xx as success with a protobuf body;
otherwise read grpc-status and the text body, and optionally grpc-status-details-bin (base64 google.rpc.Status).ktbuf.stream.v1 (servers must select it), and
also ktbuf.status-details.v1 if you can read status markers. Send each request as one binary frame, send the text
frame ktbuf.requests.end when you are done sending, read binary frames until the socket closes, then map the close
code (1000 = OK, 4000 + n = error n). A single ktbuf.status:<base64 Status> text frame may precede an error
close if you offered ktbuf.status-details.v1.| gRPC | KtBuf |
|---|
| HTTP version | HTTP/2 required | HTTP/1.1 (or anything that can carry a POST and a WebSocket) |
| Content type | application/grpc[+proto] | application/proto |
| Message framing | 5-byte prefix (compressed flag + length) | None: the body or WebSocket frame is the message |
| Status | grpc-status / grpc-message / grpc-status-details-bin in HTTP/2 trailers | grpc-status and grpc-status-details-bin headers plus HTTP status (unary); WebSocket close code plus optional status marker frame (streaming) |
| Streaming | HTTP/2 streams | One WebSocket per call |
| Deadlines | grpc-timeout header | None on the wire; client-side coroutine timeouts |
| Metadata | Headers and trailers | Request headers (or the handshake); unary response headers |
| Browser support | Needs gRPC-Web plus a proxy | Native fetch/XHR and WebSocket |
| Compression | Per-message | None |
.proto file can drive a grpc-java or grpc-go server and KtBuf clients,
and message bytes are interchangeable, since KtBuf's encoding matches the reference implementation (golden tests
check this).POST /api/{pkg}.{Svc}/{Method} to a gRPC call (adding the 5-byte
framing and turning trailers into grpc-status plus an HTTP status), and WebSocket streams to gRPC streams.RpcClient (Custom transports) that speaks gRPC or gRPC-Web on platforms
with an HTTP/2 client. Generated stubs work unchanged on top of it.ktbuf-server side by side.TestServer(requestedPort = 0) binds a port chosen by the OS, so parallel tests never collide. Use start { ... },
serverUrl, port and stop().runTestWithServer wraps runTest and always stops the server. Real network I/O should run on a real dispatcher
(Dispatchers.Default), because runTest uses virtual time.StubRpcClient with UnaryHandler, TypedUnaryHandler and MatchingTypedUnaryHandler stubs unary calls without a
server.RpcClient directly, as FakeRpcClient does in the
conformance module.| Change | Effect |
|---|
Insert(path, message) | Insert an encoded value at the path. |
Require(path) | Create an empty sub-message at the path if it is missing. |
Replace(path, message, skipFieldNumbers) | Replace the value at the path, keeping the listed field numbers from the existing value. |
Remove(path) / RemoveAll(path) | Remove one occurrence / every occurrence. |
InsertDistinct / RemoveDistinct | Insert or remove a value unless or if it is already present. Match selectors must be null. |
| Path | Purpose |
|---|
library/ | Wire codec and RPC interfaces (published). |
rpc/ | Platform transports and backoff (published). |
patch/ | Byte-level patching (published). |
validate/ | Runtime for generated buf.validate code, ktbuf-validate (published). |
server/ | Ktor server (published). |
test/ | Test helpers (published). |
conformance/ | Unpublished. Generated code from the conformance, deterministic, validation and well-known-type protos, checked against Python and Go goldens on every target. |
android-consumer/ | Unpublished Android app that checks the published API compiles and packages at minSdk 24. |
tools/ | Python scripts that regenerate the golden byte fixtures using the reference protobuf runtime (see tools/README.md). |
tools/go-goldens/ | Go module that generates the deterministic-encoding and google.rpc.Status goldens with Go's protobuf. |
tools/protovalidate-goldens/ | Go module that generates the buf.validate goldens with Go protovalidate. |
scripts/ | Validation scripts used by CI. |
review/ | Dated correctness and security review reports (historical). |
version in build.gradle.kts, update the dependency snippets in this README, and merge to main. If the
generator pin changed, push the protoc-gen-kt commit (and tag it) first, and update protocGenKtTag if tagged. The Runtime and generated consumers workflow
(.github/workflows/gradle.yml) runs on every push and pull request. It:
scripts/test-validation-gates.py);scripts/validate-generator.sh) and the code-generation cache regression.v<version> (e.g. v1.2.0). .github/workflows/release.yml:
ktbuf-library, ktbuf-validate, ktbuf-rpc, ktbuf-patch, ktbuf-server and ktbuf-test with
publishToMavenCentral. Artifacts are signed and released automatically using the MAVEN_CENTRAL_* and
SIGNING_* repository secrets.Surfaced from shared tags and platforms — no rankings paid for.