360 Secure SkillHub
360 安全技能中心

kmp-api-contracts

面向 Kotlin Multiplatform 客户端,说明未知枚举、缺失字段、请求编码等 kotlinx.serialization 问题,并给出 OpenAPI Generator 的配置、清理与漂移检查建议;包含代码片段和检查清单,但存在相互冲突的操作约束及删除输出目录的破坏性建议。

分类:开发
filippkowalski
热度 0.00
最近更新 2026-11-14 11:38:49

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add filippkowalski/kmp-skills-by-filip/kmp-api-contracts
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
kmp-api-contracts
description
Use when a Kotlin Multiplatform client decodes or sends JSON with kotlinx.serialization DTOs, hand-written or generated by OpenAPI Generator (generatorName=kotlin, library=multiplatform). Triggers on a decode that fails on a new or unknown enum value, MissingFieldException, optional vs null vs default fields, encodeDefaults, explicitNulls, coerceInputValues, openApiGenerate, enumUnknownDefaultCase, serializationLibrary, duplicate @Serializable, anyOf union models, and a drift check for checked-in generated DTOs.

API contracts with kotlinx.serialization in a KMP client

Rules 1-3 apply to any @Serializable DTOs, hand-written or generated. Rules 4-8 apply only if you generate DTOs with OpenAPI Generator (kotlin, library=multiplatform).

1. An unknown enum value fails the whole decode

Symptom: the server adds one enum value (a status, a kind, a plan). Installed builds fail to load the screen. A list response fails for every item, not only the item with the new value.

Cause: kotlinx decodes an enum by @SerialName and throws SerializationException on a value it does not know. The exception aborts the whole object tree. coerceInputValues = true replaces an unknown value only on a property that has a default, or with null on a nullable property when explicitNulls = false. A non-null enum property without a default still throws.

Fix: pick one per field.

  • Send a growable response field as a string (in an OpenAPI spec: type: string, not enum) and map it in one total when with an else that degrades and logs:
    internal fun String.toPlan(): Plan = when (this) {
        "monthly" -> Plan.Monthly; "annual" -> Plan.Annual
        else -> { log.d("wire", "unknown plan: $this"); Plan.Free }
    }
    
  • In a hand-written DTO, keep the enum and give it a serializer with an unknown fallback:
    @Serializable(with = StatusSerializer::class)
    enum class Status { Active, Paused, Unknown } // response-only: never send Unknown
    object StatusSerializer : KSerializer<Status> {
        override val descriptor = PrimitiveSerialDescriptor("Status", PrimitiveKind.STRING)
        override fun deserialize(decoder: Decoder) = when (decoder.decodeString()) {
            "active" -> Status.Active; "paused" -> Status.Paused; else -> Status.Unknown
        }
        override fun serialize(encoder: Encoder, value: Status) = encoder.encodeString(value.name.lowercase())
    }
    
  • Or set coerceInputValues = true and give the property a default (val status: Status = Status.Unknown), or make it nullable with explicitNulls = false.

Choose the fallback so a wrong guess fails safe for that field: access and trust fail closed (an unknown plan reads as free), blocking UI fails open (an unknown "update required" reads as "no update"). Request bodies keep strict enums. Do not patch values in a JSON pre-pass. The compiler cannot see a missing when branch over a String: test each value and one unknown via the real decode.

Seen on: kotlinx-serialization-json 1.7.3, Kotlin 2.4.10.

2. A property without a default must be present, even when it is nullable

Symptom: a response fails with MissingFieldException after the server stops sending a key, or an optional flag reads as false when the server said nothing.

Cause: with the default explicitNulls = true, kotlinx requires every property that has no default. String? only allows null; the key must still be there. ignoreUnknownKeys covers extra keys, never a missing one. With explicitNulls = false, a missing nullable key reads as null.

Fix:

  • While old builds are installed, never remove a required response field or make it optional. Keep sending it (as null if nullable). Add a required field only if the server always sends it.
  • Carry an optional flag as Boolean?; absent is a third answer. Pick the fail-safe direction per field (rule 1): a flag that grants access or trust (isVerified) counts only when == true; a flag that blocks or deletes acts only when explicitly set. Never write ?: false by reflex.
  • Data you persist with kotlinx follows the same rule: a property added later needs a default.
  • OpenAPI Generator maps the three schema forms like this:
Schema property Generated Kotlin
in required, nullable: true @Required val x: String? (key must be present)
not in required val x: String? = null
not in required, default: 0 val x: Double? = (0).toDouble()

Seen on: kotlinx-serialization-json 1.7.3, OpenAPI Generator 7.10.0, OpenAPI 3.0.3.

3. kotlinx request encoding does not match "optional" on the server

Symptom: a value the user set never reaches the server, though the request object looks right. Or requests fail with 400 on fields the client "did not send".

Cause: optional request properties carry a default, so a call site that stops passing one still compiles. encodeDefaults = false (the default) drops every property equal to its default. encodeDefaults = true with explicitNulls = true writes "field": null, which a server that allows a missing key but not null rejects.

Fix:

  • Test the bytes, not the object. Encode through Ktor MockEngine and assert on the JSON:
    var body: JsonObject? = null
    val engine = MockEngine { req ->
        body = Json.parseToJsonElement((req.body as TextContent).text).jsonObject
        respond("{}", HttpStatusCode.OK, headersOf(HttpHeaders.ContentType, "application/json"))
    }
    client(engine).sync(items); assertTrue(body!!.containsKey("lastSyncedAt"))
    
  • Accept null for optional request fields on the server, or keep encodeDefaults off for requests, or set explicitNulls = false on the request Json.
  • Map domain enums to request enums with an exhaustive when and no else, so new values fail the build.

