mock_backend_test.go 6.34 KB
Newer Older
1 2 3 4 5 6
package integration_tests

import (
	"bytes"
	"context"
	"encoding/json"
7
	"io"
8 9
	"net/http"
	"net/http/httptest"
10
	"strings"
11
	"sync"
12

13
	"github.com/ethereum-optimism/optimism/proxyd"
14
	"github.com/gorilla/websocket"
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
)

type RecordedRequest struct {
	Method  string
	Headers http.Header
	Body    []byte
}

type MockBackend struct {
	handler  http.Handler
	server   *httptest.Server
	mtx      sync.RWMutex
	requests []*RecordedRequest
}

func SingleResponseHandler(code int, response string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(code)
33
		_, _ = w.Write([]byte(response))
34 35 36
	}
}

37 38
func BatchedResponseHandler(code int, responses ...string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
39 40 41 42 43
		if len(responses) == 1 {
			SingleResponseHandler(code, responses[0])(w, r)
			return
		}

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
		var body string
		body += "["
		for i, response := range responses {
			body += response
			if i+1 < len(responses) {
				body += ","
			}
		}
		body += "]"
		SingleResponseHandler(code, body)(w, r)
	}
}

type responseMapping struct {
	result interface{}
	calls  int
}
type BatchRPCResponseRouter struct {
	m        map[string]map[string]*responseMapping
	fallback map[string]interface{}
	mtx      sync.Mutex
65 66
}

67 68 69 70
func NewBatchRPCResponseRouter() *BatchRPCResponseRouter {
	return &BatchRPCResponseRouter{
		m:        make(map[string]map[string]*responseMapping),
		fallback: make(map[string]interface{}),
71 72 73
	}
}

74
func (h *BatchRPCResponseRouter) SetRoute(method string, id string, result interface{}) {
75 76
	h.mtx.Lock()
	defer h.mtx.Unlock()
77

78
	switch result.(type) {
79
	case string:
Felipe Andrade's avatar
Felipe Andrade committed
80
	case []string:
81 82 83
	case nil:
		break
	default:
84
		panic("invalid result type")
85 86
	}

87 88 89 90 91 92
	m := h.m[method]
	if m == nil {
		m = make(map[string]*responseMapping)
	}
	m[id] = &responseMapping{result: result}
	h.m[method] = m
93 94
}

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
func (h *BatchRPCResponseRouter) SetFallbackRoute(method string, result interface{}) {
	h.mtx.Lock()
	defer h.mtx.Unlock()

	switch result.(type) {
	case string:
	case nil:
		break
	default:
		panic("invalid result type")
	}

	h.fallback[method] = result
}

func (h *BatchRPCResponseRouter) GetNumCalls(method string, id string) int {
	h.mtx.Lock()
	defer h.mtx.Unlock()

	if m := h.m[method]; m != nil {
		if rm := m[id]; rm != nil {
			return rm.calls
		}
	}
	return 0
}

func (h *BatchRPCResponseRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	h.mtx.Lock()
	defer h.mtx.Unlock()

126
	body, err := io.ReadAll(r.Body)
127 128 129
	if err != nil {
		panic(err)
	}
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

	if proxyd.IsBatch(body) {
		batch, err := proxyd.ParseBatchRPCReq(body)
		if err != nil {
			panic(err)
		}
		out := make([]*proxyd.RPCRes, len(batch))
		for i := range batch {
			req, err := proxyd.ParseRPCReq(batch[i])
			if err != nil {
				panic(err)
			}

			var result interface{}
			var resultHasValue bool

			if mappings, exists := h.m[req.Method]; exists {
				if rm := mappings[string(req.ID)]; rm != nil {
					result = rm.result
					resultHasValue = true
					rm.calls++
				}
			}
			if !resultHasValue {
				result, resultHasValue = h.fallback[req.Method]
			}
			if !resultHasValue {
				w.WriteHeader(400)
				return
			}

			out[i] = &proxyd.RPCRes{
				JSONRPC: proxyd.JSONRPCVersion,
				Result:  result,
				ID:      req.ID,
			}
		}
		if err := json.NewEncoder(w).Encode(out); err != nil {
			panic(err)
		}
		return
	}

173 174 175 176
	req, err := proxyd.ParseRPCReq(body)
	if err != nil {
		panic(err)
	}
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

	var result interface{}
	var resultHasValue bool

	if mappings, exists := h.m[req.Method]; exists {
		if rm := mappings[string(req.ID)]; rm != nil {
			result = rm.result
			resultHasValue = true
			rm.calls++
		}
	}
	if !resultHasValue {
		result, resultHasValue = h.fallback[req.Method]
	}
	if !resultHasValue {
192 193 194
		w.WriteHeader(400)
		return
	}
195

196 197
	out := &proxyd.RPCRes{
		JSONRPC: proxyd.JSONRPCVersion,
198
		Result:  result,
199 200 201 202 203
		ID:      req.ID,
	}
	enc := json.NewEncoder(w)
	if err := enc.Encode(out); err != nil {
		panic(err)
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
	}
}

