-
Notifications
You must be signed in to change notification settings - Fork 914
fix: fix goroutine leak in log streaming over websocket #15709
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
package wsjson | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"sync/atomic" | ||
|
||
"nhooyr.io/websocket" | ||
|
||
"cdr.dev/slog" | ||
) | ||
|
||
type Decoder[T any] struct { | ||
conn *websocket.Conn | ||
typ websocket.MessageType | ||
ctx context.Context | ||
cancel context.CancelFunc | ||
chanCalled atomic.Bool | ||
logger slog.Logger | ||
} | ||
|
||
// Chan starts the decoder reading from the websocket and returns a channel for reading the | ||
// resulting values. The chan T is closed if the underlying websocket is closed, or we encounter an | ||
// error. We also close the underlying websocket if we encounter an error reading or decoding. | ||
func (d *Decoder[T]) Chan() <-chan T { | ||
if !d.chanCalled.CompareAndSwap(false, true) { | ||
panic("chan called more than once") | ||
} | ||
values := make(chan T, 1) | ||
go func() { | ||
defer close(values) | ||
defer d.conn.Close(websocket.StatusGoingAway, "") | ||
for { | ||
// we don't use d.ctx here because it only gets canceled after closing the connection | ||
// and a "connection closed" type error is more clear than context canceled. | ||
typ, b, err := d.conn.Read(context.Background()) | ||
spikecurtis marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if err != nil { | ||
// might be benign like EOF, so just log at debug | ||
d.logger.Debug(d.ctx, "error reading from websocket", slog.Error(err)) | ||
return | ||
} | ||
if typ != d.typ { | ||
d.logger.Error(d.ctx, "websocket type mismatch while decoding") | ||
return | ||
} | ||
var value T | ||
err = json.Unmarshal(b, &value) | ||
if err != nil { | ||
d.logger.Error(d.ctx, "error unmarshalling", slog.Error(err)) | ||
return | ||
} | ||
select { | ||
case values <- value: | ||
// OK | ||
case <-d.ctx.Done(): | ||
return | ||
} | ||
} | ||
}() | ||
return values | ||
} | ||
|
||
// nolint: revive // complains that Encoder has the same function name | ||
func (d *Decoder[T]) Close() error { | ||
err := d.conn.Close(websocket.StatusNormalClosure, "") | ||
d.cancel() | ||
return err | ||
} | ||
|
||
// NewDecoder creates a JSON-over-websocket decoder for type T, which must be deserializable from | ||
// JSON. | ||
func NewDecoder[T any](conn *websocket.Conn, typ websocket.MessageType, logger slog.Logger) *Decoder[T] { | ||
ctx, cancel := context.WithCancel(context.Background()) | ||
return &Decoder[T]{conn: conn, ctx: ctx, cancel: cancel, typ: typ, logger: logger} | ||
} |
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,42 @@ | ||
package wsjson | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
|
||
"golang.org/x/xerrors" | ||
"nhooyr.io/websocket" | ||
) | ||
|
||
type Encoder[T any] struct { | ||
conn *websocket.Conn | ||
typ websocket.MessageType | ||
} | ||
|
||
func (e *Encoder[T]) Encode(v T) error { | ||
w, err := e.conn.Writer(context.Background(), e.typ) | ||
if err != nil { | ||
return xerrors.Errorf("get websocket writer: %w", err) | ||
} | ||
defer w.Close() | ||
j := json.NewEncoder(w) | ||
err = j.Encode(v) | ||
if err != nil { | ||
return xerrors.Errorf("encode json: %w", err) | ||
} | ||
return nil | ||
} | ||
|
||
func (e *Encoder[T]) Close(c websocket.StatusCode) error { | ||
return e.conn.Close(c, "") | ||
} | ||
|
||
// NewEncoder creates a JSON-over websocket encoder for the type T, which must be JSON-serializable. | ||
// You may then call Encode() to send objects over the websocket. Creating an Encoder closes the | ||
// websocket for reading, turning it into a unidirectional write stream of JSON-encoded objects. | ||
func NewEncoder[T any](conn *websocket.Conn, typ websocket.MessageType) *Encoder[T] { | ||
// Here we close the websocket for reading, so that the websocket library will handle pings and | ||
// close frames. | ||
_ = conn.CloseRead(context.Background()) | ||
return &Encoder[T]{conn: conn, typ: typ} | ||
} |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍🏻