Vert.x for Kotlin

Overview

Vert.x for Kotlin

Build Status GitHub license Kotlin version badge Coroutines version badge

This is the repository for Kotlin language support for Vert.x 3.

The following modules are available in this project:

  • vertx-lang-kotlin contains extension functions for the majority of Vert.x libraries.

  • vertx-lang-kotlin-coroutines contains coroutines support for Vert.x.

Contributing

Extending Vert.x for Kotlin

Kotlin extensions are developed in this directory.

For instance vertx-core extensions are in the io.vertx.kotlin.core package, etc…​

Extensions needs to be tested and documented.

Bumping Kotlin version

There are a couple of rules to follow before increasing the project versions:

  • If changing one between kotlin and kotlinx.coroutines version, make sure that all transitive dependencies, like kotlin-stdlib, still match between the two versions.

  • If changing the kotlin version, open a PR also on vertx-codetrans

Kotlin evolves fast, so just change the project versions, test it, and shot a PR.

Comments
  • Generate coroutine methods

    Generate coroutine methods

    This pull request generates suspending methods of the same name for methods that has kind METHOD_FUTURE.

    I will add some tests and clean up the template file later.

    I am new to pretty much everything in this pull request, please bear with me if I made some stupid mistakes.

    duplicate 
    opened by phiSgr 49
  • Coroutine suspend generated method naming scheme

    Coroutine suspend generated method naming scheme

    Current Kotlin suspend generated method are named with an Await suffix:

    vertx.deployVerticle(verticle, Handler { ... }) 
    
    // becomes
    
    val id = vertx.deployVerticleAwait(verticle);
    

    this issue gathers proposal and opinions about the best naming for 3.6

    question 
    opened by vietj 30
  • Cannot get vertx-lang-kotlin-coroutines to work

    Cannot get vertx-lang-kotlin-coroutines to work

    See minimal reproducer project:

    https://github.com/lukehutch/kotlinproj/tree/master

    [ERROR] Failed to execute goal org.jetbrains.kotlin:kotlin-maven-plugin:1.3.21:compile (compile) on project kotlinproj: Compilation failure: Compilation failure: 
    [ERROR] /tmp/kotlin-proj/src/main/java/kotlinproj/kotlinproj/Test.kt:[18,37] Unresolved reference: await
    [ERROR] /tmp/kotlin-proj/src/main/java/kotlinproj/kotlinproj/Test.kt:[21,72] Unresolved reference: await
    

    This is with 4.0-SNAPSHOT versions.

    question 
    opened by lukehutch 25
  • Created reified alternative to HttpRequest<Buffer>.as

    Created reified alternative to HttpRequest.as

    I used the same test structure as in the web-client library.

    I didn't create the extension on HttpRequest<T> because the Kotlin compiler is not smart enough to understand that the first type is already available in the receiver, making necessary to do the call like requestWitBufferResponse.like<Buffer, ToClass>().send(..)

    opened by gmariotti 21
  • Removed deprecated usage of internal class ArrayChannel

    Removed deprecated usage of internal class ArrayChannel

    • Use an internal channel instead of a ReadStream to implement the ReceiveChannelHandler.
    • Removed usage of internal ArrayChannel.

    In progress @vietj:

    • Unfortunately, I'm not able to figure it out what is the problem with the HttpParserTest, if I change line 68 from chunk.length() - 2 to chunk.length() the test actually pass, but I don't understand why. I'd appreciate if you could help me there.
    • I think that the change I made in the ReadStream<T>.toChannel resumes the stream immediately after a receive/receiveOrNull/poll is successful, but I'm not sure this is what you wanted.
    opened by gmariotti 20
  • Updated coroutines to 0.30.0 and removed (most of) deprecated code

    Updated coroutines to 0.30.0 and removed (most of) deprecated code

    • CoroutineVerticle implements now CoroutineScope based on https://github.com/Kotlin/kotlinx.coroutines/issues/410
    • Used GlobalScope.launch over launch when a verticle doesn't exist.
    • Renamed tests for improving readability.
    • Reverted to coroutines 0.30.0 to avoid warnings from atomicfu-common:0.11.10 that uses kotlin-stdlib-common:1.3.0-rc-131.

    Next steps:

    • Adjust documentation for coroutines module. (how should I update the examples in index.adoc?)
    • Remove deprecated ArrayChannel in ReceiveChannelHandler.
    • Make project depend on Kotlin 1.3.x and support the latest coroutines version.
    opened by gmariotti 19
  • Basic coroutine support

    Basic coroutine support

    This is a basic coroutine support for Kotlin using only core dependencies (no kotlinx.coroutine).

    I am not Vert.x expert, so any suggestion is well accepted.

    Please send me your feedback.

    opened by fvasco 18
  • kotlin version

    kotlin version

    3.5.1-SNAPSHOT will ship with version 1.2.20 of kotlin. see #44 Latest version as of today is 1.2.21.

    It would be great if we were able to specify the kotlin version in our projects. Right now, I am excluding kotlin dependencies from vertx-lang-kotlin:

    compile(group = "io.vertx", name = "vertx-lang-kotlin", version = vertx_version) { exclude(group = "org.jetbrains.kotlin") }

    Will this lead to incompatibilities, or is this is a reasonable way to keep kotlin version up to date?

    opened by psartini 16
  • Upgrade to Kotlin 1.3.60

    Upgrade to Kotlin 1.3.60

    Also upgraded the Kotlin coroutines library.

    ReceiveChannelHandler had to be added a field and a method due to additions in ReceiveChannel. These are internal APIs so I made them throw NotImplementedError (through TODO("...")) and all tests still pass so it doesn't seem to be on a typical call path.

    enhancement 
    opened by jponge 14
  • Add Testing Guide

    Add Testing Guide

    Kotliners (Kotlin developers) using Vert.x don't have a clear way to do testing. The new testing guide provides guidance on how to test Vert.x code that is Kotlinic (idiomatic Kotlin). Currently the guide is a draft version and hasn't been converted to AsciiDoc. More important to ensure that the approach for the guide is correct before getting the formatting right.

    opened by napperley 12
  • SQLClient connection leak in getConnectionAwait(), leads to a deadlock

    SQLClient connection leak in getConnectionAwait(), leads to a deadlock

    Version

    • vertx 3.9.7
    • kotlin 1.5.0 (tested also on 1.4.32)
    • open-jdk-14

    Context

    I observed a resource leak in JDBCClient, namely in the vertx-lang-kotlin:3.9.7 function

    suspend fun SQLClient.getConnectionAwait(): SQLConnection 
    

    The problem is if coroutine calling getConnectionAwait() is cancelled before the handler on the following method is called:

    SQLClient getConnection(Handler<AsyncResult<SQLConnection>> handler);
    

    If such situation happens (e.g., calling REST connection is terminated / timed out), the obtained connection, passed to the handler, is not closed and returned to the pool. This causes leakage, depleting all free connections (if using with connection pool like C3P0). The program ends up in the terminal state without usable DB connection.

    I believe that the problem lies in the https://github.com/vert-x3/vertx-lang-kotlin/blob/d991b1683c05c6d5081ee2f6513838c9c1dc977c/vertx-lang-kotlin-coroutines/src/main/java/io/vertx/kotlin/coroutines/VertxCoroutine.kt#L63

    suspend fun <T> awaitEvent(block: (h: Handler<T>) -> Unit): T {
      return suspendCancellableCoroutine { cont: CancellableContinuation<T> ->
        try {
          block.invoke(Handler { t ->
            cont.resume(t) // <---- here, if cont is cancelled, t remains opened
          })
        } catch (e: Exception) {
          cont.resumeWithException(e)
        }
      }
    }
    

    I solved the problem by implementing the coroutine bridging on my own with a if-branch handling cancelled coroutine, such as

        try {
          block.invoke(Handler { t ->
            if (cont.isActive)
              cont.resume(t)
            } else {
              t.close()  // <--- close connection if coroutine is already cancelled when handler is invoked
            } 
          })
        } catch (e: Exception) {
          cont.resumeWithException(e)
        }
    

    I noticed that this method is deprecated https://github.com/vert-x3/vertx-jdbc-client/issues/196 https://github.com/vert-x3/vertx-lang-kotlin/blob/c1938f890b711734d3e191d274422d3f3098726a/vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/ext/sql/SQLClient.kt#L64-L65 but this may help others having the same issues if they didn't migrate yet.

    Also, vertx 3 API is planned to be supported also in vertx 4 so this race condition can potentially affect a lot of users, making their servers unresponsive. Btw was it deprecated also because of this potential issue?

    The similar issues can be present also elsewhere in the same pattern, i.e., call await method (coroutine), wait for handler, when handler is called, coroutine is already cancelled, thus resource obtained & returned in the handler is not properly closed.

    Do you have a reproducer?

    Not yet, I can create one if description is not enough.

    Steps to reproduce

    1. setup MySQL JDBC-backed demo
    2. spawn 2000 worker threads simulating clients, each querying the database (code below), let clients timeout randomly
    3. watch number of failures / timeouts
    val rnd = Random()
    withTimeout(rnd.nextLong().rem(1000L)) {
        dbClient.getConnectionAwait().use {
            it.queryAwait("SELECT 1")
        }
    }
    
    wontfix 
    opened by ph4r05 11
  • Support for Mutiny for CoroutineVerticle for awaitSuspending Support

    Support for Mutiny for CoroutineVerticle for awaitSuspending Support

    It would be great to have Mutiny support in this project for CoroutineVerticle as Mutiny is now a preferred Reactive API and has support for Coroutines. This would allow mixing of Reactive APIs with Mutiny with the Coroutines via suspend fun.

    Here is some working example code to make it possible to use the io.smallrye.mutiny.coroutines.awaitSuspending with the CoroutineVerticle.

    import io.vertx.core.Context
    import io.vertx.kotlin.coroutines.CoroutineVerticle
    import io.vertx.kotlin.coroutines.dispatcher
    import io.vertx.mutiny.core.Vertx
    import kotlinx.coroutines.SupervisorJob
    import kotlin.coroutines.CoroutineContext
    
    abstract class MutinyCoroutineVerticle : CoroutineVerticle() {
    
        protected lateinit var vertx: Vertx
        private lateinit var context: Context
    
        override val coroutineContext: CoroutineContext by lazy { context.dispatcher() + SupervisorJob() }
    
        override fun init(vertx: io.vertx.core.Vertx, context: Context) {
            this.vertx = Vertx(vertx)
            this.context = context
        }
    }
    
    

    Here is an example of using awaitSuspending().

    import io.smallrye.mutiny.coroutines.awaitSuspending
    import io.vertx.core.DeploymentOptions
    import io.vertx.mutiny.core.Vertx
    import kotlin.Array
    import kotlin.String
    
    suspend fun main(args: Array<String>) {
        val vertx = Vertx.vertx()
        println("Deployment Starting")
        vertx.deployVerticle({ MainVerticle() }, DeploymentOptions()).awaitSuspending()
        println("Deployment completed")
    }
    
    class MainVerticle : MutinyCoroutineVerticle() {
        private var counter = 0L
    
        override suspend fun start() {
    
            vertx.periodicStream(2000L)
                .toMulti()
                .subscribe().with { tick -> counter++ }
    
            vertx.createHttpServer()
                    .requestHandler { req -> req.response().endAndForget("@$counter") }
                    .listen(8080)
                    .awaitSuspending()
       }
    }
    
    enhancement 
    opened by murphye 0
  • Add some possibly useful code ported from https://github.com/huanshankeji/kotlin-common/tree/main/vertx

    Add some possibly useful code ported from https://github.com/huanshankeji/kotlin-common/tree/main/vertx

    Motivation:

    Hi, Vert.x Maintainers. We have been developing our projects in Kotlin with the Vert.x toolkit as the core of the backend. It's been quite smooth and this project provides a lot of useful extensions in Kotlin. During our development, we came up with a few more common extensions in our shared code repository, which we thought could be ported back to this project and made universally available.

    We have tried to pick the less opinionated code from our common project in this PR so it's generally useful to most developers using Vert.x in Kotlin. If there is any code that is not appropriate to be added back to this repository, just feel free to remove it or make further changes as it suits your needs. Or if there is none to be added, just close this PR.

    Thank you.

    opened by ShreckYe 11
  • Starting a coroutine on a vert.x worker thread runs it on the same thread but should hand it over to the event loop thread

    Starting a coroutine on a vert.x worker thread runs it on the same thread but should hand it over to the event loop thread

    Questions

    Starting a coroutine on a vert.x worker thread ends up running it inline, that is on the very same thread, instead of the event loop thread. This seems like a bug because it contradicts the KDoc on Context.dispatcher()

    Version

    vert.x 4.1.5, kotlin 1.5.31, coroutines 1.5.2

    Context

    VertxCoroutineExecutor

    private class VertxCoroutineExecutor(val vertxContext: Context) : AbstractExecutorService(), ScheduledExecutorService {
    
      override fun execute(command: Runnable) {
        if (Vertx.currentContext() != vertxContext) {
          vertxContext.runOnContext { command.run() }
        } else {
          command.run()
        }
      }
    

    I suspect the code might be lacking a check for isOnWorkerThread e.g. the if-statement should look like:

    if (Vertx.currentContext() != vertxContext || Context.isOnWorkerThread()) {
          vertxContext.runOnContext { command.run() }
    
    image

    Do you have a reproducer?

                awaitBlocking {
                    launch {
                        println(Thread.currentThread().name)
                    }
                }
    

    Prints

    vert.x-worker-thread-0 @coroutine#23
    
    bug 
    opened by bbyk 2
Owner
Eclipse Vert.x
Eclipse Vert.x
Real life Kotlin Multiplatform project with an iOS application developed in Swift with SwiftUI, an Android application developed in Kotlin with Jetpack Compose and a backed in Kotlin hosted on AppEngine.

Conferences4Hall Real life Kotlin Multiplatform project with an iOS application developed in Swift with SwiftUI, an Android application developed in K

Gérard Paligot 98 Dec 15, 2022
Android + Kotlin + Github Actions + ktlint + Detekt + Gradle Kotlin DSL + buildSrc = ❤️

kotlin-android-template ?? A simple Github template that lets you create an Android/Kotlin project and be up and running in a few seconds. This templa

Nicola Corti 1.5k Jan 3, 2023
LifecycleMvp 1.2 0.0 Kotlin is MVP architecture implementation with Android Architecture Components and Kotlin language features

MinSDK 14+ Download Gradle Add to project level build.gradle allprojects { repositories { ... maven { url 'https://jitpack.io' }

Robert 20 Nov 9, 2021
Opinionated Redux-like implementation backed by Kotlin Coroutines and Kotlin Multiplatform Mobile

CoRed CoRed is Redux-like implementation that maintains the benefits of Redux's core idea without the boilerplate. No more action types, action creato

Kittinun Vantasin 28 Dec 10, 2022
👋 A common toolkit (utils) ⚒️ built to help you further reduce Kotlin boilerplate code and improve development efficiency. Do you think 'kotlin-stdlib' or 'android-ktx' is not sweet enough? You need this! 🍭

Toolkit [ ?? Work in progress ⛏ ?? ??️ ?? ] Snapshot version: repositories { maven("https://s01.oss.sonatype.org/content/repositories/snapshots") }

凛 35 Jul 23, 2022
An app architecture for Kotlin/Native on Android/iOS. Use Kotlin Multiplatform Mobile.

An app architecture for Kotlin/Native on Android/iOS. Use Kotlin Multiplatform Mobile. 项目架构主要分为原生系统层、Android/iOS业务SDK层、KMM SDK层、KMM业务逻辑SDK层、iOS sdkfra

libill 4 Nov 20, 2022
Provides Kotlin libs and some features for building Kotlin plugins

Kotlin Plugin Provides Kotlin libs and some features for building awesome Kotlin plugins. Can be used instead of CreeperFace's KotlinLib (don't use to

null 3 Dec 24, 2021
Notes-App-Kotlin - Notes App Built Using Kotlin

Notes-App-Kotlin Splash Screen Home Page Adding New Notes Filter Feature Search

Priyanka 4 Oct 2, 2022
Kotlin-client-dsl - A kotlin-based dsl project for a (Client) -> (Plugin) styled program

kotlin-client-dsl a kotlin-based dsl project for a (Client) -> (Plugin) styled p

jackson 3 Dec 10, 2022
A Kotlin Native program to show the time since a date, using Kotlin LibUI

TimeSince A Kotlin Native program to show the time since a date, using Kotlin LibUI Report Bug . Request Feature About The Project TimeSince is a Kotl

Russell Banks 2 May 6, 2022
RoomJetpackCompose is an app written in Kotlin and shows a simple solution to perform CRUD operations in the Room database using Kotlin Flow in clean architecture.

RoomJetpackCompose is an app written in Kotlin and shows a simple solution to perform CRUD operations in the Room database using Kotlin Flow in clean architecture.

Alex 27 Jan 1, 2023
Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client

Practical Kotlin Multiplatform on the Web 본 저장소는 코틀린 멀티플랫폼 기반 웹 프로그래밍 워크숍(강좌)을 위해 작성된 템플릿 프로젝트가 있는 곳입니다. 워크숍 과정에서 코틀린 멀티플랫폼을 기반으로 프론트엔드(front-end)는 Ko

SpringRunner 14 Nov 5, 2022
Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client

Building a Full Stack Web App with Kotlin Multiplatform 본 저장소는 INFCON 2022에서 코틀린 멀티플랫폼 기반 웹 프로그래밍 핸즈온랩을 위해 작성된 템플릿 프로젝트가 있는 곳입니다. 핸즈온 과정에서 코틀린 멀티플랫폼을

Arawn Park 19 Sep 8, 2022
Kotlin library for Android

KAndroid Kotlin library for Android providing useful extensions to eliminate boilerplate code in Android SDK and focus on productivity. Download Downl

Paweł Gajda 890 Nov 13, 2022
Type-safe time calculations in Kotlin, powered by generics.

Time This library is made for you if you have ever written something like this: val duration = 10 * 1000 to represent a duration of 10 seconds(in mill

Kizito Nwose 958 Dec 10, 2022
📒 NotyKT is a complete 💎Kotlin-stack (Backend + Android) 📱 application built to demonstrate the use of Modern development tools with best practices implementation🦸.

NotyKT ??️ NotyKT is the complete Kotlin-stack note taking ??️ application ?? built to demonstrate a use of Kotlin programming language in server-side

Shreyas Patil 1.4k Jan 4, 2023
A Kotlin DSL wrapper around the mikepenz/MaterialDrawer library.

MaterialDrawerKt Create navigation drawers in your Activities and Fragments without having to write any XML, in pure Kotlin code, with access to all t

Márton Braun 517 Nov 19, 2022
Kotlin-based modern RecyclerView rendering weapon

Read this in other languages: 中文, English, Changelog Yasha Item introduction: Kotlin-based modern RecyclerView rendering weapon Item Features: No Adap

Season 514 Dec 21, 2022
{ } Declarative Kotlin DSL for choreographing Android transitions

Transition X Kotlin DSL for choreographing Android Transitions TransitionManager makes it easy to animate simple changes to layout without needing to

Arunkumar 520 Dec 16, 2022