Skip to content

Commit

Permalink
PR: Move panics under must functions & add a linter
Browse files Browse the repository at this point in the history
  • Loading branch information
shahzadlone committed Oct 15, 2024
1 parent 73602bd commit 1b8b14e
Show file tree
Hide file tree
Showing 15 changed files with 202 additions and 89 deletions.
4 changes: 1 addition & 3 deletions cli/p2p_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ package cli

import (
"github.com/spf13/cobra"

"github.com/sourcenetwork/defradb/http"
)

func MakeP2PInfoCommand() *cobra.Command {
Expand All @@ -22,7 +20,7 @@ func MakeP2PInfoCommand() *cobra.Command {
Short: "Get peer info from a DefraDB node",
Long: `Get peer info from a DefraDB node`,
RunE: func(cmd *cobra.Command, args []string) error {
db := cmd.Context().Value(dbContextKey).(*http.Client)
db := mustGetContextHTTP(cmd)
return writeJSON(cmd, db.PeerInfo())
},
}
Expand Down
4 changes: 1 addition & 3 deletions cli/purge.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ package cli

import (
"github.com/spf13/cobra"

"github.com/sourcenetwork/defradb/http"
)

func MakePurgeCommand() *cobra.Command {
Expand All @@ -24,7 +22,7 @@ func MakePurgeCommand() *cobra.Command {
Long: `Delete all persisted data and restart.
WARNING this operation cannot be reversed.`,
RunE: func(cmd *cobra.Command, args []string) error {
db := mustGetContextDB(cmd).(*http.Client)
db := mustGetContextHTTP(cmd)
if !force {
return ErrPurgeForceFlagRequired
}
Expand Down
17 changes: 12 additions & 5 deletions cli/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,35 +60,42 @@ const (
//
// If a db is not set in the current context this function panics.
func mustGetContextDB(cmd *cobra.Command) client.DB {
return cmd.Context().Value(dbContextKey).(client.DB)
return cmd.Context().Value(dbContextKey).(client.DB) //nolint:forcetypeassert
}

// mustGetContextStore returns the store for the current command context.
//
// If a store is not set in the current context this function panics.
func mustGetContextStore(cmd *cobra.Command) client.Store {
return cmd.Context().Value(dbContextKey).(client.Store)
return cmd.Context().Value(dbContextKey).(client.Store) //nolint:forcetypeassert
}

// mustGetContextP2P returns the p2p implementation for the current command context.
//
// If a p2p implementation is not set in the current context this function panics.
func mustGetContextP2P(cmd *cobra.Command) client.P2P {
return cmd.Context().Value(dbContextKey).(client.P2P)
return cmd.Context().Value(dbContextKey).(client.P2P) //nolint:forcetypeassert
}

// mustGetContextHTTP returns the http client for the current command context.
//
// If http client is not set in the current context this function panics.
func mustGetContextHTTP(cmd *cobra.Command) *http.Client {
return cmd.Context().Value(dbContextKey).(*http.Client) //nolint:forcetypeassert
}

// mustGetContextConfig returns the config for the current command context.
//
// If a config is not set in the current context this function panics.
func mustGetContextConfig(cmd *cobra.Command) *viper.Viper {
return cmd.Context().Value(cfgContextKey).(*viper.Viper)
return cmd.Context().Value(cfgContextKey).(*viper.Viper) //nolint:forcetypeassert
}

// mustGetContextRootDir returns the rootdir for the current command context.
//
// If a rootdir is not set in the current context this function panics.
func mustGetContextRootDir(cmd *cobra.Command) string {
return cmd.Context().Value(rootDirContextKey).(string)
return cmd.Context().Value(rootDirContextKey).(string) //nolint:forcetypeassert
}

// tryGetContextCollection returns the collection for the current command context
Expand Down
23 changes: 12 additions & 11 deletions http/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,18 @@ const (
// This list is incomplete. Undefined errors may also be returned.
// Errors returned from this package may be tested against these errors with errors.Is.
var (
ErrNoListener = errors.New("cannot serve with no listener")
ErrNoEmail = errors.New("email address must be specified for tls with autocert")
ErrInvalidRequestBody = errors.New("invalid request body")
ErrStreamingNotSupported = errors.New("streaming not supported")
ErrMigrationNotFound = errors.New("migration not found")
ErrMissingRequest = errors.New("missing request")
ErrInvalidTransactionId = errors.New("invalid transaction id")
ErrP2PDisabled = errors.New("p2p network is disabled")
ErrMethodIsNotImplemented = errors.New(errMethodIsNotImplemented)
ErrMissingIdentityPrivateKey = errors.New("identity has no private key")
ErrMissingIdentityPublicKey = errors.New("identity has no public key")
ErrNoListener = errors.New("cannot serve with no listener")
ErrNoEmail = errors.New("email address must be specified for tls with autocert")
ErrInvalidRequestBody = errors.New("invalid request body")
ErrStreamingNotSupported = errors.New("streaming not supported")
ErrMigrationNotFound = errors.New("migration not found")
ErrMissingRequest = errors.New("missing request")
ErrInvalidTransactionId = errors.New("invalid transaction id")
ErrInvalidDataStoreTransaction = errors.New("invalid datastore transaction")
ErrP2PDisabled = errors.New("p2p network is disabled")
ErrMethodIsNotImplemented = errors.New(errMethodIsNotImplemented)
ErrMissingIdentityPrivateKey = errors.New("identity has no private key")
ErrMissingIdentityPublicKey = errors.New("identity has no public key")
)

type errorResponse struct {
Expand Down
11 changes: 8 additions & 3 deletions http/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ package http

import (
"context"
"fmt"
"net/http"
"sync"

Expand Down Expand Up @@ -100,9 +99,15 @@ func NewHandler(db client.DB) (*Handler, error) {
func (h *Handler) Transaction(id uint64) (datastore.Txn, error) {
tx, ok := h.txs.Load(id)
if !ok {
return nil, fmt.Errorf("invalid transaction id")
return nil, ErrInvalidTransactionId

Check warning on line 102 in http/handler.go

View check run for this annotation

Codecov / codecov/patch

http/handler.go#L102

Added line #L102 was not covered by tests
}
return tx.(datastore.Txn), nil

dsTxn, ok := tx.(datastore.Txn)
if !ok {
return nil, ErrInvalidDataStoreTransaction

Check warning on line 107 in http/handler.go

View check run for this annotation

Codecov / codecov/patch

http/handler.go#L107

Added line #L107 was not covered by tests
}

return dsTxn, nil
}

func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
Expand Down
8 changes: 3 additions & 5 deletions http/handler_acp.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,12 @@ import (
"net/http"

"github.com/getkin/kin-openapi/openapi3"

"github.com/sourcenetwork/defradb/client"
)

type acpHandler struct{}

func (s *acpHandler) AddPolicy(rw http.ResponseWriter, req *http.Request) {
db := req.Context().Value(dbContextKey).(client.DB)
db := mustGetContextClientDB(req)

policyBytes, err := io.ReadAll(req.Body)
if err != nil {
Expand All @@ -43,7 +41,7 @@ func (s *acpHandler) AddPolicy(rw http.ResponseWriter, req *http.Request) {
}

func (s *acpHandler) AddDocActorRelationship(rw http.ResponseWriter, req *http.Request) {
db := req.Context().Value(dbContextKey).(client.DB)
db := mustGetContextClientDB(req)

var message addDocActorRelationshipRequest
err := requestJSON(req, &message)
Expand All @@ -68,7 +66,7 @@ func (s *acpHandler) AddDocActorRelationship(rw http.ResponseWriter, req *http.R
}

func (s *acpHandler) DeleteDocActorRelationship(rw http.ResponseWriter, req *http.Request) {
db := req.Context().Value(dbContextKey).(client.DB)
db := mustGetContextClientDB(req)

var message deleteDocActorRelationshipRequest
err := requestJSON(req, &message)
Expand Down
4 changes: 1 addition & 3 deletions http/handler_ccip.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ import (

"github.com/getkin/kin-openapi/openapi3"
"github.com/go-chi/chi/v5"

"github.com/sourcenetwork/defradb/client"
)

type ccipHandler struct{}
Expand All @@ -35,7 +33,7 @@ type CCIPResponse struct {

// ExecCCIP handles GraphQL over Cross Chain Interoperability Protocol requests.
func (c *ccipHandler) ExecCCIP(rw http.ResponseWriter, req *http.Request) {
store := req.Context().Value(dbContextKey).(client.Store)
store := mustGetContextClientStore(req)

var ccipReq CCIPRequest
switch req.Method {
Expand Down
20 changes: 10 additions & 10 deletions http/handler_collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ type CollectionUpdateRequest struct {
}

func (s *collectionHandler) Create(rw http.ResponseWriter, req *http.Request) {
col := req.Context().Value(colContextKey).(client.Collection)
col := mustGetContextClientCollection(req)

data, err := io.ReadAll(req.Body)
if err != nil {
Expand Down Expand Up @@ -89,7 +89,7 @@ func (s *collectionHandler) Create(rw http.ResponseWriter, req *http.Request) {
}

func (s *collectionHandler) DeleteWithFilter(rw http.ResponseWriter, req *http.Request) {
col := req.Context().Value(colContextKey).(client.Collection)
col := mustGetContextClientCollection(req)

Check warning on line 92 in http/handler_collection.go

View check run for this annotation

Codecov / codecov/patch

http/handler_collection.go#L92

Added line #L92 was not covered by tests

var request CollectionDeleteRequest
if err := requestJSON(req, &request); err != nil {
Expand All @@ -106,7 +106,7 @@ func (s *collectionHandler) DeleteWithFilter(rw http.ResponseWriter, req *http.R
}

func (s *collectionHandler) UpdateWithFilter(rw http.ResponseWriter, req *http.Request) {
col := req.Context().Value(colContextKey).(client.Collection)
col := mustGetContextClientCollection(req)

var request CollectionUpdateRequest
if err := requestJSON(req, &request); err != nil {
Expand All @@ -123,7 +123,7 @@ func (s *collectionHandler) UpdateWithFilter(rw http.ResponseWriter, req *http.R
}

func (s *collectionHandler) Update(rw http.ResponseWriter, req *http.Request) {
col := req.Context().Value(colContextKey).(client.Collection)
col := mustGetContextClientCollection(req)

docID, err := client.NewDocIDFromString(chi.URLParam(req, "docID"))
if err != nil {
Expand Down Expand Up @@ -160,7 +160,7 @@ func (s *collectionHandler) Update(rw http.ResponseWriter, req *http.Request) {
}

func (s *collectionHandler) Delete(rw http.ResponseWriter, req *http.Request) {
col := req.Context().Value(colContextKey).(client.Collection)
col := mustGetContextClientCollection(req)

docID, err := client.NewDocIDFromString(chi.URLParam(req, "docID"))
if err != nil {
Expand All @@ -177,7 +177,7 @@ func (s *collectionHandler) Delete(rw http.ResponseWriter, req *http.Request) {
}

func (s *collectionHandler) Get(rw http.ResponseWriter, req *http.Request) {
col := req.Context().Value(colContextKey).(client.Collection)
col := mustGetContextClientCollection(req)
showDeleted, _ := strconv.ParseBool(req.URL.Query().Get("show_deleted"))

docID, err := client.NewDocIDFromString(chi.URLParam(req, "docID"))
Expand Down Expand Up @@ -211,7 +211,7 @@ type DocIDResult struct {
}

func (s *collectionHandler) GetAllDocIDs(rw http.ResponseWriter, req *http.Request) {
col := req.Context().Value(colContextKey).(client.Collection)
col := mustGetContextClientCollection(req)

Check warning on line 214 in http/handler_collection.go

View check run for this annotation

Codecov / codecov/patch

http/handler_collection.go#L214

Added line #L214 was not covered by tests

flusher, ok := rw.(http.Flusher)
if !ok {
Expand Down Expand Up @@ -252,7 +252,7 @@ func (s *collectionHandler) GetAllDocIDs(rw http.ResponseWriter, req *http.Reque
}

func (s *collectionHandler) CreateIndex(rw http.ResponseWriter, req *http.Request) {
col := req.Context().Value(colContextKey).(client.Collection)
col := mustGetContextClientCollection(req)

var indexDesc client.IndexDescription
if err := requestJSON(req, &indexDesc); err != nil {
Expand All @@ -268,7 +268,7 @@ func (s *collectionHandler) CreateIndex(rw http.ResponseWriter, req *http.Reques
}

func (s *collectionHandler) GetIndexes(rw http.ResponseWriter, req *http.Request) {
store := req.Context().Value(dbContextKey).(client.Store)
store := mustGetContextClientStore(req)
indexesMap, err := store.GetAllIndexes(req.Context())

if err != nil {
Expand All @@ -283,7 +283,7 @@ func (s *collectionHandler) GetIndexes(rw http.ResponseWriter, req *http.Request
}

func (s *collectionHandler) DropIndex(rw http.ResponseWriter, req *http.Request) {
col := req.Context().Value(colContextKey).(client.Collection)
col := mustGetContextClientCollection(req)

err := col.DropIndex(req.Context(), chi.URLParam(req, "index"))
if err != nil {
Expand Down
3 changes: 1 addition & 2 deletions http/handler_extras.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,14 @@ import (

"github.com/getkin/kin-openapi/openapi3"

"github.com/sourcenetwork/defradb/client"
"github.com/sourcenetwork/defradb/event"
)

// extrasHandler contains additional http handlers not found in client interfaces.
type extrasHandler struct{}

func (s *extrasHandler) Purge(rw http.ResponseWriter, req *http.Request) {
db := req.Context().Value(dbContextKey).(client.DB)
db := mustGetContextClientDB(req)
rw.WriteHeader(http.StatusOK) // write the response before we restart to purge
db.Events().Publish(event.NewMessage(event.PurgeName, nil))
}
Expand Down
10 changes: 4 additions & 6 deletions http/handler_lens.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,12 @@ import (

"github.com/getkin/kin-openapi/openapi3"
"github.com/sourcenetwork/immutable/enumerable"

"github.com/sourcenetwork/defradb/client"
)

type lensHandler struct{}

func (s *lensHandler) ReloadLenses(rw http.ResponseWriter, req *http.Request) {
store := req.Context().Value(dbContextKey).(client.Store)
store := mustGetContextClientStore(req)

Check warning on line 23 in http/handler_lens.go

View check run for this annotation

Codecov / codecov/patch

http/handler_lens.go#L23

Added line #L23 was not covered by tests

err := store.LensRegistry().ReloadLenses(req.Context())
if err != nil {
Expand All @@ -33,7 +31,7 @@ func (s *lensHandler) ReloadLenses(rw http.ResponseWriter, req *http.Request) {
}

func (s *lensHandler) SetMigration(rw http.ResponseWriter, req *http.Request) {
store := req.Context().Value(dbContextKey).(client.Store)
store := mustGetContextClientStore(req)

Check warning on line 34 in http/handler_lens.go

View check run for this annotation

Codecov / codecov/patch

http/handler_lens.go#L34

Added line #L34 was not covered by tests

var request setMigrationRequest
if err := requestJSON(req, &request); err != nil {
Expand All @@ -50,7 +48,7 @@ func (s *lensHandler) SetMigration(rw http.ResponseWriter, req *http.Request) {
}

func (s *lensHandler) MigrateUp(rw http.ResponseWriter, req *http.Request) {
store := req.Context().Value(dbContextKey).(client.Store)
store := mustGetContextClientStore(req)

Check warning on line 51 in http/handler_lens.go

View check run for this annotation

Codecov / codecov/patch

http/handler_lens.go#L51

Added line #L51 was not covered by tests

var request migrateRequest
if err := requestJSON(req, &request); err != nil {
Expand All @@ -75,7 +73,7 @@ func (s *lensHandler) MigrateUp(rw http.ResponseWriter, req *http.Request) {
}

func (s *lensHandler) MigrateDown(rw http.ResponseWriter, req *http.Request) {
store := req.Context().Value(dbContextKey).(client.Store)
store := mustGetContextClientStore(req)

Check warning on line 76 in http/handler_lens.go

View check run for this annotation

Codecov / codecov/patch

http/handler_lens.go#L76

Added line #L76 was not covered by tests

var request migrateRequest
if err := requestJSON(req, &request); err != nil {
Expand Down
Loading

0 comments on commit 1b8b14e

Please sign in to comment.