code.vegaprotocol.io/vega@v0.79.0/core/coreapi/services/netlimits.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 services
    17  
    18  import (
    19  	"context"
    20  	"sync"
    21  
    22  	"code.vegaprotocol.io/vega/core/events"
    23  	"code.vegaprotocol.io/vega/core/subscribers"
    24  	"code.vegaprotocol.io/vega/protos/vega"
    25  
    26  	"google.golang.org/protobuf/proto"
    27  )
    28  
    29  type netLimitsEvent interface {
    30  	events.Event
    31  	NetworkLimits() *vega.NetworkLimits
    32  }
    33  
    34  type NetLimits struct {
    35  	*subscribers.Base
    36  	ctx    context.Context
    37  	limits vega.NetworkLimits
    38  	ch     chan vega.NetworkLimits
    39  	mu     sync.RWMutex
    40  }
    41  
    42  func NewNetLimits(ctx context.Context) (netLimits *NetLimits) {
    43  	defer func() { go netLimits.consume() }()
    44  	return &NetLimits{
    45  		Base: subscribers.NewBase(ctx, 1000, true),
    46  		ctx:  ctx,
    47  		ch:   make(chan vega.NetworkLimits, 100),
    48  	}
    49  }
    50  
    51  func (n *NetLimits) consume() {
    52  	defer func() { close(n.ch) }()
    53  	for {
    54  		select {
    55  		case <-n.Closed():
    56  			return
    57  		case limits, ok := <-n.ch:
    58  			if !ok {
    59  				n.Halt()
    60  				return
    61  			}
    62  			n.mu.Lock()
    63  			n.limits = limits
    64  			n.mu.Unlock()
    65  		}
    66  	}
    67  }
    68  
    69  func (n *NetLimits) Get() *vega.NetworkLimits {
    70  	n.mu.RLock()
    71  	defer n.mu.RUnlock()
    72  	return proto.Clone(&n.limits).(*vega.NetworkLimits)
    73  }
    74  
    75  func (n *NetLimits) Push(evts ...events.Event) {
    76  	for _, e := range evts {
    77  		if ne, ok := e.(netLimitsEvent); ok {
    78  			n.ch <- *ne.NetworkLimits()
    79  		}
    80  	}
    81  }
    82  
    83  func (n *NetLimits) Types() []events.Type {
    84  	return []events.Type{events.NetworkLimitsEvent}
    85  }