Skip to content

Conversation

@jgmontoya
Copy link
Contributor

@jgmontoya jgmontoya commented Aug 19, 2025

Adds metadata and relay lists events processing to event processor

Summary by CodeRabbit

  • Bug Fixes
    • Improved real-time processing of profile metadata and relay list updates, ensuring subscription-driven changes propagate reliably with fewer missed events.
  • Tests
    • Added integration tests validating live updates for metadata and relay lists, including propagation after disconnect/reconnect scenarios to ensure consistent subscription behavior.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 19, 2025

Walkthrough

Adds duplicated subscription-driven integration tests that publish Metadata and Nip65 RelayList updates and assert propagation via state reads. Updates event processor to explicitly dispatch Metadata and RelayList-like kinds to dedicated handlers within the processing loop.

Changes

Cohort / File(s) Summary of Changes
Integration tests: subscriptions and live updates
src/bin/integration_test.rs
Added two identical test blocks creating a second test client, publishing a Metadata update and a Nip65 RelayList (tag 'R' with wss://sub-update.example.com), waiting, disconnecting, and asserting state updates for metadata and relay URLs. Purely additive test logic.
Event processor dispatch for metadata and relay lists
src/whitenoise/event_processor/mod.rs
Introduced explicit branches: Kind::Metadata -> handle_metadata; Kind::RelayList

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant T as TestClient2
  participant R as Relays
  participant EP as EventProcessor
  participant W as Whitenoise State

  rect rgb(240,248,255)
    note over T: Publish Metadata
    T->>R: Event(Kind::Metadata)
    R->>EP: Deliver event
    EP->>EP: Match kind == Metadata
    EP->>W: handle_metadata(event)
    W-->>EP: Ok / Err
    EP->>EP: retry if Err per retry_info
  end

  rect rgb(245,255,250)
    note over T: Publish RelayList (Nip65 'R')
    T->>R: Event(Kind::RelayList)
    R->>EP: Deliver event
    EP->>EP: Match kind ∈ {RelayList, InboxRelays, MlsKeyPackageRelays}
    EP->>W: handle_relay_list(event)
    W-->>EP: Ok / Err
    EP->>EP: retry if Err per retry_info
  end

  note over T,W: Tests assert updated metadata and relay URLs
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Fix tag reference #305 — Also touches RelayList handling; adjusts tag creation/parsing, which aligns with this PR’s explicit dispatch of RelayList-related kinds.

Poem

A bunny taps on relays bright,
Sends names and routes into the night.
The processor listens, swift and keen,
Sorting kinds in tidy scenes.
Two hops, same dance—state updated right—
Whiskers twitch: green lights ignite. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/process-metadata-and-relay-events

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.
    • 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.
  • 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 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/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@jgmontoya jgmontoya marked this pull request as ready for review August 19, 2025 11:03
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 (2)
src/whitenoise/event_processor/mod.rs (1)

102-107: Avoid retrying non-transient parse/validation errors from handlers

Right now, handler parse failures (e.g., invalid metadata JSON) bubble up as errors and will be retried, which is usually futile. Consider classifying handler errors into retryable vs non-retryable (e.g., map parse/validation issues to WhitenoiseError::InvalidEvent) and short-circuit retries for those.

Example approach (outside this hunk):

  • Make handle_metadata return WhitenoiseError::InvalidEvent for parse errors.
  • In process_events’ error branch, skip retry when error is InvalidEvent.

Sketch:

// Inside handle_metadata on parse failure:
Err(WhitenoiseError::InvalidEvent(format!("Invalid metadata for {}: {}", event.pubkey, e)))

// Inside process_events error handling:
if let Err(e) = result {
    match &e {
        WhitenoiseError::InvalidEvent(_) => {
            tracing::debug!("Non-retryable error for event kind {:?}: {}", event.kind, e);
        }
        _ => { /* existing retry logic */ }
    }
}

This avoids wasting retry budget on non-transient failures while keeping transient paths intact.

src/bin/integration_test.rs (1)

330-342: Reduce flakiness: poll until condition instead of fixed sleeps

The fixed 500ms wait can intermittently race with async processing. Prefer polling with a timeout to assert the state changes.

Minimal pattern (outside this hunk):

async fn wait_until<F, Fut>(mut check: F, timeout_ms: u64, poll_ms: u64) -> anyhow::Result<()>
where
    F: FnMut() -> Fut,
    Fut: std::future::Future<Output = bool>,
{
    let deadline = std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
    while std::time::Instant::now() < deadline {
        if check().await {
            return Ok(());
        }
        tokio::time::sleep(tokio::time::Duration::from_millis(poll_ms)).await;
    }
    anyhow::bail!("condition not met within {}ms", timeout_ms)
}

Then, instead of sleeping once, poll:

wait_until(
    || {
        let wn = whitenoise.clone();
        let pk = account3.pubkey;
        async move {
            wn.user_metadata(&pk).await.map(|m| m.name.as_deref() == Some("Known User Sub Update")).unwrap_or(false)
        }
    },
    4000,
    100,
).await.unwrap();

// Similarly for relay membership:
wait_until(
    || {
        let wn = whitenoise.clone();
        let user = user3.clone();
        let parsed_new = RelayUrl::parse(&new_relay_url).unwrap();
        async move {
            wn.user_relays(&user, whitenoise::RelayType::Nip65).await
              .map(|rs| rs.iter().any(|r| r.url == parsed_new))
              .unwrap_or(false)
        }
    },
    4000,
    100,
).await.unwrap();

This will make the test far more resilient across different environments and load conditions.

Also applies to: 348-357

📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7290efc and 8ce098d.

📒 Files selected for processing (2)
  • src/bin/integration_test.rs (1 hunks)
  • src/whitenoise/event_processor/mod.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/bin/integration_test.rs

📄 CodeRabbit Inference Engine (.cursor/rules/integration-test.mdc)

The integration test in src/bin/integration_test.rs should ALWAYS be run with the just int-test command and not run on its own with different log and data directories.

Files:

  • src/bin/integration_test.rs
🧬 Code Graph Analysis (2)
src/whitenoise/event_processor/mod.rs (3)
src/whitenoise/event_processor/event_handlers/handle_metadata.rs (1)
  • handle_metadata (7-26)
src/nostr_manager/mod.rs (1)
  • event (884-889)
src/whitenoise/event_processor/event_handlers/handle_relay_list.rs (1)
  • handle_relay_list (9-20)
src/bin/integration_test.rs (3)
src/whitenoise/relays.rs (1)
  • new (68-75)
src/whitenoise/users.rs (1)
  • new (19-27)
src/nostr_manager/mod.rs (1)
  • new (79-188)
⏰ 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)
🔇 Additional comments (3)
src/whitenoise/event_processor/mod.rs (1)

102-107: Explicit dispatch for Metadata and RelayList-like kinds: LGTM

Routing Kind::Metadata to handle_metadata and RelayList | InboxRelays | MlsKeyPackageRelays to handle_relay_list is correct and aligns with the handlers’ semantics. This integrates cleanly into the existing retry/error flow.

src/bin/integration_test.rs (2)

294-359: Subscription-driven Metadata + NIP-65 relay updates validation: LGTM

Nicely exercises the new event routing end-to-end. Publishing a fresh Metadata and a NIP-65 RelayList and then asserting state via user_metadata and user_relays is a good, realistic verification of the processor.


294-299: Reminder: run this integration test via just int-test

Per repo guidelines, this binary integration test should be executed with the just int-test command to ensure consistent data/log directories and environment. Running it ad hoc can lead to state leakage and false positives (e.g., the relay URL check).

Copy link
Contributor

@delcin-raj delcin-raj left a comment

Choose a reason for hiding this comment

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

LGTM

@jgmontoya jgmontoya merged commit 1ae8ffe into master Aug 19, 2025
4 checks passed
@jgmontoya jgmontoya deleted the feat/process-metadata-and-relay-events branch August 19, 2025 11:51
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.

3 participants