-
Notifications
You must be signed in to change notification settings - Fork 4
feat(sse): added ext/sse #59
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package sse | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"errors" | ||
"fmt" | ||
) | ||
|
||
var ErrClientClosed = errors.New("sse: client closed") | ||
|
||
// Client represents a WebSocket client that handles HTTP responses and supports | ||
// flushing data to the client. It contains a response writer, a flusher for | ||
// sending data immediately, and a channel for managing the client's lifecycle. | ||
type Client struct { | ||
s Streamer | ||
|
||
ctx context.Context | ||
} | ||
|
||
// Connect establishes a connection for the Client using the provided Streamer. | ||
// It assigns the Streamer to the Client's rw field and ensures that it implements | ||
// the http.Flusher interface for flushing data. | ||
func (c *Client) Connect(ctx context.Context, s Streamer) { | ||
c.s = s | ||
c.ctx = ctx | ||
} | ||
|
||
// Send sends an event to the client by writing the event name and data to the response writer. | ||
// It marshals the event data into JSON format and flushes the output to ensure the data is sent immediately. | ||
// This method is part of the Client struct and is intended for use in server-sent events (SSE) communication. | ||
func (c *Client) Send(event Event) error { | ||
select { | ||
case <-c.ctx.Done(): | ||
return ErrClientClosed | ||
default: | ||
buf, err := json.Marshal(event.Data) | ||
if err != nil { | ||
return err | ||
} | ||
_, err = fmt.Fprintf(c.s, "event: %s\ndata: %s\n\n", event.Name, string(buf)) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
c.s.Flush() | ||
} | ||
|
||
return nil | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
package sse | ||
|
||
// Event represents a server-sent event with a name and associated data. | ||
// It can be used to transmit information from the server to the client in real-time. | ||
type Event struct { | ||
Name string | ||
Data any | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
// Package sse provides a server implementation for Server-Sent Events (SSE). | ||
// SSE is a technology enabling a client to receive automatic updates from a server via HTTP connection. | ||
package sse | ||
|
||
import ( | ||
"context" | ||
"sync" | ||
|
||
"github.com/yaitoo/async" | ||
) | ||
|
||
// Server represents a structure that manages connected clients | ||
// in a concurrent environment. It uses a read-write mutex to | ||
// ensure safe access to the clients map, which holds the | ||
// active Client instances identified by their unique keys. | ||
type Server struct { | ||
sync.RWMutex | ||
clients map[string]*Client | ||
} | ||
|
||
// New creates and returns a new instance of the Server struct. | ||
func New() *Server { | ||
return &Server{ | ||
clients: make(map[string]*Client), | ||
} | ||
} | ||
|
||
// Join adds a new client to the server or retrieves an existing one based on the provided ID. | ||
// It establishes a connection with the specified Streamer and sets the appropriate headers | ||
// for Server-Sent Events (SSE). If a client with the given ID already exists, it reuses that client. | ||
func (s *Server) Join(ctx context.Context, id string, sm Streamer) *Client { | ||
s.Lock() | ||
defer s.Unlock() | ||
c, ok := s.clients[id] | ||
|
||
if !ok { | ||
c = &Client{} | ||
s.clients[id] = c | ||
} | ||
|
||
c.Connect(ctx, sm) | ||
|
||
sm.Header().Set("Content-Type", "text/event-stream") | ||
sm.Header().Set("Cache-Control", "no-cache") | ||
sm.Header().Set("Connection", "keep-alive") | ||
|
||
return c | ||
} | ||
|
||
// Leave removes a client from the server's client list by its ID. | ||
// This method is safe for concurrent use, as it locks the server | ||
// before modifying the clients map and ensures that the lock is | ||
// released afterward. | ||
func (s *Server) Leave(id string) { | ||
s.Lock() | ||
defer s.Unlock() | ||
|
||
delete(s.clients, id) | ||
} | ||
|
||
// Get retrieves the Client associated with the given id from the Server. | ||
// It uses a read lock to ensure thread-safe access to the clients map. | ||
// Returns nil if no Client is found for the specified id. | ||
func (s *Server) Get(id string) *Client { | ||
s.RLock() | ||
defer s.RUnlock() | ||
return s.clients[id] | ||
} | ||
|
||
// Broadcast sends the specified event to all connected clients. | ||
cnlangzi marked this conversation as resolved.
Show resolved
Hide resolved
cnlangzi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// It acquires a read lock to ensure thread-safe access to the clients slice, | ||
// and spawns a goroutine for each client to handle the sending of the event. | ||
func (s *Server) Broadcast(ctx context.Context, event Event) ([]error, error) { | ||
s.RLock() | ||
defer s.RUnlock() | ||
|
||
task := async.NewA() | ||
|
||
for _, c := range s.clients { | ||
task.Add(func(ctx context.Context) error { | ||
return c.Send(event) | ||
}) | ||
} | ||
|
||
return task.Wait(ctx) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
package sse | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestServer(t *testing.T) { | ||
t.Run("join", func(t *testing.T) { | ||
srv := New() | ||
rw := httptest.NewRecorder() | ||
|
||
c1 := srv.Join(context.TODO(), "join", rw) | ||
|
||
c2 := srv.Join(context.TODO(), "join", rw) | ||
|
||
require.Equal(t, c1, c2) | ||
|
||
c3 := srv.Get("join") | ||
|
||
require.Equal(t, c1, c3) | ||
|
||
srv.Leave("join") | ||
|
||
c4 := srv.Get("join") | ||
require.Nil(t, c4) | ||
|
||
}) | ||
|
||
t.Run("send", func(t *testing.T) { | ||
srv := New() | ||
rw := httptest.NewRecorder() | ||
|
||
c := srv.Join(context.TODO(), "send", rw) | ||
|
||
err := c.Send(Event{Name: "event1", Data: "data1"}) | ||
require.NoError(t, err) | ||
buf := rw.Body.Bytes() | ||
require.Equal(t, "event: event1\ndata: \"data1\"\n\n", string(buf)) | ||
|
||
err = c.Send(Event{Name: "event2", Data: "data2"}) | ||
require.NoError(t, err) | ||
buf = rw.Body.Bytes() | ||
require.Equal(t, "event: event1\ndata: \"data1\"\n\nevent: event2\ndata: \"data2\"\n\n", string(buf)) | ||
}) | ||
|
||
t.Run("broadcast", func(t *testing.T) { | ||
srv := New() | ||
|
||
rw1 := httptest.NewRecorder() | ||
rw2 := httptest.NewRecorder() | ||
|
||
c1 := srv.Join(context.TODO(), "c1", rw1) | ||
require.NotNil(t, c1) | ||
|
||
c2 := srv.Join(context.TODO(), "c2", rw2) | ||
require.NotNil(t, c2) | ||
|
||
errs, err := srv.Broadcast(context.TODO(), Event{Name: "event1", Data: "data1"}) | ||
require.NoError(t, err) | ||
require.Nil(t, errs) | ||
|
||
buf1 := rw1.Body.Bytes() | ||
buf2 := rw2.Body.Bytes() | ||
|
||
require.Equal(t, buf1, buf2) | ||
require.Equal(t, "event: event1\ndata: \"data1\"\n\n", string(buf1)) | ||
}) | ||
|
||
t.Run("invalid", func(t *testing.T) { | ||
srv := New() | ||
|
||
rw := &streamerMock{ | ||
ResponseWriter: httptest.NewRecorder(), | ||
} | ||
|
||
ctx, cancel := context.WithCancel(context.TODO()) | ||
|
||
c := srv.Join(ctx, "invalid", rw) | ||
|
||
err := c.Send(Event{Name: "event1", Data: make(chan int)}) | ||
require.Error(t, err) | ||
|
||
err = c.Send(Event{Name: "event1"}) | ||
require.Error(t, err) | ||
|
||
cancel() | ||
|
||
err = c.Send(Event{Name: "event1"}) | ||
require.ErrorIs(t, err, ErrClientClosed) | ||
|
||
}) | ||
} | ||
|
||
type streamerMock struct { | ||
http.ResponseWriter | ||
} | ||
|
||
func (*streamerMock) Write([]byte) (int, error) { | ||
return 0, errors.New("mock: invalid") | ||
} | ||
|
||
func (*streamerMock) Flush() {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
package sse | ||
|
||
import ( | ||
"net/http" | ||
) | ||
|
||
type Streamer interface { | ||
http.ResponseWriter | ||
http.Flusher | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.