Skip to content

Commit

Permalink
🔧 #262: adding connection pool for chat request and response (#271)
Browse files Browse the repository at this point in the history
Basic implementation of connection pooling for chat functionality.
  • Loading branch information
tom-fitz authored Jun 13, 2024
1 parent b80a3f9 commit 0bb4878
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
8 changes: 6 additions & 2 deletions pkg/api/http/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ func LangChatHandler(routerManager *routers.RouterManager) Handler {
}

// Unmarshal request body
var req *schemas.ChatRequest
req := schemas.GetChatRequest()
defer schemas.ReleaseChatRequest(req)

err := c.BodyParser(&req)
if err != nil {
Expand All @@ -56,7 +57,10 @@ func LangChatHandler(routerManager *routers.RouterManager) Handler {
}

// Chat with router
resp, err := router.Chat(c.Context(), req)
resp := schemas.GetChatResponse()
defer schemas.ReleaseChatResponse(resp)

resp, err = router.Chat(c.Context(), req)
if err != nil {
httpErr := schemas.FromErr(err)

Expand Down
39 changes: 39 additions & 0 deletions pkg/api/schemas/pool.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package schemas

import (
"sync"
)

var chatRequestPool = sync.Pool{
New: func() interface{} {
return &ChatRequest{}
},
}

var chatResponsePool = sync.Pool{
New: func() interface{} {
return &ChatResponse{}
},
}

// GetChatRequest get objects from the pool
func GetChatRequest() *ChatRequest {
return chatRequestPool.Get().(*ChatRequest)
}

// ReleaseChatRequest release objects from the pool
func ReleaseChatRequest(req *ChatRequest) {
*req = ChatRequest{}
chatRequestPool.Put(req)
}

// GetChatResponse get objects from the pool
func GetChatResponse() *ChatResponse {
return chatResponsePool.Get().(*ChatResponse)
}

// ReleaseChatResponse release objects from the pool
func ReleaseChatResponse(res *ChatResponse) {
*res = ChatResponse{}
chatResponsePool.Put(res)
}

0 comments on commit 0bb4878

Please sign in to comment.