Kotlin

Kotlin の生成物は、data class と sealed interface で書かれます。ランタイムは 2 つで、型・検証・cookie・エンドポイントは Java の comatype(packages/java)、コルーチン(suspend)で書ける c / s は Kotlin の comatype.ktx(packages/kotlin)です。どちらも標準ライブラリだけで書いてあり、kotlinx.coroutines は要りません。JDK 21 以上と kotlinc が必要です。

生成されるもの#

<out>/                       既定は src/main/kotlin/comatype/gen(パッケージ名は out から決める。target の package で指定もできる)
├─ Types.kt                  名前付きの型(data class・enum class)
├─ Init.kt                   ラッパー・ctx・ラッパーのステータス
└─ UserPutId.kt              エンドポイントごと(object 名は PascalCase の連結名)

クライアント#

user_put_id.kt
import comatype.ktx.CK
import comatype.gen.Types
import comatype.gen.UserPutId

suspend fun putUser(id: java.util.UUID, user: Types.UserData) {
    // Request has params / headers / body, typed from the params block of put__id.comat
    val res = CK.put(UserPutId.ENDPOINT, UserPutId.Request(params = UserPutId.Params(id), body = user))

    when (res) {
        is UserPutId.S200 -> res.body // UserData (res.headers is S200Headers)
        is UserPutId.S404 -> res.body // ApiError
        else -> {}
    }
}
  • 引数は、params / search / ヘッダがあれば Request、body だけならボディそのもの、無ければ comatype.NoArg.INSTANCE。任意のプロパティには既定値(null)があるので、Request(params = ...) のように名前付き引数で書けます。
  • 戻り値は Response(sealed interface)。when で絞り込めます。
  • .comat に無いステータスは ComatypeException.UnexpectedStatus、検証エラーは ValidationException。
  • CK.get / CK.put ... は suspend 関数です。通信は HttpClient.sendAsync(スレッドをブロックしません)。ラッパーも suspend の関数(CWrap)です。
init.kt
// Client init file: pass the implemented ComatypeWrap
// The base url defaults to baseUrl in init.comat. Override with the COMATYPE_BASE_URL environment variable or Config.baseUrl
// Call initComatype() once at startup (whether a wrapper is on or off is decided by defaults.comat and `wrap` in each .comat)
import comatype.CookieJar
import comatype.gen.Init
import comatype.ktx.CK

fun initComatype() {
    CK.init(
        CK.Config(
            // With the generated types, a missing wrapper declared in init.comat, or a wrong type, is a compile error
            wrappers = Init.Wrappers(auth),
            // Used by `cookie on` endpoints. The cookie jar keeps the httpOnly cookie
            cookieJar = CookieJar(),
        )
    )
}
wrappers/auth.kt
// Implement a wrapper as a suspend function value (CWrap) (corresponds to the `wrapper auth` of init.comat)
import comatype.ktx.CWrap

val auth: CWrap = { req, next ->
    req.headers.set("Authorization", "Bearer " + System.getenv("API_TOKEN"))
    next(req)
}

サーバ#

user_put_id.kt
import comatype.S
import comatype.gen.Types
import comatype.gen.UserPutId
import comatype.ktx.coPut

fun S.userPutId() {
    // The handler is a suspend function. The returned Reply is used to add a cookie (S.Reply.of(res).withCookie(...))
    coPut(UserPutId.ENDPOINT) { req ->
        // req.params.id: UUID, req.body: UserData, req.ctx.auth.user (wrap auth is on)
        val user = db.user.update(req.params.id, req.body) // the app's own storage
            ?: return@coPut S.Reply.of<UserPutId.Response>(UserPutId.S404(Types.ApiError("not_found", "user not found")))
        // headerRes (X-Resource-Version) of user/defaults.comat
        S.Reply.of<UserPutId.Response>(UserPutId.S200(user, UserPutId.S200Headers(xResourceVersion = "v2")))
    }
}
  • comatype.S に、s.coGet / s.coPut ... で suspend のハンドラを登録します(同期のハンドラは s.get / s.put)。cookie on のエンドポイントのハンドラは S.Reply<Response> を返します。
  • s.serve("127.0.0.1", 3000) は JDK のサーバ、s.handle(...) は任意のフレームワーク用の入口です。リクエストごとのスレッドで、ハンドラの完了を待ちます。
init.kt
// Server init file: pass the implemented ComatypeWrap
// The cookie settings (name, httpOnly, etc.) are in init.comat
import comatype.S
import comatype.gen.Init
import comatype.ktx.init

fun initComatype(s: S) {
    // With the generated types, a missing wrapper declared in init.comat, or a wrong type, is a compile error
    s.init(Init.Wrappers(auth))
}
wrappers/auth.kt
// Implement a wrapper as a suspend function (SWrap<AuthCtx>) value (corresponds to the `wrapper auth` of init.comat)
import comatype.gen.Init
import comatype.gen.Types
import comatype.ktx.SWrap

val auth: SWrap<Init.AuthCtx> = { req, next ->
    val user = verifySession(req.cookie("session")) // the app's own logic
    if (user == null) {
        Init.s401(Types.ApiError("unauthorized", "login required"))
    } else {
        // On endpoints with `wrap auth` on, a handler can read req.ctx.auth.user, typed
        next(req.withCtx(Init.AuthCtx(user)))
    }
}

型の対応#

型の対応は Java と同じです(UUID LocalDate Instant BigDecimal URI ByteArray、int と int64 は Long)。省略可能と T | null は T? です。

ビルド#

shell
javac -d rt $(find packages/java/src/main -name '*.java')
kotlinc -cp rt -include-runtime -d app.jar <out> packages/kotlin/src/main/kotlin src/...
java -cp app.jar:rt MainKt