Files
amethyst/nestsClient/src/commonTest/kotlin/com/vitorpamplona/nestsclient/NestsSpeakerTest.kt
T
Claude beec8204e5 refactor(audio-rooms): NestsClient API matches nostrnests reality (phase 2/3)
The Phase-1 interop harness exposed a substantial mismatch between our
production HTTP client and what the nostrnests reference server actually
exposes. This commit refactors `:nestsClient` and the wiring above it so
the production code path can talk to a real moq-auth + moq-relay.

| Aspect    | Before                                    | After (matches nostrnests/moq-auth/src/index.ts) |
|-----------|-------------------------------------------|--------------------------------------------------|
| Method    | GET                                       | POST                                             |
| URL       | `<base>/<roomId>`                         | `<base>/auth`                                    |
| Body      | none                                      | `{"namespace":"nests/<kind>:<host>:<roomId>","publish":bool}` |
| Response  | `{endpoint, token, codec, sample_rate}`   | `{token}` only                                   |
| Endpoint  | from response                             | from event's `endpoint` tag (passed via `NestsRoomConfig.endpoint`) |
| NIP-98    | bound to GET URL                          | bound to POST URL + body hash                    |

Type changes:
- New `NestsRoomConfig` data class bundling (authBaseUrl, endpoint,
  hostPubkey, roomId, kind). Built by the caller (UI / VM) from the
  NIP-53 kind 30312 event before invoking connectNests*.
- `NestsRoomConfig.moqNamespace()` produces the exact format
  moq-auth's NAMESPACE_REGEX expects: `nests/<kind>:<hex64>:<roomId>`.
- `NestsRoomInfo` deleted; replaced with a tiny `NestsTokenResponse(token)`
  matching the real response shape.
- `NestsClient.resolveRoom(serviceBase, roomId, signer): NestsRoomInfo`
  → `NestsClient.mintToken(room, publish, signer): String`. The
  publish flag drives the JWT claims (`get` for listeners, `put`
  for speakers).

Wire path:
- `OkHttpNestsClient` now POSTs `<authBase>/auth` with a JSON body
  and a NIP-98 Authorization header bound to (POST, url, body-hash).
- `connectNestsListener` / `connectNestsSpeaker` take `room:
  NestsRoomConfig` instead of split (serviceBase, roomId), pass
  `publish=false` / `publish=true` respectively, and use the room's
  `endpoint` (not a server-returned one) for the WebTransport
  connect. The minted JWT is the bearer token.
- `NestsListenerState.Connected` / `NestsSpeakerState.Connected` /
  `Broadcasting` carry the `room: NestsRoomConfig` instead of the old
  `roomInfo: NestsRoomInfo`.
- MoQ TrackNamespace for the room is now a single segment whose
  bytes are `room.moqNamespace()` — the simplest mapping to the
  relay's JWT claim check (`root: "<namespace>"`); Phase-3 round-trip
  test will confirm and adjust if the relay expects a multi-segment
  tuple.

Wiring above:
- `AudioRoomViewModel` constructor: replaces `(serviceBase, roomId)`
  with `(room: NestsRoomConfig)`. Connector seam interfaces
  (NestsListenerConnector, NestsSpeakerConnector) follow the same
  shape.
- `AudioRoomViewModelFactory` (Android) takes `room: NestsRoomConfig`.
- `AudioRoomActivity` adds `EXTRA_AUTH_BASE_URL`, `EXTRA_ENDPOINT`,
  `EXTRA_HOST_PUBKEY`, `EXTRA_KIND` Intent extras (was just service
  + roomId) and reconstructs `NestsRoomConfig` in onCreate. Drops
  `EXTRA_SERVICE_BASE`.
- `AudioRoomJoinCard` reads `event.endpoint()` + `event.pubKey` +
  `event.kind` in addition to `event.service()`; rooms missing any
  of those are silently un-joinable (the event author didn't host
  on a nests-compatible relay).
- `AudioRoomActivityContent` takes `room: NestsRoomConfig` in place
  of (serviceBase, roomId) and threads it down.

Phase-1 ping test rewired to use the production `OkHttpNestsClient`
end-to-end against the real `/auth`, asserting we get back a
3-segment JWT.

Existing in-process tests updated for the new types: NestsConnectTest,
NestsSpeakerTest, AudioRoomViewModelTest. NestsRoomInfoTest renamed to
NestsRoomConfigTest with new cases for the namespace formatter and the
auth-URL helper. All 80 in-process tests still green.

Phase 3 (next) will add the full round-trip interop test that runs
production `connectNestsListener` + `connectNestsSpeaker` through the
real moq-relay — that's where MoQ wire-format assumptions (draft
revision, OBJECT_DATAGRAM layout, namespace tuple shape) get verified
or get followup audit findings.
2026-04-26 14:42:26 +00:00

181 lines
7.2 KiB
Kotlin

