service.go raw

   1  package main
   2  
   3  import (
   4  	"context"
   5  	"encoding/json"
   6  	"errors"
   7  	"fmt"
   8  	"net/http"
   9  	"strings"
  10  	"sync"
  11  	"time"
  12  
  13  	"git.smesh.lol/nostrino/pkg/blockcache"
  14  	"git.smesh.lol/nostrino/pkg/chain"
  15  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  16  )
  17  
  18  // blockReader is the node side of the block service: one block by hash.
  19  type blockReader interface {
  20  	blockByHash(context.Context, chainhash.Hash) ([]byte, error)
  21  }
  22  
  23  // blockService serves raw blocks over HTTP, from the cache or from the node.
  24  //
  25  // A block is the one thing a relay cannot carry, so the sidecar is what a wallet asks. The
  26  // cache is bounded and evicts the oldest entry first, which is where the requests are not: a
  27  // client scanning the chain wants the newest blocks and a client catching up wants whatever
  28  // it is behind by, and the second case pays a node read once and then a cache hit for whoever
  29  // asks next.
  30  type blockService struct {
  31  	chain string
  32  	node  blockReader
  33  	cache *blockcache.Cache
  34  	logf  func(string, ...any)
  35  
  36  	// mu guards fetching, which coalesces concurrent requests for one hash into one node read:
  37  	// ten clients asking for the tip block are still one fetch.
  38  	mu       sync.Mutex
  39  	fetching map[string]chan struct{}
  40  	last     time.Time
  41  }
  42  
  43  // newBlockService prepares the service.
  44  func newBlockService(chain string, node blockReader, cache *blockcache.Cache, logf func(string, ...any)) *blockService {
  45  	return &blockService{
  46  		chain: chain, node: node, cache: cache, logf: logf,
  47  		fetching: make(map[string]chan struct{}),
  48  	}
  49  }
  50  
  51  // handler routes the service.
  52  func (s *blockService) handler() http.Handler {
  53  	mux := http.NewServeMux()
  54  	mux.HandleFunc("/block/", s.serveBlock)
  55  	mux.HandleFunc("/health", s.serveHealth)
  56  
  57  	return mux
  58  }
  59  
  60  // serveBlock answers one block by hash.
  61  //
  62  // The path is /block/<chain>/<hash>. The chain is checked against the one this process follows
  63  // rather than used as a cache key alone: a sidecar for one chain answering for another is a
  64  // deployment mistake, and a client that trusted it would hash the block and throw it away.
  65  func (s *blockService) serveBlock(w http.ResponseWriter, r *http.Request) {
  66  	//
  67  	// The client is a page, not a program: a browser will not read a cross-origin response
  68  	// without this, and the service is on its own port beside the relay the page came from.
  69  	// The response is public, immutable block data addressed by its own hash, so a wildcard
  70  	// costs nothing that a read of the chain does not already give away.
  71  	//
  72  	w.Header().Set("Access-Control-Allow-Origin", "*")
  73  	w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS")
  74  	w.Header().Set("Access-Control-Allow-Headers", "*")
  75  
  76  	if r.Method == http.MethodOptions {
  77  		w.WriteHeader(http.StatusNoContent)
  78  
  79  		return
  80  	}
  81  
  82  	if r.Method != http.MethodGet && r.Method != http.MethodHead {
  83  		w.Header().Set("Allow", "GET, HEAD")
  84  		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  85  
  86  		return
  87  	}
  88  
  89  	parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/block/"), "/")
  90  
  91  	if len(parts) != 2 {
  92  		http.Error(w, "want /block/<chain>/<hash>", http.StatusBadRequest)
  93  
  94  		return
  95  	}
  96  
  97  	if profile, err := chain.ByName(parts[0]); err != nil || profile.Name != s.chain {
  98  		http.Error(w, "this service serves "+s.chain, http.StatusNotFound)
  99  
 100  		return
 101  	}
 102  
 103  	hash, err := chainhash.NewHashFromStr(parts[1])
 104  
 105  	if err != nil {
 106  		http.Error(w, "not a block hash", http.StatusBadRequest)
 107  
 108  		return
 109  	}
 110  
 111  	raw, hit, err := s.cache.Get(s.chain, *hash)
 112  
 113  	if err != nil {
 114  		http.Error(w, err.Error(), http.StatusInternalServerError)
 115  
 116  		return
 117  	}
 118  
 119  	if !hit {
 120  		raw, err = s.fetch(r.Context(), *hash)
 121  
 122  		if err != nil {
 123  			status := http.StatusBadGateway
 124  
 125  			if errors.Is(err, errNoSuchBlock) {
 126  				status = http.StatusNotFound
 127  			}
 128  
 129  			http.Error(w, err.Error(), status)
 130  
 131  			return
 132  		}
 133  	}
 134  
 135  	w.Header().Set("Content-Type", "application/octet-stream")
 136  	w.Header().Set("Content-Length", fmt.Sprint(len(raw)))
 137  	w.Header().Set("X-Block-Source", map[bool]string{true: "cache", false: "node"}[hit])
 138  
 139  	if r.Method == http.MethodHead {
 140  		return
 141  	}
 142  
 143  	if _, err := w.Write(raw); err != nil {
 144  		s.logf("block %s: write: %v", hash.String(), err)
 145  	}
 146  }
 147  
 148  // errNoSuchBlock reports a hash the node does not have.
 149  var errNoSuchBlock = errors.New("no such block")
 150  
 151  // fetch reads one block from the node and stores it, coalescing concurrent requests.
 152  func (s *blockService) fetch(ctx context.Context, hash chainhash.Hash) ([]byte, error) {
 153  	key := hash.String()
 154  
 155  	s.mu.Lock()
 156  
 157  	if waiting, present := s.fetching[key]; present {
 158  		s.mu.Unlock()
 159  
 160  		select {
 161  		case <-waiting:
 162  		case <-ctx.Done():
 163  			return nil, ctx.Err()
 164  		}
 165  
 166  		raw, hit, err := s.cache.Get(s.chain, hash)
 167  
 168  		if err != nil {
 169  			return nil, err
 170  		}
 171  
 172  		if !hit {
 173  			return nil, fmt.Errorf("block %s: the fetch that was already running did not store it", key)
 174  		}
 175  
 176  		return raw, nil
 177  	}
 178  
 179  	done := make(chan struct{})
 180  	s.fetching[key] = done
 181  
 182  	s.mu.Unlock()
 183  
 184  	defer func() {
 185  		s.mu.Lock()
 186  		delete(s.fetching, key)
 187  		s.mu.Unlock()
 188  
 189  		close(done)
 190  	}()
 191  
 192  	started := time.Now()
 193  
 194  	raw, err := s.node.blockByHash(ctx, hash)
 195  
 196  	if err != nil {
 197  		if strings.Contains(err.Error(), "not found") || strings.Contains(err.Error(), "-5") {
 198  			return nil, fmt.Errorf("%w: %s", errNoSuchBlock, hash.String())
 199  		}
 200  
 201  		return nil, err
 202  	}
 203  
 204  	// Storing is best effort: a full cache that cannot evict must not fail the request that
 205  	// paid for the read.
 206  	if err := s.cache.Put(s.chain, hash, raw); err != nil {
 207  		s.logf("block %s: fetched %d bytes in %s, not cached: %v",
 208  			key, len(raw), time.Since(started).Round(time.Millisecond), err)
 209  	} else {
 210  		s.logf("block %s: fetched %d bytes in %s and cached", key, len(raw),
 211  			time.Since(started).Round(time.Millisecond))
 212  	}
 213  
 214  	return raw, nil
 215  }
 216  
 217  // prefetch stores one height's block ahead of a request.
 218  //
 219  // It is for the tip: the first client to need the new block would otherwise pay the node read,
 220  // and the point of the cache is that nobody has to pay it twice.
 221  func (s *blockService) prefetch(ctx context.Context, height uint32, hash chainhash.Hash) {
 222  	if _, hit, err := s.cache.Get(s.chain, hash); err != nil || hit {
 223  		return
 224  	}
 225  
 226  	if _, err := s.fetch(ctx, hash); err != nil {
 227  		s.logf("prefetch %d (%s): %v", height, hash.String(), err)
 228  	}
 229  }
 230  
 231  // serveHealth reports the cache and the chain.
 232  func (s *blockService) serveHealth(w http.ResponseWriter, _ *http.Request) {
 233  	blocks, bytes := s.cache.Len()
 234  
 235  	w.Header().Set("Content-Type", "application/json")
 236  
 237  	_ = json.NewEncoder(w).Encode(map[string]any{
 238  		"chain":        s.chain,
 239  		"cache_blocks": blocks,
 240  		"cache_bytes":  bytes,
 241  	})
 242  }
 243