Skip to content

Commit

Permalink
Simplifying Request logic to parsing logic to midleware
Browse files Browse the repository at this point in the history
  • Loading branch information
ksysoev committed Jan 14, 2024
1 parent 08c17af commit c693c63
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 147 deletions.
18 changes: 3 additions & 15 deletions backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,8 @@ func NewBackend(endpoint string) *HTTPBackend {
}

func (b *HTTPBackend) Handle(conn Connection, r Request) error {
req, ok := r.(*JSONRPCRequest)
if !ok {
return nil
}

body := bytes.NewBufferString(req.Data)
req := string(r.Data())
body := bytes.NewBufferString(req)
httpReq, err := http.NewRequest("POST", b.endpoint, body)

if err != nil {
Expand All @@ -50,13 +46,5 @@ func (b *HTTPBackend) Handle(conn Connection, r Request) error {
return err
}

apiResp := NewResponse(req.ID, respBody.String())
data, err := apiResp.String()

if err != nil {
slog.Error("Error creating response", "error", err)
return err
}

return conn.Send([]byte(data))
return conn.Send(respBody.Bytes())
}
2 changes: 1 addition & 1 deletion cmd/web/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func main() {

backend := wasabi.NewBackend("http://localhost:8081")
connRegistry := wasabi.NewDefaultConnectionRegistry()
dispatcher := wasabi.NewPipeDispatcher(backend, &wasabi.JSONRPCRequestParser{})
dispatcher := wasabi.NewPipeDispatcher(backend)
server := wasabi.NewServer(Port)
channel := wasabi.NewDefaultChannel("/", dispatcher, connRegistry)

Expand Down
34 changes: 5 additions & 29 deletions dispatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ type Dispatcher interface {
// but for single backend API gateways is enough
type PipeDispatcher struct {
backend Backend
reqParser RequestParser
middlewares []RequestMiddlewere
}

Expand All @@ -24,22 +23,17 @@ type RequestHandler interface {
type RequestMiddlewere func(next RequestHandler) RequestHandler

// NewPipeDispatcher creates new instance of PipeDispatcher
func NewPipeDispatcher(backend Backend, reqParser RequestParser) *PipeDispatcher {
return &PipeDispatcher{backend: backend, reqParser: reqParser}
func NewPipeDispatcher(backend Backend) *PipeDispatcher {
return &PipeDispatcher{backend: backend}
}

// Dispatch dispatches request to backend
func (d *PipeDispatcher) Dispatch(conn Connection, data []byte) {
req, err := d.reqParser.Parse(data)
if err != nil {
handleRequestError(err, conn)
}

req = req.WithContext(conn.Context())
req := NewRawRequest(conn.Context(), data)

err = d.useMiddleware(d.backend).Handle(conn, req)
err := d.useMiddleware(d.backend).Handle(conn, req)
if err != nil {
handleRequestError(err, conn)
slog.Error("Error handling request: " + err.Error())
}
}

Expand All @@ -56,21 +50,3 @@ func (d *PipeDispatcher) useMiddleware(endpoint RequestHandler) RequestHandler {

return endpoint
}

// onMessage handles incoming messages
func handleRequestError(err error, conn Connection) {
slog.Debug("Error parsing request: " + err.Error())
resp := ResponseFromError(err)

data, err := resp.String()
if err != nil {
slog.Debug("Error creating response: " + err.Error())
return
}

err = conn.Send([]byte(data))
if err != nil {
slog.Debug("Error sending response: " + err.Error())
return
}
}
67 changes: 14 additions & 53 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,80 +2,41 @@ package wasabi

import (
"context"
"encoding/json"
"fmt"
)

type Request interface {
String() (string, error)
Data() []byte
RoutingKey() string
Context() context.Context
WithContext(ctx context.Context) Request
}

type RequestParser interface {
Parse(data []byte) (Request, error)
type RawRequest struct {
ctx context.Context
data []byte
}

type JSONRPCRequest struct {
orginReq *RPCRequest
ctx context.Context
Data string
ID string
ConnectionID string
}

type RPCRequest struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params any `json:"params,omitempty"`
// TODO make work with string and numbers
ID string `json:"id"`
}
type JSONRPCRequestParser struct{}

func (j *JSONRPCRequestParser) Parse(data []byte) (Request, error) {
msg := string(data)

originReq, err := parseRequest(msg)

if err != nil {
return nil, err
}

return &JSONRPCRequest{
ID: originReq.ID,
Data: msg,
orginReq: originReq,
}, nil
}

func parseRequest(data string) (*RPCRequest, error) {
var req RPCRequest
if err := json.Unmarshal([]byte(data), &req); err != nil {
return nil, err
}

if req.JSONRPC != "2.0" {
return nil, fmt.Errorf("invalid JSON-RPC version: %s", req.JSONRPC)
func NewRawRequest(ctx context.Context, data []byte) *RawRequest {
if ctx == nil {
panic("nil context")
}

return &req, nil
return &RawRequest{ctx: ctx, data: data}
}

func (r *JSONRPCRequest) String() (string, error) {
return r.Data, nil
func (r *RawRequest) Data() []byte {
return r.data
}

func (r *JSONRPCRequest) RoutingKey() string {
return r.orginReq.Method
func (r *RawRequest) RoutingKey() string {
return ""
}

func (r *JSONRPCRequest) Context() context.Context {
func (r *RawRequest) Context() context.Context {
return r.ctx
}

func (r *JSONRPCRequest) WithContext(ctx context.Context) Request {
func (r *RawRequest) WithContext(ctx context.Context) Request {
if ctx == nil {
panic("nil context")
}
Expand Down
49 changes: 0 additions & 49 deletions response.go

This file was deleted.

0 comments on commit c693c63

Please sign in to comment.