Skip to content

Conversation

cnlangzi
Copy link
Member

@cnlangzi cnlangzi commented Feb 27, 2025

Changed

Fixed

Added

  • fix(sse): added stdStreamer to wrap raw http.ResponseWriter

Tests

Tasks to complete before merging PR:

  • Ensure unit tests are passing. If not run make unit-test to check for any regressions 📋
  • Ensure lint tests are passing. if not run make lint to check for any issues
  • Ensure codecov/patch is passing for changes.

Summary by Sourcery

This PR enhances the SSE extension by adding a streamer implementation to handle raw HTTP responses, adding support for JSON events, and implementing a graceful shutdown mechanism. It also includes documentation updates and improved error handling.

New Features:

  • Introduce a stdStreamer to wrap the raw http.ResponseWriter and ensure it implements the http.Flusher interface, which is required for Server-Sent Events (SSE) to work correctly.
  • Add support for sending JSON events in addition to text events.
  • Implement a Shutdown method to gracefully close all active SSE client connections.

Documentation:

  • Document the SSE extension in the README, including usage examples for joining a room, sending events, broadcasting events, and shutting down the server, as well as an example using the htmx-ext-sse extension.

Tests:

  • Add tests to verify the correct behavior of the SSE server, including joining clients, sending events, broadcasting events, handling invalid events, and shutting down the server.
  • Add tests to ensure that the server returns an error when joining with a non-streamer response writer.

Copy link

sourcery-ai bot commented Feb 27, 2025

Reviewer's Guide by Sourcery

This pull request introduces a Server-Sent Events (SSE) extension. It wraps the raw http.ResponseWriter with a stdStreamer to ensure that the response writer implements the http.Flusher interface, which is required for SSE. It also adds error handling, context awareness, and different event types to the SSE client and server. Finally, it adds documentation for the SSE extension in the README.

Sequence diagram for joining a SSE client

sequenceDiagram
    participant User
    participant Server
    participant Client
    participant Streamer

    User->>Server: GET /chatroom/{id}
    Server->>Server: ss.Join(ctx, id, rw)
    Server->>Streamer: NewStreamer(rw)
    alt rw does not implement http.Flusher
    Streamer-->>Server: error
    Server-->>User: error
    else
    Server->>Server: Check if client exists
    alt Client does not exist
    Server->>Client: Create new client
    Server->>Server: Store client
    end
    Server->>Client: client.Connect(ctx, streamer)
    Server-->>User: Client
    end
Loading

Sequence diagram for sending a SSE event

sequenceDiagram
    participant Client
    participant Streamer

    Client->>Client: Send(event)
    alt Context is not done
    Client->>Streamer: event.Write(streamer)
    Streamer->>Streamer: Write event data
    Streamer->>Streamer: Flush()
    Client-->>Client: nil
    else Context is done
    Client-->>Client: ErrClientClosed
    end
Loading

Updated class diagram for SSE Event

classDiagram
    Event <|-- TextEvent
    Event <|-- JsonEvent
    class Event{
        <<interface>>
        Write(r io.Writer) error
    }
    class TextEvent{
        Name string
        Data string
        Write(w io.Writer) error
    }
    class JsonEvent{
        Name string
        Data any
        Write(w io.Writer) error
    }
Loading

Updated class diagram for SSE Client

classDiagram
    Client -- Streamer : has
    Client -- context.Context : has
    Client : ID string
    Client : s Streamer
    Client : ctx context.Context
    Client : cancel context.CancelFunc
    Client : Connect(ctx context.Context, s Streamer)
    Client : Send(event Event) error
    Client : Wait()
    Client : Close()
    Streamer <|-- stdStreamer
    class Streamer{
        <<interface>>
        http.ResponseWriter
        http.Flusher
    }
    class stdStreamer{
        http.ResponseWriter
        http.Flusher
    }
    note for Client "Represents a connection to a streaming service."
Loading

File-Level Changes

Change Details Files
Wrapped the raw http.ResponseWriter with a stdStreamer to ensure it implements the http.Flusher interface, which is required for Server-Sent Events (SSE).
  • Created a stdStreamer struct that implements the Streamer interface.
  • Implemented the NewStreamer function to wrap http.ResponseWriter with stdStreamer and return an error if the http.ResponseWriter does not implement the http.Flusher interface.
ext/sse/server_test.go
ext/sse/streamer.go
Added error handling and context awareness to the SSE client and server.
  • Return an error when joining a client with a response writer that does not implement the http.Flusher interface.
  • Added context to the Join function to handle client disconnections.
  • Added a Close method to the Client struct to allow closing the client connection.
  • Added a Shutdown method to the Server struct to close all client connections.
  • Return errors when sending events to a closed client.
  • Return errors when broadcasting events to closed clients.
  • Added an Error struct to wrap errors with client IDs.
  • Added tests to verify the new error handling and context awareness.
ext/sse/server_test.go
ext/sse/client.go
ext/sse/server.go
ext/sse/error.go
Updated the event handling to support different event types (TextEvent and JsonEvent) and to correctly format the event data.
  • Introduced TextEvent and JsonEvent structs to represent different event types.
  • Implemented the Write method for each event type to format the event data correctly.
  • Updated the Send method to use the Write method of the event to send the event data.
  • Updated the tests to use the new event types.
ext/sse/server_test.go
ext/sse/event.go
Added documentation for the SSE extension in the README.
  • Added a section for the SSE extension.
  • Added example code for using the SSE extension.
  • Added a link to the htmx-ext-sse extension.
README.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

deepsource-io bot commented Feb 27, 2025

Here's the code health analysis summary for commits ac40b61..da8fa44. View details on DeepSource ↗.

Analysis Summary

AnalyzerStatusSummaryLink
DeepSource Go LogoGo✅ SuccessView Check ↗

💡 If you’re a repository administrator, you can configure the quality gates from the settings.

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @cnlangzi - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding a comment to Client explaining why the context is stored on the struct.
  • The error wrapping in Client.Send and Server.Broadcast seems a bit verbose; consider if a simpler approach would suffice.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link

codecov bot commented Feb 27, 2025

Codecov Report

Attention: Patch coverage is 92.53731% with 5 lines in your changes missing coverage. Please review.

Project coverage is 90.79%. Comparing base (ac40b61) to head (da8fa44).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
response_writer_std.go 0.00% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #60      +/-   ##
==========================================
- Coverage   90.81%   90.79%   -0.02%     
==========================================
  Files          58       61       +3     
  Lines        2363     2413      +50     
==========================================
+ Hits         2146     2191      +45     
- Misses        188      193       +5     
  Partials       29       29              
Flag Coverage Δ
Unit-Tests 90.79% <92.53%> (-0.02%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@cnlangzi
Copy link
Member Author

@sourcery-ai review

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @cnlangzi - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding a Close() method to the Server to ensure all clients are properly closed when the server shuts down.
  • The Connect method on the Client struct could be simplified by directly calling context.WithCancel instead of having a separate Connect method.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@cnlangzi
Copy link
Member Author

@sourcery-ai review

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @cnlangzi - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding an example of how to use the SSE functionality with htmx in the README.
  • The error handling in Broadcast could be improved by returning a channel of errors instead of a slice.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 2 issues found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

return err
}

// JsonEvent represents an event with a name and associated data.
Copy link

Choose a reason for hiding this comment

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

issue (complexity): Consider consolidating TextEvent and JsonEvent into a single Event struct with a flag to indicate if JSON marshaling is needed.

Consider consolidating the two event types into a unified Event struct to avoid duplicating the formatting logic. For example, you could add a flag to determine if JSON marshaling is needed:

type Event struct {
    Name   string
    Data   any
    IsJSON bool
}

func (e *Event) Write(w io.Writer) error {
    var dataStr string
    if e.IsJSON {
        buf, err := json.Marshal(e.Data)
        if err != nil {
            return err
        }
        dataStr = string(buf)
    } else {
        // Expecting e.Data to be a string when not using JSON.
        str, ok := e.Data.(string)
        if !ok {
            return fmt.Errorf("data is not a string")
        }
        dataStr = str
    }
    _, err := fmt.Fprintf(w, "event: %s\ndata: %s\n\n", e.Name, dataStr)
    return err
}

Actionable steps:

  1. Replace the separate TextEvent and JsonEvent types with the unified Event type.
  2. Use the IsJSON flag (or similar mechanism) to decide whether to JSON marshal Data or treat it as a plain string.
  3. Update any callers accordingly.

This approach reduces duplication while preserving functionality.

@cnlangzi cnlangzi changed the title fix(sse): added stdStreamer to wrap raw http.ResponseWriter fix(sse): added JsonEvent/TextEvent and updated Join with http.ResponseWriter Feb 27, 2025
@cnlangzi cnlangzi merged commit 990a2fa into main Feb 27, 2025
8 checks passed
@cnlangzi cnlangzi deleted the fix/htmx_sse branch February 27, 2025 07:56
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.

1 participant