From a10518de25a179332038b87fdb4b588324721879 Mon Sep 17 00:00:00 2001 From: Remade Date: Fri, 13 Sep 2024 05:30:11 +0400 Subject: [PATCH] lint --- README.md | 2 + db.go | 9 ++--- db_test.go | 12 ++++-- internal/benchmark/benchmark_test.go | 2 +- internal/mock/mock.go | 4 +- pkg/connection/http.go | 35 +++++++++-------- pkg/connection/http_test.go | 15 ++++---- pkg/connection/ws.go | 56 ++++++++++++++-------------- pkg/connection/ws_test.go | 2 +- pkg/constants/constants.go | 7 ++++ pkg/logger/slog_test.go | 2 +- pkg/model/cbor.go | 24 ------------ pkg/model/cbor_test.go | 2 +- pkg/model/model.go | 29 +++++++++++++- 14 files changed, 110 insertions(+), 91 deletions(-) diff --git a/README.md b/README.md index bfdcb2d..b075c73 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,8 @@ func main() { - Run `go mod tidy` to download the `surrealdb.go` dependency - Run `go run main.go` to run the example. +## Data Models + ## Contributing You can run the Makefile commands to run and build the project diff --git a/db.go b/db.go index 08c4ebd..48b5598 100644 --- a/db.go +++ b/db.go @@ -29,9 +29,9 @@ func New(connectionURL string) (*DB, error) { } var conn connection.Connection if scheme == "http" || scheme == "https" { - conn = connection.NewHttp(newParams) + conn = connection.NewHTTPConnection(newParams) } else if scheme == "ws" || scheme == "wss" { - conn = connection.NewWebSocket(newParams) + conn = connection.NewWebSocketConnection(newParams) } else { return nil, fmt.Errorf("invalid connection url") } @@ -48,7 +48,7 @@ func New(connectionURL string) (*DB, error) { } newLiveConnParams := newParams newLiveConnParams.BaseURL = fmt.Sprintf("%s://%s", liveScheme, u.Host) - liveconn := connection.NewWebSocket(newParams) + liveconn := connection.NewWebSocketConnection(newParams) err = liveconn.Connect() if err != nil { return nil, err @@ -156,7 +156,7 @@ func (db *DB) Kill(liveQueryID string) (interface{}, error) { // LiveNotifications returns a channel for live query. func (db *DB) LiveNotifications(liveQueryID string) (chan connection.Notification, error) { - return db.liveHandler.LiveNotifications(liveQueryID) //check if implemented + return db.liveHandler.LiveNotifications(liveQueryID) } // -------------------------------------------------- @@ -184,7 +184,6 @@ func (db *DB) send(method string, params ...interface{}) (interface{}, error) { // resp is a helper method for parsing the response from a query. func (db *DB) resp(_ string, _ []interface{}, res interface{}) (interface{}, error) { if res == nil { - //return nil, pkg.ErrNoRow return nil, constants.ErrNoRow } return res, nil diff --git a/db_test.go b/db_test.go index 1a45531..a4e7c66 100644 --- a/db_test.go +++ b/db_test.go @@ -64,13 +64,19 @@ func TestSurrealDBSuite(t *testing.T) { // Without options buff := bytes.NewBufferString("") logData := createLogger(t, buff) - SurrealDBSuite.connImplementations["ws"] = connection.NewWebSocket(connection.NewConnectionParams{}).Logger(logData) + SurrealDBSuite.connImplementations["ws"] = connection. + NewWebSocketConnection(connection.NewConnectionParams{}). + Logger(logData) SurrealDBSuite.logBuffer = buff // With options buffOpt := bytes.NewBufferString("") logDataOpt := createLogger(t, buff) - SurrealDBSuite.connImplementations["ws_opt"] = connection.NewWebSocket(connection.NewConnectionParams{}).SetTimeOut(time.Minute).SetCompression(true).Logger(logDataOpt) + SurrealDBSuite.connImplementations["ws_opt"] = connection. + NewWebSocketConnection(connection.NewConnectionParams{}). + SetTimeOut(time.Minute). + SetCompression(true). + Logger(logDataOpt) SurrealDBSuite.logBuffer = buffOpt RunWsMap(t, SurrealDBSuite) @@ -777,7 +783,7 @@ func (s *SurrealDBTestSuite) TestConcurrentOperations() { } func (s *SurrealDBTestSuite) TestConnectionBreak() { - ws := connection.NewWebSocket(connection.NewConnectionParams{}) + ws := connection.NewWebSocketConnection(connection.NewConnectionParams{}) var url string if currentURL == "" { url = defaultURL diff --git a/internal/benchmark/benchmark_test.go b/internal/benchmark/benchmark_test.go index 2bb07c2..8f87b9a 100644 --- a/internal/benchmark/benchmark_test.go +++ b/internal/benchmark/benchmark_test.go @@ -17,7 +17,7 @@ type testUser struct { } func SetupMockDB() (*surrealdb.DB, error) { - return surrealdb.New("", "") + return surrealdb.New("") } func BenchmarkCreate(b *testing.B) { diff --git a/internal/mock/mock.go b/internal/mock/mock.go index 0a14c21..1ff8966 100644 --- a/internal/mock/mock.go +++ b/internal/mock/mock.go @@ -8,8 +8,8 @@ import ( type ws struct { } -func (w *ws) Connect(url string) (connection.Connection, error) { - return w, nil +func (w *ws) Connect(url string) error { + return nil } func (w *ws) Send(method string, params []interface{}) (interface{}, error) { diff --git a/pkg/connection/http.go b/pkg/connection/http.go index 64c3e1b..78ae7e7 100644 --- a/pkg/connection/http.go +++ b/pkg/connection/http.go @@ -11,15 +11,15 @@ import ( "time" ) -type Http struct { +type HTTPConnection struct { BaseConnection httpClient *http.Client variables sync.Map } -func NewHttp(p NewConnectionParams) *Http { - con := Http{ +func NewHTTPConnection(p NewConnectionParams) *HTTPConnection { + con := HTTPConnection{ BaseConnection: BaseConnection{ marshaler: p.Marshaler, unmarshaler: p.Unmarshaler, @@ -36,7 +36,7 @@ func NewHttp(p NewConnectionParams) *Http { return &con } -func (h *Http) Connect() error { +func (h *HTTPConnection) Connect() error { if h.baseURL == "" { return fmt.Errorf("base url not set") } @@ -49,7 +49,7 @@ func (h *Http) Connect() error { return fmt.Errorf("unmarshaler is not set") } - httpReq, err := http.NewRequest(http.MethodGet, h.baseURL+"/health", nil) + httpReq, err := http.NewRequest(http.MethodGet, h.baseURL+"/health", http.NoBody) if err != nil { return err } @@ -61,21 +61,21 @@ func (h *Http) Connect() error { return nil } -func (h *Http) Close() error { +func (h *HTTPConnection) Close() error { return nil } -func (h *Http) SetTimeout(timeout time.Duration) *Http { +func (h *HTTPConnection) SetTimeout(timeout time.Duration) *HTTPConnection { h.httpClient.Timeout = timeout return h } -func (h *Http) SetHttpClient(client *http.Client) *Http { +func (h *HTTPConnection) SetHTTPClient(client *http.Client) *HTTPConnection { h.httpClient = client return h } -func (h *Http) Send(method string, params []interface{}) (interface{}, error) { +func (h *HTTPConnection) Send(method string, params []interface{}) (interface{}, error) { if h.baseURL == "" { return nil, fmt.Errorf("connection host not set") } @@ -92,6 +92,9 @@ func (h *Http) Send(method string, params []interface{}) (interface{}, error) { } req, err := http.NewRequest(http.MethodPost, h.baseURL+"/rpc", bytes.NewBuffer(reqBody)) + if err != nil { + return nil, err + } req.Header.Set("Accept", "application/cbor") req.Header.Set("Content-Type", "application/cbor") @@ -118,24 +121,24 @@ func (h *Http) Send(method string, params []interface{}) (interface{}, error) { var rpcResponse RPCResponse err = h.unmarshaler.Unmarshal(resp, &rpcResponse) + if err != nil { + return nil, err + } // Manage auth tokens switch method { case "signin", "signup": h.variables.Store("token", rpcResponse.Result) - break case "authenticate": h.variables.Store("token", params[0]) - break case "invalidate": h.variables.Delete("token") - break } return rpcResponse.Result, nil } -func (h *Http) MakeRequest(req *http.Request) ([]byte, error) { +func (h *HTTPConnection) MakeRequest(req *http.Request) ([]byte, error) { resp, err := h.httpClient.Do(req) if err != nil { log.Fatalf("Error making HTTP request: %v", err) @@ -149,19 +152,19 @@ func (h *Http) MakeRequest(req *http.Request) ([]byte, error) { return io.ReadAll(resp.Body) } -func (h *Http) Use(namespace string, database string) error { +func (h *HTTPConnection) Use(namespace string, database string) error { h.variables.Store("namespace", namespace) h.variables.Store("database", database) return nil } -func (h *Http) Let(key string, value interface{}) error { +func (h *HTTPConnection) Let(key string, value interface{}) error { h.variables.Store(key, value) return nil } -func (h *Http) Unset(key string) error { +func (h *HTTPConnection) Unset(key string) error { h.variables.Delete(key) return nil } diff --git a/pkg/connection/http_test.go b/pkg/connection/http_test.go index 02e53ff..a1047ff 100644 --- a/pkg/connection/http_test.go +++ b/pkg/connection/http_test.go @@ -5,7 +5,7 @@ import ( "fmt" "github.com/stretchr/testify/assert" "github.com/surrealdb/surrealdb.go/pkg/model" - "io/ioutil" + "io" "net/http" "testing" "time" @@ -33,7 +33,7 @@ func TestEngine_MakeRequest(t *testing.T) { return &http.Response{ StatusCode: 400, // Send response to be tested - Body: ioutil.NopCloser(bytes.NewBufferString(`OK`)), + Body: io.NopCloser(bytes.NewBufferString(`OK`)), // Must be set to non-nil value or it panics Header: make(http.Header), } @@ -44,10 +44,10 @@ func TestEngine_MakeRequest(t *testing.T) { Marshaler: model.CborMarshaler{}, Unmarshaler: model.CborUnmashaler{}, } - httpEngine := NewHttp(p) - httpEngine.SetHttpClient(httpClient) + httpEngine := NewHTTPConnection(p) + httpEngine.SetHTTPClient(httpClient) - req, _ := http.NewRequest(http.MethodGet, "http://test.surreal/rpc", nil) + req, _ := http.NewRequest(http.MethodGet, "http://test.surreal/rpc", http.NoBody) resp, err := httpEngine.MakeRequest(req) assert.Error(t, err, "should return error for status code 400") @@ -55,17 +55,16 @@ func TestEngine_MakeRequest(t *testing.T) { } func TestEngine_HttpMakeRequest(t *testing.T) { - p := NewConnectionParams{ BaseURL: "http://localhost:8000", Marshaler: model.CborMarshaler{}, Unmarshaler: model.CborUnmashaler{}, } - con := NewHttp(p) + con := NewHTTPConnection(p) err := con.Use("test", "test") assert.Nil(t, err, "no error returned when setting namespace and database") - err = con.Connect() //implement a is ready + err = con.Connect() // implement a "is ready" assert.Nil(t, err, "no error returned when initializing engine connection") token, err := con.Send("signin", []interface{}{model.Auth{Username: "pass", Password: "pass"}}) diff --git a/pkg/connection/ws.go b/pkg/connection/ws.go index 2347b96..d885154 100644 --- a/pkg/connection/ws.go +++ b/pkg/connection/ws.go @@ -24,9 +24,9 @@ const ( DefaultTimeout = 30 ) -type Option func(ws *WebSocket) error +type Option func(ws *WebSocketConnection) error -type WebSocket struct { +type WebSocketConnection struct { BaseConnection Conn *gorilla.Conn @@ -45,8 +45,8 @@ type WebSocket struct { closeError error } -func NewWebSocket(p NewConnectionParams) *WebSocket { - return &WebSocket{ +func NewWebSocketConnection(p NewConnectionParams) *WebSocketConnection { + return &WebSocketConnection{ BaseConnection: BaseConnection{ marshaler: p.Marshaler, unmarshaler: p.Unmarshaler, @@ -61,7 +61,7 @@ func NewWebSocket(p NewConnectionParams) *WebSocket { } } -func (ws *WebSocket) Connect() error { +func (ws *WebSocketConnection) Connect() error { if ws.baseURL == "" { return fmt.Errorf("base url not set") } @@ -87,8 +87,8 @@ func (ws *WebSocket) Connect() error { return nil } -func (ws *WebSocket) SetTimeOut(timeout time.Duration) *WebSocket { - ws.Option = append(ws.Option, func(ws *WebSocket) error { +func (ws *WebSocketConnection) SetTimeOut(timeout time.Duration) *WebSocketConnection { + ws.Option = append(ws.Option, func(ws *WebSocketConnection) error { ws.Timeout = timeout return nil }) @@ -96,25 +96,25 @@ func (ws *WebSocket) SetTimeOut(timeout time.Duration) *WebSocket { } // If path is empty it will use os.stdout/os.stderr -func (ws *WebSocket) Logger(logData logger.Logger) *WebSocket { +func (ws *WebSocketConnection) Logger(logData logger.Logger) *WebSocketConnection { ws.logger = logData return ws } -func (ws *WebSocket) RawLogger(logData logger.Logger) *WebSocket { +func (ws *WebSocketConnection) RawLogger(logData logger.Logger) *WebSocketConnection { ws.logger = logData return ws } -func (ws *WebSocket) SetCompression(compress bool) *WebSocket { - ws.Option = append(ws.Option, func(ws *WebSocket) error { +func (ws *WebSocketConnection) SetCompression(compress bool) *WebSocketConnection { + ws.Option = append(ws.Option, func(ws *WebSocketConnection) error { ws.Conn.EnableWriteCompression(compress) return nil }) return ws } -func (ws *WebSocket) Close() error { +func (ws *WebSocketConnection) Close() error { ws.connLock.Lock() defer ws.connLock.Unlock() close(ws.closeChan) @@ -126,7 +126,7 @@ func (ws *WebSocket) Close() error { return ws.Conn.Close() } -func (ws *WebSocket) LiveNotifications(liveQueryID string) (chan Notification, error) { +func (ws *WebSocketConnection) LiveNotifications(liveQueryID string) (chan Notification, error) { c, err := ws.createNotificationChannel(liveQueryID) if err != nil { ws.logger.Error(err.Error()) @@ -134,7 +134,7 @@ func (ws *WebSocket) LiveNotifications(liveQueryID string) (chan Notification, e return c, err } -func (ws *WebSocket) Kill(id string) (interface{}, error) { +func (ws *WebSocketConnection) Kill(id string) (interface{}, error) { return ws.Send("kill", []interface{}{id}) } @@ -144,7 +144,7 @@ var ( ErrInvalidResponseID = errors.New("invalid response id") ) -func (ws *WebSocket) createResponseChannel(id string) (chan RPCResponse, error) { +func (ws *WebSocketConnection) createResponseChannel(id string) (chan RPCResponse, error) { ws.responseChannelsLock.Lock() defer ws.responseChannelsLock.Unlock() @@ -158,7 +158,7 @@ func (ws *WebSocket) createResponseChannel(id string) (chan RPCResponse, error) return ch, nil } -func (ws *WebSocket) createNotificationChannel(liveQueryID string) (chan Notification, error) { +func (ws *WebSocketConnection) createNotificationChannel(liveQueryID string) (chan Notification, error) { ws.notificationChannelsLock.Lock() defer ws.notificationChannelsLock.Unlock() @@ -172,27 +172,27 @@ func (ws *WebSocket) createNotificationChannel(liveQueryID string) (chan Notific return ch, nil } -func (ws *WebSocket) removeResponseChannel(id string) { +func (ws *WebSocketConnection) removeResponseChannel(id string) { ws.responseChannelsLock.Lock() defer ws.responseChannelsLock.Unlock() delete(ws.responseChannels, id) } -func (ws *WebSocket) getResponseChannel(id string) (chan RPCResponse, bool) { +func (ws *WebSocketConnection) getResponseChannel(id string) (chan RPCResponse, bool) { ws.responseChannelsLock.RLock() defer ws.responseChannelsLock.RUnlock() ch, ok := ws.responseChannels[id] return ch, ok } -func (ws *WebSocket) getLiveChannel(id string) (chan Notification, bool) { +func (ws *WebSocketConnection) getLiveChannel(id string) (chan Notification, bool) { ws.notificationChannelsLock.RLock() defer ws.notificationChannelsLock.RUnlock() ch, ok := ws.notificationChannels[id] return ch, ok } -func (ws *WebSocket) Use(namespace string, database string) error { +func (ws *WebSocketConnection) Use(namespace, database string) error { _, err := ws.Send("use", []interface{}{namespace, database}) if err != nil { return err @@ -201,17 +201,17 @@ func (ws *WebSocket) Use(namespace string, database string) error { return nil } -func (ws *WebSocket) Let(key string, value interface{}) error { +func (ws *WebSocketConnection) Let(key string, value interface{}) error { _, err := ws.Send("let", []interface{}{key, value}) return err } -func (ws *WebSocket) Unset(key string) error { +func (ws *WebSocketConnection) Unset(key string) error { _, err := ws.Send("unset", []interface{}{key}) return err } -func (ws *WebSocket) Send(method string, params []interface{}) (interface{}, error) { +func (ws *WebSocketConnection) Send(method string, params []interface{}) (interface{}, error) { select { case <-ws.closeChan: return nil, ws.closeError @@ -253,7 +253,7 @@ func (ws *WebSocket) Send(method string, params []interface{}) (interface{}, err } } -func (ws *WebSocket) read(v interface{}) error { +func (ws *WebSocketConnection) read(v interface{}) error { _, data, err := ws.Conn.ReadMessage() if err != nil { return err @@ -261,7 +261,7 @@ func (ws *WebSocket) read(v interface{}) error { return ws.unmarshaler.Unmarshal(data, v) } -func (ws *WebSocket) write(v interface{}) error { +func (ws *WebSocketConnection) write(v interface{}) error { data, err := ws.marshaler.Marshal(v) if err != nil { return err @@ -272,7 +272,7 @@ func (ws *WebSocket) write(v interface{}) error { return ws.Conn.WriteMessage(gorilla.BinaryMessage, data) } -func (ws *WebSocket) initialize() { +func (ws *WebSocketConnection) initialize() { for { select { case <-ws.closeChan: @@ -292,7 +292,7 @@ func (ws *WebSocket) initialize() { } } -func (ws *WebSocket) handleError(err error) bool { +func (ws *WebSocketConnection) handleError(err error) bool { fmt.Println(err) if errors.Is(err, net.ErrClosed) { ws.closeError = net.ErrClosed @@ -308,7 +308,7 @@ func (ws *WebSocket) handleError(err error) bool { return false } -func (ws *WebSocket) handleResponse(res RPCResponse) { +func (ws *WebSocketConnection) handleResponse(res RPCResponse) { if res.ID != nil && res.ID != "" { // Try to resolve message as response to query responseChan, ok := ws.getResponseChannel(fmt.Sprintf("%v", res.ID)) diff --git a/pkg/connection/ws_test.go b/pkg/connection/ws_test.go index 287aa46..a0ff73c 100644 --- a/pkg/connection/ws_test.go +++ b/pkg/connection/ws_test.go @@ -14,7 +14,7 @@ func TestEngine_WsMakeRequest(t *testing.T) { Unmarshaler: model.CborUnmashaler{}, BaseURL: "ws://127.0.0.1:8000", } - con := NewWebSocket(p) + con := NewWebSocketConnection(p) err := con.Connect() assert.Nil(t, err, "no error returned when initializing engine connection") diff --git a/pkg/constants/constants.go b/pkg/constants/constants.go index 3935c5f..26357d8 100644 --- a/pkg/constants/constants.go +++ b/pkg/constants/constants.go @@ -8,3 +8,10 @@ var ( ErrQuery = errors.New("error occurred processing the SurrealDB query") ErrNoRow = errors.New("error no row") ) + +var ( + WebsocketScheme = "ws" + WebsocketSucerScheme = "wss" + HTTPScheme = "http" + HTTPSecureScheme = "https" +) diff --git a/pkg/logger/slog_test.go b/pkg/logger/slog_test.go index 05174cd..9d0ccba 100644 --- a/pkg/logger/slog_test.go +++ b/pkg/logger/slog_test.go @@ -1,4 +1,4 @@ -package logger_test +package logger import ( "bytes" diff --git a/pkg/model/cbor.go b/pkg/model/cbor.go index b914432..b646aa1 100644 --- a/pkg/model/cbor.go +++ b/pkg/model/cbor.go @@ -115,30 +115,6 @@ func getCborDecoder() cbor.DecMode { return dm } -func (gp *GeometryPoint) MarshalCBOR() ([]byte, error) { - enc := getCborEncoder() - - return enc.Marshal(cbor.Tag{ - Number: uint64(GeometryPointTag), - Content: gp.GetCoordinates(), - }) -} - -func (g *GeometryPoint) UnmarshalCBOR(data []byte) error { - dec := getCborDecoder() - - var temp [2]float64 - err := dec.Unmarshal(data, &temp) - if err != nil { - return err - } - - g.Latitude = temp[0] - g.Longitude = temp[1] - - return nil -} - func (r *RecordID) MarshalCBOR() ([]byte, error) { enc := getCborEncoder() diff --git a/pkg/model/cbor_test.go b/pkg/model/cbor_test.go index 996c3ec..9e004f4 100644 --- a/pkg/model/cbor_test.go +++ b/pkg/model/cbor_test.go @@ -71,7 +71,7 @@ func TestForRequestPayload(t *testing.T) { "line": GeometryLine{NewGeometryPoint(11.11, 22.22), NewGeometryPoint(33.33, 44.44)}, "datetime": time.Now(), "testnil": nil, - //"duration": Duration(340), + // "duration": Duration(340), }, } diff --git a/pkg/model/model.go b/pkg/model/model.go index 76c7379..d8f5c88 100644 --- a/pkg/model/model.go +++ b/pkg/model/model.go @@ -1,6 +1,9 @@ package model -import "time" +import ( + "github.com/fxamacker/cbor/v2" + "time" +) type GeometryPoint struct { Latitude float64 @@ -17,6 +20,30 @@ func (g *GeometryPoint) GetCoordinates() [2]float64 { return [2]float64{g.Latitude, g.Longitude} } +func (gp *GeometryPoint) MarshalCBOR() ([]byte, error) { + enc := getCborEncoder() + + return enc.Marshal(cbor.Tag{ + Number: uint64(GeometryPointTag), + Content: gp.GetCoordinates(), + }) +} + +func (g *GeometryPoint) UnmarshalCBOR(data []byte) error { + dec := getCborDecoder() + + var temp [2]float64 + err := dec.Unmarshal(data, &temp) + if err != nil { + return err + } + + g.Latitude = temp[0] + g.Longitude = temp[1] + + return nil +} + type GeometryLine []GeometryPoint type GeometryPolygon []GeometryLine