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
1 change: 1 addition & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ clikt = { module = "com.github.ajalt.clikt:clikt", version.ref = "clikt" }
logback-classic = { module = "ch.qos.logback:logback-classic", version.ref = "logback" }

kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" }
sqlite-jdbc = { module = "org.xerial:sqlite-jdbc", version = "3.41.2.2" }
mockk = { module = "io.mockk:mockk", version.ref = "mockk" }

[plugins]
Expand Down
1 change: 1 addition & 0 deletions server/core/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,5 @@ dependencies {
testImplementation(libs.ktor.server.test.host)
testImplementation(libs.kotlinx.coroutines.test)
testImplementation(libs.mockk)
testImplementation(libs.sqlite.jdbc)
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ fun Route.emailRoutes(

// Determine tier for attachment handling
val sessionId = inboxService.getSessionIdForInbox(inbox.id)
val tier = sessionId?.let { sessionService.getSessionById(it)?.tier } ?: Tier.FREE
val tier = inboxService.tierForInbox(inbox.id)
val stripAttachments = !tier.attachmentsEnabled

val summary = emailService.ingestEmail(inbox.id, request, stripAttachments, tier.maxAttachmentBytes)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package dev.bmcreations.blip.server.services

import dev.bmcreations.blip.server.db.TursoClient
import dev.bmcreations.blip.server.db.TursoValue
import dev.bmcreations.blip.server.sse.SseManager
import io.ktor.server.application.*
import kotlinx.coroutines.*
import org.slf4j.LoggerFactory
import java.time.Instant

class CleanupService(
private val turso: TursoClient,
Expand All @@ -14,6 +16,12 @@ class CleanupService(
) {
private val logger = LoggerFactory.getLogger(CleanupService::class.java)

private companion object {
const val FREE_RETENTION_SECONDS = 86_400L
const val PRO_RETENTION_SECONDS = 2_592_000L
const val AGENT_RETENTION_SECONDS = 3_600L
}

fun startScheduled(app: Application) {
app.launch {
while (isActive) {
Expand All @@ -28,33 +36,60 @@ class CleanupService(
}

suspend fun cleanup() {
// Delete emails past their tier's retention period
// Timestamps are stored as ISO-8601 (Instant.toString()), so compare against bound
// ISO values. datetime('now') yields "YYYY-MM-DD HH:MM:SS"; since 'T' > ' ', an ISO
// value on the same day sorts after it, delaying expiry by up to 24h.
val now = Instant.now()
val nowIso = now.toString()

// Delete emails past their tier's retention period. The tier comes from the owning
// user when the inbox has one, else the creating session, else FREE
// (same rule as InboxService.resolveTier).
val retentionResult = turso.execute(
"""
DELETE FROM emails WHERE id IN (
SELECT e.id FROM emails e
JOIN inboxes i ON e.inbox_id = i.id
JOIN sessions s ON i.session_id = s.id
WHERE (s.tier = 'FREE' AND e.received_at < datetime('now', '-86400 seconds'))
OR (s.tier = 'PRO' AND e.received_at < datetime('now', '-2592000 seconds'))
OR (s.tier = 'AGENT' AND e.received_at < datetime('now', '-3600 seconds'))
LEFT JOIN users u ON u.id = i.user_id
LEFT JOIN sessions s ON s.id = i.session_id
WHERE ((CASE
WHEN u.id IS NOT NULL THEN
CASE WHEN u.has_pro = 1 THEN 'PRO' WHEN u.has_agent = 1 THEN 'AGENT' ELSE 'FREE' END
ELSE COALESCE(s.tier, 'FREE')
END) = 'FREE' AND e.received_at < ?)
OR ((CASE
WHEN u.id IS NOT NULL THEN
CASE WHEN u.has_pro = 1 THEN 'PRO' WHEN u.has_agent = 1 THEN 'AGENT' ELSE 'FREE' END
ELSE COALESCE(s.tier, 'FREE')
END) = 'PRO' AND e.received_at < ?)
OR ((CASE
WHEN u.id IS NOT NULL THEN
CASE WHEN u.has_pro = 1 THEN 'PRO' WHEN u.has_agent = 1 THEN 'AGENT' ELSE 'FREE' END
ELSE COALESCE(s.tier, 'FREE')
END) = 'AGENT' AND e.received_at < ?)
)
""".trimIndent(),
listOf(
TursoValue.Text(now.minusSeconds(FREE_RETENTION_SECONDS).toString()),
TursoValue.Text(now.minusSeconds(PRO_RETENTION_SECONDS).toString()),
TursoValue.Text(now.minusSeconds(AGENT_RETENTION_SECONDS).toString()),
)
""".trimIndent()
)
if (retentionResult.affectedRowCount > 0) {
logger.info("Deleted ${retentionResult.affectedRowCount} emails past retention")
}

// Seal expired sniper windows
val sealResult = turso.execute(
"UPDATE inboxes SET sniper_sealed = 1 WHERE sniper_closes_at IS NOT NULL AND sniper_closes_at < datetime('now') AND sniper_sealed = 0"
"UPDATE inboxes SET sniper_sealed = 1 WHERE sniper_closes_at IS NOT NULL AND sniper_closes_at < ? AND sniper_sealed = 0",
listOf(TursoValue.Text(nowIso))
)
if (sealResult.affectedRowCount > 0) {
logger.info("Sealed ${sealResult.affectedRowCount} expired sniper inboxes")
}

// Delete expired inboxes (cascades to emails and attachments)
val result = turso.execute("DELETE FROM inboxes WHERE expires_at < datetime('now')")
val result = turso.execute("DELETE FROM inboxes WHERE expires_at < ?", listOf(TursoValue.Text(nowIso)))
if (result.affectedRowCount > 0) {
logger.info("Cleaned up ${result.affectedRowCount} expired inboxes")
}
Expand All @@ -66,8 +101,17 @@ class CleanupService(
sseManager.pruneStaleFlows(activeInboxIds)
}

// Delete expired sessions
val sessionResult = turso.execute("DELETE FROM sessions WHERE expires_at < datetime('now')")
// Delete expired sessions, but keep any that still own an unexpired inbox:
// inboxes.session_id is ON DELETE CASCADE, and PRO inboxes (90d TTL) outlive
// the 24h anonymous session that created them. An expired session is already
// rejected by SessionService.getSessionByToken, so keeping the row grants nothing.
val sessionResult = turso.execute(
"""
DELETE FROM sessions WHERE expires_at < ?
AND id NOT IN (SELECT session_id FROM inboxes WHERE expires_at > ?)
""".trimIndent(),
listOf(TursoValue.Text(nowIso), TursoValue.Text(nowIso))
)
if (sessionResult.affectedRowCount > 0) {
logger.info("Cleaned up ${sessionResult.affectedRowCount} expired sessions")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ class InboxService(
val count = if (userId != null) {
turso.execute(
"SELECT COUNT(*) as cnt FROM inboxes WHERE user_id = ?",
listOf(TursoValue.Text(userId))
listOf(TursoValue.Text(userId), TursoValue.Text(Instant.now().toString()))
)
} else {
turso.execute(
Expand Down Expand Up @@ -193,10 +193,10 @@ class InboxService(
i.sniper_opens_at, i.sniper_closes_at, i.sniper_sealed,
(SELECT COUNT(*) FROM emails e WHERE e.inbox_id = i.id) as email_count
FROM inboxes i
WHERE i.user_id = ? AND i.expires_at > datetime('now')
WHERE i.user_id = ? AND i.expires_at > ?
ORDER BY i.created_at DESC
""".trimIndent(),
listOf(TursoValue.Text(userId))
listOf(TursoValue.Text(userId), TursoValue.Text(Instant.now().toString()))
)
} else {
turso.execute(
Expand All @@ -205,10 +205,10 @@ class InboxService(
i.sniper_opens_at, i.sniper_closes_at, i.sniper_sealed,
(SELECT COUNT(*) FROM emails e WHERE e.inbox_id = i.id) as email_count
FROM inboxes i
WHERE i.session_id = ? AND i.expires_at > datetime('now')
WHERE i.session_id = ? AND i.expires_at > ?
ORDER BY i.created_at DESC
""".trimIndent(),
listOf(TursoValue.Text(sessionId))
listOf(TursoValue.Text(sessionId), TursoValue.Text(Instant.now().toString()))
)
}

Expand All @@ -226,6 +226,11 @@ class InboxService(
listOf(TursoValue.Text(inboxId))
).firstOrNull() ?: throw NotFoundException("Inbox not found")

// Expired inboxes may linger until the next cleanup pass; treat them as gone.
if (!Instant.parse(inboxRow["expires_at"]!!).isAfter(Instant.now())) {
throw NotFoundException("Inbox not found")
}

val ownerMatch = (userId != null && inboxRow["user_id"] == userId) || inboxRow["session_id"] == sessionId
if (!ownerMatch) {
throw ForbiddenException("Access denied")
Expand Down Expand Up @@ -267,9 +272,9 @@ class InboxService(
"""
SELECT id, address, domain, session_id, created_at, expires_at,
sniper_opens_at, sniper_closes_at, sniper_sealed
FROM inboxes WHERE address = ? AND expires_at > datetime('now')
FROM inboxes WHERE address = ? AND expires_at > ?
""".trimIndent(),
listOf(TursoValue.Text(address))
listOf(TursoValue.Text(address), TursoValue.Text(Instant.now().toString()))
).firstOrNull() ?: return null

return row.toInbox()
Expand Down Expand Up @@ -329,6 +334,31 @@ class InboxService(
return row["session_id"]
}

/**
* Tier governing inbox-scoped behaviour (attachments, retention). Prefers the owning
* user's subscription flags when the inbox has a user_id, since the creating session
* may be gone or stale; falls back to the creating session's tier, then FREE.
*/
suspend fun tierForInbox(inboxId: String): Tier {
val row = turso.execute(
"""
SELECT i.user_id, u.id AS owner_id, u.has_pro, u.has_agent, s.tier AS session_tier
FROM inboxes i
LEFT JOIN users u ON u.id = i.user_id
LEFT JOIN sessions s ON s.id = i.session_id
WHERE i.id = ?
""".trimIndent(),
listOf(TursoValue.Text(inboxId))
).firstOrNull() ?: return Tier.FREE

return resolveTier(
userFound = row["owner_id"] != null,
hasPro = row["has_pro"] == "1",
hasAgent = row["has_agent"] == "1",
sessionTier = row["session_tier"]?.let { runCatching { Tier.valueOf(it) }.getOrNull() },
)
}

private fun Map<String, String?>.toInbox(): Inbox {
val sniperOpens = this["sniper_opens_at"]
val sniperCloses = this["sniper_closes_at"]
Expand All @@ -353,3 +383,13 @@ class InboxService(
)
}
}

/** PRO wins over AGENT when a user has both flags. */
internal fun resolveTier(userFound: Boolean, hasPro: Boolean, hasAgent: Boolean, sessionTier: Tier?): Tier =
if (userFound) {
when {
hasPro -> Tier.PRO
hasAgent -> Tier.AGENT
else -> Tier.FREE
}
} else sessionTier ?: Tier.FREE
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package dev.bmcreations.blip.server

import dev.bmcreations.blip.server.db.Migrations
import dev.bmcreations.blip.server.db.TursoClient
import dev.bmcreations.blip.server.db.TursoResult
import dev.bmcreations.blip.server.db.TursoValue
import io.mockk.coEvery
import io.mockk.mockk
import java.sql.Connection
import java.sql.DriverManager

/**
* In-memory SQLite stand-in for TursoClient, running the real [Migrations] with
* foreign keys enforced (as in production), so SQL-level behaviour such as cascades
* and timestamp comparisons is exercised rather than mocked.
*/
class SqliteTurso : AutoCloseable {
val connection: Connection = DriverManager.getConnection("jdbc:sqlite::memory:").also {
it.createStatement().use { s -> s.execute("PRAGMA foreign_keys = ON") }
}

val client: TursoClient = mockk<TursoClient>().also { mock ->
coEvery { mock.execute(any(), any()) } coAnswers {
run(firstArg(), secondArg())
}
}

init {
Migrations.migrations.forEach { sql ->
try {
connection.createStatement().use { it.execute(sql) }
} catch (e: java.sql.SQLException) {
if ("duplicate column" !in (e.message ?: "")) throw e
}
}
}

fun run(sql: String, args: List<TursoValue> = emptyList()): TursoResult {
connection.prepareStatement(sql).use { ps ->
args.forEachIndexed { i, v ->
when (v) {
is TursoValue.Text -> ps.setString(i + 1, v.value)
is TursoValue.Integer -> ps.setLong(i + 1, v.value)
is TursoValue.Blob -> ps.setBytes(i + 1, java.util.Base64.getDecoder().decode(v.base64))
TursoValue.Null -> ps.setNull(i + 1, java.sql.Types.NULL)
}
}
return if (ps.execute()) {
val rs = ps.resultSet
val md = rs.metaData
val cols = (1..md.columnCount).map { md.getColumnLabel(it) }
val rows = mutableListOf<List<String?>>()
while (rs.next()) rows += (1..md.columnCount).map { rs.getString(it) }
TursoResult(cols, rows, 0, 0)
} else {
TursoResult(emptyList(), emptyList(), ps.updateCount.toLong(), 0)
}
}
}

fun count(table: String): Int = run("SELECT COUNT(*) AS c FROM $table").firstOrNull()!!["c"]!!.toInt()

override fun close() = connection.close()
}
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ class EmailRoutesTest {
coEvery { inboxService.getInboxByAddress("swift-fox-42@useblip.email") } returns testInbox
every { inboxService.isSniperWindowOpen(any()) } returns true
coEvery { inboxService.getSessionIdForInbox("inbox-1") } returns "s1"
coEvery { sessionService.getSessionById("s1") } returns testSession
coEvery { inboxService.tierForInbox("inbox-1") } returns testSession.tier
coEvery { emailService.ingestEmail("inbox-1", any(), any()) } returns testEmailSummary

setup {
Expand Down Expand Up @@ -278,7 +278,7 @@ class EmailRoutesTest {
coEvery { inboxService.getInboxByAddress("swift-fox-42@useblip.email") } returns testInbox
every { inboxService.isSniperWindowOpen(any()) } returns true
coEvery { inboxService.getSessionIdForInbox("inbox-1") } returns "s1"
coEvery { sessionService.getSessionById("s1") } returns testSession
coEvery { inboxService.tierForInbox("inbox-1") } returns testSession.tier
coEvery { emailService.ingestEmail("inbox-1", any(), any()) } returns testEmailSummary

setup {
Expand Down
Loading
Loading