github.com/shyftnetwork/go-empyrean@v1.8.3-0.20191127201940-fbfca9338f04/swarm/storage/netstore.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package storage
    18  
    19  import (
    20  	"context"
    21  	"encoding/hex"
    22  	"fmt"
    23  	"sync"
    24  	"sync/atomic"
    25  	"time"
    26  
    27  	"github.com/ShyftNetwork/go-empyrean/p2p/enode"
    28  	"github.com/ShyftNetwork/go-empyrean/swarm/log"
    29  	lru "github.com/hashicorp/golang-lru"
    30  )
    31  
    32  type (
    33  	NewNetFetcherFunc func(ctx context.Context, addr Address, peers *sync.Map) NetFetcher
    34  )
    35  
    36  type NetFetcher interface {
    37  	Request(ctx context.Context, hopCount uint8)
    38  	Offer(ctx context.Context, source *enode.ID)
    39  }
    40  
    41  // NetStore is an extension of local storage
    42  // it implements the ChunkStore interface
    43  // on request it initiates remote cloud retrieval using a fetcher
    44  // fetchers are unique to a chunk and are stored in fetchers LRU memory cache
    45  // fetchFuncFactory is a factory object to create a fetch function for a specific chunk address
    46  type NetStore struct {
    47  	mu                sync.Mutex
    48  	store             SyncChunkStore
    49  	fetchers          *lru.Cache
    50  	NewNetFetcherFunc NewNetFetcherFunc
    51  	closeC            chan struct{}
    52  }
    53  
    54  var fetcherTimeout = 2 * time.Minute // timeout to cancel the fetcher even if requests are coming in
    55  
    56  // NewNetStore creates a new NetStore object using the given local store. newFetchFunc is a
    57  // constructor function that can create a fetch function for a specific chunk address.
    58  func NewNetStore(store SyncChunkStore, nnf NewNetFetcherFunc) (*NetStore, error) {
    59  	fetchers, err := lru.New(defaultChunkRequestsCacheCapacity)
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  	return &NetStore{
    64  		store:             store,
    65  		fetchers:          fetchers,
    66  		NewNetFetcherFunc: nnf,
    67  		closeC:            make(chan struct{}),
    68  	}, nil
    69  }
    70  
    71  // Put stores a chunk in localstore, and delivers to all requestor peers using the fetcher stored in
    72  // the fetchers cache
    73  func (n *NetStore) Put(ctx context.Context, ch Chunk) error {
    74  	n.mu.Lock()
    75  	defer n.mu.Unlock()
    76  
    77  	// put to the chunk to the store, there should be no error
    78  	err := n.store.Put(ctx, ch)
    79  	if err != nil {
    80  		return err
    81  	}
    82  
    83  	// if chunk is now put in the store, check if there was an active fetcher and call deliver on it
    84  	// (this delivers the chunk to requestors via the fetcher)
    85  	if f := n.getFetcher(ch.Address()); f != nil {
    86  		f.deliver(ctx, ch)
    87  	}
    88  	return nil
    89  }
    90  
    91  // Get retrieves the chunk from the NetStore DPA synchronously.
    92  // It calls NetStore.get, and if the chunk is not in local Storage
    93  // it calls fetch with the request, which blocks until the chunk
    94  // arrived or context is done
    95  func (n *NetStore) Get(rctx context.Context, ref Address) (Chunk, error) {
    96  	chunk, fetch, err := n.get(rctx, ref)
    97  	if err != nil {
    98  		return nil, err
    99  	}
   100  	if chunk != nil {
   101  		return chunk, nil
   102  	}
   103  	return fetch(rctx)
   104  }
   105  
   106  func (n *NetStore) BinIndex(po uint8) uint64 {
   107  	return n.store.BinIndex(po)
   108  }
   109  
   110  func (n *NetStore) Iterator(from uint64, to uint64, po uint8, f func(Address, uint64) bool) error {
   111  	return n.store.Iterator(from, to, po, f)
   112  }
   113  
   114  // FetchFunc returns nil if the store contains the given address. Otherwise it returns a wait function,
   115  // which returns after the chunk is available or the context is done
   116  func (n *NetStore) FetchFunc(ctx context.Context, ref Address) func(context.Context) error {
   117  	chunk, fetch, _ := n.get(ctx, ref)
   118  	if chunk != nil {
   119  		return nil
   120  	}
   121  	return func(ctx context.Context) error {
   122  		_, err := fetch(ctx)
   123  		return err
   124  	}
   125  }
   126  
   127  // Close chunk store
   128  func (n *NetStore) Close() {
   129  	close(n.closeC)
   130  	n.store.Close()
   131  	// TODO: loop through fetchers to cancel them
   132  }
   133  
   134  // get attempts at retrieving the chunk from LocalStore
   135  // If it is not found then using getOrCreateFetcher:
   136  //     1. Either there is already a fetcher to retrieve it
   137  //     2. A new fetcher is created and saved in the fetchers cache
   138  // From here on, all Get will hit on this fetcher until the chunk is delivered
   139  // or all fetcher contexts are done.
   140  // It returns a chunk, a fetcher function and an error
   141  // If chunk is nil, the returned fetch function needs to be called with a context to return the chunk.
   142  func (n *NetStore) get(ctx context.Context, ref Address) (Chunk, func(context.Context) (Chunk, error), error) {
   143  	n.mu.Lock()
   144  	defer n.mu.Unlock()
   145  
   146  	chunk, err := n.store.Get(ctx, ref)
   147  	if err != nil {
   148  		if err != ErrChunkNotFound {
   149  			log.Debug("Received error from LocalStore other than ErrNotFound", "err", err)
   150  		}
   151  		// The chunk is not available in the LocalStore, let's get the fetcher for it, or create a new one
   152  		// if it doesn't exist yet
   153  		f := n.getOrCreateFetcher(ref)
   154  		// If the caller needs the chunk, it has to use the returned fetch function to get it
   155  		return nil, f.Fetch, nil
   156  	}
   157  
   158  	return chunk, nil, nil
   159  }
   160  
   161  // getOrCreateFetcher attempts at retrieving an existing fetchers
   162  // if none exists, creates one and saves it in the fetchers cache
   163  // caller must hold the lock
   164  func (n *NetStore) getOrCreateFetcher(ref Address) *fetcher {
   165  	if f := n.getFetcher(ref); f != nil {
   166  		return f
   167  	}
   168  
   169  	// no fetcher for the given address, we have to create a new one
   170  	key := hex.EncodeToString(ref)
   171  	// create the context during which fetching is kept alive
   172  	ctx, cancel := context.WithTimeout(context.Background(), fetcherTimeout)
   173  	// destroy is called when all requests finish
   174  	destroy := func() {
   175  		// remove fetcher from fetchers
   176  		n.fetchers.Remove(key)
   177  		// stop fetcher by cancelling context called when
   178  		// all requests cancelled/timedout or chunk is delivered
   179  		cancel()
   180  	}
   181  	// peers always stores all the peers which have an active request for the chunk. It is shared
   182  	// between fetcher and the NewFetchFunc function. It is needed by the NewFetchFunc because
   183  	// the peers which requested the chunk should not be requested to deliver it.
   184  	peers := &sync.Map{}
   185  
   186  	fetcher := newFetcher(ref, n.NewNetFetcherFunc(ctx, ref, peers), destroy, peers, n.closeC)
   187  	n.fetchers.Add(key, fetcher)
   188  
   189  	return fetcher
   190  }
   191  
   192  // getFetcher retrieves the fetcher for the given address from the fetchers cache if it exists,
   193  // otherwise it returns nil
   194  func (n *NetStore) getFetcher(ref Address) *fetcher {
   195  	key := hex.EncodeToString(ref)
   196  	f, ok := n.fetchers.Get(key)
   197  	if ok {
   198  		return f.(*fetcher)
   199  	}
   200  	return nil
   201  }
   202  
   203  // RequestsCacheLen returns the current number of outgoing requests stored in the cache
   204  func (n *NetStore) RequestsCacheLen() int {
   205  	return n.fetchers.Len()
   206  }
   207  
   208  // One fetcher object is responsible to fetch one chunk for one address, and keep track of all the
   209  // peers who have requested it and did not receive it yet.
   210  type fetcher struct {
   211  	addr        Address       // address of chunk
   212  	chunk       Chunk         // fetcher can set the chunk on the fetcher
   213  	deliveredC  chan struct{} // chan signalling chunk delivery to requests
   214  	cancelledC  chan struct{} // chan signalling the fetcher has been cancelled (removed from fetchers in NetStore)
   215  	netFetcher  NetFetcher    // remote fetch function to be called with a request source taken from the context
   216  	cancel      func()        // cleanup function for the remote fetcher to call when all upstream contexts are called
   217  	peers       *sync.Map     // the peers which asked for the chunk
   218  	requestCnt  int32         // number of requests on this chunk. If all the requests are done (delivered or context is done) the cancel function is called
   219  	deliverOnce *sync.Once    // guarantees that we only close deliveredC once
   220  }
   221  
   222  // newFetcher creates a new fetcher object for the fiven addr. fetch is the function which actually
   223  // does the retrieval (in non-test cases this is coming from the network package). cancel function is
   224  // called either
   225  //     1. when the chunk has been fetched all peers have been either notified or their context has been done
   226  //     2. the chunk has not been fetched but all context from all the requests has been done
   227  // The peers map stores all the peers which have requested chunk.
   228  func newFetcher(addr Address, nf NetFetcher, cancel func(), peers *sync.Map, closeC chan struct{}) *fetcher {
   229  	cancelOnce := &sync.Once{} // cancel should only be called once
   230  	return &fetcher{
   231  		addr:        addr,
   232  		deliveredC:  make(chan struct{}),
   233  		deliverOnce: &sync.Once{},
   234  		cancelledC:  closeC,
   235  		netFetcher:  nf,
   236  		cancel: func() {
   237  			cancelOnce.Do(func() {
   238  				cancel()
   239  			})
   240  		},
   241  		peers: peers,
   242  	}
   243  }
   244  
   245  // Fetch fetches the chunk synchronously, it is called by NetStore.Get is the chunk is not available
   246  // locally.
   247  func (f *fetcher) Fetch(rctx context.Context) (Chunk, error) {
   248  	atomic.AddInt32(&f.requestCnt, 1)
   249  	defer func() {
   250  		// if all the requests are done the fetcher can be cancelled
   251  		if atomic.AddInt32(&f.requestCnt, -1) == 0 {
   252  			f.cancel()
   253  		}
   254  	}()
   255  
   256  	// The peer asking for the chunk. Store in the shared peers map, but delete after the request
   257  	// has been delivered
   258  	peer := rctx.Value("peer")
   259  	if peer != nil {
   260  		f.peers.Store(peer, time.Now())
   261  		defer f.peers.Delete(peer)
   262  	}
   263  
   264  	// If there is a source in the context then it is an offer, otherwise a request
   265  	sourceIF := rctx.Value("source")
   266  
   267  	hopCount, _ := rctx.Value("hopcount").(uint8)
   268  
   269  	if sourceIF != nil {
   270  		var source enode.ID
   271  		if err := source.UnmarshalText([]byte(sourceIF.(string))); err != nil {
   272  			return nil, err
   273  		}
   274  		f.netFetcher.Offer(rctx, &source)
   275  	} else {
   276  		f.netFetcher.Request(rctx, hopCount)
   277  	}
   278  
   279  	// wait until either the chunk is delivered or the context is done
   280  	select {
   281  	case <-rctx.Done():
   282  		return nil, rctx.Err()
   283  	case <-f.deliveredC:
   284  		return f.chunk, nil
   285  	case <-f.cancelledC:
   286  		return nil, fmt.Errorf("fetcher cancelled")
   287  	}
   288  }
   289  
   290  // deliver is called by NetStore.Put to notify all pending requests
   291  func (f *fetcher) deliver(ctx context.Context, ch Chunk) {
   292  	f.deliverOnce.Do(func() {
   293  		f.chunk = ch
   294  		// closing the deliveredC channel will terminate ongoing requests
   295  		close(f.deliveredC)
   296  	})
   297  }