Skip to content
This repository was archived by the owner on Sep 30, 2025. It is now read-only.

Comments

feat(chaper-9): Add newsletter publication endpoint#19

Merged
TN19N merged 1 commit intomainfrom
18-finish-chapter-9
Sep 3, 2025
Merged

feat(chaper-9): Add newsletter publication endpoint#19
TN19N merged 1 commit intomainfrom
18-finish-chapter-9

Conversation

@TN19N
Copy link
Owner

@TN19N TN19N commented Sep 3, 2025

  • This commit introduces a new endpoint /newsletter that allows for publishing newsletters.
  • It includes the necessary handlers and data structures for handling newsletter publication.

Summary by CodeRabbit

  • New Features

    • Added a POST /newsletter endpoint to publish newsletters to confirmed subscribers.
  • Refactor

    • Simplified health endpoint to always return 200 OK.
    • Streamlined error handling and handler setup for more consistent behavior.
  • Tests

    • Added end-to-end tests covering newsletter delivery to confirmed subscribers, ensuring unconfirmed subscribers are skipped, and validating request payloads.
  • Chores

    • Updated dependency features to reduce unused options.

This commit introduces a new endpoint `/newsletter` that allows for
publishing newsletters. It includes the necessary handlers and data
structures for handling newsletter publication.
@TN19N TN19N self-assigned this Sep 3, 2025
@TN19N TN19N added the enhancement New feature or request label Sep 3, 2025
@TN19N TN19N linked an issue Sep 3, 2025 that may be closed by this pull request
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 3, 2025

Walkthrough

Removes axum macros feature; adjusts error conversions for surrealdb::Error; simplifies health_check to always return 200; adds newsletter publishing handler and routes; exposes handlers::newsletter; introduces ConfirmedSubscriber type and get_confirmed_subscribers; refactors error propagation in model; adds newsletter integration tests and test module wiring.

Changes

Cohort / File(s) Summary
Dependency config
Cargo.toml
Removed axum "macros" feature; axum now enabled with ["tracing"].
Error conversion adjustments
src/errors.rs
Dropped #[from] on Error::SurrealDb(Boxsurrealdb::Error); added impl Fromsurrealdb::Error that boxes into Error::SurrealDb.
Handlers: module wiring
src/handlers/mod.rs
Added submodule newsletter and pub use newsletter::*;.
Handlers: new newsletter feature
src/handlers/newsletter.rs
Added BodyData (pub) and publish_newsletter handler to send emails to confirmed subscribers via EmailClient; uses Axum State and tracing instrumentation.
Handlers: health check simplification
src/handlers/health_check.rs
Removed debug_handler attribute and DB health call; handler now unconditionally returns 200 OK.
Handlers: subscription cleanup
src/handlers/subscription.rs
Removed AppState import and debug_handler attributes; no functional changes to subscribe/confirm logic.
Model: confirmed subscribers + error flow
src/model.rs
Added pub ConfirmedSubscriber { email }; added pub async get_confirmed_subscribers() -> Result<Vec>; refactored multiple methods to use ? for error propagation.
Startup: route registration
src/startup.rs
Registered POST /newsletter -> publish_newsletter; existing routes unchanged.
Tests: module wiring
tests/api/main.rs
Added mod newsletter;.
Tests: newsletter integration
tests/api/newsletter.rs
Added E2E tests for newsletter delivery to confirmed subscribers, exclusion of unconfirmed, and 422 on invalid payloads; uses wiremock and TestApp helpers.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant R as Axum Router
  participant H as publish_newsletter
  participant M as ModelManager
  participant E as EmailClient

  C->>R: POST /newsletter {title, content{html,text}}
  R->>H: Route to handler (State<Arc<...>>, Json)
  rect rgba(200,220,255,0.25)
    note right of H: Retrieve recipients
    H->>M: get_confirmed_subscribers()
    M-->>H: Vec<ConfirmedSubscriber>
  end
  loop For each confirmed subscriber
    H->>E: send_email(to, subject, html, text)
    E-->>H: Result()
  end
  H-->>R: StatusCode::OK
  R-->>C: 200 OK
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

Thump-thump, my paws tap send with glee,
Confirmed ears hear the newsletter spree.
Unconfirmed burrows wait their turn,
While tracing trails of logs we learn.
A 200 breeze, inboxes hop—
Carrots for code, we never stop! 🥕📬

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 18-finish-chapter-9

🪧 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 or @coderabbit 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.

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: 12

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
src/handlers/subscription.rs (2)

11-15: Harden deserialization: reject unknown fields.
Prevents silent acceptance of misspelled JSON/form keys.

