Skip to content

Fix/concurrent write conn #61

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion lava/middleware.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
package lava

import "context"
import (
"context"
"net/http"

"google.golang.org/grpc/metadata"
)

type GrpcGatewayMetadata func(ctx context.Context, req *http.Request, rpcPath string, httpPattern string) metadata.MD

type HandlerFunc func(ctx context.Context, req Request) (Response, error)

Expand Down
38 changes: 35 additions & 3 deletions pkg/wsproxy/websocket_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ package wsproxy
import (
"bufio"
"bytes"
"errors"
"io"
"net"
"net/http"
"strings"
"sync"
"time"

"github.com/gorilla/websocket"
Expand Down Expand Up @@ -170,24 +172,25 @@ func (p *Proxy) proxy(w http.ResponseWriter, r *http.Request) {
p.timeWait = timeWait
}

conn, err := upgrade.Upgrade(w, r, responseHeader)
conn1, err := upgrade.Upgrade(w, r, responseHeader)
if err != nil {
log.Warn().Err(err).Msg("error upgrading websocket")
return
}
defer conn.Close()
defer conn1.Close()

ctx, cancelFn := context.WithCancel(context.Background())
defer cancelFn()

conn := WsConn{Conn: conn1, mu: &sync.Mutex{}}
conn.SetReadLimit(maxMessageSize)
conn.SetPingHandler(func(text string) error {
logutil.HandlerErr(conn.SetReadDeadline(time.Now().Add(p.timeWait)))

log.Info().Str("text", text).Msg("websocket received ping frame")
// 不设置 write deadline
err := conn.WriteControl(websocket.PongMessage, []byte(text), time.Time{})
if err == websocket.ErrCloseSent {
if errors.Is(err, websocket.ErrCloseSent) {
return nil
} else if _, ok := err.(net.Error); ok {
return nil
Expand Down Expand Up @@ -354,3 +357,32 @@ func (w *inMemoryResponseWriter) CloseNotify() <-chan bool {
return w.closed
}
func (w *inMemoryResponseWriter) Flush() {}

type WsConn struct {
*websocket.Conn
mu *sync.Mutex
}

func (ws WsConn) WritePreparedMessage(pm *websocket.PreparedMessage) error {
ws.mu.Lock()
defer ws.mu.Unlock()
return ws.Conn.WritePreparedMessage(pm)
}

func (ws WsConn) WriteJSON(v interface{}) error {
ws.mu.Lock()
defer ws.mu.Unlock()
return ws.Conn.WriteJSON(v)
}

func (ws WsConn) WriteControl(messageType int, data []byte, deadline time.Time) error {
ws.mu.Lock()
defer ws.mu.Unlock()
return ws.Conn.WriteControl(messageType, data, deadline)
}

func (ws WsConn) WriteMessage(messageType int, data []byte) error {
ws.mu.Lock()
defer ws.mu.Unlock()
return ws.Conn.WriteMessage(messageType, data)
}
20 changes: 16 additions & 4 deletions servers/grpcs/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ func (s *serviceImpl) DixInject(
log log.Logger,
conf *Config,
gw []*gateway.Mux,
metadataHandlers []lava.GrpcGatewayMetadata,
) {
s.conf = conf
if conf.HttpPort == nil {
Expand Down Expand Up @@ -165,6 +166,11 @@ func (s *serviceImpl) DixInject(
}))
}

httpServer.Use(func(ctx *fiber.Ctx) error {
ctx.SetUserContext(ctx.Context())
return ctx.Next()
})

app := fiber.New()
app.Group("/debug", httputil.StripPrefix(filepath.Join(conf.BaseUrl, "/debug"), debug.Handler))

Expand Down Expand Up @@ -239,11 +245,17 @@ func (s *serviceImpl) DixInject(
return strings.ToUpper(s), true
}),
runtime.WithMetadata(func(ctx context.Context, request *http.Request) metadata.MD {
path, ok := runtime.HTTPPathPattern(ctx)
if !ok {
return nil
rpcPath, _ := runtime.RPCMethod(ctx)
path, _ := runtime.HTTPPathPattern(ctx)

md := metadata.Pairs("http_path", path, "http_method", request.Method, "http_url", request.URL.Path)
for _, h := range metadataHandlers {
for k, v := range h(ctx, request, rpcPath, path) {
md.Append(k, v...)
}
}
return metadata.Pairs("http_path", path, "http_method", request.Method, "http_url", request.URL.Path)

return md
}),
runtime.WithErrorHandler(func(ctx context.Context, mux *runtime.ServeMux, marshal runtime.Marshaler, w http.ResponseWriter, request *http.Request, err error) {
md, ok := runtime.ServerMetadataFromContext(ctx)
Expand Down
3 changes: 0 additions & 3 deletions servers/https/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import (
"github.com/pubgo/funk/stack"
"github.com/pubgo/funk/version"
"github.com/pubgo/opendoc/opendoc"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"

"github.com/pubgo/lava/core/debug"
Expand Down Expand Up @@ -51,8 +50,6 @@ func (s *serviceImpl) Run() {
defer s.stop()
s.start()
signal.Wait()

fasthttp.AcquireArgs()
}

func (s *serviceImpl) Start() { s.start() }
Expand Down
Loading