Auto Added by WPeMatico

Ktor 2024 Roadmap DI Update

Since the Ktor Roadmap for 2024 was published there have been a lot of questions regarding Dependency Injection (DI). Specifically how Ktor will be changed to support DI, and to integrate existing DI frameworks. This work is still in its early stages, but we would like to clarify our intentions and invite feedback.

First and foremost, we would stress that:

  1. There will never be any requirement to use a DI framework with Ktor.
  2. Ktor itself will never include a DI framework as part of its design.

The proposed feature is solely for users who wish to combine DI with their Ktor services. We want to help existing DI frameworks integrate with Ktor as seamlessly as possible.

How the proposed Dependency Injection feature will work

Let’s consider how we could use Koin within a Ktor route. Imagine the unfortunate scenario where we require seven separate services in order to purchase the contents of the customer’s shopping cart:

fun Application.root() {
   install(Koin) {
      modules(module {
         single { PricingRules() }
         single { DiscountRules() }
         single { StockCheckRepository() }
         single { DeliveryRoutePlanner() }
         single { PaymentGateway() }
         single { CreditRatingChecker() }
         single { PastPurchasesRecord() }
      })
   }
   ...
}

The DI framework will create and inject the dependencies for us. But because Ktor has no knowledge of Koin we have to specify the dependencies manually. Also the injection process is complex, requiring Delegated Properties and Type Parameters.

Our proposal is to replace the above with something like this:

fun Application.root() {
   install(Koin)
   ...
}

This will be achieved as follows:

  1. You will be able to select which DI framework (if any) you wish to use in the Ktor Project Generator. We hope to support all popular DI frameworks.
  2. The presence of a DI framework will be noted by the Ktor Gradle plugin. It will automatically find all the components managed by that framework. 
  3. The plugin will add new methods to these types, which will enable you to inject them in the simplest possible way.

Our goal is to radically simplify how DI is used within Ktor, without adding any extra complexity. The code generated by the Ktor Gradle plugin will be fully debuggable, and the pipeline architecture will not be modified at all. You will be able to use this new approach in both services and tests.

Hopefully, fans of DI will find this a great improvement, but like DI itself, this will be a completely optional feature. You will still be able to use the DI framework’s native syntax if it suits you better. 

As always we remain committed to Ktor’s founding principles. Every feature we add is aligned with the vision of a no-magic, lightweight solution that is minimalist, simple, flexible, and fast. To help shape the future of Ktor, please join the discussion on the Ktor channel of Kotlinlang Slack (request an invite to Slack).

Continue ReadingKtor 2024 Roadmap DI Update

The Ktor Roadmap for 2024

As in 2023 and 2022, we have been working on a roadmap for our development of Ktor for the year ahead. In the interests of transparency and accountability, we would like to share our plans with you here.

Our ongoing plan

Our ongoing plans and goals for Ktor remain consistent with previous years. We aim to keep the framework lightweight, flexible, and transparent, so our users can easily create powerful and maintainable services and clients.

With each new release, we try to improve the quality and performance of the features we provide, while simultaneously expanding our ecosystem of Ktor plugins. This involves introducing new plugins to simplify existing use cases (like transaction handling) and adding support for new ones (such as Observability and gRPC).

Along with improving the core product, we want to make the development experience easier for our users. We aim to make the plugin ecosystem easier to work with and to remove impediments to community contributions. We are also working to improve the range, quality, and variety of the documentation we provide.

Lastly, we want to take advantage of the stabilization of Kotlin Multiplatform (KMP) and the growing ecosystem of multiplatform libraries. Our goal is to make the benefits of KMP available to Ktor developers and empower them to create multiplatform applications.

New features

We intend to deliver the following new functionality in 2024:

OpenTelemetry plugins

We plan to introduce OpenTelemetry plugins for Ktor Client and Server, which will enable you to generate telemetry data (metrics, logs, and traces) and advertise it for collection.

gRPC based services

We have already been working to add gPRC support. In 2024, we will integrate gRPC into both Ktor Client and Server via an idiomatic Kotlin implementation. This will make creating and consuming gRPC-based services as natural and familiar as HTTP and REST.

Migration to Kotlinx-io in Ktor 3.0.0

Kotlinx-io is a multiplatform library that provides abstractions for data sources and destinations. Before Ktor 3.0.0 becomes final, we intend to replace the existing bespoke networking types with those provided by Kotlinx-io. This will make it much easier for creators of multiplatform libraries to support Ktor Client and Server. With this update, the existing IO functionality is now deprecated and will eventually be removed.

Add support for managed transactions

At present, Ktor services require manual management of database transactions, which is appropriate in complex scenarios. However, in many cases, it is preferable to start a transaction at the beginning of the request and commit it at the end, provided there are no errors.

In 2024, we will introduce an official plugin that implements this behavior. This will simplify database access while providing support for recovering from SQL and application-specific exceptions.

Simplified dependency injection

Until now, we have been agnostic on dependency injection (DI) libraries, preferring to allow users to integrate their preferred products as they see fit. However, many users have asked for explicit recommendations on how to integrate frameworks like Koin into Ktor-based services.