/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.nestsclient
import com.vitorpamplona.nestsclient.audio.AudioCapture
import com.vitorpamplona.nestsclient.audio.OpusEncoder
import com.vitorpamplona.nestsclient.moq.Announce
import com.vitorpamplona.nestsclient.moq.AnnounceOk
import com.vitorpamplona.nestsclient.moq.ClientSetup
import com.vitorpamplona.nestsclient.moq.MoqCodec
import com.vitorpamplona.nestsclient.moq.MoqSession
import com.vitorpamplona.nestsclient.moq.MoqVersion
import com.vitorpamplona.nestsclient.moq.ServerSetup
import com.vitorpamplona.nestsclient.moq.TrackNamespace
import com.vitorpamplona.nestsclient.transport.FakeWebTransport
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertTrue
class NestsSpeakerTest {
@Test
fun startBroadcasting_announces_then_state_is_Broadcasting() =
runTest {
val (speakerSide, peerSide) = FakeWebTransport.pair()
val speakerSession = MoqSession.client(speakerSide, backgroundScope)
val ns = TrackNamespace.of("nests", "test-room")
val peer =
async {
val ctrl = peerSide.peerOpenedBidiStreams().first()
val cs = MoqCodec.decode(ctrl.incoming().first())!!.message as ClientSetup
ctrl.write(MoqCodec.encode(ServerSetup(cs.supportedVersions.first())))
val ann = MoqCodec.decode(ctrl.incoming().first())!!.message as Announce
ctrl.write(MoqCodec.encode(AnnounceOk(ann.namespace)))
}
speakerSession.setup(listOf(MoqVersion.DRAFT_17))
val state =
MutableStateFlow<NestsSpeakerState>(
NestsSpeakerState.Connected(
room = TEST_ROOM,
negotiatedMoqVersion = speakerSession.selectedVersion!!,
),
)
val speaker =
DefaultNestsSpeaker(
session = speakerSession,
roomNamespace = ns,
speakerTrackName = "test-pubkey".encodeToByteArray(),
captureFactory = { ConstantCapture() },
encoderFactory = { ConstantEncoder() },
scope = backgroundScope,
mutableState = state,
)
val handle = speaker.startBroadcasting()
peer.await()
val now = speaker.state.value
assertIs<NestsSpeakerState.Broadcasting>(now)
assertEquals(false, now.isMuted)
// setMuted reflects through into the public state.
handle.setMuted(true)
assertEquals(true, (speaker.state.value as NestsSpeakerState.Broadcasting).isMuted)
assertEquals(true, handle.isMuted)
handle.close()
// Should fall back to Connected after broadcast ends.
assertIs<NestsSpeakerState.Connected>(speaker.state.value)
speaker.close()
assertEquals(NestsSpeakerState.Closed, speaker.state.value)
}
@Test
fun startBroadcasting_twice_throws_IllegalStateException() =
runTest {
val (speakerSide, peerSide) = FakeWebTransport.pair()
val speakerSession = MoqSession.client(speakerSide, backgroundScope)
val ns = TrackNamespace.of("nests", "test-room")
val peer =
async {
val ctrl = peerSide.peerOpenedBidiStreams().first()
val cs = MoqCodec.decode(ctrl.incoming().first())!!.message as ClientSetup
ctrl.write(MoqCodec.encode(ServerSetup(cs.supportedVersions.first())))
val ann = MoqCodec.decode(ctrl.incoming().first())!!.message as Announce
ctrl.write(MoqCodec.encode(AnnounceOk(ann.namespace)))
}
speakerSession.setup(listOf(MoqVersion.DRAFT_17))
val state =
MutableStateFlow<NestsSpeakerState>(
NestsSpeakerState.Connected(
room = TEST_ROOM,
negotiatedMoqVersion = speakerSession.selectedVersion!!,
),
)
val speaker =
DefaultNestsSpeaker(
session = speakerSession,
roomNamespace = ns,
speakerTrackName = "test-pubkey".encodeToByteArray(),
captureFactory = { ConstantCapture() },
encoderFactory = { ConstantEncoder() },
scope = backgroundScope,
mutableState = state,
)
speaker.startBroadcasting()
peer.await()
val ex =
runCatching { speaker.startBroadcasting() }.exceptionOrNull()
assertTrue(ex is IllegalStateException, "second startBroadcasting should throw IllegalStateException, got $ex")
speaker.close()
}
// ----- Fakes -----
private class ConstantCapture : AudioCapture {
// Yields a single dummy frame then drains; per-instance so tests
// don't share state through a singleton.
private val ch = Channel<ShortArray>(capacity = 1)
init {
ch.trySend(ShortArray(960) { 0 })
ch.close()
}
override fun start() {}
override suspend fun readFrame(): ShortArray? = ch.receiveCatching().getOrNull()
override fun stop() {}
}
private class ConstantEncoder : OpusEncoder {
override fun encode(pcm: ShortArray): ByteArray = byteArrayOf(0xAA.toByte(), 0xBB.toByte())
override fun release() {}
}
companion object {
private val TEST_ROOM =
NestsRoomConfig(
authBaseUrl = "https://relay.example/api/v1/nests",
endpoint = "https://relay.example/moq",
hostPubkey = "0".repeat(64),
roomId = "test-room",
)
}
}