Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,40 @@ data class CoreServices(
val cleanupService: CleanupService,
)

private val RequestBodyLimit = createApplicationPlugin("RequestBodyLimit") {
private const val DEFAULT_BODY_LIMIT = 10L * 1024 * 1024

// The email worker base64-encodes attachments into one JSON body (~4/3 growth),
// and PRO allows 10 MB attachments, so the ingress route needs a larger cap.
private const val INGRESS_BODY_LIMIT = 16L * 1024 * 1024

private val IngressPath = Regex("^/v1/inboxes/[^/]+/emails/?$")

private fun isIngressRequest(call: ApplicationCall, workerSecret: String): Boolean {
if (call.request.httpMethod != HttpMethod.Post) return false
if (!IngressPath.matches(call.request.path())) return false
val provided = call.request.headers["X-Worker-Secret"] ?: return false
return java.security.MessageDigest.isEqual(provided.toByteArray(), workerSecret.toByteArray())
}

internal class RequestBodyLimitConfig {
var workerSecret: String = ""
}

internal val RequestBodyLimit = createApplicationPlugin("RequestBodyLimit", ::RequestBodyLimitConfig) {
val workerSecret = pluginConfig.workerSecret
onCall { call ->
val ingress = isIngressRequest(call, workerSecret)
val limit = if (ingress) INGRESS_BODY_LIMIT else DEFAULT_BODY_LIMIT
val contentLength = call.request.header(HttpHeaders.ContentLength)?.toLongOrNull()
if (contentLength != null && contentLength > 10 * 1024 * 1024) {
call.respond(HttpStatusCode.PayloadTooLarge, ErrorResponse("payload_too_large", "Request body too large"))
val chunked = call.request.header(HttpHeaders.TransferEncoding)
?.contains("chunked", ignoreCase = true) == true
when {
contentLength != null && contentLength > limit ->
call.respond(HttpStatusCode.PayloadTooLarge, ErrorResponse("payload_too_large", "Request body too large"))
// A chunked body has no declared size, so the limit can't be enforced up front.
// Only the ingress route is stricter; other routes keep accepting small chunked bodies.
ingress && contentLength == null && chunked ->
call.respond(HttpStatusCode.LengthRequired, ErrorResponse("length_required", "Content-Length required"))
}
}
}
Expand Down Expand Up @@ -80,7 +109,9 @@ fun Application.coreModule(config: CoreConfig): CoreServices {
val webhookService = WebhookService(turso, encryptionService = encryptionService, inboxService = inboxService)
val cleanupService = CleanupService(turso, webhookService, sseManager, config.cleanupContributors)

install(RequestBodyLimit)
install(RequestBodyLimit) {
workerSecret = config.workerSecret
}

install(ContentNegotiation) {
json(json)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.serialization.Serializable
import java.io.IOException
import kotlinx.serialization.json.*

class TursoClient(
Expand All @@ -21,16 +24,19 @@ class TursoClient(
json(json)
}
install(HttpTimeout) {
requestTimeoutMillis = 30_000
requestTimeoutMillis = 10_000
connectTimeoutMillis = 10_000
}
}

private val logger = org.slf4j.LoggerFactory.getLogger(TursoClient::class.java)

private val pipelineUrl = "$baseUrl/v2/pipeline"

suspend fun execute(sql: String, args: List<TursoValue> = emptyList()): TursoResult {
val results = executeBatch(listOf(Statement(sql, args)))
return results.first()
return results.firstOrNull()
?: throw RuntimeException("Turso returned no result for statement")
}

suspend fun executeBatch(statements: List<Statement>): List<TursoResult> {
Expand Down Expand Up @@ -59,20 +65,9 @@ class TursoClient(
}
}

val response = client.post(pipelineUrl) {
contentType(ContentType.Application.Json)
if (authToken.isNotBlank()) {
header("Authorization", "Bearer $authToken")
}
setBody(body.toString())
}

if (response.status != HttpStatusCode.OK) {
val text = response.bodyAsText()
throw RuntimeException("Turso error ${response.status}: $text")
}
val responseText = postWithRetry(body.toString())

val responseJson = json.parseToJsonElement(response.bodyAsText()).jsonObject
val responseJson = json.parseToJsonElement(responseText).jsonObject
val results = responseJson["results"]?.jsonArray ?: return emptyList()

return results.mapNotNull { result ->
Expand All @@ -93,6 +88,34 @@ class TursoClient(
}
}

/** Retries network errors, timeouts, 5xx and 429; any other status fails immediately. */
private suspend fun postWithRetry(body: String): String {
var lastError: Exception? = null
for (attempt in 0 until RETRY_DELAYS_MS.size + 1) {
if (attempt > 0) delay(RETRY_DELAYS_MS[attempt - 1])
try {
val response = client.post(pipelineUrl) {
contentType(ContentType.Application.Json)
if (authToken.isNotBlank()) {
header("Authorization", "Bearer $authToken")
}
setBody(body)
}
if (response.status == HttpStatusCode.OK) return response.bodyAsText()
val error = RuntimeException("Turso error ${response.status}: ${response.bodyAsText()}")
val retryable = response.status.value >= 500 || response.status == HttpStatusCode.TooManyRequests
if (!retryable) throw error
lastError = error
} catch (e: CancellationException) {
throw e
} catch (e: IOException) { // includes Ktor request/connect/socket timeouts
lastError = e
}
logger.warn("Turso request failed (attempt {}/{}): {}", attempt + 1, RETRY_DELAYS_MS.size + 1, lastError?.message)
}
throw lastError!!
}

private fun parseResult(result: JsonObject?): TursoResult {
if (result == null) return TursoResult(emptyList(), emptyList(), 0, 0)

Expand Down Expand Up @@ -125,6 +148,8 @@ class TursoClient(
}
}

private val RETRY_DELAYS_MS = listOf(200L, 600L)

data class Statement(val sql: String, val args: List<TursoValue> = emptyList())

data class TursoResult(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,90 +5,28 @@ import io.ktor.http.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.Serializable
import java.lang.management.ManagementFactory

@Serializable
data class HealthResponse(
val status: String,
val uptime: String,
val db: DbHealth,
val stats: Stats? = null,
)

@Serializable
data class DbHealth(
val connected: Boolean,
val latencyMs: Long,
)

@Serializable
data class Stats(
val activeSessions: Long,
val activeInboxes: Long,
val emailsLast24h: Long,
)
data class HealthResponse(val status: String)

fun Route.healthRoutes(turso: TursoClient) {
get("/health") {
val uptime = ManagementFactory.getRuntimeMXBean().uptime
val uptimeStr = formatUptime(uptime)
// Liveness: no dependencies, so a database outage doesn't get the process restarted.
get("/livez") {
call.respond(HttpStatusCode.OK, HealthResponse("ok"))
}

// Check DB connectivity and latency
val dbStart = System.currentTimeMillis()
// Readiness: one trivial query. Public, so it returns no counts or timings.
get("/health") {
val dbConnected = try {
turso.execute("SELECT 1", emptyList())
true
} catch (_: Exception) {
false
}
val dbLatency = System.currentTimeMillis() - dbStart

val stats = if (dbConnected) {
try {
val now = java.time.Instant.now().toString()
val dayAgo = java.time.Instant.now().minus(java.time.Duration.ofHours(24)).toString()

val sessions = turso.execute(
"SELECT COUNT(*) as cnt FROM sessions WHERE expires_at > ?",
listOf(dev.bmcreations.blip.server.db.TursoValue.Text(now))
).firstOrNull()?.get("cnt")?.toLongOrNull() ?: 0

val inboxes = turso.execute(
"SELECT COUNT(*) as cnt FROM inboxes WHERE expires_at > ?",
listOf(dev.bmcreations.blip.server.db.TursoValue.Text(now))
).firstOrNull()?.get("cnt")?.toLongOrNull() ?: 0

val emails = turso.execute(
"SELECT COUNT(*) as cnt FROM emails WHERE received_at > ?",
listOf(dev.bmcreations.blip.server.db.TursoValue.Text(dayAgo))
).firstOrNull()?.get("cnt")?.toLongOrNull() ?: 0

Stats(activeSessions = sessions, activeInboxes = inboxes, emailsLast24h = emails)
} catch (_: Exception) {
null
}
} else null

val status = if (dbConnected) "ok" else "degraded"
val httpStatus = if (dbConnected) HttpStatusCode.OK else HttpStatusCode.ServiceUnavailable

call.respond(httpStatus, HealthResponse(
status = status,
uptime = uptimeStr,
db = DbHealth(connected = dbConnected, latencyMs = dbLatency),
stats = stats,
))
}
}

private fun formatUptime(millis: Long): String {
val seconds = millis / 1000
val days = seconds / 86400
val hours = (seconds % 86400) / 3600
val minutes = (seconds % 3600) / 60
return when {
days > 0 -> "${days}d ${hours}h ${minutes}m"
hours > 0 -> "${hours}h ${minutes}m"
else -> "${minutes}m"
if (dbConnected) {
call.respond(HttpStatusCode.OK, HealthResponse("ok"))
} else {
call.respond(HttpStatusCode.ServiceUnavailable, HealthResponse("degraded"))
}
}
}
Original file line number Diff line number Diff line change
@@ -1,19 +1,34 @@
package dev.bmcreations.blip.server.routes

import dev.bmcreations.blip.models.EmailSummary
import dev.bmcreations.blip.server.UnauthorizedException
import dev.bmcreations.blip.server.services.InboxService
import dev.bmcreations.blip.server.services.SessionService
import dev.bmcreations.blip.server.sse.SseManager
import io.ktor.http.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.utils.io.*
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

const val SSE_HEARTBEAT_MILLIS = 25_000L

private sealed interface SseEvent {
data class Email(val summary: EmailSummary) : SseEvent
data object Heartbeat : SseEvent
}

fun Route.sseRoutes(
sseManager: SseManager,
sessionService: SessionService,
inboxService: InboxService,
heartbeatMillis: Long = SSE_HEARTBEAT_MILLIS,
) {
get("/v1/inboxes/{id}/sse") {
// Support token via query param for EventSource (can't set headers)
Expand All @@ -30,9 +45,37 @@ fun Route.sseRoutes(
writeStringUtf8("event: connected\ndata: {}\n\n")
flush()

sseManager.subscribe(inboxId).collect { email ->
val data = Json.encodeToString(email)
writeStringUtf8("event: email\ndata: $data\n\n")
val events = sseManager.subscribe(inboxId).map<EmailSummary, SseEvent> { SseEvent.Email(it) }
val heartbeats = flow {
while (true) {
delay(heartbeatMillis)
emit(SseEvent.Heartbeat)
}
}

// A single collector writes both streams, so writes never interleave.
merge(events, heartbeats).collect { event ->
when (event) {
is SseEvent.Email -> {
val data = Json.encodeToString(event.summary)
writeStringUtf8("event: email\ndata: $data\n\n")
}
SseEvent.Heartbeat -> {
// Re-check expiry so an expired session doesn't keep a stream open.
// Failures other than an auth rejection (e.g. a transient DB error) keep the stream.
val stillValid = try {
sessionService.getSessionByToken(token ?: "")
true
} catch (_: UnauthorizedException) {
false
} catch (_: Exception) {
true
}
if (!stillValid) throw CancellationException("Session expired")
// Comment line keeps idle connections open through proxies.
writeStringUtf8(": keepalive\n\n")
}
}
flush()
}
}
Expand Down
Loading
Loading