In response to this, we will officially add support for DI into Ktor Server in 2024, and publish guidelines on how best to integrate existing DI libraries.

Making Ktor development better

Along with adding new features to Ktor, we will be making changes that simplify the development process and expand your potential options:

Improved documentation

Based on the feedback we received over the past year, our focus for 2024 is on enhancing current content quality and expanding support with new materials. Our primary goal is to make the learning journey more flexible and straightforward – a goal we aim to achieve over several iterations:

  • Extending, improving, and streamlining the tutorials in the Getting Started sections of the Ktor Server and Ktor Client documentation.
  • Addressing cloud deployment and configuration topics.
  • Introducing a comprehensive guide on full-stack development with Kotlin Multiplatform.
  • Increasing the scope of API coverage in our documentation.

We are also planning structural changes. Tutorials will seamlessly complement each other, interlinking topics more efficiently, and Server and Client content will be reorganized to ensure clearer distinctions.

All of these additions will take advantage of a modernized look and feel, plus integration with the documentation for other JetBrains frameworks and libraries.

A plugin registry

Currently, the online project generator only offers plugins created by the Ktor team. While users can create and integrate their own plugins into services, there is no way to register them for other teams to use. This impedes the growth of the Ktor community.

To fix this, we will introduce a mechanism for accepting third-party Ktor plugins. 

This will consist of:

  • A new, simplified format for creating Ktor plugins. This format will enable you to include all of the information needed to register and display the plugin within the project generator.
  • A new version of the project generator, with support for registering external plugins.
  • A procedure for submitting a pull request to the Ktor team in order to begin the process of evaluating and registering a third-party plugin. 

A command line tool

At present, we recommend creating new Ktor-based projects using either the online project generator or the wizard in IntelliJ IDEA Ultimate. While these two methods cover most scenarios, there is demand for a command line-based alternative. This would allow users to create and modify projects within the terminal or shell.

In response to this demand, we will publish a CLI Tool for Ktor in 2024.

Conclusions

We hope these plans sound exciting and address any outstanding issues you may have with the framework. Thanks to everyone who helps keep the Ktor community flourishing and expanding, whether through contributions, feedback, patronage, or advocacy. If you would like to comment on these plans or suggest additional features, we encourage you to join the discussion on the Ktor channel of Kotlinlang Slack (request an invite to Slack).

Continue ReadingThe Ktor Roadmap for 2024

Server-Side Development with Kotlin: Frameworks and Libraries

It is quite common to use existing frameworks and libraries for backend application development. If we look at most of the popular frameworks in the Java ecosystem, many of them actually support Kotlin out of the box. There are a lot of Java libraries too. You can use these frameworks and libraries in your Kotlin programs thanks to Kotlin’s flawless Java interoperability.


Kotlin is an excellent choice for server-side application development. Go to the Kotlin for server-side page to learn more!


This blog post is partially based on presentation content from the Kotlin 1.4 Online Event. You can watch the full video on our YouTube channel.

Spring Framework

The most popular and feature-rich framework in the ecosystem is Spring. Approximately half of all projects in the JVM ecosystem now use Spring as the framework of choice. The previous blog post about Kotlin for server-side development includes stories from Atlassian and Expedia who use Spring Boot for their projects.

Kotlin is one of the four major themes for Spring Framework 5.x. A number of extensions were added to the Spring core API specifically to provide better support for Kotlin.

In fact, Spring’s official documentation features code samples in both Java and Kotlin. This is very convenient if you’re new to Kotlin, because you can see the code sample in Java and then immediately see its Kotlin equivalent and so understand the idioms faster.

The start.spring.io project generator also supports Kotlin along with Java and Groovy.

The number of Spring tutorials is growing. We recommend that you start with the Building web applications with Spring Boot and Kotlin tutorial.

As support for Kotlin in Spring Framework is being improved, we had the privilege to host Sebastien Deleuze with his presentation about The State of Kotlin Support in Spring at the Kotlin 1.4 Online Event this year. See the video below.

An interesting new addition to Spring is the project Spring Fu. It is designed to configure Spring Boot with code in a declarative way. The Kotlin variety of the configuration DSL looks quite nice:

val app = webApplication {
	logging {
		level = LogLevel.DEBUG
	}
	beans {
		bean<SampleService>()
	}
	webMvc {
		port = if (profiles.contains("test")) 8181 else 8080
		router {
			val service = ref<SampleService>()
			GET("/") {
				ok().body(service.generateMessage())
			}
			GET("/api") {
				ok().body(Sample(service.generateMessage()))
			}
		}
		converters {
			string()
			jackson {
				indentOutput = true
			}
		}
	}
}

This new approach to configuration in Spring promises faster startup times and lower memory consumption, and it is a good fit with GraalVM native image thanks to its reflection-less approach.

Ktor

Ktor is a framework created and maintained by JetBrains. It was built with Kotlin from the ground up. Ktor encourages a minimalistic approach to application design, as you only need to configure the functionality that your project requires. Using Kotlin coroutines, Ktor is truly asynchronous and highly scalable. Ktor also includes an HTTP client that is implemented as a multiplatform library and is widely used in mobile application development with Kotlin.

Our previous blog post covers JetBrains Space and Adobe Experience Platform projects that use Ktor because of its support for asynchronous programming.

At Kotlin 1.4 Online Event, Hadi Hariri gave a presentation about the current state of the Ktor project and its future plans. See the video below.

Here are a few tutorials we recommend for learning about Ktor:

More web frameworks

Of course, Spring and Ktor are not the only frameworks in the JVM ecosystem and there are plenty of other frameworks that you can use with Kotlin. Take a look at Micronaut, Quarkus, Javalin, SparkJava, Vaadin, CUBA, and Vert.x. This is just a small list of the frameworks available. All these frameworks have either code samples in Java and Kotlin side by side or have dedicated tutorials on how to use the framework with Kotlin.

There are also a number of frameworks that are implemented in Kotlin. For instance, http4k, and Hexagon.

Database access

Backend applications often rely on database access. One of the most popular libraries today for working with databases is the Exposed library. It is an ORM framework for Kotlin that offers two levels of database access: a typesafe SQL-wrapping DSL, and lightweight data access objects.

Here’s a very simple example using Exposed:

object Cities : Table() {
   val id = integer("id").autoIncrement().primaryKey() // Column<Int>
   val name = varchar("name", 50) // Column<String>
}

Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")

transaction {
   create(Cities)

   val saintPetersburgId = Cities.insert {
       it[name] = "St. Petersburg"
   } get Cities.id

   val munichId = Cities.insert {
       it[name] = "Munich"
   } get Cities.id

   Cities.insert {
       it[name] = "Prague"
   }

println("All cities:")

for (city in Cities.selectAll()) {
   println("${city[Cities.id]}: ${city[Cities.name]}")
}

As you might have guessed, Exposed is not the only library that you can use with Kotlin for database access. You can use jdbi, jooq, JPA with Spring Data, and even just pure JDBC API to access databases from Kotlin code.

Testing

Testing a vital part of application development. JUnit and TestNG are perfectly fine for implementing unit tests in Kotlin. But there are more additional libraries that are great for testing in Kotlin:

  • Spek – a Kotlin-based Specification Testing framework for the JVM.
  • Kotest – a testing library with support for Kotlin multiplatform projects.
  • MokK – a mocking library for Kotlin tests.
  • Kotlin Power Assert – an amazing compiler plugin for Kotlin that enables the diagramming of assert function calls, making diagnosis of test failures a breeze.

Other libraries

Aside from handling HTTP requests and accessing databases, applications are often required to communicate with other services using specific protocols, perform decoding/encoding of data in various formats, and many other things. Here are a few libraries that will be useful for application development with Kotlin.

JSON is the universally accepted standard format for sending data between web servers and browsers. There are awesome JSON libraries available in the Java ecosystem and they are great for use in Kotlin programs too. Jackson and gson are the most popular Java libraries for working with JSON. However, there are also libraries that are implemented with Kotlin from scratch. Klaxon is a good example. Also kotlinx.serialization was recently released and it provides JSON support.

gRPC is a high-performance, open-source, universal RPC framework. Kotlin is now supported by gRPC.

RSocket is also gaining popularity as a protocol for use in building microservices. Kotlin integration was recently added to RSocket.

To work with GraphQL there’s graphql-kotlin library maintained by Expedia Group engineers.

These are just a few examples. In fact, there is a long list of Kotlin libraries maintained by the community where you’re sure to find a library for the task at hand. However, we’d like to point out that, thanks to Java interoperability, it is also possible to use virtually any Java library with Kotlin.

Additional Tools

Code quality is an important topic for Kotlin too! Thanks to the type system, especially null-safety, Kotlin is quite a safe programming language. However, there is still a need for code style checks. That’s the part that is currently implemented via additional tools.

Ktlint is a static code analysis tool maintained by Pinterest. It is a 2-in-1 tool that provides linting and formatting (supported via EditorConfig) for Kotlin code.

Detekt is a static code analysis tool that operates with the abstract syntax tree provided by the Kotlin compiler. It is easy to set up with Gradle and there’s also an IntelliJ IDEA plugin that simplifies configuration.

Generating API documentation from source code is also an important part of software project development. In Kotlin, we can use Dokka for this task. It is a documentation engine for Kotlin. Just like Kotlin itself, Dokka fully supports mixed-language Java/Kotlin projects. It understands standard Javadoc comments in Java files and KDoc comments in Kotlin files, and can generate documentation in multiple formats including standard Javadoc, HTML, and Markdown.

Summary

Kotlin was initially designed as an alternative JVM programming language, meaning that Kotlin can be used anywhere where Java is used. Thanks to Java interoperability, it is easy to use any of the existing frameworks and libraries that are familiar to Java developers. This all greatly simplifies the adoption of Kotlin for application development on the JVM.

The current state of Kotlin support in the ecosystem is at the stage where even big projects and companies are confidently adopting it. You can read about a few notable examples of such projects in the previous blog post, Productive Server-Side Development With Kotlin: Stories From The Industry

Continue ReadingServer-Side Development with Kotlin: Frameworks and Libraries

End of content

No more pages to load