@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) package eu.friedcutlet.yokan.services.http import eu.friedcutlet.yokan.domain.ProfileId import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancel import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertSame import kotlin.test.assertTrue class ProfileHttpServiceTest { @Test fun preservesRequestAndResponseIncludingCredentialsAndBinaryBodies() = runTest { val parent = SupervisorJob() val request = HttpRequest("https://source.test/upload", "POST", mapOf("Authorization" to "Bearer owner"), bodyBytes = byteArrayOf(0, -1)) val response = HttpResponse(401, headers = mapOf("WWW-Authenticate" to "Bearer"), bodyBytes = byteArrayOf(1, -1), setCookies = listOf("id=owner")) val delegate = FakeHttp().apply { requestAction = { assertSame(request, it); response } } val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) assertEquals(A, service.profileId); assertSame(response, service.request(request)) parent.cancelAndJoin() } @Test fun streamsChunksInOrderAndPreservesBufferedErrorResponses() = runTest { val parent = SupervisorJob() val delegate = FakeHttp().apply { streamAction = { request, chunk -> assertSame(Request, request); chunk(byteArrayOf(1, 2)); chunk(byteArrayOf(-1)) HttpStreamResponse(200, setCookies = listOf("id=owner")) } } val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) val received = mutableListOf() assertEquals(listOf("id=owner"), service.stream(Request) { received.addAll(it.toList()) }.setCookies) assertContentEquals(byteArrayOf(1, 2, -1), received.toByteArray()) val error = HttpStreamResponse(403, body = "challenge".encodeToByteArray()) delegate.streamAction = { _, _ -> error } assertSame(error, service.stream(Request) { error("Error body streamed") }) parent.cancelAndJoin() } @Test fun retiredOwnerRejectsBothEntryPointsBeforeDelegateAccess() = runTest { val parent = SupervisorJob() val delegate = FakeHttp() val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) parent.cancelAndJoin() assertFailsWith { service.request(Request) } assertFailsWith { service.stream(Request) { error("Expired chunk") } } assertEquals(0, delegate.calls) } @Test fun retirementJoinsExternalRequestFinalizersBeforeRelease() = runTest { val parent = SupervisorJob() val entered = CompletableDeferred(); val release = CompletableDeferred() var finalized = false val delegate = FakeHttp().apply { requestAction = { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } } } } val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) val caller = launch { service.request(Request) } entered.await() val retiring = launch { parent.cancelAndJoin() } testScheduler.runCurrent(); assertFalse(retiring.isCompleted); assertFalse(caller.isCompleted) release.complete(Unit); retiring.join(); caller.join(); assertTrue(finalized) } @Test fun callerExpiryJoinsStreamFinalizersAndPreservesSiblingWork() = runTest { val parent = SupervisorJob() val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) val entered = CompletableDeferred(); val release = CompletableDeferred() val delegate = FakeHttp().apply { streamAction = { _, _ -> try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } } } val service = ProfileHttpService(A, delegate, scope) val sibling = scope.launch { awaitCancellation() } val caller = launch { service.stream(Request) {} } entered.await(); caller.cancel(); testScheduler.runCurrent() assertFalse(caller.isCompleted); assertTrue(parent.isActive); assertTrue(sibling.isActive) release.complete(Unit); caller.join() assertEquals(200, service.request(Request).statusCode) parent.cancelAndJoin() } @Test fun streamCleanupCannotDeliverLateBytesEvenFromNonCancellableContext() = runTest { val parent = SupervisorJob() val entered = CompletableDeferred() var lateRejected = false; var delivered = 0 val delegate = FakeHttp().apply { streamAction = { _, chunk -> try { chunk(byteArrayOf(1)); entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { assertFailsWith { chunk(byteArrayOf(2)) }; lateRejected = true } } } } val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) val caller = launch { service.stream(Request) { delivered++ } } entered.await(); caller.cancelAndJoin() assertEquals(1, delivered); assertTrue(lateRejected); assertTrue(parent.isActive) parent.cancelAndJoin() } @Test fun retainedStreamCallbackCannotWriteAfterSuccessfulCompletion() = runTest { val parent = SupervisorJob() var retained: (suspend (ByteArray) -> Unit)? = null val delegate = FakeHttp().apply { streamAction = { _, chunk -> retained = chunk; HttpStreamResponse(200) } } val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) service.stream(Request) { error("Detached callback wrote bytes") } assertFailsWith { requireNotNull(retained).invoke(byteArrayOf(1)) } parent.cancelAndJoin() } @Test fun responseHeadersCannotWriteAfterCancellationOrCompletion() = runTest { val parent = SupervisorJob() val entered = CompletableDeferred() var retained: (suspend (HttpStreamResponse) -> Unit)? = null var delivered = 0 val response = HttpStreamResponse(200) val delegate = FakeHttp().apply { streamAction = { request, _ -> retained = request.onStreamResponse try { requireNotNull(retained).invoke(response) entered.complete(Unit) awaitCancellation() } finally { withContext(NonCancellable) { assertFailsWith { requireNotNull(retained).invoke(response) } } } } } val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) val request = Request.copy(onStreamResponse = { delivered++ }) val caller = launch { service.stream(request) {} } entered.await() caller.cancelAndJoin() assertEquals(1, delivered) delegate.streamAction = { current, _ -> retained = current.onStreamResponse; response } service.stream(request) {} assertFailsWith { requireNotNull(retained).invoke(response) } assertEquals(1, delivered) parent.cancelAndJoin() } @Test fun alreadyExpiredCallerCannotDispatchWithImmediateOwnerDispatcher() = runTest { val parent = SupervisorJob(); val delegate = FakeHttp() val service = ProfileHttpService(A, delegate, CoroutineScope(parent + UnconfinedTestDispatcher(testScheduler))) val caller = launch { currentCoroutineContext().cancel() assertFailsWith { service.request(Request) } assertFailsWith { service.stream(Request) {} } } caller.join(); assertEquals(0, delegate.calls); assertTrue(parent.isActive) parent.cancelAndJoin() } @Test fun queuedRequestCannotReachTransportAfterOwnerRetires() = runTest { val parent = SupervisorJob(); val delegate = FakeHttp() val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) val caller = launch(UnconfinedTestDispatcher(testScheduler)) { service.request(Request) } parent.cancel(); testScheduler.runCurrent(); caller.join(); parent.join() assertEquals(0, delegate.calls) } @Test fun transportOrChunkFailureDoesNotRetireAnOrdinaryParentOrSiblings() = runTest { val parent = Job(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) val delegate = FakeHttp().apply { requestAction = { error("Transport failed") } } val service = ProfileHttpService(A, delegate, scope) val sibling = scope.launch { awaitCancellation() } assertFailsWith { service.request(Request) } delegate.streamAction = { _, chunk -> chunk(byteArrayOf(1)); HttpStreamResponse(200) } assertFailsWith { service.stream(Request) { throw IllegalArgumentException("Disk failed") } } assertTrue(parent.isActive); assertTrue(sibling.isActive) delegate.requestAction = { HttpResponse(200) } assertEquals(200, service.request(Request).statusCode) parent.cancelAndJoin() } @Test fun retiringOneOwnerDoesNotRetargetOrCancelAnotherOwnersTransport() = runTest { val parentA = SupervisorJob(); val parentB = SupervisorJob() val a = FakeHttp().apply { requestAction = { HttpResponse(200, "A") } } val b = FakeHttp().apply { requestAction = { HttpResponse(200, "B") } } val serviceA = ProfileHttpService(A, a, CoroutineScope(parentA + StandardTestDispatcher(testScheduler))) val serviceB = ProfileHttpService(B, b, CoroutineScope(parentB + StandardTestDispatcher(testScheduler))) assertEquals("A", serviceA.request(Request).body); parentA.cancelAndJoin() assertFailsWith { serviceA.request(Request) } assertEquals("B", serviceB.request(Request).body); assertTrue(parentB.isActive) assertEquals(1, a.calls); assertEquals(1, b.calls); parentB.cancelAndJoin() } @Test fun extraPlatformEnginesHaveIndependentLifetimes() = runTest { val first = createPlatformHttpClientEngine(A) val second = createPlatformHttpClientEngine(B) try { kotlin.test.assertNotSame(first, second) ProfileHttpEngine(first).closeAndJoin() assertTrue(second.coroutineContext[Job]?.isActive == true) } finally { ProfileHttpEngine(first).closeAndJoin() ProfileHttpEngine(second).closeAndJoin() } } private class FakeHttp : HttpService { var calls = 0 var requestAction: suspend (HttpRequest) -> HttpResponse = { HttpResponse(200) } var streamAction: suspend (HttpRequest, suspend (ByteArray) -> Unit) -> HttpStreamResponse = { _, _ -> HttpStreamResponse(200) } override suspend fun request(request: HttpRequest): HttpResponse { calls++; return requestAction(request) } override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse { calls++; return streamAction(request, onChunk) } } private companion object { val A = ProfileId("p_11111111111111111111111111111111") val B = ProfileId("p_22222222222222222222222222222222") val Request = HttpRequest("https://source.test/chapter") } }