code.vegaprotocol.io/vega@v0.79.0/datanode/service/chain.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 service
    17  
    18  import (
    19  	"context"
    20  	"errors"
    21  	"sync"
    22  
    23  	"code.vegaprotocol.io/vega/datanode/entities"
    24  )
    25  
    26  type ChainStore interface {
    27  	Get(context.Context) (entities.Chain, error)
    28  	Set(context.Context, entities.Chain) error
    29  }
    30  
    31  type Chain struct {
    32  	store ChainStore
    33  	chain *entities.Chain
    34  	mu    sync.Mutex
    35  }
    36  
    37  func NewChain(store ChainStore) *Chain {
    38  	return &Chain{
    39  		store: store,
    40  	}
    41  }
    42  
    43  /*
    44  GetChainID returns the current chain ID stored in the database (if one is set).
    45  
    46  	If one is not set, return empty string and no error. If an error occurs,
    47  	return empty string and an that error.
    48  
    49  	It caches the result of calling to the store, so that once we have successfully
    50  	retrieved a chain ID, we don't ask again.
    51  */
    52  func (c *Chain) GetChainID() (string, error) {
    53  	c.mu.Lock()
    54  	defer c.mu.Unlock()
    55  
    56  	if c.chain != nil {
    57  		return c.chain.ID, nil
    58  	}
    59  
    60  	ctx := context.Background()
    61  	chain, err := c.store.Get(ctx)
    62  	if errors.Is(err, entities.ErrNotFound) {
    63  		return "", nil
    64  	}
    65  
    66  	if err != nil {
    67  		return "", err
    68  	}
    69  
    70  	c.chain = &chain
    71  	return chain.ID, nil
    72  }
    73  
    74  func (c *Chain) SetChainID(chainID string) error {
    75  	// Don't bother caching when we set, otherwise the code to fetch from the DB will never
    76  	// be exercised until we start restoring mid-chain.
    77  	ctx := context.Background()
    78  	return c.store.Set(ctx, entities.Chain{ID: chainID})
    79  }