package eu.friedcutlet.yokan.services.together import eu.friedcutlet.yokan.services.http.ProfileTestEngine import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.runTest import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import kotlin.concurrent.thread import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class RoomClientAdmissionConcurrencyTest { @Test fun concurrentCloseDoesNotWaitForABlockedCredentialRead() = runTest { val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler) val entered = CountDownLatch(1); val release = CountDownLatch(1); val closed = CountDownLatch(1) val failures = ConcurrentLinkedQueue() val engine = ProfileTestEngine(dispatcher) { awaitCancellation() } val client = RoomClient(engine, HubSession("https://hub.test", "token", "device"), "ABC", CoroutineScope(parent + dispatcher)) { entered.countDown() release.await() true } val connecting = thread(name = "room-admission-test", isDaemon = true) { try { client.connect() } catch (error: Throwable) { failures.add(error) } } var closing: Thread? = null try { assertTrue(entered.await(5, TimeUnit.SECONDS), "Credential read did not start") closing = thread(name = "room-close-test", isDaemon = true) { try { client.close() } catch (error: Throwable) { failures.add(error) } finally { closed.countDown() } } // If admission holds the room lock, release would wait for this blocked database read. assertTrue(closed.await(5, TimeUnit.SECONDS), "Close is blocked by the credential read") assertEquals(1, engine.closeCalls) } finally { release.countDown() connecting.join(5_000); closing?.join(5_000) client.closeAndJoin(); parent.cancelAndJoin() } assertFalse(connecting.isAlive); assertFalse(closing.isAlive) assertTrue(failures.isEmpty(), failures.toString()) assertTrue(engine.requests.tryReceive().isFailure) } }