github.com/mavryk-network/mvgo@v1.19.9/internal/compose/cache.go (about)

     1  // Copyright (c) 2023 Blockwatch Data Inc.
     2  // Author: alex@blockwatch.cc, abdul@blockwatch.cc
     3  
     4  package compose
     5  
     6  import (
     7  	"fmt"
     8  	"os"
     9  	"path/filepath"
    10  	"strconv"
    11  )
    12  
    13  var (
    14  	cacheFullPath string
    15  )
    16  
    17  func init() {
    18  	home, err := os.UserHomeDir()
    19  	if err != nil {
    20  		panic(fmt.Errorf("cannot read $HOME: %v", err))
    21  	}
    22  	cacheFullPath = filepath.Join(home, ".cache/tzcompose")
    23  }
    24  
    25  type PipelineCache struct {
    26  	hash uint64
    27  	last int
    28  }
    29  
    30  func NewCache() *PipelineCache {
    31  	return &PipelineCache{
    32  		hash: 0,
    33  		last: 0,
    34  	}
    35  }
    36  
    37  func (c *PipelineCache) Update(idx int) error {
    38  	c.last = idx
    39  	return writeFile(c.hash, []byte(strconv.Itoa(c.last)))
    40  }
    41  
    42  func (c PipelineCache) Get() int {
    43  	return c.last
    44  }
    45  
    46  func (c *PipelineCache) Load(hash uint64, reset bool) error {
    47  	c.hash = hash
    48  	if reset {
    49  		return c.Update(0)
    50  	}
    51  	buf, err := readFile(hash)
    52  	if err != nil {
    53  		if !os.IsNotExist(err) {
    54  			return err
    55  		}
    56  		c.last = -1
    57  
    58  	} else {
    59  		num, err := strconv.Atoi(string(buf))
    60  		if err != nil {
    61  			return fmt.Errorf("parsing cache file %016x: %v", hash, err)
    62  		}
    63  		c.last = num
    64  	}
    65  	return nil
    66  }
    67  
    68  func writeFile(hash uint64, buf []byte) error {
    69  	_, err := os.Stat(cacheFullPath)
    70  	if err != nil {
    71  		if !os.IsNotExist(err) {
    72  			return err
    73  		}
    74  		err = os.MkdirAll(cacheFullPath, 0755)
    75  		if err != nil {
    76  			return err
    77  		}
    78  	}
    79  	filename := filepath.Join(cacheFullPath, strconv.FormatUint(hash, 16))
    80  	return os.WriteFile(filename, buf, 0644)
    81  }
    82  
    83  func readFile(hash uint64) ([]byte, error) {
    84  	filename := filepath.Join(cacheFullPath, strconv.FormatUint(hash, 16))
    85  	return os.ReadFile(filename)
    86  }