package com.anaplan.definitionservice.handlers import com.anaplan.definitionservice.extensions.endWithJson import io.vertx.core.json.JsonObject import io.vertx.ext.mongo.MongoClient import io.vertx.ext.web.RoutingContext import io.vertx.kotlin.core.json.json import io.vertx.kotlin.core.json.obj import kotlinx.coroutines.experimental.* fun health(mongo: MongoClient): (RoutingContext) -> Unit = { launch { withTimeout(500) { try { val result = pingMongo(mongo) it.response().endWithJson(result) } catch (throwable: Throwable) { val errorObj = json { obj("error" to throwable.message) } it.response().statusCode = 500 it.response().endWithJson(errorObj) } } } } private suspend fun pingMongo(mongoClient: MongoClient): JsonObject = runCommandAsync(mongoClient, "ping", json { obj("ping" to 1) }) private suspend fun runCommandAsync(mongoClient: MongoClient, commandName: String, command: JsonObject): JsonObject = suspendCancellableCoroutine { cont -> try { mongoClient.runCommand(commandName, command, { if (it.succeeded()) cont.resume(it.result()) else cont.resumeWithException(it.cause()) }) } catch (throwable: Throwable) { cont.resumeWithException(throwable) } }