Skip to content

Commit

Permalink
Merge branch 'feat/allow-random-port' of github.com:marschwar/klite
Browse files Browse the repository at this point in the history
  • Loading branch information
angryziber committed Dec 13, 2024
2 parents 9ef0f1e + 2bb495e commit f59f0c2
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 6 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* jdbc: fixed usage of multiple different DataSources when there is an active transaction
* json: TSGenerator will now use more type-safe string template types for java.time classes, e.g. `${number}-${number}-${number}` instead of `string`
* openapi: fix compliancy: output parameter types as lowercase in OpenAPI spec
* server: `Server(InetSocketAddress(0))` can now be used to bind to any available port.

# 1.6.9
* core: logger(name) is now accessible without a class instance context
Expand Down
1 change: 1 addition & 0 deletions TUTORIAL.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ fun main() {

This will start a server on the default port 8080.
You can change the listening IP and port by passing it as an argument to the `Server` constructor.
Passing `InetSocketAddress(0)` will bind to any available port.

## Config

Expand Down
5 changes: 2 additions & 3 deletions sample/test/ServerIntegrationTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,9 @@ import java.net.http.HttpRequest.BodyPublishers.noBody

class ServerIntegrationTest {
@Test fun requests() {
val port = (Math.random() * 60000 + 1000).toInt()
val server = sampleServer(port).apply { start(gracefulStopDelaySec = -1) }
val server = sampleServer(0).apply { start(gracefulStopDelaySec = -1) }

val http = JsonHttpClient("http://localhost:$port", registry = server.registry)
val http = JsonHttpClient("http://localhost:${server.listen.port}", registry = server.registry)
runBlocking {
expect(http.get<String>("/hello")).toEqual("\"Hello World\"")
expect(http.get<String>("/hello/param/123456?query=123")).toEqual("\"Path: 123456, Query: {query=123}\"")
Expand Down
7 changes: 4 additions & 3 deletions server/src/klite/Server.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import kotlin.reflect.KFunction
import kotlin.reflect.full.primaryConstructor

class Server(
val listen: InetSocketAddress = InetSocketAddress(Config.optional("PORT")?.toInt() ?: 8080),
listen: InetSocketAddress = InetSocketAddress(Config.optional("PORT")?.toInt() ?: 8080),
val workerPool: ExecutorService = Executors.newWorkStealingPool(Config.optional("NUM_WORKERS")?.toInt() ?: getRuntime().availableProcessors()),
override val registry: MutableRegistry = DependencyInjectingRegistry().apply {
register<RequestLogger>()
Expand All @@ -36,12 +36,13 @@ class Server(
private val httpExchangeCreator: KFunction<HttpExchange> = HttpExchange::class.primaryConstructor!!,
): RouterConfig(decorators, registry.requireAll(), registry.requireAll()), MutableRegistry by registry {
init { currentThread().name += "/" + requestIdGenerator.prefix }
private val http = HttpServer.create()
private val requestScope = CoroutineScope(SupervisorJob() + workerPool.asCoroutineDispatcher())
private val log = logger()

private val http = HttpServer.create(listen, 0)
val listen: InetSocketAddress get() = http.address

fun start(gracefulStopDelaySec: Int = 3) {
http.bind(listen, 0)
log.info("Listening on $listen")
http.start()
if (gracefulStopDelaySec >= 0) getRuntime().addShutdownHook(thread(start = false) { stop(gracefulStopDelaySec) })
Expand Down
36 changes: 36 additions & 0 deletions server/test/klite/ServerTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package klite

import ch.tutteli.atrium.api.fluent.en_GB.toBeGreaterThan
import ch.tutteli.atrium.api.fluent.en_GB.toEqual
import ch.tutteli.atrium.api.verbs.expect
import org.junit.jupiter.api.Test
import java.net.InetSocketAddress
import kotlin.random.Random

class ServerTest {
@Test fun `bind server to any available port`() {
val server = Server(listen = InetSocketAddress( 0))
try {
server.start(gracefulStopDelaySec = -1)
expect(server.listen.port).toBeGreaterThan(0)
} finally {
server.stop(0)
}
}

@Test fun `bind server to custom port`() {
val port = Random.nextInt(1024, 65535) + 1
val server = Server(listen = InetSocketAddress(port))
try {
server.start(gracefulStopDelaySec = -1)
expect(server.listen.port).toEqual(port)
} finally {
server.stop(0)
}
}

@Test fun `expose bound address if server is not started`() {
expect(Server().listen.port).toEqual(8080)
}
}

0 comments on commit f59f0c2

Please sign in to comment.