# Functional Kotlin Services > Functional Kotlin Services at Lambda World. Suspension, structured concurrency, resources, context parameters, and typed errors in one service. Source: /lambda-world-functional-kotlin-services/ ## Functional Kotlin Services Slide 1: /lambda-world-functional-kotlin-services/#/1 #### Simon Vergauwen · Arrow-kt · JetBrains > Speaker notes: The audience already knows functional programming. Start from what we can build, not a language contest. The examples follow one service from application lifetime through HTTP into domain logic. ### What? Slide 2: /lambda-world-functional-kotlin-services/#/2 1. Suspend and composing lifecycle 2. Constraining functions to a context 3. Domain modelling 4. Errors as part of the contract ## A service owns its work and its lifetime Slide 3: /lambda-world-functional-kotlin-services/#/3 > Speaker notes: - App runs in a process - resources & work form ~> tree - SIGTERM ~> Graceful stop - Completed when both are completed - Model this in FP? ### What is `suspend`? Slide 4: /lambda-world-functional-kotlin-services/#/4 ```kotlin typealias Thunk = () -> A typealias IO = suspend () -> A ``` > Speaker notes: - Lambdas or Thunk not enough - IO, or suspend -> Clearly side-effects -> Async / Concurrent ### What is `suspend`? Slide 5: /lambda-world-functional-kotlin-services/#/5 ```kotlin suspend fun events(): List suspend fun Event.process( ): Unit ``` > **`Event`** — Extension function ```kotlin fun events(): IO> fun Event.process(): IO ``` > Speaker notes: - suspend keyword - IO return type - Extension function ### What is `suspend`? Slide 6: /lambda-world-functional-kotlin-services/#/6 ```kotlin suspend fun events(): List suspend fun Event.process( ): Unit { val event: Event = this } ``` > **`Event`** — receiver of extension function ```kotlin fun events(): IO> fun Event.process(): IO ``` > Speaker notes: - Receiver becomes this - Access public API in body ### What is `suspend`? Slide 7: /lambda-world-functional-kotlin-services/#/7 ```kotlin suspend fun events(): List suspend fun Event.process(): Unit suspend fun program() { val events = events() events.process() } ``` ```kotlin fun events(): IO> fun Event.process(): IO fun program(): IO = events() .flatMap { it.process() } ``` ### What is `suspend`? Slide 8: /lambda-world-functional-kotlin-services/#/8 > **`suspend`** — suspend lambda > **`SuspendAppScope`** — lambda with receiver, allows calling `exitApp(code)` ```kotlin fun SuspendApp(block: suspend SuspendAppScope.() -> Unit): Unit ``` ```kotlin import arrow.continuations.SuspendApp suspend fun program(): Unit = TODO() //Example fun main() = SuspendApp { program() } ``` > **Type hint** `this: SuspendAppScope` Cancellation on SIGINT & SIGTERM Await all cancelled coroutines to complete Structured Concurrency through KotlinX Coroutines ### Server as a Resource Slide 9: /lambda-world-functional-kotlin-services/#/9 > **`resourceScope`** — Scope for resource management > **`server`** — `install` a server into the `resourceScope` > **`awaitCancellation`** — Await `SIGTERM`/`SIGINT` which cancels the `SuspendApp`\n-> cancels and awaits the running `suspend` lambda and `CoroutineScope` ```kotlin import io.ktor.server.netty.Netty import arrow.continuations.SuspendApp import arrow.continuations.ktor.server import arrow.fx.coroutines.resourceScope import java.lang.System.getenv import kotlinx.coroutines.* fun main() = SuspendApp { resourceScope { server(Netty, host = getenv("HOST"), port = getenv("PORT").toInt()) { } awaitCancellation() } } ``` > **Type hint** `this: SuspendAppScope` > **Type hint** `context(ResourceScope)` ### Installing as a Resource Slide 10: /lambda-world-functional-kotlin-services/#/10 > **`ExitCase`** — `Completed`, `Cancelled` or `Failure` ```kotlin context(_: ResourceScope) suspend fun install( acquire: suspend () -> A, release: suspend (A, ExitCase) -> Unit, ): A ``` ### Server as a Resource Slide 11: /lambda-world-functional-kotlin-services/#/11 ```kotlin context(_: ResourceScope) suspend fun server( engine: ApplicationEngine, host: String, port: Int, ): ServerEngine = install({ engine.createAndStart(host, port) }) { server, _ -> server.stop() } ``` ### Processors share that lifetime Slide 12: /lambda-world-functional-kotlin-services/#/12 > **`launch`** — Starts a parallel task within the `SuspendAppScope` ```kotlin import kotlinx.coroutines.* import arrow.continuations.SuspendApp import arrow.continuations.ktor.server import arrow.fx.coroutines.resourceScope import io.ktor.server.netty.Netty import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.launch import java.lang.System.getenv val host: String = getenv("HOST") val port: Int = getenv("PORT").toInt() suspend fun processor(): Unit = awaitCancellation() // Example fun main() = SuspendApp { resourceScope { server(Netty, host = host, port = port) { } launch { processor() } awaitCancellation() } } ``` > **Type hint** `this: SuspendAppScope` > **Type hint** `context(ResourceScope)` ### Resources are released in reverse order Slide 13: /lambda-world-functional-kotlin-services/#/13 ```kotlin import kotlinx.coroutines.* import arrow.continuations.SuspendApp import arrow.continuations.ktor.server import arrow.fx.coroutines.ResourceScope import arrow.fx.coroutines.resourceScope import io.ktor.server.netty.Netty import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.job import kotlinx.coroutines.launch import java.lang.System.getenv val host: String = getenv("HOST") val port: Int = getenv("PORT").toInt() class Dependencies { suspend fun processor(): Unit = awaitCancellation() suspend fun close(): Unit = Unit } suspend fun ResourceScope.dependencies(): Dependencies = install({ Dependencies() }) { dep, _ -> dep.close() } suspend fun ResourceScope.coroutineScope(): CoroutineScope = install({ CoroutineScope(SupervisorJob() + Dispatchers.Default) }) { scope, _ -> scope.coroutineContext.job.cancelAndJoin() } // Example fun main() = SuspendApp { resourceScope { val dep = dependencies() server(Netty, host = host, port = port) { } launch { dep.processor() } awaitCancellation() } } ``` > **Type hint** `this: SuspendAppScope` > **Type hint** `context(ResourceScope)` Race condition between dependencies and launch > Speaker notes: `dependencies()` is a resource like the server: database pools, clients, whatever the processor needs. Both are `install`ed in the same `resourceScope`, in this order, and the scope releases them in reverse: last acquired, first released. Click 3: the server stops first, no new requests. Click 4: then the dependencies close. The processor, still a child of `SuspendApp`, is cancelled on click 2 and gone by click 3: it happens to be done before its dependencies close, but nothing guarantees it. The next slide makes that a guarantee. ### Processors finish before dependencies close Slide 14: /lambda-world-functional-kotlin-services/#/14 ```kotlin import kotlinx.coroutines.* import arrow.continuations.SuspendApp import arrow.continuations.ktor.server import arrow.fx.coroutines.ResourceScope import arrow.fx.coroutines.resourceScope import io.ktor.server.netty.Netty import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.job import kotlinx.coroutines.launch import java.lang.System.getenv val host: String = getenv("HOST") val port: Int = getenv("PORT").toInt() class Dependencies { suspend fun processor(): Unit = awaitCancellation() suspend fun close(): Unit = Unit } suspend fun ResourceScope.dependencies(): Dependencies = install({ Dependencies() }) { dep, _ -> dep.close() } suspend fun ResourceScope.coroutineScope(): CoroutineScope = install({ CoroutineScope(SupervisorJob() + Dispatchers.Default) }) { scope, _ -> scope.coroutineContext.job.cancelAndJoin() } // Example fun main() = SuspendApp { resourceScope { val dep = dependencies() val scope = coroutineScope() server(Netty, host = host, port = port) { } scope.launch { dep.processor() } awaitCancellation() } } ``` > **Type hint** `this: SuspendAppScope` > **Type hint** `context(ResourceScope)` > Speaker notes: Make the `CoroutineScope` itself a resource: acquired after the dependencies, before the server; its release cancels its children and waits for them. Now the processor is owned by the `resourceScope`, not by `SuspendApp`, and the reverse release order is the shutdown plan. Click 3: the server stops, no new requests. Click 4: the scope's release cancels the processor and waits for it to finish the event it is on. Click 5: only then do the dependencies close. Nothing is closed under a running processor, by construction. ### Configuring your server Slide 15: /lambda-world-functional-kotlin-services/#/15 > **`@Serializable`** — Compiler plugin to generate serialization code > **`getAs`** — Read, and deserialize the configuration ```kotlin import arrow.fx.coroutines.ResourceScope import presentation.snippets.s01suspend.slide13.dependencies import presentation.snippets.s01suspend.slide13.coroutineScope import io.ktor.server.application.* import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import arrow.continuations.SuspendApp import arrow.continuations.ktor.server import arrow.fx.coroutines.resourceScope import io.ktor.server.config.ApplicationConfig import io.ktor.server.config.getAs import io.ktor.server.netty.Netty import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.launchIn import kotlinx.serialization.Serializable fun processor(): Flow = emptyFlow() // Example @Serializable data class Config(val host: String, val port: Int) fun main() = SuspendApp { val config = ApplicationConfig("application.yaml").getAs() resourceScope { val dep = dependencies() val scope = coroutineScope() server(Netty, host = config.host, port = config.port) { } scope.launch { dep.processor() } awaitCancellation() } } ``` > **Type hint** `this: SuspendAppScope` > **Type hint** `context(ResourceScope)` > **Type hint** `this: Application` ### Configuring your Ktor server Slide 16: /lambda-world-functional-kotlin-services/#/16 ```kotlin import io.ktor.server.application.* import io.ktor.serialization.kotlinx.json.json import io.ktor.server.application.Application import io.ktor.server.application.install import io.ktor.server.plugins.contentnegotiation.ContentNegotiation import kotlinx.serialization.json.Json fun Application.app() { install(ContentNegotiation) { json(Json { isLenient = true ignoreUnknownKeys = true }) } } ``` > **Type hint** `this: ContentNegotiationConfig` > **Type hint** `this: JsonBuilder` ### Configuring your Ktor server Slide 17: /lambda-world-functional-kotlin-services/#/17 ```kotlin import io.ktor.server.application.* import io.ktor.http.ContentType import io.ktor.http.content.OutgoingContent import io.ktor.serialization.ContentConverter import io.ktor.serialization.kotlinx.json.json import io.ktor.server.application.Application import io.ktor.server.application.install import io.ktor.server.plugins.contentnegotiation.ContentNegotiation import io.ktor.util.reflect.TypeInfo import io.ktor.utils.io.ByteReadChannel import io.ktor.utils.io.charsets.Charset import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json class CustomConverter : ContentConverter { override suspend fun serialize( contentType: ContentType, charset: Charset, typeInfo: TypeInfo, value: Any? ): OutgoingContent? = TODO("Not yet implemented") override suspend fun deserialize( charset: Charset, typeInfo: TypeInfo, content: ByteReadChannel ): Any? = TODO("Not yet implemented") } //Example fun Application.app() { install(ContentNegotiation) { json(Json { isLenient = true ignoreUnknownKeys = true }) register(ContentType("application", "custom"), CustomConverter()) } } ``` > **Type hint** `this: ContentNegotiationConfig` > **Type hint** `this: JsonBuilder` ### Ktor Routes using Spine Slide 18: /lambda-world-functional-kotlin-services/#/18 ```kotlin import io.ktor.http.HttpStatusCode import opensavvy.spine.api.RootResource import opensavvy.spine.api.StaticResource import presentation.support.* data class CreateUser(val name: String) object UserAlreadyExists object InvalidUser { val errors: List = ["username too short", "email doesn't contain @"] } //Example object Api : RootResource("api") { // api object Users : StaticResource("users", Api) { // api/users val list by get() // GET /v3/users .response>() } } ``` ### Ktor Routes using Spine Slide 19: /lambda-world-functional-kotlin-services/#/19 ```kotlin import io.ktor.http.HttpStatusCode import opensavvy.spine.api.RootResource import opensavvy.spine.api.StaticResource import presentation.support.* data class CreateUser(val name: String) object UserAlreadyExists object InvalidUser { val errors: List = ["username too short", "email doesn't contain @"] } //Example object Api : RootResource("api") { // api object Users : StaticResource("users", Api) { // api/users val list by get() // GET /v3/users .response>() val create by post() // POST /api/users .request() .response() .failure(HttpStatusCode.Conflict) .failure(HttpStatusCode.UnprocessableEntity) } } ``` ### Calling Ktor Spine routes Slide 20: /lambda-world-functional-kotlin-services/#/20 > **`Apache5`** — Support for many different clients across all KMP platforms > **`User`** — Handle all cases as defined by response and failures ```kotlin import io.ktor.client.engine.apache5.Apache5 import io.ktor.client.HttpClient import opensavvy.spine.api.div import opensavvy.spine.client.handle import opensavvy.spine.client.request import presentation.snippets.s01suspend.slide19.Api import presentation.snippets.s01suspend.slide19.Api.Users import presentation.snippets.s01suspend.slide19.Api.Users.create import presentation.snippets.s01suspend.slide19.CreateUser import presentation.snippets.s01suspend.slide19.InvalidUser import presentation.snippets.s01suspend.slide19.UserAlreadyExists import presentation.support.* // Example suspend fun main() { HttpClient(Apache5) { // Configure Apache5 Client }.use { client -> client.request(Api / Users / create, CreateUser("johndoe")) .handle( { _: UserAlreadyExists -> println("User already exists") }, { errors: InvalidUser -> println(errors.errors.joinToString()) }, { _: User -> println("User created") } ) } } ``` > **Type hint** `this: HttpClientConfig` ### Ktor Routes using Spine Slide 21: /lambda-world-functional-kotlin-services/#/21 ```kotlin import io.ktor.server.application.* import io.ktor.server.application.Application import io.ktor.server.routing.routing import opensavvy.spine.server.fail import presentation.snippets.s01suspend.slide19.Api import opensavvy.spine.server.route import opensavvy.spine.server.respond import presentation.snippets.s01suspend.slide19.CreateUser import presentation.snippets.s01suspend.slide19.UserAlreadyExists import presentation.support.* sealed interface Result { data class Success(val user: User) : Result data object AlreadyExists : Result } fun insertUser(createUser: CreateUser): Result = TODO() //Example fun Application.users() = routing { route(Api.Users.create) { when(val result = insertUser(body)) { is Success -> respond(result.user) AlreadyExists -> fail(UserAlreadyExists) } } } ``` > **Type hint** `this: Routing` > **Type hint** `this: TypedRespondScope>, ByCode>, Parameters.Empty>` ### When statement Slide 22: /lambda-world-functional-kotlin-services/#/22 > **`sealed interface`** — Closed inheritance within this compilation unit (module) > **`@JvmInline`** — Valhalla (JEP 401) will bring value classes to JVM,\n`@JvmInline` emulates it > **`data object`** — Singleton object ```kotlin import io.ktor.server.application.* import io.ktor.server.application.Application import io.ktor.server.routing.routing import opensavvy.spine.server.fail import presentation.snippets.s01suspend.slide19.Api import opensavvy.spine.server.route import opensavvy.spine.server.respond import presentation.snippets.s01suspend.slide19.CreateUser import presentation.snippets.s01suspend.slide19.UserAlreadyExists import presentation.support.* //Example sealed interface Result { @JvmInline value class Success(val user: User) : Result data object AlreadyExists : Result } suspend fun insertUser(createUser: CreateUser): Result = TODO() fun Application.users() = routing { route(Api.Users.create) { when(val result = insertUser(body)) { is Success -> respond(result.user) AlreadyExists -> fail(UserAlreadyExists) } } } ``` > **Type hint** `this: Routing` > **Type hint** `this: TypedRespondScope>, ByCode>, Parameters.Empty>` ### `Raise` adds an expected error to the signature Slide 23: /lambda-world-functional-kotlin-services/#/23 > **`Raise`** — Can `Raise` a `UserAlreadyExists` error ```kotlin import arrow.core.raise.context.Raise import opensavvy.spine.server.respond import io.ktor.server.application.* import io.ktor.server.routing.routing data object UserAlreadyExists context(_: Raise) suspend fun insertUser(createUser: CreateUser): User = TODO() fun Application.users() = routing { route(Api.Users.create) { val user = insertUser(body) respond(user) } } ``` > **Type hint** `this: TypedRespondScope>, ByCode>, Parameters.Empty>` > ⚠ **Compiler error** at `insertUser`: No context argument for `_: Raise` found ### `Raise` adds an expected error to the signature Slide 24: /lambda-world-functional-kotlin-services/#/24 > **`routeWithRaise`** — Spine's Arrow-kt support brings `Raise` into the context for all failures > **`body`** — Missing validation ```kotlin import arrow.core.raise.context.Raise import opensavvy.spine.server.arrow.routeWithRaise import opensavvy.spine.server.respond import io.ktor.server.application.* import io.ktor.server.routing.routing import presentation.snippets.s01suspend.slide19.Api import presentation.snippets.s01suspend.slide19.CreateUser import presentation.snippets.s01suspend.slide19.UserAlreadyExists context(_: Raise) suspend fun insertUser(createUser: CreateUser): User = TODO() fun Application.users() = routing { routeWithRaise(Api.Users.create) { val user = insertUser(body) respond(user) } } ``` > **Type hint** `context(Raise, Raise)` ### Validation Slide 25: /lambda-world-functional-kotlin-services/#/25 > **`(val value: String)`** — Can create invalid values ```kotlin @JvmInline value class Username(val value: String) ``` ### Validation Slide 26: /lambda-world-functional-kotlin-services/#/26 > **`private constructor`** — Enforce using smart-constructor > **`Raise>`** — Accumulate `String` error messages into `NonEmptyList`, at least one error or the success value > **`operator fun invoke`** — Custom `invoke` operator allows for `Username(...)` syntax ```kotlin import arrow.core.raise.context.Raise import arrow.core.nonEmptyListOf import arrow.core.NonEmptyList @JvmInline value class Username private constructor(val value: String) { companion object { context(_: Raise>) operator fun invoke(value: String): Username = TODO() } } ``` ### Validation Slide 27: /lambda-world-functional-kotlin-services/#/27 > **`ensure`** — Defined on `context(Raise)` so it short-circuits ```kotlin import arrow.core.raise.context.Raise import arrow.core.nonEmptyListOf import arrow.core.NonEmptyList import arrow.core.raise.context.ensure @JvmInline value class Username private constructor(val value: String) { companion object { context(_: Raise>) operator fun invoke(value: String): Username { ensure(value.length >= 4) { nonEmptyListOf("Username is too short") } ensure(value.length <= 255) { nonEmptyListOf("Username is too long") } return Username(value) } } } ``` ### Validation Slide 28: /lambda-world-functional-kotlin-services/#/28 > **`ensureOrAccumulate`** — Defined on `context(Accumulate)` so it _accumulates_ in `NonEmptyList` ```kotlin import arrow.core.raise.context.Raise import arrow.core.nonEmptyListOf import arrow.core.NonEmptyList import presentation.support.ensureOrAccumulate import arrow.core.raise.context.accumulate @JvmInline value class Username private constructor(val value: String) { companion object { context(_: Raise>) operator fun invoke(value: String): Username = accumulate { ensureOrAccumulate(value.length >= 4) { "Username is too short" } ensureOrAccumulate(value.length <= 255) { "Username is too long" } ensureOrAccumulate(value.matches(Regex("[a-zA-Z0-9]+"))) { "Username is invalid" } Username(value) } } } ``` > **Type hint** `context(Accumulate, Raise)` ### Validation Slide 29: /lambda-world-functional-kotlin-services/#/29 ```kotlin import arrow.core.raise.context.Raise import arrow.core.nonEmptyListOf import arrow.core.NonEmptyList import presentation.support.ensureOrAccumulate import arrow.core.raise.context.accumulate @JvmInline value class Email private constructor(val value: String) { companion object { context(_: Raise>) operator fun invoke(value: String): Email = accumulate { ensureOrAccumulate(value.contains("@")) { "Email is invalid" } Email(value) } } } ``` > **Type hint** `context(Accumulate, Raise)` ### Validation Slide 30: /lambda-world-functional-kotlin-services/#/30 ```kotlin import arrow.core.raise.context.Raise import arrow.core.nonEmptyListOf import arrow.core.NonEmptyList import presentation.snippets.s01suspend.slide28.Username import presentation.snippets.s01suspend.slide29.Email data class CreateUserRequest(val username: String, val email: String) // Example data class CreateUser(val username: Username, val email: Email) context(_: Raise>) fun CreateUserRequest.toCreateUser(): CreateUser = TODO() ``` ### Validation Slide 31: /lambda-world-functional-kotlin-services/#/31 > **`NonEmptyList` into a `NonEmptyList` ```kotlin import arrow.core.raise.context.Raise import arrow.core.nonEmptyListOf import arrow.core.NonEmptyList import arrow.core.raise.context.withError import presentation.snippets.s01suspend.slide28.Username import presentation.snippets.s01suspend.slide29.Email data class CreateUserRequest(val username: String, val email: String) // Example data class CreateUser(val username: Username, val email: Email) context(_: Raise>) fun CreateUserRequest.toCreateUser(): CreateUser = withError({ errors: NonEmptyList> -> errors.reduce { acc, errors -> acc + errors } }) { } ``` ### Validation Slide 32: /lambda-world-functional-kotlin-services/#/32 > **`accumulating`** — Lift `Raise>` into `Accumulate` ```kotlin import arrow.core.raise.context.Raise import arrow.core.nonEmptyListOf import arrow.core.NonEmptyList import presentation.support.accumulating import arrow.core.raise.context.accumulate import arrow.core.raise.context.withError import presentation.snippets.s01suspend.slide28.Username import presentation.snippets.s01suspend.slide29.Email data class CreateUserRequest(val username: String, val email: String) // Example data class CreateUser(val username: Username, val email: Email) context(_: Raise>) fun CreateUserRequest.toCreateUser(): CreateUser = withError({ errors: NonEmptyList> -> errors.reduce { acc, errors -> acc + errors } }) { accumulate { val username by accumulating { Username(username) } val email by accumulating { Email(email) } CreateUser(username, email) } } ``` > **Type hint** `context(Accumulate, Raise)` ### Validation Slide 33: /lambda-world-functional-kotlin-services/#/33 ```kotlin import arrow.core.raise.context.Raise import arrow.core.nonEmptyListOf import arrow.core.NonEmptyList import presentation.support.accumulating import arrow.core.raise.context.accumulate import arrow.core.raise.context.withError import presentation.snippets.s01suspend.slide28.Username import presentation.snippets.s01suspend.slide29.Email data class CreateUserRequest(val username: String, val email: String) // Example @JvmInline value class InvalidUser(val errors: NonEmptyList) data class CreateUser(val username: Username, val email: Email) context(_: Raise) fun CreateUserRequest.toCreateUser(): CreateUser = withError({ errors: NonEmptyList> -> InvalidUser(errors.reduce { acc, errors -> acc + errors }) }) { accumulate { val username by accumulating { Username(username) } val email by accumulating { Email(email) } CreateUser(username, email) } } ``` > **Type hint** `context(Accumulate, Raise)` ### Call directly in the route Slide 34: /lambda-world-functional-kotlin-services/#/34 ```kotlin import org.jetbrains.exposed.v1.jdbc.JdbcTransaction as Transaction import opensavvy.spine.server.arrow.routeWithRaise import opensavvy.spine.server.respond import io.ktor.server.application.* import io.ktor.server.routing.routing import presentation.snippets.s01suspend.slide19.Api import presentation.snippets.s01suspend.slide19.CreateUser import presentation.snippets.s01suspend.slide19.UserAlreadyExists fun CreateUser.toCreateUser(): CreateUser = this suspend fun insertUser(create: CreateUser): User = TODO() // Example fun Application.users() = routing { routeWithRaise(Api.Users.create) { val create = body.toCreateUser() val user = insertUser(create) respond(user) } } ``` > **Type hint** `context(Raise, Raise)` ### `|.` skips the call on an error Slide 35: /lambda-world-functional-kotlin-services/#/35 > Design proposal · KEEP-0462 > **`error`** — Explicit error types > **`User | MissingUser`** — Error union, single success type with multiple error types > **`|.mark()`** — Language level short-circuit syntax like `?.` for nullable types > **`Unit | MissingUser | NotEligible`** — Errors accumulate automatically in the type ```kotlin error class MissingUser(val id: UserId) suspend fun findUser(id: UserId): User | MissingUser suspend fun User.mark(): Unit | NotEligible suspend fun process(id: UserId): Unit | MissingUser | NotEligible = findUser(id)|.mark() ``` ### `Raise` adds an expected error to the signature Slide 36: /lambda-world-functional-kotlin-services/#/36 > **`Transaction`** — Type of the Exposed Typed SQL DSL ```kotlin import org.jetbrains.exposed.v1.jdbc.* import org.jetbrains.exposed.v1.jdbc.transactions.transaction import org.jetbrains.exposed.v1.core.Table import org.jetbrains.exposed.v1.core.ResultRow import org.jetbrains.exposed.v1.jdbc.JdbcTransaction as Transaction data class CreateUser(val username: String, val email: String) object UserTable : Table("users") { val username = varchar("username", 255) val email = varchar("email", 350) } fun Iterable.toUser(): User = single().let { User(UserId(1), it[UserTable.username]) } // Example context(_: Transaction) fun insertUser(create: CreateUser): User = UserTable.insertReturning { insert -> insert[username] = create.username insert[email] = create.email }.toUser() ``` ### `Raise` adds an expected error to the signature Slide 37: /lambda-world-functional-kotlin-services/#/37 > **`PLSQLException`** — `catch` specific errors and lift them to type signature > **`raise(UserAlreadyExists(`** — Raise error into `context(Raise)` ```kotlin import org.jetbrains.exposed.v1.jdbc.* import org.jetbrains.exposed.v1.jdbc.transactions.transaction import org.jetbrains.exposed.v1.core.Table import org.jetbrains.exposed.v1.core.ResultRow import java.sql.SQLException as PLSQLException import org.jetbrains.exposed.v1.jdbc.JdbcTransaction as Transaction import arrow.core.raise.context.Raise import arrow.core.raise.catch import arrow.core.raise.context.raise data class CreateUser(val username: String, val email: String) object UserTable : Table("users") { val username = varchar("username", 255) val email = varchar("email", 350) } fun Iterable.toUser(): User = single().let { User(UserId(1), it[UserTable.username]) } fun PLSQLException.uniqueViolation(): Boolean = sqlState == "23505" // Example @JvmInline value class UserAlreadyExists(val username: String) context(_: Transaction, _: Raise) fun insertUser(create: CreateUser): User = catch({ UserTable.insertReturning { insert -> insert[username] = create.username insert[email] = create.email }.toUser() }) { e: PLSQLException -> if(e.uniqueViolation()) raise(UserAlreadyExists(create.username)) else throw e } ``` ### Handling the error supplies `Raise` Slide 38: /lambda-world-functional-kotlin-services/#/38 ```kotlin import org.jetbrains.exposed.v1.jdbc.* import org.jetbrains.exposed.v1.jdbc.transactions.transaction import org.jetbrains.exposed.v1.core.Table import org.jetbrains.exposed.v1.core.ResultRow import java.sql.SQLException as PLSQLException import org.jetbrains.exposed.v1.jdbc.JdbcTransaction as Transaction import arrow.core.raise.context.Raise import arrow.core.raise.context.either import arrow.core.raise.catch import arrow.core.raise.context.raise @JvmInline value class UserAlreadyExists(val username: String) context(_: Transaction, _: Raise) fun insertUser(create: CreateUser): User = catch({ UserTable.insertReturning { insert -> insert[username] = create.username insert[email] = create.email }.toUser() }) { e: PLSQLException -> if(e.uniqueViolation()) raise(UserAlreadyExists(create.username)) else throw e } data class CreateUser(val username: String, val email: String) object UserTable : Table("users") { val username = varchar("username", 255) val email = varchar("email", 350) } fun Iterable.toUser(): User = single().let { User(UserId(1), it[UserTable.username]) } fun PLSQLException.uniqueViolation(): Boolean = sqlState == "23505" // Example context(_: Transaction) fun insertUserOrNull(create: CreateUser): User? = either { insertUser(create) }.getOrNull() context(_: Raise) suspend fun insertUserResult(database: Database, create: CreateUser): User = transaction(database) { insertUser(create) } ``` > **Type hint** `context(Raise)` > **Type hint** `this: Transaction` ### Ktor Routes using Spine Slide 39: /lambda-world-functional-kotlin-services/#/39 ```kotlin import org.jetbrains.exposed.v1.jdbc.JdbcTransaction as Transaction import arrow.core.raise.context.Raise import io.ktor.server.application.* import presentation.snippets.s01suspend.slide19.UserAlreadyExists import presentation.support.* import io.ktor.server.application.Application import io.ktor.server.routing.routing import opensavvy.spine.server.arrow.routeWithRaise import opensavvy.spine.server.respond import org.jetbrains.exposed.v1.jdbc.Database import org.jetbrains.exposed.v1.jdbc.transactions.transaction import presentation.snippets.s01suspend.slide19.Api import presentation.snippets.s01suspend.slide19.CreateUser sealed interface Result data class Success(val user: User) : Result data object AlreadyExists : Result fun CreateUser.toCreateUser(): CreateUser = this //Example context(_: Transaction, _: Raise) fun insertUser(create: CreateUser): User = TODO() fun Application.users(database: Database) = routing { routeWithRaise(Api.Users.create) { val create = body.toCreateUser() val user = transaction(database) { insertUser(create) } respond(user) } } ``` > **Type hint** `this: Routing` > **Type hint** `context(context(Raise, Raise))` > **Type hint** `this: Transaction` ### Processors finish before dependencies close Slide 40: /lambda-world-functional-kotlin-services/#/40 ```kotlin import org.jetbrains.exposed.v1.jdbc.Database import presentation.snippets.s01suspend.slide39.users import kotlinx.coroutines.* import arrow.continuations.SuspendApp import arrow.continuations.ktor.server import arrow.fx.coroutines.ResourceScope import arrow.fx.coroutines.resourceScope import io.ktor.server.netty.Netty import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.job import kotlinx.coroutines.launch import java.lang.System.getenv val host: String = getenv("HOST") val port: Int = getenv("PORT").toInt() class Dependencies { val database: Database = TODO() suspend fun processor(): Unit = awaitCancellation() suspend fun close(): Unit = Unit } suspend fun ResourceScope.dependencies(): Dependencies = install({ Dependencies() }) { dep, _ -> dep.close() } suspend fun ResourceScope.coroutineScope(): CoroutineScope = install({ CoroutineScope(SupervisorJob() + Dispatchers.Default) }) { scope, _ -> scope.coroutineContext.job.cancelAndJoin() } // Example fun main() = SuspendApp { resourceScope { val dep = dependencies() val scope = coroutineScope() server(Netty, host = host, port = port) { users(dep.database) } scope.launch { dep.processor() } awaitCancellation() } } ``` > **Type hint** `this: SuspendAppScope` > **Type hint** `context(ResourceScope)` ### A null check refines the type Slide 41: /lambda-world-functional-kotlin-services/#/41 > **`user`** — Smart casted `User?` to `User` ```kotlin fun greeting(user: User?): String = if (user == null) "Unknown user" else "Hello, ${user.name}" ``` ### `when` handles absence and guarded values Slide 42: /lambda-world-functional-kotlin-services/#/42 ```kotlin fun greeting(user: User?): String = when (user) { null -> "Unknown user" is User if user.active -> "Hello, ${user.name}" is User -> "Your account is inactive" } ``` ### A sealed interface names every outcome Slide 43: /lambda-world-functional-kotlin-services/#/43 ```kotlin sealed interface Access { data class Granted(val user: User) : Access data class Suspended(val reason: String) : Access data object Missing : Access } fun message(access: Access): String = when (access) { is Access.Granted -> "Hello, ${access.user.name}" is Access.Suspended -> access.reason Access.Missing -> "Unknown user" } ``` ### Context-sensitive resolution Slide 44: /lambda-world-functional-kotlin-services/#/44 > **`when (access)`** — Prefixed type is known ```kotlin sealed interface Access { data class Granted(val user: User) : Access data class Suspended(val reason: String) : Access data object Missing : Access } fun message(access: Access): String = when (access) { is Granted -> "Hello, ${access.user.name}" is Suspended -> access.reason Missing -> "Unknown user" } ``` > Experimental Kotlin 2.4.20 > > `-Xcontext-sensitive-resolution` ### Check patterns with if-guard Slide 45: /lambda-world-functional-kotlin-services/#/45 > **`if access.user.active`** — if-guard checks condition ```kotlin sealed interface Access { data class Granted(val user: User) : Access data class Suspended(val reason: String) : Access data object Missing : Access } fun message(access: Access): String = when (access) { is Granted if access.user.active -> "Hello, ${access.user.name}" is Granted -> "Your account is inactive" is Suspended -> access.reason Missing -> "Unknown user" } ``` ### Destructuring follows property names Slide 46: /lambda-world-functional-kotlin-services/#/46 > **`val (email, name)`** — Destructure by matching property names ```kotlin sealed interface Access { data class Granted(val user: User) : Access data class Suspended(val reason: String) : Access data object Missing : Access } //Example data class User(val name: String, val age: Int, val email: String, val active: Boolean = true) fun message(access: Access): String = when (access) { is Granted if access.user.active -> { val (email, name) = access.user "$name <$email>" } is Granted -> "Your account is inactive" is Suspended -> access.reason Missing -> "Unknown user" } ``` > Experimental Kotlin 2.4.20 > > `-Xname-based-destructuring=complete` ### Destructuring follows property names Slide 47: /lambda-world-functional-kotlin-services/#/47 ```kotlin sealed interface Access { data class Granted(val user: User) : Access data class Suspended(val reason: String) : Access data object Missing : Access } //Example data class User(val name: String, val age: Int, val email: String, val active: Boolean = true) fun message(access: Access): String = when (access) { is Granted if access.user.active -> { val (email2, name) = access.user "$name <$email2>" } is Granted -> "Your account is inactive" is Suspended -> access.reason Missing -> "Unknown user" } ``` > ⚠ **Compiler error** at `email2`: Unresolved reference `email2` on receiver of type `User` > Experimental Kotlin 2.4.20 > > `-Xname-based-destructuring=complete` ### Collection literals Slide 48: /lambda-world-functional-kotlin-services/#/48 ```kotlin val list: List = ["a", "bb", "ccc"] val set: Set = ["a", "bb", "ccc"] val iterable: Iterable = ["a", "bb", "ccc"] ``` ### Custom collection literals Slide 49: /lambda-world-functional-kotlin-services/#/49 ```kotlin import arrow.core.nonEmptyListOf import arrow.core.NonEmptyList data class NonEmptyList(val head: A, val tail: List) val literal: NonEmptyList = ["a", "bb", "ccc"] val nonEmptyList = NonEmptyList("a", ["bb", "ccc"]) ``` > ⚠ **Compiler error** at `["a", "bb", "ccc"]`: `NonEmptyList` for collection literal does not\ndefine operator `of` and is not a supertype of `List` ### Custom collection literals Slide 50: /lambda-world-functional-kotlin-services/#/50 ```kotlin import arrow.core.nonEmptyListOf import arrow.core.NonEmptyList data class NonEmptyList private constructor(val head: A, val tail: List) { companion object { operator fun of(head: A, vararg tail: A) = NonEmptyList(head, tail.toList()) } } val literal = ["a", "bb", "ccc"] val nonEmptyList = NonEmptyList("a", ["bb", "ccc"]) val empty: NonEmptyList = [] ``` > ⚠ **Compiler error** at `NonEmptyList("a", ["bb", "ccc"])`: `constructor(head: A, tail: List): NonEmptyList` is private > ⚠ **Compiler error** at `[]`: No value passed for parameter `head` ## `suspend`, `context`, and typed errors Slide 51: /lambda-world-functional-kotlin-services/#/51 - `suspend` → asynchronous composition - `CoroutineScope` and `ResourceScope` → owned lifetimes - `context` → required capabilities - Domain types and `Raise` → values and expected failures - There is so much more!!! > **Everything composes together** ### Thank you Slide 52: /lambda-world-functional-kotlin-services/#/52 Lambda World #### Questions? > Speaker notes: Useful follow-ups if questions arise: where cancellation stops at an SDK boundary; why Raise differs from accumulating validation; how context resolution works; what is stable versus preview versus the rich-errors proposal. ## `suspend` is Continuation Passing Style Slide 53: /lambda-world-functional-kotlin-services/#/53 --- ```kotlin import kotlin.coroutines.Continuation import kotlin.coroutines.suspendCoroutine data class CreateUser(val name: String) data class SdkUser(val name: String) abstract class RequestHandler { abstract fun onSuccess(value: T) abstract fun onFailure(error: Throwable) } fun CreateUser.toSdkRequest(): String = name object sdk { fun execute(request: String, handler: RequestHandler): Request = TODO() } // Example suspend fun insertUser(create: CreateUser): User = suspendCoroutine { cont: Continuation -> } ``` ### `suspend` is Continuation Passing Style Slide 54: /lambda-world-functional-kotlin-services/#/54 ```kotlin import kotlin.coroutines.suspendCoroutine import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException data class CreateUser(val name: String) data class SdkUser(val name: String) abstract class RequestHandler { abstract fun onSuccess(value: T) abstract fun onFailure(error: Throwable) } fun CreateUser.toSdkRequest(): String = name object sdk { fun execute(request: String, handler: RequestHandler): Request = TODO() } // Example suspend fun insertUser(create: CreateUser): SdkUser = suspendCoroutine { cont -> sdk.execute(create.toSdkRequest(), object : RequestHandler() { override fun onSuccess(value: SdkUser) = cont.resume(value) override fun onFailure(error: Throwable) = cont.resumeWithException(error) }) } ``` ### `suspend` is cancellable Slide 55: /lambda-world-functional-kotlin-services/#/55 ```kotlin import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlinx.coroutines.* data class CreateUser(val name: String) data class SdkUser(val name: String) abstract class RequestHandler { abstract fun onSuccess(value: T) abstract fun onFailure(error: Throwable) } fun CreateUser.toSdkRequest(): String = name object sdk { fun execute(request: String, handler: RequestHandler): Request = TODO() } // Example suspend fun insertSdkUser(create: CreateUser): SdkUser = suspendCancellableCoroutine { cont -> val call = sdk.execute(create.toSdkRequest(), object : RequestHandler() { override fun onSuccess(value: SdkUser) = cont.resume(value) override fun onFailure(error: Throwable) = cont.resumeWithException(error) }) cont.invokeOnCancellation { call.cancel() } } ``` ### `suspend` is cancellable Slide 56: /lambda-world-functional-kotlin-services/#/56 > **`ensureActive()`** — Check cancellation, and stop if case of cancellation ```kotlin import kotlinx.coroutines.* import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive suspend fun ByteArray.checksum() = foldIndexed(0L) { index, acc, byte -> if (index % 1024 == 0) currentCoroutineContext().ensureActive() acc * 31 + byte } ``` ### `suspend` is cancellable Slide 57: /lambda-world-functional-kotlin-services/#/57 > **`yield()`** — Fairness operator, reschedule yourself to allow interleaving of tasks ```kotlin import kotlinx.coroutines.* import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive suspend fun ByteArray.checksum() = foldIndexed(0L) { index, acc, byte -> if (index % 1024 == 0) yield() acc * 31 + byte } ``` ### Process events in parallel Slide 58: /lambda-world-functional-kotlin-services/#/58 > **`Channel`** — KotlinX Coroutines suspending Queue > **`for (event in events)`** — Suspending iterator ```kotlin import kotlinx.coroutines.channels.Channel object sdk { fun events(): Channel = Channel() } // Example suspend fun processor() { val events: Channel = sdk.events() for (event in events) { handle(event) } } ``` ### Process events in parallel Slide 59: /lambda-world-functional-kotlin-services/#/59 > **`consumeAsFlow`** — Flow is a concurrent stream > **`map`** — Supports `suspend` > **`collect`** — Drain the `Flow`, `suspend` awaits until entire `Flow` is drained ```kotlin import kotlinx.coroutines.flow.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.map import presentation.support.* object sdk { fun events(): Channel = Channel() } // Example suspend fun processor() { sdk.events().consumeAsFlow() .map { handle(it) } .collect() } ``` ### Process events in parallel Slide 60: /lambda-world-functional-kotlin-services/#/60 > **`asFlow()`** — Manually lift `suspend` to `Flow` to access parallelism ```kotlin import kotlinx.coroutines.flow.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.map import presentation.support.* object sdk { fun events(): Channel = Channel() } // Example suspend fun processor() { sdk.events().consumeAsFlow() .flatMapMerge(concurrency = 64) { suspend { handle(it) }.asFlow() } .collect() } ``` ### Process events in parallel Slide 61: /lambda-world-functional-kotlin-services/#/61 > **`parMapUnordered`** — Equivalent of `flatMapMerge`, ordering comes at a cost ```kotlin import kotlinx.coroutines.flow.* import arrow.fx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.map import presentation.support.* object sdk { fun events(): Channel = Channel() } // Example suspend fun processor() { sdk.events().consumeAsFlow() .parMapUnordered(concurrency = 64) { handle(it) } .collect() } ``` ### Process events in parallel Slide 62: /lambda-world-functional-kotlin-services/#/62 ```kotlin import kotlinx.coroutines.flow.* import arrow.fx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.map import presentation.support.* object sdk { fun events(): Channel = Channel() } // Example suspend fun processor() { sdk.events().consumeAsFlow() .parMap(concurrency = 64) { handle(it) } .collect() } ``` ### Process events in parallel Slide 63: /lambda-world-functional-kotlin-services/#/63 > **`Flow`** — Allow further composition ```kotlin import kotlinx.coroutines.flow.* import arrow.fx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import presentation.support.* object sdk { fun events(): Channel = Channel() } // Example suspend fun processor(): Flow = sdk.events().consumeAsFlow() .parMap(concurrency = 64) { handle(it) } ``` ### Process events in parallel Slide 64: /lambda-world-functional-kotlin-services/#/64 > **`buffer`** — Typical streaming operators available, easy to build your own\nArrow Fx Coroutines has additional ones like `parMap` ```kotlin import kotlinx.coroutines.flow.* import arrow.fx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.map import presentation.support.* class RetryiableException : Exception() object sdk { fun events(): Channel = Channel() } // Example suspend fun processor(): Flow = sdk.events().consumeAsFlow() .parMap(concurrency = 64) { handle(it) } suspend fun program(): Unit { processor() .retry(3) { cause -> cause is RetryiableException } .buffer(100) .collect() } ``` ### Process events in parallel Slide 65: /lambda-world-functional-kotlin-services/#/65 > **`onCompletion`** — We can backpressure SuspendApp process on exit ```kotlin import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import arrow.fx.coroutines.* import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.map import presentation.support.* class RetryiableException : Exception() object sdk { fun events(): Channel = Channel() } // Example suspend fun processor(): Flow = sdk.events().consumeAsFlow() .parMap(concurrency = 64) { handle(it) } suspend fun program(): Unit { processor() .retry(3) { cause -> cause is RetryiableException } .buffer(100) .onCompletion { withContext(NonCancellable) { delay(10.seconds) } } .collect() } ``` ### `async` starts independent work Slide 66: /lambda-world-functional-kotlin-services/#/66 ```kotlin import arrow.core.raise.context.Raise import io.ktor.server.application.* import kotlinx.coroutines.* import presentation.snippets.s01suspend.slide19.UserAlreadyExists import presentation.support.* import io.ktor.server.application.Application import io.ktor.server.routing.routing import opensavvy.spine.server.arrow.routeWithRaise import opensavvy.spine.server.respond import org.jetbrains.exposed.v1.jdbc.JdbcTransaction as Transaction import org.jetbrains.exposed.v1.jdbc.Database import org.jetbrains.exposed.v1.jdbc.transactions.transaction import presentation.snippets.s01suspend.slide19.Api import presentation.snippets.s01suspend.slide19.CreateUser sealed interface Result data class Success(val user: User) : Result data object AlreadyExists : Result fun CreateUser.toCreateUser(): CreateUser = this fun createProfile(create: CreateUser): Unit = TODO() fun User.withProfile(profile: Unit): User = this context(_: Transaction, _: Raise) fun insertUser(create: CreateUser): User = TODO() //Example fun Application.users(database: Database) = routing { routeWithRaise(Api.Users.create) { val create = body.toCreateUser() val userWithProfile = coroutineScope { val user = async { transaction(database) { insertUser(create) } } val profile = async { transaction(database) { createProfile(create) } } user.await().withProfile(profile.await()) } respond(userWithProfile) } } ``` > **Type hint** `this: Routing` > **Type hint** `context(context(Raise, Raise))` > **Type hint** `this: CoroutineScope` > Speaker notes: Both children start before we await. This is concurrent; actual parallel execution depends on the dispatcher and work. The enclosing coroutineScope waits for its children. A failing child cancels its sibling, and cancelling the caller cancels both: structured concurrency makes ownership visible in the block. Source: https://kotlinlang.org/docs/composing-suspending-functions.html ### Typed authentication Slide 67: /lambda-world-functional-kotlin-services/#/67 ```kotlin import io.ktor.server.application.* import io.ktor.server.application.Application import io.ktor.server.routing.routing import opensavvy.spine.server.fail import presentation.snippets.s01suspend.slide19.Api import opensavvy.spine.server.route import opensavvy.spine.server.respond import presentation.snippets.s01suspend.slide19.CreateUser import presentation.snippets.s01suspend.slide19.UserAlreadyExists import presentation.support.* sealed interface Result data class Success(val user: User) : Result data object AlreadyExists : Result fun insertUser(createUser: CreateUser): Result = TODO() fun getAllUsers(): List = emptyList() //Example fun Application.users() = routing { route(Api.Users.list) { val users = getAllUsers() respond(users) } } ``` > **Type hint** `this: Routing` > **Type hint** `this: TypedRespondScope, Never, Parameters.Empty>` ### Typed authentication Slide 68: /lambda-world-functional-kotlin-services/#/68 > **`JwtUser`** — The `principal` is typed ```kotlin import io.ktor.server.auth.* import io.ktor.server.auth.jwt.* import com.auth0.jwt.algorithms.Algorithm import opensavvy.spine.server.route import presentation.snippets.s01suspend.slide19.Api enum class Role : AuthenticationRole { Admin } typealias JwtRole = Role data class JwtUser(val id: Long, val roles: Set = emptySet()) object env { val issuer = "issuer"; val secret = "secret" } fun getAllUsers(): List = emptyList() // Example val jwt: AuthenticationScheme = jwt("ktor-arrow-server") { verifier(env.issuer, "ktor-arrow-server", Algorithm.HMAC512(env.secret)) validate { val userId = it.getClaim("user_id", Long::class) ?: return@validate null JwtUser(userId) } } ``` ### Typed authentication Slide 69: /lambda-world-functional-kotlin-services/#/69 ```kotlin import io.ktor.server.auth.* import io.ktor.server.auth.jwt.* import com.auth0.jwt.algorithms.Algorithm import opensavvy.spine.server.route import presentation.snippets.s01suspend.slide19.Api import opensavvy.spine.server.respond import io.ktor.server.application.* import io.ktor.server.routing.routing enum class Role : AuthenticationRole { Admin } typealias JwtRole = Role data class JwtUser(val id: Long, val roles: Set = emptySet()) object env { val issuer = "issuer"; val secret = "secret" } fun getAllUsers(): List = emptyList() // Example val jwt: AuthenticationScheme = jwt("ktor-arrow-server") { } fun Application.users() = routing { authenticateWith(jwt) { route(Api.Users.list) { val user = call.principal val users = getAllUsers() respond(users) } } } ``` > **Type hint** `this: Routing` > **Type hint** `context(context(PrincipalContext, Unit))` > **Type hint** `this: TypedRespondScope, Never, Parameters.Empty>` ### Typed authentication Slide 70: /lambda-world-functional-kotlin-services/#/70 ```kotlin import io.ktor.server.auth.principal as typedPrincipal import io.ktor.server.auth.* import io.ktor.server.auth.jwt.* import com.auth0.jwt.algorithms.Algorithm import opensavvy.spine.server.route import presentation.snippets.s01suspend.slide19.Api import opensavvy.spine.server.respond import io.ktor.server.application.* import io.ktor.server.routing.routing enum class Role : AuthenticationRole { Admin } typealias JwtRole = Role data class JwtUser(val id: Long, val roles: Set = emptySet()) object env { val issuer = "issuer"; val secret = "secret" } fun getAllUsers(): List = emptyList() // Example val jwt: AuthenticationScheme = jwt("ktor-arrow-server") { } fun Application.users() = routing { authenticateWith(jwt) { route(Api.Users.list) { val user = call.principal val users = getAllUsers() respond(users) } } } context(ctx: PrincipalContext

) val

ApplicationCall.principal: P get() = this.typedPrincipal ``` > **Type hint** `this: Routing` > **Type hint** `context(context(PrincipalContext, Unit))` > **Type hint** `this: TypedRespondScope, Never, Parameters.Empty>` ### Typed authentication Slide 71: /lambda-world-functional-kotlin-services/#/71 > **`SchemeWithRoles = emptySet()) object env { val issuer = "issuer"; val secret = "secret" } fun getAllUsers(): List = emptyList() // Example val jwt: AuthenticationSchemeWithRoles> = jwt("ktor-arrow-server") { } .withRoles { it.roles } fun Application.users() = routing { authenticateWith(jwt, roles = [Role.Admin]) { route(Api.Users.list) { val user = call.principal val roles = user.roles val users = getAllUsers() respond(users) } } } ``` > **Type hint** `this: Routing` > **Type hint** `context(context(RolesContext, PrincipalContext, Unit))` > **Type hint** `this: TypedRespondScope, Never, Parameters.Empty>`