This repository was archived by the owner on Jun 27, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 115
Index caching #82
Open
sblinch
wants to merge
1
commit into
pgaskin:master
Choose a base branch
from
sblinch:indexcaching
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Index caching #82
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -11,9 +11,10 @@ import ( | |
"github.com/geek1011/BookBrowser/booklist" | ||
"github.com/geek1011/BookBrowser/formats" | ||
|
||
zglob "github.com/mattn/go-zglob" | ||
"github.com/mattn/go-zglob" | ||
"github.com/nfnt/resize" | ||
"github.com/pkg/errors" | ||
"encoding/json" | ||
) | ||
|
||
type Indexer struct { | ||
|
@@ -25,6 +26,7 @@ type Indexer struct { | |
booklist booklist.BookList | ||
mu sync.Mutex | ||
indMu sync.Mutex | ||
seen *SeenCache | ||
} | ||
|
||
func New(paths []string, coverpath *string, exts []string) (*Indexer, error) { | ||
|
@@ -45,7 +47,79 @@ func New(paths []string, coverpath *string, exts []string) (*Indexer, error) { | |
cp = &p | ||
} | ||
|
||
return &Indexer{paths: paths, coverpath: cp, exts: exts}, nil | ||
return &Indexer{paths: paths, coverpath: cp, exts: exts, seen: NewSeenCache()}, nil | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think the cache should be passed as an argument to New. |
||
} | ||
|
||
func (i *Indexer) Load() error { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Some of this code may fit better as part of the cache. Ideally, the cache would handle it's own loading, and the indexer would query the cache during the indexing. |
||
i.indMu.Lock() | ||
defer i.indMu.Unlock() | ||
|
||
booklist := booklist.BookList{} | ||
|
||
jsonFilename := filepath.Join(*i.coverpath, "index.json") | ||
f, err := os.Open(jsonFilename) | ||
if err != nil { | ||
if os.IsNotExist(err) { | ||
return nil | ||
} else { | ||
return errors.Wrap(err, "could not open index cache file") | ||
} | ||
} | ||
dec := json.NewDecoder(f) | ||
err = dec.Decode(&booklist) | ||
if err != nil { | ||
return errors.Wrap(err, "could not decode index cache file") | ||
} | ||
seen := NewSeenCache() | ||
for index, b := range booklist { | ||
seen.Add(b.FilePath, b.FileSize, b.ModTime, index) | ||
} | ||
|
||
if i.Verbose { | ||
log.Printf("Loaded %d items from index cache", len(booklist)) | ||
} | ||
|
||
i.mu.Lock() | ||
i.booklist = booklist | ||
i.seen = seen | ||
i.mu.Unlock() | ||
|
||
return nil | ||
} | ||
|
||
func (i *Indexer) Save() error { | ||
i.indMu.Lock() | ||
defer i.indMu.Unlock() | ||
|
||
i.mu.Lock() | ||
booklist := i.booklist | ||
i.mu.Unlock() | ||
|
||
tmpFilename := filepath.Join(*i.coverpath, ".index.json.tmp") | ||
jsonFilename := filepath.Join(*i.coverpath, "index.json") | ||
f, err := os.Create(tmpFilename) | ||
if err != nil { | ||
f.Close() | ||
return errors.Wrap(err, "could not create index cache temporary file") | ||
} | ||
|
||
enc := json.NewEncoder(f) | ||
err = enc.Encode(&booklist) | ||
if err != nil { | ||
f.Close() | ||
return errors.Wrap(err, "could not encode index cache file") | ||
} | ||
|
||
err = os.Rename(tmpFilename, jsonFilename) | ||
if err != nil { | ||
return errors.Wrap(err, "could not replace index cache file with temporary file") | ||
} | ||
|
||
if i.Verbose { | ||
log.Printf("Saved %d items to index cache", len(booklist)) | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func (i *Indexer) Refresh() ([]error, error) { | ||
|
@@ -62,8 +136,15 @@ func (i *Indexer) Refresh() ([]error, error) { | |
return errs, errors.New("no paths to index") | ||
} | ||
|
||
booklist := booklist.BookList{} | ||
seen := map[string]bool{} | ||
// seenID may be redundant at this point given that SeenCache does essentially the same thing, but | ||
// seenCache is based on the mtime/size/filename of each book (for performance), whereas seenID is based on | ||
// the file hash | ||
seenID := map[string]bool{} | ||
seen := NewSeenCache() | ||
|
||
i.mu.Lock() | ||
bl := i.booklist | ||
i.mu.Unlock() | ||
|
||
filenames := []string{} | ||
for _, path := range i.paths { | ||
|
@@ -81,29 +162,65 @@ func (i *Indexer) Refresh() ([]error, error) { | |
} | ||
} | ||
|
||
exists := make([]bool, len(bl), len(bl)) | ||
|
||
for fi, filepath := range filenames { | ||
if i.Verbose { | ||
log.Printf("Indexing %s", filepath) | ||
} | ||
|
||
book, err := i.getBook(filepath) | ||
stat, err := os.Stat(filepath) | ||
if err != nil { | ||
errs = append(errs, errors.Wrapf(err, "error reading book '%s'", filepath)) | ||
errs = append(errs, errors.Wrapf(err, "cannot stat file '%s'", filepath)) | ||
if i.Verbose { | ||
log.Printf("--> Error: %v", errs[len(errs)-1]) | ||
} | ||
continue | ||
} | ||
if !seen[book.ID()] { | ||
booklist = append(booklist, book) | ||
seen[book.ID()] = true | ||
|
||
var book *booklist.Book | ||
hash := i.seen.Hash(filepath, stat.Size(), stat.ModTime()) | ||
haveSeen, blIndex := i.seen.SeenHash(hash) | ||
if haveSeen { | ||
exists[blIndex] = true | ||
seen.AddHash(hash, blIndex) | ||
if i.Verbose { | ||
log.Printf("Already seen; not reindexing") | ||
} | ||
} else { | ||
// TODO: pass stat variable to i.getBook() to avoid a duplicate os.Stat() for each book | ||
book, err = i.getBook(filepath) | ||
if err != nil { | ||
errs = append(errs, errors.Wrapf(err, "error reading book '%s'", filepath)) | ||
if i.Verbose { | ||
log.Printf("--> Error: %v", errs[len(errs)-1]) | ||
} | ||
continue | ||
} | ||
if !seenID[book.ID()] { | ||
bl = append(bl, book) | ||
seenID[book.ID()] = true | ||
blIndex = len(bl) - 1 | ||
seen.AddHash(hash, blIndex) | ||
} | ||
} | ||
|
||
i.Progress = float64(fi+1) / float64(len(filenames)) | ||
} | ||
|
||
// remove any books that have disappeared since our last indexing job | ||
lastEntry := len(bl)-1 | ||
for index, stillExists := range exists { | ||
if !stillExists { | ||
bl[index] = bl[lastEntry] | ||
lastEntry-- | ||
} | ||
} | ||
bl = bl[0:lastEntry+1] | ||
|
||
i.mu.Lock() | ||
i.booklist = booklist | ||
i.booklist = bl | ||
i.seen = seen | ||
i.mu.Unlock() | ||
|
||
return errs, nil | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package indexer | ||
|
||
import ( | ||
"fmt" | ||
"crypto/sha1" | ||
"time" | ||
) | ||
|
||
type SeenCache struct { | ||
seen map[string]int | ||
} | ||
|
||
func NewSeenCache() *SeenCache { | ||
return &SeenCache{seen: make(map[string]int)} | ||
} | ||
|
||
func (c *SeenCache) Hash(filePath string, fileSize int64, modTime time.Time) string { | ||
token := fmt.Sprintf("%08d|%s|%s",fileSize,modTime,filePath) | ||
return fmt.Sprintf("%x", sha1.Sum([]byte(token)))[:10] | ||
} | ||
|
||
func (c *SeenCache) Clear() { | ||
c.seen = make(map[string]int) | ||
} | ||
|
||
func (c *SeenCache) Add(filePath string, fileSize int64, modTime time.Time, index int) string { | ||
hash := c.Hash(filePath, fileSize, modTime) | ||
c.seen[hash] = index | ||
return hash | ||
} | ||
|
||
func (c *SeenCache) AddHash(hash string, index int) { | ||
c.seen[hash] = index | ||
} | ||
|
||
func (c *SeenCache) Seen(filePath string, fileSize int64, modTime time.Time) (bool, string, int) { | ||
hash := c.Hash(filePath, fileSize, modTime) | ||
if index, exists := c.seen[hash]; exists { | ||
return true, hash, index | ||
} else { | ||
return false, "", -1 | ||
} | ||
} | ||
|
||
func (c *SeenCache) SeenHash(hash string) (bool, int) { | ||
index, exists := c.seen[hash] | ||
return exists, index | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -75,6 +75,13 @@ func (s *Server) printLog(format string, v ...interface{}) { | |
} | ||
} | ||
|
||
func (s *Server) LoadBookIndex() error { | ||
return s.Indexer.Load() | ||
} | ||
func (s *Server) SaveBookIndex() error { | ||
return s.Indexer.Save() | ||
} | ||
|
||
// RefreshBookIndex refreshes the book index | ||
func (s *Server) RefreshBookIndex() error { | ||
errs, err := s.Indexer.Refresh() | ||
|
@@ -91,6 +98,13 @@ func (s *Server) RefreshBookIndex() error { | |
} | ||
|
||
debug.FreeOSMemory() | ||
|
||
err = s.Indexer.Save() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should be able to be disabled using a command line flag. |
||
if err != nil { | ||
log.Printf("Error saving index: %s",err) | ||
return err | ||
} | ||
|
||
return nil | ||
} | ||
|
||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This should be an interface to allow for different cache implementations.