Apply:

-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
 pub struct FormData {
@@
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
 pub struct Params {

Also applies to: 35-38


50-56: Fix random token generation to use thread_rng() with rand 0.9.2
Cargo.toml pins rand = "0.9.2", so rand::rng() is unavailable. Update imports and invocation as follows:

--- a/src/handlers/subscription.rs
+++ b/src/handlers/subscription.rs
@@
- use rand::Rng;
- use rand::distr::Alphanumeric;
+ use rand::{distributions::Alphanumeric, Rng, thread_rng};
@@
 fn get_confirmation_token() -> String {
-    rand::rng()
+    thread_rng()
         .sample_iter(&Alphanumeric)
         .map(char::from)
         .take(25)
         .collect()
 }
src/model.rs (2)

60-77: Consistently check query responses for errors.
create_subscriber uses .check()?; confirm_subscriber should do the same to surface statement errors consistently.

     pub async fn confirm_subscriber(&self, token: String) -> Result<()> {
         self.db()
             .await?
             .query(
                 r#"
                 UPDATE subscriptions
                 SET status = 'CONFIRMED'
@@
             )
             .bind(("token_val", token))
-            .await?;
+            .await?
+            .check()?;
 
         Ok(())
     }

95-121: Connection flow looks solid. Minor readiness optimization.
Happy path is fine. If this backs a /health readiness check, consider a cheap ping instead of re-running health() frequently; OnceCell ensures single connect anyway.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

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 430c598 and 8cc6cd4.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (10)
  • Cargo.toml (1 hunks)
  • src/errors.rs (2 hunks)
  • src/handlers/health_check.rs (1 hunks)
  • src/handlers/mod.rs (1 hunks)
  • src/handlers/newsletter.rs (1 hunks)
  • src/handlers/subscription.rs (1 hunks)
  • src/model.rs (6 hunks)
  • src/startup.rs (2 hunks)
  • tests/api/main.rs (1 hunks)
  • tests/api/newsletter.rs (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-08-28T13:50:40.460Z
Learnt from: TN19N
PR: TN19N/subscriptions#9
File: src/domain/subscriber/email.rs:18-19
Timestamp: 2025-08-28T13:50:40.460Z
Learning: For the SubscriberEmail validation in src/domain/subscriber/email.rs, the user TN19N prefers to include the actual email value in ValidationError messages for debugging purposes, accepting the PII exposure trade-off in favor of detailed error information returned with 400 HTTP status.

Applied to files:

  • src/model.rs
🧬 Code graph analysis (7)
src/handlers/subscription.rs (2)
src/state.rs (4)
  • AppState (10-14)
  • AppState (16-24)
  • FromRef (32-36)
  • from_ref (33-35)
tests/api/helpers.rs (2)
  • TestApp (12-16)
  • TestApp (23-72)
tests/api/newsletter.rs (1)
tests/api/helpers.rs (1)
  • TestApp (23-72)
src/handlers/health_check.rs (1)
src/state.rs (1)
  • AppState (10-14)
src/startup.rs (1)
src/handlers/newsletter.rs (1)
  • publish_newsletter (21-40)
src/handlers/mod.rs (1)
src/lib.rs (1)
  • handlers (5-5)
src/handlers/newsletter.rs (3)
src/email_client.rs (2)
  • email_client (207-215)
  • EmailClient (25-62)
src/domain/subscriber/mod.rs (1)
  • Subscriber (11-14)
src/domain/subscriber/email.rs (1)
  • SubscriberEmail (6-6)
src/model.rs (2)
tests/api/subscriptions_confirm.rs (2)
  • QueryResult (52-56)
  • confirmation_works (24-75)
src/domain/subscriber/mod.rs (1)
  • Subscriber (11-14)
⏰ 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
🔇 Additional comments (5)
Cargo.toml (1)

17-17: No remaining axum macros detected

tests/api/main.rs (1)

3-3: LGTM: newsletter test module wired in.

src/handlers/subscription.rs (1)

1-1: Axum state import cleanup looks good.
No issues with removing AppState/debug macro usage here. Handler signatures already extract Arc directly.

src/model.rs (2)

32-56: Good: transactional insert and response checking.
Using a transaction plus .check()? is the right call to catch multi-statement failures.


32-56: Ensure subscriptions.status defaults to 'PENDING'. create_subscriber omits status, while confirm_subscriber filters by status = 'PENDING'. Please verify that your migrations define status with a default of 'PENDING'.

@TN19N TN19N merged commit 983b72a into main Sep 3, 2025
2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Sep 4, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Finish Chapter 9

1 participant