Skip to content

Commit

Permalink
fix(store): make don't cause error even if log file removed
Browse files Browse the repository at this point in the history
  • Loading branch information
macrat committed Nov 27, 2022
1 parent cfa9ce4 commit 219db0c
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 1 deletion.
23 changes: 22 additions & 1 deletion internal/store/scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package store

import (
"bufio"
"errors"
"os"
"sort"
"time"
Expand Down Expand Up @@ -133,11 +134,31 @@ func (r *inMemoryScanner) Record() api.Record {
return r.records[r.index]
}

type dummyScanner struct{}

func (r dummyScanner) Close() error {
return nil
}

func (r dummyScanner) Scan() bool {
return false
}

func (r dummyScanner) Record() api.Record {
// This method never be called.
panic("This is a bug if you see this message.")
}

func (s *Store) OpenLog(since, until time.Time) (api.LogScanner, error) {
if s.Path() == "" {
return newInMemoryScanner(s, since, until), nil
}

interests := s.index.Search(since.Unix(), until.Unix())
return newFileScanner(s.Path(), since, until, interests)
r, err := newFileScanner(s.Path(), since, until, interests)
if errors.Is(err, os.ErrNotExist) {
return dummyScanner{}, nil
} else {
return r, err
}
}
44 changes: 44 additions & 0 deletions internal/store/scanner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ package store_test

import (
"io"
"os"
"path/filepath"
"testing"
"time"

"github.com/google/go-cmp/cmp"
"github.com/macrat/ayd/internal/store"
"github.com/macrat/ayd/internal/testutil"
api "github.com/macrat/ayd/lib-ayd"
)

func TestStore_OpenLog(t *testing.T) {
Expand Down Expand Up @@ -94,3 +97,44 @@ func TestStore_OpenLog(t *testing.T) {
})
}
}

func TestStore_OpenLog_logRemoved(t *testing.T) {
p := filepath.Join(t.TempDir(), "ayd.log")

s, err := store.New(p, io.Discard)
if err != nil {
t.Fatalf("failed to make store: %s", err)
}
defer s.Close()

testCount := func(r api.LogScanner) {
t.Helper()
count := 0
for r.Scan() {
count++
}
if count != 0 {
t.Fatalf("unexpected number of records found: %d", count)
}
}

baseTime := time.Now()

if r, err := s.OpenLog(baseTime.Add(-1*time.Hour), baseTime.Add(1*time.Hour)); err != nil {
t.Fatalf("failed to open reader: %s", err)
} else {
testCount(r)
r.Close()
}

if err := os.Remove(p); err != nil {
t.Fatalf("failed to remove test log file: %s", err)
}

if r, err := s.OpenLog(baseTime.Add(-1*time.Hour), baseTime.Add(1*time.Hour)); err != nil {
t.Fatalf("failed to open reader: %s", err)
} else {
testCount(r)
r.Close()
}
}

0 comments on commit 219db0c

Please sign in to comment.