Skip to content

Conversation

@erskingardner
Copy link
Member

@erskingardner erskingardner commented Aug 8, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved relay tag handling to ensure correct tag types are used for different relay event kinds, enhancing compatibility and reliability when extracting relay URLs.
  • Tests
    • Added comprehensive tests to verify relay tag extraction and event publishing behavior for various relay types and event kinds, including handling of invalid URLs and backward compatibility.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 8, 2025

Walkthrough

The changes update the logic for handling relay tags in Nostr events and relay list publishing. Tag filtering and creation are now differentiated based on event or relay type, using single-letter "r" tags for certain kinds and "relay" tags for others. Extensive asynchronous tests were added to verify correct tag usage and extraction.

Changes

Cohort / File(s) Change Summary
NostrManager Relay Tag Filtering & Extraction
src/nostr_manager/mod.rs
Updated relay_urls_from_event to use tag filtering logic based on event kind, distinguishing between "r" and "relay" tags. Added comprehensive async tests for all relevant scenarios, including backward compatibility and invalid tag handling.
Relay List Event Tag Creation & Publishing
src/whitenoise/accounts/relays.rs
Modified relay list publishing to generate "r" tags for RelayType::Nostr and "relay" tags for other types. Added async tests to ensure correct tag kinds in published events and to verify tag creation methods.

Sequence Diagram(s)

sequenceDiagram
    participant Account
    participant RelayManager
    participant Event
    participant Database

    Account->>RelayManager: publish_relay_list_for_account()
    RelayManager->>RelayManager: For each relay, create tag ("r" for Nostr, "relay" for others)
    RelayManager->>Event: Construct event with tags
    RelayManager->>Database: Store event

    Note over RelayManager,Event: Tests verify correct tag types per event kind
Loading
sequenceDiagram
    participant Test
    participant NostrManager
    participant Event

    Test->>Event: Create event with tags (varied kinds)
    Test->>NostrManager: relay_urls_from_event(event)
    NostrManager->>NostrManager: Filter tags by kind ("r" or "relay" depending on event)
    NostrManager->>Test: Return extracted relay URLs

    Note over Test,NostrManager: Tests assert correct extraction for all cases
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–25 minutes

Poem

A bunny hopped through fields of tags,
Sorting "r" from "relay" with nimble wags.
Events and relays, tested with care,
Ensuring the right tags are always there.
With every async test, the garden grew bright—
Relay logic now works just right! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10eb3f7 and a7bdfed.

📒 Files selected for processing (1)
  • src/whitenoise/accounts/relays.rs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/whitenoise/accounts/relays.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: check (ubuntu-latest, native)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-tag-reference

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
src/whitenoise/accounts/relays.rs (3)

275-286: Minor allocation nit: avoid cloning the entire DashSet when building tags

You can iterate by reference and avoid cloning the whole set.

-            RelayType::Nostr => relays_to_publish
-                .clone()
-                .into_iter()
-                .map(|url| Tag::reference(url.to_string()))
-                .collect(),
+            RelayType::Nostr => relays_to_publish
+                .iter()
+                .map(|url| Tag::reference(url.to_string()))
+                .collect(),
-            RelayType::Inbox | RelayType::KeyPackage => relays_to_publish
-                .clone()
-                .into_iter()
-                .map(|url| Tag::custom(TagKind::Relay, [url.to_string()]))
-                .collect(),
+            RelayType::Inbox | RelayType::KeyPackage => relays_to_publish
+                .iter()
+                .map(|url| Tag::custom(TagKind::Relay, [url.to_string()]))
+                .collect(),

269-273: Confirm intended publish target set for non-Nostr relay types

When target_relays is None, events (including Inbox/KeyPackage relay lists) are published only to account.nip65_relays. If an account has only Inbox or KeyPackage relays (and zero NIP-65 relays), publication might go to an empty set. If you want broader propagation, consider publishing to the union of nip65_relays and the specific relays for the relay_type.

Example change:

let relays_to_use = match target_relays.as_ref() {
    Some(relays) => relays.clone(),
    None => {
        let mut union = DashSet::new();
        union.extend(account.nip65_relays.clone());
        union.extend(match relay_type {
            RelayType::Nostr => account.nip65_relays.clone(),
            RelayType::Inbox => account.inbox_relays.clone(),
            RelayType::KeyPackage => account.key_package_relays.clone(),
        });
        union
    }
};

