431 lines · 22.0 KB · KotlinRaw
package com.cottondb.callingimport com.cottondb.shell.core.CoreExceptionimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.runBlockingimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.putimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonNullimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitiveimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertNullimport org.junit.Assert.assertTrueimport org.junit.Testprivate const val UUID = "01234567-89ab-cdef-0123-456789abcdef"private const val ROOM = "0123456789abcdef0123456789abcdef"/** A core that answers each method from a script (JSON as the core writes it), and records every ask. */class ScriptedCalls : CallsCore { private val answers = mutableMapOf<String, ArrayDeque<String>>() val asked = mutableListOf<Pair<String, JsonObject>>() fun answer(method: String, call: String = """{"phase":"live"}""", effects: String = "[]") { answers.getOrPut(method) { ArrayDeque() } += """{"call":$call,"effects":$effects}""" } fun reply(method: String, json: String) { answers.getOrPut(method) { ArrayDeque() } += json } fun refuse(method: String, code: String = "no_number") { answers.getOrPut(method) { ArrayDeque() } += "refuse:$code" } val methods get() = asked.map { it.first } fun request(method: String) = asked.lastOrNull { it.first == method }?.second override suspend fun ask(method: String, request: JsonObject): JsonObject { asked += method to request val next = answers[method]?.removeFirstOrNull() ?: return Json.parseToJsonElement("""{"call":{"phase":"idle"},"effects":[]}""").jsonObject if (next.startsWith("refuse:")) throw CoreException(next.removePrefix("refuse:"), "This person has no phone number to call.", JsonNull) return Json.parseToJsonElement(next).jsonObject }}class FakeSystem : SystemCallPort { val said = mutableListOf<String>() override fun startOutgoing(uuid: String, handle: String, name: String?, video: Boolean) { said += "outgoing $handle ${name ?: "-"} $video" } override fun outgoingConnecting(uuid: String) { said += "connecting" } override fun connected(uuid: String) { said += "connected" } override fun reportIncoming(uuid: String, title: String, video: Boolean) { said += "incoming $title $video" } override fun update(uuid: String, handle: String, name: String?, video: Boolean) { said += "update $handle ${name ?: "-"}" } override fun ended(uuid: String, cause: Int) { said += "ended $cause" }}class FakeSocket : CallSocketPort { val opened = mutableListOf<Pair<String, String>>() val sent = mutableListOf<JsonElement>() var closes = 0 var received: ((JsonElement) -> Unit)? = null var closed: (() -> Unit)? = null override fun open(url: String, credential: String, received: (JsonElement) -> Unit, closed: () -> Unit) { opened += url to credential this.received = received this.closed = closed } override fun send(frame: JsonElement) { sent += frame } override fun close() { closes += 1 }}class FakePeer : CallPeerPort { val said = mutableListOf<String>() var events: CallPeerEvents? = null override fun create(offerer: Boolean, iceServers: List<CallIceServer>, video: Boolean, events: CallPeerEvents) { said += "create $offerer ${iceServers.flatMap { it.urls }} $video" this.events = events } override fun applyRemote(kind: CallSignalKind, sdp: String) { said += "remote ${kind.word} $sdp" } override fun addCandidate(candidate: String, mid: String?, mline: Int?) { said += "candidate $candidate $mid $mline" } override fun restartIce() { said += "restart" } override fun close() { said += "close" } override fun setSending(audio: Boolean, video: Boolean) { said += "sending $audio $video" } override fun startCamera() { said += "camera on" } override fun stopCamera() { said += "camera off" } override fun switchToSfu(iceServers: List<CallIceServer>, video: Boolean, events: CallPeerEvents) { said += "sfu $video" this.events = events } override fun pushTracks(audio: Boolean, video: Boolean) { said += "push $audio $video" } override fun applySfu(op: String, sdp: String, tracks: List<SfuTrack>) { said += "sfu $op $sdp ${tracks.joinToString { "${it.mid}=${it.member}" }}" } override fun closeTracks(member: String) { said += "close $member" }}class FakeAudio : CallAudioPort { val said = mutableListOf<String>() override fun configure(video: Boolean) { said += "configure $video" } override fun stop() { said += "stop" } override fun setSpeaker(on: Boolean) { said += "speaker $on" }}class FakeTone : CallTonePort { val said = mutableListOf<String>() override fun play(tone: String) { said += "play $tone" } override fun stop() { said += "stop" }}class FakeClock : CallClockPort { val waits = mutableListOf<Long>() private val fires = mutableListOf<() -> Unit>() override fun after(milliseconds: Long, fire: () -> Unit) { waits += milliseconds; fires += fire } override fun cancelAll() { fires.clear() } fun fireAll() { val now = fires.toList(); fires.clear(); now.forEach { it() } }}class CallCenterTest { private val core = ScriptedCalls() private val system = FakeSystem() private val socket = FakeSocket() private val peer = FakePeer() private val audio = FakeAudio() private val tone = FakeTone() private val clock = FakeClock() private fun CoroutineScope.center() = CallCenter(CallCenter.Ports(system, socket, peer, audio, tone, clock), this, core = { core }) /** Every effect the core answers a dial with reaches its port, once and in order, and the call is the core's. */ @Test fun a_dial_performs_each_effect_on_its_port_in_order() = runBlocking { core.answer( "calls.start", call = """{"phase":"dialling","direction":"out","video":true,"uuid":"$UUID","name":"Ananya","own":{"audio":true,"video":true}}""", effects = """[ {"do":"system_call_outgoing","uuid":"$UUID","handle":"+15550100001","name":"Ananya","video":true}, {"do":"start_audio","video":true}, {"do":"start_camera"}, {"do":"play_tone","tone":"ringback"}, {"do":"open_socket","url":"wss://dev.example/v1/calls/socket","path":"/v1/calls/socket","credential":"ccr_x","after_ms":0}, {"do":"create_peer","offerer":true,"ice_servers":[{"urls":["stun:stun.example:3478"]},{"urls":"turn:turn.example","username":"u","credential":"c"}]}, {"do":"timer","after_ms":45000} ]""", ) val center = center() center.start("p1", video = true) center.settle() assertEquals(listOf("system_call_outgoing", "start_audio", "start_camera", "play_tone", "open_socket", "create_peer", "timer"), center.performed) assertEquals(listOf("outgoing +15550100001 Ananya true"), system.said) assertEquals(listOf("configure true"), audio.said) assertEquals(listOf("camera on", "create true [stun:stun.example:3478, turn:turn.example] true"), peer.said) assertEquals(listOf("play ringback"), tone.said) assertEquals(listOf("wss://dev.example/v1/calls/socket" to "ccr_x"), socket.opened) assertEquals(listOf(45_000L), clock.waits) assertEquals(CallState.Phase.Dialling, center.call.phase) assertEquals("Ananya", center.call.name) assertEquals("""{"person":"p1","video":true}""", core.request("calls.start").toString()) } /** The socket's frames, the peer's descriptions and candidates, the ICE state and the timer each go back as their method. */ @Test fun what_the_ports_report_goes_back_as_the_right_method() = runBlocking { core.answer("calls.start", effects = """[ {"do":"open_socket","url":"wss://x/v1/calls/socket","credential":"ccr_x"}, {"do":"create_peer","offerer":true,"ice_servers":[]}, {"do":"timer","after_ms":1000} ]""") val center = center() center.start("p1", video = false) center.settle() socket.received!!.invoke(Json.parseToJsonElement("""{"t":"accepted"}""")) peer.events!!.signal(CallSignalKind.Offer, "v=0", null, null, null) peer.events!!.signal(CallSignalKind.Ice, null, "candidate:1", "0", 0) peer.events!!.media(CallMediaState.Connected) clock.fireAll() center.settle() assertEquals(listOf("calls.start", "calls.signal", "calls.signal", "calls.signal", "calls.media", "calls.tick"), core.methods) val signals = core.asked.filter { it.first == "calls.signal" }.map { it.second.toString() } assertEquals("""{"in":{"t":"accepted"}}""", signals[0]) assertEquals("""{"out":{"kind":"offer","sdp":"v=0"}}""", signals[1]) assertEquals("""{"out":{"kind":"ice","candidate":"candidate:1","mid":"0","mline":0}}""", signals[2]) assertEquals("""{"state":"connected"}""", core.request("calls.media").toString()) } /** A socket closed by the core drops its later frames and its close; a close nobody asked for is `calls.socketClosed`. */ @Test fun an_answer_that_says_flush_flushes_chat() = runBlocking { core.reply("chat.call", """{"call":{"phase":"dialling"},"effects":[],"flush":true}""") core.reply("calls.mute", """{"call":{"phase":"live"},"effects":[]}""") val center = center() var flushed = 0 center.flushPort = { flushed += 1 } center.place("chat.call", buildJsonObject { put("thread", "t1") }) center.settle() assertEquals(1, flushed) center.place("calls.mute", buildJsonObject { put("audio", false) }) center.settle() assertEquals(1, flushed) } @Test fun a_stale_socket_is_dropped_and_a_drop_is_said() = runBlocking { core.answer("calls.start", effects = """[{"do":"open_socket","url":"wss://x/s","credential":"a"}]""") val center = center() center.start("p1", video = false) center.settle() val firstClosed = socket.closed!! firstClosed() center.settle() assertEquals(listOf("calls.start", "calls.socketClosed"), core.methods) // Again, but the core closes it first: the old socket's frame and close reach nothing. core.answer("calls.answer", effects = """[{"do":"open_socket","url":"wss://x/s","credential":"b"}]""") core.answer("calls.end", effects = """[{"do":"close_socket"},{"do":"system_call_ended","uuid":"$UUID","cause":"local","ios":null,"android":2}]""") center.answer() center.settle() val stale = socket.received!! val staleClose = socket.closed!! center.end() center.settle() stale(Json.parseToJsonElement("{}")) staleClose() center.settle() assertEquals(listOf("calls.start", "calls.socketClosed", "calls.answer", "calls.end"), core.methods) assertEquals(1, socket.closes) assertEquals(listOf("ended 2"), system.said) } /** A ring: the system's call is reported, its caller updated, answered and connected; the end's Telecom cause reaches the system. */ @Test fun a_ring_is_reported_answered_and_ended_with_telecoms_cause() = runBlocking { core.answer("calls.incoming", call = """{"phase":"ringing_in","direction":"in","uuid":"$UUID","room":"$ROOM"}""", effects = """[ {"do":"system_call_incoming","uuid":"$UUID","title":"Cotton","video":false}, {"do":"system_call_update","uuid":"$UUID","handle":"+15550100002","name":"Ravi","video":false} ]""") core.answer("calls.answer", call = """{"phase":"connecting","direction":"in","uuid":"$UUID"}""", effects = """[ {"do":"start_audio","video":false}, {"do":"system_call_connected","uuid":"$UUID","outgoing":false} ]""") core.answer("calls.end", call = """{"phase":"ended","uuid":"$UUID","reason":"hung_up"}""", effects = """[ {"do":"stop_audio"},{"do":"close_peer"},{"do":"system_call_ended","uuid":"$UUID","cause":"local","ios":null,"android":2} ]""") val center = center() center.incoming(ROOM, video = false) center.settle() assertEquals(CallState.Phase.RingingIn, center.call.phase) assertTrue(!center.call.outgoing) // The ring's Decline on the system side, while ringing, declines; once live it hangs up. center.answer() center.settle() center.toggleSpeaker() center.end() center.settle() assertEquals(listOf("incoming Cotton false", "update +15550100002 Ravi", "connected", "ended 2"), system.said) assertEquals(listOf("configure false", "speaker true", "stop"), audio.said) assertEquals(false, center.speaker) assertEquals(CallState.Phase.Ended, center.call.phase) assertEquals("hung_up", center.call.reason) assertEquals("""{"room":"$ROOM","video":false,"later":true}""", core.request("calls.incoming").toString()) } /** A ring's sealed box goes to the core with Chat's key; the caller comes back at once and the join follows. */ @Test fun a_sealed_ring_names_the_caller_then_joins() = runBlocking { core.reply("calls.incoming", """{"call":{"phase":"ringing_in","direction":"in"},"effects":[{"do":"system_call_incoming","uuid":"$UUID","title":"Ravi","handle":"+15550100002","video":false}], "caller":{"number":"+15550100002","name":"Ravi","photoPath":"/p/r.jpg"},"join":"$ROOM"}""") core.answer("calls.join", call = """{"phase":"ringing_in","direction":"in"}""") val center = center() center.chatKey = { "key" } center.incoming(ROOM, video = false, box = "c1:sealed") center.settle() assertEquals("""{"room":"$ROOM","video":false,"later":true,"ring":"c1:sealed","privateKey":"key"}""", core.request("calls.incoming").toString()) assertEquals(Caller("+15550100002", "Ravi", "/p/r.jpg"), center.caller) assertEquals(listOf("calls.incoming", "calls.join"), core.methods) assertEquals("""{"room":"$ROOM"}""", core.request("calls.join").toString()) assertEquals("incoming Ravi false", system.said.first()) } @Test fun the_systems_end_declines_a_ring_and_hangs_up_a_call() = runBlocking { core.answer("calls.incoming", call = """{"phase":"ringing_in","direction":"in"}""") val center = center() center.incoming(ROOM, video = true) center.settle() center.systemEnded() center.settle() core.answer("calls.state", call = """{"phase":"live"}""") center.refresh() center.settle() center.systemEnded() center.settle() assertEquals(listOf("calls.incoming", "calls.decline", "calls.state", "calls.end"), core.methods) } /** A refused start says the core's words to whoever asked, and nothing is performed. */ @Test fun a_refusal_is_said_once() = runBlocking { core.refuse("calls.start", "no_number") val center = center() var heard: String? = null center.start("p1", video = false) { heard = it } center.settle() assertEquals("This person has no phone number to call.", heard) assertEquals("This person has no phone number to call.", center.refusal) assertTrue(center.performed.isEmpty()) } /** Mute and camera go to `calls.mute` with both halves; the camera's on and off reach the peer as the core says. */ @Test fun mute_and_camera_go_to_calls_mute() = runBlocking { core.answer("calls.state", call = """{"phase":"live","video":true,"own":{"audio":true,"video":true}}""") core.answer("calls.mute", call = """{"phase":"live","video":true,"own":{"audio":false,"video":true}}""", effects = """[{"do":"set_sending","audio":false,"video":true}]""") core.answer("calls.mute", call = """{"phase":"live","video":true,"own":{"audio":false,"video":false}}""", effects = """[{"do":"set_sending","audio":false,"video":false},{"do":"stop_camera"}]""") val center = center() center.refresh() center.settle() center.toggleMute() center.settle() center.toggleVideo() center.settle() val mutes = core.asked.filter { it.first == "calls.mute" }.map { it.second.toString() } assertEquals(listOf("""{"audio":false,"video":true}""", """{"audio":false,"video":false}"""), mutes) assertEquals(listOf("sending false true", "sending false false", "camera off"), peer.said) } /** Remote descriptions, candidates and restarts reach the peer; a group's effects reach its SFU connection (owner, 23 Nov 2026). */ @Test fun the_peers_effects_and_a_groups() = runBlocking { core.answer("calls.signal", effects = """[ {"do":"apply_remote","kind":"answer","sdp":"v=0 a"}, {"do":"add_candidate","candidate":"candidate:2","mid":"0","mline":0}, {"do":"restart_ice"}, {"do":"show_roster","members":[]}, {"do":"switch_to_sfu"},{"do":"push_tracks","audio":true,"video":false}, {"do":"apply_remote_sdp","op":"offer","sdp":"v=0 o","tracks":[{"mid":"100","member":"m1","name":"audio-0"}]}, {"do":"close_tracks","member":"m1"}, {"do":"no_such_effect"} ]""") val center = center() center.perform(listOf()) // Hand a frame in through a socket the core opened. core.answer("calls.start", effects = """[{"do":"open_socket","url":"wss://x/s","credential":"c"}]""") center.start("p1", video = false) center.settle() socket.received!!.invoke(Json.parseToJsonElement("""{"t":"answer"}""")) center.settle() assertEquals(listOf("remote answer v=0 a", "candidate candidate:2 0 0", "restart", "sfu false", "push true false", "sfu offer v=0 o 100=m1", "close m1"), peer.said) // A group call is never ended for being one. assertEquals(listOf("calls.start", "calls.signal"), core.methods) assertTrue(center.performed.containsAll(listOf("switch_to_sfu", "push_tracks", "apply_remote_sdp", "close_tracks", "no_such_effect"))) // The SFU's ops and this phone's voice go back to the core. peer.events!!.sfu("push", "v=0 p", listOf(SfuTrack("0", null, "audio-0", "audio")), null) peer.events!!.speaking(true) center.settle() val signals = core.asked.filter { it.first == "calls.signal" }.map { it.second.toString() }.last() assertEquals("""{"out":{"sfu":"push","sdp":"v=0 p","tracks":[{"mid":"0","name":"audio-0","kind":"audio"}]}}""", signals) assertEquals("calls.speaking", core.methods.last()) } /** * A one-to-one call's roster ends nothing: the core says show_roster on the room's roster and member frames of * every call (walk 20261116-053606: the call ended as the room opened). */ @Test fun a_roster_on_a_call_of_two_ends_nothing() = runBlocking { core.answer("calls.start", call = """{"phase":"ringing_out","mode":"p2p"}""", effects = """[{"do":"open_socket","url":"wss://x/s","credential":"c"}]""") core.answer("calls.signal", call = """{"phase":"ringing_out","mode":"p2p"}""", effects = """[{"do":"show_roster","members":[{"id":"caller","state":"joined"},{"id":"m1","state":"invited"}]}]""") val center = center() center.start("p1", video = false) center.settle() socket.received!!.invoke(Json.parseToJsonElement("""{"t":"roster"}""")) center.settle() assertEquals(listOf("calls.start", "calls.signal"), core.methods) assertEquals(listOf("open_socket", "show_roster"), center.performed) } /** CALLS FIX 3: a push's ack that fails (an older Worker's 404, no network) is never shown and is tried again quietly. */ @Test fun a_failed_ack_is_quiet_and_tried_again() = runBlocking { core.refuse("calls.ack", "not_found") val center = center() center.ack("0123456789abcdef0123456789abcdef") center.settle() assertNull(center.refusal) assertEquals(listOf(CallCenter.ACK_RETRY), clock.waits) clock.fireAll() center.settle() assertEquals(listOf("calls.ack", "calls.ack"), core.methods) assertNull(center.refusal) } /** The push token waits for the object: refused `not_connected`, it is sent again on the clock until taken. */ @Test fun a_token_waits_for_the_object() = runBlocking { core.refuse("calls.pushToken", "not_connected") core.reply("calls.pushToken", """{"ok":true}""") val center = center() center.pushToken("f".repeat(40)) center.settle() assertEquals(listOf(CallCenter.PUSH_RETRY), clock.waits) assertNull(center.refusal) clock.fireAll() center.settle() assertEquals(listOf("calls.pushToken", "calls.pushToken"), core.methods) assertEquals("android", core.request("calls.pushToken")!!["platform"]!!.jsonPrimitive.content) // Taken: a refresh sends it no more. center.refresh() center.settle() assertEquals(listOf("calls.pushToken", "calls.pushToken", "calls.state"), core.methods) } /** A call link: the core reads it, and a call to its one person starts. */ @Test fun a_link_starts_a_call_to_its_person() = runBlocking { core.reply("calls.openLink", """{"people":["p9"],"video":true}""") val center = center() center.open("cottoncalling://call?person=p9&video=1") center.settle() assertEquals(listOf("calls.openLink", "calls.start"), core.methods) assertEquals("""{"person":"p9","video":true}""", core.request("calls.start").toString()) } /** Your people's rows are numbers: a call to one starts by number. */ @Test fun a_number_is_called_by_number() = runBlocking { val center = center() center.startNumber("+15550102252", video = false) center.settle() assertEquals("""{"number":"+15550102252","video":false}""", core.request("calls.start").toString()) }}