code.vegaprotocol.io/vega@v0.79.0/datanode/sqlsubscribers/margin_levels.go (about) 1 // Copyright (C) 2023 Gobalsky Labs Limited 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16 package sqlsubscribers 17 18 import ( 19 "context" 20 21 "code.vegaprotocol.io/vega/core/events" 22 "code.vegaprotocol.io/vega/datanode/entities" 23 "code.vegaprotocol.io/vega/protos/vega" 24 25 "github.com/pkg/errors" 26 ) 27 28 type MarginLevelsEvent interface { 29 events.Event 30 MarginLevels() vega.MarginLevels 31 } 32 33 type MarginLevelsStore interface { 34 Add(entities.MarginLevels) error 35 Flush(context.Context) error 36 } 37 38 type MarginLevels struct { 39 subscriber 40 store MarginLevelsStore 41 accountSource AccountSource 42 } 43 44 func NewMarginLevels(store MarginLevelsStore, accountSource AccountSource) *MarginLevels { 45 return &MarginLevels{ 46 store: store, 47 accountSource: accountSource, 48 } 49 } 50 51 func (ml *MarginLevels) Types() []events.Type { 52 return []events.Type{events.MarginLevelsEvent} 53 } 54 55 func (ml *MarginLevels) Flush(ctx context.Context) error { 56 err := ml.flush(ctx) 57 if err != nil { 58 return errors.Wrap(err, "flushing margin levels") 59 } 60 61 return nil 62 } 63 64 func (ml *MarginLevels) Push(ctx context.Context, evt events.Event) error { 65 return ml.consume(ctx, evt.(MarginLevelsEvent)) 66 } 67 68 func (ml *MarginLevels) flush(ctx context.Context) error { 69 err := ml.store.Flush(ctx) 70 return errors.Wrap(err, "flushing margin levels") 71 } 72 73 func (ml *MarginLevels) consume(ctx context.Context, event MarginLevelsEvent) error { 74 marginLevel := event.MarginLevels() 75 marginLevel.Timestamp = 0 76 77 proto := event.MarginLevels() 78 entity, err := entities.MarginLevelsFromProto(ctx, &proto, ml.accountSource, entities.TxHash(event.TxHash()), ml.vegaTime) 79 if err != nil { 80 return errors.Wrap(err, "converting margin level to database entity failed") 81 } 82 83 err = ml.store.Add(entity) 84 return errors.Wrap(err, "add margin level to store") 85 } 86 87 func (ml *MarginLevels) Name() string { 88 return "MarginLevels" 89 }