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

feat: add Context pool #356

Merged
merged 2 commits into from Jul 29, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 22 additions & 8 deletions core/context.go
Expand Up @@ -11,6 +11,8 @@ import (
"github.com/yomorun/yomo/pkg/logger"
)

var ctxPool sync.Pool

// Context for YoMo Server.
type Context struct {
// Conn is the connection of client.
Expand All @@ -26,13 +28,17 @@ type Context struct {
mu sync.RWMutex
}

func newContext(conn quic.Connection, stream quic.Stream) *Context {
return &Context{
Conn: conn,
connID: conn.RemoteAddr().String(),
Stream: stream,
// keys: make(map[string]interface{}),
func newContext(conn quic.Connection, stream quic.Stream) (ctx *Context) {
v := ctxPool.Get()
if v == nil {
ctx = new(Context)
} else {
ctx = v.(*Context)
}
ctx.Conn = conn
ctx.Stream = stream
ctx.connID = conn.RemoteAddr().String()
return
}

// WithFrame sets a frame to context.
Expand All @@ -44,10 +50,18 @@ func (c *Context) WithFrame(f frame.Frame) *Context {
// Clean the context.
func (c *Context) Clean() {
logger.Debugf("%sconn[%s] context clean", ServerLogPrefix, c.connID)
c.reset()
ctxPool.Put(c)
}

func (c *Context) reset() {
c.Conn = nil
c.connID = ""
c.Stream = nil
c.Frame = nil
c.Keys = nil
c.Conn = nil
for k := range c.Keys {
delete(c.Keys, k)
}
}

// CloseWithError closes the stream and cleans the context.
Expand Down