Skip to content
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

fix: allow for multiple browser sources #191

Merged
merged 1 commit into from
Oct 19, 2024

Conversation

williamsjokvist
Copy link
Owner

@williamsjokvist williamsjokvist commented Oct 19, 2024

Summary by CodeRabbit

  • New Features

    • Introduced support for server-sent events (SSE) to enable real-time updates.
    • Enhanced match processing with improved channel handling and safety.
  • Bug Fixes

    • Implemented nil checks for channels to prevent potential errors during match sending.
  • Refactor

    • Updated the Start and handleStream methods to improve the flow and reliability of match data handling.

Copy link
Contributor

coderabbitai bot commented Oct 19, 2024

Walkthrough

This pull request introduces modifications to the TrackingHandler in cmd/tracking.go and the BrowserSourceServer in pkg/server/server.go. Key changes include the adjustment of channel handling for match notifications, with a shift to buffered channels and the addition of nil checks. The BrowserSourceServer now supports server-sent events (SSE) with the inclusion of a new sseChans field and updates to the Start and handleStream methods to facilitate real-time data streaming.

Changes

File Path Change Summary
cmd/tracking.go - Modified TrackingHandler to use a buffered matchChan channel.
- Added nil checks for channels in matchChans in onNewMatch function.
- Enhanced polling logic in StartTracking method.
pkg/server/server.go - Added sseChans []chan []byte field to BrowserSourceServer struct.
- Updated NewBrowserSourceServer to initialize sseChans.
- Modified Start method to handle matches and send data to sseChans.
- Replaced direct reading from matchChan with a buffered sseChan in handleStream method.

Possibly related PRs

  • chore: use channels for browser src updates #190: The changes in this PR also modify the TrackingHandler struct in cmd/tracking.go, specifically enhancing its handling of channels for match notifications, which aligns with the changes made in the main PR regarding channel operations.

Suggested reviewers

  • tifye

Poem

In the burrow where matches play,
Channels now buffer, come what may.
SSE streams with data bright,
Hopping along, a joyful sight!
With nil checks in place, we cheer,
Safe and sound, the matches near! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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

🧹 Outside diff range and nitpick comments (2)
cmd/tracking.go (2)

86-90: Approve: Improved channel safety with nil checks.

The addition of nil checks before sending to channels in matchChans is a good practice. It prevents potential panics that could occur when attempting to send to a nil channel.

As a minor optimization, consider using a separate slice for non-nil channels to avoid checking for nil on every iteration:

var activeChans []chan model.Match
for _, mc := range ch.matchChans {
    if mc != nil {
        activeChans = append(activeChans, mc)
    }
}
for _, mc := range activeChans {
    mc <- match
}

This approach would be more efficient if onNewMatch is called frequently or if ch.matchChans contains many elements.


98-100: Approve: Consistent nil checks for channel safety.

The addition of nil checks in this loop is consistent with the changes made in the onNewMatch function. This improves the overall safety of the code by preventing potential panics when sending to nil channels.

For consistency and potential optimization, consider applying the same approach suggested for the onNewMatch function:

var activeChans []chan model.Match
for _, mc := range ch.matchChans {
    if mc != nil {
        activeChans = append(activeChans, mc)
    }
}
for _, mc := range activeChans {
    mc <- match
}

This would centralize the nil checking logic and potentially improve performance if this loop is executed frequently.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6ae8cd3 and d59ab56.

📒 Files selected for processing (2)
  • cmd/tracking.go (1 hunks)
  • pkg/server/server.go (2 hunks)
🧰 Additional context used
🔇 Additional comments (1)
pkg/server/server.go (1)

83-84: Potential goroutine leak: Missing client disconnect handling

The handleStream function listens indefinitely on sseChan. If the client disconnects, the server may not detect it immediately, potentially leading to a goroutine leak.

Consider implementing context cancellation or detecting client disconnection to properly exit the goroutine.

Comment on lines +43 to +47
for _, sse := range b.sseChans {
if sse != nil {
sse <- matchJson
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential data race on sseChans: Concurrent access without synchronization

The sseChans slice is accessed concurrently by multiple goroutines without proper synchronization, which can lead to data races and undefined behavior.

  • In the Start method (lines 43-47), the goroutine iterates over b.sseChans to send data to each channel.
  • In the handleStream method (line 85), new channels are appended to b.sseChans.

To prevent data races, synchronize access to sseChans using a mutex.

Apply this diff to add synchronization:

+import "sync"

 type BrowserSourceServer struct {
 	matchChan chan model.Match
 	sseChans  []chan []byte
+	mu        sync.Mutex
 	lastMatch []byte
 }

 func (b *BrowserSourceServer) handleStream(w http.ResponseWriter, _ *http.Request) {
 	// ...
 	sseChan := make(chan []byte, 1)
 	defer close(sseChan)
+	b.mu.Lock()
 	b.sseChans = append(b.sseChans, sseChan)
+	b.mu.Unlock()
 	// ...
 }

 func (b *BrowserSourceServer) Start(ctx context.Context, cfg *config.Config) {
 	// ...
 	go func() {
 		for match := range b.matchChan {
 			// ...
+			b.mu.Lock()
 			for _, sse := range b.sseChans {
 				if sse != nil {
 					sse <- matchJson
 				}
 			}
+			b.mu.Unlock()
 		}
 	}()
 	// ...
 }

Also applies to: 85-85

b.lastMatch = matchJson
sseChan := make(chan []byte, 1)
defer close(sseChan)
b.sseChans = append(b.sseChans, sseChan)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Connection cleanup: Remove closed channels from sseChans

When a client disconnects, the sseChan is closed but remains in b.sseChans, potentially leading to resource leaks and memory consumption over time. Consider removing the closed channel from b.sseChans to prevent this.

Apply this diff to remove closed channels:

 func (b *BrowserSourceServer) handleStream(w http.ResponseWriter, _ *http.Request) {
 	// ...
 	sseChan := make(chan []byte, 1)
 	defer func() {
+		b.mu.Lock()
+		// Remove sseChan from sseChans slice
+		for i, ch := range b.sseChans {
+			if ch == sseChan {
+				b.sseChans = append(b.sseChans[:i], b.sseChans[i+1:]...)
+				break
+			}
+		}
+		b.mu.Unlock()
 		close(sseChan)
 	}()
 	// ...
 }

Committable suggestion was skipped due to low confidence.

pkg/server/server.go Show resolved Hide resolved
pkg/server/server.go Show resolved Hide resolved
@williamsjokvist williamsjokvist merged commit c0d1024 into master Oct 19, 2024
2 checks passed
@williamsjokvist williamsjokvist deleted the fix/multiple-browser-sources branch October 19, 2024 19:10
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