Seen on: kotlinx-serialization-json 1.7.3, Ktor 3.0.3 and 3.1.0, Kotlin 2.1.21 and 2.4.10.

4. OpenAPI Generator: enumUnknownDefaultCase does not rescue multiplatform enums

Symptom: you set enumUnknownDefaultCase=true, regenerate, and an unknown value still throws.

Cause: in the 7.10.0 data_class.mustache, the @Serializable(with = XSerializer::class) form that maps unknown values to the fallback case is emitted only in the non-multiplatform branch. Multiplatform enums keep a plain @Serializable, and kotlinx still matches by @SerialName.

Fix: do not rely on the option. Use type: string in the spec and a total when (rule 1).

Seen on: OpenAPI Generator 7.10.0.

5. OpenAPI Generator: an anyOf union with required branch fields generates one class that decodes no branch

Symptom: a union response fails every real body with MissingFieldException or an enum error.

Cause: 7.10.0 flattens the branches into one data class. A field any branch lists in required becomes required; other fields stay optional. The discriminator enum keeps only one branch's value. So anyOf: [{ok}, {ignored}], each branch requiring its own field, requires both ok and ignored, and no real body decodes.

Fix: for responses the client decodes, publish one flat object: shared properties required, branch properties optional, the discriminator type: string. If the union must stay, decode it with a hand-written flat DTO whose branch fields have defaults.

Seen on: OpenAPI Generator 7.10.0, OpenAPI 3.0.3.

6. OpenAPI Generator does not clean its output by default

Symptom: models for removed schemas stay. A drift check keeps failing after you regenerate.

Cause: by default the generator only writes files, so output from an earlier spec stays. cleanupOutput.set(true) (off by default) deletes the entire output directory before it generates.

Fix: use cleanupOutput only on an output directory that holds nothing else. Otherwise wipe only the Kotlin source root in doFirst, not the folder that holds your README and .openapi-generator-ignore (list both files in the ignore file).

val apiKotlin = layout.projectDirectory.dir("openapi/src/commonMain/kotlin")
tasks.named<GenerateTask>("openApiGenerate") {
    doFirst { apiKotlin.asFile.deleteRecursively() }; configureModelGen(layout.projectDirectory.dir("openapi"))
}

Seen on: OpenAPI Generator 7.10.0 (cleanupOutput read from the Gradle plugin jar).

7. OpenAPI Generator: serializationLibrary duplicates @Serializable

Symptom: generated models do not compile after you set serializationLibrary.

Cause: library=multiplatform already emits @Serializable. The 7.10.0 template adds a second one when serializationLibrary=kotlinx_serialization is also set.

Fix: leave serializationLibrary unset. Related config for the same library:

fun GenerateTask.configureModelGen(outDir: Directory) {
    generatorName.set("kotlin"); library.set("multiplatform")
    inputSpec.set(specFile.absolutePath); outputDir.set(outDir.asFile.absolutePath)
    packageName.set("com.example.api.generated"); modelPackage.set("com.example.api.generated")
    globalProperties.set(mapOf("models" to "", "modelDocs" to "false")) // models only
    typeMappings.set(mapOf("kotlin.Any" to "kotlinx.serialization.json.JsonElement"))
    configOptions.set(mapOf("dateLibrary" to "string", "enumPropertyNaming" to "original"))
}
  • typeMappings maps additionalProperties: {} (Map<String, kotlin.Any>, which kotlinx cannot serialize) to JsonElement. dateLibrary=string keeps date-time fields as String: parse them in your mappers, and a major bump of your date library changes no generated file.

Seen on: OpenAPI Generator 7.10.0, kotlinx-datetime 0.6.1 and 0.7.1.

8. OpenAPI Generator: checked-in DTOs drift unless a check regenerates and compares

Symptom: the spec changed and the checked-in models did not, or a drift check fails on whitespace.

Cause: nothing forces openApiGenerate to run after a spec change. The generator also emits trailing KDoc spaces and end-of-file blank lines inconsistently, so a byte compare is flaky.

Fix: regenerate into its own build dir (cleanupOutput, rule 6), compare text with trailing whitespace removed, and run it before merge and deploy. Server-generated specs need it too.

val verifyDir = layout.buildDirectory.dir("openapi-verify")
val generateApiModelsCheck by tasks.registering(GenerateTask::class) { cleanupOutput.set(true); configureModelGen(verifyDir.get()) }
val verifyApiModels by tasks.registering {
    dependsOn(generateApiModelsCheck)
    doLast {
        fun snap(root: File) = root.walkTopDown().filter { it.isFile && it.extension == "kt" }
            .associate { f -> f.relativeTo(root).path to f.readLines().joinToString("\n") { it.trimEnd() }.trimEnd() }
        val a = snap(apiKotlin.asFile); val b = snap(verifyDir.get().asFile.resolve("src/commonMain/kotlin"))
        if (a != b) throw GradleException("Stale DTOs: " + (a.keys + b.keys).filter { a[it] != b[it] }.sorted())
    }
}

Seen on: OpenAPI Generator 7.10.0, Gradle 8.11 and 8.14.

Checklist

  • Growable response enums arrive as strings or have an unknown fallback; tested with a new value.
  • Fallbacks and absent optional flags fail safe per field. No required response field removed.
  • Request bodies are tested as encoded JSON; encodeDefaults / explicitNulls match the server.
  • OpenAPI Generator: no enumUnknownDefaultCase, no serializationLibrary, no anyOf responses.
  • OpenAPI Generator: stale output is removed (cleanupOutput on a dedicated dir, or a targeted wipe); a verify task compares trimmed text.