A service owns its work and its lifetime
Part of Functional Kotlin Services. Slides 3–50.
A service owns its work and its lifetime slide 3 ↗
What is `suspend`? slide 4 ↗
typealias Thunk<A> = () -> A
typealias IO<A> = suspend () -> AWhat is `suspend`? slide 5 ↗
suspend fun events(): List<Event>
suspend fun Event.process( ): Unit
Event— Extension function
fun events(): IO<List<Event>>
fun Event.process(): IO<Unit>What is `suspend`? slide 6 ↗
suspend fun events(): List<Event>
suspend fun Event.process( ): Unit {
val event: Event = this
}
Event— receiver of extension function
fun events(): IO<List<Event>>
fun Event.process(): IO<Unit>What is `suspend`? slide 7 ↗
suspend fun events(): List<Event>
suspend fun Event.process(): Unit
suspend fun program() {
val events = events()
events.process()
}fun events(): IO<List<Event>>
fun Event.process(): IO<Unit>
fun program(): IO<Unit> =
events()
.flatMap { it.process() }What is `suspend`? slide 8 ↗
suspend— suspend lambda
SuspendAppScope— lambda with receiver, allows callingexitApp(code)
fun SuspendApp(block: suspend SuspendAppScope.() -> Unit): Unitimport 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 ↗
resourceScope— Scope for resource management
server—installa server into theresourceScope
awaitCancellation— AwaitSIGTERM/SIGINTwhich cancels theSuspendApp\n-> cancels and awaits the runningsuspendlambda andCoroutineScope
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 ↗
ExitCase—Completed,CancelledorFailure
context(_: ResourceScope)
suspend fun <A> install(
acquire: suspend () -> A,
release: suspend (A, ExitCase) -> Unit,
): AServer as a Resource slide 11 ↗
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 ↗
launch— Starts a parallel task within theSuspendAppScope
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 ↗
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
Processors finish before dependencies close slide 14 ↗
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)
Configuring your server slide 15 ↗
@Serializable— Compiler plugin to generate serialization code
getAs<Config>— Read, and deserialize the configuration
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<Unit> = emptyFlow()
// Example
@Serializable
data class Config(val host: String, val port: Int)
fun main() = SuspendApp {
val config = ApplicationConfig("application.yaml").getAs<Config>()
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 ↗
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 ↗
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 ↗
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<String> = ["username too short", "email doesn't contain @"]
}
//Example
object Api : RootResource("api") { // api
object Users : StaticResource<Api>("users", Api) { // api/users
val list by get() // GET /v3/users
.response<List<User>>()
}
}Ktor Routes using Spine slide 19 ↗
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<String> = ["username too short", "email doesn't contain @"]
}
//Example
object Api : RootResource("api") { // api
object Users : StaticResource<Api>("users", Api) { // api/users
val list by get() // GET /v3/users
.response<List<User>>()
val create by post() // POST /api/users
.request<CreateUser>()
.response<User>()
.failure<UserAlreadyExists>(HttpStatusCode.Conflict)
.failure<InvalidUser>(HttpStatusCode.UnprocessableEntity)
}
}Calling Ktor Spine routes slide 20 ↗
Apache5— Support for many different clients across all KMP platforms
User— Handle all cases as defined by response and failures
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<Apache5Config>
Ktor Routes using Spine slide 21 ↗
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<CreateUser, User, Or<Or<Never, ByCode<UserAlreadyExists>>, ByCode<InvalidUser>>, Parameters.Empty>
When statement slide 22 ↗
sealed interface— Closed inheritance within this compilation unit (module)
@JvmInline— Valhalla (JEP 401) will bring value classes to JVM,\n@JvmInlineemulates it
data object— Singleton object
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<CreateUser, User, Or<Or<Never, ByCode<UserAlreadyExists>>, ByCode<InvalidUser>>, Parameters.Empty>
`Raise` adds an expected error to the signature slide 23 ↗
Raise<UserAlreadyExists>— CanRaiseaUserAlreadyExistserror
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<UserAlreadyExists>)
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<CreateUser, User, Or<Or<Never, ByCode<UserAlreadyExists>>, ByCode<InvalidUser>>, Parameters.Empty>
⚠ Compiler error at
insertUser: No context argument for_: Raise<UserAlreadyExists>found
`Raise` adds an expected error to the signature slide 24 ↗
routeWithRaise— Spine's Arrow-kt support bringsRaiseinto the context for all failures
body— Missing validation
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<UserAlreadyExists>)
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<InvalidUser>, Raise<UserAlreadyExists>)
Validation slide 25 ↗
(val value: String)— Can create invalid values
@JvmInline
value class Username(val value: String)Validation slide 26 ↗
private constructor— Enforce using smart-constructor
Raise<NonEmptyList<String>>— AccumulateStringerror messages intoNonEmptyList, at least one error or the success value
operator fun invoke— Custominvokeoperator allows forUsername(...)syntax
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<NonEmptyList<String>>)
operator fun invoke(value: String): Username = TODO()
}
}Validation slide 27 ↗
ensure— Defined oncontext(Raise<String>)so it short-circuits
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<NonEmptyList<String>>)
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 ↗
ensureOrAccumulate— Defined oncontext(Accumulate<String>)so it accumulates inNonEmptyList<String>
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<NonEmptyList<String>>)
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<String>, Raise<String>)
Validation slide 29 ↗
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<NonEmptyList<String>>)
operator fun invoke(value: String): Email =
accumulate {
ensureOrAccumulate(value.contains("@")) { "Email is invalid" }
Email(value)
}
}
}Type hint
context(Accumulate<String>, Raise<String>)
Validation slide 30 ↗
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<NonEmptyList<String>>)
fun CreateUserRequest.toCreateUser(): CreateUser = TODO()Validation slide 31 ↗
NonEmptyList<NonEmptyList— AccumulatingNonEmptyList<String>into aNonEmptyList
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<NonEmptyList<String>>)
fun CreateUserRequest.toCreateUser(): CreateUser =
withError({ errors: NonEmptyList<NonEmptyList<String>> ->
errors.reduce { acc, errors -> acc + errors }
}) {
}Validation slide 32 ↗
accumulating— LiftRaise<NonEmptyList<String>>intoAccumulate<String>
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<NonEmptyList<String>>)
fun CreateUserRequest.toCreateUser(): CreateUser =
withError({ errors: NonEmptyList<NonEmptyList<String>> ->
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<String>, Raise<String>)
Validation slide 33 ↗
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<String>)
data class CreateUser(val username: Username, val email: Email)
context(_: Raise<InvalidUser>)
fun CreateUserRequest.toCreateUser(): CreateUser =
withError({ errors: NonEmptyList<NonEmptyList<String>> ->
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<String>, Raise<String>)
Call directly in the route slide 34 ↗
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<InvalidUser>, Raise<UserAlreadyExists>)
`|.` skips the call on an error slide 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
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 ↗
Transaction— Type of the Exposed Typed SQL DSL
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<ResultRow>.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 ↗
PLSQLException—catchspecific errors and lift them to type signature
raise(UserAlreadyExists(— Raise error intocontext(Raise<UserAlreadyExists>)
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<ResultRow>.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<UserAlreadyExists>)
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 ↗
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<UserAlreadyExists>)
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<ResultRow>.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<UserAlreadyExists>)
suspend fun insertUserResult(database: Database, create: CreateUser): User =
transaction(database) {
insertUser(create)
}Type hint
context(Raise<UserAlreadyExists>)
Type hint
this: Transaction
Ktor Routes using Spine slide 39 ↗
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<UserAlreadyExists>)
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<AlreadyExists>, Raise<InvalidUser>))
Type hint
this: Transaction
Processors finish before dependencies close slide 40 ↗
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 ↗
user— Smart castedUser?toUser
fun greeting(user: User?): String =
if (user == null) "Unknown user" else "Hello, ${user.name}"`when` handles absence and guarded values slide 42 ↗
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 ↗
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 ↗
when (access)— Prefixed type is known
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 ↗
if access.user.active— if-guard checks condition
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 ↗
val (email, name)— Destructure by matching property names
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 ↗
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 referenceemail2on receiver of typeUser
Experimental Kotlin 2.4.20
-Xname-based-destructuring=complete
Collection literals slide 48 ↗
val list: List<String> = ["a", "bb", "ccc"]
val set: Set<String> = ["a", "bb", "ccc"]
val iterable: Iterable<String> = ["a", "bb", "ccc"]Custom collection literals slide 49 ↗
import arrow.core.nonEmptyListOf
import arrow.core.NonEmptyList
data class NonEmptyList<A>(val head: A, val tail: List<A>)
val literal: NonEmptyList<String> =
["a", "bb", "ccc"]
val nonEmptyList = NonEmptyList("a", ["bb", "ccc"])⚠ Compiler error at
["a", "bb", "ccc"]:NonEmptyList<String>for collection literal does not\ndefine operatorofand is not a supertype ofList
Custom collection literals slide 50 ↗
import arrow.core.nonEmptyListOf
import arrow.core.NonEmptyList
data class NonEmptyList<A> private constructor(val head: A, val tail: List<A>) {
companion object {
operator fun <A> of(head: A, vararg tail: A) =
NonEmptyList(head, tail.toList())
}
}
val literal = ["a", "bb", "ccc"]
val nonEmptyList =
NonEmptyList("a", ["bb", "ccc"])
val empty: NonEmptyList<String> = []⚠ Compiler error at
NonEmptyList("a", ["bb", "ccc"]):constructor<A>(head: A, tail: List<A>): NonEmptyList<A>is private
⚠ Compiler error at
[]: No value passed for parameterhead