Kotlin#
The Kotlin generator emits a client: serializable types for the model’s
structs, enums and unions, and a Client whose suspend methods call the
routes and REST resources the Go output serves. Nothing is
generated for serving HTTP. Enable it with a [tool.model.kotlin] table:
[tool.model.kotlin]
out = "src/main/kotlin/com/example/catalog/Catalog.kt"
package = "com.example.catalog"
out is one .kt file holding every type of the model, declared in
package.
The types are what a response holds, as TypeScript’s are (see
perms): a field whose read is false is left out,
and one whose read names a perm is nullable, whatever its required says,
since a response to a request without the perm leaves it out.
Dependencies#
Generated code is built on
kotlinx.serialization for
JSON, kotlinx-datetime for
dates and times, and the Ktor client
for HTTP, and imports this library’s runtime, dev.omniblack.model:model-runtime
(package dev.omniblack.model.runtime). The runtime declares the others as
api dependencies, so a build that depends on it gets them too. It needs
Kotlin 2.4 and its serialization plugin:
plugins {
kotlin("jvm") version "2.4.21"
kotlin("plugin.serialization") version "2.4.21"
}
kotlin {
compilerOptions {
optIn.addAll("kotlin.uuid.ExperimentalUuidApi", "kotlin.time.ExperimentalTime")
}
}
dependencies {
implementation("dev.omniblack.model:model-runtime:0.1.0")
implementation("io.ktor:ktor-client-cio:3.6.1") // or another Ktor engine
}
The opt-ins are for the Uuid a uuid field holds and the Instant a
datetime holds; the generated file opts in to kotlinx.serialization’s
experimental API itself. The runtime is a Kotlin Multiplatform module, but
only its JVM target is built so far.
The runtime ships with model rather than on a registry. The flake builds it
as packages.<system>.kotlin-runtime, a Maven repository directory, so the
runtime always matches the generator that wrote the code. The flake’s
wrk module, wrkModules.default, points
the MODEL_KOTLIN_RUNTIME environment variable at it:
wrk = {
imports = [model.wrkModules.default];
model.kotlin.enable = true;
};
For plain nix develop, render the same environment as a dev shell with
(work.lib.evalWrk { inherit pkgs; modules = [self.wrk]; }).devShell.
and read it as a repository in settings.gradle.kts:
dependencyResolutionManagement {
repositories {
maven { url = uri(System.getenv("MODEL_KOTLIN_RUNTIME")) }
mavenCentral()
}
}
Types#
Field type |
Kotlin |
|---|---|
|
|
|
runtime |
|
|
|
|
|
|
|
runtime |
|
|
|
runtime |
|
|
|
|
|
the target’s |
|
the struct, enum or union |
|
|
|
runtime |
|
its |
A struct is a @Serializable data class, with a property per field in
camelCase, each @SerialNamed with the field’s own name:
@Serializable
data class Product(
@SerialName("sku") val sku: @Serializable(with = StringNotBlank::class) String,
@SerialName("price") val price: @Serializable(with = DecimalNotBlank::class) Decimal,
@SerialName("tags") val tags: List<String> = emptyList(),
) {
fun validate(path: DataPath = DataPath.root): List<FieldError> { /* ... */ }
}
An optional field is T? = null, a list or map defaults to empty, and a
constant field holds its value by default and always writes it.
An enum is an enum class. A string enum’s members are @SerialNamed with
their values; an integer enum carries its value as value, and a generated
<Enum>Serializer writes it.
A union is a sealed interface with a data class per variant, read and
written by a generated <Union>Serializer that picks the variant by its tag.
Each variant carries its tag as a property that is always written.
A reference is a @JvmInline value class <Target>Ref(val key: K), written as
the bare key. One is declared for every struct a reference could name,
whether this model refers to it or not, so another model can
refer into this one.
Decode with kotlinx.serialization and the runtime’s WireJson, which ignores
keys the types do not have and leaves out nulls:
val product = WireJson.decodeFromString(Product.serializer(), text)
Blank strings#
A blank string, "", is a missing value, in every language. Every scalar
field is read through a file-private serializer that applies this on decode: a
required field holding "" fails as a missing one does, with
MissingFieldException at its path, and an optional one reads as null.
Validating#
Every struct and union has validate(path), which returns every constraint
violation as a FieldError(kind, path, message) rather than throwing:
val errors = product.validate()
for (error in errors) {
println("${error.path}: ${error.message}")
}
The paths and messages are the Go output’s: a dotted data path from $, a
list item by its index, a map entry by its quoted key, so
$.tags.0 or $.prices.'eur'. kind is one of length, range,
version, content_type, constant and required. A reference is never
checked against the rows it names: only the server can.
The client#
Client is generated when the model has a route, a root endpoint, or with
[tool.model.go.rest] a REST resource. It takes the
server’s base URL, whose path prefixes every endpoint’s, and a Ktor
HttpClient. It does its own JSON, so the HttpClient needs no content
negotiation plugin:
val api = Client("https://catalog.example", HttpClient(CIO))
Every method takes a trailing configure: HttpRequestBuilder.() -> Unit,
run on the request before it is sent, for headers, cookies or a timeout:
api.product.read(id) { bearerAuth(token) }
A response the client cannot read, such as a body that is not the
declared type, is an HttpError(status, body).
Routes#
Each route is a suspend fun named for the route in camelCase. Its
request’s fields fill the route’s path placeholders; a route with a body
sends the request as JSON, and one without sends the other fields in the
query string:
when (val resp = api.getProduct(ProductKey(sku = "ABC-1"))) {
is RouteResp.Success -> show(resp.value)
is RouteResp.Failure -> report(resp.error, resp.status)
}
RouteResp<S, E> is the decoded success body, or the route’s declared
error, each with the response’s status; a route without a success body
answers Unit. A merge-patch route takes a generated <Request>Patch; see
below.
REST resources#
The Client has a <Name>Resource for each served struct, as a property
named for the struct in camelCase (api.product). Its methods are those of
the Go client:
Method |
Request |
|---|---|
|
|
|
|
|
search the collection, with the search index or the query language |
|
|
|
|
|
merge-patch a row |
|
|
|
the row’s listing item |
|
the rows referring to it, and every row related to it |
|
the row’s URL, without a request |
|
a file under one of the row’s rooted paths |
|
a |
|
A resource has the methods its struct is served with: query needs a search
index, find the find feature, referencedBy a reference to the struct,
and related a reference to or from it. The keys are id, or the struct’s
key fields in camelCase. An upload’s body is a Ktor OutgoingContent, sent as
it is rather than as multipart, so it can be streamed. Each answers a
RestResp<T>: Success(value, etag) or Failure(problem), a refusal’s RFC
9457 Problem, with the field errors it was refused for:
when (val resp = api.product.read(42)) {
is RestResp.Success -> {
val product = resp.value
api.product.replace(42, product.copy(name = "New"), WriteOptions(etag = resp.etag))
}
is RestResp.Failure -> println(resp.problem.title)
}
Passing the etag back in WriteOptions makes the write fail with a 412
problem if the row changed since it was read.
A listing answers a Page<ListItem<<Name>Summary>>: its items, and the
next and prev tokens, which PageOptions(page = ...) passes back. A
listing that can hold several structs’ rows — referencedBy, related and
the Client’s own search(text) — holds a sealed interface of
<Name>TypedItems, one per struct, so a when picks each row’s type.
Patches#
A merge-patch route, and a resource’s patch, take a generated
<Name>Patch: one runtime Patch<T> per field, each Patch.Absent unless
set. Absent leaves the field as it is, Patch.Null clears it, and
Patch.Value(v) replaces it; Patch.of(v) is Null for null and Value
otherwise. T? could not tell leaving a field alone from clearing it.
api.product.patch(42, ProductPatch(name = Patch.Value("New"), note = Patch.Null))
Following a row’s URLs#
The server sends each row’s URLs — its own, its summary, its related and
referencedBy listings, its files — and the client keeps them, as
<Name>Urls, on a row it read (row.urls) and on a listing item
(item.urls). Every method of one row has an overload taking the urls in
place of the keys, and calls the URL the server sent:
val row = (api.product.read(42) as RestResp.Success).value
val related = api.product.related(row.urls!!)
val self = api.get(row.urls!!.self)
urls is null on a value built rather than read, on a copy(), and on a
listing item whose row the request may not read.
Root endpoints#
A root endpoint is a RootFiles property
on the Client. list(path) answers its directory’s DirEntrys, url(path)
gives a file’s URL, and fetch(path) { response -> ... } reads a file,
streaming it inside the block:
api.bookFiles.fetch("covers/42.jpg") { it.bodyAsChannel().copyTo(out) }
Limitations#
Only the JVM target is built.