[Kotlin][ktor] add delegate pattern support

Merged
CH
6mo ago
+4331-86

Fixes #23755
Adds delegate pattern for the kotlin-server ktor generator.
Integration tests added under samples/server/petstore/kotlin-server/ktor-delegate-pattern
See the readme under samples/server/petstore/kotlin-server/ktor-delegate-pattern/generated/README.md for usage example.

Using the delegate pattern (ktor)

When generating a server with the delegatePattern enabled, the router delegates request handling to small, focused interfaces you implement. This is ideal for API‑first development: you wire your business logic without touching generated routing code.

What gets generated

  • For each API: an interface org.openapitools.server.apis.<ApiName>Delegate with one suspend function per operation. Each function receives parsed parameters plus a io.ktor.server.routing.RoutingCall named call.

  • In org.openapitools.server.infrastructure:

    • AppDelegates – a data holder aggregating all optional delegates.
    • Delegates – helpers to register and inject delegates (Application.delegates(AppDelegates(...)), RoutingCall.delegates(AppDelegates(...)).
    • APINotImplementedException – thrown when a delegate is missing.
      – BadParameterException – used for parameter validation errors (400).
  • Generated interface: org.openapitools.server.apis.PetApiDelegate

  • Generated interface: org.openapitools.server.apis.StoreApiDelegate

  • Generated interface: org.openapitools.server.apis.UserApiDelegate

Implement a delegate

Implement the generated interface(s) in your codebase. Example (using the first generated API):

package com.example.impl

import org.openapitools.server.apis.PetApiDelegate
import io.ktor.server.routing.RoutingCall
import 

class PetApiDelegateImpl : PetApiDelegate {

    override suspend fun addPet(pet: Pet, call: RoutingCall): Pet {
        // Access authentication, request, etc. via the call if needed
        // val principal = call.principal<org.openapitools.server.infrastructure.ApiPrincipal>()
        // Return the payload expected by the spec (or Unit if no body)
        TODO("Provide implementation")
    }

}

Notes:

  • Do not call call.respond(...) inside the delegate. Return the value; the generated route will serialize and respond for you. For operations without a response body, return kotlin.Unit and the route responds with 200 by default.

Register your delegates

Register your implementations once during application startup so routes can resolve them:

import org.openapitools.server.infrastructure.AppDelegates
import org.openapitools.server.infrastructure.delegates
import org.openapitools.server.AllApis
import io.ktor.server.application.Application
import io.ktor.server.routing.routing

fun Application.module() {
    delegates(
        AppDelegates(
            // Property names are lowerCamelCase of the API class + "Delegate"
            // Provide only what you implement; others can be left null
            // petApiDelegate = PetApiDelegateImpl(),
            // storeApiDelegate = StoreApiDelegateImpl(),
            // userApiDelegate = UserApiDelegateImpl(),

        )
    )

    // ... install features, etc.
    routing {
        AllApis()
    }
}

If you prefer to register APIs individually:

import org.openapitools.server.apis.PetApi
import org.openapitools.server.apis.StoreApi
import org.openapitools.server.apis.UserApi

import io.ktor.server.application.Application
import io.ktor.server.routing.routing

fun Application.module() {
    // ...
    routing {
        PetApi()
        StoreApi()
        UserApi()

    }
}

If you prefer per-request scoping, you may also attach delegates to a specific RoutingCall:

call.delegates(AppDelegates(petApiDelegate = PetApiDelegateImpl()))

Runtime behavior

  • If a route is invoked and its corresponding delegate is not provided, the server throws APINotImplementedException and responds with 501 Not Implemented.
  • If a required parameter is missing or invalid, BadParameterException is thrown and the server responds with 400 Bad Request.
  • You can access authenticated principals within delegates via call.principal<org.openapitools.server.infrastructure.ApiPrincipal>() when auth is enabled for the operation.

Handle delegate exceptions with StatusPages

To return consistent responses for delegate errors, install Ktor StatusPages and map both exceptions:

import io.ktor.http.HttpStatusCode
import io.ktor.server.plugins.statuspages.StatusPages
import io.ktor.server.plugins.statuspages.exception
import io.ktor.server.response.respondText
import org.openapitools.server.infrastructure.APINotImplementedException
import org.openapitools.server.infrastructure.BadParameterException

install(StatusPages) {
    exception<Throwable> { call, cause ->
        when (cause) {
            is BadParameterException -> {
                call.respondText(
                    status = cause.statusCode,
                    text = mapOf(
                        "message" to (cause.message ?: "Invalid parameter"),
                        "parameter" to cause.parameterName,
                        "validation" to cause.validationType,
                        "expected" to cause.expectedValue,
                        "actual" to cause.actualValue
                    ).filterValues { it != null }.mapValues { it.toString() }.toString()
                )
            }

            is APINotImplementedException -> {
                call.respondText(
                    status = HttpStatusCode.NotImplemented,
                    text = cause.message ?: "API not implemented"
                )
            }
        }
    }
}

Handle file uploads in delegates

For multipart endpoints, generated delegates receive an <operation_id>MultiPartReceiver (operation-specific name) so you can parse form fields and process file parts inside your implementation.

Example (uploadFile):

import io.ktor.server.routing.RoutingCall
import io.ktor.utils.io.toByteArray
import org.openapitools.server.apis.PetApiDelegate
import org.openapitools.server.models.ModelApiResponse

class PetApiDelegateImpl : PetApiDelegate {
    override suspend fun uploadFile(
        petId: Long,
        uploadFileMultipartReceiver: PetApiDelegate.UploadFileMultiPartReceiver,
        call: RoutingCall
    ): ModelApiResponse {
        var fileName: String? = null
        var fileContent: String? = null

        val multipart = uploadFileMultipartReceiver.receiveMultipart {
            onReceiveFile {
                fileName = originalFileName
                fileContent = provider().toByteArray().decodeToString()
            }
        }

        val additionalMetadata = multipart.additionalMetadata

        return ModelApiResponse(
            code = 200,
            message = "uploaded file=$fileName metadata=$additionalMetadata content=$fileContent"
        )
    }
}

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package || exit
    ./bin/generate-samples.sh ./bin/configs/*.yaml || exit
    ./bin/utils/export_docs_generators.sh || exit
    
    (For Windows users, please run the script in WSL)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.x.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR solves a reported issue, reference it using GitHub's linking syntax (e.g., having "fixes #123" present in the PR description)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@karismann, @Zomzog, @andrewemery @4brunu @yutaka0m @stefankoppier @e5l @dennisameling


Summary by cubic

Adds delegate pattern support to the kotlin-server generator for ktor, letting routes call generated *ApiDelegate interfaces for clean separation between transport and business logic. Also fixes multipleOf validation for floating-point values and improves enum/number parameter parsing with safer delegate injection.

  • New Features

    • New delegatePattern option for ktor in kotlin-server (documented in generator options).
    • Generates *ApiDelegate interfaces per API and an AllApis() route helper.
    • Infrastructure: AppDelegates, Delegates (safe as? lookups), APINotImplementedException, BadParameterException.
    • Parameter validation plus model validate() methods; violations return 400 via BadParameterException.
    • Validation: multipleOf now correctly supports float/double values.
    • Parameter parsing: enums via fromValue(), numbers via to<Type>(); invalids produce clear 400 errors.
    • Multipart support via operation-scoped *MultiPartReceiver.
    • New samples/server/petstore/kotlin-server/ktor-delegate-pattern with tests and a Maven profile.
  • Migration

    • Enable with additionalProperties.delegatePattern=true when generating kotlin-server with ktor.
    • Implement generated XxxApiDelegate and register once: Application.delegates(AppDelegates(xxxApiDelegate = ...)) (or per-request via call.delegates(...)).
    • Return values from delegates; do not call call.respond(...). Unimplemented ops throw APINotImplementedException (501).
    • Install Ktor StatusPages to handle BadParameterException (400) and APINotImplementedException (501).