716-884: Great end-to-end verification of published tag types; consider reducing flakiness

The tests thoroughly verify that Kind::RelayList contains only "r" tags and that Inbox/KeyPackage relay events contain only "relay" tags. The fixed sleep can be flaky; prefer polling with a timeout until events appear in the DB.

A sketch to replace the fixed sleep:

use tokio::time::{sleep, timeout};
use std::time::Duration;

// wait up to 2s for at least one event
timeout(Duration::from_secs(2), async {
    loop {
        let events = whitenoise.nostr.client.database().query(relay_list_filter.clone()).await.unwrap();
        if !events.is_empty() {
            break;
        }
        sleep(Duration::from_millis(50)).await;
    }
}).await.expect("timed out waiting for relay list event");
src/nostr_manager/mod.rs (1)

491-514: Micro-optimization: avoid boxing a closure

You can inline the match in the filter to eliminate the Box allocation.

-        let tag_filter: Box<dyn Fn(&Tag) -> bool> = match event.kind {
-            Kind::RelayList => {
-                Box::new(|tag| {
-                    tag.kind() == TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::R))
-                })
-            }
-            Kind::InboxRelays | Kind::MlsKeyPackageRelays => {
-                Box::new(|tag| tag.kind() == TagKind::Relay)
-            }
-            _ => {
-                Box::new(|tag| {
-                    tag.kind() == TagKind::Relay
-                        || tag.kind()
-                            == TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::R))
-                })
-            }
-        };
-
-        event
-            .tags
-            .into_iter()
-            .filter(|tag| tag_filter(tag))
+        event
+            .tags
+            .into_iter()
+            .filter(|tag| match event.kind {
+                Kind::RelayList => {
+                    tag.kind() == TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::R))
+                }
+                Kind::InboxRelays | Kind::MlsKeyPackageRelays => tag.kind() == TagKind::Relay,
+                _ => {
+                    tag.kind() == TagKind::Relay
+                        || tag.kind()
+                            == TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::R))
+                }
+            })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7a240c1 and 10eb3f7.

📒 Files selected for processing (2)
  • src/nostr_manager/mod.rs (2 hunks)
  • src/whitenoise/accounts/relays.rs (2 hunks)
🔇 Additional comments (9)
src/whitenoise/accounts/relays.rs (2)

275-286: Correct tag-kind selection for each relay type

Using Tag::reference for Nostr (produces "r" tags) and Tag::custom(TagKind::Relay, ...) for Inbox/KeyPackage is consistent and matches the parsing logic in NostrManager.


692-714: Unit test correctly asserts tag kinds created by the helpers

The assertions validate that Tag::reference yields the "r" single-letter tag and Tag::custom(TagKind::Relay, ...) yields "relay" tags. Solid coverage of the new behavior.

src/nostr_manager/mod.rs (7)

491-514: Clear, kind-aware tag filtering (RelayList uses "r"; Inbox/KeyPackage use "relay")

This logic aligns with the updated publishing behavior and preserves backward compatibility for unknown kinds.


1042-1069: Test: RelayList with mixed tags parses only "r" entries

Validates the filter excludes TagKind::Relay for Kind::RelayList. Good guard against regressions.


1070-1097: Test: InboxRelays parses only "relay" tags and ignores "r"

Accurately captures the intended behavior for Kind::InboxRelays.


1098-1125: Test: KeyPackageRelays parses only "relay" tags and ignores "r"

Mirrors the inbox test; confirms correct behavior for Kind::MlsKeyPackageRelays.


1126-1151: Test: Unknown kind supports both tag forms (backward compatibility)

Good coverage to ensure legacy events continue to work.


1153-1180: Test: Invalid URLs are filtered out

Ensures robustness against malformed tag contents.


1181-1201: Test: No relay tags yields empty result

Sanity check looks good; helps prevent accidental inclusion of unrelated tags.

@erskingardner erskingardner merged commit 25bd9a6 into master Aug 9, 2025
4 checks passed
@erskingardner erskingardner deleted the fix-tag-reference branch August 9, 2025 06:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants