Core server functionality for the Ktor asynchronous web framework, providing essential building blocks for HTTP servers including application lifecycle management, routing foundations, request/response handling, and plugin architecture specifically compiled for JVM targets.
—
Engine abstraction layer for different server implementations providing a unified interface for HTTP server management, environment configuration, and connector setup for various server backends like Netty, Jetty, and CIO.
Core interface for server engine implementations providing lifecycle management and environment access.
/**
* Interface for server engine implementations
*/
interface ApplicationEngine {
/** Application engine environment */
val environment: ApplicationEngineEnvironment
/** Start the server engine */
fun start(wait: Boolean = true): ApplicationEngine
/** Stop the server engine */
fun stop(gracePeriodMillis: Long, timeoutMillis: Long)
/** Add shutdown hook */
fun addShutdownHook(hook: () -> Unit)
}
/**
* Base implementation for application engines
*/
abstract class BaseApplicationEngine(
final override val environment: ApplicationEngineEnvironment,
val pipeline: EnginePipeline = defaultEnginePipeline(environment)
) : ApplicationEngine {
/** Engine is running */
val isRunning: Boolean
/** Engine monitor for lifecycle events */
val monitor: Events
/** Execute engine pipeline */
protected suspend fun executeEngine(call: ApplicationCall)
/** Start engine implementation */
protected abstract fun start(wait: Boolean): ApplicationEngine
/** Stop engine implementation */
protected abstract fun stop(gracePeriodMillis: Long, timeoutMillis: Long)
}Environment configuration for application engines including connectors, modules, and application lifecycle.
/**
* Environment for application engines
*/
interface ApplicationEngineEnvironment {
/** Application instance */
val application: Application
/** Environment logger */
val log: Logger
/** Environment configuration */
val config: ApplicationConfig
/** Event monitor */
val monitor: Events
/** Development mode flag */
val developmentMode: Boolean
/** Server connectors configuration */
val connectors: List<EngineConnectorConfig>
/** Application modules to load */
val modules: List<Application.() -> Unit>
/** Parent coroutine context */
val parentCoroutineContext: CoroutineContext
/** Watch paths for development mode */
val watchPatterns: List<String>
/** Root path for the application */
val rootPath: String
}
/**
* Builder for creating engine environments
*/
class ApplicationEngineEnvironmentBuilder {
/** Set parent coroutine context */
var parentCoroutineContext: CoroutineContext = EmptyCoroutineContext
/** Set development mode */
var developmentMode: Boolean = false
/** Set root path */
var rootPath: String = "/"
/** Watch patterns for auto-reload */
val watchPatterns: MutableList<String> = mutableListOf()
/** Connector configurations */
val connectors: MutableList<EngineConnectorConfig> = mutableListOf()
/** Application modules */
val modules: MutableList<Application.() -> Unit> = mutableListOf()
/** Add HTTP connector */
fun connector(block: EngineConnectorConfigBuilder.() -> Unit)
/** Add application module */
fun module(body: Application.() -> Unit)
/** Build environment */
fun build(): ApplicationEngineEnvironment
}Configuration for HTTP/HTTPS connectors with customizable host, port, and protocol settings.
/**
* Engine connector configuration
*/
interface EngineConnectorConfig {
/** Connector type (HTTP, HTTPS) */
val type: ConnectorType
/** Server host */
val host: String
/** Server port */
val port: Int
}
/**
* Builder for engine connector configuration
*/
class EngineConnectorConfigBuilder {
/** Connector host (default: 0.0.0.0) */
var host: String = "0.0.0.0"
/** Connector port (default: 80) */
var port: Int = 80
/** Build connector configuration */
fun build(): EngineConnectorConfig
}
/**
* Connector types
*/
enum class ConnectorType {
HTTP,
HTTPS
}
/**
* HTTP connector configuration
*/
class HttpConnectorConfig(
override val host: String = "0.0.0.0",
override val port: Int = 80
) : EngineConnectorConfig {
override val type: ConnectorType = ConnectorType.HTTP
}
/**
* HTTPS connector configuration
*/
class HttpsConnectorConfig(
override val host: String = "0.0.0.0",
override val port: Int = 443,
val keyStorePath: String,
val keyStorePassword: String,
val privateKeyPassword: String? = null
) : EngineConnectorConfig {
override val type: ConnectorType = ConnectorType.HTTPS
}Pipeline system for processing HTTP requests at the engine level before application processing.
/**
* Engine pipeline for request processing
*/
class EnginePipeline : Pipeline<Unit, ApplicationCall> {
companion object {
/** Before phase for engine pre-processing */
val Before: PipelinePhase = PipelinePhase("Before")
/** Call phase for application call processing */
val Call: PipelinePhase = PipelinePhase("Call")
/** After phase for engine post-processing */
val After: PipelinePhase = PipelinePhase("After")
}
}
/**
* Create default engine pipeline
* @param environment - Engine environment
* @return Configured engine pipeline
*/
fun defaultEnginePipeline(environment: ApplicationEngineEnvironment): EnginePipelineUtilities for parsing command line arguments and configuring engines from command line options.
/**
* Command line configuration parser
*/
class CommandLineConfig(args: Array<String>) {
/** Parsed configuration */
val config: ApplicationConfig
/** Server host from command line */
val host: String?
/** Server port from command line */
val port: Int?
/** Development mode flag */
val developmentMode: Boolean
/** Watch patterns from command line */
val watchPatterns: List<String>
/** Create engine environment from command line */
fun createEnvironment(): ApplicationEngineEnvironment
}
/**
* Parse command line arguments
* @param args - Command line arguments array
* @return Parsed command line configuration
*/
fun parseCommandLineArgs(args: Array<String>): CommandLineConfigUtility functions for creating and configuring application engine environments.
/**
* Create application engine environment
* @param configure - Environment configuration block
* @return Configured environment
*/
fun applicationEngineEnvironment(configure: ApplicationEngineEnvironmentBuilder.() -> Unit): ApplicationEngineEnvironment
/**
* Create development environment with auto-reload
* @param configure - Environment configuration block
* @return Development environment
*/
fun developmentEnvironment(configure: ApplicationEngineEnvironmentBuilder.() -> Unit): ApplicationEngineEnvironment
/**
* Create production environment
* @param configure - Environment configuration block
* @return Production environment
*/
fun productionEnvironment(configure: ApplicationEngineEnvironmentBuilder.() -> Unit): ApplicationEngineEnvironmentEvent system for engine lifecycle monitoring and health checking.
/**
* Engine lifecycle events
*/
object EngineEvents {
/** Engine starting event */
val EngineStarting: EventDefinition<ApplicationEngine>
/** Engine started event */
val EngineStarted: EventDefinition<ApplicationEngine>
/** Engine stopping event */
val EngineStopping: EventDefinition<ApplicationEngine>
/** Engine stopped event */
val EngineStopped: EventDefinition<ApplicationEngine>
}
/**
* Event monitoring for engines
*/
interface Events {
/** Subscribe to event */
fun <T> subscribe(definition: EventDefinition<T>, handler: (T) -> Unit)
/** Unsubscribe from event */
fun <T> unsubscribe(definition: EventDefinition<T>, handler: (T) -> Unit)
/** Raise event */
fun <T> raise(definition: EventDefinition<T>, value: T)
}
/**
* Event definition
*/
data class EventDefinition<T>(val name: String)Usage Examples:
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
// Basic engine environment setup
fun createBasicEnvironment(): ApplicationEngineEnvironment {
return applicationEngineEnvironment {
// Add HTTP connector
connector {
host = "0.0.0.0"
port = 8080
}
// Add application module
module {
routing {
get("/") {
call.respondText("Hello from Ktor!")
}
}
}
}
}
// Development environment with auto-reload
fun createDevelopmentEnvironment(): ApplicationEngineEnvironment {
return developmentEnvironment {
developmentMode = true
// Watch for changes
watchPatterns += "src/main/kotlin/**/*.kt"
watchPatterns += "src/main/resources/**/*"
connector {
host = "localhost"
port = 8080
}
module(Application::developmentModule)
}
}
// Production environment with HTTPS
fun createProductionEnvironment(): ApplicationEngineEnvironment {
return productionEnvironment {
developmentMode = false
// HTTP connector (for redirects)
connector {
host = "0.0.0.0"
port = 80
}
// HTTPS connector
connector {
host = "0.0.0.0"
port = 443
// Note: HTTPS configuration would be engine-specific
}
module(Application::productionModule)
}
}
// Multiple connectors setup
fun createMultiConnectorEnvironment(): ApplicationEngineEnvironment {
return applicationEngineEnvironment {
// Public HTTP connector
connector {
host = "0.0.0.0"
port = 8080
}
// Admin connector on different port
connector {
host = "127.0.0.1"
port = 8081
}
module {
routing {
get("/") {
call.respondText("Public API")
}
get("/admin") {
// Check if request came from admin connector
val localPort = call.request.local.port
if (localPort == 8081) {
call.respondText("Admin Interface")
} else {
call.respond(HttpStatusCode.NotFound)
}
}
}
}
}
}
// Command line configuration
fun main(args: Array<String>) {
val commandLineConfig = parseCommandLineArgs(args)
val environment = commandLineConfig.createEnvironment()
// Engine would be started here with the environment
// Example: embeddedServer(Netty, environment).start(wait = true)
}
// Custom engine implementation example
abstract class CustomApplicationEngine(
environment: ApplicationEngineEnvironment
) : BaseApplicationEngine(environment) {
override fun start(wait: Boolean): ApplicationEngine {
// Subscribe to engine events
environment.monitor.subscribe(EngineEvents.EngineStarting) { engine ->
environment.log.info("Starting custom engine...")
}
environment.monitor.subscribe(EngineEvents.EngineStarted) { engine ->
environment.log.info("Custom engine started on ${environment.connectors.joinToString { "${it.host}:${it.port}" }}")
}
// Start server implementation
startServer()
if (wait) {
// Wait for shutdown
Runtime.getRuntime().addShutdownHook(Thread {
stop(1000, 5000)
})
}
return this
}
override fun stop(gracePeriodMillis: Long, timeoutMillis: Long) {
environment.monitor.raise(EngineEvents.EngineStopping, this)
// Stop server implementation
stopServer(gracePeriodMillis, timeoutMillis)
environment.monitor.raise(EngineEvents.EngineStopped, this)
}
protected abstract fun startServer()
protected abstract fun stopServer(gracePeriodMillis: Long, timeoutMillis: Long)
}
// Environment with custom configuration
fun createConfigurableEnvironment(config: ApplicationConfig): ApplicationEngineEnvironment {
return applicationEngineEnvironment {
// Load configuration
val serverConfig = config.config("server")
val host = serverConfig.property("host").getString()
val port = serverConfig.property("port").getInt()
connector {
this.host = host
this.port = port
}
// Set development mode from config
developmentMode = config.propertyOrNull("app.development")?.getBoolean() ?: false
// Set root path from config
rootPath = config.propertyOrNull("app.rootPath")?.getString() ?: "/"
// Load modules based on configuration
val enabledModules = config.propertyOrNull("app.modules")?.getList() ?: emptyList()
if ("routing" in enabledModules) {
module(Application::routingModule)
}
if ("authentication" in enabledModules) {
module(Application::authenticationModule)
}
if ("monitoring" in enabledModules) {
module(Application::monitoringModule)
}
}
}
// Extension modules
fun Application.developmentModule() {
routing {
get("/") {
call.respondText("Development Server")
}
get("/reload") {
call.respondText("Auto-reload enabled")
}
}
}
fun Application.productionModule() {
routing {
get("/") {
call.respondText("Production Server")
}
get("/health") {
call.respond(HttpStatusCode.OK, mapOf("status" to "healthy"))
}
}
}
fun Application.routingModule() {
routing {
get("/api/status") {
call.respond(mapOf("service" to "running"))
}
}
}
fun Application.authenticationModule() {
// Authentication setup would go here
}
fun Application.monitoringModule() {
// Monitoring and metrics setup would go here
}Install with Tessl CLI
npx tessl i tessl/maven-io-ktor--ktor-server-core-jvm