diff --git a/cmd/api/docs/docs.go b/cmd/api/docs/docs.go index fe7f6f8af..332125d38 100644 --- a/cmd/api/docs/docs.go +++ b/cmd/api/docs/docs.go @@ -3944,14 +3944,6 @@ var doc = `{ "tx_count": { "type": "integer", "x-nullable": true - }, - "verification_source": { - "type": "string", - "x-nullable": true - }, - "verified": { - "type": "boolean", - "x-nullable": true } } }, @@ -4472,14 +4464,6 @@ var doc = `{ "tx_count": { "type": "integer", "x-nullable": true - }, - "verification_source": { - "type": "string", - "x-nullable": true - }, - "verified": { - "type": "boolean", - "x-nullable": true } } }, diff --git a/cmd/api/docs/swagger.json b/cmd/api/docs/swagger.json index 636eeb10c..2362a77eb 100644 --- a/cmd/api/docs/swagger.json +++ b/cmd/api/docs/swagger.json @@ -3926,14 +3926,6 @@ "tx_count": { "type": "integer", "x-nullable": true - }, - "verification_source": { - "type": "string", - "x-nullable": true - }, - "verified": { - "type": "boolean", - "x-nullable": true } } }, @@ -4454,14 +4446,6 @@ "tx_count": { "type": "integer", "x-nullable": true - }, - "verification_source": { - "type": "string", - "x-nullable": true - }, - "verified": { - "type": "boolean", - "x-nullable": true } } }, diff --git a/cmd/api/docs/swagger.yaml b/cmd/api/docs/swagger.yaml index d43896660..a3d5a7fc4 100644 --- a/cmd/api/docs/swagger.yaml +++ b/cmd/api/docs/swagger.yaml @@ -357,12 +357,6 @@ definitions: tx_count: type: integer x-nullable: true - verification_source: - type: string - x-nullable: true - verified: - type: boolean - x-nullable: true type: object handlers.CountResponse: properties: @@ -726,12 +720,6 @@ definitions: tx_count: type: integer x-nullable: true - verification_source: - type: string - x-nullable: true - verified: - type: boolean - x-nullable: true type: object handlers.SimilarContractsResponse: properties: diff --git a/cmd/api/handlers/auth.go b/cmd/api/handlers/auth.go deleted file mode 100644 index 275db74aa..000000000 --- a/cmd/api/handlers/auth.go +++ /dev/null @@ -1,63 +0,0 @@ -package handlers - -import ( - "fmt" - "net/http" - - "github.com/baking-bad/bcdhub/internal/helpers" - - "github.com/gin-gonic/gin" -) - -// AuthJWTRequired - -func (ctx *Context) AuthJWTRequired() gin.HandlerFunc { - if ctx.Config.API.SeedEnabled { - return ctx.skipAuth() - } - - return func(c *gin.Context) { - userID, err := ctx.getUserFromToken(c) - if ctx.handleError(c, err, http.StatusUnauthorized) { - return - } - - helpers.SetUserIDSentry(fmt.Sprintf("%v", userID)) - setUserIDAndNext(userID, c) - } - -} - -// IsAuthenticated - -func (ctx *Context) IsAuthenticated() gin.HandlerFunc { - if ctx.Config.API.SeedEnabled { - return ctx.skipAuth() - } - - return func(c *gin.Context) { - userID, err := ctx.getUserFromToken(c) - if err != nil { - return - } - - setUserIDAndNext(userID, c) - } - -} - -func (ctx *Context) getUserFromToken(c *gin.Context) (uint, error) { - token := c.GetHeader("Authorization") - return ctx.OAUTH.GetIDFromToken(token) -} - -func (ctx *Context) skipAuth() func(*gin.Context) { - userID := ctx.OAUTH.UserID - - return func(c *gin.Context) { - setUserIDAndNext(userID, c) - } -} - -func setUserIDAndNext(userID uint, c *gin.Context) { - c.Set("userID", userID) - c.Next() -} diff --git a/cmd/api/handlers/config.go b/cmd/api/handlers/config.go index bf032c81f..a0d469589 100644 --- a/cmd/api/handlers/config.go +++ b/cmd/api/handlers/config.go @@ -21,7 +21,6 @@ func (ctx *Context) GetConfig(c *gin.Context) { cfg := ConfigResponse{ Networks: ctx.Config.API.Networks, - OauthEnabled: ctx.Config.API.OAuthEnabled, RPCEndpoints: rpcEndpoints, TzKTEndpoints: tzktEndpoints, GaEnabled: ctx.Config.API.Frontend.GaEnabled, diff --git a/cmd/api/handlers/context.go b/cmd/api/handlers/context.go index c82f12ce3..5b5d0a272 100644 --- a/cmd/api/handlers/context.go +++ b/cmd/api/handlers/context.go @@ -1,9 +1,7 @@ package handlers import ( - "github.com/baking-bad/bcdhub/cmd/api/oauth" "github.com/baking-bad/bcdhub/internal/config" - "github.com/gin-gonic/gin" jsoniter "github.com/json-iterator/go" ) @@ -12,24 +10,13 @@ var json = jsoniter.ConfigCompatibleWithStandardLibrary // Context - type Context struct { *config.Context - OAUTH oauth.Config } // NewContext - func NewContext(cfg config.Config) (*Context, error) { - var oauthCfg oauth.Config - if cfg.API.OAuthEnabled { - var err error - oauthCfg, err = oauth.New(cfg) - if err != nil { - return nil, err - } - } - ctx := config.NewContext( config.WithStorage(cfg.Storage, cfg.API.ProjectName, int64(cfg.API.PageSize)), config.WithRPC(cfg.RPC), - config.WithDatabase(cfg.DB), config.WithSearch(cfg.Storage), config.WithShare(cfg.SharePath), config.WithTzKTServices(cfg.TzKT), @@ -41,17 +28,5 @@ func NewContext(cfg config.Config) (*Context, error) { return &Context{ Context: ctx, - OAUTH: oauthCfg, }, nil } - -// CurrentUserID - return userID (uint) from gin context -func CurrentUserID(c *gin.Context) uint { - if val, ok := c.Get("userID"); ok && val != nil { - if userID, valid := val.(uint); valid { - return userID - } - } - - return 0 -} diff --git a/cmd/api/handlers/contract.go b/cmd/api/handlers/contract.go index 3430cb011..5407a190e 100644 --- a/cmd/api/handlers/contract.go +++ b/cmd/api/handlers/contract.go @@ -5,7 +5,6 @@ import ( "github.com/baking-bad/bcdhub/internal/models/contract" "github.com/gin-gonic/gin" - "github.com/jinzhu/gorm" ) // GetContract godoc @@ -39,7 +38,7 @@ func (ctx *Context) GetContract(c *gin.Context) { return } - res, err := ctx.contractPostprocessing(contract, c) + res, err := ctx.contractPostprocessing(contract) if ctx.handleError(c, err, 0) { return } @@ -74,32 +73,17 @@ func (ctx *Context) GetRandomContract(c *gin.Context) { return } - res, err := ctx.contractPostprocessing(contract, c) + res, err := ctx.contractPostprocessing(contract) if ctx.handleError(c, err, 0) { return } c.JSON(http.StatusOK, res) } -func (ctx *Context) contractPostprocessing(contract contract.Contract, c *gin.Context) (Contract, error) { +func (ctx *Context) contractPostprocessing(contract contract.Contract) (Contract, error) { var res Contract res.FromModel(contract) - if userID, err := ctx.getUserFromToken(c); err == nil && userID != 0 { - if sub, err := ctx.DB.GetSubscription(userID, res.Address, contract.Network); err == nil { - subscription := PrepareSubscription(sub) - res.Subscription = &subscription - } else if !gorm.IsRecordNotFoundError(err) { - return res, err - } - } - - if totalSubscribed, err := ctx.DB.GetSubscriptionsCount(res.Address, contract.Network); err == nil { - res.TotalSubscribed = totalSubscribed - } else { - return res, err - } - if alias, err := ctx.TZIP.Get(contract.Network, contract.Address); err == nil { res.Slug = alias.Slug } else if !ctx.Storage.IsRecordNotFound(err) { diff --git a/cmd/api/handlers/events.go b/cmd/api/handlers/events.go deleted file mode 100644 index 9edd4f52c..000000000 --- a/cmd/api/handlers/events.go +++ /dev/null @@ -1,180 +0,0 @@ -package handlers - -import ( - "net/http" - "time" - - "github.com/baking-bad/bcdhub/internal/bcd" - "github.com/baking-bad/bcdhub/internal/bcd/consts" - "github.com/baking-bad/bcdhub/internal/bcd/tezerrors" - "github.com/baking-bad/bcdhub/internal/bcd/types" - "github.com/baking-bad/bcdhub/internal/database" - "github.com/baking-bad/bcdhub/internal/models" - "github.com/baking-bad/bcdhub/internal/models/contract" - "github.com/baking-bad/bcdhub/internal/postgres/core" - "github.com/gin-gonic/gin" -) - -// GetEvents - -func (ctx *Context) GetEvents(c *gin.Context) { - userID := CurrentUserID(c) - if userID == 0 { - c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user"}) - return - } - - var pageReq pageableRequest - if err := c.BindQuery(&pageReq); ctx.handleError(c, err, http.StatusBadRequest) { - return - } - - subscriptions, err := ctx.DB.ListSubscriptions(userID) - if ctx.handleError(c, err, 0) { - return - } - - events, err := ctx.getEvents(subscriptions, pageReq.Size, pageReq.Offset) - if ctx.handleError(c, err, 0) { - return - } - - c.JSON(http.StatusOK, events) -} - -// GetMempoolEvents - -func (ctx *Context) GetMempoolEvents(c *gin.Context) { - userID := CurrentUserID(c) - if userID == 0 { - c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user"}) - return - } - - subscriptions, err := ctx.DB.ListSubscriptions(userID) - if ctx.handleError(c, err, 0) { - return - } - - events, err := ctx.getMempoolEvents(subscriptions) - if ctx.handleError(c, err, 0) { - return - } - - c.JSON(http.StatusOK, events) -} - -func (ctx *Context) getEvents(subscriptions []database.Subscription, size, offset int64) ([]models.Event, error) { - subs := make([]models.SubscriptionRequest, len(subscriptions)) - for i := range subscriptions { - subs[i] = models.SubscriptionRequest{ - Address: subscriptions[i].Address, - Network: subscriptions[i].Network, - Alias: subscriptions[i].Alias, - - WithSame: subscriptions[i].WatchMask&WatchSame != 0, - WithSimilar: subscriptions[i].WatchMask&WatchSimilar != 0, - WithMempool: subscriptions[i].WatchMask&WatchMempool != 0, - WithMigrations: subscriptions[i].WatchMask&WatchMigrations != 0, - WithDeployments: subscriptions[i].WatchMask&WatchDeployments != 0, - WithCalls: subscriptions[i].WatchMask&WatchCalls != 0, - WithErrors: subscriptions[i].WatchMask&WatchErrors != 0, - } - - if bcd.IsContract(subscriptions[i].Address) { - contract := contract.NewEmptyContract(subscriptions[i].Network, subscriptions[i].Address) - if err := ctx.Storage.GetByID(&contract); err != nil { - return []models.Event{}, err - } - subs[i].Hash = contract.Hash - subs[i].ProjectID = contract.ProjectID - } - } - - return ctx.Storage.GetEvents(subs, size, offset) -} - -func (ctx *Context) getMempoolEvents(subscriptions []database.Subscription) ([]models.Event, error) { - events := make([]models.Event, 0) - - for _, sub := range subscriptions { - if sub.WatchMask&WatchMempool == 0 { - continue - } - - api, err := ctx.GetTzKTService(sub.Network) - if err != nil { - return events, err - } - - res, err := api.GetMempool(sub.Address) - if err != nil { - return events, err - } - if len(res) == 0 { - continue - } - - aliases, err := ctx.TZIP.GetAliasesMap(sub.Network) - if err != nil { - if !ctx.Storage.IsRecordNotFound(err) { - return nil, err - } - aliases = make(map[string]string) - } - - for _, item := range res { - status := item.Body.Status - if status == consts.Applied { - status = consts.Pending - } - - op := core.EventOperation{ - Network: sub.Network, - Hash: item.Body.Hash, - Status: status, - Timestamp: time.Unix(item.Body.Timestamp, 0).UTC(), - Kind: item.Body.Kind, - Fee: item.Body.Fee, - Amount: item.Body.Amount, - Source: item.Body.Source, - Destination: item.Body.Destination, - } - - op.SourceAlias = aliases[op.Source] - op.DestinationAlias = aliases[op.Destination] - op.Errors, err = tezerrors.ParseArray(item.Body.Errors) - if err != nil { - return nil, err - } - - if bcd.IsContract(op.Destination) && item.Body.Protocol != "" { - if len(item.Body.Parameters) > 0 { - p := types.NewParameters(item.Body.Parameters) - - parameter, err := ctx.getParameterType(op.Network, op.Destination, item.Body.Protocol) - if err != nil { - return events, err - } - - tree, err := parameter.FromParameters(p) - if err != nil && op.Errors == nil { - return events, err - } - - op.Entrypoint = tree.Nodes[0].GetName() - } else { - op.Entrypoint = consts.DefaultEntrypoint - } - } - - event := models.Event{ - Type: models.EventTypeMempool, - Address: sub.Address, - Network: sub.Network, - Alias: sub.Alias, - Body: &op, - } - events = append(events, event) - } - } - return events, nil -} diff --git a/cmd/api/handlers/oauth.go b/cmd/api/handlers/oauth.go deleted file mode 100644 index 5e50a47e8..000000000 --- a/cmd/api/handlers/oauth.go +++ /dev/null @@ -1,73 +0,0 @@ -package handlers - -import ( - "fmt" - "net/http" - - "github.com/baking-bad/bcdhub/internal/database" - "github.com/gin-gonic/gin" - "github.com/pkg/errors" -) - -// OauthLogin - -func (ctx *Context) OauthLogin(c *gin.Context) { - var params OauthParams - if err := c.BindUri(¶ms); ctx.handleError(c, err, http.StatusBadRequest) { - return - } - - var redirectURL string - - if provider, ok := ctx.OAUTH.Providers[params.Provider]; ok { - redirectURL = provider.AuthCodeURL(ctx.OAUTH.State) - } else { - ctx.handleError(c, fmt.Errorf("invalid provider %v", params.Provider), http.StatusBadRequest) - return - } - - c.Redirect(http.StatusTemporaryRedirect, redirectURL) -} - -// OauthCallback - -func (ctx *Context) OauthCallback(c *gin.Context) { - var params OauthParams - if err := c.BindUri(¶ms); ctx.handleError(c, err, http.StatusBadRequest) { - return - } - - var req OauthRequest - if err := c.ShouldBind(&req); ctx.handleError(c, err, http.StatusBadRequest) { - return - } - - if req.State != ctx.OAUTH.State { - ctx.handleError(c, errors.Errorf("invalid oauth state"), http.StatusBadRequest) - return - } - - var user database.User - var err error - - if provider, ok := ctx.OAUTH.Providers[params.Provider]; ok { - user, err = provider.AuthUser(req.Code) - } else { - ctx.handleError(c, fmt.Errorf("invalid provider %v", params.Provider), http.StatusBadRequest) - return - } - - if ctx.handleError(c, err, http.StatusBadRequest) { - return - } - - if err := ctx.DB.GetOrCreateUser(&user, user.Token); ctx.handleError(c, err, http.StatusBadRequest) { - return - } - - jwt, err := ctx.OAUTH.MakeJWT(user.ID) - if ctx.handleError(c, err, http.StatusBadRequest) { - return - } - - location := fmt.Sprintf("%v?jwt=%v", ctx.OAUTH.JWTRedirectURL, jwt) - c.Redirect(http.StatusTemporaryRedirect, location) -} diff --git a/cmd/api/handlers/repos.go b/cmd/api/handlers/repos.go deleted file mode 100644 index a4c56c8fa..000000000 --- a/cmd/api/handlers/repos.go +++ /dev/null @@ -1,141 +0,0 @@ -package handlers - -import ( - "fmt" - "net/http" - - "github.com/baking-bad/bcdhub/internal/database" - "github.com/baking-bad/bcdhub/internal/providers" - "github.com/gin-gonic/gin" -) - -// ListPublicAccounts - -func (ctx *Context) ListPublicAccounts(c *gin.Context) { - userID := CurrentUserID(c) - if userID == 0 { - c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user"}) - return - } - - user, err := ctx.DB.GetUser(userID) - if ctx.handleError(c, err, 0) { - return - } - - orgs, err := getPublicOrgs(user) - if ctx.handleError(c, err, 0) { - return - } - - accounts := []providers.Account{ - { - Login: user.Login, - AvatarURL: user.AvatarURL, - }, - } - - c.JSON(http.StatusOK, append(accounts, orgs...)) -} - -func getPublicOrgs(user *database.User) ([]providers.Account, error) { - if user.Provider == "" { - return nil, fmt.Errorf("getPublicOrgs error, user has no provider") - } - - provider, err := providers.NewPublic(user.Provider) - if err != nil { - return nil, err - } - - if user.Login == "" { - return nil, fmt.Errorf("getPublicOrgs error, user has empty login") - } - - return provider.GetOrganizations(user.Login) -} - -// ListPublicRepos - -func (ctx *Context) ListPublicRepos(c *gin.Context) { - var req publicReposRequest - if err := c.BindQuery(&req); ctx.handleError(c, err, http.StatusBadRequest) { - return - } - - userID := CurrentUserID(c) - if userID == 0 { - c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user"}) - return - } - - user, err := ctx.DB.GetUser(userID) - if ctx.handleError(c, err, 0) { - return - } - - repos, err := getPublicRepos(req.Login, user) - if ctx.handleError(c, err, 0) { - return - } - - c.JSON(http.StatusOK, repos) -} - -func getPublicRepos(account string, user *database.User) ([]providers.Project, error) { - if user.Provider == "" { - return nil, fmt.Errorf("getPublicRepos error, user has no provider") - } - - provider, err := providers.NewPublic(user.Provider) - if err != nil { - return nil, err - } - - if user.Login == "" { - return nil, fmt.Errorf("getPublicRepos error, user has empty login") - } - - return provider.GetRepos(account) -} - -// ListPublicRefs - -func (ctx *Context) ListPublicRefs(c *gin.Context) { - userID := CurrentUserID(c) - if userID == 0 { - c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user"}) - return - } - - user, err := ctx.DB.GetUser(userID) - if ctx.handleError(c, err, 0) { - return - } - - var req publicRefsRequest - if err := c.BindQuery(&req); ctx.handleError(c, err, http.StatusBadRequest) { - return - } - - refs, err := getPublicRefs(user, req.Owner, req.Repo) - if ctx.handleError(c, err, 0) { - return - } - - c.JSON(http.StatusOK, refs) -} - -func getPublicRefs(user *database.User, owner, repo string) ([]providers.Ref, error) { - if user.Provider == "" { - return nil, fmt.Errorf("getPublicRefs error, user has no provider") - } - - provider, err := providers.NewPublic(user.Provider) - if err != nil { - return nil, err - } - - if user.Login == "" { - return nil, fmt.Errorf("getPublicRefs error, user has empty login") - } - - return provider.GetRefs(owner, repo) -} diff --git a/cmd/api/handlers/requests.go b/cmd/api/handlers/requests.go index c1be457fa..345ad717c 100644 --- a/cmd/api/handlers/requests.go +++ b/cmd/api/handlers/requests.go @@ -99,96 +99,11 @@ type searchRequest struct { Languages string `form:"l,omitempty"` } -// Subscription flags -const ( - WatchSame uint = 1 << iota - WatchSimilar - WatchMempool - WatchMigrations - WatchDeployments - WatchCalls - WatchErrors - SentryEnabled -) - -type subRequest struct { - getContractRequest - Alias string `json:"alias"` - WatchSame bool `json:"watch_same"` - WatchSimilar bool `json:"watch_similar"` - WatchMempool bool `json:"watch_mempool"` - WatchMigrations bool `json:"watch_migrations"` - WatchDeployments bool `json:"watch_deployments"` - WatchCalls bool `json:"watch_calls"` - WatchErrors bool `json:"watch_errors"` - SentryEnabled bool `json:"sentry_enabled"` - SentryDSN string `json:"sentry_dsn,omitempty"` -} - -func newSubscriptionWithMask(mask uint) Subscription { - return Subscription{ - WatchSame: mask&WatchSame != 0, - WatchSimilar: mask&WatchSimilar != 0, - WatchMempool: mask&WatchMempool != 0, - WatchMigrations: mask&WatchMigrations != 0, - WatchDeployments: mask&WatchDeployments != 0, - WatchCalls: mask&WatchCalls != 0, - WatchErrors: mask&WatchErrors != 0, - SentryEnabled: mask&SentryEnabled != 0, - } -} - -func (s subRequest) getMask() uint { - var b uint - - if s.WatchSame { - b |= WatchSame - } - - if s.WatchSimilar { - b |= WatchSimilar - } - - if s.WatchMempool { - b |= WatchMempool - } - - if s.WatchMigrations { - b |= WatchMigrations - } - - if s.WatchDeployments { - b |= WatchDeployments - } - - if s.WatchCalls { - b |= WatchCalls - } - - if s.WatchErrors { - b |= WatchErrors - } - - if s.SentryEnabled { - b |= SentryEnabled - } - - return b -} - type sameContractRequest struct { pageableRequest Manager string `form:"manager,omitempty"` } -type voteRequest struct { - SourceAddress string `json:"src" binding:"required,address"` - SourceNetwork types.Network `json:"src_network" binding:"required,network"` - DestinationAddress string `json:"dest" binding:"required,address"` - DestinationNetwork types.Network `json:"dest_network" binding:"required,network"` - Vote uint `json:"vote" binding:"oneof=1 2"` -} - // OPGRequest - type OPGRequest struct { Hash string `uri:"hash" binding:"required,opg" example:"ooy4c6G2BZzybYEY3vRQ7WXGL63tFmamTeGTHdjUxhd6ckbSNnb"` @@ -271,10 +186,6 @@ type runCodeRequest struct { Sender string `json:"sender,omitempty" binding:"omitempty,address"` } -type markReadRequest struct { - Timestamp int64 `json:"timestamp"` -} - type storageSchemaRequest struct { FillType string `form:"fill_type,omitempty" binding:"omitempty,fill_type"` } @@ -317,15 +228,6 @@ type getTokenSeriesRequest struct { Slug string `form:"slug" binding:"required"` } -type publicReposRequest struct { - Login string `form:"login" binding:"required"` -} - -type publicRefsRequest struct { - Owner string `form:"owner" binding:"required"` - Repo string `form:"repo" binding:"required"` -} - type getDappRequest struct { Slug string `uri:"slug" binding:"required"` } diff --git a/cmd/api/handlers/responses.go b/cmd/api/handlers/responses.go index 675a1978d..c5b1a5d26 100644 --- a/cmd/api/handlers/responses.go +++ b/cmd/api/handlers/responses.go @@ -214,19 +214,6 @@ type OperationResponse struct { LastID string `json:"last_id,omitempty" extensions:"x-nullable" example:"1588640276994159"` } -type userProfile struct { - Login string `json:"login"` - AvatarURL string `json:"avatar_url"` - MarkReadAt time.Time `json:"mark_read_at"` - RegisteredAt time.Time `json:"registered_at"` - MarkedContracts int `json:"marked_contracts"` - CompilationTasks int64 `json:"compilation_tasks"` - Verifications int64 `json:"verifications"` - Deployments int64 `json:"deployments"` - - Subscriptions []Subscription `json:"subscriptions"` -} - // BigMapItem - type BigMapItem struct { Key interface{} `json:"key"` diff --git a/cmd/api/handlers/subscriptions.go b/cmd/api/handlers/subscriptions.go deleted file mode 100644 index 4ed3b72c7..000000000 --- a/cmd/api/handlers/subscriptions.go +++ /dev/null @@ -1,108 +0,0 @@ -package handlers - -import ( - "fmt" - "net/http" - - "github.com/baking-bad/bcdhub/internal/database" - "github.com/baking-bad/bcdhub/internal/models/types" - - "github.com/gin-gonic/gin" -) - -// ListSubscriptions - -func (ctx *Context) ListSubscriptions(c *gin.Context) { - userID := CurrentUserID(c) - if userID == 0 { - c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user"}) - return - } - - subscriptions, err := ctx.DB.ListSubscriptions(userID) - if ctx.handleError(c, err, 0) { - return - } - - c.JSON(http.StatusOK, PrepareSubscriptions(subscriptions)) -} - -// CreateSubscription - -func (ctx *Context) CreateSubscription(c *gin.Context) { - var sub subRequest - if err := c.ShouldBindJSON(&sub); ctx.handleError(c, err, http.StatusBadRequest) { - return - } - if sub.SentryEnabled && sub.SentryDSN == "" { - ctx.handleError(c, fmt.Errorf("you have to set `Sentry DSN` when sentry notifications is enabled"), http.StatusBadRequest) - return - } - - userID := CurrentUserID(c) - if userID == 0 { - c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user"}) - return - } - - subscription := database.Subscription{ - UserID: userID, - Address: sub.Address, - Network: types.NewNetwork(sub.Network), - Alias: sub.Alias, - WatchMask: sub.getMask(), - SentryDSN: sub.SentryDSN, - } - - if err := ctx.DB.UpsertSubscription(&subscription); ctx.handleError(c, err, 0) { - return - } - - c.JSON(http.StatusOK, subscription) -} - -// DeleteSubscription - -func (ctx *Context) DeleteSubscription(c *gin.Context) { - var sub subRequest - if err := c.ShouldBindJSON(&sub); ctx.handleError(c, err, http.StatusBadRequest) { - return - } - - userID := CurrentUserID(c) - if userID == 0 { - c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user"}) - return - } - - subscription := database.Subscription{ - UserID: userID, - Address: sub.Address, - Network: types.NewNetwork(sub.Network), - } - - if err := ctx.DB.DeleteSubscription(&subscription); ctx.handleError(c, err, 0) { - return - } - - c.JSON(http.StatusOK, gin.H{}) -} - -// PrepareSubscription - -func PrepareSubscription(sub database.Subscription) (res Subscription) { - res = newSubscriptionWithMask(sub.WatchMask) - res.Address = sub.Address - res.Network = sub.Network.String() - res.Alias = sub.Alias - res.SubscribedAt = sub.CreatedAt - res.SentryDSN = sub.SentryDSN - return -} - -// PrepareSubscriptions - -func PrepareSubscriptions(subs []database.Subscription) []Subscription { - res := make([]Subscription, len(subs)) - - for i, sub := range subs { - res[i] = PrepareSubscription(sub) - } - - return res -} diff --git a/cmd/api/handlers/user.go b/cmd/api/handlers/user.go deleted file mode 100644 index 061067004..000000000 --- a/cmd/api/handlers/user.go +++ /dev/null @@ -1,88 +0,0 @@ -package handlers - -import ( - "net/http" - "time" - - "github.com/gin-gonic/gin" -) - -// GetUserProfile - -func (ctx *Context) GetUserProfile(c *gin.Context) { - userID := CurrentUserID(c) - if userID == 0 { - c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user"}) - return - } - - user, err := ctx.DB.GetUser(userID) - if ctx.handleError(c, err, 0) { - return - } - - subscriptions, err := ctx.DB.ListSubscriptions(userID) - if ctx.handleError(c, err, 0) { - return - } - - count, err := ctx.DB.GetUserCompletedAssesments(user.ID) - if ctx.handleError(c, err, 0) { - return - } - - compilationTasks, err := ctx.DB.CountCompilationTasks(user.ID) - if ctx.handleError(c, err, 0) { - return - } - - verifications, err := ctx.DB.CountVerifications(user.ID) - if ctx.handleError(c, err, 0) { - return - } - - deployments, err := ctx.DB.CountDeployments(user.ID) - if ctx.handleError(c, err, 0) { - return - } - - profile := userProfile{ - Login: user.Login, - AvatarURL: user.AvatarURL, - MarkReadAt: user.MarkReadAt, - RegisteredAt: user.CreatedAt, - MarkedContracts: count, - CompilationTasks: compilationTasks, - Verifications: verifications, - Deployments: deployments, - - Subscriptions: PrepareSubscriptions(subscriptions), - } - - c.JSON(http.StatusOK, profile) -} - -// UserMarkAllRead - -func (ctx *Context) UserMarkAllRead(c *gin.Context) { - userID := CurrentUserID(c) - if userID == 0 { - c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user"}) - return - } - - var req markReadRequest - if err := c.ShouldBindJSON(&req); ctx.handleError(c, err, http.StatusBadRequest) { - return - } - - if req.Timestamp > time.Now().Unix() { - c.JSON(http.StatusBadRequest, gin.H{"error": "timestamp can't be in the future"}) - return - } - - err := ctx.DB.UpdateUserMarkReadAt(userID, req.Timestamp) - if ctx.handleError(c, err, 0) { - return - } - - c.JSON(http.StatusOK, gin.H{}) -} diff --git a/cmd/api/handlers/vote.go b/cmd/api/handlers/vote.go deleted file mode 100644 index d8b14cce4..000000000 --- a/cmd/api/handlers/vote.go +++ /dev/null @@ -1,88 +0,0 @@ -package handlers - -import ( - "net/http" - - "github.com/baking-bad/bcdhub/internal/database" - "github.com/baking-bad/bcdhub/internal/models/contract" - "github.com/gin-gonic/gin" - "github.com/jinzhu/gorm" -) - -// Vote - -func (ctx *Context) Vote(c *gin.Context) { - var req voteRequest - if err := c.BindJSON(&req); ctx.handleError(c, err, http.StatusBadRequest) { - _ = c.AbortWithError(http.StatusBadRequest, err) - return - } - - a := contract.NewEmptyContract(req.SourceNetwork, req.SourceAddress) - if err := ctx.Storage.GetByID(&a); ctx.handleError(c, err, 0) { - return - } - - b := contract.NewEmptyContract(req.DestinationNetwork, req.DestinationAddress) - if err := ctx.Storage.GetByID(&b); ctx.handleError(c, err, 0) { - return - } - - assessment := database.Assessments{ - Address1: a.Address, - Network1: a.Network, - Address2: b.Address, - Network2: b.Network, - UserID: CurrentUserID(c), - Assessment: req.Vote, - } - if err := ctx.DB.CreateOrUpdateAssessment(&assessment); ctx.handleError(c, err, 0) { - return - } - c.JSON(http.StatusOK, "") -} - -// GetTasks - -func (ctx *Context) GetTasks(c *gin.Context) { - var req pageableRequest - if err := c.BindQuery(&req); ctx.handleError(c, err, http.StatusBadRequest) { - return - } - userID := CurrentUserID(c) - - assesments, err := ctx.DB.GetAssessmentsWithValue(userID, database.AssessmentUndefined, uint(req.Size)) - if err != nil { - if !gorm.IsRecordNotFoundError(err) && ctx.handleError(c, err, 0) { - return - } - assesments = make([]database.Assessments, 0) - } - - c.JSON(http.StatusOK, assesments) -} - -// GenerateTasks - -func (ctx *Context) GenerateTasks(c *gin.Context) { - userID := CurrentUserID(c) - tasks, err := ctx.Contracts.GetDiffTasks() - if ctx.handleError(c, err, 0) { - return - } - assesments := make([]database.Assessments, 0) - for i := 0; i < len(tasks) && len(assesments) < 10; i++ { - a := database.Assessments{ - Address1: tasks[i].Address1, - Network1: tasks[i].Network1, - Address2: tasks[i].Address2, - Network2: tasks[i].Network2, - UserID: userID, - Assessment: database.AssessmentUndefined, - } - if err := ctx.DB.CreateAssessment(&a); ctx.handleError(c, err, 0) { - return - } - if a.Assessment == database.AssessmentUndefined { - assesments = append(assesments, a) - } - } - c.JSON(http.StatusOK, assesments) -} diff --git a/cmd/api/main.go b/cmd/api/main.go index 0b932c997..f792213b6 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -7,7 +7,6 @@ import ( "github.com/baking-bad/bcdhub/cmd/api/docs" "github.com/baking-bad/bcdhub/cmd/api/handlers" - "github.com/baking-bad/bcdhub/cmd/api/seed" "github.com/baking-bad/bcdhub/cmd/api/validations" "github.com/baking-bad/bcdhub/internal/config" "github.com/baking-bad/bcdhub/internal/helpers" @@ -46,12 +45,6 @@ func newApp() *app { return nil } - if cfg.API.SeedEnabled { - if err := seed.Run(ctx, cfg.API.Seed); err != nil { - logger.Fatal(err) - } - } - api := &app{ Context: ctx, } @@ -132,7 +125,6 @@ func (api *app) makeRouter() { } contract := v1.Group("contract/:network/:address") - contract.Use(api.Context.IsAuthenticated()) { contract.GET("", api.Context.GetContract) contract.GET("code", api.Context.GetContractCode) @@ -211,39 +203,6 @@ func (api *app) makeRouter() { metadata.DELETE("delete", api.Context.DeleteMetadata) } - oauth := v1.Group("oauth/:provider") - { - oauth.GET("login", api.Context.OauthLogin) - oauth.GET("callback", api.Context.OauthCallback) - } - - authorized := v1.Group("/") - authorized.Use(api.Context.AuthJWTRequired()) - { - profile := authorized.Group("profile") - { - profile.GET("", api.Context.GetUserProfile) - profile.POST("/mark_all_read", api.Context.UserMarkAllRead) - subscriptions := profile.Group("subscriptions") - { - subscriptions.GET("", api.Context.ListSubscriptions) - subscriptions.POST("", api.Context.CreateSubscription) - subscriptions.DELETE("", api.Context.DeleteSubscription) - subscriptions.GET("events", api.Context.GetEvents) - subscriptions.GET("mempool", api.Context.GetMempoolEvents) - } - vote := profile.Group("vote") - { - vote.POST("", api.Context.Vote) - vote.GET("tasks", api.Context.GetTasks) - vote.GET("generate", api.Context.GenerateTasks) - } - profile.GET("accounts", api.Context.ListPublicAccounts) - profile.GET("repos", api.Context.ListPublicRepos) - profile.GET("refs", api.Context.ListPublicRefs) - } - } - dapps := v1.Group("dapps") { dapps.GET("", api.Context.GetDAppList) diff --git a/cmd/api/oauth/oauth.go b/cmd/api/oauth/oauth.go deleted file mode 100644 index 79c25b643..000000000 --- a/cmd/api/oauth/oauth.go +++ /dev/null @@ -1,74 +0,0 @@ -package oauth - -import ( - "fmt" - "time" - - "github.com/baking-bad/bcdhub/internal/config" - "github.com/baking-bad/bcdhub/internal/providers" - "github.com/dgrijalva/jwt-go" - "github.com/pkg/errors" -) - -// Config - -type Config struct { - Providers map[string]providers.Oauth - JWTKey []byte - State string - UserID uint - JWTRedirectURL string -} - -// New - -func New(cfg config.Config) (Config, error) { - return Config{ - Providers: providers.InitOauth(cfg), - JWTKey: []byte(cfg.OAuth.JWT.Secret), - State: cfg.OAuth.State, - JWTRedirectURL: cfg.OAuth.JWT.RedirectURL, - }, nil -} - -type jwtClaims struct { - UserID uint `json:"userID"` - jwt.StandardClaims -} - -// MakeJWT - -func (c Config) MakeJWT(userID uint) (string, error) { - expirationTime := time.Now().Add(48 * time.Hour) - - claims := &jwtClaims{ - UserID: userID, - StandardClaims: jwt.StandardClaims{ - ExpiresAt: expirationTime.Unix(), - }, - } - - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - - return token.SignedString(c.JWTKey) -} - -// GetIDFromToken - -func (c Config) GetIDFromToken(token string) (uint, error) { - claims := &jwtClaims{} - - tkn, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) { - return c.JWTKey, nil - }) - - if err != nil { - return 0, errors.Errorf("failed to parse token %v", token) - } - - if !tkn.Valid { - return 0, errors.Errorf("invalid token %v", token) - } - - if time.Now().Unix() > claims.StandardClaims.ExpiresAt { - return 0, fmt.Errorf("token expired") - } - - return claims.UserID, nil -} diff --git a/cmd/api/seed/seed.go b/cmd/api/seed/seed.go deleted file mode 100644 index b847ebfb5..000000000 --- a/cmd/api/seed/seed.go +++ /dev/null @@ -1,71 +0,0 @@ -package seed - -import ( - "github.com/baking-bad/bcdhub/cmd/api/handlers" - "github.com/baking-bad/bcdhub/internal/config" - "github.com/baking-bad/bcdhub/internal/database" - "github.com/baking-bad/bcdhub/internal/models" - "github.com/baking-bad/bcdhub/internal/models/types" - "github.com/baking-bad/bcdhub/internal/models/tzip" -) - -// Run - -func Run(ctx *handlers.Context, seed config.SeedConfig) error { - // 1. seed user - user := database.User{ - Login: seed.User.Login, - Name: seed.User.Name, - AvatarURL: seed.User.AvatarURL, - } - - if err := ctx.DB.GetOrCreateUser(&user, ""); err != nil { - return err - } - - ctx.OAUTH.UserID = user.ID - - // 2. seed subscriptions - for _, sub := range seed.Subscriptions { - subscription := database.Subscription{ - UserID: user.ID, - Address: sub.Address, - Network: types.NewNetwork(sub.Network), - Alias: sub.Alias, - WatchMask: sub.WatchMask, - } - - if err := ctx.DB.UpsertSubscription(&subscription); err != nil { - return err - } - } - - // 3. seed aliases - aliasModels := make([]models.Model, 0) - for _, a := range seed.Aliases { - aliasModels = append(aliasModels, &tzip.TZIP{ - TZIP16: tzip.TZIP16{ - Name: a.Alias, - }, - Network: types.NewNetwork(a.Network), - Address: a.Address, - }) - } - if err := ctx.Storage.Save(aliasModels); err != nil { - return err - } - - // 4. seed accounts - for _, a := range seed.Accounts { - account := database.Account{ - UserID: user.ID, - PrivateKey: a.PrivateKey, - PublicKeyHash: a.PublicKeyHash, - Network: types.NewNetwork(a.Network), - } - - if err := ctx.DB.GetOrCreateAccount(&account); err != nil { - return err - } - } - return nil -} diff --git a/cmd/metrics/bigmapdiff.go b/cmd/metrics/bigmapdiff.go index 8aa8600ca..cc753cc82 100644 --- a/cmd/metrics/bigmapdiff.go +++ b/cmd/metrics/bigmapdiff.go @@ -55,7 +55,7 @@ func initHandlers() { } func parseBigMapDiff(bmd bigmapdiff.BigMapDiff) ([]models.Model, error) { - h := metrics.New(ctx.Contracts, ctx.BigMapDiffs, ctx.Blocks, ctx.Protocols, ctx.Operations, ctx.TokenBalances, ctx.TokenMetadata, ctx.TZIP, ctx.Migrations, ctx.Storage, ctx.DB) + h := metrics.New(ctx.Contracts, ctx.BigMapDiffs, ctx.Blocks, ctx.Protocols, ctx.Operations, ctx.TokenBalances, ctx.TokenMetadata, ctx.TZIP, ctx.Migrations, ctx.Storage) if err := h.SetBigMapDiffsStrings(&bmd); err != nil { return nil, err diff --git a/cmd/metrics/contract.go b/cmd/metrics/contract.go index 19b915cbd..0bf9193a7 100644 --- a/cmd/metrics/contract.go +++ b/cmd/metrics/contract.go @@ -36,7 +36,7 @@ func getContract(ids []int64) error { } func parseContract(contract *contract.Contract, chunk []contract.Contract) ([]models.Model, error) { - h := metrics.New(ctx.Contracts, ctx.BigMapDiffs, ctx.Blocks, ctx.Protocols, ctx.Operations, ctx.TokenBalances, ctx.TokenMetadata, ctx.TZIP, ctx.Migrations, ctx.Storage, ctx.DB) + h := metrics.New(ctx.Contracts, ctx.BigMapDiffs, ctx.Blocks, ctx.Protocols, ctx.Operations, ctx.TokenBalances, ctx.TokenMetadata, ctx.TZIP, ctx.Migrations, ctx.Storage) if contract.ProjectID == "" { if err := h.SetContractProjectID(contract, chunk); err != nil { diff --git a/cmd/metrics/main.go b/cmd/metrics/main.go index 626483c89..b82fe3235 100644 --- a/cmd/metrics/main.go +++ b/cmd/metrics/main.go @@ -92,7 +92,6 @@ func main() { configCtx := config.NewContext( config.WithStorage(cfg.Storage, cfg.Metrics.ProjectName, 0), config.WithRPC(cfg.RPC), - config.WithDatabase(cfg.DB), config.WithRabbit(cfg.RabbitMQ, cfg.Metrics.ProjectName, cfg.Metrics.MQ), config.WithSearch(cfg.Storage), config.WithShare(cfg.SharePath), diff --git a/cmd/metrics/operations.go b/cmd/metrics/operations.go index 417f81467..d26d4872f 100644 --- a/cmd/metrics/operations.go +++ b/cmd/metrics/operations.go @@ -1,7 +1,6 @@ package main import ( - "github.com/baking-bad/bcdhub/internal/bcd" "github.com/baking-bad/bcdhub/internal/metrics" "github.com/baking-bad/bcdhub/internal/models" "github.com/baking-bad/bcdhub/internal/models/operation" @@ -18,10 +17,7 @@ func getOperation(ids []int64) error { updated := make([]models.Model, 0) for i := range operations { - if err := parseOperation(operations[i]); err != nil { - return errors.Errorf("[getOperation] Compute error message: %s", err) - } - + parseOperation(operations[i]) updated = append(updated, &operations[i]) } logger.Info("%d operations are processed", len(operations)) @@ -33,15 +29,7 @@ func getOperation(ids []int64) error { return ctx.Storage.Save(updated) } -func parseOperation(operation operation.Operation) error { - h := metrics.New(ctx.Contracts, ctx.BigMapDiffs, ctx.Blocks, ctx.Protocols, ctx.Operations, ctx.TokenBalances, ctx.TokenMetadata, ctx.TZIP, ctx.Migrations, ctx.Storage, ctx.DB) - +func parseOperation(operation operation.Operation) { + h := metrics.New(ctx.Contracts, ctx.BigMapDiffs, ctx.Blocks, ctx.Protocols, ctx.Operations, ctx.TokenBalances, ctx.TokenMetadata, ctx.TZIP, ctx.Migrations, ctx.Storage) h.SetOperationStrings(&operation) - - if bcd.IsContract(operation.Destination) || operation.IsOrigination() { - if err := h.SendSentryNotifications(operation); err != nil { - return err - } - } - return nil } diff --git a/configs/development.yml b/configs/development.yml index c9ea5c564..7b139b246 100644 --- a/configs/development.yml +++ b/configs/development.yml @@ -39,24 +39,6 @@ rabbitmq: uri: "amqp://${RABBITMQ_DEFAULT_USER}:${RABBITMQ_DEFAULT_PASS}@127.0.0.1:5672/" timeout: 10 -db: - conn_string: "host=${DB_HOSTNAME:-127.0.0.1} port=5432 user=${POSTGRES_USER} dbname=${POSTGRES_DB} password=${POSTGRES_PASSWORD} sslmode=disable" - timeout: 10 - -oauth: - state: ${OAUTH_STATE_STRING} - jwt: - secret: ${JWT_SECRET_KEY} - redirect_url: http://localhost:8080/welcome - github: - client_id: ${GITHUB_CLIENT_ID} - secret: ${GITHUB_CLIENT_SECRET} - callback_url: http://localhost:14000/v1/oauth/github/callback - gitlab: - client_id: ${GITLAB_CLIENT_ID} - secret: ${GITLAB_CLIENT_SECRET} - callback_url: http://localhost:14000/v1/oauth/gitlab/callback - sentry: environment: development uri: ${SENTRY_DSN} @@ -80,7 +62,6 @@ api: bind: "127.0.0.1:14000" swagger_host: "localhost:14000" cors_enabled: true - oauth_enabled: true sentry_enabled: false seed_enabled: false page_size: ${PAGE_SIZE:-10} diff --git a/configs/production.yml b/configs/production.yml index cd41d13d9..2b663be20 100644 --- a/configs/production.yml +++ b/configs/production.yml @@ -32,24 +32,6 @@ storage: - http://${ELASTIC_HOSTNAME:-elastic}:9200 timeout: 10 -db: - conn_string: "host=${DB_HOSTNAME:-db} port=5432 user=${POSTGRES_USER} dbname=${POSTGRES_DB} password=${POSTGRES_PASSWORD} sslmode=disable" - timeout: 10 - -oauth: - state: ${OAUTH_STATE_STRING} - jwt: - secret: ${JWT_SECRET_KEY} - redirect_url: https://better-call.dev/welcome - github: - client_id: ${GITHUB_CLIENT_ID} - secret: ${GITHUB_CLIENT_SECRET} - callback_url: https://api.better-call.dev/v1/oauth/github/callback - gitlab: - client_id: ${GITLAB_CLIENT_ID} - secret: ${GITLAB_CLIENT_SECRET} - callback_url: https://api.better-call.dev/v1/oauth/gitlab/callback - sentry: environment: production uri: ${SENTRY_DSN} @@ -74,7 +56,6 @@ api: bind: ":14000" swagger_host: "api.better-call.dev" cors_enabled: false - oauth_enabled: true sentry_enabled: true seed_enabled: false page_size: ${PAGE_SIZE:-10} diff --git a/configs/sandbox.yml b/configs/sandbox.yml index d594328e0..bebe54b95 100644 --- a/configs/sandbox.yml +++ b/configs/sandbox.yml @@ -9,10 +9,6 @@ storage: - http://${ELASTIC_HOSTNAME:-elastic}:9200 timeout: 10 -db: - conn_string: "host=${DB_HOSTNAME:-db} port=5432 user=${POSTGRES_USER} dbname=${POSTGRES_DB} password=${POSTGRES_PASSWORD} sslmode=disable" - timeout: 10 - rabbitmq: uri: "amqp://${RABBITMQ_DEFAULT_USER}:${RABBITMQ_DEFAULT_PASS}@${RABBITMQ_HOSTNAME:-mq}:5672/" timeout: 10 @@ -29,7 +25,6 @@ api: bind: ":14000" swagger_host: "localhost:8000" cors_enabled: true - oauth_enabled: false sentry_enabled: false seed_enabled: true page_size: ${PAGE_SIZE:-10} diff --git a/configs/you.yml b/configs/you.yml index e9c953760..52c63ee9c 100644 --- a/configs/you.yml +++ b/configs/you.yml @@ -15,28 +15,10 @@ storage: - http://${ELASTIC_HOSTNAME:-elastic}:9200 timeout: 10 -db: - conn_string: "host=${DB_HOSTNAME:-db} port=5432 user=${POSTGRES_USER} dbname=${POSTGRES_DB} password=${POSTGRES_PASSWORD} sslmode=disable" - timeout: 10 - rabbitmq: uri: "amqp://${RABBITMQ_DEFAULT_USER}:${RABBITMQ_DEFAULT_PASS}@${RABBITMQ_HOSTNAME:-mq}:5672/" timeout: 10 -oauth: - state: ${OAUTH_STATE_STRING} - jwt: - secret: ${JWT_SECRET_KEY} - redirect_url: https://you.better-call.dev/welcome - github: - client_id: ${GITHUB_CLIENT_ID} - secret: ${GITHUB_CLIENT_SECRET} - callback_url: https://you.better-call.dev/v1/oauth/github/callback - gitlab: - client_id: ${GITLAB_CLIENT_ID} - secret: ${GITLAB_CLIENT_SECRET} - callback_url: https://you.better-call.dev/v1/oauth/gitlab/callback - sentry: environment: staging uri: ${SENTRY_DSN} @@ -61,7 +43,6 @@ api: bind: ":14000" swagger_host: "you.better-call.dev" cors_enabled: false - oauth_enabled: true sentry_enabled: true seed_enabled: false page_size: ${PAGE_SIZE:-10} diff --git a/docs/configuration.md b/docs/configuration.md index cca4afffd..f531c9bb6 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -98,7 +98,6 @@ api: bind: ":14000" swagger_host: "api.better-call.dev" cors_enabled: false - oauth_enabled: true sentry_enabled: true seed_enabled: false networks: diff --git a/go.mod b/go.mod index 8eebd9d07..0f425ad8c 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,6 @@ require ( github.com/aws/aws-sdk-go v1.36.1 github.com/btcsuite/btcutil v1.0.1 github.com/cenkalti/backoff v2.2.1+incompatible - github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/dosco/graphjin v0.16.16 github.com/ebellocchia/go-base58 v0.1.0 github.com/elastic/go-elasticsearch/v8 v8.0.0-20191218082911-5398a82b748f @@ -19,13 +18,10 @@ require ( github.com/go-openapi/spec v0.20.0 // indirect github.com/go-playground/validator/v10 v10.4.1 github.com/golang/mock v1.4.4 - github.com/google/go-github v17.0.0+incompatible github.com/google/uuid v1.1.2 - github.com/hashicorp/go-retryablehttp v0.6.6 // indirect github.com/iancoleman/strcase v0.1.3 github.com/jackc/pgx/v4 v4.10.1 github.com/jessevdk/go-flags v1.4.0 - github.com/jinzhu/gorm v1.9.11 github.com/json-iterator/go v1.1.10 github.com/karlseguin/ccache v2.0.3+incompatible github.com/karlseguin/expect v1.0.2-0.20190806010014-778a5f0c6003 // indirect @@ -43,12 +39,10 @@ require ( github.com/tidwall/gjson v1.4.0 github.com/valyala/fastjson v1.5.1 github.com/wsxiaoys/terminal v0.0.0-20160513160801-0940f3fc43a0 // indirect - github.com/xanzy/go-gitlab v0.44.0 github.com/xeipuuv/gojsonschema v1.2.0 github.com/yhirose/go-peg v0.0.0-20190710015414-7eb2cf046928 golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 golang.org/x/net v0.0.0-20201224014010-6772e930b67b // indirect - golang.org/x/oauth2 v0.0.0-20201203001011-0b49973bad19 golang.org/x/sys v0.0.0-20210305034016-7844c3c200c3 // indirect gopkg.in/yaml.v2 v2.4.0 gorm.io/driver/postgres v1.0.8 diff --git a/go.sum b/go.sum index 9c5b55dbc..080d8b792 100644 --- a/go.sum +++ b/go.sum @@ -3,8 +3,6 @@ bazil.org/fuse v0.0.0-20180421153158-65cc252bf669/go.mod h1:Xbm+BRKSBEpa4q4hTSxo cloud.google.com/go v0.0.0-20170206221025-ce650573d812/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.37.4 h1:glPeL3BQJsbF6aIIYfZizMwc5LTYz250bDMjttbBGAU= -cloud.google.com/go v0.37.4/go.mod h1:NHPJ89PdicEuT9hdPXMROBD91xc5uRDxsMtSB16k7hw= cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= cloud.google.com/go v0.39.0/go.mod h1:rVLT6fkc8chs9sfPtFc1SBH6em7n+ZoXaG+87tDISts= cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= @@ -260,8 +258,6 @@ github.com/decred/dcrd/chaincfg/chainhash v1.0.2/go.mod h1:BpbrGgrPTr3YJYRN3Bm+D github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= github.com/decred/dcrd/dcrec/secp256k1/v3 v3.0.0/go.mod h1:J70FGZSbzsjecRTiTzER+3f1KZLNaXkuv+yeFTKoxM8= github.com/denis-tingajkin/go-header v0.4.2/go.mod h1:eLRHAVXzE5atsKAnNRDB90WHCFFnBUn4RN0nRcs1LJA= -github.com/denisenkom/go-mssqldb v0.0.0-20190515213511-eb9f6a1743f3 h1:tkum0XDgfR0jcVVXuTsYv/erY2NnEDqwRojbxR1rBYA= -github.com/denisenkom/go-mssqldb v0.0.0-20190515213511-eb9f6a1743f3/go.mod h1:zAg7JM8CkOJ43xKXIj7eRO9kmWm/TW578qo+oDO6tuM= github.com/denisenkom/go-mssqldb v0.0.0-20200428022330-06a60b6afbbc/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= github.com/denisenkom/go-mssqldb v0.9.0 h1:RSohk2RsiZqLZ0zCjtfn3S4Gp4exhpBWHyQ7D0yGjAk= github.com/denisenkom/go-mssqldb v0.9.0/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= @@ -308,8 +304,6 @@ github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.m github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y= -github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0= github.com/esimonov/ifshort v1.0.0/go.mod h1:yZqNJUrNn20K8Q9n2CrjTKYyVEmX209Hgu+M1LBpeZE= github.com/esimonov/ifshort v1.0.1/go.mod h1:yZqNJUrNn20K8Q9n2CrjTKYyVEmX209Hgu+M1LBpeZE= github.com/etcd-io/bbolt v1.3.3/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw= @@ -546,8 +540,6 @@ github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4 h1:L8R9j+yAqZuZjsqh/z+F1NCffTKKLShY6zXTItVIZ8M= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-github v17.0.0+incompatible h1:N0LgJ1j65A7kfXrZnUDaYCs/Sf4rEjNlfyDHW9dolSY= -github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= github.com/google/go-github/v28 v28.1.1/go.mod h1:bsqJWQX05omyWVmc00nEUql9mhQyv38lDZ8kPZcQVoM= github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= @@ -628,8 +620,6 @@ github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iP github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-retryablehttp v0.6.4 h1:BbgctKO892xEyOXnGiaAwIoSq1QZ/SS4AhjoAh9DnfY= github.com/hashicorp/go-retryablehttp v0.6.4/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= -github.com/hashicorp/go-retryablehttp v0.6.6 h1:HJunrbHTDDbBb/ay4kxa1n+dLmttUlnP3V9oNE4hmsM= -github.com/hashicorp/go-retryablehttp v0.6.6/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= @@ -734,12 +724,8 @@ github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJS github.com/jgautheron/goconst v0.0.0-20201117150253-ccae5bf973f3/go.mod h1:aAosetZ5zaeC/2EfMeRswtxUFBpe2Hr7HzkgX4fanO4= github.com/jingyugao/rowserrcheck v0.0.0-20191204022205-72ab7603b68a/go.mod h1:xRskid8CManxVta/ALEhJha/pweKBaVG6fWgc0yH25s= github.com/jingyugao/rowserrcheck v0.0.0-20210130005344-c6a0c12dd98d/go.mod h1:/EZlaYCnEX24i7qdVhT9du5JrtFWYRQr67bVgR7JJC8= -github.com/jinzhu/gorm v1.9.11 h1:gaHGvE+UnWGlbWG4Y3FUwY1EcZ5n6S9WtqBA/uySMLE= -github.com/jinzhu/gorm v1.9.11/go.mod h1:bu/pK8szGZ2puuErfU0RwyeNdsf3e6nCX/noXaVxkfw= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= -github.com/jinzhu/now v1.0.1 h1:HjfetcXq097iXP0uoPCdnM4Efp5/9MsM0/M+XOTeR3M= -github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jinzhu/now v1.1.1 h1:g39TucaRWyV3dwDO++eEc6qf8TVIQ/Da48WmqjZ3i7E= github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jirfag/go-printf-func-name v0.0.0-20191110105641-45db9963cdd3/go.mod h1:HEWGJkRDzjJY2sqdDwxccsGicWEf9BQOZsq2tV+xzM0= @@ -839,8 +825,6 @@ github.com/lestrrat-go/option v1.0.0/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmt github.com/lestrrat-go/pdebug/v3 v3.0.1/go.mod h1:za+m+Ve24yCxTEhR59N7UlnJomWwCiIqbJRmKeiADU4= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.1.1 h1:sJZmqHoEaY7f+NPP8pgLB/WxulyR3fewgCM2qaSlBb4= -github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.3.0 h1:/qkRGz8zljWiDcFvgpwUpwIAPu3r07TDvs3Rws+o/pU= github.com/lib/pq v1.3.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= @@ -889,8 +873,6 @@ github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzp github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-shellwords v1.0.10/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y= github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= -github.com/mattn/go-sqlite3 v1.11.0 h1:LDdKkqtYlom37fkvqs8rMPFKAMe8+SgjbwZ6ex1/A/Q= -github.com/mattn/go-sqlite3 v1.11.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/go-sqlite3 v1.14.5 h1:1IdxlwTNazvbKJQSxoJ5/9ECbEeaTTyeU7sEAZ5KKTQ= github.com/mattn/go-sqlite3 v1.14.5/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI= github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= @@ -1698,7 +1680,6 @@ google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6 google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190404172233-64821d5d2107/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= diff --git a/internal/config/config.go b/internal/config/config.go index 6a13d9a74..5d38f9ed1 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -24,8 +24,6 @@ type Config struct { TzKT map[string]TzKTConfig `yaml:"tzkt"` Storage StorageConfig `yaml:"storage"` RabbitMQ RabbitConfig `yaml:"rabbitmq"` - DB DatabaseConfig `yaml:"db"` - OAuth OAuthConfig `yaml:"oauth"` Sentry SentryConfig `yaml:"sentry"` SharePath string `yaml:"share_path"` BaseURL string `yaml:"base_url"` @@ -161,7 +159,6 @@ type APIConfig struct { Bind string `yaml:"bind"` SwaggerHost string `yaml:"swagger_host"` CorsEnabled bool `yaml:"cors_enabled"` - OAuthEnabled bool `yaml:"oauth_enabled"` SentryEnabled bool `yaml:"sentry_enabled"` SeedEnabled bool `yaml:"seed_enabled"` Frontend FrontendConfig `yaml:"frontend"` diff --git a/internal/config/context.go b/internal/config/context.go index 7055f7cdd..cc0e0be6d 100644 --- a/internal/config/context.go +++ b/internal/config/context.go @@ -3,7 +3,6 @@ package config import ( "github.com/baking-bad/bcdhub/internal/aws" "github.com/baking-bad/bcdhub/internal/cache" - "github.com/baking-bad/bcdhub/internal/database" "github.com/baking-bad/bcdhub/internal/models" "github.com/baking-bad/bcdhub/internal/models/bigmapaction" "github.com/baking-bad/bcdhub/internal/models/bigmapdiff" @@ -31,7 +30,6 @@ import ( // Context - type Context struct { - DB database.DB MQ mq.Mediator AWS *aws.Client RPC map[types.Network]noderpc.INode @@ -100,9 +98,6 @@ func (ctx *Context) Close() { if ctx.MQ != nil { ctx.MQ.Close() } - if ctx.DB != nil { - ctx.DB.Close() - } if ctx.StorageDB != nil { ctx.StorageDB.Close() } diff --git a/internal/config/options.go b/internal/config/options.go index 4b077988c..206b12774 100644 --- a/internal/config/options.go +++ b/internal/config/options.go @@ -7,7 +7,6 @@ import ( "github.com/baking-bad/bcdhub/internal/aws" "github.com/baking-bad/bcdhub/internal/bcd/tezerrors" - "github.com/baking-bad/bcdhub/internal/database" "github.com/baking-bad/bcdhub/internal/elastic" "github.com/baking-bad/bcdhub/internal/models/types" "github.com/baking-bad/bcdhub/internal/postgres/bigmapdiff" @@ -81,13 +80,6 @@ func WithStorage(cfg StorageConfig, appName string, maxPageSize int64) ContextOp } } -// WithDatabase - -func WithDatabase(dbConfig DatabaseConfig) ContextOption { - return func(ctx *Context) { - ctx.DB = database.WaitNew(dbConfig.ConnString, dbConfig.Timeout) - } -} - // WithSearch - func WithSearch(cfg StorageConfig) ContextOption { return func(ctx *Context) { diff --git a/internal/database/account.go b/internal/database/account.go deleted file mode 100644 index 75694a2bf..000000000 --- a/internal/database/account.go +++ /dev/null @@ -1,20 +0,0 @@ -package database - -import ( - "github.com/baking-bad/bcdhub/internal/models/types" - "github.com/jinzhu/gorm" -) - -// Account model -type Account struct { - gorm.Model - UserID uint `gorm:"primary_key;not null"` - PrivateKey string `gorm:"primary_key;not null"` - PublicKeyHash string - Network types.Network -} - -// GetOrCreateAccount - -func (d *db) GetOrCreateAccount(a *Account) error { - return d.Where("user_id = ? AND private_key = ?", a.UserID, a.PrivateKey).FirstOrCreate(a).Error -} diff --git a/internal/database/assessment.go b/internal/database/assessment.go deleted file mode 100644 index eed2d85fb..000000000 --- a/internal/database/assessment.go +++ /dev/null @@ -1,64 +0,0 @@ -package database - -import ( - "github.com/baking-bad/bcdhub/internal/models/types" - "github.com/jinzhu/gorm" -) - -// Assessments - -type Assessments struct { - Address1 string `gorm:"primary_key;not null" json:"address_1"` - Network1 types.Network `gorm:"primary_key;not null" json:"network_1"` - Address2 string `gorm:"primary_key;not null" json:"address_2"` - Network2 types.Network `gorm:"primary_key;not null" json:"network_2"` - UserID uint `gorm:"primary_key;not_null;auto_increment:false" json:"-"` - Assessment uint `gorm:"not null" json:"-"` -} - -// Assessment field values -const ( - AssessmentUndefined = uint(10) - AssessmentSimilar = uint(1) - AssessmentNotSimilar = uint(2) -) - -// CreateAssessment - -func (d *db) CreateAssessment(a *Assessments) error { - return d. - Attrs(Assessments{Assessment: a.Assessment}). - FirstOrCreate(a).Error -} - -// CreateOrUpdateAssessment - -func (d *db) CreateOrUpdateAssessment(a *Assessments) error { - return d. - Assign(Assessments{Assessment: a.Assessment}). - FirstOrCreate(a).Error -} - -// GetAssessmentsWithValue - -func (d *db) GetAssessmentsWithValue(userID, assessment, size uint) (result []Assessments, err error) { - a := &Assessments{ - UserID: userID, - } - if assessment == AssessmentUndefined || assessment == AssessmentSimilar || assessment == AssessmentNotSimilar { - a.Assessment = assessment - } - query := d. - Where(a). - Order(gorm.Expr("random()")) - - if size > 0 { - query = query.Limit(size) - } - err = query.Find(&result).Error - return -} - -// GetUserCompletedAssesments - -func (d *db) GetUserCompletedAssesments(userID uint) (count int, err error) { - err = d.Model(&Assessments{}). - Where("user_id = ? AND (assessment = ? OR assessment = ?)", userID, AssessmentSimilar, AssessmentNotSimilar). - Count(&count).Error - return -} diff --git a/internal/database/compilation_task.go b/internal/database/compilation_task.go deleted file mode 100644 index 6c6589d1f..000000000 --- a/internal/database/compilation_task.go +++ /dev/null @@ -1,97 +0,0 @@ -package database - -import ( - "time" - - "github.com/baking-bad/bcdhub/internal/models/types" - "github.com/jinzhu/gorm/dialects/postgres" -) - -// CompilationTask model -// kind: verification or deployment -type CompilationTask struct { - ID uint `gorm:"primary_key" json:"id"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - DeletedAt *time.Time `sql:"index" json:"-"` - UserID uint `json:"user_id"` - Address string `json:"address"` - Network types.Network `json:"network"` - Account string `json:"account"` - Repo string `json:"repo"` - Ref string `json:"ref"` - Kind string `gorm:"not null" json:"kind"` - Status string `gorm:"not null" json:"status"` - Results []CompilationTaskResult `json:"results,omitempty"` -} - -// CompilationTaskResult - -type CompilationTaskResult struct { - ID uint `gorm:"primary_key;not null" json:"id"` - CompilationTaskID uint `json:"-"` - Status string `json:"status"` - Language string `json:"language,omitempty"` - Path string `json:"path"` - AWSPath string `json:"aws_path"` - Script *postgres.Jsonb `json:"script,omitempty"` - Error string `json:"error,omitempty"` - Schema interface{} `gorm:"-" json:"schema,omitempty"` - Typedef interface{} `gorm:"-" json:"typedef,omitempty"` -} - -func (d *db) ListCompilationTasks(userID, limit, offset uint, kind string) ([]CompilationTask, error) { - var tasks []CompilationTask - - req := d.Preload("Results").Scopes(userIDScope(userID), pagination(limit, offset), createdAtDesc) - - if kind != "" { - req = req.Where("kind = ?", kind) - } - - if err := req.Find(&tasks).Error; err != nil { - return nil, err - } - - return tasks, nil -} - -func (d *db) GetCompilationTask(taskID uint) (*CompilationTask, error) { - var task CompilationTask - - if err := d.Preload("Results").Where("id = ?", taskID).First(&task).Error; err != nil { - return nil, err - } - - return &task, nil -} - -// GetCompilationTaskBy - -func (d *db) GetCompilationTaskBy(network types.Network, address, status string) (*CompilationTask, error) { - task := new(CompilationTask) - - return task, d.Preload("Results").Scopes(contract(address, network)).Where("status = ?", status).First(task).Error -} - -// CreateCompilationTask - -func (d *db) CreateCompilationTask(ct *CompilationTask) error { - return d.Create(ct).Error -} - -// UpdateTaskStatus - -func (d *db) UpdateTaskStatus(taskID uint, status string) error { - return d.Model(&CompilationTask{}).Where("id = ?", taskID).Update("status", status).Error -} - -// UpdateTaskResults - -func (d *db) UpdateTaskResults(task *CompilationTask, status string, results []CompilationTaskResult) error { - task.Status = status - task.Results = results - - return d.Save(task).Error -} - -// CountCompilationTasks - -func (d *db) CountCompilationTasks(userID uint) (int64, error) { - var count int64 - return count, d.Model(&CompilationTask{}).Scopes(userIDScope(userID)).Count(&count).Error -} diff --git a/internal/database/database.go b/internal/database/database.go deleted file mode 100644 index db1bd95de..000000000 --- a/internal/database/database.go +++ /dev/null @@ -1,133 +0,0 @@ -package database - -import ( - "time" - - "github.com/baking-bad/bcdhub/internal/logger" - "github.com/baking-bad/bcdhub/internal/models/types" - "github.com/jinzhu/gorm" - - // postgres driver - _ "github.com/jinzhu/gorm/dialects/postgres" -) - -// DB - -type DB interface { - IAccount - IAssessment - ICompilationTask - IDeployment - ISubscription - IUser - IVerification - - Close() -} - -// IAccount - -type IAccount interface { - GetOrCreateAccount(*Account) error -} - -// IAssessment - -type IAssessment interface { - CreateAssessment(a *Assessments) error - CreateOrUpdateAssessment(a *Assessments) error - GetAssessmentsWithValue(userID, assessment, size uint) ([]Assessments, error) - GetUserCompletedAssesments(userID uint) (count int, err error) -} - -// ICompilationTask - -type ICompilationTask interface { - ListCompilationTasks(userID, limit, offset uint, kind string) ([]CompilationTask, error) - GetCompilationTask(taskID uint) (*CompilationTask, error) - GetCompilationTaskBy(network types.Network, address, status string) (*CompilationTask, error) - CreateCompilationTask(ct *CompilationTask) error - UpdateTaskStatus(taskID uint, status string) error - UpdateTaskResults(task *CompilationTask, status string, results []CompilationTaskResult) error - CountCompilationTasks(userID uint) (int64, error) -} - -// IDeployment - -type IDeployment interface { - ListDeployments(userID, limit, offset uint) ([]Deployment, error) - CreateDeployment(dt *Deployment) error - GetDeploymentBy(opHash string) (*Deployment, error) - GetDeploymentsByAddressNetwork(address string, network types.Network) ([]Deployment, error) - UpdateDeployment(dt *Deployment) error - CountDeployments(userID uint) (int64, error) -} - -// ISubscription - -type ISubscription interface { - GetSubscription(userID uint, address string, network types.Network) (Subscription, error) - GetSubscriptions(address string, network types.Network) ([]Subscription, error) - ListSubscriptions(userID uint) ([]Subscription, error) - UpsertSubscription(s *Subscription) error - DeleteSubscription(s *Subscription) error - GetSubscriptionsCount(address string, network types.Network) (int, error) -} - -// IUser - -type IUser interface { - GetOrCreateUser(u *User, token string) error - GetUser(userID uint) (*User, error) - UpdateUserMarkReadAt(userID uint, ts int64) error -} - -// IVerification - -type IVerification interface { - ListVerifications(userID, limit, offset uint) ([]Verification, error) - CreateVerification(v *Verification) error - GetVerificationBy(address string, network types.Network) (*Verification, error) - CountVerifications(userID uint) (int64, error) -} - -type db struct { - *gorm.DB -} - -// New - creates db connection -func New(connectionString string) (DB, error) { - gormDB, err := gorm.Open("postgres", connectionString) - if err != nil { - return nil, err - } - - gormDB.LogMode(false) - - gormDB.AutoMigrate( - &User{}, - &Subscription{}, - &Assessments{}, - &Account{}, - &CompilationTask{}, - &CompilationTaskResult{}, - &Verification{}, - &Deployment{}, - ) - - gormDB = gormDB.Set("gorm:auto_preload", false) - - return &db{gormDB}, nil -} - -// WaitNew - waiting for db up and creating connection -func WaitNew(connectionString string, timeout int) DB { - var db DB - var err error - - for db == nil { - db, err = New(connectionString) - if err != nil { - logger.Warning("Waiting postgres up %d seconds...", timeout) - time.Sleep(time.Second * time.Duration(timeout)) - } - } - - return db -} - -func (d *db) Close() { - d.DB.Close() -} diff --git a/internal/database/deployment.go b/internal/database/deployment.go deleted file mode 100644 index 8e161ea0f..000000000 --- a/internal/database/deployment.go +++ /dev/null @@ -1,69 +0,0 @@ -package database - -import ( - "time" - - "github.com/baking-bad/bcdhub/internal/models/types" - "github.com/lib/pq" -) - -// Deployment - -type Deployment struct { - ID uint `gorm:"primary_key" json:"id"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - DeletedAt *time.Time `sql:"index" json:"-"` - UserID uint `json:"user_id"` - CompilationTaskID uint `json:"-"` - Address string `json:"address"` - Network types.Network `json:"network"` - OperationHash string `json:"operation_hash"` - Sources pq.StringArray `gorm:"type:varchar(128)[]" json:"sources"` -} - -// ListDeployments - -func (d *db) ListDeployments(userID, limit, offset uint) ([]Deployment, error) { - var deployments []Deployment - - req := d.Scopes( - userIDScope(userID), - pagination(limit, offset), - createdAtDesc, - ) - - return deployments, req.Find(&deployments).Error -} - -// CreateDeployment - -func (d *db) CreateDeployment(dt *Deployment) error { - return d.Create(dt).Error -} - -// GetDeploymentBy - -func (d *db) GetDeploymentBy(opHash string) (*Deployment, error) { - dt := new(Deployment) - return dt, d.Raw("SELECT * FROM deployments WHERE operation_hash = ?", opHash).Scan(dt).Error -} - -// GetDeploymentsByAddressNetwork - -func (d *db) GetDeploymentsByAddressNetwork(address string, network types.Network) ([]Deployment, error) { - var deployments []Deployment - - req := d.Scopes( - addressScope(address), - networkScope(network), - ) - - return deployments, req.Find(&deployments).Error -} - -// UpdateDeployment - -func (d *db) UpdateDeployment(dt *Deployment) error { - return d.Save(dt).Error -} - -// CountDeployments - -func (d *db) CountDeployments(userID uint) (int64, error) { - var count int64 - return count, d.Model(&Deployment{}).Scopes(userIDScope(userID)).Count(&count).Error -} diff --git a/internal/database/mock.go b/internal/database/mock.go deleted file mode 100644 index dfe8f74c4..000000000 --- a/internal/database/mock.go +++ /dev/null @@ -1,1080 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: go - -// Package mock_database is a generated GoMock package. -package database - -import ( - gomock "github.com/golang/mock/gomock" - reflect "reflect" -) - -// MockDB is a mock of DB interface -type MockDB struct { - ctrl *gomock.Controller - recorder *MockDBMockRecorder -} - -// MockDBMockRecorder is the mock recorder for MockDB -type MockDBMockRecorder struct { - mock *MockDB -} - -// NewMockDB creates a new mock instance -func NewMockDB(ctrl *gomock.Controller) *MockDB { - mock := &MockDB{ctrl: ctrl} - mock.recorder = &MockDBMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockDB) EXPECT() *MockDBMockRecorder { - return m.recorder -} - -// GetOrCreateAccount mocks base method -func (m *MockDB) GetOrCreateAccount(arg0 *Account) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetOrCreateAccount", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// GetOrCreateAccount indicates an expected call of GetOrCreateAccount -func (mr *MockDBMockRecorder) GetOrCreateAccount(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOrCreateAccount", reflect.TypeOf((*MockDB)(nil).GetOrCreateAccount), arg0) -} - -// CreateAssessment mocks base method -func (m *MockDB) CreateAssessment(a *Assessments) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateAssessment", a) - ret0, _ := ret[0].(error) - return ret0 -} - -// CreateAssessment indicates an expected call of CreateAssessment -func (mr *MockDBMockRecorder) CreateAssessment(a interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateAssessment", reflect.TypeOf((*MockDB)(nil).CreateAssessment), a) -} - -// CreateOrUpdateAssessment mocks base method -func (m *MockDB) CreateOrUpdateAssessment(a *Assessments) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrUpdateAssessment", a) - ret0, _ := ret[0].(error) - return ret0 -} - -// CreateOrUpdateAssessment indicates an expected call of CreateOrUpdateAssessment -func (mr *MockDBMockRecorder) CreateOrUpdateAssessment(a interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrUpdateAssessment", reflect.TypeOf((*MockDB)(nil).CreateOrUpdateAssessment), a) -} - -// GetAssessmentsWithValue mocks base method -func (m *MockDB) GetAssessmentsWithValue(arg0, arg1, arg2 uint) ([]Assessments, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAssessmentsWithValue", arg0, arg1, arg2) - ret0, _ := ret[0].([]Assessments) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAssessmentsWithValue indicates an expected call of GetAssessmentsWithValue -func (mr *MockDBMockRecorder) GetAssessmentsWithValue(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAssessmentsWithValue", reflect.TypeOf((*MockDB)(nil).GetAssessmentsWithValue), arg0, arg1, arg2) -} - -// GetUserCompletedAssesments mocks base method -func (m *MockDB) GetUserCompletedAssesments(userID uint) (int, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUserCompletedAssesments", userID) - ret0, _ := ret[0].(int) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetUserCompletedAssesments indicates an expected call of GetUserCompletedAssesments -func (mr *MockDBMockRecorder) GetUserCompletedAssesments(userID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserCompletedAssesments", reflect.TypeOf((*MockDB)(nil).GetUserCompletedAssesments), userID) -} - -// ListCompilationTasks mocks base method -func (m *MockDB) ListCompilationTasks(userID, limit, offset uint, kind string) ([]CompilationTask, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListCompilationTasks", userID, limit, offset, kind) - ret0, _ := ret[0].([]CompilationTask) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListCompilationTasks indicates an expected call of ListCompilationTasks -func (mr *MockDBMockRecorder) ListCompilationTasks(userID, limit, offset, kind interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListCompilationTasks", reflect.TypeOf((*MockDB)(nil).ListCompilationTasks), userID, limit, offset, kind) -} - -// GetCompilationTask mocks base method -func (m *MockDB) GetCompilationTask(taskID uint) (*CompilationTask, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCompilationTask", taskID) - ret0, _ := ret[0].(*CompilationTask) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCompilationTask indicates an expected call of GetCompilationTask -func (mr *MockDBMockRecorder) GetCompilationTask(taskID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCompilationTask", reflect.TypeOf((*MockDB)(nil).GetCompilationTask), taskID) -} - -// GetCompilationTaskBy mocks base method -func (m *MockDB) GetCompilationTaskBy(address, network, status string) (*CompilationTask, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCompilationTaskBy", address, network, status) - ret0, _ := ret[0].(*CompilationTask) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCompilationTaskBy indicates an expected call of GetCompilationTaskBy -func (mr *MockDBMockRecorder) GetCompilationTaskBy(address, network, status interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCompilationTaskBy", reflect.TypeOf((*MockDB)(nil).GetCompilationTaskBy), address, network, status) -} - -// CreateCompilationTask mocks base method -func (m *MockDB) CreateCompilationTask(ct *CompilationTask) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateCompilationTask", ct) - ret0, _ := ret[0].(error) - return ret0 -} - -// CreateCompilationTask indicates an expected call of CreateCompilationTask -func (mr *MockDBMockRecorder) CreateCompilationTask(ct interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateCompilationTask", reflect.TypeOf((*MockDB)(nil).CreateCompilationTask), ct) -} - -// UpdateTaskStatus mocks base method -func (m *MockDB) UpdateTaskStatus(taskID uint, status string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateTaskStatus", taskID, status) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpdateTaskStatus indicates an expected call of UpdateTaskStatus -func (mr *MockDBMockRecorder) UpdateTaskStatus(taskID, status interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateTaskStatus", reflect.TypeOf((*MockDB)(nil).UpdateTaskStatus), taskID, status) -} - -// UpdateTaskResults mocks base method -func (m *MockDB) UpdateTaskResults(task *CompilationTask, status string, results []CompilationTaskResult) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateTaskResults", task, status, results) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpdateTaskResults indicates an expected call of UpdateTaskResults -func (mr *MockDBMockRecorder) UpdateTaskResults(task, status, results interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateTaskResults", reflect.TypeOf((*MockDB)(nil).UpdateTaskResults), task, status, results) -} - -// CountCompilationTasks mocks base method -func (m *MockDB) CountCompilationTasks(userID uint) (int64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CountCompilationTasks", userID) - ret0, _ := ret[0].(int64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CountCompilationTasks indicates an expected call of CountCompilationTasks -func (mr *MockDBMockRecorder) CountCompilationTasks(userID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CountCompilationTasks", reflect.TypeOf((*MockDB)(nil).CountCompilationTasks), userID) -} - -// ListDeployments mocks base method -func (m *MockDB) ListDeployments(userID, limit, offset uint) ([]Deployment, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListDeployments", userID, limit, offset) - ret0, _ := ret[0].([]Deployment) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListDeployments indicates an expected call of ListDeployments -func (mr *MockDBMockRecorder) ListDeployments(userID, limit, offset interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListDeployments", reflect.TypeOf((*MockDB)(nil).ListDeployments), userID, limit, offset) -} - -// CreateDeployment mocks base method -func (m *MockDB) CreateDeployment(dt *Deployment) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateDeployment", dt) - ret0, _ := ret[0].(error) - return ret0 -} - -// CreateDeployment indicates an expected call of CreateDeployment -func (mr *MockDBMockRecorder) CreateDeployment(dt interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateDeployment", reflect.TypeOf((*MockDB)(nil).CreateDeployment), dt) -} - -// GetDeploymentBy mocks base method -func (m *MockDB) GetDeploymentBy(opHash string) (*Deployment, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetDeploymentBy", opHash) - ret0, _ := ret[0].(*Deployment) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetDeploymentBy indicates an expected call of GetDeploymentBy -func (mr *MockDBMockRecorder) GetDeploymentBy(opHash interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDeploymentBy", reflect.TypeOf((*MockDB)(nil).GetDeploymentBy), opHash) -} - -// UpdateDeployment mocks base method -func (m *MockDB) UpdateDeployment(dt *Deployment) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateDeployment", dt) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpdateDeployment indicates an expected call of UpdateDeployment -func (mr *MockDBMockRecorder) UpdateDeployment(dt interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateDeployment", reflect.TypeOf((*MockDB)(nil).UpdateDeployment), dt) -} - -// CountDeployments mocks base method -func (m *MockDB) CountDeployments(userID uint) (int64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CountDeployments", userID) - ret0, _ := ret[0].(int64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CountDeployments indicates an expected call of CountDeployments -func (mr *MockDBMockRecorder) CountDeployments(userID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CountDeployments", reflect.TypeOf((*MockDB)(nil).CountDeployments), userID) -} - -// GetSubscription mocks base method -func (m *MockDB) GetSubscription(userID uint, address, network string) (Subscription, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubscription", userID, address, network) - ret0, _ := ret[0].(Subscription) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSubscription indicates an expected call of GetSubscription -func (mr *MockDBMockRecorder) GetSubscription(userID, address, network interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubscription", reflect.TypeOf((*MockDB)(nil).GetSubscription), userID, address, network) -} - -// GetSubscriptions mocks base method -func (m *MockDB) GetSubscriptions(address, network string) ([]Subscription, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubscriptions", address, network) - ret0, _ := ret[0].([]Subscription) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSubscriptions indicates an expected call of GetSubscriptions -func (mr *MockDBMockRecorder) GetSubscriptions(address, network interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubscriptions", reflect.TypeOf((*MockDB)(nil).GetSubscriptions), address, network) -} - -// ListSubscriptions mocks base method -func (m *MockDB) ListSubscriptions(userID uint) ([]Subscription, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListSubscriptions", userID) - ret0, _ := ret[0].([]Subscription) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListSubscriptions indicates an expected call of ListSubscriptions -func (mr *MockDBMockRecorder) ListSubscriptions(userID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListSubscriptions", reflect.TypeOf((*MockDB)(nil).ListSubscriptions), userID) -} - -// UpsertSubscription mocks base method -func (m *MockDB) UpsertSubscription(arg0 *Subscription) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpsertSubscription", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpsertSubscription indicates an expected call of UpsertSubscription -func (mr *MockDBMockRecorder) UpsertSubscription(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpsertSubscription", reflect.TypeOf((*MockDB)(nil).UpsertSubscription), arg0) -} - -// DeleteSubscription mocks base method -func (m *MockDB) DeleteSubscription(arg0 *Subscription) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteSubscription", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteSubscription indicates an expected call of DeleteSubscription -func (mr *MockDBMockRecorder) DeleteSubscription(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteSubscription", reflect.TypeOf((*MockDB)(nil).DeleteSubscription), arg0) -} - -// GetSubscriptionsCount mocks base method -func (m *MockDB) GetSubscriptionsCount(address, network string) (int, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubscriptionsCount", address, network) - ret0, _ := ret[0].(int) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSubscriptionsCount indicates an expected call of GetSubscriptionsCount -func (mr *MockDBMockRecorder) GetSubscriptionsCount(address, network interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubscriptionsCount", reflect.TypeOf((*MockDB)(nil).GetSubscriptionsCount), address, network) -} - -// GetOrCreateUser mocks base method -func (m *MockDB) GetOrCreateUser(arg0 *User, arg1 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetOrCreateUser", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// GetOrCreateUser indicates an expected call of GetOrCreateUser -func (mr *MockDBMockRecorder) GetOrCreateUser(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOrCreateUser", reflect.TypeOf((*MockDB)(nil).GetOrCreateUser), arg0, arg1) -} - -// GetUser mocks base method -func (m *MockDB) GetUser(arg0 uint) (*User, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUser", arg0) - ret0, _ := ret[0].(*User) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetUser indicates an expected call of GetUser -func (mr *MockDBMockRecorder) GetUser(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUser", reflect.TypeOf((*MockDB)(nil).GetUser), arg0) -} - -// UpdateUserMarkReadAt mocks base method -func (m *MockDB) UpdateUserMarkReadAt(arg0 uint, arg1 int64) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateUserMarkReadAt", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpdateUserMarkReadAt indicates an expected call of UpdateUserMarkReadAt -func (mr *MockDBMockRecorder) UpdateUserMarkReadAt(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateUserMarkReadAt", reflect.TypeOf((*MockDB)(nil).UpdateUserMarkReadAt), arg0, arg1) -} - -// ListVerifications mocks base method -func (m *MockDB) ListVerifications(userID, limit, offset uint) ([]Verification, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListVerifications", userID, limit, offset) - ret0, _ := ret[0].([]Verification) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListVerifications indicates an expected call of ListVerifications -func (mr *MockDBMockRecorder) ListVerifications(userID, limit, offset interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListVerifications", reflect.TypeOf((*MockDB)(nil).ListVerifications), userID, limit, offset) -} - -// CreateVerification mocks base method -func (m *MockDB) CreateVerification(v *Verification) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateVerification", v) - ret0, _ := ret[0].(error) - return ret0 -} - -// CreateVerification indicates an expected call of CreateVerification -func (mr *MockDBMockRecorder) CreateVerification(v interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateVerification", reflect.TypeOf((*MockDB)(nil).CreateVerification), v) -} - -// GetVerificationBy mocks base method -func (m *MockDB) GetVerificationBy(address, network string) (*Verification, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetVerificationBy", address, network) - ret0, _ := ret[0].(*Verification) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetVerificationBy indicates an expected call of GetVerificationBy -func (mr *MockDBMockRecorder) GetVerificationBy(address, network interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetVerificationBy", reflect.TypeOf((*MockDB)(nil).GetVerificationBy), address, network) -} - -// CountVerifications mocks base method -func (m *MockDB) CountVerifications(userID uint) (int64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CountVerifications", userID) - ret0, _ := ret[0].(int64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CountVerifications indicates an expected call of CountVerifications -func (mr *MockDBMockRecorder) CountVerifications(userID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CountVerifications", reflect.TypeOf((*MockDB)(nil).CountVerifications), userID) -} - -// Close mocks base method -func (m *MockDB) Close() { - m.ctrl.T.Helper() - m.ctrl.Call(m, "Close") -} - -// Close indicates an expected call of Close -func (mr *MockDBMockRecorder) Close() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockDB)(nil).Close)) -} - -// MockIAccount is a mock of IAccount interface -type MockIAccount struct { - ctrl *gomock.Controller - recorder *MockIAccountMockRecorder -} - -// MockIAccountMockRecorder is the mock recorder for MockIAccount -type MockIAccountMockRecorder struct { - mock *MockIAccount -} - -// NewMockIAccount creates a new mock instance -func NewMockIAccount(ctrl *gomock.Controller) *MockIAccount { - mock := &MockIAccount{ctrl: ctrl} - mock.recorder = &MockIAccountMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockIAccount) EXPECT() *MockIAccountMockRecorder { - return m.recorder -} - -// GetOrCreateAccount mocks base method -func (m *MockIAccount) GetOrCreateAccount(arg0 *Account) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetOrCreateAccount", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// GetOrCreateAccount indicates an expected call of GetOrCreateAccount -func (mr *MockIAccountMockRecorder) GetOrCreateAccount(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOrCreateAccount", reflect.TypeOf((*MockIAccount)(nil).GetOrCreateAccount), arg0) -} - -// MockIAssessment is a mock of IAssessment interface -type MockIAssessment struct { - ctrl *gomock.Controller - recorder *MockIAssessmentMockRecorder -} - -// MockIAssessmentMockRecorder is the mock recorder for MockIAssessment -type MockIAssessmentMockRecorder struct { - mock *MockIAssessment -} - -// NewMockIAssessment creates a new mock instance -func NewMockIAssessment(ctrl *gomock.Controller) *MockIAssessment { - mock := &MockIAssessment{ctrl: ctrl} - mock.recorder = &MockIAssessmentMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockIAssessment) EXPECT() *MockIAssessmentMockRecorder { - return m.recorder -} - -// CreateAssessment mocks base method -func (m *MockIAssessment) CreateAssessment(a *Assessments) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateAssessment", a) - ret0, _ := ret[0].(error) - return ret0 -} - -// CreateAssessment indicates an expected call of CreateAssessment -func (mr *MockIAssessmentMockRecorder) CreateAssessment(a interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateAssessment", reflect.TypeOf((*MockIAssessment)(nil).CreateAssessment), a) -} - -// CreateOrUpdateAssessment mocks base method -func (m *MockIAssessment) CreateOrUpdateAssessment(a *Assessments) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrUpdateAssessment", a) - ret0, _ := ret[0].(error) - return ret0 -} - -// CreateOrUpdateAssessment indicates an expected call of CreateOrUpdateAssessment -func (mr *MockIAssessmentMockRecorder) CreateOrUpdateAssessment(a interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrUpdateAssessment", reflect.TypeOf((*MockIAssessment)(nil).CreateOrUpdateAssessment), a) -} - -// GetAssessmentsWithValue mocks base method -func (m *MockIAssessment) GetAssessmentsWithValue(arg0, arg1, arg2 uint) ([]Assessments, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAssessmentsWithValue", arg0, arg1, arg2) - ret0, _ := ret[0].([]Assessments) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAssessmentsWithValue indicates an expected call of GetAssessmentsWithValue -func (mr *MockIAssessmentMockRecorder) GetAssessmentsWithValue(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAssessmentsWithValue", reflect.TypeOf((*MockIAssessment)(nil).GetAssessmentsWithValue), arg0, arg1, arg2) -} - -// GetUserCompletedAssesments mocks base method -func (m *MockIAssessment) GetUserCompletedAssesments(userID uint) (int, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUserCompletedAssesments", userID) - ret0, _ := ret[0].(int) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetUserCompletedAssesments indicates an expected call of GetUserCompletedAssesments -func (mr *MockIAssessmentMockRecorder) GetUserCompletedAssesments(userID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserCompletedAssesments", reflect.TypeOf((*MockIAssessment)(nil).GetUserCompletedAssesments), userID) -} - -// MockICompilationTask is a mock of ICompilationTask interface -type MockICompilationTask struct { - ctrl *gomock.Controller - recorder *MockICompilationTaskMockRecorder -} - -// MockICompilationTaskMockRecorder is the mock recorder for MockICompilationTask -type MockICompilationTaskMockRecorder struct { - mock *MockICompilationTask -} - -// NewMockICompilationTask creates a new mock instance -func NewMockICompilationTask(ctrl *gomock.Controller) *MockICompilationTask { - mock := &MockICompilationTask{ctrl: ctrl} - mock.recorder = &MockICompilationTaskMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockICompilationTask) EXPECT() *MockICompilationTaskMockRecorder { - return m.recorder -} - -// ListCompilationTasks mocks base method -func (m *MockICompilationTask) ListCompilationTasks(userID, limit, offset uint, kind string) ([]CompilationTask, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListCompilationTasks", userID, limit, offset, kind) - ret0, _ := ret[0].([]CompilationTask) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListCompilationTasks indicates an expected call of ListCompilationTasks -func (mr *MockICompilationTaskMockRecorder) ListCompilationTasks(userID, limit, offset, kind interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListCompilationTasks", reflect.TypeOf((*MockICompilationTask)(nil).ListCompilationTasks), userID, limit, offset, kind) -} - -// GetCompilationTask mocks base method -func (m *MockICompilationTask) GetCompilationTask(taskID uint) (*CompilationTask, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCompilationTask", taskID) - ret0, _ := ret[0].(*CompilationTask) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCompilationTask indicates an expected call of GetCompilationTask -func (mr *MockICompilationTaskMockRecorder) GetCompilationTask(taskID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCompilationTask", reflect.TypeOf((*MockICompilationTask)(nil).GetCompilationTask), taskID) -} - -// GetCompilationTaskBy mocks base method -func (m *MockICompilationTask) GetCompilationTaskBy(address, network, status string) (*CompilationTask, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCompilationTaskBy", address, network, status) - ret0, _ := ret[0].(*CompilationTask) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCompilationTaskBy indicates an expected call of GetCompilationTaskBy -func (mr *MockICompilationTaskMockRecorder) GetCompilationTaskBy(address, network, status interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCompilationTaskBy", reflect.TypeOf((*MockICompilationTask)(nil).GetCompilationTaskBy), address, network, status) -} - -// CreateCompilationTask mocks base method -func (m *MockICompilationTask) CreateCompilationTask(ct *CompilationTask) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateCompilationTask", ct) - ret0, _ := ret[0].(error) - return ret0 -} - -// CreateCompilationTask indicates an expected call of CreateCompilationTask -func (mr *MockICompilationTaskMockRecorder) CreateCompilationTask(ct interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateCompilationTask", reflect.TypeOf((*MockICompilationTask)(nil).CreateCompilationTask), ct) -} - -// UpdateTaskStatus mocks base method -func (m *MockICompilationTask) UpdateTaskStatus(taskID uint, status string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateTaskStatus", taskID, status) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpdateTaskStatus indicates an expected call of UpdateTaskStatus -func (mr *MockICompilationTaskMockRecorder) UpdateTaskStatus(taskID, status interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateTaskStatus", reflect.TypeOf((*MockICompilationTask)(nil).UpdateTaskStatus), taskID, status) -} - -// UpdateTaskResults mocks base method -func (m *MockICompilationTask) UpdateTaskResults(task *CompilationTask, status string, results []CompilationTaskResult) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateTaskResults", task, status, results) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpdateTaskResults indicates an expected call of UpdateTaskResults -func (mr *MockICompilationTaskMockRecorder) UpdateTaskResults(task, status, results interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateTaskResults", reflect.TypeOf((*MockICompilationTask)(nil).UpdateTaskResults), task, status, results) -} - -// CountCompilationTasks mocks base method -func (m *MockICompilationTask) CountCompilationTasks(userID uint) (int64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CountCompilationTasks", userID) - ret0, _ := ret[0].(int64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CountCompilationTasks indicates an expected call of CountCompilationTasks -func (mr *MockICompilationTaskMockRecorder) CountCompilationTasks(userID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CountCompilationTasks", reflect.TypeOf((*MockICompilationTask)(nil).CountCompilationTasks), userID) -} - -// MockIDeployment is a mock of IDeployment interface -type MockIDeployment struct { - ctrl *gomock.Controller - recorder *MockIDeploymentMockRecorder -} - -// MockIDeploymentMockRecorder is the mock recorder for MockIDeployment -type MockIDeploymentMockRecorder struct { - mock *MockIDeployment -} - -// NewMockIDeployment creates a new mock instance -func NewMockIDeployment(ctrl *gomock.Controller) *MockIDeployment { - mock := &MockIDeployment{ctrl: ctrl} - mock.recorder = &MockIDeploymentMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockIDeployment) EXPECT() *MockIDeploymentMockRecorder { - return m.recorder -} - -// ListDeployments mocks base method -func (m *MockIDeployment) ListDeployments(userID, limit, offset uint) ([]Deployment, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListDeployments", userID, limit, offset) - ret0, _ := ret[0].([]Deployment) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListDeployments indicates an expected call of ListDeployments -func (mr *MockIDeploymentMockRecorder) ListDeployments(userID, limit, offset interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListDeployments", reflect.TypeOf((*MockIDeployment)(nil).ListDeployments), userID, limit, offset) -} - -// CreateDeployment mocks base method -func (m *MockIDeployment) CreateDeployment(dt *Deployment) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateDeployment", dt) - ret0, _ := ret[0].(error) - return ret0 -} - -// CreateDeployment indicates an expected call of CreateDeployment -func (mr *MockIDeploymentMockRecorder) CreateDeployment(dt interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateDeployment", reflect.TypeOf((*MockIDeployment)(nil).CreateDeployment), dt) -} - -// GetDeploymentBy mocks base method -func (m *MockIDeployment) GetDeploymentBy(opHash string) (*Deployment, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetDeploymentBy", opHash) - ret0, _ := ret[0].(*Deployment) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetDeploymentBy indicates an expected call of GetDeploymentBy -func (mr *MockIDeploymentMockRecorder) GetDeploymentBy(opHash interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDeploymentBy", reflect.TypeOf((*MockIDeployment)(nil).GetDeploymentBy), opHash) -} - -// UpdateDeployment mocks base method -func (m *MockIDeployment) UpdateDeployment(dt *Deployment) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateDeployment", dt) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpdateDeployment indicates an expected call of UpdateDeployment -func (mr *MockIDeploymentMockRecorder) UpdateDeployment(dt interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateDeployment", reflect.TypeOf((*MockIDeployment)(nil).UpdateDeployment), dt) -} - -// CountDeployments mocks base method -func (m *MockIDeployment) CountDeployments(userID uint) (int64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CountDeployments", userID) - ret0, _ := ret[0].(int64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CountDeployments indicates an expected call of CountDeployments -func (mr *MockIDeploymentMockRecorder) CountDeployments(userID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CountDeployments", reflect.TypeOf((*MockIDeployment)(nil).CountDeployments), userID) -} - -// MockISubscription is a mock of ISubscription interface -type MockISubscription struct { - ctrl *gomock.Controller - recorder *MockISubscriptionMockRecorder -} - -// MockISubscriptionMockRecorder is the mock recorder for MockISubscription -type MockISubscriptionMockRecorder struct { - mock *MockISubscription -} - -// NewMockISubscription creates a new mock instance -func NewMockISubscription(ctrl *gomock.Controller) *MockISubscription { - mock := &MockISubscription{ctrl: ctrl} - mock.recorder = &MockISubscriptionMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockISubscription) EXPECT() *MockISubscriptionMockRecorder { - return m.recorder -} - -// GetSubscription mocks base method -func (m *MockISubscription) GetSubscription(userID uint, address, network string) (Subscription, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubscription", userID, address, network) - ret0, _ := ret[0].(Subscription) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSubscription indicates an expected call of GetSubscription -func (mr *MockISubscriptionMockRecorder) GetSubscription(userID, address, network interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubscription", reflect.TypeOf((*MockISubscription)(nil).GetSubscription), userID, address, network) -} - -// GetSubscriptions mocks base method -func (m *MockISubscription) GetSubscriptions(address, network string) ([]Subscription, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubscriptions", address, network) - ret0, _ := ret[0].([]Subscription) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSubscriptions indicates an expected call of GetSubscriptions -func (mr *MockISubscriptionMockRecorder) GetSubscriptions(address, network interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubscriptions", reflect.TypeOf((*MockISubscription)(nil).GetSubscriptions), address, network) -} - -// ListSubscriptions mocks base method -func (m *MockISubscription) ListSubscriptions(userID uint) ([]Subscription, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListSubscriptions", userID) - ret0, _ := ret[0].([]Subscription) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListSubscriptions indicates an expected call of ListSubscriptions -func (mr *MockISubscriptionMockRecorder) ListSubscriptions(userID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListSubscriptions", reflect.TypeOf((*MockISubscription)(nil).ListSubscriptions), userID) -} - -// UpsertSubscription mocks base method -func (m *MockISubscription) UpsertSubscription(arg0 *Subscription) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpsertSubscription", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpsertSubscription indicates an expected call of UpsertSubscription -func (mr *MockISubscriptionMockRecorder) UpsertSubscription(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpsertSubscription", reflect.TypeOf((*MockISubscription)(nil).UpsertSubscription), arg0) -} - -// DeleteSubscription mocks base method -func (m *MockISubscription) DeleteSubscription(arg0 *Subscription) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteSubscription", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteSubscription indicates an expected call of DeleteSubscription -func (mr *MockISubscriptionMockRecorder) DeleteSubscription(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteSubscription", reflect.TypeOf((*MockISubscription)(nil).DeleteSubscription), arg0) -} - -// GetSubscriptionsCount mocks base method -func (m *MockISubscription) GetSubscriptionsCount(address, network string) (int, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubscriptionsCount", address, network) - ret0, _ := ret[0].(int) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSubscriptionsCount indicates an expected call of GetSubscriptionsCount -func (mr *MockISubscriptionMockRecorder) GetSubscriptionsCount(address, network interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubscriptionsCount", reflect.TypeOf((*MockISubscription)(nil).GetSubscriptionsCount), address, network) -} - -// MockIUser is a mock of IUser interface -type MockIUser struct { - ctrl *gomock.Controller - recorder *MockIUserMockRecorder -} - -// MockIUserMockRecorder is the mock recorder for MockIUser -type MockIUserMockRecorder struct { - mock *MockIUser -} - -// NewMockIUser creates a new mock instance -func NewMockIUser(ctrl *gomock.Controller) *MockIUser { - mock := &MockIUser{ctrl: ctrl} - mock.recorder = &MockIUserMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockIUser) EXPECT() *MockIUserMockRecorder { - return m.recorder -} - -// GetOrCreateUser mocks base method -func (m *MockIUser) GetOrCreateUser(arg0 *User, arg1 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetOrCreateUser", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// GetOrCreateUser indicates an expected call of GetOrCreateUser -func (mr *MockIUserMockRecorder) GetOrCreateUser(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOrCreateUser", reflect.TypeOf((*MockIUser)(nil).GetOrCreateUser), arg0, arg1) -} - -// GetUser mocks base method -func (m *MockIUser) GetUser(arg0 uint) (*User, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUser", arg0) - ret0, _ := ret[0].(*User) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetUser indicates an expected call of GetUser -func (mr *MockIUserMockRecorder) GetUser(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUser", reflect.TypeOf((*MockIUser)(nil).GetUser), arg0) -} - -// UpdateUserMarkReadAt mocks base method -func (m *MockIUser) UpdateUserMarkReadAt(arg0 uint, arg1 int64) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateUserMarkReadAt", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpdateUserMarkReadAt indicates an expected call of UpdateUserMarkReadAt -func (mr *MockIUserMockRecorder) UpdateUserMarkReadAt(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateUserMarkReadAt", reflect.TypeOf((*MockIUser)(nil).UpdateUserMarkReadAt), arg0, arg1) -} - -// MockIVerification is a mock of IVerification interface -type MockIVerification struct { - ctrl *gomock.Controller - recorder *MockIVerificationMockRecorder -} - -// MockIVerificationMockRecorder is the mock recorder for MockIVerification -type MockIVerificationMockRecorder struct { - mock *MockIVerification -} - -// NewMockIVerification creates a new mock instance -func NewMockIVerification(ctrl *gomock.Controller) *MockIVerification { - mock := &MockIVerification{ctrl: ctrl} - mock.recorder = &MockIVerificationMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockIVerification) EXPECT() *MockIVerificationMockRecorder { - return m.recorder -} - -// ListVerifications mocks base method -func (m *MockIVerification) ListVerifications(userID, limit, offset uint) ([]Verification, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListVerifications", userID, limit, offset) - ret0, _ := ret[0].([]Verification) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListVerifications indicates an expected call of ListVerifications -func (mr *MockIVerificationMockRecorder) ListVerifications(userID, limit, offset interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListVerifications", reflect.TypeOf((*MockIVerification)(nil).ListVerifications), userID, limit, offset) -} - -// CreateVerification mocks base method -func (m *MockIVerification) CreateVerification(v *Verification) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateVerification", v) - ret0, _ := ret[0].(error) - return ret0 -} - -// CreateVerification indicates an expected call of CreateVerification -func (mr *MockIVerificationMockRecorder) CreateVerification(v interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateVerification", reflect.TypeOf((*MockIVerification)(nil).CreateVerification), v) -} - -// GetVerificationBy mocks base method -func (m *MockIVerification) GetVerificationBy(address, network string) (*Verification, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetVerificationBy", address, network) - ret0, _ := ret[0].(*Verification) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetVerificationBy indicates an expected call of GetVerificationBy -func (mr *MockIVerificationMockRecorder) GetVerificationBy(address, network interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetVerificationBy", reflect.TypeOf((*MockIVerification)(nil).GetVerificationBy), address, network) -} - -// CountVerifications mocks base method -func (m *MockIVerification) CountVerifications(userID uint) (int64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CountVerifications", userID) - ret0, _ := ret[0].(int64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CountVerifications indicates an expected call of CountVerifications -func (mr *MockIVerificationMockRecorder) CountVerifications(userID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CountVerifications", reflect.TypeOf((*MockIVerification)(nil).CountVerifications), userID) -} diff --git a/internal/database/scopes.go b/internal/database/scopes.go deleted file mode 100644 index 5f303a24d..000000000 --- a/internal/database/scopes.go +++ /dev/null @@ -1,58 +0,0 @@ -package database - -import ( - "github.com/baking-bad/bcdhub/internal/models/types" - "github.com/jinzhu/gorm" -) - -func addressScope(address string) func(db *gorm.DB) *gorm.DB { - return func(db *gorm.DB) *gorm.DB { - return db.Where("address = ?", address) - } -} - -func networkScope(network types.Network) func(db *gorm.DB) *gorm.DB { - return func(db *gorm.DB) *gorm.DB { - return db.Where("network = ?", network) - } -} - -func userIDScope(userID uint) func(db *gorm.DB) *gorm.DB { - return func(db *gorm.DB) *gorm.DB { - return db.Where("user_id = ?", userID) - } -} - -func idScope(id uint) func(db *gorm.DB) *gorm.DB { - return func(db *gorm.DB) *gorm.DB { - return db.Where("id = ?", id) - } -} - -func pagination(limit, offset uint) func(db *gorm.DB) *gorm.DB { - return func(db *gorm.DB) *gorm.DB { - if limit > 0 { - db = db.Limit(limit) - } - if limit > 0 { - db = db.Offset(offset) - } - return db - } -} - -func contract(address string, network types.Network) func(db *gorm.DB) *gorm.DB { - return func(db *gorm.DB) *gorm.DB { - return db.Where("address = ? AND network = ?", address, network) - } -} - -func createdAtDesc(db *gorm.DB) *gorm.DB { - return db.Order("created_at desc") -} - -func loginScope(login string) func(db *gorm.DB) *gorm.DB { - return func(db *gorm.DB) *gorm.DB { - return db.Where("login = ?", login) - } -} diff --git a/internal/database/subscription.go b/internal/database/subscription.go deleted file mode 100644 index 896127ee8..000000000 --- a/internal/database/subscription.go +++ /dev/null @@ -1,66 +0,0 @@ -package database - -import ( - "github.com/baking-bad/bcdhub/internal/models/types" - "github.com/jinzhu/gorm" -) - -// Subscription model -type Subscription struct { - gorm.Model - UserID uint `gorm:"primary_key;not null"` - Address string `gorm:"primary_key;not null"` - Network types.Network `gorm:"primary_key;not null"` - Alias string - WatchMask uint - SentryDSN string -} - -func (d *db) GetSubscription(userID uint, address string, network types.Network) (s Subscription, err error) { - err = d. - Scopes(userIDScope(userID), networkScope(network), addressScope(address)). - First(&s).Error - return -} - -func (d *db) GetSubscriptions(address string, network types.Network) ([]Subscription, error) { - var subs []Subscription - - err := d. - Scopes(contract(address, network)). - Find(&subs).Error - - return subs, err -} - -func (d *db) ListSubscriptions(userID uint) ([]Subscription, error) { - var subs []Subscription - - err := d. - Scopes(userIDScope(userID)). - Order("created_at DESC"). - Find(&subs).Error - - return subs, err -} - -func (d *db) UpsertSubscription(s *Subscription) error { - return d. - Scopes(userIDScope(s.UserID), contract(s.Address, s.Network)). - Assign(Subscription{Alias: s.Alias, WatchMask: s.WatchMask, SentryDSN: s.SentryDSN}). - FirstOrCreate(s).Error -} - -func (d *db) DeleteSubscription(s *Subscription) error { - return d.Unscoped(). - Scopes(userIDScope(s.UserID), contract(s.Address, s.Network)). - Delete(Subscription{}).Error -} - -func (d *db) GetSubscriptionsCount(address string, network types.Network) (count int, err error) { - err = d. - Model(&Subscription{}). - Scopes(contract(address, network)). - Count(&count).Error - return -} diff --git a/internal/database/user.go b/internal/database/user.go deleted file mode 100644 index 4aa7882df..000000000 --- a/internal/database/user.go +++ /dev/null @@ -1,46 +0,0 @@ -package database - -import ( - "time" - - "github.com/jinzhu/gorm" -) - -// User model -type User struct { - gorm.Model - Login string `gorm:"primary_key;not null"` - Name string - AvatarURL string `gorm:"not null"` - Token string `gorm:"not null"` - Provider string - Subscriptions []Subscription - MarkReadAt time.Time -} - -func (d *db) GetOrCreateUser(u *User, token string) error { - err := d.Scopes(loginScope(u.Login)).First(u).Error - if err != nil { - if gorm.IsRecordNotFoundError(err) { - return d.Create(u).Error - } - - return err - } - - return d.Model(u).Scopes(loginScope(u.Login)).Update("token", u.Token).Error -} - -func (d *db) GetUser(userID uint) (*User, error) { - var user User - - if err := d.Scopes(idScope(userID)).First(&user).Error; err != nil { - return nil, err - } - - return &user, nil -} - -func (d *db) UpdateUserMarkReadAt(userID uint, ts int64) error { - return d.Model(&User{}).Scopes(idScope(userID)).Update("mark_read_at", time.Unix(ts, 0)).Error -} diff --git a/internal/database/verification.go b/internal/database/verification.go deleted file mode 100644 index c9b20a34f..000000000 --- a/internal/database/verification.go +++ /dev/null @@ -1,51 +0,0 @@ -package database - -import ( - "time" - - "github.com/baking-bad/bcdhub/internal/models/types" -) - -// Verification - -type Verification struct { - ID uint `gorm:"primary_key" json:"id"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - DeletedAt *time.Time `sql:"index" json:"-"` - UserID uint `json:"user_id"` - CompilationTaskID uint `json:"-"` - Address string `json:"address"` - Network types.Network `json:"network"` - SourcePath string `json:"source_path"` -} - -// ListVerifications - -func (d *db) ListVerifications(userID, limit, offset uint) ([]Verification, error) { - var verifications []Verification - - req := d.Scopes(userIDScope(userID), pagination(limit, offset), createdAtDesc) - - if err := req.Find(&verifications).Error; err != nil { - return nil, err - } - - return verifications, nil -} - -// GetVerificationBy - -func (d *db) GetVerificationBy(address string, network types.Network) (*Verification, error) { - v := new(Verification) - - return v, d.Scopes(contract(address, network)).First(v).Error -} - -// CreateVerification - -func (d *db) CreateVerification(v *Verification) error { - return d.Create(v).Error -} - -// CountVerifications - -func (d *db) CountVerifications(userID uint) (int64, error) { - var count int64 - return count, d.Model(&Verification{}).Scopes(userIDScope(userID)).Count(&count).Error -} diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go index a4037cada..ab635f038 100644 --- a/internal/metrics/metrics.go +++ b/internal/metrics/metrics.go @@ -1,7 +1,6 @@ package metrics import ( - "github.com/baking-bad/bcdhub/internal/database" "github.com/baking-bad/bcdhub/internal/models" "github.com/baking-bad/bcdhub/internal/models/bigmapdiff" "github.com/baking-bad/bcdhub/internal/models/block" @@ -26,7 +25,6 @@ type Handler struct { TokenMetadata tokenmetadata.Repository TZIP tzip.Repository Storage models.GeneralRepository - DB database.DB } // New - @@ -41,7 +39,6 @@ func New( tzipRepo tzip.Repository, migrationRepo migration.Repository, storage models.GeneralRepository, - db database.DB, ) *Handler { - return &Handler{contracts, bmdRepo, blocksRepo, protocolRepo, operations, migrationRepo, tbRepo, tmRepo, tzipRepo, storage, db} + return &Handler{contracts, bmdRepo, blocksRepo, protocolRepo, operations, migrationRepo, tbRepo, tmRepo, tzipRepo, storage} } diff --git a/internal/metrics/operation.go b/internal/metrics/operation.go index 6aa65cd7a..8711549a1 100644 --- a/internal/metrics/operation.go +++ b/internal/metrics/operation.go @@ -1,13 +1,7 @@ package metrics import ( - "fmt" - "time" - - "github.com/baking-bad/bcdhub/internal/logger" "github.com/baking-bad/bcdhub/internal/models/operation" - "github.com/baking-bad/bcdhub/internal/models/types" - "github.com/getsentry/sentry-go" ) // SetOperationStrings - @@ -21,80 +15,3 @@ func (h *Handler) SetOperationStrings(op *operation.Operation) { op.StorageStrings = ss } } - -// SendSentryNotifications - -func (h *Handler) SendSentryNotifications(op operation.Operation) error { - if op.Status != types.OperationStatusFailed { - return nil - } - - subscriptions, err := h.DB.GetSubscriptions(op.Destination, op.Network) - if err != nil { - return err - } - if len(subscriptions) == 0 { - return nil - } - - defer sentry.Flush(2 * time.Second) - - for _, subscription := range subscriptions { - initSentry(op.Network.String(), subscription.SentryDSN) - - hub := sentry.CurrentHub().Clone() - tags := map[string]string{ - "hash": op.Hash, - "source": op.Source, - "address": op.Destination, - "kind": op.Kind, - "block": fmt.Sprintf("%d", op.Level), - "os.name": "tezos", - } - - if op.Entrypoint != "" { - tags["entrypoint"] = op.Entrypoint - } - - exceptions := make([]sentry.Exception, 0) - var message string - for i := range op.Errors { - if err := op.Errors[i].Format(); err != nil { - return err - } - - if i == 0 { - message = op.Errors[i].GetTitle() - } - - exceptions = append(exceptions, sentry.Exception{ - Value: op.Errors[i].String(), - Type: op.Errors[i].GetTitle(), - }) - } - - hub.Client().Transport.SendEvent(&sentry.Event{ - Tags: tags, - Timestamp: op.Timestamp.Unix(), - Level: sentry.LevelError, - Environment: op.Network.String(), - Message: message, - Exception: exceptions, - Sdk: sentry.SdkInfo{ - Name: "BCD tezos SDK", - Version: "0.1", - }, - }) - } - return nil -} - -func initSentry(environment, dsn string) { - if err := sentry.Init(sentry.ClientOptions{ - Dsn: dsn, - Environment: environment, - Debug: false, - AttachStacktrace: false, - }); err != nil { - logger.Errorf("Sentry initialization failed: %v", err) - } -} diff --git a/internal/models/interface.go b/internal/models/interface.go index ec70136cc..975cc2739 100644 --- a/internal/models/interface.go +++ b/internal/models/interface.go @@ -11,7 +11,6 @@ type GeneralRepository interface { GetByNetwork(network types.Network, index string) ([]Model, error) UpdateDoc(model Model) (err error) UpdateFields(index string, id int64, data interface{}, fields ...string) error - GetEvents([]SubscriptionRequest, int64, int64) ([]Event, error) GetNetworkCountStats(network types.Network) (map[string]int64, error) GetDateHistogram(period string, opts ...HistogramOption) ([][]float64, error) diff --git a/internal/postgres/core/events.go b/internal/postgres/core/events.go deleted file mode 100644 index 0b4b9c514..000000000 --- a/internal/postgres/core/events.go +++ /dev/null @@ -1,257 +0,0 @@ -package core - -import ( - "sort" - "strings" - - "github.com/baking-bad/bcdhub/internal/bcd" - "github.com/baking-bad/bcdhub/internal/bcd/consts" - "github.com/baking-bad/bcdhub/internal/models" - "github.com/pkg/errors" - "gorm.io/gorm" -) - -// GetEvents - -func (p *Postgres) GetEvents(subscriptions []models.SubscriptionRequest, size, offset int64) ([]models.Event, error) { - if len(subscriptions) == 0 { - return []models.Event{}, nil - } - - queries := make(map[string]*gorm.DB) - - for i := range subscriptions { - subQueries := make(map[string]*gorm.DB) - getEventsQuery(p, subscriptions[i], subQueries) - - for table, sq := range subQueries { - makePartOfQuery(p, table, sq, queries) - } - } - - events := make([]models.Event, 0) - limit := p.GetPageSize(size) - for table, q := range queries { - q.Limit(limit).Offset(int(offset)).Order("timestamp desc") - - switch table { - case models.DocContracts: - var contracts []EventContract - if err := q.Find(&contracts).Error; err != nil { - return nil, err - } - - for i := range contracts { - e, err := contracts[i].makeEvent(subscriptions) - if err != nil { - return nil, err - } - events = append(events, e) - } - case models.DocOperations: - var ops []EventOperation - if err := q.Find(&ops).Error; err != nil { - return nil, err - } - - for i := range ops { - e, err := ops[i].makeEvent(subscriptions) - if err != nil { - return nil, err - } - events = append(events, e) - } - case models.DocMigrations: - var migrations []EventMigration - if err := q.Find(&migrations).Error; err != nil { - return nil, err - } - - for i := range migrations { - e, err := migrations[i].makeEvent(subscriptions) - if err != nil { - return nil, err - } - events = append(events, e) - } - } - } - - sort.Sort(models.ByTimestamp(events)) - - return events, nil -} - -func (m *EventMigration) makeEvent(subscriptions []models.SubscriptionRequest) (models.Event, error) { - res := models.Event{ - Type: models.EventTypeMigration, - Address: m.Address, - Network: m.Network, - Timestamp: m.Timestamp, - Body: m, - } - for i := range subscriptions { - if m.Network == subscriptions[i].Network && m.Address == subscriptions[i].Address { - res.Alias = subscriptions[i].Alias - return res, nil - } - } - return models.Event{}, errors.Errorf("Couldn't find a matching subscription for %v", m) -} - -func (o *EventOperation) makeEvent(subscriptions []models.SubscriptionRequest) (models.Event, error) { - res := models.Event{ - Network: o.Network, - Timestamp: o.Timestamp, - Body: o, - } - for i := range subscriptions { - if o.Network != subscriptions[i].Network { - continue - } - if o.Source != subscriptions[i].Address && o.Destination != subscriptions[i].Address { - continue - } - - res.Address = subscriptions[i].Address - res.Alias = subscriptions[i].Alias - - switch { - case o.Status != "applied": - res.Type = models.EventTypeError - case o.Source == subscriptions[i].Address && o.Kind == "origination": - res.Type = models.EventTypeDeploy - case o.Source == subscriptions[i].Address && o.Kind == "transaction": - res.Type = models.EventTypeCall - case o.Destination == subscriptions[i].Address && o.Kind == "transaction": - res.Type = models.EventTypeInvoke - } - - return res, nil - } - return models.Event{}, errors.Errorf("Couldn't find a matching subscription for %v", o) -} - -func (c *EventContract) makeEvent(subscriptions []models.SubscriptionRequest) (models.Event, error) { - res := models.Event{ - Body: c, - Timestamp: c.Timestamp, - } - for i := range subscriptions { - if c.Hash == subscriptions[i].Hash || c.ProjectID == subscriptions[i].ProjectID { - res.Network = subscriptions[i].Network - res.Address = subscriptions[i].Address - res.Alias = subscriptions[i].Alias - - if c.Hash == subscriptions[i].Hash { - res.Type = models.EventTypeSame - } else { - res.Type = models.EventTypeSimilar - } - return res, nil - } - } - return models.Event{}, errors.Errorf("Couldn't find a matching subscription for %v", c) -} - -func getEventsQuery(p *Postgres, subscription models.SubscriptionRequest, queries map[string]*gorm.DB) { - - if item := getEventsWatchCalls(p, subscription); item != nil { - makePartOfQuery(p, models.DocOperations, item, queries) - } - if item := getEventsWatchErrors(p, subscription); item != nil { - makePartOfQuery(p, models.DocOperations, item, queries) - } - if item := getEventsWatchDeployments(p, subscription); item != nil { - makePartOfQuery(p, models.DocOperations, item, queries) - } - - if bcd.IsContract(subscription.Address) { - if item := getEventsWatchMigrations(p, subscription); item != nil { - makePartOfQuery(p, models.DocMigrations, item, queries) - } - if item := getSubscriptionWithSame(p, subscription); item != nil { - makePartOfQuery(p, models.DocContracts, item, queries) - } - if item := getSubscriptionWithSimilar(p, subscription); item != nil { - makePartOfQuery(p, models.DocContracts, item, queries) - } - } -} - -func makePartOfQuery(p *Postgres, table string, item *gorm.DB, queries map[string]*gorm.DB) { - if q, ok := queries[table]; ok { - q.Or(item) - } else { - queries[table] = p.DB.Table(table).Where(item) - } -} - -func getEventsWatchMigrations(p *Postgres, subscription models.SubscriptionRequest) *gorm.DB { - if !subscription.WithMigrations { - return nil - } - - return p.DB.Where("kind IN (?)", []string{consts.MigrationBootstrap, consts.MigrationLambda, consts.MigrationUpdate}). - Where("network = ?", subscription.Network). - Where("address = ?", subscription.Address) -} - -func getEventsWatchDeployments(p *Postgres, subscription models.SubscriptionRequest) *gorm.DB { - if !subscription.WithDeployments { - return nil - } - - return p.DB.Where("kind = ?", consts.Origination). - Where("network = ?", subscription.Network). - Where("source = ?", subscription.Address) -} - -func getEventsWatchCalls(p *Postgres, subscription models.SubscriptionRequest) *gorm.DB { - if !subscription.WithCalls { - return nil - } - - addressKeyword := "destination = ?" - if strings.HasPrefix(subscription.Address, "tz") { - addressKeyword = "source = ?" - } - - return p.DB.Where("kind = ?", consts.Transaction). - Where("status = ?", consts.Applied). - Where("network = ?", subscription.Network). - Where(addressKeyword, subscription.Address) -} - -func getEventsWatchErrors(p *Postgres, subscription models.SubscriptionRequest) *gorm.DB { - if !subscription.WithErrors { - return nil - } - - addressKeyword := "destination = ?" - if strings.HasPrefix(subscription.Address, "tz") { - addressKeyword = "source = ?" - } - - return p.DB.Where("status != ?", consts.Applied). - Where("network = ?", subscription.Network). - Where(addressKeyword, subscription.Address) -} - -func getSubscriptionWithSame(p *Postgres, subscription models.SubscriptionRequest) *gorm.DB { - if !subscription.WithSame { - return nil - } - - return p.DB.Where("hash = ?", subscription.Hash). - Where("address != ?", subscription.Address) -} - -func getSubscriptionWithSimilar(p *Postgres, subscription models.SubscriptionRequest) *gorm.DB { - if !subscription.WithSimilar { - return nil - } - - return p.DB.Where("project_id = ?", subscription.ProjectID). - Where("hash != ?", subscription.Hash). - Where("address != ?", subscription.Address) -} diff --git a/internal/providers/data.go b/internal/providers/data.go deleted file mode 100644 index 08f0ea77c..000000000 --- a/internal/providers/data.go +++ /dev/null @@ -1,27 +0,0 @@ -package providers - -// references types -const ( - RefTypeBranch = "branch" - RefTypeTag = "tag" -) - -// Project - -type Project struct { - User string `json:"user"` - Project string `json:"project"` - URL string `json:"url"` -} - -// Account - -type Account struct { - Login string `json:"login"` - AvatarURL string `json:"avatarURL"` -} - -// Ref - -type Ref struct { - Name string `json:"name"` - URL string `json:"url"` - Type string `json:"type"` -} diff --git a/internal/providers/github.go b/internal/providers/github.go deleted file mode 100644 index f81c92e72..000000000 --- a/internal/providers/github.go +++ /dev/null @@ -1,179 +0,0 @@ -package providers - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/baking-bad/bcdhub/internal/config" - "github.com/baking-bad/bcdhub/internal/database" - "github.com/google/go-github/github" - "golang.org/x/oauth2" - oauthgithub "golang.org/x/oauth2/github" -) - -// Github - -type Github struct { - Config *oauth2.Config -} - -// Name - -func (p *Github) Name() string { - return "github" -} - -// Init - -func (p *Github) Init(cfg config.Config) { - p.Config = &oauth2.Config{ - RedirectURL: cfg.OAuth.Github.CallbackURL, - ClientID: cfg.OAuth.Github.ClientID, - ClientSecret: cfg.OAuth.Github.Secret, - Scopes: []string{}, - Endpoint: oauthgithub.Endpoint, - } -} - -// AuthCodeURL - -func (p *Github) AuthCodeURL(state string) string { - return p.Config.AuthCodeURL(state) -} - -// AuthUser - -func (p *Github) AuthUser(code string) (database.User, error) { - var user database.User - - token, err := p.Config.Exchange(context.Background(), code) - if err != nil { - return user, fmt.Errorf("github code exchange failed: %s", err.Error()) - } - - u, _, err := getGithubUser(token) - if err != nil { - return user, fmt.Errorf("getGithubUser failed: %s", err.Error()) - } - - var name string - if u.Name == nil { - name = *u.Login - } else { - name = *u.Name - } - - user = database.User{ - Token: token.AccessToken, - Login: *u.Login, - Name: name, - AvatarURL: *u.AvatarURL, - Provider: p.Name(), - } - - return user, nil -} - -func getGithubUser(token *oauth2.Token) (*github.User, *github.Response, error) { - ts := oauth2.StaticTokenSource(token) - tc := oauth2.NewClient(context.Background(), ts) - client := github.NewClient(tc) - - return client.Users.Get(context.Background(), "") -} - -// GetOrganizations - -func (p *Github) GetOrganizations(login string) ([]Account, error) { - client := github.NewClient(nil) - orgs, resp, err := client.Organizations.List(context.Background(), login, nil) - if resp.StatusCode == http.StatusNotFound { - return []Account{}, nil - } - if err != nil { - return nil, err - } - - res := make([]Account, len(orgs)) - for i, org := range orgs { - res[i] = Account{ - Login: org.GetLogin(), - AvatarURL: org.GetAvatarURL(), - } - } - - return res, nil -} - -// GetRepos - -func (p *Github) GetRepos(login string) ([]Project, error) { - client := github.NewClient(nil) - repos, resp, err := client.Repositories.List(context.Background(), login, nil) - if resp.StatusCode == http.StatusNotFound { - return []Project{}, nil - } - if err != nil { - return nil, err - } - - res := make([]Project, len(repos)) - - for i, r := range repos { - res[i] = Project{ - User: *r.Owner.Login, - Project: *r.Name, - URL: *r.HTMLURL, - } - } - - return res, nil -} - -// GetRefs - -func (p *Github) GetRefs(owner, repo string) ([]Ref, error) { - client := github.NewClient(nil) - - branches, err := p.getRefs(client, owner, repo, "heads", "refs/heads/", RefTypeBranch) - if err != nil { - return nil, err - } - - tags, err := p.getRefs(client, owner, repo, "tags", "refs/tags/", RefTypeTag) - if err != nil { - return nil, err - } - - return append(branches, tags...), nil -} - -func (p *Github) getRefs(client *github.Client, owner, repo, optType, prefix, refType string) ([]Ref, error) { - opts := new(github.ReferenceListOptions) - opts.Type = optType - - refs, resp, err := client.Git.ListRefs(context.Background(), owner, repo, opts) - if resp.StatusCode == http.StatusNotFound { - return []Ref{}, nil - } - if err != nil { - return nil, err - } - - res := make([]Ref, len(refs)) - - for i, r := range refs { - ref := strings.TrimPrefix(*r.Ref, prefix) - res[i] = Ref{ - Name: ref, - URL: p.ArchivePath(owner, repo, ref), - Type: refType, - } - } - - return res, nil -} - -// ArchivePath - -func (p *Github) ArchivePath(owner, repo, ref string) string { - return fmt.Sprintf("https://github.com/%s/%s/archive/%s.zip", owner, repo, ref) -} - -// BaseFilePath - -func (p *Github) BaseFilePath(owner, repo, ref string) string { - return fmt.Sprintf("https://github.com/%s/%s/blob/%s/", owner, repo, ref) -} diff --git a/internal/providers/gitlab.go b/internal/providers/gitlab.go deleted file mode 100644 index 5a39a7533..000000000 --- a/internal/providers/gitlab.go +++ /dev/null @@ -1,182 +0,0 @@ -package providers - -import ( - "context" - "fmt" - "net/http" - - "github.com/baking-bad/bcdhub/internal/config" - "github.com/baking-bad/bcdhub/internal/database" - "github.com/xanzy/go-gitlab" - "golang.org/x/oauth2" - oauthgitlab "golang.org/x/oauth2/gitlab" -) - -// Gitlab - -type Gitlab struct { - Config *oauth2.Config -} - -// Name - -func (p *Gitlab) Name() string { - return "gitlab" -} - -// Init - -func (p *Gitlab) Init(cfg config.Config) { - p.Config = &oauth2.Config{ - RedirectURL: cfg.OAuth.Gitlab.CallbackURL, - ClientID: cfg.OAuth.Gitlab.ClientID, - ClientSecret: cfg.OAuth.Gitlab.Secret, - Scopes: []string{"read_user"}, - Endpoint: oauthgitlab.Endpoint, - } -} - -// AuthCodeURL - -func (p *Gitlab) AuthCodeURL(state string) string { - return p.Config.AuthCodeURL(state) -} - -// AuthUser - -func (p *Gitlab) AuthUser(code string) (database.User, error) { - var user database.User - - token, err := p.Config.Exchange(context.Background(), code) - if err != nil { - return user, fmt.Errorf("gitlab code exchange failed: %s", err.Error()) - } - - u, _, err := getGitlabUser(token.AccessToken) - if err != nil { - return user, fmt.Errorf("getGitlabUser failed: %s", err.Error()) - } - - user = database.User{ - Token: token.AccessToken, - Login: u.Username, - Name: u.Name, - AvatarURL: u.AvatarURL, - Provider: p.Name(), - } - - return user, nil -} - -func getGitlabUser(token string) (*gitlab.User, *gitlab.Response, error) { - client, err := gitlab.NewOAuthClient(token) - if err != nil { - return nil, nil, err - } - - return client.Users.CurrentUser() -} - -// GetOrganizations - -func (p *Gitlab) GetOrganizations(login string) ([]Account, error) { - return []Account{}, nil -} - -// GetRepos - -func (p *Gitlab) GetRepos(login string) ([]Project, error) { - client, err := gitlab.NewClient("") - if err != nil { - return nil, err - } - - projects, resp, err := client.Projects.ListUserProjects(login, nil) - if resp.StatusCode == http.StatusNotFound { - return []Project{}, nil - } - if err != nil { - return nil, err - } - - res := make([]Project, len(projects)) - - for i, r := range projects { - res[i] = Project{ - User: r.Owner.Name, - Project: r.Path, - URL: r.WebURL, - } - } - - return res, nil -} - -// GetRefs - -func (p *Gitlab) GetRefs(owner, repo string) ([]Ref, error) { - client, err := gitlab.NewClient("") - if err != nil { - return nil, err - } - - id := fmt.Sprintf("%s/%s", owner, repo) - - branches, err := p.getBranches(client, id, owner, repo) - if err != nil { - return nil, err - } - - tags, err := p.getTags(client, id, owner, repo) - if err != nil { - return nil, err - } - - return append(branches, tags...), nil -} - -func (p *Gitlab) getTags(client *gitlab.Client, id, owner, repo string) ([]Ref, error) { - tags, resp, err := client.Tags.ListTags(id, nil) - if resp.StatusCode == http.StatusNotFound { - return []Ref{}, nil - } - if err != nil { - return nil, err - } - - res := make([]Ref, len(tags)) - - for i, t := range tags { - res[i] = Ref{ - Name: t.Name, - URL: p.ArchivePath(owner, repo, t.Name), - Type: RefTypeTag, - } - } - - return res, nil -} - -func (p *Gitlab) getBranches(client *gitlab.Client, id, owner, repo string) ([]Ref, error) { - branches, resp, err := client.Branches.ListBranches(id, nil) - if resp.StatusCode == http.StatusNotFound { - return []Ref{}, nil - } - if err != nil { - return nil, err - } - - res := make([]Ref, len(branches)) - - for i, t := range branches { - res[i] = Ref{ - Name: t.Name, - URL: p.ArchivePath(owner, repo, t.Name), - Type: RefTypeBranch, - } - } - - return res, nil -} - -// ArchivePath - -func (p *Gitlab) ArchivePath(owner, repo, ref string) string { - return fmt.Sprintf("https://gitlab.com/%s/%s/-/archive/%s/%s-%s.zip", owner, repo, ref, repo, ref) -} - -// BaseFilePath - -func (p *Gitlab) BaseFilePath(owner, repo, ref string) string { - return fmt.Sprintf("https://gitlab.com/%s/%s/-/blob/%s/", owner, repo, ref) -} diff --git a/internal/providers/providers.go b/internal/providers/providers.go deleted file mode 100644 index 6e9e88dd3..000000000 --- a/internal/providers/providers.go +++ /dev/null @@ -1,49 +0,0 @@ -package providers - -import ( - "fmt" - - "github.com/baking-bad/bcdhub/internal/config" - "github.com/baking-bad/bcdhub/internal/database" -) - -// Public - -type Public interface { - GetOrganizations(login string) ([]Account, error) - GetRepos(login string) ([]Project, error) - GetRefs(owner, repo string) ([]Ref, error) - ArchivePath(owner, repo, ref string) string - BaseFilePath(owner, repo, ref string) string -} - -// Oauth - -type Oauth interface { - Name() string - Init(cfg config.Config) - AuthCodeURL(state string) string - AuthUser(code string) (database.User, error) -} - -// InitOauth - -func InitOauth(cfg config.Config) map[string]Oauth { - providers := make(map[string]Oauth) - - for _, provider := range []Oauth{new(Github), new(Gitlab)} { - provider.Init(cfg) - providers[provider.Name()] = provider - } - - return providers -} - -// NewPublic - -func NewPublic(name string) (Public, error) { - switch name { - case "github": - return new(Github), nil - case "gitlab": - return new(Gitlab), nil - default: - return nil, fmt.Errorf("unknown provider %s", name) - } -} diff --git a/scripts/migration/main.go b/scripts/migration/main.go index e2cd5a4b6..d446cda36 100644 --- a/scripts/migration/main.go +++ b/scripts/migration/main.go @@ -47,7 +47,6 @@ func main() { ctx := config.NewContext( config.WithShare(cfg.SharePath), config.WithStorage(cfg.Storage, "migrations", 0), - config.WithDatabase(cfg.DB), config.WithRPC(cfg.RPC), config.WithConfigCopy(cfg), config.WithLoadErrorDescriptions(), diff --git a/scripts/migration/migrations/initial_storage_events.go b/scripts/migration/migrations/initial_storage_events.go index df973fa61..b867f6cac 100644 --- a/scripts/migration/migrations/initial_storage_events.go +++ b/scripts/migration/migrations/initial_storage_events.go @@ -33,7 +33,7 @@ func (m *InitialStorageEvents) Do(ctx *config.Context) error { logger.Info("Found %d tzips", len(tzips)) - h := metrics.New(ctx.Contracts, ctx.BigMapDiffs, ctx.Blocks, ctx.Protocols, ctx.Operations, ctx.TokenBalances, ctx.TokenMetadata, ctx.TZIP, ctx.Migrations, ctx.Storage, ctx.DB) + h := metrics.New(ctx.Contracts, ctx.BigMapDiffs, ctx.Blocks, ctx.Protocols, ctx.Operations, ctx.TokenBalances, ctx.TokenMetadata, ctx.TZIP, ctx.Migrations, ctx.Storage) logger.Info("Execution events...") items := make([]models.Model, 0)