@@ -30,6 +30,8 @@ import kotlinx.coroutines.test.advanceUntilIdle
3030import kotlinx.coroutines.test.runCurrent
3131import kotlinx.coroutines.test.runTest
3232import kotlinx.serialization.json.JsonElement
33+ import kotlinx.serialization.json.JsonPrimitive
34+ import kotlin.test.assertNotNull
3335import kotlinx.serialization.json.JsonObject
3436import kotlinx.serialization.json.buildJsonObject
3537import kotlinx.serialization.json.put
@@ -368,6 +370,7 @@ class CloudAccountClientTest {
368370 */
369371 @Test
370372 fun hostStreamRecoversRepeatsOnlyTheReadAndUnsubscribesOnClose () = runTest {
373+ for (supportsScoped in listOf (true , false )) {
371374 val commands = mutableListOf<RemoteCommand >()
372375 val master = ByteArray (32 )
373376 val peerSecret = ByteArray (32 ) { 11 }
@@ -387,7 +390,11 @@ class CloudAccountClientTest {
387390 " unsubscribe_stream" -> """ {"resp":"stream_unsubscribed","stream_id":"session"}"""
388391 else -> error(" unexpected ${command.cmd} " )
389392 }
390- val encrypted = CloudAccountCipher .encrypt(response.encodeToByteArray(), key, nonce)
393+ val answer = if (supportsScoped && command.cmd == " read_stream" ) {
394+ JsonObject (RelayJson .parseToJsonElement(response).jsonObject +
395+ (" subscription_id" to JsonPrimitive (command.subscriptionId))).toString()
396+ } else response
397+ val encrypted = CloudAccountCipher .encrypt(answer.encodeToByteArray(), key, nonce)
391398 RelayJson .encodeToJsonElement(EncryptedPayload .serializer(),
392399 EncryptedPayload (Base64 .Default .encode(encrypted), Base64 .Default .encode(nonce)))
393400 }
@@ -399,11 +406,58 @@ class CloudAccountClientTest {
399406 " desktop-1" , " session" , {}, {})
400407 .onEach { received + = it.getValue(" event" ).jsonPrimitive.content }
401408 .first { it.getValue(" event" ).jsonPrimitive.content == STREAM_EVENT_READY }
402- assertEquals(listOf (" read_stream" , " read_stream" , " unsubscribe_stream" ), commands.map { it.cmd })
403- assertEquals(RemoteCommand (cmd = " read_stream" , streamId = " session" , subscribe = true ), commands[1 ])
409+ assertEquals(if (supportsScoped) listOf (" read_stream" , " read_stream" , " unsubscribe_stream" )
410+ else listOf (" read_stream" , " read_stream" ), commands.map { it.cmd })
411+ assertNotNull(commands.first().subscriptionId)
412+ assertTrue(commands.all { it.subscriptionId == commands.first().subscriptionId })
413+ assertEquals(RemoteCommand (cmd = " read_stream" , streamId = " session" , subscribe = true ), commands[1 ].copy(subscriptionId = null ))
404414 assertEquals(listOf (" session-record" , STREAM_EVENT_READY ), received)
405415 assertEquals(" session" , commands.last().streamId)
406416 assertEquals(1 , keyReads, " the peer key is fetched once and reused for every read" )
417+ }
418+ }
419+
420+ @Test
421+ fun collectingTheSameStreamTwiceOwnsIndependentSubscriptions () = runTest {
422+ val master = ByteArray (32 )
423+ val peerSecret = ByteArray (32 ) { 11 }
424+ val key = DeviceIdentity .messageKey(peerSecret, DeviceIdentity .publicKey(master))
425+ val commands = mutableListOf<RemoteCommand >()
426+ val client = rpcClient(DeviceIdentity .publicKey(peerSecret)) { _, params ->
427+ val envelope = RelayJson .decodeFromJsonElement(EncryptedPayload .serializer(), params)
428+ val plain = CloudAccountCipher .decrypt(Base64 .Default .decode(envelope.encryptedData), key,
429+ Base64 .Default .decode(envelope.nonce)).decodeToString()
430+ val command = RelayJson .decodeFromString(RemoteCommand .serializer(), plain)
431+ commands + = command
432+ val response = if (command.cmd == " read_stream" )
433+ """ {"resp":"stream_page","stream_id":"session","subscription_id":"${command.subscriptionId} ","epoch":1,"events":[],"has_more":false,"cursor":0,"oldest_seq":1,"truncated":false}"""
434+ else """ {"resp":"stream_unsubscribed","stream_id":"session"}"""
435+ val nonce = ByteArray (12 ) { commands.size.toByte() }
436+ val encrypted = CloudAccountCipher .encrypt(response.encodeToByteArray(), key, nonce)
437+ RelayJson .encodeToJsonElement(EncryptedPayload .serializer(),
438+ EncryptedPayload (Base64 .Default .encode(encrypted), Base64 .Default .encode(nonce)))
439+ }
440+ val stream = client.subscribeSession(" http://192.168.1.2:9700" ,
441+ CloudAccountSession (" token-1" , " user-1" , master), " desktop-1" , " session" , {}, {})
442+ val ready = Channel <Unit >(Channel .UNLIMITED )
443+ val first = launch { stream.collect { if (it[" event" ]?.jsonPrimitive?.content == STREAM_EVENT_READY ) ready.send(Unit ) } }
444+ ready.receive()
445+ val second = launch { stream.collect { if (it[" event" ]?.jsonPrimitive?.content == STREAM_EVENT_READY ) ready.send(Unit ) } }
446+ try {
447+ ready.receive()
448+ val ids = commands.filter { it.cmd == " read_stream" }.map { it.subscriptionId }
449+ assertEquals(2 , ids.size)
450+ assertNotNull(ids[0 ])
451+ assertNotNull(ids[1 ])
452+ assertTrue(ids[0 ] != ids[1 ], " each collector owns its lease and history lane" )
453+ first.cancelAndJoin()
454+ assertEquals(ids[0 ], commands.last().subscriptionId)
455+ assertEquals(" unsubscribe_stream" , commands.last().cmd)
456+ assertTrue(second.isActive)
457+ } finally {
458+ first.cancelAndJoin()
459+ second.cancelAndJoin()
460+ }
407461 }
408462
409463 @Test
0 commit comments