package eu.friedcutlet.yokan.services.sync import eu.friedcutlet.yokan.database.DbCategory import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbSourcePreference import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.emptySnapshot import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.http.KtorHttpService import eu.friedcutlet.yokan.services.http.createPlatformHttpClientEngine import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.Json import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import org.junit.Assume.assumeTrue import org.junit.Test import java.io.File import kotlin.test.assertEquals import kotlin.test.assertTrue class HubSyncDockerIntegrationTest { @Test fun productionClientAuthenticatesAndRoundTripsDottedSettingsPreference() = runBlocking { val hubUrl = System.getenv("YOKAN_TEST_HUB_URL")?.trim()?.takeIf(String::isNotEmpty) val envPath = System.getenv("YOKAN_TEST_HUB_ENV_FILE")?.trim()?.takeIf(String::isNotEmpty) assumeTrue("Set YOKAN_TEST_HUB_URL and YOKAN_TEST_HUB_ENV_FILE to enable the local-hub test", hubUrl != null && envPath != null) val configuredHub = requireNotNull(hubUrl) val credentials = readCredentials(File(requireNotNull(envPath))) val reproValue = "repro-value" val diagnostics = mutableListOf() val productionHttp = KtorHttpService(createPlatformHttpClientEngine()) val http = RecordingHttpService(productionHttp, diagnostics, credentials.values + reproValue) val owner = CoroutineScope(SupervisorJob() + Dispatchers.Default) val firstDb = InMemoryYokanDatabase(emptySnapshot()) val first = HubSyncService(firstDb, http, webSocketEngine = null, autoSync = false, scope = owner) val secondDb = InMemoryYokanDatabase(emptySnapshot()) val second = HubSyncService(secondDb, http, webSocketEngine = null, autoSync = false, scope = owner) try { assertTrue(first.login(1, configuredHub, credentials.getValue("ADMIN_EMAIL"), credentials.getValue("ADMIN_PASSWORD")).success, "Disposable hub admin login failed") enableSettingsSync(firstDb) firstDb.upsertCategory(DbCategory(name = "synthetic-round-trip", forItemType = DbItemType.Manga)) val initialPush = first.sync(1, firstDb.settings()) val initialSyncAccepted = diagnostics.any { it.status in 200..299 } if (!initialSyncAccepted) printDiagnostic(diagnostics.lastOrNull { it.status >= 400 }, phase = "initialSync") assertTrue(initialSyncAccepted, "Hub did not accept the initial full-state sync") assertTrue(initialPush.uploadedChanges > 0, "Initial state push sent no changes") assertTrue(second.login(2, configuredHub, credentials.getValue("ADMIN_EMAIL"), credentials.getValue("ADMIN_PASSWORD")).success, "Second disposable hub admin login failed") enableSettingsSync(secondDb) val pull = second.pullChanges(2) assertTrue(pull.errors.isEmpty(), "Second-client pull failed: ${pull.errors.size} sync error(s)") assertTrue(secondDb.categories().any { it.name == "synthetic-round-trip" }, "Synthetic category did not round-trip") firstDb.updateSettings(firstDb.settings().copy(sourcePreferences = listOf(DbSourcePreference(7, "invalid.dot-key", reproValue)))) val keyedPush = first.pushChanges(1) val acceptedPreferencePush = diagnostics.lastOrNull { it.status in 200..299 && it.paths.any { (_, path) -> path == "sourcePreferences.7:invalid.dot-key" } } if (acceptedPreferencePush == null) { printDiagnostic(diagnostics.lastOrNull { it.status >= 400 }, phase = "keyedPreferencePush") } assertTrue(acceptedPreferencePush != null, "Hub did not accept dotted preference path with a 2xx response") assertTrue(keyedPush.uploadedChanges > 0, "Dotted preference push sent no changes") val keyedPull = second.pullChanges(2) if (keyedPull.errors.isNotEmpty()) { printDiagnostic(diagnostics.lastOrNull { it.status >= 400 }, phase = "keyedPreferencePull") } assertTrue(keyedPull.errors.isEmpty(), "Second-client dotted preference pull failed: ${keyedPull.errors.size} sync error(s)") assertEquals( reproValue, secondDb.settings().sourcePreferences.orEmpty() .singleOrNull { it.sourceId == 7L && it.key == "invalid.dot-key" }?.value, "Dotted preference key/value did not round-trip exactly", ) } finally { first.close() second.close() http.close() owner.cancel() } } private fun enableSettingsSync(database: InMemoryYokanDatabase) { val preference = database.syncPreferences().single() database.upsertSyncPreference(preference.copy(syncSettings = true)) } private fun readCredentials(file: File): Map { require(file.isFile && file.canRead()) { "Hub env file is unavailable" } return file.readLines() .filter { it.isNotBlank() && !it.trimStart().startsWith("#") } .mapNotNull { line -> val (key, value) = line.removePrefix("export ").split("=", limit = 2).takeIf { it.size == 2 } ?: return@mapNotNull null key.trim() to value.trim().removeSurrounding("\"").removeSurrounding("'") } .toMap() .also { require("ADMIN_EMAIL" in it && "ADMIN_PASSWORD" in it) { "Hub env file lacks disposable admin credentials" } } } private class RecordingHttpService( private val delegate: KtorHttpService, private val diagnostics: MutableList, private val secrets: List, ) : HttpService { override suspend fun request(request: HttpRequest): HttpResponse { val response = delegate.request(request) if (request.url.endsWith("/api/v1/sync") && request.method.equals("POST", ignoreCase = true)) { val req = runCatching { Json.parseToJsonElement(request.body.orEmpty()).jsonObject }.getOrNull() val ops = req?.get("ops")?.let { runCatching { it as kotlinx.serialization.json.JsonArray }.getOrNull() } val paths = ops.orEmpty().mapNotNull { op -> runCatching { val value = op.jsonObject value["k"]?.jsonPrimitive?.content?.let { kind -> value["p"]?.jsonPrimitive?.content?.let { path -> kind to path } } }.getOrNull() } val error = runCatching { Json.parseToJsonElement(response.body).jsonObject["error"]?.jsonPrimitive?.content ?: Json.parseToJsonElement(response.body).jsonObject["code"]?.jsonPrimitive?.content }.getOrNull()?.let { message -> val authToken = request.headers.entries.firstOrNull { it.key.equals("Authorization", ignoreCase = true) } ?.value?.removePrefix("Bearer ") safeError(message, secrets + listOfNotNull(authToken)) } diagnostics += SyncDiagnostic(response.statusCode, error, paths.size, paths) } return response } override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit) = delegate.stream(request, onChunk) fun close() = delegate.close() private fun safeError(message: String, secrets: List): String = secrets .filter(String::isNotEmpty) .fold(message) { safe, secret -> safe.replace(secret, "") } .filter { it.isLetterOrDigit() || it in " _.:/-<>" } .take(240) } private data class SyncDiagnostic(val status: Int, val error: String?, val opCount: Int, val paths: List>) private fun printDiagnostic(diagnostic: SyncDiagnostic?, phase: String) { if (diagnostic == null) { println("Hub diagnostic: request=not-captured phase=$phase") return } val op = diagnostic.paths.firstOrNull { (_, path) -> path == "sourcePreferences.7:invalid.dot-key" } ?: diagnostic.paths.firstOrNull() println("Hub diagnostic: status=${diagnostic.status} error=${diagnostic.error ?: ""} " + "opKind=${op?.first ?: ""} opCount=${diagnostic.opCount} path=${op?.second ?: ""} " + "phase=$phase") } }