func NewMockBackend(handler http.Handler) *MockBackend {
	mb := &MockBackend{
		handler: handler,
	}
	mb.server = httptest.NewServer(http.HandlerFunc(mb.wrappedHandler))
	return mb
}

func (m *MockBackend) URL() string {
	return m.server.URL
}

func (m *MockBackend) Close() {
	m.server.Close()
}

func (m *MockBackend) SetHandler(handler http.Handler) {
	m.mtx.Lock()
	m.handler = handler
	m.mtx.Unlock()
}

func (m *MockBackend) Reset() {
	m.mtx.Lock()
	m.requests = nil
	m.mtx.Unlock()
}

func (m *MockBackend) Requests() []*RecordedRequest {
	m.mtx.RLock()
	defer m.mtx.RUnlock()
	out := make([]*RecordedRequest, len(m.requests))
239
	copy(out, m.requests)
240 241 242 243 244
	return out
}

func (m *MockBackend) wrappedHandler(w http.ResponseWriter, r *http.Request) {
	m.mtx.Lock()
245
	body, err := io.ReadAll(r.Body)
246 247 248 249
	if err != nil {
		panic(err)
	}
	clone := r.Clone(context.Background())
250
	clone.Body = io.NopCloser(bytes.NewReader(body))
251 252 253 254 255 256 257 258
	m.requests = append(m.requests, &RecordedRequest{
		Method:  r.Method,
		Headers: r.Header.Clone(),
		Body:    body,
	})
	m.handler.ServeHTTP(w, clone)
	m.mtx.Unlock()
}
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327

type MockWSBackend struct {
	connCB   MockWSBackendOnConnect
	msgCB    MockWSBackendOnMessage
	closeCB  MockWSBackendOnClose
	server   *httptest.Server
	upgrader websocket.Upgrader
	conns    []*websocket.Conn
	connsMu  sync.Mutex
}

type MockWSBackendOnConnect func(conn *websocket.Conn)
type MockWSBackendOnMessage func(conn *websocket.Conn, msgType int, data []byte)
type MockWSBackendOnClose func(conn *websocket.Conn, err error)

func NewMockWSBackend(
	connCB MockWSBackendOnConnect,
	msgCB MockWSBackendOnMessage,
	closeCB MockWSBackendOnClose,
) *MockWSBackend {
	mb := &MockWSBackend{
		connCB:  connCB,
		msgCB:   msgCB,
		closeCB: closeCB,
	}
	mb.server = httptest.NewServer(mb)
	return mb
}

func (m *MockWSBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	conn, err := m.upgrader.Upgrade(w, r, nil)
	if err != nil {
		panic(err)
	}
	if m.connCB != nil {
		m.connCB(conn)
	}
	go func() {
		for {
			mType, msg, err := conn.ReadMessage()
			if err != nil {
				if m.closeCB != nil {
					m.closeCB(conn, err)
				}
				return
			}
			if m.msgCB != nil {
				m.msgCB(conn, mType, msg)
			}
		}
	}()
	m.connsMu.Lock()
	m.conns = append(m.conns, conn)
	m.connsMu.Unlock()
}

func (m *MockWSBackend) URL() string {
	return strings.Replace(m.server.URL, "http://", "ws://", 1)
}

func (m *MockWSBackend) Close() {
	m.server.Close()

	m.connsMu.Lock()
	for _, conn := range m.conns {
		conn.Close()
	}
	m.connsMu.Unlock()
}