diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 2dfe6b5e..1cdc3724 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -649,6 +649,12 @@ Accepted by %1$s of %2$s relays. Copy raw JSON Copied the raw JSON + + Broadcast all + Sending entry %1$s of %2$s… + Accepted by every relay for %1$s of %2$s entries. + No relays to send it to: every relay the group named is blocked. + %1$s · %2$s A password-protected key (ncryptsec) is not supported yet. Decrypt it in the app it came from and paste the nsec. Enter a recovery phrase or an nsec to sign in. diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/database/model/GroupSignedEvent.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/database/model/GroupSignedEvent.kt index 0f09eb33..f848c584 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/database/model/GroupSignedEvent.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/database/model/GroupSignedEvent.kt @@ -36,9 +36,10 @@ import to.curare.compose.nostr.frost.GroupKeyStateEvent * columns are `NostrEvent`'s so that what is stored is an event rather than a * summary of one, which is what makes [verifies] answerable from the row alone. * - * The one way one reaches a relay is a member sending it there by hand, from - * `BroadcastGroupSignedEventScreen`, and that path serialises the row straight - * to the pool without ever making a `NostrEvent` of it -- see + * The one way one reaches a relay is a member sending it there by hand -- from + * `BroadcastGroupSignedEventScreen`, or every accepted entry at once from the + * entries screen -- and that path serialises the row straight to the pool + * without ever making a `NostrEvent` of it -- see * `BroadcastGroupSignedEventViewModel` for why a row would be the wrong shape. * * ### The derivation path diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/GroupCuratedEntry.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/GroupCuratedEntry.kt index 7d56c270..4084e7bb 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/GroupCuratedEntry.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/GroupCuratedEntry.kt @@ -49,7 +49,8 @@ import kotlin.time.Instant * queue screen marks a suggestion curated only from a copy read back off the * list's relays, so until a member broadcasts an entry from this section the * queue still shows it waiting. The broadcast button under each card is how - * it gets there. + * it gets there, or the one at the bottom of the entries screen that sends + * all of them. */ data class GroupCuratedEntry( /** The group's statement, whole, with the signature that makes it one. */ diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/BroadcastGroupSignedEventScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/BroadcastGroupSignedEventScreen.kt index 3807c147..73a3c97c 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/BroadcastGroupSignedEventScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/BroadcastGroupSignedEventScreen.kt @@ -69,11 +69,6 @@ import curare.composeapp.generated.resources.copied_the_raw_json import curare.composeapp.generated.resources.copy_raw_json import curare.composeapp.generated.resources.eg_wss_relay_example_com import curare.composeapp.generated.resources.no_relays_to_broadcast_to -import curare.composeapp.generated.resources.relay_accepted -import curare.composeapp.generated.resources.relay_could_not_send -import curare.composeapp.generated.resources.relay_no_answer -import curare.composeapp.generated.resources.relay_rejected -import curare.composeapp.generated.resources.relay_sending import curare.composeapp.generated.resources.relay_url import curare.composeapp.generated.resources.relays import curare.composeapp.generated.resources.sends_the_event_exactly_as_the_group_signed_it @@ -96,6 +91,7 @@ import to.curare.compose.ui.composable.widgets.ErrorState import to.curare.compose.ui.composable.widgets.LoadingDataIndicator import to.curare.compose.ui.composable.widgets.LocalSnackbarHostState import to.curare.compose.ui.composable.widgets.ScreenStateTransition +import to.curare.compose.ui.composable.widgets.label import to.curare.compose.ui.composable.widgets.rememberNotifier import to.curare.compose.ui.composable.widgets.NavigateBackButton import to.curare.compose.ui.theme.ConformancePreviews @@ -539,15 +535,7 @@ private fun BroadcastRelayRow( outcome?.let { Text( - text = when (it) { - RelayOutcome.Sending -> stringResource(Res.string.relay_sending) - RelayOutcome.Accepted -> stringResource(Res.string.relay_accepted) - is RelayOutcome.Rejected -> - stringResource(Res.string.relay_rejected, it.reason) - is RelayOutcome.Failed -> - stringResource(Res.string.relay_could_not_send, it.reason) - RelayOutcome.NoAnswer -> stringResource(Res.string.relay_no_answer) - }, + text = it.label(), style = MaterialTheme.typography.bodySmall, color = when (it) { RelayOutcome.Accepted -> MaterialTheme.colorScheme.primary diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/GroupCuratedEntriesScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/GroupCuratedEntriesScreen.kt index 2ebba572..29715a26 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/GroupCuratedEntriesScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/GroupCuratedEntriesScreen.kt @@ -10,9 +10,14 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.CellTower import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material3.BottomAppBar +import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExtendedFloatingActionButton +import androidx.compose.material3.FloatingActionButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.ListItem import androidx.compose.material3.MaterialTheme @@ -21,25 +26,43 @@ import androidx.compose.material3.SnackbarHost import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar +import androidx.compose.material3.contentColorFor import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.disabled +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.lifecycle.viewmodel.compose.viewModel import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl import curare.composeapp.generated.resources.Res +import curare.composeapp.generated.resources.accepted_by_every_relay_for_n_of_m_entries +import curare.composeapp.generated.resources.accepted_by_n_of_m_relays +import curare.composeapp.generated.resources.broadcast_all import curare.composeapp.generated.resources.curated_entries import curare.composeapp.generated.resources.in_list +import curare.composeapp.generated.resources.no_relays_to_send_it_to +import curare.composeapp.generated.resources.relay_and_answer +import curare.composeapp.generated.resources.relay_sending +import curare.composeapp.generated.resources.sending_entry_n_of_m import curare.composeapp.generated.resources.signed_by_the_group_on import curare.composeapp.generated.resources.suggested_by import curare.composeapp.generated.resources.this_group_has_not_accepted_anything_into_a_list_yet +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emptyFlow import org.jetbrains.compose.resources.stringResource import to.curare.compose.database.model.ChatRoom import to.curare.compose.database.model.GroupSignedEvent +import to.curare.compose.database.model.NostrEvent import to.curare.compose.database.model.intermdiate.LocalChatRoom import to.curare.compose.extensions.shortened import to.curare.compose.extensions.toFormattedTimeAndDateString +import to.curare.compose.network.dto.RelayDTO +import to.curare.compose.network.relays.EventPublishTransport +import to.curare.compose.network.relays.NostrPublishResult import to.curare.compose.nostr.GroupCuratedEntry import to.curare.compose.nostr.GroupCuratedSchema import to.curare.compose.nostr.curated.CuratedEntry @@ -59,11 +82,14 @@ import to.curare.compose.ui.composable.widgets.LocalSnackbarHostState import to.curare.compose.ui.composable.widgets.NavigateBackButton import to.curare.compose.ui.composable.widgets.ScreenStateTransition import to.curare.compose.ui.composable.widgets.buttons.BroadcastButton +import to.curare.compose.ui.composable.widgets.label import to.curare.compose.ui.theme.ConformancePreviews import to.curare.compose.ui.theme.CurareTheme import to.curare.compose.ui.theme.readableContent import to.curare.compose.ui.theme.spacing import to.curare.compose.ui.view.model.GroupCuratedEntriesViewModel +import to.curare.compose.ui.view.model.GroupCuratedEntriesViewModel.BroadcastAllProgress +import to.curare.compose.ui.view.model.GroupCuratedEntriesViewModel.EntryBroadcast import to.curare.compose.ui.view.state.GroupCuratedEntriesUIState import kotlin.time.Instant @@ -72,9 +98,16 @@ import kotlin.time.Instant * * Pushed from its row on the group's screen, which counts the entries and * nothing more. This is where they are read: one card per entry with a - * broadcast under it. No gate on either, because reading what the group - * decided takes no share of the key, and neither does repeating its signature - * to a relay. + * broadcast under it, and one button at the bottom that broadcasts all of + * them. No gate on any of it, because reading what the group decided takes + * no share of the key, and neither does repeating its signature to a relay. + * + * The two broadcasts differ in what the member sees first. The button under + * a card opens `BroadcastGroupSignedEventScreen`, where the relays are shown + * and can be changed before the send; the one at the bottom sends every + * entry straight to where that screen would have started, one after another, + * and says under each card what its relays answered. See + * `GroupCuratedEntriesViewModel.broadcastAll` for why one at a time. * * There is no way in to add one here, because an entry is accepted from the * queue it was suggested to, which is reached from its schema's card on the @@ -89,6 +122,7 @@ fun GroupCuratedEntriesScreen( initialGroupCuratedEntriesUIState: GroupCuratedEntriesUIState = GroupCuratedEntriesUIState.Loading, chatRepository: ChatRepository, + publishTransport: EventPublishTransport, onNavigateToRoute: (Route) -> Unit, onNavigateBack: () -> Unit, ) { @@ -97,6 +131,7 @@ fun GroupCuratedEntriesScreen( chatRoomId = chatRoomId, initialGroupCuratedEntriesUIState = initialGroupCuratedEntriesUIState, chatRepository = chatRepository, + publishTransport = publishTransport, ) ) @@ -119,6 +154,53 @@ fun GroupCuratedEntriesScreen( }, navigationIcon = { NavigateBackButton(onNavigateBack) } ) + }, + bottomBar = { + // Only over a list with something in it. The empty state already + // says why there is nothing to send, and a button that sends + // nothing under it would say the opposite. + val loaded = groupCuratedEntriesViewModel.groupCuratedEntriesUIState + as? GroupCuratedEntriesUIState.Loaded + + if (loaded != null && loaded.groupCuratedEntries.isNotEmpty()) { + val canSend = !groupCuratedEntriesViewModel.isActionPending.value + + // M3 gives a FAB no `enabled`, so borrow the disabled colours every + // other button in the app uses rather than inventing a shade here. + val buttonColors = ButtonDefaults.buttonColors() + + BottomAppBar( + actions = {}, + floatingActionButton = { + ExtendedFloatingActionButton( + modifier = if (canSend) { + Modifier + } else { + // Looking unavailable is not being unavailable. + Modifier.semantics { disabled() } + }, + containerColor = if (canSend) { + FloatingActionButtonDefaults.containerColor + } else { + buttonColors.disabledContainerColor + }, + contentColor = if (canSend) { + contentColorFor(FloatingActionButtonDefaults.containerColor) + } else { + buttonColors.disabledContentColor + }, + onClick = { + if (!canSend) return@ExtendedFloatingActionButton + + groupCuratedEntriesViewModel.broadcastAll() + } + ) { + Icon(Icons.Default.CellTower, contentDescription = Decorative) + Text(stringResource(Res.string.broadcast_all)) + } + } + ) + } } ) { padding -> ScreenStateTransition(groupCuratedEntriesViewModel.groupCuratedEntriesUIState) { uiState -> @@ -162,19 +244,37 @@ fun GroupCuratedEntriesScreen( ) } } else { + // The last press of "Broadcast all", summed up, above + // the cards that break it down. Persistent rather than + // a snackbar, because it is the answer the member came + // for and a snackbar would be gone before the last + // card had been read. + groupCuratedEntriesViewModel.broadcastAllProgress?.let { progress -> + item(key = "broadcast-all-progress") { + BroadcastAllProgressLine(progress = progress) + } + } + items( items = state.groupCuratedEntries, key = { accepted -> accepted.signedEvent.id } ) { accepted -> - // The card and its broadcast as one item, so the - // button stays under the entry it sends however - // the list is arranged. + // The card, what its relays answered, and its + // broadcast as one item, so all three stay under + // the entry they are about however the list is + // arranged. The answer sits above the button + // because the button is what a refusal calls for: + // it opens the screen where the relay can be + // changed and the send tried again. Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { GroupCuratedEntryCard(accepted = accepted) + groupCuratedEntriesViewModel.entryBroadcasts[accepted.signedEvent.id] + ?.let { EntryBroadcastLines(broadcast = it) } + BroadcastButton( onClick = { onNavigateToRoute.invoke( @@ -197,6 +297,106 @@ fun GroupCuratedEntriesScreen( } } +/** + * Where "Broadcast all" has got to: which entry is out while the batch runs, + * and how many were accepted everywhere once it is done -- in the primary + * colour when that is all of them, and the error colour when the cards below + * have a refusal to show. + */ +@Composable +private fun BroadcastAllProgressLine(progress: BroadcastAllProgress) { + Text( + text = when (progress) { + is BroadcastAllProgress.Sending -> + stringResource(Res.string.sending_entry_n_of_m, progress.entry, progress.total) + is BroadcastAllProgress.Done -> + stringResource( + Res.string.accepted_by_every_relay_for_n_of_m_entries, + progress.acceptedEverywhere, + progress.total + ) + }, + style = MaterialTheme.typography.bodyMedium, + color = when (progress) { + is BroadcastAllProgress.Sending -> MaterialTheme.colorScheme.onSurfaceVariant + is BroadcastAllProgress.Done -> if (progress.acceptedEverywhere == progress.total) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.error + } + }, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth() + ) +} + +/** + * What one entry's relays answered to "Broadcast all", under its card. + * + * The count first, in the words the one-event screen uses for its own; then + * one line per relay that did not say OK, in the relay's words, because + * "blocked: not on the allow list" is something a member can act on and a + * count of two out of three is not. A relay that said OK is in the count and + * nowhere else. + */ +@Composable +private fun EntryBroadcastLines(broadcast: EntryBroadcast) { + Column( + modifier = Modifier.fillMaxWidth().padding(vertical = MaterialTheme.spacing.relatedGap), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + horizontalAlignment = Alignment.CenterHorizontally + ) { + when (broadcast) { + EntryBroadcast.Sending -> Text( + text = stringResource(Res.string.relay_sending), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center + ) + + EntryBroadcast.NoRelays -> Text( + text = stringResource(Res.string.no_relays_to_send_it_to), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + textAlign = TextAlign.Center + ) + + is EntryBroadcast.Sent -> { + Text( + text = stringResource( + Res.string.accepted_by_n_of_m_relays, + broadcast.accepted, + broadcast.asked + ), + style = MaterialTheme.typography.bodySmall, + color = if (broadcast.isAcceptedEverywhere) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.error + }, + textAlign = TextAlign.Center + ) + + broadcast.refusals.forEach { (relay, outcome) -> + Text( + text = stringResource( + Res.string.relay_and_answer, + // The host rather than the whole URL, as the + // one-event screen's rows: every relay here starts + // `wss://`. + relay.displayUrl(), + outcome.label() + ), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.error, + textAlign = TextAlign.Center + ) + } + } + } + } +} + /** * One entry the group accepted into a list it curates, as the list's own word. * @@ -357,6 +557,12 @@ private fun GroupCuratedEntriesScreenPreview() { ) ), chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + publishTransport = object : EventPublishTransport { + override suspend fun publishEvent( + nostrEvent: NostrEvent, + relays: Set + ): Flow = emptyFlow() + }, onNavigateToRoute = {}, onNavigateBack = {}, ) diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/CurareNavHost.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/CurareNavHost.kt index 95eeaf8d..eb6f22da 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/CurareNavHost.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/CurareNavHost.kt @@ -1245,6 +1245,10 @@ fun CurareNavHost( chatRoomId = route.chatRoomId, relayHint = route.relayHint, chatRepository = databaseChatRepository, + // The pool itself, for "Broadcast all": the same send as the + // broadcast screen's, for the same reason it does not go + // through the queue. See `BroadcastGroupSignedEventViewModel`. + publishTransport = synchronizationViewModel.relaysSocketManager, onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, @@ -1399,9 +1403,10 @@ fun CurareNavHost( relayHint = route.relayHint, signedEventId = route.signedEventId, chatRepository = databaseChatRepository, - // The one screen handed the pool itself rather than a queue - // to write to: a group-signed event must not become a - // `NostrEvent` row, and the queue hangs off one. See + // Handed the pool itself rather than a queue to write to, + // as the entries screen is for its "Broadcast all": a + // group-signed event must not become a `NostrEvent` row, and + // the queue hangs off one. See // `BroadcastGroupSignedEventViewModel`. publishTransport = synchronizationViewModel.relaysSocketManager, onNavigateBack = { diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/RelayOutcomeLabel.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/RelayOutcomeLabel.kt new file mode 100644 index 00000000..152e7cdb --- /dev/null +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/RelayOutcomeLabel.kt @@ -0,0 +1,30 @@ +package to.curare.compose.ui.composable.widgets + +import androidx.compose.runtime.Composable +import curare.composeapp.generated.resources.Res +import curare.composeapp.generated.resources.relay_accepted +import curare.composeapp.generated.resources.relay_could_not_send +import curare.composeapp.generated.resources.relay_no_answer +import curare.composeapp.generated.resources.relay_rejected +import curare.composeapp.generated.resources.relay_sending +import org.jetbrains.compose.resources.stringResource +import to.curare.compose.ui.view.model.BroadcastGroupSignedEventViewModel.RelayOutcome + +/** + * One relay's answer to a broadcast, in the words both screens that show one + * use for it: the row under a relay on `BroadcastGroupSignedEventScreen`, and + * the line under an entry that "Broadcast all" sent. + * + * A rejection and a failure carry the relay's own reason, because "blocked: + * not on the allow list" is something a member can act on and a red icon is + * not. One spelling for both screens, so a relay's answer reads the same + * whichever button sent to it. + */ +@Composable +fun RelayOutcome.label(): String = when (this) { + RelayOutcome.Sending -> stringResource(Res.string.relay_sending) + RelayOutcome.Accepted -> stringResource(Res.string.relay_accepted) + is RelayOutcome.Rejected -> stringResource(Res.string.relay_rejected, reason) + is RelayOutcome.Failed -> stringResource(Res.string.relay_could_not_send, reason) + RelayOutcome.NoAnswer -> stringResource(Res.string.relay_no_answer) +} diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt index e506e620..beb3c610 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt @@ -52,6 +52,11 @@ import kotlin.time.Duration.Companion.milliseconds * event exactly as the group signed it -- the signature is the group's, so any * member holding the event can send it and no share of the key is needed. * + * The send itself, [sendToRelays], is also what the entries screen's "Broadcast + * all" uses, one entry after another and each to the relays [defaultRelaysFor] + * would have seeded here; what is this screen's is the list the member edits + * and the rows that show each relay's answer. + * * ### Why not the broadcast queue * * Everything the app publishes as itself goes through `BroadcastNostrEventRequest`, @@ -88,8 +93,6 @@ class BroadcastGroupSignedEventViewModel( ) private set - private val logger = Logger.withTag(TAG) - val isActionPending: MutableState = mutableStateOf(false) /** @@ -238,17 +241,15 @@ class BroadcastGroupSignedEventViewModel( /** * Sends [signedEvent] to every relay in the list and records what each said. * - * One call to the pool for the whole list, which opens a socket to any relay - * it does not hold and answers once per relay -- an OK, a rejection with the - * relay's reason, or the error that stopped it being asked. Each answer lands - * in [outcomes] as it arrives, so the rows fill in one by one rather than all - * at the end; a relay that has not answered when the whole thing runs out of - * time is marked so, which is different from having been refused. + * The send itself is [sendToRelays], which the entries screen's + * "Broadcast all" shares; what is this screen's is the state around it. + * Each answer lands in [outcomes] as it arrives, so the rows fill in one + * by one rather than all at the end, and [lastBroadcast] sums it up once + * every row has settled. * - * [lastBroadcast] sums it up once every row has settled. [onNoRelays] instead - * of a send to nobody: an empty list is a question rather than a mistake, and - * the pool would otherwise fall back to the *member's* relays, which is not - * what an empty list on this screen means. + * [onNoRelays] instead of a send to nobody: an empty list is a question + * rather than a mistake, and the pool would otherwise fall back to the + * *member's* relays, which is not what an empty list on this screen means. * * Returns the send, for a caller that has to wait for it, and null when * nothing was sent. @@ -272,43 +273,13 @@ class BroadcastGroupSignedEventViewModel( outcomes.clear() targets.forEach { outcomes[it] = RelayOutcome.Sending } - val wireEvent = wireEventOf(signedEvent) - return viewModelScope.launch(Dispatchers.IO) { - try { - withTimeout(BROADCAST_TIMEOUT) { - publishTransport.publishEvent( - nostrEvent = wireEvent, - relays = targets.map { RelayDTO(url = it.url, read = false, write = true) }.toSet(), - ) - // One answer per relay is all the pool ever gives, and the - // flow underneath never completes on its own. - .take(targets.size) - .collect { result -> record(targets, result) } - } - } catch (e: TimeoutCancellationException) { - // Ordinary: a relay that never answers is what the timeout is - // for. The rows still marked as sending are settled below. - logger.w("Broadcast of ${signedEvent.id} ran out of time") - } catch (e: CancellationException) { - throw e - } catch (e: Throwable) { - // The pool refused the whole call rather than one relay's part of - // it, so every row that was waiting gets the same answer. - logger.e("Broadcast of ${signedEvent.id} failed before any relay answered", e) - targets.forEach { relay -> - if (outcomes[relay] == RelayOutcome.Sending) { - outcomes[relay] = RelayOutcome.Failed(e.message ?: "Could not send") - } - } - } - - targets.forEach { relay -> - if (outcomes[relay] == RelayOutcome.Sending) outcomes[relay] = RelayOutcome.NoAnswer + val settled = sendToRelays(publishTransport, signedEvent, targets) { relay, outcome -> + outcomes[relay] = outcome } lastBroadcast = BroadcastSummary( - accepted = targets.count { outcomes[it] == RelayOutcome.Accepted }, + accepted = settled.count { it.value == RelayOutcome.Accepted }, asked = targets.size, ) @@ -316,37 +287,11 @@ class BroadcastGroupSignedEventViewModel( } } - /** - * Files one relay's answer against the row that asked it. - * - * Matched by host rather than by string, because the pool names a relay by - * the URL it first opened a socket with, and that may carry a trailing slash - * this list's spelling does not. - */ - private fun record(targets: List, result: NostrPublishResult) { - val answered = NormalizedRelayUrl(result.relayUrl).displayUrl() - val relay = targets.firstOrNull { it.displayUrl() == answered } ?: run { - logger.w("Answer from ${result.relayUrl}, which was not asked") - return - } - - val error = result.error - val ok = result.result as? NostrIncomingMessage.OkMessage - - outcomes[relay] = when { - // The pool wraps a relay's ["OK", id, false, reason] in this one - // exception type and nothing else in it, so the message is the - // relay's reason in the relay's words. - error is NostrPublishException -> RelayOutcome.Rejected(error.message ?: "Rejected") - error != null -> RelayOutcome.Failed(error.message ?: "Could not send") - ok?.success == true -> RelayOutcome.Accepted - else -> RelayOutcome.Failed("No OK from the relay") - } - } - companion object { private const val TAG = "BroadcastGroupSignedEventViewModel" + private val logger = Logger.withTag(TAG) + /** * A ceiling on the whole broadcast, past the pool's own per-relay wait, * so a socket that opens and then says nothing cannot hold the button @@ -354,6 +299,103 @@ class BroadcastGroupSignedEventViewModel( */ val BROADCAST_TIMEOUT = (RelayPool.PUBLISH_TIMEOUT * 2).milliseconds + /** + * Sends [signedEvent] to [targets] and says what each relay answered. + * + * One call to the pool for the whole list, which opens a socket to any + * relay it does not hold and answers once per relay -- an OK, a + * rejection with the relay's reason, or the error that stopped it being + * asked. Each answer goes to [onOutcome] as it arrives, so a caller + * showing rows can fill them in one by one rather than all at the end; + * a relay that has not answered when the whole thing runs out of time + * is marked so, which is different from having been refused, and one + * the pool refused to ask at all is marked failed with the pool's reason. + * + * Returns once every relay has settled, with the answers in the order + * [targets] gave them. Shared by the one-event screen and the entries + * screen's "Broadcast all", so that what a relay's answer becomes is + * decided in one place. + */ + suspend fun sendToRelays( + publishTransport: EventPublishTransport, + signedEvent: GroupSignedEvent, + targets: List, + onOutcome: (NormalizedRelayUrl, RelayOutcome) -> Unit = { _, _ -> }, + ): Map { + val outcomes = mutableMapOf() + + fun settle(relay: NormalizedRelayUrl, outcome: RelayOutcome) { + outcomes[relay] = outcome + onOutcome(relay, outcome) + } + + try { + withTimeout(BROADCAST_TIMEOUT) { + publishTransport.publishEvent( + nostrEvent = wireEventOf(signedEvent), + relays = targets.map { RelayDTO(url = it.url, read = false, write = true) }.toSet(), + ) + // One answer per relay is all the pool ever gives, and the + // flow underneath never completes on its own. + .take(targets.size) + .collect { result -> + outcomeOf(targets, result)?.let { (relay, outcome) -> settle(relay, outcome) } + } + } + } catch (e: TimeoutCancellationException) { + // Ordinary: a relay that never answers is what the timeout is + // for. The relays still unanswered are settled below. + logger.w("Broadcast of ${signedEvent.id} ran out of time") + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + // The pool refused the whole call rather than one relay's part of + // it, so every relay that was waiting gets the same answer. + logger.e("Broadcast of ${signedEvent.id} failed before any relay answered", e) + targets.forEach { relay -> + if (relay !in outcomes) settle(relay, RelayOutcome.Failed(e.message ?: "Could not send")) + } + } + + targets.forEach { relay -> + if (relay !in outcomes) settle(relay, RelayOutcome.NoAnswer) + } + + return targets.associateWith { outcomes.getValue(it) } + } + + /** + * One relay's answer, against the relay that was asked. + * + * Matched by host rather than by string, because the pool names a relay + * by the URL it first opened a socket with, and that may carry a + * trailing slash the caller's spelling does not. Null for an answer + * from a relay nobody asked, which is logged and dropped. + */ + private fun outcomeOf( + targets: List, + result: NostrPublishResult, + ): Pair? { + val answered = NormalizedRelayUrl(result.relayUrl).displayUrl() + val relay = targets.firstOrNull { it.displayUrl() == answered } ?: run { + logger.w("Answer from ${result.relayUrl}, which was not asked") + return null + } + + val error = result.error + val ok = result.result as? NostrIncomingMessage.OkMessage + + return relay to when { + // The pool wraps a relay's ["OK", id, false, reason] in this one + // exception type and nothing else in it, so the message is the + // relay's reason in the relay's words. + error is NostrPublishException -> RelayOutcome.Rejected(error.message ?: "Rejected") + error != null -> RelayOutcome.Failed(error.message ?: "Could not send") + ok?.success == true -> RelayOutcome.Accepted + else -> RelayOutcome.Failed("No OK from the relay") + } + } + /** * The event as the pool wants it, and nothing more. * diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/GroupCuratedEntriesViewModel.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/GroupCuratedEntriesViewModel.kt index 06fb12f9..9e9653e1 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/GroupCuratedEntriesViewModel.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/GroupCuratedEntriesViewModel.kt @@ -1,6 +1,8 @@ package to.curare.compose.ui.view.model +import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel @@ -8,10 +10,16 @@ import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO +import kotlinx.coroutines.Job import kotlinx.coroutines.launch +import to.curare.compose.network.relays.EventPublishTransport +import to.curare.compose.nostr.GroupCuratedEntry import to.curare.compose.repository.ChatRepository +import to.curare.compose.ui.view.model.BroadcastGroupSignedEventViewModel.RelayOutcome import to.curare.compose.ui.view.state.GroupCuratedEntriesUIState /** @@ -19,11 +27,34 @@ import to.curare.compose.ui.view.state.GroupCuratedEntriesUIState * that shows them. One read rather than a watch, for the reason * `GroupNostrProfileViewModel` gives. Nothing here asks whether this device * can sign, because nothing on the screen would change if it could. + * + * ### Broadcast all + * + * The one thing the screen does besides show: [broadcastAll] sends every + * entry, one after another, each to the relays its own broadcast screen would + * have filled in -- `defaultRelaysFor`, read against the group's relay lists + * and the entry's own schema -- and says under each card what its relays + * answered. The member sees nothing before pressing, which is the difference + * from sending one at a time: that screen exists so the relays can be read + * and changed first, and this button is for the member who has read them + * once and has twenty entries to send. The seeded list is what a member who + * reads nothing and presses the button sends to there too. + * + * One entry at a time rather than all at once, for two reasons. The rows fill + * in top to bottom, so the member can see where the batch is; and a public + * relay sent twenty events in one burst answers "rate-limited" to most of + * them, which would make the button worse than the twenty presses it saves. + * Each entry's send is bounded by the same ceiling as a single broadcast, + * and the whole batch by nothing but that, since a long list is meant to + * take a while. It goes to the pool directly rather than through the queue, + * for the reason `BroadcastGroupSignedEventViewModel` gives, and it is only + * as durable as the button press: leaving the screen ends it where it is. */ class GroupCuratedEntriesViewModel( val chatRoomId: String, initialGroupCuratedEntriesUIState: GroupCuratedEntriesUIState, val chatRepository: ChatRepository, + val publishTransport: EventPublishTransport, ): ViewModel() { var groupCuratedEntriesUIState: GroupCuratedEntriesUIState by mutableStateOf( @@ -31,6 +62,69 @@ class GroupCuratedEntriesViewModel( ) private set + val isActionPending: MutableState = mutableStateOf(false) + + /** + * How each entry's send went the last time the button was pressed, keyed + * by the signed event's id. An entry the batch has not reached yet has + * none, which is how the screen tells "not yet" from "sending". + */ + val entryBroadcasts = mutableStateMapOf() + + /** + * Where the last press has got to, or null before the first one. + * + * On the screen rather than in a snackbar, for the reason the one-event + * screen gives: it is the answer the member came for, and it should still + * be there once the cards under it have been read. Cleared when the next + * press starts. + */ + var broadcastAllProgress: BroadcastAllProgress? by mutableStateOf(null) + private set + + /** One entry's part of one press of the button. */ + sealed interface EntryBroadcast { + /** Sent, and not every relay has answered yet. */ + data object Sending : EntryBroadcast + + /** + * Not sent, because there was nowhere to send it: everything the seed + * rule would have named is on the group's blocked list. The one-event + * screen meets the same case as an empty list and a snackbar. + */ + data object NoRelays : EntryBroadcast + + /** Every relay has answered, or been given up on. */ + data class Sent(val outcomes: Map) : EntryBroadcast { + val accepted: Int get() = outcomes.count { it.value == RelayOutcome.Accepted } + + val asked: Int get() = outcomes.size + + val isAcceptedEverywhere: Boolean get() = accepted == asked + + /** + * The relays that did not say OK, with what they said instead, in + * the order they were asked. Named under the count because the + * relay's reason is what a member can act on, and a count is not. + */ + val refusals: List> + get() = outcomes.filterValues { it != RelayOutcome.Accepted }.toList() + } + } + + /** How far the last press has got, and then how it went. */ + sealed interface BroadcastAllProgress { + /** Entry [entry] of [total] is out, counting from one. */ + data class Sending(val entry: Int, val total: Int) : BroadcastAllProgress + + /** + * Every entry has been sent, and [acceptedEverywhere] of [total] were + * accepted by every relay they went to. The rest say under their own + * cards which relay refused, and why. + */ + data class Done(val acceptedEverywhere: Int, val total: Int) : BroadcastAllProgress + } + fun initiate() { viewModelScope.launch(Dispatchers.IO) { val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) @@ -41,23 +135,96 @@ class GroupCuratedEntriesViewModel( GroupCuratedEntriesUIState.Loaded( localChatRoom = localChatRoom, groupCuratedEntries = chatRepository.groupCuratedEntries(chatRoomId), + relayLists = chatRepository.groupRelayLists(chatRoomId), ) } } } + /** + * Sends every entry on the screen, in the order it shows them, and records + * what each one's relays said. + * + * Returns the batch, for a caller that has to wait for it, and null when + * nothing was sent: a press while one is already out, or a screen with no + * entries on it, which has no button. + */ + fun broadcastAll(): Job? { + // Guard against double submits. A second press while the first is out + // would send every entry twice and count each answer twice. + if (isActionPending.value) return null + + val state = groupCuratedEntriesUIState as? GroupCuratedEntriesUIState.Loaded ?: return null + val entries = state.groupCuratedEntries + if (entries.isEmpty()) return null + + isActionPending.value = true + broadcastAllProgress = null + entryBroadcasts.clear() + + return viewModelScope.launch(Dispatchers.IO) { + var acceptedEverywhere = 0 + + entries.forEachIndexed { index, accepted -> + broadcastAllProgress = BroadcastAllProgress.Sending(entry = index + 1, total = entries.size) + + val sent = send(accepted, state) + entryBroadcasts[accepted.signedEvent.id] = sent + if (sent is EntryBroadcast.Sent && sent.isAcceptedEverywhere) acceptedEverywhere++ + } + + broadcastAllProgress = BroadcastAllProgress.Done( + acceptedEverywhere = acceptedEverywhere, + total = entries.size, + ) + + isActionPending.value = false + } + } + + /** + * One entry, to where its own broadcast screen would have sent it. + * + * The relays are the seed rule's, read against the group's lists and the + * entry's own schema -- an entry carries the list it is in, so the rule + * is handed that one schema rather than all of the group's. + */ + private suspend fun send( + accepted: GroupCuratedEntry, + state: GroupCuratedEntriesUIState.Loaded, + ): EntryBroadcast { + val signedEvent = accepted.signedEvent + val targets = BroadcastGroupSignedEventViewModel.defaultRelaysFor( + relayLists = state.relayLists, + kind = signedEvent.kind, + tags = signedEvent.tags, + content = signedEvent.content, + schemas = listOf(accepted.list), + ) + + if (targets.isEmpty()) return EntryBroadcast.NoRelays + + entryBroadcasts[signedEvent.id] = EntryBroadcast.Sending + + return EntryBroadcast.Sent( + BroadcastGroupSignedEventViewModel.sendToRelays(publishTransport, signedEvent, targets) + ) + } + companion object { fun factory( chatRoomId: String, initialGroupCuratedEntriesUIState: GroupCuratedEntriesUIState = GroupCuratedEntriesUIState.Loading, chatRepository: ChatRepository, + publishTransport: EventPublishTransport, ): ViewModelProvider.Factory = viewModelFactory { initializer { GroupCuratedEntriesViewModel( chatRoomId = chatRoomId, initialGroupCuratedEntriesUIState = initialGroupCuratedEntriesUIState, chatRepository = chatRepository, + publishTransport = publishTransport, ) } } diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/state/GroupCuratedEntriesUIState.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/state/GroupCuratedEntriesUIState.kt index da4ec1f7..2d32b1a1 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/state/GroupCuratedEntriesUIState.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/state/GroupCuratedEntriesUIState.kt @@ -2,6 +2,7 @@ package to.curare.compose.ui.view.state import to.curare.compose.database.model.intermdiate.LocalChatRoom import to.curare.compose.nostr.GroupCuratedEntry +import to.curare.compose.nostr.GroupRelayList sealed interface GroupCuratedEntriesUIState { data class Loaded( @@ -16,6 +17,14 @@ sealed interface GroupCuratedEntriesUIState { * neither does repeating its signature to a relay. */ val groupCuratedEntries: List = emptyList(), + /** + * Where the group has said it lives, for "Broadcast all": each entry + * goes where its own broadcast screen would send it before the member + * changed anything, and that starts from these. See + * `BroadcastGroupSignedEventViewModel.defaultRelaysFor`; the list's + * own relays come off the entry, which carries its schema. + */ + val relayLists: List = emptyList(), ): GroupCuratedEntriesUIState data class Error( diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/GroupCuratedEntriesScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/GroupCuratedEntriesScreenJvmTest.kt index 9e03e537..1d931e6c 100644 --- a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/GroupCuratedEntriesScreenJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/GroupCuratedEntriesScreenJvmTest.kt @@ -12,7 +12,19 @@ import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.runDesktopComposeUiTest +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf +import to.curare.compose.database.model.NostrEvent +import to.curare.compose.exceptions.NostrPublishException +import to.curare.compose.network.dto.RelayDTO +import to.curare.compose.network.relays.EventPublishTransport +import to.curare.compose.network.relays.NostrPublishResult +import to.curare.compose.network.sockets.NostrIncomingMessage import to.curare.compose.nostr.GroupCuratedEntry +import to.curare.compose.nostr.GroupRelay +import to.curare.compose.nostr.GroupRelayList +import to.curare.compose.nostr.GroupRelaySet import to.curare.compose.repository.ChatRepository import to.curare.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey import to.curare.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId @@ -28,8 +40,8 @@ import kotlin.test.assertTrue /** * The entries the group has accepted on their own screen: one card per entry, - * most recently signed first, each with its broadcast and nothing else -- - * there is no way in to add one here. + * most recently signed first, each with its broadcast, and one button at the + * bottom that broadcasts all of them -- there is no way in to add one here. */ @OptIn(ExperimentalTestApi::class) class GroupCuratedEntriesScreenJvmTest { @@ -37,6 +49,19 @@ class GroupCuratedEntriesScreenJvmTest { private val newest = entry("The Rise and Rise of Bitcoin", 1_700_000_900) private val oldest = entry("Magic Money", 1_700_000_300, suggestedBy = null) + private val one = RelayUrlNormalizer.normalize("wss://relay.one.example") + private val two = RelayUrlNormalizer.normalize("wss://relay.two.example") + + /** A pool that answers each event as [answers] says and never opens a socket. */ + private class FakeTransport( + private val answers: (NostrEvent) -> List = { emptyList() } + ) : EventPublishTransport { + override suspend fun publishEvent( + nostrEvent: NostrEvent, + relays: Set + ): Flow = flowOf(*answers(nostrEvent).toTypedArray()) + } + @Test fun `the entries are drawn most recently signed first, one card per entry`() = render( state(entries = listOf(newest, oldest)) @@ -95,19 +120,100 @@ class GroupCuratedEntriesScreenJvmTest { .assertIsDisplayed() // An entry is accepted from the queue on its schema's card, on the - // schemas screen, so this screen has no button of its own. + // schemas screen, so this screen has no button of its own -- and + // nothing to broadcast, so no button for that either. onAllNodesWithText("Add entry").assertCountEquals(0) onAllNodesWithText("Broadcast").assertCountEquals(0) + onAllNodesWithText("Broadcast all").assertCountEquals(0) } + @Test + fun `the button at the bottom sends every entry, and each card says what its relays answered`() { + val ok = { relay: String, event: NostrEvent -> + NostrPublishResult( + result = NostrIncomingMessage.OkMessage(eventId = event.id, success = true), + relayUrl = relay, + ) + } + val transport = FakeTransport { event -> + if (event.id == newest.signedEvent.id) { + listOf(ok(two.url, event), ok(one.url, event)) + } else { + listOf( + ok(two.url, event), + NostrPublishResult( + result = NostrIncomingMessage.OkMessage( + eventId = event.id, + success = false, + message = "blocked: not on the allow list", + ), + error = NostrPublishException(message = "blocked: not on the allow list"), + relayUrl = one.url, + ), + ) + } + } + + render(state(entries = listOf(newest, oldest)), transport = transport) { + onNodeWithText("Broadcast all").performClick() + + // The sum above the cards, once the last has settled. + waitUntil(timeoutMillis = 5_000) { + onAllNodesWithText("Accepted by every relay for 1 of 2 entries.") + .fetchSemanticsNodes().isNotEmpty() + } + + // Each entry's count, and the one relay that refused named with its + // reason -- the relay that said OK is in the count and nowhere else. + onNodeWithText("Accepted by 2 of 2 relays.").assertIsDisplayed() + onNodeWithText("Accepted by 1 of 2 relays.").assertIsDisplayed() + onNodeWithText("relay.one.example · Rejected: blocked: not on the allow list") + .assertIsDisplayed() + onAllNodesWithText("relay.two.example", substring = true).assertCountEquals(0) + + // The sum above every card; each answer under its own card and + // above that card's broadcast, which is what a refusal calls for. + val sum = onNodeWithText("Accepted by every relay for 1 of 2 entries.").getBoundsInRoot().top + val firstCard = onNodeWithText("The Rise and Rise of Bitcoin").getBoundsInRoot().top + val firstAnswer = onNodeWithText("Accepted by 2 of 2 relays.").getBoundsInRoot().top + val secondCard = onNodeWithText("Magic Money").getBoundsInRoot().top + val secondAnswer = onNodeWithText("Accepted by 1 of 2 relays.").getBoundsInRoot().top + val buttons = onAllNodesWithText("Broadcast") + val firstButton = buttons[0].getBoundsInRoot().top + val secondButton = buttons[1].getBoundsInRoot().top + + assertTrue(sum < firstCard, "the sum is not above the cards") + assertTrue(firstCard < firstAnswer && firstAnswer < firstButton, "the first answer is not between its card and its broadcast") + assertTrue(firstButton < secondCard, "the second card climbed above the first's broadcast") + assertTrue(secondCard < secondAnswer && secondAnswer < secondButton, "the second answer is not between its card and its broadcast") + } + } + + /** + * A General list of [two] agreed, so each entry goes to one relay of the + * group's and one of its list's -- [one], which the fixture's schema names. + */ + private fun relayLists(): List = + GroupRelayList.allAmong(emptyList(), chatRoomId).map { list -> + if (list.set != GroupRelaySet.General) return@map list + + GroupRelayList( + set = list.set, + signedEvent = GroupSignedWorkFixtures.relaySignedEvent(list.set), + relays = listOf(GroupRelay(two)), + ) + } + private fun state(entries: List) = GroupCuratedEntriesUIState.Loaded( localChatRoom = GroupSignedWorkFixtures.localChatRoom(), - groupCuratedEntries = entries + groupCuratedEntries = entries, + relayLists = relayLists(), ) private fun render( uiState: GroupCuratedEntriesUIState, onNavigateToRoute: (Route) -> Unit = {}, + transport: EventPublishTransport = FakeTransport(), assertions: ComposeUiTest.() -> Unit ) = runDesktopComposeUiTest(width = 400, height = 2000) { setContent { @@ -120,6 +226,7 @@ class GroupCuratedEntriesScreenJvmTest { relayHint = null, initialGroupCuratedEntriesUIState = uiState, chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + publishTransport = transport, onNavigateToRoute = onNavigateToRoute, onNavigateBack = {}, ) diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/GroupSignedWorkFixtures.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/GroupSignedWorkFixtures.kt index 6c60de49..a150876b 100644 --- a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/GroupSignedWorkFixtures.kt +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/GroupSignedWorkFixtures.kt @@ -185,7 +185,14 @@ internal object GroupSignedWorkFixtures { chatRoomId = chatRoomId, publicKey = chatRoomId, kind = CuratedEntryEvent.CANONICAL_KIND, - tags = arrayOf(arrayOf("d", identifier), arrayOf("title", title)), + // The root names the list, as a real entry's does: it is how + // the reading matched the entry to its schema, and how the + // broadcast finds the list's relays. + tags = arrayOf( + arrayOf("a", list.coordinate(), "", "root"), + arrayOf("d", identifier), + arrayOf("title", title) + ), content = "", signature = "f".repeat(128), createdAt = Instant.fromEpochSeconds(createdAt) diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/GroupCuratedEntriesViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/GroupCuratedEntriesViewModelJvmTest.kt new file mode 100644 index 00000000..b51bec31 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/GroupCuratedEntriesViewModelJvmTest.kt @@ -0,0 +1,309 @@ +package to.curare.compose.ui.view.model + +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import to.curare.compose.database.model.NostrEvent +import to.curare.compose.exceptions.NostrPublishException +import to.curare.compose.network.dto.RelayDTO +import to.curare.compose.network.relays.EventPublishTransport +import to.curare.compose.network.relays.NostrPublishResult +import to.curare.compose.network.sockets.NostrIncomingMessage +import to.curare.compose.nostr.GroupCuratedEntry +import to.curare.compose.nostr.GroupRelay +import to.curare.compose.nostr.GroupRelayList +import to.curare.compose.nostr.GroupRelaySet +import to.curare.compose.repository.ChatRepository +import to.curare.compose.ui.composable.GroupSignedWorkFixtures +import to.curare.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId +import to.curare.compose.ui.composable.GroupSignedWorkFixtures.entry +import to.curare.compose.ui.view.model.BroadcastGroupSignedEventViewModel.RelayOutcome +import to.curare.compose.ui.view.model.GroupCuratedEntriesViewModel.BroadcastAllProgress +import to.curare.compose.ui.view.model.GroupCuratedEntriesViewModel.EntryBroadcast +import to.curare.compose.ui.view.state.GroupCuratedEntriesUIState +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * What "Broadcast all" decides that nothing else can check. + * + * **Where each entry goes.** The same relays its own broadcast screen would + * have filled in -- the group's General list plus the list the entry is in, + * minus what the group has blocked -- because the button is the member + * trusting that seed rather than editing it, and a rule that sent to + * anywhere else would make the two buttons disagree. + * + * **One after another, in the order shown.** The transport is asked once per + * entry, and the next is not asked until the last has settled. + * + * **What the answers become.** The count under each card and the sum above + * them, with a relay that refused named against its reason, and an entry with + * nowhere to go marked so rather than sent to nobody. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class GroupCuratedEntriesViewModelJvmTest { + + private val one = RelayUrlNormalizer.normalize("wss://relay.one.example") + private val two = RelayUrlNormalizer.normalize("wss://relay.two.example") + + /** + * Answers every event with [answers] and remembers each send in the order + * it was asked for. Holds every answer back until [gate] is completed, + * where a test hands one in, so a batch can be caught while it is out; + * [arrived] says when the first send has reached it. + */ + private class FakeTransport( + private val gate: CompletableDeferred? = null, + private val answers: (NostrEvent) -> List, + ) : EventPublishTransport { + val sends = mutableListOf>>() + + val arrived = CompletableDeferred() + + override suspend fun publishEvent( + nostrEvent: NostrEvent, + relays: Set + ): Flow { + sends += nostrEvent to relays + arrived.complete(Unit) + gate?.await() + return flowOf(*answers(nostrEvent).toTypedArray()) + } + } + + @BeforeTest + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + } + + private val newest = entry("The Rise and Rise of Bitcoin", 1_700_000_900) + private val oldest = entry("Magic Money", 1_700_000_300, suggestedBy = null) + + /** + * A General list of [two] agreed, so each entry has one relay of the + * group's and one of its list's ([one], which the fixture's schema names), + * plus whatever [blocked] takes away. + */ + private fun relayLists(blocked: List = emptyList()): List = + GroupRelayList.allAmong(emptyList(), chatRoomId).map { list -> + when (list.set) { + GroupRelaySet.General -> GroupRelayList( + set = list.set, + signedEvent = GroupSignedWorkFixtures.relaySignedEvent(list.set), + relays = listOf(GroupRelay(two)), + ) + GroupRelaySet.Blocked -> GroupRelayList( + set = list.set, + signedEvent = GroupSignedWorkFixtures.relaySignedEvent(list.set), + relays = blocked.map { GroupRelay(it) }, + ) + else -> list + } + } + + private fun viewModel( + transport: EventPublishTransport, + entries: List = listOf(newest, oldest), + relayLists: List = relayLists(), + ) = GroupCuratedEntriesViewModel( + chatRoomId = chatRoomId, + initialGroupCuratedEntriesUIState = GroupCuratedEntriesUIState.Loaded( + localChatRoom = GroupSignedWorkFixtures.localChatRoom(), + groupCuratedEntries = entries, + relayLists = relayLists, + ), + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + publishTransport = transport, + ) + + private fun ok(relay: NormalizedRelayUrl, event: NostrEvent) = NostrPublishResult( + result = NostrIncomingMessage.OkMessage(eventId = event.id, success = true), + relayUrl = relay.url, + ) + + private fun rejected(relay: NormalizedRelayUrl, event: NostrEvent, reason: String) = NostrPublishResult( + result = NostrIncomingMessage.OkMessage(eventId = event.id, success = false, message = reason), + error = NostrPublishException(message = reason), + relayUrl = relay.url, + ) + + private fun GroupCuratedEntriesViewModel.broadcastAllAndWait() { + val job = broadcastAll() + runBlocking { withTimeout(5_000) { job!!.join() } } + } + + // -- where each entry goes ---------------------------------------------------- + + @Test + fun `each entry goes where its own broadcast would, one after another, in the order shown`() { + val transport = FakeTransport { event -> listOf(ok(two, event), ok(one, event)) } + val viewModel = viewModel(transport) + + viewModel.broadcastAllAndWait() + + // The newest first, as the screen lists them, and nothing twice. + assertEquals( + listOf(newest.signedEvent.id, oldest.signedEvent.id), + transport.sends.map { it.first.id }, + ) + + // The group's General relay and the list's own, asked as write relays + // -- the pool would otherwise read from them too -- and what went was + // the event as the group signed it. + transport.sends.forEach { (event, relays) -> + assertEquals( + setOf(two, one).map { RelayDTO(url = it.url, read = false, write = true) }.toSet(), + relays, + ) + assertEquals("f".repeat(128), event.sig) + assertEquals(chatRoomId, event.pubKey) + } + } + + @Test + fun `a relay the group has blocked is left out, and an entry with nowhere to go is marked so`() { + val transport = FakeTransport { event -> listOf(ok(two, event)) } + + // Everything the seed would name is blocked, so nothing is asked. + val nowhere = viewModel(transport, relayLists = relayLists(blocked = listOf(one, two))) + nowhere.broadcastAllAndWait() + + assertTrue(transport.sends.isEmpty(), "an entry with nowhere to go was sent somewhere") + assertEquals(EntryBroadcast.NoRelays, nowhere.entryBroadcasts[newest.signedEvent.id]) + assertEquals(EntryBroadcast.NoRelays, nowhere.entryBroadcasts[oldest.signedEvent.id]) + assertEquals( + BroadcastAllProgress.Done(acceptedEverywhere = 0, total = 2), + nowhere.broadcastAllProgress, + ) + + // Only the list's relay blocked: the group's own is still asked. + val partly = viewModel(transport, relayLists = relayLists(blocked = listOf(one))) + partly.broadcastAllAndWait() + + assertEquals(2, transport.sends.size) + transport.sends.forEach { (_, relays) -> + assertEquals(setOf(two.url), relays.map { it.url }.toSet()) + } + } + + // -- what the answers become --------------------------------------------------- + + @Test + fun `each entry's count sits under it, a refusal is named with its reason, and the sum counts only the entries accepted everywhere`() { + val transport = FakeTransport { event -> + if (event.id == newest.signedEvent.id) { + listOf(ok(two, event), ok(one, event)) + } else { + listOf(ok(two, event), rejected(one, event, "blocked: not on the allow list")) + } + } + val viewModel = viewModel(transport) + + viewModel.broadcastAllAndWait() + + val first = assertIs(viewModel.entryBroadcasts[newest.signedEvent.id]) + assertEquals(2, first.accepted) + assertEquals(2, first.asked) + assertTrue(first.isAcceptedEverywhere) + assertEquals(emptyList(), first.refusals) + + val second = assertIs(viewModel.entryBroadcasts[oldest.signedEvent.id]) + assertEquals(1, second.accepted) + assertEquals(2, second.asked) + assertFalse(second.isAcceptedEverywhere) + assertEquals( + listOf(one to RelayOutcome.Rejected("blocked: not on the allow list")), + second.refusals, + ) + + assertEquals( + BroadcastAllProgress.Done(acceptedEverywhere = 1, total = 2), + viewModel.broadcastAllProgress, + ) + assertFalse(viewModel.isActionPending.value) + } + + @Test + fun `a relay that never answers counts against the entry, which is not the same as refused`() { + // The pool answers for one relay and then the flow ends, which is what + // a send that ran out of time looks like from here. + val transport = FakeTransport { event -> listOf(ok(two, event)) } + val viewModel = viewModel(transport, entries = listOf(newest)) + + viewModel.broadcastAllAndWait() + + val sent = assertIs(viewModel.entryBroadcasts[newest.signedEvent.id]) + assertEquals(listOf(one to RelayOutcome.NoAnswer), sent.refusals) + assertEquals( + BroadcastAllProgress.Done(acceptedEverywhere = 0, total = 1), + viewModel.broadcastAllProgress, + ) + } + + // -- when nothing is sent ---------------------------------------------------------- + + @Test + fun `the next entry waits for the last to settle, and a second press while one is out is refused`() { + val gate = CompletableDeferred() + val transport = FakeTransport(gate) { event -> listOf(ok(two, event), ok(one, event)) } + val viewModel = viewModel(transport) + + // The first press is held at the transport, so the second meets the + // guard however fast the dispatcher is. + val first = viewModel.broadcastAll() + val second = viewModel.broadcastAll() + assertNull(second) + assertTrue(viewModel.isActionPending.value) + + // One entry out and held; the other has not been asked for, and the + // held one is marked as out while the rest are marked as nothing. + runBlocking { withTimeout(5_000) { transport.arrived.await() } } + assertEquals(listOf(newest.signedEvent.id), transport.sends.map { it.first.id }) + assertEquals(EntryBroadcast.Sending, viewModel.entryBroadcasts[newest.signedEvent.id]) + assertNull(viewModel.entryBroadcasts[oldest.signedEvent.id]) + assertEquals(BroadcastAllProgress.Sending(entry = 1, total = 2), viewModel.broadcastAllProgress) + + gate.complete(Unit) + runBlocking { withTimeout(5_000) { first!!.join() } } + + assertEquals(2, transport.sends.size) + assertFalse(viewModel.isActionPending.value) + } + + @Test + fun `nothing is sent from a screen with no entries, or one that has not loaded`() { + val transport = FakeTransport { event -> listOf(ok(two, event)) } + + assertNull(viewModel(transport, entries = emptyList()).broadcastAll()) + + val loading = GroupCuratedEntriesViewModel( + chatRoomId = chatRoomId, + initialGroupCuratedEntriesUIState = GroupCuratedEntriesUIState.Loading, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + publishTransport = transport, + ) + assertNull(loading.broadcastAll()) + + assertTrue(transport.sends.isEmpty()) + } +}