HubSyncDockerIntegrationTest.kt
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncDockerIntegrationTest.kt
1package eu.friedcutlet.yokan.services.sync23import eu.friedcutlet.yokan.database.DbCategory4import eu.friedcutlet.yokan.database.DbItemType5import eu.friedcutlet.yokan.database.DbSourcePreference6import eu.friedcutlet.yokan.database.InMemoryYokanDatabase7import eu.friedcutlet.yokan.database.emptySnapshot8import eu.friedcutlet.yokan.services.http.HttpRequest9import eu.friedcutlet.yokan.services.http.HttpResponse10import eu.friedcutlet.yokan.services.http.HttpService11import eu.friedcutlet.yokan.services.http.KtorHttpService12import eu.friedcutlet.yokan.services.http.createPlatformHttpClientEngine13import kotlinx.coroutines.CoroutineScope14import kotlinx.coroutines.Dispatchers15import kotlinx.coroutines.SupervisorJob16import kotlinx.coroutines.cancel17import kotlinx.coroutines.runBlocking18import kotlinx.serialization.json.Json19import kotlinx.serialization.json.jsonObject20import kotlinx.serialization.json.jsonPrimitive21import org.junit.Assume.assumeTrue22import org.junit.Test23import java.io.File24import kotlin.test.assertEquals25import kotlin.test.assertTrue2627class HubSyncDockerIntegrationTest {28 @Test29 fun productionClientAuthenticatesAndRoundTripsDottedSettingsPreference() = runBlocking {30 val hubUrl = System.getenv("YOKAN_TEST_HUB_URL")?.trim()?.takeIf(String::isNotEmpty)31 val envPath = System.getenv("YOKAN_TEST_HUB_ENV_FILE")?.trim()?.takeIf(String::isNotEmpty)32 assumeTrue("Set YOKAN_TEST_HUB_URL and YOKAN_TEST_HUB_ENV_FILE to enable the local-hub test", hubUrl != null && envPath != null)3334 val configuredHub = requireNotNull(hubUrl)35 val credentials = readCredentials(File(requireNotNull(envPath)))36 val reproValue = "repro-value"37 val diagnostics = mutableListOf<SyncDiagnostic>()38 val productionHttp = KtorHttpService(createPlatformHttpClientEngine())39 val http = RecordingHttpService(productionHttp, diagnostics, credentials.values + reproValue)40 val owner = CoroutineScope(SupervisorJob() + Dispatchers.Default)41 val firstDb = InMemoryYokanDatabase(emptySnapshot())42 val first = HubSyncService(firstDb, http, webSocketEngine = null, autoSync = false, scope = owner)43 val secondDb = InMemoryYokanDatabase(emptySnapshot())44 val second = HubSyncService(secondDb, http, webSocketEngine = null, autoSync = false, scope = owner)45 try {46 assertTrue(first.login(1, configuredHub, credentials.getValue("ADMIN_EMAIL"), credentials.getValue("ADMIN_PASSWORD")).success, "Disposable hub admin login failed")47 enableSettingsSync(firstDb)48 firstDb.upsertCategory(DbCategory(name = "synthetic-round-trip", forItemType = DbItemType.Manga))4950 val initialPush = first.sync(1, firstDb.settings())51 val initialSyncAccepted = diagnostics.any { it.status in 200..299 }52 if (!initialSyncAccepted) printDiagnostic(diagnostics.lastOrNull { it.status >= 400 }, phase = "initialSync")53 assertTrue(initialSyncAccepted, "Hub did not accept the initial full-state sync")54 assertTrue(initialPush.uploadedChanges > 0, "Initial state push sent no changes")5556 assertTrue(second.login(2, configuredHub, credentials.getValue("ADMIN_EMAIL"), credentials.getValue("ADMIN_PASSWORD")).success, "Second disposable hub admin login failed")57 enableSettingsSync(secondDb)58 val pull = second.pullChanges(2)59 assertTrue(pull.errors.isEmpty(), "Second-client pull failed: ${pull.errors.size} sync error(s)")60 assertTrue(secondDb.categories().any { it.name == "synthetic-round-trip" }, "Synthetic category did not round-trip")6162 firstDb.updateSettings(firstDb.settings().copy(sourcePreferences = listOf(DbSourcePreference(7, "invalid.dot-key", reproValue))))63 val keyedPush = first.pushChanges(1)64 val acceptedPreferencePush = diagnostics.lastOrNull {65 it.status in 200..299 && it.paths.any { (_, path) -> path == "sourcePreferences.7:invalid.dot-key" }66 }67 if (acceptedPreferencePush == null) {68 printDiagnostic(diagnostics.lastOrNull { it.status >= 400 }, phase = "keyedPreferencePush")69 }70 assertTrue(acceptedPreferencePush != null, "Hub did not accept dotted preference path with a 2xx response")71 assertTrue(keyedPush.uploadedChanges > 0, "Dotted preference push sent no changes")7273 val keyedPull = second.pullChanges(2)74 if (keyedPull.errors.isNotEmpty()) {75 printDiagnostic(diagnostics.lastOrNull { it.status >= 400 }, phase = "keyedPreferencePull")76 }77 assertTrue(keyedPull.errors.isEmpty(), "Second-client dotted preference pull failed: ${keyedPull.errors.size} sync error(s)")78 assertEquals(79 reproValue,80 secondDb.settings().sourcePreferences.orEmpty()81 .singleOrNull { it.sourceId == 7L && it.key == "invalid.dot-key" }?.value,82 "Dotted preference key/value did not round-trip exactly",83 )84 } finally {85 first.close()86 second.close()87 http.close()88 owner.cancel()89 }90 }9192 private fun enableSettingsSync(database: InMemoryYokanDatabase) {93 val preference = database.syncPreferences().single()94 database.upsertSyncPreference(preference.copy(syncSettings = true))95 }9697 private fun readCredentials(file: File): Map<String, String> {98 require(file.isFile && file.canRead()) { "Hub env file is unavailable" }99 return file.readLines()100 .filter { it.isNotBlank() && !it.trimStart().startsWith("#") }101 .mapNotNull { line ->102 val (key, value) = line.removePrefix("export ").split("=", limit = 2).takeIf { it.size == 2 } ?: return@mapNotNull null103 key.trim() to value.trim().removeSurrounding("\"").removeSurrounding("'")104 }105 .toMap()106 .also { require("ADMIN_EMAIL" in it && "ADMIN_PASSWORD" in it) { "Hub env file lacks disposable admin credentials" } }107 }108109 private class RecordingHttpService(110 private val delegate: KtorHttpService,111 private val diagnostics: MutableList<SyncDiagnostic>,112 private val secrets: List<String>,113 ) : HttpService {114 override suspend fun request(request: HttpRequest): HttpResponse {115 val response = delegate.request(request)116 if (request.url.endsWith("/api/v1/sync") && request.method.equals("POST", ignoreCase = true)) {117 val req = runCatching { Json.parseToJsonElement(request.body.orEmpty()).jsonObject }.getOrNull()118 val ops = req?.get("ops")?.let { runCatching { it as kotlinx.serialization.json.JsonArray }.getOrNull() }119 val paths = ops.orEmpty().mapNotNull { op ->120 runCatching {121 val value = op.jsonObject122 value["k"]?.jsonPrimitive?.content?.let { kind ->123 value["p"]?.jsonPrimitive?.content?.let { path -> kind to path }124 }125 }.getOrNull()126 }127 val error = runCatching {128 Json.parseToJsonElement(response.body).jsonObject["error"]?.jsonPrimitive?.content129 ?: Json.parseToJsonElement(response.body).jsonObject["code"]?.jsonPrimitive?.content130 }.getOrNull()?.let { message ->131 val authToken = request.headers.entries.firstOrNull { it.key.equals("Authorization", ignoreCase = true) }132 ?.value?.removePrefix("Bearer ")133 safeError(message, secrets + listOfNotNull(authToken))134 }135 diagnostics += SyncDiagnostic(response.statusCode, error, paths.size, paths)136 }137 return response138 }139140 override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit) =141 delegate.stream(request, onChunk)142143 fun close() = delegate.close()144145 private fun safeError(message: String, secrets: List<String>): String = secrets146 .filter(String::isNotEmpty)147 .fold(message) { safe, secret -> safe.replace(secret, "<redacted>") }148 .filter { it.isLetterOrDigit() || it in " _.:/-<>" }149 .take(240)150 }151152 private data class SyncDiagnostic(val status: Int, val error: String?, val opCount: Int, val paths: List<Pair<String, String>>)153154 private fun printDiagnostic(diagnostic: SyncDiagnostic?, phase: String) {155 if (diagnostic == null) {156 println("Hub diagnostic: request=not-captured phase=$phase")157 return158 }159 val op = diagnostic.paths.firstOrNull { (_, path) -> path == "sourcePreferences.7:invalid.dot-key" }160 ?: diagnostic.paths.firstOrNull()161 println("Hub diagnostic: status=${diagnostic.status} error=${diagnostic.error ?: "<none>"} " +162 "opKind=${op?.first ?: "<unknown>"} opCount=${diagnostic.opCount} path=${op?.second ?: "<unknown>"} " +163 "phase=$phase")164 }165}166